Class SchemaModule

Provides methods for building database schema.

Hierarchy

  • SchemaModule

Constructors

Methods

  • Create a new table.

    Examples

    This example creates a new table with columns id, first_name, last_name and gender:

    await db.schema
    .createTable('person')
    .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
    .addColumn('first_name', 'varchar', col => col.notNull())
    .addColumn('last_name', 'varchar', col => col.notNull())
    .addColumn('gender', 'varchar')
    .execute()

    This example creates a table with a foreign key. Not all database engines support column-level foreign key constraint definitions. For example if you are using MySQL 5.X see the next example after this one.

    await db.schema
    .createTable('pet')
    .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
    .addColumn('owner_id', 'integer', col => col
    .references('person.id')
    .onDelete('cascade')
    )
    .execute()

    This example adds a foreign key constraint for a columns just like the previous example, but using a table-level statement. On MySQL 5.X you need to define foreign key constraints like this:

    await db.schema
    .createTable('pet')
    .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
    .addColumn('owner_id', 'integer')
    .addForeignKeyConstraint(
    'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],
    (constraint) => constraint.onDelete('cascade')
    )
    .execute()

    Type Parameters

    • TB extends string

    Parameters

    • table: TB

    Returns CreateTableBuilder<TB, never>

Generated using TypeDoc