I am trying to use Sequelize (1.7) with Postgresql (9.3) and trying to make use of schemas. I have created schemas externally in the database but making use of them in my models. When I am trying to do model associations, Sequelize complains that the relation doesn't exist. When I redefine the models to use the default "public" schema of PostgreSQL, it works fine.
Here are the model definitions and code for the test case
var Promise = require("bluebird");
var Sequelize = require("sequelize");
var _ = require('lodash-node');
var schemaName ="test_schema";
var sequelize = new Sequelize( c.database,c.username,
c.password,{dialect :'postgres', port:'5432',schema:schemaName});
var User =sequelize.define('User',{
id:{ type: Sequelize.INTEGER,primaryKey:true, autoIncrement:true},
name:{type:Sequelize.TEXT,allowNull:false},
nick_name:{type:Sequelize.TEXT,allowNull:true},
date_of_joining:{type:Sequelize.DATE,allowNull:false,defaultValue:Sequelize.NOW}
},
{
tableName:"user",
underscored:true,
timestamps:false
}
);
var Task = sequelize.define( 'Task',
{
id:{ type: Sequelize.INTEGER,primaryKey:true, autoIncrement:true},
name:{type:Sequelize.TEXT,allowNull:false},
begin_time:{type:Sequelize.DATE,allowNull:false,defaultValue:Sequelize.NOW},
end_time:{type:Sequelize.DATE,allowNull:true}
},
{
tableName:"task",
underscored:true,
timestamps:false
}
);
User.schema(schemaName);
Task.schema(schemaName);
User.hasMany( Task, {as:"Tasks"});
sequelize.sync( {force:true}, {logging:console.log})
.then( function( args ){
var users =[
{name:"Abraham Milbard"},
{name:"Jimmy Quake"},
{name:"John Amayo"}
];
var tasks =[
{name:"Bring 100 apples by today evening"},
{name:"Do the dishes"},
{name:"Watch soap and weep"},
{name:"Bitch about your miserable life"}
];
User.create( users[0])
.success( function( usr ){
var chainer = new Sequelize.Utils.QueryChainer;
var t1 = Task.build( tasks[0 ]),
t2 = Task.build( tasks[1]);
chainer.add(t1.save() );
chainer.add(t2.save() );
chainer.runSerially({ skipOnError:true})
.success( function( results ){
var tsk1 = results[0];
var tsk2 = results[1];
usr.setTasks([tsk1,tsk2]).success( function(assocTasks){
});
}).error( function( err ){
console.log("Could not add tasks to user"+err);
});
}).error( function( err ){
console.log("Could not create user ");
});
});
If you execute this code, the error reported is:
error: relation "task" does not exist
And the queries generated are:
Executing (default): SELECT * FROM "test_schema"."task" WHERE "test_schema"."task"."user_id"=1;
Executing (default): UPDATE "task" SET "user_id"=1 WHERE "id" IN (1,2) RETURNING *
It can clearly be seen that the UPDATE statement is failing because the schema prefix "test_schema" is missing. In other words, had the tool emitted the following query:
UPDATE "test_schema"."task" SET "user_id"=1 WHERE "id" IN (1,2) RETURNING *
It would have worked just fine. Can anyone here provide any workarounds/insights?