Skip to content

addConstraint, removeConstraint - #7108

Merged
sushantdhiman merged 13 commits into
sequelize:masterfrom
harshithkashyap:add-remove-constraints
Apr 6, 2017
Merged

sushantdhiman merged 13 commits into
sequelize:masterfrom
harshithkashyap:add-remove-constraints

Conversation

@harshithkashyap

@harshithkashyap harshithkashyap commented Jan 14, 2017 •

Copy link
Copy Markdown

Pull Request check-list

  • Does npm run test or npm run test-DIALECT pass with this change (including linting)?
  • Does your issue contain a link to existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
  • Have you added an entry under Future in the changelog?

Description of change

Added addConstraint, showConstraint, removeConstraint methods. Closes #5212

Supported constraints

  • UNIQUE
  • CHECK
  • DEFAULT (MSSQL only)
  • PRIMARY KEY
  • FOREIGN KEY

@codecov-io

codecov-io commented Jan 14, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #7108 into master will increase coverage by 0.05%.
The diff coverage is 97.42%.


Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 2f7ac2d...bf40306. Read the comment docs.

@harshithkashyap

harshithkashyap commented Jan 14, 2017 •

Copy link
Copy Markdown
Author

@mickhansen @janmeier @sushantdhiman @felixfbecker Request review.
I've skipped tests for mysql & sqlite.

  • Sqlite does not support add/remove constraints.
  • MySQL does not support DROP CONSTRAINT but it is rather implemented as DROP PRIMARY, DROP FOREIGN KEY FK_NAME for primary and foreign keys.
  • DROP INDEX should be used for UNIQUE constraint(MySQL).
  • CHECK constraints are silently ignored by the db engines(MySQL)

@sushantdhiman

Copy link
Copy Markdown
Contributor

@harshithkashyap

MySQL does not support DROP CONSTRAINT but it is rather implemented as DROP PRIMARY, DROP FOREIGN KEY FK_NAME for primary and foreign keys.
DROP INDEX should be used for UNIQUE constraint(MySQL).
CHECK constraints are silently ignored by the db engines(MySQL)

ORM should be able to abstract these changes, It wont help much if these methods cant be used for 50% dialects

Sqlite does not support add/remove constraints.

You can create new table with constraints and move data to it

@harshithkashyap

harshithkashyap commented Jan 15, 2017 •

Copy link
Copy Markdown
Author

@sushantdhiman I've added a removeConstraint method in mysql queryinterface to handle drop constraint based on the case.
SQLite stores the create table query in sqlite_master table. Since the specified constraints are not stored in any table/view, i've dropped down to parsing and modifying sql queries.

@harshithkashyap

Copy link
Copy Markdown
Author

Ping @janmeier @mickhansen

