# SQL Schema Builder

# Introduction

Schema builder provides a database agnostic way of manipulating tables. It works well with all SQL databases supported by ExpressWebJs. Thanks to Knex.

# Dropping Column

table.dropColumn("name");

Drops a column, specified by the column’s name

# dropColumns

table.dropColumns("columns");

Drops multiple columns, taking a variable number of column names

# renameColumn

table.renameColumn("from", "to");

Renames a column from one name to another.

# Increments

table.increments("id");

Adds an auto incrementing column. In PostgreSQL this is a serial; in Amazon Redshift an integer identity(1,1). This will be used as the primary key for the table. Also available is a bigIncrements if you wish to add a bigint incrementing number (in PostgreSQL bigserial).

import { Migration } from "Elucidate/Database/Model";

let tableName = "users";
exports.up = function(migration: Migration) {
  return migration.schema.createTable(tableName, (table) => {
    table.increments("id");
    table.string("name", 255).notNullable();
    table
      .string("email", 255)
      .unique()
      .notNullable();
    table.datetime("email_verified_at");
    table.string("password", 255).notNullable();
    table.string("remember_token", 100);
    table.timestamps(true, true);
  });
};

// reference the 'users' primary key in new table 'posts'

import { Migration } from "Elucidate/Database/Model";

let tableName = "posts";
exports.up = function(migration: Migration) {
  return migration.schema.createTable(tableName, (table) => {
    table
      .integer("author")
      .unsigned()
      .notNullable();
    table.string("title", 255).notNullable();
    table.string("content", 255).notNullable();

    table
      .foreign("author")
      .references("id")
      .inTable("users");
    table.timestamps(true, true);
  });
};

integer

table.integer(name);

Adds an integer column.

bigInteger

table.bigInteger(name);

In MySQL or PostgreSQL, adds a bigint column, otherwise adds a normal integer. Note that bigint data is returned as a string in queries because JavaScript may be unable to parse them without loss of precision.

text

table.text(name, [textType]);

Adds a text column, with optional textType for MySql text datatype preference. textType may be mediumtext or longtext, otherwise defaults to text.

string

table.string(name, [length]);

Adds a string column, with optional length defaulting to 255.

float

table.float(column, [precision], [scale]);

Adds a float column, with optional precision (defaults to 8) and scale (defaults to 2).

decimal

table.decimal(column, [precision], [scale]);

Adds a decimal column, with optional precision (defaults to 8) and scale (defaults to 2). Specifying NULL as precision creates a decimal column that can store numbers of any precision and scale. (Only supported for Oracle, SQLite, Postgres).

boolean

table.boolean(name);

Adds a boolean column.

date

table.date(name);

Adds a date column.

datetime

   table.datetime(name, options={[useTz: boolean], [precision: number]})

Adds a datetime column. By default PostgreSQL creates column with timezone (timestamptz type). This behaviour can be overriden by passing the useTz option (which is by default true for PostgreSQL). MySQL and MSSQL do not have useTz option.

A precision option may be passed:

table.datetime("some_time", { precision: 6 }).defaultTo(migration.fn.now(6));

time

table.time(name, [precision]);

Adds a time column, with optional precision for MySQL. Not supported on Amazon Redshift.

In MySQL a precision option may be passed:

table.time("some_time", { precision: 6 });

timestamp

table.timestamp(name, options={[useTz: boolean], [precision: number]})

Adds a timestamp column. By default PostgreSQL creates column with timezone (timestamptz type) and MSSQL does not (datetime2). This behaviour can be overriden by passing the useTz option (which is by default false for MSSQL and true for PostgreSQL). MySQL does not have useTz option.

table.timestamp("created_at").defaultTo(migration.fn.now());

In PostgreSQL and MySQL a precision option may be passed:

table.timestamp("created_at", { precision: 6 }).defaultTo(migration.fn.now(6));

In PostgreSQL and MSSQL a timezone option may be passed:

table.timestamp("created_at", { useTz: true });

timestamps

table.timestamps([useTimestamps], [defaultToNow]);

Adds created_at and updated_at columns on the database, setting each to datetime types. When true is passed as the first argument a timestamp type is used instead. Both columns default to being not null and using the current timestamp when true is passed as the second argument. Note that on MySQL the .timestamps() only have seconds precision, to get better precision use the .datetime or .timestamp methods directly with precision.

