Skip to content

Knex Schemer Definition Format

Branden Horiuchi edited this page Sep 18, 2015 · 5 revisions

❁ Overview


Knex-Schemer Definition Format or KSDF is a standard format for defining a relational database schema in JSON that can be extended to provide non-database specific data/configuration, and ultimately consumed by knex-schemer to create and manage a database schema via Knex.js.

Related documentation: Data Types and Column Options

❁ Notation


The following notations are used to document syntax where language is insufficient

Notation Description
... one or more, not an array
_ as a prefix to a field name indicates the field is an extension and its name must be prefixed with an underscore
(optional) not required

❁ Syntax

☴ Schema Syntax

{
    tableName: JSON Object of Table ...,
}

☴ Table Syntax

{
    columnName: JSON Object of Column ...,
    _extensionName: JSON Object (optional) ...,
}

☴ Column Syntax

{
    type: DataType (optional),
    option: ColumnOption (optional) ...,
    extension: Object (optional) ...,
}

❁ Examples

☴ Basic Example
A simple schema with user and location tables ```js var schema = { user: { id: { type: 'integer', primary: true, increments: true } name: { type: 'string' }, username: { type: 'string', size: 32, unique: true }, passwordHash: { type: 'string' }, email: { type: 'string' }, location_id: { type: 'integer', nullable: true } }, location: { id: { type: 'integer', primary: true, increments: true } name: { type: 'string' } } } ```

Creates Table(s)

user id name username passwordHash email location
type INT(10) VARCHAR(255) VARCHAR(32) VARCHAR(255) VARCHAR(255) INT(10)
options PrimaryKey,
NotNULL,
Unsigned,
AutoIncrement
NotNULL NotNULL,
Unique
NotNULL NotNULL

location id name
type INT(10) VARCHAR(255)
options PrimaryKey,
NotNULL,
Unsigned,
AutoIncrement
NotNULL

☴ Extended Schema Example
Shows a table schema that has been extended to work with [`dreamcatcher.js`](https://github.com/bhoriuchi/dreamcatcher) which looks for a `_rest` field ```js var schema = { location: { id: { type: 'integer', primary: true, increments: true } name: { type: 'string' } }, _rest : { auth: function(req, res, next) { // authentication code }, methods: { HEAD: {} GET: {}, POST: {}, PUT: {}, DELETE: {} } } } ```

Creates Table(s)

location id name
type INT(10) VARCHAR(255)
options PrimaryKey,
NotNULL,
Unsigned,
AutoIncrement
NotNULL