Comment thread docs/docs/migrations.md Outdated
queryInterface.addConstraint('Posts', ['username'], {
type: 'FOREIGN KEY',
references: { //Required field
model: 'target_table_name',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

table

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mickhansen I used the same naming conventions from migration docs. It has model/key for the references object.

Comment thread docs/docs/migrations.md Outdated
type: 'FOREIGN KEY',
references: { //Required field
model: 'target_table_name',
key: 'target_column_name',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

column? or field

Comment thread test/unit/sql/remove-constraint.test.js Outdated
const sql = current.dialect.QueryGenerator;
const dialect = Support.getTestDialect();

if (dialect === 'mssql' || dialect === 'postgres') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't remove constraints in mysql?
Please use dialect.features rather dialect naming checks

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, mysql doesn't have removeConstraint in queryGenerator. We have to override removeConstraint in mysql queryInterface and it ultimately calls QueryGenerator.removeIndexQuery or QueryGenerator.dropForeignKeyQuery which already have tests covered

Comment thread test/unit/sql/add-constraint.test.js Outdated
const expect = require('chai').expect;
const dialect = Support.getTestDialect();

if (dialect !== 'sqlite') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

features check, no constraints in sqlite?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sqlite implementation of addContraint is a bit different. It has its own queryInterface method and queryGenerator functions. So, i've skipped them. But i'll go ahead and add unit tests for sqlite queryGenerator functions.

@harshithkashyap
harshithkashyap force-pushed the add-remove-constraints branch 4 times, most recently from bd380af to c34276d Compare January 30, 2017 18:42
@harshithkashyap

Copy link
Copy Markdown
Author

}
});

if(options.where) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

space before parens (saw this in multiple places)

@harshithkashyap harshithkashyap Jan 31, 2017 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching. I'll fix all occurrences and also add keyword-spacing to eslintrc

Comment thread lib/query-interface.js
options = Utils.cloneDeep(options);
options.fields = attributes;
if (this.sequelize.dialect.name === 'sqlite') {
return SQLiteQueryInterface.addConstraint.call(this, tableName, options, rawTablename);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't get this. The dialect-specific query interfaces inherit from the base one. So the user would get a SQLiteQueryInterface if they use SQLite. That may call super, in which case you get an infinite recursion here?
The children should call the parent, not the other way around

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@felixfbecker Only QueryGenerators are inherited. removeColumn also uses the same pattern.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay

Comment thread lib/dialects/sqlite/query.js Outdated
if (constraintSql.indexOf('REFERENCES') !== -1) {
//Parse out the constraint condition form sql string
update_action = constraintSql.match(/ON UPDATE (CASCADE|SET NULL|RESTRICT|NO ACTION|SET DEFAULT){1}/);
delete_action = constraintSql.match(/ON DELETE (CASCADE|SET NULL|RESTRICT|NO ACTION|SET DEFAULT){1}/);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why snake_case?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postgres & mssql returns it in snake case. Used the same here to maintain consistency

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@harshithkashyap harshithkashyap Jan 31, 2017 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies. Looks like MSSQL is the culprit here. I'm using MSSQL stored procedure sp_helpconstraint and hence can't format the results. I used the same snake_case for other dialects aswell.
Since default constraint in case of mssql are not part of ISO standard, i can't query on INFORMATION_SCHEMA.TABLE_CONSTRAINTS as we query in case of mysql and postgresql.
We could convert the snake_case to camelCase in mssql query.js and use sql aliases in case of mysql & postgres?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postgres and MSSQL return format doesn't control variable name we use, does it ?

Just rename update_action => updateAction , delete_action => deleteAction

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postgres is not a problem. Only MSSQL is. I'll convert snake_case keys to camelCase only in case of MSSQL.

@harshithkashyap

Copy link
Copy Markdown
Author

@sushantdhiman Can you take a look at this please?

@sushantdhiman sushantdhiman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initial review

Comment thread docs/docs/migrations.md Outdated
queryInterface.removeIndex('Person', ['firstname', 'lastname'])
```

### addConstraint(tableName, indexNameOrAttributes, options)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this is named as indexNameOrAttributes, I think it should be just attributes. Please explain your rationale behind this naming @harshithkashyap , I may be missing something

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry. It should just be attributes. The signature in the code is correct. But i missed it here. Will change it

Comment thread docs/docs/migrations.md Outdated
queryInterface.addConstraint('Posts', ['username'], {
type: 'FOREIGN KEY',
references: { //Required field
model: 'target_table_name',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can pass model here @harshithkashyap right, it will get table name from that ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't aware that we could pass model here. I'll modify the code to include the same.
Self Note: Add tests passing model

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sushantdhiman Since constraints are executed only via migrations, i'll keep it to tableName only for now. Even createTable method expects a string and not a model

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@harshithkashyap Please rename it to table as @mickhansen suggested, that more suited if we dont support passing model

Comment thread docs/docs/migrations.md Outdated
roles: ['user', 'admin', 'moderator', 'guest']
}
});
//Constraint name is automatically constructed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this comment line

Comment thread docs/docs/migrations.md Outdated
//UNIQUE
queryInterface.addConstraint('Users', ['email'], {
type: 'unique',
name: 'custom_unique_constraint_name' //If not specifed, sequelize automatically creates a named constraint based on constraint type, table & column names

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the comment

Comment thread docs/docs/migrations.md
```

### addConstraint(tableName, indexNameOrAttributes, options)
This method adds a new constraint of the specified type.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the description explain meaning of arguments, and what common options we have. Here you can explain things like options.name and what happens if you dont pass them

Comment thread lib/dialects/sqlite/query-generator.js Outdated
+ `DROP TABLE ${quotedBackupTableName};`;
},

alterConstraintQuery(tableName, attributes, createTableSql) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a private method, right. I don think user will ever call this as it require createTableSql. It will be good idea to prefix such private methods with _

Comment thread lib/dialects/sqlite/query.js Outdated
if (constraintSql.indexOf('REFERENCES') !== -1) {
//Parse out the constraint condition form sql string
update_action = constraintSql.match(/ON UPDATE (CASCADE|SET NULL|RESTRICT|NO ACTION|SET DEFAULT){1}/);
delete_action = constraintSql.match(/ON DELETE (CASCADE|SET NULL|RESTRICT|NO ACTION|SET DEFAULT){1}/);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postgres and MSSQL return format doesn't control variable name we use, does it ?

Just rename update_action => updateAction , delete_action => deleteAction

Comment thread lib/query-interface.js
options = attributes;
attributes = options.fields;
}
if (!options.type) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty line before this line

Comment thread lib/query-interface.js Outdated
if (!options.type) {
throw new Error('Constraint type must be specified through options.type');
}
// testhint argsConform.end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whats this comment ? remove this comment

Comment thread lib/query-interface.js

options = Utils.cloneDeep(options);
options.fields = attributes;
if (this.sequelize.dialect.name === 'sqlite') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty line before this line

@sushantdhiman

Copy link
Copy Markdown
Contributor

@harshithkashyap what happens for SQLite case, does it support addConstraint / removeConstraint. How we are handling that ?

@harshithkashyap

Copy link
Copy Markdown
Author

@sushantdhiman No, SQLite doesn't support addConstraint/removeConstraint.
Though SQLite allows us to name constraints as described here, SQLite does not store named constraints reference anywhere. We cannot removeConstraints by name.
The create table sql is stored in sqlite_master table. I'm querying on sqlite_master table, parsing the sql and adding constraint snippet at the end of create table query and recreating the table. In case of removeConstraint, we are finding the constraint snippet from the create table sql, remove it and recreate the table.

There are other open issues as well regarding sqlite alter table #7078 and i could not find any other way to go about it.

@harshithkashyap

Copy link
Copy Markdown
Author

@sushantdhiman

Copy link
Copy Markdown
Contributor

@harshithkashyap Please rebase this branch and take care of my last comment (Using table instead of model) :) We should merge it, its a good feature for CLI as well

@felixfbecker felixfbecker added the type: feature DEPRECATED: replace with the "feature" issue type label Apr 1, 2017
Comment thread docs/docs/migrations.md
references: { //Required field
model: 'target_table_name',
key: 'target_column_name'
},

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sushantdhiman Since we are changing model to table, would it better to rename key to column as well?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably field will make sense, as in our code base column is usually represented as field

@harshithkashyap
harshithkashyap force-pushed the add-remove-constraints branch from 5ff637c to bf40306 Compare April 6, 2017 13:23
@sushantdhiman
sushantdhiman merged commit 6730bc0 into sequelize:master Apr 6, 2017
@sushantdhiman

Copy link
Copy Markdown
Contributor

@harshithkashyap Great work ❤️

mkaufmaner pushed a commit to mkaufmaner/sequelize that referenced this pull request Apr 25, 2017
* Added add, remove & show constraints feat

* Added showConstraintsQuery for postgres & mysql

* [ci skip] Added docs for constraints usage

* Added removeIndex support for mysql

* Added altering constraints to sqlite dialect

* Refactor onDelete, onUpdate to work in sqlite dialect

* Throw non existent constraints in removeConstraint query as UnknownConstraintError, improve test coverage

* Fix failing tests

* Removed dialect naming check in favor of dialect.supports feature check

* Improve code coverage, eslint fixes

* Review fixes

* Review fixes

* Renamed model, key to table, field for foreign key contraint definition
@yyyyyyuanfei

Copy link
Copy Markdown

Which version will include this patch?

@felixfbecker

Copy link
Copy Markdown
Contributor

@yuanfeiz the next ;)

@yyyyyyuanfei

Copy link
Copy Markdown

Cool! Timely deliver!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature DEPRECATED: replace with the "feature" issue type

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants