Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
12b18f9
test: support wrapping value in a function to catch error in expectsql
ephys Sep 17, 2022
1cf6754
feat: rework createDatabase/dropDatabase
ephys Sep 17, 2022
7c9c043
feat: add listDatabases
ephys Sep 17, 2022
1fa3320
Merge branch 'main' into ephys/mysql-create-schema
ephys Sep 17, 2022
71b5e5a
feat: hoist mariadb fixes in mysql
ephys Sep 17, 2022
a2b18a4
Merge branch 'ephys/mysql-create-schema' of github.com:sequelize/sequ…
ephys Sep 17, 2022
b4cc363
test: disable schema tests on sqlite
ephys Sep 17, 2022
123d8dc
Merge branch 'main' into ephys/mysql-create-schema
ephys Sep 17, 2022
ae9c58e
Merge branch 'main' into ephys/mysql-create-schema
ephys Sep 17, 2022
9d452c8
fix: declare mysql as supporting schemas
ephys Sep 17, 2022
905d3e1
test: fix mysql unit tests
ephys Sep 17, 2022
f70906e
fix(mysql): exclude system schemas from showAllSchemas
ephys Sep 17, 2022
e3d1be1
fix(mysql): map show tables result
ephys Sep 17, 2022
ec8b7a9
test: fix tests
ephys Sep 17, 2022
e5cbbf7
refactor: revert style change
ephys Sep 17, 2022
d47fef2
feat: make createSchemaQuery strict
ephys Sep 17, 2022
4267069
test: test dropSchemaQuery
ephys Sep 17, 2022
59f0c32
feat: support skip in all listAllSchemas
ephys Sep 17, 2022
538bbe8
test: add listDatabasesQuery tests
ephys Sep 17, 2022
3e2a45f
feat: implement schema methods in snowflake
ephys Sep 17, 2022
d41062f
test: update tests
ephys Sep 18, 2022
22fa54c
Merge branch 'main' into ephys/mysql-create-schema
ephys Sep 18, 2022
fafb962
test: fix db2 test
ephys Sep 18, 2022
4073646
Merge branch 'ephys/mysql-create-schema' of github.com:sequelize/sequ…
ephys Sep 18, 2022
cf7ad50
refactor: revert change, reserved for another pr
ephys Sep 18, 2022
5202c5b
refactor: simplify crud database error messages
ephys Sep 18, 2022
4c092f1
fix: prevent query-generator from throwing when receiving unrelated o…
ephys Sep 18, 2022
a88d3eb
test: update test
ephys Sep 18, 2022
8fc0c94
Merge branch 'main' into ephys/mysql-create-schema
ephys Sep 23, 2022
611d5ba
feat: apply review comments
ephys Sep 23, 2022
acb34fb
Merge branch 'ephys/mysql-create-schema' of github.com:sequelize/sequ…
ephys Sep 23, 2022
4a49ea1
test: re-add fake schema test
ephys Sep 23, 2022
3bc869c
test: update tests
ephys Sep 23, 2022
b6756cd
Merge branch 'main' into ephys/mysql-create-schema
fzn0x Sep 24, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/dialects/abstract/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,19 @@ export type DialectSupports = {
},
/* Do we need to say DEFAULT for bulk insert */
bulkDefault: boolean,
/**
* Whether this dialect has native support for schemas.
* For the purposes of Sequelize, a Schema is considered to be a grouping of tables.
* For instance, in MySQL, "CREATE DATABASE" creates what we consider to be a schema.
*/
schemas: boolean,
/**
* Whether this dialect has native support for having multiple databases per instance (in the postgres or mssql sense).
* For the purposes of Sequelize, a database is considered to be a grouping of schemas.
* For instance, in MySQL, "CREATE DATABASE" creates what we consider to be a schema,
* so we do not consider that MySQL supports this option.
*/
multiDatabases: boolean,
transactions: boolean,
settingIsolationLevelDuringTransaction: boolean,
transactionOptions: {
Expand Down Expand Up @@ -148,6 +160,7 @@ export abstract class AbstractDialect {
},
bulkDefault: false,
schemas: false,
multiDatabases: false,
transactions: true,
settingIsolationLevelDuringTransaction: true,
transactionOptions: {
Expand Down
29 changes: 28 additions & 1 deletion src/dialects/abstract/query-generator.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,27 @@ type HandleSequelizeMethodOptions = ParameterOptions & {

};

// keep CREATE_DATABASE_QUERY_OPTION_NAMES updated when modifying this
export interface CreateDatabaseQueryOptions {
collate?: string;
charset?: string;
encoding?: string;
ctype?: string;
template?: string;
}

// keep CREATE_SCHEMA_QUERY_OPTION_NAMES updated when modifying this
export interface CreateSchemaQueryOptions {
collate?: string;
charset?: string;
}

// keep LIST_SCHEMAS_QUERY_OPTION_NAMES updated when modifying this
export interface ListSchemasQueryOptions {
/** List of schemas to exclude from output */
skip?: string[];
}

export class AbstractQueryGenerator {
_dialect: AbstractDialect;

Expand Down Expand Up @@ -123,5 +144,11 @@ export class AbstractQueryGenerator {
options?: ArithmeticQueryOptions,
): string;

dropSchema(tableName: TableName): string | { query: string, bind?: unknown[] };
createSchemaQuery(schemaName: string, options?: CreateSchemaQueryOptions): string;
dropSchemaQuery(schemaName: string): string | { query: string, bind?: unknown[] };
listSchemasQuery(options?: ListSchemasQueryOptions): string;

createDatabaseQuery(databaseName: string, options?: CreateDatabaseQueryOptions): string;
dropDatabaseQuery(databaseName: string): string;
listDatabasesQuery(): string;
}
57 changes: 55 additions & 2 deletions src/dialects/abstract/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ const sequelizeError = require('../../errors');
const { IndexHints } = require('../../index-hints');
const { _validateIncludedElements } = require('../../model-internals');

/**
* List of possible options listed in {@link CreateDatabaseQueryOptions}.
* It is used to validate the options passed to {@link QueryGenerator#createDatabaseQuery},
* as not all of them are supported by all dialects.
*/
export const CREATE_DATABASE_QUERY_SUPPORTABLE_OPTION = new Set(['collate', 'charset', 'encoding', 'ctype', 'template']);
export const CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTION = new Set(['collate', 'charset']);
export const LIST_SCHEMAS_QUERY_SUPPORTABLE_OPTION = new Set(['skip']);

/**
* Abstract Query Generator
*
Expand All @@ -47,6 +56,30 @@ export class AbstractQueryGenerator {
this._initQuoteIdentifier();
}

createDatabaseQuery() {
if (this._dialect.supports.multiDatabases) {
throw new Error(`${this.dialect} declares supporting databases but createDatabaseQuery is not implemented.`);
}

throw new Error(`Databases are not supported in ${this.dialect}.`);
}

dropDatabaseQuery() {
if (this._dialect.supports.multiDatabases) {
throw new Error(`${this.dialect} declares supporting databases but dropDatabaseQuery is not implemented.`);
}

throw new Error(`Databases are not supported in ${this.dialect}.`);
}

listDatabasesQuery() {
if (this._dialect.supports.multiDatabases) {
throw new Error(`${this.dialect} declares supporting databases but listDatabasesQuery is not implemented.`);
}

throw new Error(`Databases are not supported in ${this.dialect}.`);
}

extractTableDetails(tableName, options) {
options = options || {};
tableName = tableName || {};
Expand Down Expand Up @@ -78,8 +111,28 @@ export class AbstractQueryGenerator {
};
}

dropSchema(tableName, options) {
return this.dropTableQuery(tableName, options);
createSchemaQuery() {
if (this._dialect.supports.schemas) {
throw new Error(`${this.dialect} declares supporting schema but createSchemaQuery is not implemented.`);
}

throw new Error(`Schemas are not supported in ${this.dialect}.`);
}

dropSchemaQuery() {
if (this._dialect.supports.schemas) {
throw new Error(`${this.dialect} declares supporting schema but dropSchemaQuery is not implemented.`);
}

throw new Error(`Schemas are not supported in ${this.dialect}.`);
}

listSchemasQuery() {
if (this._dialect.supports.schemas) {
throw new Error(`${this.dialect} declares supporting schema but listSchemasQuery is not implemented.`);
}

throw new Error(`Schemas are not supported in ${this.dialect}.`);
}

describeTableQuery(tableName, schema, schemaDelimiter) {
Expand Down
9 changes: 9 additions & 0 deletions src/dialects/abstract/query-interface.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ export interface ColumnsDescription {
[key: string]: ColumnDescription;
}

export interface DatabaseDescription {
Comment thread
WikiRik marked this conversation as resolved.
Resolved
name: string;
}

/**
* The interface that Sequelize uses to talk to all databases.
*
Expand Down Expand Up @@ -668,4 +672,9 @@ export class QueryInterface {
* Creates a database
*/
dropDatabase(name: string, options?: QueryRawOptions): Promise<void>;

/**
* Lists all available databases
*/
listDatabases(options?: QueryRawOptions): Promise<DatabaseDescription[]>;
}
25 changes: 13 additions & 12 deletions src/dialects/abstract/query-interface.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,17 @@ export class QueryInterface {
* @returns {Promise}
*/
async dropDatabase(database, options) {
options = options || {};
const sql = this.queryGenerator.dropDatabaseQuery(database);

return await this.sequelize.queryRaw(sql, options);
}

async listDatabases(options) {
const sql = this.queryGenerator.listDatabasesQuery();

return await this.sequelize.queryRaw(sql, { ...options, type: QueryTypes.SELECT });
}

/**
* Create a schema
*
Expand All @@ -62,8 +67,7 @@ export class QueryInterface {
* @returns {Promise}
*/
async createSchema(schema, options) {
options = options || {};
const sql = this.queryGenerator.createSchema(schema);
const sql = this.queryGenerator.createSchemaQuery(schema);

return await this.sequelize.queryRaw(sql, options);
}
Expand All @@ -77,12 +81,11 @@ export class QueryInterface {
* @returns {Promise}
*/
async dropSchema(schema, options) {
options = options || {};
const query = this.queryGenerator.dropSchema(schema);
const query = this.queryGenerator.dropSchemaQuery(schema);

let sql;
if (typeof query === 'object') {
options.bind = query.bind;
options = { ...options, bind: query.bind };
sql = query.query;
} else {
sql = query;
Expand Down Expand Up @@ -118,15 +121,13 @@ export class QueryInterface {
* @returns {Promise<Array>}
*/
async showAllSchemas(options) {
options = {
const showSchemasSql = this.queryGenerator.listSchemasQuery(options);

const schemaNames = await this.sequelize.queryRaw(showSchemasSql, {
...options,
raw: true,
type: this.sequelize.QueryTypes.SELECT,
};

const showSchemasSql = this.queryGenerator.showSchemasQuery(options);

const schemaNames = await this.sequelize.queryRaw(showSchemasSql, options);
});

return schemaNames.flatMap(value => (value.schema_name ? value.schema_name : value));
}
Expand Down
35 changes: 24 additions & 11 deletions src/dialects/db2/query-generator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

import { removeTrailingSemicolon } from '../../utils';
import { rejectInvalidOptions, removeTrailingSemicolon } from '../../utils';
import { CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTION } from '../abstract/query-generator';

const _ = require('lodash');
const Utils = require('../../utils');
Expand All @@ -9,6 +10,8 @@ const { AbstractQueryGenerator } = require('../abstract/query-generator');
const randomBytes = require('crypto').randomBytes;
const { Op } = require('../../operators');

const CREATE_SCHEMA_SUPPORTED_OPTIONS = new Set();

/* istanbul ignore next */
Comment thread
WikiRik marked this conversation as resolved.
Resolved
function throwMethodUndefined(methodName) {
throw new Error(`The method "${methodName}" is not defined! Please add it to your sql dialect.`);
Expand All @@ -25,17 +28,23 @@ export class Db2QueryGenerator extends AbstractQueryGenerator {
this.autoGenValue = 1;
}

createSchema(schema) {
return [
'CREATE SCHEMA',
this.quoteIdentifier(schema),
';',
].join(' ');
createSchemaQuery(schema, options) {
if (options) {
rejectInvalidOptions(
'createSchemaQuery',
this.dialect,
CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTION,
CREATE_SCHEMA_SUPPORTED_OPTIONS,
options,
);
}

return `CREATE SCHEMA ${this.quoteIdentifier(schema)};`;
}

_errorTableCount = 0;

dropSchema(schema) {
dropSchemaQuery(schema) {
// DROP SCHEMA Can't drop schema if it is not empty.
// DROP SCHEMA Can't drop objects belonging to the schema
// So, call the admin procedure to drop schema.
Expand All @@ -54,9 +63,13 @@ export class Db2QueryGenerator extends AbstractQueryGenerator {
};
}

showSchemasQuery() {
return 'SELECT SCHEMANAME AS "schema_name" FROM SYSCAT.SCHEMATA WHERE '
+ '(SCHEMANAME NOT LIKE \'SYS%\') AND SCHEMANAME NOT IN (\'NULLID\', \'SQLJ\', \'ERRORSCHEMA\')';
listSchemasQuery(options) {
const schemasToSkip = ['NULLID', 'SQLJ', 'ERRORSCHEMA'];
if (options?.skip) {
schemasToSkip.push(...options.skip);
}

return `SELECT SCHEMANAME AS "schema_name" FROM SYSCAT.SCHEMATA WHERE (SCHEMANAME NOT LIKE 'SYS%') AND SCHEMANAME NOT IN (${schemasToSkip.map(schema => this.escape(schema)).join(', ')});`;
}

versionQuery() {
Expand Down
24 changes: 18 additions & 6 deletions src/dialects/ibmi/query-generator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

import { removeTrailingSemicolon } from '../../utils';
import { rejectInvalidOptions, removeTrailingSemicolon } from '../../utils';
import { CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTION } from '../abstract/query-generator';

const Utils = require('../../utils');
const util = require('util');
Expand All @@ -11,6 +12,7 @@ const { Model } = require('../../model');
const SqlString = require('../../sql-string');

const typeWithoutDefault = new Set(['BLOB']);
const CREATE_SCHEMA_SUPPORTED_OPTIONS = new Set();

export class IBMiQueryGenerator extends AbstractQueryGenerator {

Expand All @@ -20,19 +22,29 @@ export class IBMiQueryGenerator extends AbstractQueryGenerator {
}

// Schema queries
createSchema(schema) {
createSchemaQuery(schema, options) {
if (options) {
rejectInvalidOptions(
'createSchemaQuery',
this.dialect,
CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTION,
CREATE_SCHEMA_SUPPORTED_OPTIONS,
options,
);
}

return `CREATE SCHEMA "${schema}"`;
}

dropSchema(schema) {
dropSchemaQuery(schema) {
return `BEGIN IF EXISTS (SELECT * FROM SYSIBM.SQLSCHEMAS WHERE TABLE_SCHEM = ${schema ? `'${schema}'` : 'CURRENT SCHEMA'}) THEN SET TRANSACTION ISOLATION LEVEL NO COMMIT; DROP SCHEMA "${schema ? `${schema}` : 'CURRENT SCHEMA'}"; COMMIT; END IF; END`;
}

showSchemasQuery(options) {
listSchemasQuery(options) {
let skippedSchemas = '';
if (options.skip) {
if (options?.skip) {
for (let i = 0; i < options.skip.length; i++) {
skippedSchemas += ` AND SCHEMA_NAME != '${options.skip[i]}'`;
skippedSchemas += ` AND SCHEMA_NAME != ${this.escape(options.skip[i])}`;
}
}

Expand Down
Loading