dropTimestamps

table.dropTimestamps();

Drops the columns created_at and updated_at from the table, which can be created via timestamps.

binary

table.binary(name, [length]);

Adds a binary column, with optional length argument for MySQL.

enum / enu

table.enu(col, values, [options]);

Adds a enum column, (aliased to enu, as enum is a reserved word in JavaScript). Implemented as unchecked varchar(255) on Amazon Redshift. Note that the second argument is an array of values. Example:

table.enu("column", ["value1", "value2"]);

For Postgres, an additional options argument can be provided to specify whether or not to use Postgres's native TYPE:

table.enu("column", ["value1", "value2"], { useNative: true, enumName: "foo_type" });

It will use the values provided to generate the appropriate TYPE. Example:

CREATE TYPE -

   "foo_type" AS ENUM ('value1', 'value2');

To use an existing native type across columns, specify 'existingType' in the options (this assumes the type has already been created): Note: Since the enum values aren't utilized for a native && existing type, the type being passed in for values is immaterial.

table.enu("column", null, { useNative: true, existingType: true, enumName: "foo_type" });

If you want to use existing enums from a schema, different from the schema of your current table, specify 'schemaName' in the options:

table.enu("column", null, { useNative: true, existingType: true, enumName: "foo_type", schemaName: "public" });

json

table.json(name);

Adds a json column, using the built-in json type in PostgreSQL, MySQL and SQLite, defaulting to a text column in older versions or in unsupported databases.

For PostgreSQL, due to incompatibility between native array and json types, when setting an array (or a value that could be an array) as the value of a json or jsonb column, you should use JSON.stringify() to convert your value to a string prior to passing it to the query builder, e.g.

migration
  .table("users")
  .where({ id: 1 })
  .update({ json_data: JSON.stringify(mightBeAnArray) });

jsonb

table.jsonb(name);

Adds a jsonb column. Works similar to table.json(), but uses native jsonb type if possible.

uuid

table.uuid(name);

Adds a uuid column - this uses the built-in uuid type in PostgreSQL, and falling back to a char(36) in other databases.

comment

table.comment(value);

Sets the comment for a table.

engine

table.engine(val);

Sets the engine for the database table, only available within a createTable call, and only applicable to MySQL.

charset

table.charset(val);

Sets the charset for the database table, only available within a createTable call, and only applicable to MySQL.

collate

table.collate(val);

Sets the collation for the database table, only available within a createTable call, and only applicable to MySQL.

inherits

table.inherits(val);

Sets the tables that this table inherits, only available within a createTable call, and only applicable to PostgreSQL.

specificType

table.specificType(name, type);

Sets a specific type for the column creation, if you'd like to add a column type that isn't supported here.

index

table.index(columns, [indexName], [indexType]);

Adds an index to a table over the given columns. A default index name using the columns is used unless indexName is specified. The indexType can be optionally specified for PostgreSQL and MySQL. Amazon Redshift does not allow creating an index.

dropIndex

table.dropIndex(columns, [indexName])
```

Drops an index from a table. A default index name using the columns is used unless indexName is specified (in which case columns is ignored). Amazon Redshift does not allow creating an index.

**unique** —
```ts
table.unique(columns, [indexName])
```

Adds an unique index to a table over the given columns. A default index name using the columns is used unless indexName is specified.

```ts
migration.schema.alterTable("users", function(t) {
  t.unique("email");
});
migration.schema.alterTable("job", function(t) {
  t.unique(["account_id", "program_id"]);
});

foreign

table.foreign(columns, [foreignKeyName])[.onDelete(statement).onUpdate(statement).withKeyName(foreignKeyName)]

Adds a foreign key constraint to a table for an existing column using table.foreign(column).references(column) or multiple columns using table.foreign(columns).references(columns).inTable(table). A default key name using the columns is used unless foreignKeyName is specified. You can also chain onDelete() and/or onUpdate() to set the reference option (RESTRICT, CASCADE, SET NULL, NO ACTION) for the operation. You can also chain withKeyName() to override default key name that is generated from table and column names (result is identical to specifying second parameter to function foreign()). Note that using foreign() is the same as column.references(column) but it works for existing columns.

migration.schema.table("users", function(table) {
  table.integer("user_id").unsigned();
  table.foreign("user_id").references("Items.user_id_in_items");
});

