A class representing database tables and their properties.

Use this to create or delete tables and their properties, or to query or change table rows.

To query, update, insert or delete rows in an existing table, first you should find the table object with findOne.

Example

Table.findOne({name: "Customers"}) // find the table with name "Customers"
Table.findOne("Customers") // find the table with name "Customers" (shortcut)
Table.findOne({ id: 5 }) // find the table with id=5
Table.findOne(5) // find the table with id=5 (shortcut)

Table.findOne is synchronous (no need to await), But the functions that query and manipulate (such as insertRow, getRows, updateRow, deleteRows) rows are mostly asyncronous, so you can put the await in front of the whole expression

Example

To count the number of rows in the customer table

const nrows = await Table.findOne("Customers").countRows()

For further examples, see the Table test suite

Querying table rows

There are several methods you can use to retrieve rows in the database:

  • countRows To count the number of rows, optionally matching a criterion
  • getRows To retrieve multiple rows matching a criterion
  • getRow To retrieve a single row matching a criterion
  • getJoinedRows To retrieve rows together with joinfields and aggregations

These functions all take Where expressions which are JavaScript objects describing the criterion to match to. Some examples:

  • {}: Match all rows
  • { name: "Jim" }: Match all rows with name="Jim"
  • { name: { ilike: "im"} }: Match all rows where name contains "im" (case insensitive)
  • { name: /im/ }: Match all rows with name matching regular expression "im"
  • { age: { lt: 18 } }: Match all rows with age<18
  • { age: { lt: 18, equal: true } }: Match all rows with age<=18
  • { age: { gt: 18, lt: 65} }: Match all rows with 18<age<65
  • { name: { or: ["Harry", "Sally"] } }: Match all rows with name="Harry" or "Sally"
  • { or: [{ name: "Joe"}, { age: 37 }] }: Match all rows with name="Joe" or age=37
  • { not: { id: 5 } }: All rows except id=5
  • { id: { in: [1, 2, 3] } }: Rows with id 1, 2, or 3
  • { id: { not: { in: [1, 2, 3] } } }: Rows with id any value except 1, 2, or 3

For further examples, see the mkWhere test suite

Updating a Row

There are two nearly identical functions for updating rows depending on how you want failures treated

  • updateRow Update a row, throws an exception if update is invalid
  • tryUpdateRow Update a row, return an error message if update is invalid

Inserting a new Row

There are two nearly identical functions for inserting a new row depending on how you want failures treated

  • insertRow insert a row, throws an exception if it is invalid
  • tryInsertRow insert a row, return an error message if it is invalid

Deleting rows

Use deleteRows to delete any number (zero, one or many) of rows matching a criterion. It uses the same where expression as the functions for querying rows

Hierarchy

  • Table

Implements

  • AbstractTable

Constructors

Properties

constraints: TableConstraint[]

An array of TableConstraints for this table

description?: string

A description of the purpose of the table

external: boolean

If true this is an external table (not a database table)

fields: Field[]

An array of Fields in this table

has_sync_info: boolean

Whether sync info for mobile apps is enabled for this table

id?: number

The table ID

is_user_group: boolean

Is this a user group? If yes it will appear as options in the ownership dropdown

min_role_read: number

Minimum role to read

min_role_write: number

Minimum role to write

name: string

The table name

ownership_field_id?: string

The ID of the ownership field

ownership_formula?: string

A formula to denote ownership. This is a JavaScript expression which must evaluate to true if the user is the owner

provider_cfg?: any

Configuration for the table provider for this table

provider_name?: string

Name of the table provider for this table (not a database table)

versioned: boolean

Version history enabled for this table

Accessors

  • get to_json(): {
        external: boolean;
        fields: any[];
        id: undefined | number;
        min_role_read: number;
        min_role_write: number;
        name: string;
        ownership_field_id: undefined | string;
        ownership_formula: undefined | string;
        provider_cfg: any;
        provider_name: undefined | string;
        versioned: boolean;
    }
  • Returns {
        external: boolean;
        fields: any[];
        id: undefined | number;
        min_role_read: number;
        min_role_write: number;
        name: string;
        ownership_field_id: undefined | string;
        ownership_formula: undefined | string;
        provider_cfg: any;
        provider_name: undefined | string;
        versioned: boolean;
    }

    • external: boolean
    • fields: any[]
    • id: undefined | number
    • min_role_read: number
    • min_role_write: number
    • name: string
    • ownership_field_id: undefined | string
    • ownership_formula: undefined | string
    • provider_cfg: any
    • provider_name: undefined | string
    • versioned: boolean

