Skip to content

Working with tables

Dev Harry edited this page Apr 25, 2020 · 5 revisions

Defining tables

Before doing anything else you'll probably want to define your tables.

Syntax:

var myTable = sql.define(tableConf);

Table Config

tableConf is the definition for your table. It can have the following fields:

  • name: The name of the table (required)
  • columns: column definitions (see below)
  • columnWhiteList: TODO: define this parameter
  • isTemporary: true if this is a temporary table. Default value: false
  • snakeToCamel: if true column names will be converted to camelCase (e.g. needs_more_info will become needsMoreInfo, but the original will be used in generating queries)

Column Definitions

There are two valid formats for your Column Definitions:

Object-style Column Definitions

In this configuration the key is the column name, the value is the column spec.

Table.define({
    name: "AwesomeTable",
    columns: {
        id: {dataType: "serial primary key"},
        numCol: {dataType: "decimal"},
        notes: {dataType: "text"}
    }
});

Array-style Column Definitions

In this configuration an array of column definitions are used. The column definition can be a column spec object or a string; if a string then no type will be registered.

Table.define({
    name: "AwesomeTable",
    columns: [
        {name: "id", dataType: "serial primary key"},
        "numCol",
        {name: "notes", dataType: "text"}
    ]
});

Column Specification objects

The column specification can contain the following fields:

  • name: Not needed w/ Object-style column definitions; this is the name of the field.
  • dataType: specifies the SQL datatype of the field
  • primaryKey: true if this field should be part of the primary key

TODO: What other fields are valid here?

Creating tables

You can generate the SQL for creating a table from any complete table definition; the primary requirement is that your defintion contain field types.

var createSqlStr = Table.create().toQuery().text;

Dropping tables

You can generate the SQL for dropping a table from any table definition.

var createSqlStr = Table.drop().toQuery().text;

Please help complete these docs!

This project needs a lot better documentation; if you know how to use it well, please consider adding some information to this page or to other wiki pages