dropForeign

table.dropForeign(columns, [foreignKeyName]);

Drops a foreign key constraint from a table. A default foreign key name using the columns is used unless foreignKeyName is specified (in which case columns is ignored).

dropUnique

table.dropUnique(columns, [indexName]);

Drops a unique key constraint from a table. A default unique key name using the columns is used unless indexName is specified (in which case columns is ignored).

dropPrimary

table.dropPrimary([constraintName]);

Drops the primary key constraint on a table. Defaults to tablename_pkey unless constraintName is specified.

queryContext

table.queryContext(context);

Allows configuring a context to be passed to the wrapIdentifier hook for formatting table builder identifiers. The context can be any kind of value and will be passed to wrapIdentifier without modification.

migration.schema.table("users", function(table) {
  table.queryContext({ foo: "bar" });
  table.string("first_name");
  table.string("last_name");
});

This method also enables overwriting the context configured for a schema builder instance via schema.queryContext:

migration.schema.queryContext("schema context").table("users", function(table) {
  table.queryContext("table context");
  table.string("first_name");
  table.string("last_name");
});

Note that it's also possible to overwrite the table builder context for any column in the table definition:

migration.schema.queryContext("schema context").table("users", function(table) {
  table.queryContext("table context");
  table.string("first_name").queryContext("first_name context");
  table.string("last_name").queryContext("last_name context");
});

Calling queryContext with no arguments will return any context configured for the table builder instance.

# Chainable Methods

The following three methods may be chained on the schema building methods, as modifiers to the column.

alter

column.alter();

Marks the column as an alter / modify, instead of the default add. Note: This only works in .alterTable() and is not supported by SQlite or Amazon Redshift. Alter is not done incrementally over older column type so if you like to add notNullable and keep the old default value, the alter statement must contain both .notNullable().defaultTo(1).alter(). If one just tries to add .notNullable().alter() the old default value will be dropped.

migration.schema.alterTable("user", function(t) {
  t.increments().primary(); // add
  // drops previous default value from column, change type to string and add not nullable constraint
  t.string("username", 35)
    .notNullable()
    .alter();
  // drops both not null constraint and the default value
  t.integer("age").alter();
});

index

column.index([indexName], [indexType]);

Specifies a field as an index. If an indexName is specified, it is used in place of the standard index naming convention of tableName_columnName. The indexType can be optionally specified for PostgreSQL and MySQL. No-op if this is chained off of a field that cannot be indexed.

primary

column.primary([constraintName]);
table.primary(columns, [constraintName]);

When called on a single column it will set that column as the primary key for a table. If you need to create a composite primary key, call it on a table with an array of column names instead. Constraint name defaults to tablename_pkey unless constraintName is specified. On Amazon Redshift, all columns included in a primary key must be not nullable.

unique

column.unique();

Sets the column as unique. On Amazon Redshift, this constraint is not enforced, but it is used by the query planner.

references

column.references(column);

Sets the "column" that the current column references as a foreign key. "column" can either be "." syntax, or just the column name followed up with a call to inTable to specify the table.

inTable

column.inTable(table);

Sets the "table" where the foreign key column is located after calling column.references.

onDelete

column.onDelete(command);

Sets the SQL command to be run "onDelete".

onUpdate

column.onUpdate(command);

Sets the SQL command to be run "onUpdate".

defaultTo

column.defaultTo(value);

Sets the default value for the column on an insert.

unsigned

column.unsigned();

Specifies an integer as unsigned. No-op if this is chained off of a non-integer field.

notNullable

column.notNullable();

Adds a not null on the current column being created.

nullable

column.nullable();

Default on column creation, this explicitly sets a field to be nullable.

first

column.first();

Sets the column to be inserted on the first position, only used in MySQL alter tables.

after

column.after(field);

Sets the column to be inserted after another, only used in MySQL alter tables.

comment

column.comment(value);

Sets the comment for a column.

migration.schema.createTable("accounts", function(t) {
  t.increments().primary();
  t.string("email")
    .unique()
    .comment("This is the email field");
});

collate

column.collate(collation);

Sets the collation for a column (only works in MySQL). Here is a list of all available collations: (opens new window)

migration.schema.createTable("users", function(t) {
  t.increments();
  t.string("email")
    .unique()
    .collate("utf8_unicode_ci");
});