ORM: Sequelize: Add Not Equal Constraint for Two Columns - mysql

I have a following table. I don't want user to follow himself so I want to add a CHECK constraint.
For example, if this is inserted, I want database to throw an error.
{
userID: 1,
followingID: 1,
}
I can check with Javascript if userID and followingID are equal but I want database to check it.
My MYSQL version is 8.0.17 so I think it is possible to create this constraint with SQL. How can I add this constraint with Sequelize?

There is two solution
1. Using Model wise validation and adding check constraint in database manually:
Model wise validation:
const FollowingModel = sequelize.define("following", {
userId: {
type: Sequelize.INTEGER,
// .. other configuration like `allowNull`
},
followingId: {
type: Sequelize.INTEGER,
// .. other configuration like `allowNull`
}
}, {
validate: {
userShouldNotFollowSelf : function() {
if(this.userId === this.followingId) {
throw Error("User should not follow self") // Use any custom error class if your application has such class.
}
}
}
}
Beware this will allow you create entry in database which does not maintain this constraint.
It is just ORM's application layer check that, this application won't allow any entry where userId and followingId is not same.
Mysql database layer check constraint.
CREATE TABLE `following`
(
`userId` INT NOT NULL,
`followingId` INT NOT NULL,
CONSTRAINT `no_self_following` CHECK (`userId` <> `followingId`)
-- other properties and foreign key constraints.
);
It will ensure that, no such entry inserted where userId and followingId is same.
2. Declaring constraint in sequelize query interface.
This require to declare your model using query interfaces addConstraint as follows
sequelize.getQueryInterface().addConstraint("following", ['userId'], {
type: 'check',
name: "no_self_following"
where: {
userId: {
[Sequelize.Op.ne]: Sequelize.col("followingId")
}
}
});
Run this while all database model is been synced correctly. It will add database level constraint.
Which one to use ?
Approach #1 is more efficient. It is checking within the application without going into the database call, Makes your database less busy.

Related

How to make sequelize stop creating automatic tables (SEQUELIZE)

I found out that sequelize is creating tables automatically according to the definition of my model names.
I have the following code:
const DataTypes = require("sequelize");
const sequelize = require("../mysql.js");
const Approver = sequelize.define("approver", {
subordinate_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: "user",
key: "id",
},
},
leader_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: "user",
key: "id",
},
},
main_leader_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: "user",
key: "id",
},
},
});
const connect = async () => {
await Approver.sync();
};
connect();
module.exports = Approver;
every time I run the local server, I get the following message in the terminal:
CREATE TABLE IF NOT EXISTS `approvers` (`id` INTEGER NOT NULL auto_increment , `subordinate_id` INTEGER NOT NULL, `leader_id` INTEGER NOT NULL, `main_leader_id` INTEGER NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`subordinate_id`) REFERENCES `user` (`id`), FOREIGN KEY (`leader_id`) REFERENCES `user` (`id`), FOREIGN KEY (`main_leader_id`) REFERENCES `user` (`id`)) ENGINE=InnoDB;
and I found out that the table creation is generated from the model's define because I put other names in the model and the table created was the same as the one I had named the code.
I don't know why the table that is created is in the plural "approvers" and in the model I put the name "approver" and apparently if I try to put another name the plural doesn't happen as well as the word "approver".
the big problem is that I have migrations and when I run them the table "approver" is created in my database, but when I run the command to start the local server, the sequelize creates one more table. So I end up with 2 tables in the database, "approver" of the migration and "approvers" of the model.
I already tried to put the migration and the model with the plural name "approver" but this causes an error when I try to use the model, the sequelize shows a missing field error when I try to create or update data, it says that the value "updatedAt" is missing, and this only happens because the automatically generated table creates this field, but the funniest thing is that the table was not created in my Dbeaver but the sequelize shows the error of being missing a field, even the model containing the plural name and the migration too...
I would like to get the result that the table is not created with the plural.
does anyone know how to solve this bug?
enter image description here
You have two problems here:
An auto-creation of a table according to a model definition
Pluralization of a table name while auto-creating it
Solutions:
Just remove sync call or the whole piece of the following code:
const connect = async () => {
await Approver.sync();
};
connect();
If you use migrations to create the whole structure and to make modifications to it then you don't need to use sync method of a model or a Sequelize instance.
Pluralization of table names can be turned off by indicating 'freezeTableName: true' in the model's options (see Enforcing table name to be equal to a model name in the official documentation).

