Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize schema for PostgreSQL: How to accurately define a schema in a model?

I searched throughout the net and have not been able to determine how to add a schema to this sequelize model below. The following code does not kick back errors, however when I inspect the postgres DB, the only schema is the default one for public.

// The model definition is done in /path/to/models/project.js
module.exports = function(sequelize, DataTypes) {
  return sequelize.define("project", {
    name: DataTypes.STRING,
    description: DataTypes.TEXT,
  },
    define: {
        schema: "prefix"
    },
    classMethods: {
      method1: function() {},
      method2: function() {}
  },
    instanceMethods: {
      method3: function() {}
  })

How should the script be revised to accurately define a schema?

EDIT

In my case, the final answer was

 database_name.sequelize.createSchema('prefix').then(() => {...});

in my ./models/index.js file the database object is as follows:

database_name = {
    Sequelize: Sequelize,
    sequelize: sq,
    table_1: sq.import(__dirname + '/file_folder')
 };

module.exports = database_name;
like image 411
Val Avatar asked Feb 27 '17 22:02

Val


People also ask

How do you define a model in Sequelize?

Models can be defined in two equivalent ways in Sequelize: Calling sequelize.define(modelName, attributes, options) Extending Model and calling init(attributes, options)

How do I name a schema in PostgreSQL?

PostgreSQL ALTER SCHEMA statement overviewALTER SCHEMA schema_name RENAME TO new_name; In this syntax: First, specify the name of the schema that you want to rename after the ALTER SCHEMA keywords. Second, specify the new name of the schema after the RENAME TO keywords.


1 Answers

Your model definition should look as follows

module.exports = function(sequelize, DataTypes) {

    return sequelize.define("project", {
        name: DataTypes.STRING,
        description: DataTypes.TEXT,
    }, {
        schema: 'prefix',
        classMethods: {
            method1: function() {},
            method2: function() {}
        },
        instanceMethods: {
            method3: function() {}
        }
    }
}

According to the documentation of options object in sequelize.define method, it can have attribute called schema.

EDIT - Creating schema programatically

In order to create a new schema (only for PostgreSQL!), you can use the sequelize.createSchema() method:

sequelize.createSchema('prefix').then(() => {
    // new schema is created
});

Above creates given SQL

CREATE SCHEMA prefix;

In order to use this schema in model definitions, you need to create the schema before synchronising any model into the database - it could be run before sequelize.sync() or, if you use migrations, as a first migration file.

like image 108
piotrbienias Avatar answered Sep 18 '22 02:09

piotrbienias