Skip to content

Schema Definition

Branden Horiuchi edited this page Jul 7, 2015 · 10 revisions

Schema Definition


knex-schemer uses the schema definition to create/sync/delete tables in the database. The schema definition is a simple JavaScript object in JSON format. Each key in the parent object defines a table name and its property is an object that defines that tables columns. Each column object then defines how that column should be built using types and options.

Column definitions can contain ignore attributes that are used to bypass the creation of the column when using the column as a relationship or other extensible property.

Any column that is not ignorable requires a type attribute


Format
var schema = {
    <table 1 name>: {
        <column 1 name>: { <attribute>: <value>, [additional column attributes] },
        <column 2 name>: { <attribute>: <value>, [additional column attributes] },
        ...
    },
    <table 2 name>: {
        <column 1 name>: { <attribute>: <value>, [additional column attributes] },
        <column 2 name>: { <attribute>: <value>, [additional column attributes] },
        ...
    },
    ...
};

Basic Example
// use the constants module for type values
var c = schemer.constants;

// define the schema for a user with multiple email addresses
// two entity tables and one junction table will be defined
// the entity tables will each define a primary key and the
// junction table will define a composite key by defining a
// primary key on 2 or more columns
var schema = {
  user: {
    id: {type: c.type.integer, primary: true, increments: true},
    name: {type: c.type.string, size: 255},
    username: {type: c.type.string, size: 100},
    password: {type: c.type.string, size: 255}
  },
  email: {
    id: {type: c.type.integer, primary: true, increments: true},
    address: {type: c.type.string, size:255}

  },
  email_user: {
    email_id: {type: c.type.integer, primary: true},
    user_id: {type: c.type.integer, primary: true}
  }
};

Ignore/Extensible example
// use the constants module for type values
var c = schemer.constants;

// in this example we define the relationship belongsToMany that
// can be used by bookshelf-factory to generate a model with a
// one-to-many relationship, pulling the data from the email table
// the _hello column is also ignored and can be used to define 
// table level properties. in this instance a function that
// returns hello
var schema = {
  user: {
    id: {type: c.type.integer, primary: true, increments: true},
    name: {type: c.type.string, size: 255},
    username: {type: c.type.string, size: 100},
    password: {type: c.type.string, size: 255},
    email: {hasMany: 'email'},
    _hello: {
      invoke: function() {
        return 'Hello!';
      }
    }
  },
  email: {
    id: {type: c.type.integer, primary: true, increments: true},
    user_id: {type: c.type.integer},
    address: {type: c.type.string, size:255}
  }
};