Prisma, how to see relational foreign key id?

Prisma, how to see relational foreign key id?
They say when you do this
await ctx.prisma.post.create({
data: {
title: input.title,
content: input.content,
contentHtml: markdownToHtml(input.content),
author: {
connect: {
id: ctx.session.user.id,
},
},
},
})
It says "connect:" automatically connects. However, when I enter the database on planet scale and check, the corresponding column does not exist. How is this data permanently preserved? Also where can I extract it?

Add foreign key index Loopback 4 MySQL

i am new in Loopback 4
I followed this tutorial to get started and everything worked fine.
I tried to create my own models Category and SubCategory using a MySQL database, with one to many relation (one category has many sub categories), i have noticed that it did create a field in subcategory table (categoryId) but the foreign key index is missing.
can someone help?
LoopBack 4 does not implicitly add foreign key constraints. This is to allow weak cross-datasource relations (e.g. a relation between PostgreSQL & Oracle).
Hence, the responsibility falls on the connectors to provide an interface to define these constraints. This however, means that there isn't a consistent interface across different connectors. There is an open issue to track this.
In the case of MySQL:
#model({
settings: {
foreignKeys: {
categorySubCategoryFK: {
name: 'categorySubCategoryFK',
entity: 'Category',
entityKey: 'id',
foreignKey: 'categoryId',
},
},
},
})
In case auto-migration is used (which it should not be used in production!), migrate.ts would need to be updated to define explicit ordering of the schemas:
await app.migrateSchema({
existingSchema,
models: ['Category', 'SubCategory'],
});
Further reading
https://loopback.io/doc/en/lb4/todo-list-tutorial-sqldb.html#specify-the-foreign-key-constraints-in-todo-model
https://loopback.io/doc/en/lb4/MySQL-connector.html
found the answer here, besides adding the settings to #model annotation, like so
#model({
settings: {
foreignKeys: {
categorySubCategoryFK: {
name: 'categorySubCategoryFK',
entity: 'Category',
entityKey: 'id',
foreignKey: 'categoryId',
},
},
},
})
you have to change to specify in which order tables should be created in migrate.ts and change this
await app.migrateSchema({existingSchema});
to this
await app.migrateSchema({
existingSchema,
models: ['Category', 'SubCategory'],
});
more details here
Loopback 4 creates relation on models and Api's not on database. Thus it won't get reflected on your mysql database

Defining Sequelize model for existing MySQL database