Methods

  • Returns aggregations for this table, possibly on a subset by where-expression

    Parameters

    • aggregations: {
          [nm: string]: {
              aggregate: string;
              field?: string;
              valueFormula?: string;
          };
      }
      • [nm: string]: {
            aggregate: string;
            field?: string;
            valueFormula?: string;
        }
        • aggregate: string
        • Optional field?: string
        • Optional valueFormula?: string
    • Optional options: {
          groupBy?: string | string[];
          where?: any;
      }
      • Optional groupBy?: string | string[]
      • Optional where?: any

    Returns Promise<any>

  • Check table constraints against a row object. Will return a string With an error message if the table constraints are violated, undefined if the row does not violate any constraints

    Parameters

    • row0: Row

    Returns undefined | string

  • Count the number of rows in db table. The argument is a where-expression with conditions the counted rows should match. countRows returns the number of matching rows wrapped in a promise.

    Parameters

    • Optional where: Where
    • Optional opts: ForUserRequest

    Returns Promise<number>

    Example

    const bookTable = Table.findOne({name: "books"})

    // Count the total number of rows in the books table
    const totalNumberOfBooks = await bookTable.countRows({})

    // Count the number of books where the cover_color field has the value is "Red"
    const numberOfRedBooks = await bookTable.countRows({cover_color: "Red"})

    // Count number of books with more than 500 pages
    const numberOfLongBooks = await bookTable.countRows({pages: {gt: 500}})
  • Drop current table

    Parameters

    • only_forget: boolean = false

      boolean - if true that only

    Returns Promise<void>

  • Delete rows from table. The first argument is a where expression indicating the conditions for the rows to be deleted

    Parameters

    • where: Where

      condition

    • Optional user: Row

      optional user, if null then no authorization will be checked

    • Optional noTrigger: boolean

    Returns Promise<void>

    Example

    // delete all books where author = "Friedrich Nietzsche"
    await Table.findOne({name: "books"}).deleteRows({author: "Friedrich Nietzsche"})
  • Return distinct Values for column in table ????

    Parameters

    • fieldnm: string
    • Optional whereObj: object

    Returns Promise<any[]>

  • Parameters

    • nrecurse: number = 0
    • fieldWhere: ((f) => boolean) = ...
        • (f): boolean
        • Parameters

          Returns boolean

    • prefix: string = ""

    Returns Promise<string[]>

  • Returns Promise<AbstractTable[]>

  • Get rows along with joined and aggregated fields. The argument to getJoinedRows is an object with several different possible fields, all of which are optional

    • where: A Where expression indicating the criterion to match
    • joinFields: An object with the joinfields to retrieve
    • aggregations: An object with the aggregations to retrieve
    • orderBy: A string with the name of the field to order by
    • orderDesc: If true, descending order
    • limit: A number with the maximum number of rows to retrieve
    • offset: The number of rows to skip in the result before returning rows

    Parameters

    • Optional opts: any = {}

    Returns Promise<Row[]>

    Example

    const patients = Table.findOne({ name: "patients" });
    const patients_rows = await patients.getJoinedRows({
    where: { age: { gt: 65 } },
    orderBy: "id",
    aggregations: {
    avg_temp: {
    table: "readings",
    ref: "patient_id",
    field: "temperature",
    aggregate: "avg",
    },
    },
    joinFields: {
    pages: { ref: "favbook", target: "pages" },
    author: { ref: "favbook", target: "author" },
    },
    });
  • Get one row from the table in the database. The matching row will be returned in a promise - use await to read the value. If no matching rule can be found, null will be returned. If more than one row matches, the first found row will be returned.

    The first argument to get row is a where-expression With the conditions the returned row should match.

    The second document is optional and is an object that can modify the search. This is mainly useful in case there is more than one matching row for the where-expression in the first argument and you want to give an explicit order. For example, use {orderBy: "name"} as the second argument to pick the first row by the name field, ordered ascending. {orderBy: "name", orderDesc: true} to order by name, descending

    This is however rare and usually getRow is run with a single argument of a Where expression that uniquely determines the row to return, if it exisits.

    Parameters

    • where: Where = {}
    • selopts: SelectOptions & ForUserRequest = {}

    Returns Promise<null | Row>

    Example

    const bookTable = Table.findOne({name: "books"})


    // get the row in the book table with id = 5
    const myBook = await bookTable.getRow({id: 5})

    // get the row for the last book published by Leo Tolstoy
    const myBook = await bookTable.getRow({author: "Leo Tolstoy"}, {orderBy: "published", orderDesc: true})
  • Get all matching rows from the table in the database.

    The arguments are the same as for getRow. The first argument is where-expression with the conditions to match, and the second argument is an optional object and allows you to set ordering and limit options. Keywords that can be used in the second argument are orderBy, orderDesc, limit and offset.

    getRows will return an array of rows matching the where-expression in the first argument, wrapped in a Promise (use await to read the array).

    Parameters

    • where: Where = {}
    • selopts: SelectOptions & ForUserRequest = {}

    Returns Promise<Row[]>

    Example

    const bookTable = Table.findOne({name: "books"})

    // get the rows in the book table with author = "Henrik Pontoppidan"
    const myBooks = await bookTable.getRows({author: "Henrik Pontoppidan"})

    // get the 3 most recent books written by "Henrik Pontoppidan" with more that 500 pages
    const myBooks = await bookTable.getRows({author: "Henrik Pontoppidan", pages: {gt: 500}}, {orderBy: "published", orderDesc: true})
  • get join-field-options joined from a field in this table

    Parameters

    • Optional allow_double: boolean
    • Optional allow_triple: boolean

    Returns Promise<JoinFieldOption[]>

  • Get Models tbd why this function in this file - needs to models

    Parameters

    • Optional opts: any

    Returns Promise<any>

  • get relation-options joined from a field of another table

    Returns Promise<RelationOption[]>

  • Import CSV file to existing table

    Parameters

    • filePath: string
    • Optional options: {
          no_table_write?: boolean;
          recalc_stored?: boolean;
          skip_first_data_row?: boolean;
      }
      • Optional no_table_write?: boolean
      • Optional recalc_stored?: boolean
      • Optional skip_first_data_row?: boolean

    Returns Promise<ResultMessage>

  • Import JSON table description

    Parameters

    • filePath: string
    • Optional skip_first_data_row: boolean

    Returns Promise<any>

  • Insert row into the table. By passing in the user as the second argument, tt will check write rights. If a user object is not supplied, the insert goes ahead without checking write permissions.

    Returns the primary key value of the inserted row.

    This will throw an exception if the row does not conform to the table constraints. If you would like to insert a row with a function that can return an error message, use tryInsertRow instead.

    Parameters

    • v_in: Row
    • Optional user: Row
    • Optional resultCollector: object
    • Optional noTrigger: boolean
    • Optional syncTimestamp: Date

    Returns Promise<any>

    Example

    await Table.findOne("People").insertRow({ name: "Jim", age: 35 })
    
  • Check if user is owner of row

    Parameters

    • user: any

      user

    • row: Row

      table row

    Returns boolean

  • Get owner column name

    Parameters

    • Optional fields: null | Field[]

      fields list

    Returns undefined | null | string

    null or owner column name

  • get Ownership options user interface...

    Returns Promise<{
        label: string;
        value: string;
    }[]>

  • Parameters

    • selopts: SelectOptions & ForUserRequest = {}

    Returns SelectOptions & ForUserRequest

  • Restore Row Version

    Parameters

    • id: any
    • version: number
    • Optional user: Row

    Returns Promise<void>

  • Returns Promise<{
        label: string;
        steps: any;
    }[]>

  • ????

    Parameters

    • id: any
    • field_name: string
    • Optional user: Row

    Returns Promise<void>

  • Try to Insert row

    Parameters

    • v: Row
    • Optional user: Row
    • Optional resultCollector: object

    Returns Promise<{
        error: string;
    } | {
        success: any;
    }>

  • Try to Update row

    Parameters

    • v: any
    • id: any
    • Optional user: Row
    • Optional resultCollector: object

    Returns Promise<ResultMessage>

  • Update Table description in _sc_table Also creates / drops history table for table

    Parameters

    • new_table_rec: any

    Returns Promise<void>

  • Update a single row in the table database.

    The first two arguments are mandatory. The first is an object with the new values to set in the row. The second argument is the value of the primary key of the row to update. Typically this is the id field of an existing row object

    Parameters

    • v_in: any

      columns with values to update

    • id: any

      id value

    • Optional user: Row
    • Optional noTrigger: boolean
    • Optional resultCollector: object
    • Optional restore_of_version: any
    • Optional syncTimestamp: Date

    Returns Promise<string | void>

    Example

    const bookTable = Table.findOne({name: "books"})

    // get the row in the book table for Moby Dick
    const moby_dick = await bookTable.getRow({title: "Moby Dick"})

    // Update the read field to true and the rating field to 5
    await bookTable.updateRow({read: true, rating: 5}, moby_dick.id)

    // if you want to update more than one row, you must first retrieve all the rows and
    // then update them individually

    const allBooks = await bookTable.getRows()
    for(const book of allBooks) {
    await bookTable.updateRow({price: book.price*0.8}, book.id)
    }
  • Returns Promise<{
        [nm: string]: {
            label: string;
            steps: any;
        }[];
    }>

  • Create table

    Parameters

    • name: string

      table name

    • options: SelectOptions | TablePack = {}

      table fields

    • Optional id: number

      optional id, if set, no '_sc_tables' entry is inserted

    Returns Promise<Table>

    table

  • Table Create from CSV

    Parameters

    • name: string
    • filePath: string

    Returns Promise<ResultMessage>

  • Find Tables

    Parameters

    • Optional where: Where

      where condition

    • selectopts: SelectOptions = ...

      options

    Returns Promise<Table[]>

    table list

  • Find Tables including external tables

    Parameters

    • where0: Where = {}
    • selectopts: SelectOptions = ...

    Returns Promise<Table[]>

Generated using TypeDoc