How to create a UNIQUE constraint on a JSONB field with Sequelize - node.js

I'm using the Sequelize ORM in NodeJS to manage a postgreSQL database.
I'm using the JSONB datatype in my table, I need an index on the JSONB field and an unique constraint on a property of this JSON.
If I have to do in a classic SQL here my script :
CREATE TABLE tableJson (id SERIAL PRIMARY KEY,
content JSONB NOT NULL);
CREATE INDEX j_idx ON tableJson USING gin(content jsonb_path_ops);
CREATE UNIQUE INDEX content_name_idx ON tableJson(((content->>'name')::varchar));
I've found how to create the table with the INDEX but not how to deal with the UNIQUE constraint. Here is a sample of my script :
var tableJson = sequelize.define('tableJson', {
content: Sequelize.JSONB
}, {
indexes: [{
fields: ['content'],
using: 'gin',
operator: 'jsonb_path_ops'
}
});
Is there a solution for my problem? If not I'll probably use the sequelize.query method to execute raw query but this is not very evolutive.
Any help would be appreciated!

This is the workaround I use to add indexes on JSONB fields with Postgres and Sequelize.
First, set the quoteIdentifiers option to false in your Sequelize client.
const seq = new Sequelize(db, user, pass, {
host: host,
dialect: 'postgres',
quoteIdentifiers: false,
});
(Watch out though, this will make all your table names case insensitive when created by Sequelize.sync())
You can now add indexes on JSONB fields this way in your model definition :
indexes: [
{
fields: ['content'],
using: 'gin',
operator: 'jsonb_path_ops'
},
{
fields: ['((content->>\'name\')::varchar)'],
unique: true,
name: 'content_name_idx',
}
],

Related

Add lower() to a field in addIndex() in sequelize migration

To create a unique index in sequelize migrations we can do something like below,
await queryInterface.addIndex(SCHOOL_TABLE, {
fields: ['name', 'school_id'],
unique: true,
name: SCHOOL_NAME_ID_UNIQUE_INDEX,
where: {
is_deleted: false
},
transaction,
})
The problem is It allows duplicates due to case senstivity.
In the doc here, It is mentioned that fields should be an array of attributes.
How can I apply lower() to name field so that It can become case insensitive?
I am using a workaround for now, using raw query. I don't think addIndex() supports using functions on fields.
await queryInterface.sequelize.query(`CREATE UNIQUE INDEX IF NOT EXISTS ${SCHOOL_NAME_ID_UNIQUE_INDEX}
ON ${SCHEMA}.schools USING btree (lower(name), school_id) where is_deleted = false;
`, { transaction});

Sequelize table name updates

I have a table in Postgres and for ORM I am using sequelize I need to update the table name so I've tried the below migration for this
queryInterface.renameTable('table1', 'table2', { transaction }
but for some reason, it's creating a new table with table2 with the same data as table 1 but table 1 still exits with blank data.is this correct behavior of this function so'll add a delete query.
This works
queryInterface.renameTable('OldTableName', 'NewTableName');
For that use case i normally rely on raw queries:
const { sequelize } = queryInterface;
await sequelize.query(
`ALTER TABLE table1
RENAME TO table2`,
{
type: QueryTypes.RAW,
raw: true,
transaction,
},
);

sequelize postgress bulk insert ignore if exist

I have following code
await tbl.bulkCreate(response.data, {
ignoreDuplicates: true
});
in response.data there is array of object.
What I expect it should check all the fields found duplicate do not insert,
What I am think it working like if Id exist ignore
I Think this ignoreDuplicates is not working due to id field which is always new for new record
Is there anyway I can say that check certain fields if that exist do not insert else insert
Thanks
Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5)
check your postgres version or you can use
{updateOnDuplicate : true}
try with composite key
queryInterface.addConstraint('Items', ['col1', 'col2'], {
type: 'unique',
name: 'custom_unique_constraint_name'
});

sequelize for Node.js : ER_NO_SUCH_TABLE

I'm new to sequelize and Node.js.
I coded for test sequelize, but error occured "ER_NO_SUCH_TABLE : Table 'db.node_tests' doesn't exist"
Error is very simple.
However, I want to get data from "node_test" table.
I think sequelize appends 's' character.
There is my source code.
var Sequelize = require('sequelize');
var sequelize = new Sequelize('db', 'user', 'pass');
var nodeTest = sequelize.define('node_test',
{ uid: Sequelize.INTEGER
, val: Sequelize.STRING} );
nodeTest.find({where:{uid:'1'}})
.success(function(tbl){
console.log(tbl);
});
I already create table "node_test", and inserted data using mysql client.
Does I misunderstood usage?
I found the answer my own question.
I appended Sequelize method option following. {define:{freezeTableName:true}}
Then sequelize not appends 's' character after table name.
Though the answer works nicely, I nowadays recommend the use of the tableName option when declaring the model:
sequelize.define('node_test', {
uid: Sequelize.INTEGER,
val: Sequelize.STRING
}, {
tableName: 'node_test'
});
http://docs.sequelizejs.com/manual/tutorial/models-definition.html
Sequelize is using by default the plural of the passed model name. So it will look for the table "node_tests" or "NodeTests". Also it can create the table for you if you want that.
nodeTest.sync().success(function() {
// here comes your find command.
})
Sync will try to create the table if it does not already exist. You can also drop the existing table and create a new one from scratch by using sync({ force: true }). Check the SQL commands on your command line for more details about what is going on.
When you define a model to an existing table, you need to set two options for sequelize to:
find your table name as-is and
not fret about sequelize's default columns updatedAt and createdAt that it expects.
Simply add both options like so:
var nodeTest = sequelize.define('node_test',
{ uid: Sequelize.INTEGER , val: Sequelize.STRING},
{ freezeTableName: true , timestamps: false} //add both options here
);
Note the options parameter:
sequelize.define('name_of_your_table',
{attributes_of_your_table_columns},
{options}
);
Missing either options triggers respective errors when using sequelize methods such as nodeTest.findAll().
> ER_NO_SUCH_TABLE //freezeTableName
> ER_BAD_FIELD_ERROR //timestamps
Alternatively, you can:
create a fresh table through sequelize. It will append "s" to the table name and create two timestamp columns as defaults or
use sequelize-auto, an awesome npm package to generate sequelize models from your existing database programmatically.
Here's the sequelize documentation for option configurations.
In my case, it was due to case. I was having:
sequelize.define('User', {
The correct way is to use lowercase:
sequelize.define('user', {

Sequelize.js how to map a varbinary type from MySQL

I am trying to use Sequelize.js to map all of the columns in my MySQL table.
The mysql table "User" has a Password column as type varbinary(50).
Does Sequelize.js support mapping for a varbinary type? I did not see such an option in the Sequelize docs, is there another way I can map it?
The built-in types in sequelize just maps to strings, so intead of:
User = sequelize.define('user', {
Password: Sequelize.STRING
});
You can write your own string like this:
User = sequelize.define('user', {
Password: 'VARBINARY(50)'
});
This is only necessary if you want sequelize to create your table for you (sequelize.sync()), if you are using pre-created tables it does not matter what you write as the type. The only exception to this is if you are using the Sequelize.BOOLEAN type, which converts 0 and 1 to their boolean value.

Resources