Please advise on the following issue. I'd like to use Sequelize to work with existing database.
Stack used:
- Node.js v6.10.3
- MySQL 2nd Gen 5.7 running on Google Cloud
- Sequelize 4.7.5
MySQL contains 1 table - 'test_table' with columns 'id', 'content', 'status' and holds some data.
I want to define testTable model which would "explain" my MySQL 'test_table' for sequelize, so I run:
const connection = new Sequelize("dbName", "user", "pass", {
host: xxx.xxx.xxx.xxx,
dialect: mysql
});
const testTable = connection.define('test_table', {
id: {type: Sequelize.INTEGER,
allowNull: false, unique: true,
primaryKey: true, autoIncrement:
true},
content: {type: Sequelize.STRING},
status: {type: Sequelize.STRING},
});
First surprise I get is that from this moment onwards Node completely ignores existence of 'test_table' and creates its 'analogue' (???).
C:\Users\dmitri\Desktop\app>node query.js
Executing (default): CREATE TABLE IF NOT EXISTS `test_tables` (`id` INTEGER NOT NULL auto_increment UNIQUE , `content` VARCHAR(255), `status` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DAT
ETIME NOT NULL, UNIQUE `test_tables_id_unique` (`id`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SELECT `id`, `content`, `status`, `createdAt`, `updatedAt` FROM `test_tables` AS `test_table`;
Executing (default): SHOW INDEX FROM `test_tables`
Now MySQL contains two tables:
- 'test_table' (singular)
- 'test_tables' (plural) identical to "test_table" but empty.
I am trying to SELECTid,contentFROMtest_table` by executing the following Sequelize code:
testTable
.findAll({attributes: ['id', 'content']})
.then(result=>{
console.log(result)
})
Instead of returning contents of 'test_table', node keeps ignoring it:
C:\Users\dmitri\Desktop\app>node query.js
Executing (default): SELECT id, content FROM test_tables AS test_table;
and returns [].
What may be the reason it voluntarily jumps to query 'test_tables' instead of 'test_table'? Am I completely missing something here?
Many thanks!
You should have specified the table name in the options. Delete this new table, add the table name option and re-lift the app.
connection.define('test_table', {
//.... your fields
}, {
tableName: 'test_table'
});
On a side note, I like to have my models named with camelcase. TestTable. Same goes for connection.define('TestTable'...
EDIT:
As your comments I clarify a couple of things:
You can/have to specify the table name when defining the model. Look at my example. Specifying the tableName property guarantees the pluralization doesnt screw you over.
You shouldnt do sequelize.sync() (unless you know what it does and you want it). Otherwise you might get problems (like sequelize creating another table because it cant find the one it looks for).
Defining the models is something you have to do if you want to use sequelize. Otherwise it doesnt make sense and you should use just mysql2. You have to define the models to match the tables in your database.

How to build self referencing tables in Symfony using Propel ORM

I have an error trying to build a model from an existing database in a symfony project using the Propel ORM.
The error is this:
build-propel.xml:474:20: The 1:1 relationship expressed by foreign key a_table_on_my_schema_FK_1 is defined in both directions; Propel does not currently support this (if you must have both foreign key constraints, consider adding this constraint with a custom SQL file.)
the schema.yml file is really extensive but the description of the table that causes the error (the first not correctly created) is like this:
self_referenced_table:
_attributes: { phpName: SelfReferencedTable }
[...]
JERARQUIC_CODE: { phpName: JerarquicCode, type: INTEGER, size: '8', required: false, foreignTable: self_referenced_table, foreignReference: JERARQUIC_CODE, onDelete: RESTRICT, onUpdate: RESTRICT }
[...]
I think this error is because of the self referenced table.
I need to implement a jerarquic relation between many elements so this implementation is a good way to do it. But causes me this problem on construction.
Can you give me some clues? have someone had this error? what would you do?
thank you!! :D
Solved: It was not a self referencing table error, as said by #Colin Fine. The error was on the source database. I generated the schema.yml from an existing database on mysql. The error was there: the target attribute of the reference was not the identifier of the table, was the reference attribute itself. So, the generated schema.yml contained wrong definitions. I think i havn't explained well enough:
self_referenced_table was that:
_attributes: { phpName: SelfReferencedTable }
[...]
JERARQUIC_CODE: { phpName: JerarquicCode, type: INTEGER, size: '8', required: false, foreignTable: self_referenced_table, foreignReference: JERARQUIC_CODE, onDelete: RESTRICT, onUpdate: RESTRICT }
[...]
self_referenced_table should be:
_attributes: { phpName: SelfReferencedTable }
[...]
JERARQUIC_CODE: { phpName: JerarquicCode, type: INTEGER, size: '8', required: false, foreignTable: self_referenced_table, foreignReference: TABLE_CODE, onDelete: RESTRICT, onUpdate: RESTRICT }
[...]