sequelize-typescript-generator 12.0.1 → 13.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +832 -204
- package/build/bin/cli.js +65 -47
- package/build/bin/utils.d.ts +5 -2
- package/build/bin/utils.js +87 -104
- package/build/builders/Builder.d.ts +2 -2
- package/build/builders/Builder.js +3 -5
- package/build/builders/ModelBuilder.d.ts +43 -8
- package/build/builders/ModelBuilder.js +120 -122
- package/build/builders/NativeModelRenderer.d.ts +98 -0
- package/build/builders/NativeModelRenderer.js +353 -0
- package/build/builders/associationNaming.d.ts +9 -0
- package/build/builders/associationNaming.js +15 -0
- package/build/builders/decoratorsDependency.d.ts +27 -0
- package/build/builders/decoratorsDependency.js +45 -0
- package/build/builders/defaultValues.d.ts +40 -0
- package/build/builders/defaultValues.js +56 -0
- package/build/builders/generatedFile.d.ts +23 -0
- package/build/builders/generatedFile.js +31 -0
- package/build/builders/index.d.ts +1 -1
- package/build/builders/index.js +1 -5
- package/build/builders/nativeAssociations.d.ts +109 -0
- package/build/builders/nativeAssociations.js +308 -0
- package/build/builders/nativeAttributes.d.ts +96 -0
- package/build/builders/nativeAttributes.js +174 -0
- package/build/builders/nativeWiring.d.ts +51 -0
- package/build/builders/nativeWiring.js +108 -0
- package/build/builders/utils.d.ts +75 -0
- package/build/builders/utils.js +142 -48
- package/build/config/IConfig.d.ts +11 -2
- package/build/config/IConfig.js +4 -6
- package/build/config/format.d.ts +27 -0
- package/build/config/format.js +26 -0
- package/build/config/index.d.ts +1 -1
- package/build/config/index.js +1 -2
- package/build/connection/createConnection.d.ts +8 -1
- package/build/connection/createConnection.js +30 -7
- package/build/connection/index.d.ts +1 -1
- package/build/connection/index.js +1 -17
- package/build/dialects/AssociationsParser.d.ts +10 -2
- package/build/dialects/AssociationsParser.js +16 -19
- package/build/dialects/Dialect.d.ts +52 -9
- package/build/dialects/Dialect.js +93 -57
- package/build/dialects/DialectMSSQL.d.ts +22 -3
- package/build/dialects/DialectMSSQL.js +169 -75
- package/build/dialects/DialectMariaDB.d.ts +13 -3
- package/build/dialects/DialectMariaDB.js +98 -79
- package/build/dialects/DialectMySQL.d.ts +13 -3
- package/build/dialects/DialectMySQL.js +102 -84
- package/build/dialects/DialectPostgres.d.ts +14 -3
- package/build/dialects/DialectPostgres.js +129 -75
- package/build/dialects/DialectSQLite.d.ts +41 -3
- package/build/dialects/DialectSQLite.js +166 -24
- package/build/dialects/associationDiscovery.d.ts +64 -0
- package/build/dialects/associationDiscovery.js +275 -0
- package/build/dialects/associationsFileMerge.d.ts +21 -0
- package/build/dialects/associationsFileMerge.js +107 -0
- package/build/dialects/createDialect.d.ts +8 -0
- package/build/dialects/createDialect.js +24 -0
- package/build/dialects/dataTypes.d.ts +58 -0
- package/build/dialects/dataTypes.js +108 -0
- package/build/dialects/foreignKeys.d.ts +115 -0
- package/build/dialects/foreignKeys.js +198 -0
- package/build/dialects/index.d.ts +5 -5
- package/build/dialects/index.js +5 -13
- package/build/dialects/paranoid.d.ts +24 -0
- package/build/dialects/paranoid.js +29 -0
- package/build/dialects/utils.d.ts +2 -8
- package/build/dialects/utils.js +61 -58
- package/build/index.d.ts +11 -3
- package/build/index.js +5 -19
- package/build/lint/Linter.d.ts +14 -3
- package/build/lint/Linter.js +114 -14
- package/build/lint/eslintDefaultConfig.d.ts +2 -2
- package/build/lint/eslintDefaultConfig.js +28 -23
- package/build/lint/index.d.ts +1 -1
- package/build/lint/index.js +1 -5
- package/build/utils/errors.d.ts +6 -0
- package/build/utils/errors.js +6 -0
- package/package.json +48 -28
- package/.github/FUNDING.yml +0 -1
- package/.github/workflows/ci.yml +0 -199
- package/CHANGELOG.md +0 -30
- package/tsconfig.json +0 -21
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import pluralize from 'pluralize';
|
|
2
|
+
/**
|
|
3
|
+
* The property name an association is emitted under: plural of the target model for
|
|
4
|
+
* the many-side associations, singular otherwise.
|
|
5
|
+
* @param {IAssociationMetadata} association
|
|
6
|
+
* @returns {string}
|
|
7
|
+
*/
|
|
8
|
+
const resolveEffectivePropertyName = (association) => association.associationName.includes('Many')
|
|
9
|
+
? pluralize.plural(association.targetModel)
|
|
10
|
+
: pluralize.singular(association.targetModel);
|
|
11
|
+
/**
|
|
12
|
+
* Apply the parsed associations file on top of discovered associations. For every
|
|
13
|
+
* declared foreign key the paired discovered association is dropped (junction rows keep
|
|
14
|
+
* their discovered associations), the column foreign key is rewritten to the declared
|
|
15
|
+
* target, the declared associations are appended, and any discovered association whose
|
|
16
|
+
* alias collides with a declared association is dropped. The inputs are not mutated.
|
|
17
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
18
|
+
* @param {IAssociationsParsed} parsed
|
|
19
|
+
* @returns {IAssociationsFileMergeResult}
|
|
20
|
+
*/
|
|
21
|
+
export const applyAssociationsFile = (tablesMetadata, parsed) => {
|
|
22
|
+
const warnings = [];
|
|
23
|
+
const nextTablesMetadata = {};
|
|
24
|
+
for (const [tableKey, table] of Object.entries(tablesMetadata)) {
|
|
25
|
+
const columns = {};
|
|
26
|
+
for (const [columnName, column] of Object.entries(table.columns)) {
|
|
27
|
+
columns[columnName] = {
|
|
28
|
+
...column,
|
|
29
|
+
...column.foreignKey && { foreignKey: { ...column.foreignKey } },
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const nextTable = {
|
|
33
|
+
...table,
|
|
34
|
+
columns,
|
|
35
|
+
...table.associations !== undefined && { associations: [...table.associations] },
|
|
36
|
+
};
|
|
37
|
+
nextTablesMetadata[tableKey] = nextTable;
|
|
38
|
+
}
|
|
39
|
+
// The mutable association list of a model, created on first use.
|
|
40
|
+
const getAssociations = (modelKey) => {
|
|
41
|
+
const table = nextTablesMetadata[modelKey];
|
|
42
|
+
if (!table.associations) {
|
|
43
|
+
table.associations = [];
|
|
44
|
+
}
|
|
45
|
+
return table.associations;
|
|
46
|
+
};
|
|
47
|
+
// Drop the discovered BelongsTo on the source model for the given foreign key column
|
|
48
|
+
// and its paired Has* on the discovered target model.
|
|
49
|
+
const removeDiscoveredPair = (sourceKey, foreignKeyColumn) => {
|
|
50
|
+
const sourceAssociations = getAssociations(sourceKey);
|
|
51
|
+
const belongsToIndex = sourceAssociations.findIndex(association => association.associationName === 'BelongsTo'
|
|
52
|
+
&& association.foreignKey === foreignKeyColumn);
|
|
53
|
+
if (belongsToIndex === -1) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const [belongsTo] = sourceAssociations.splice(belongsToIndex, 1);
|
|
57
|
+
const targetTable = nextTablesMetadata[belongsTo.targetModel];
|
|
58
|
+
if (!targetTable || !targetTable.associations) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const hasIndex = targetTable.associations.findIndex(association => (association.associationName === 'HasOne' || association.associationName === 'HasMany')
|
|
62
|
+
&& association.targetModel === sourceKey
|
|
63
|
+
&& association.foreignKey === foreignKeyColumn);
|
|
64
|
+
if (hasIndex !== -1) {
|
|
65
|
+
targetTable.associations.splice(hasIndex, 1);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
for (const [sourceKey, parsedTable] of Object.entries(parsed)) {
|
|
69
|
+
if (!nextTablesMetadata[sourceKey]) {
|
|
70
|
+
warnings.push(`Associated table ${sourceKey} not found among (${Object.keys(tablesMetadata).join(', ')})`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const { columns } = nextTablesMetadata[sourceKey];
|
|
74
|
+
for (const { name: foreignKeyColumn, targetModel, isJunctionForeignKey } of parsedTable.foreignKeys) {
|
|
75
|
+
if (!isJunctionForeignKey) {
|
|
76
|
+
removeDiscoveredPair(sourceKey, foreignKeyColumn);
|
|
77
|
+
}
|
|
78
|
+
if (!columns[foreignKeyColumn]) {
|
|
79
|
+
warnings.push(`Foreign key column ${foreignKeyColumn} not found among (${Object.keys(columns).join(', ')})`);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const discovered = columns[foreignKeyColumn].foreignKey;
|
|
83
|
+
columns[foreignKeyColumn] = {
|
|
84
|
+
...columns[foreignKeyColumn],
|
|
85
|
+
foreignKey: {
|
|
86
|
+
...(discovered?.targetModel === targetModel ? discovered : {}),
|
|
87
|
+
name: foreignKeyColumn,
|
|
88
|
+
targetModel,
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const sourceAssociations = getAssociations(sourceKey);
|
|
93
|
+
for (const parsedAssociation of parsedTable.associations) {
|
|
94
|
+
const propertyName = resolveEffectivePropertyName(parsedAssociation);
|
|
95
|
+
for (let index = sourceAssociations.length - 1; index >= 0; index--) {
|
|
96
|
+
const existing = sourceAssociations[index];
|
|
97
|
+
if (existing.alias !== undefined && existing.alias === propertyName) {
|
|
98
|
+
warnings.push(`Association alias '${existing.alias}' on table '${sourceKey}' is used by both a `
|
|
99
|
+
+ `discovered association and the associations file; the associations file entry is kept`);
|
|
100
|
+
sourceAssociations.splice(index, 1);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
sourceAssociations.push(...parsedTable.associations.map(association => ({ ...association })));
|
|
105
|
+
}
|
|
106
|
+
return { tablesMetadata: nextTablesMetadata, warnings };
|
|
107
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Dialect } from './Dialect.js';
|
|
2
|
+
/**
|
|
3
|
+
* Create the Dialect instance matching the given dialect name.
|
|
4
|
+
* @param {string} name
|
|
5
|
+
* @returns {Dialect}
|
|
6
|
+
* @throws {Error} When the name is not one of the accepted dialects
|
|
7
|
+
*/
|
|
8
|
+
export declare const createDialect: (name: string) => Dialect;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { DIALECT_NAMES } from './Dialect.js';
|
|
2
|
+
import { DialectMySQL, DialectPostgres, DialectMSSQL, DialectMariaDB, DialectSQLite, } from './index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Create the Dialect instance matching the given dialect name.
|
|
5
|
+
* @param {string} name
|
|
6
|
+
* @returns {Dialect}
|
|
7
|
+
* @throws {Error} When the name is not one of the accepted dialects
|
|
8
|
+
*/
|
|
9
|
+
export const createDialect = (name) => {
|
|
10
|
+
switch (name) {
|
|
11
|
+
case 'postgres':
|
|
12
|
+
return new DialectPostgres();
|
|
13
|
+
case 'mysql':
|
|
14
|
+
return new DialectMySQL();
|
|
15
|
+
case 'mariadb':
|
|
16
|
+
return new DialectMariaDB();
|
|
17
|
+
case 'sqlite':
|
|
18
|
+
return new DialectSQLite();
|
|
19
|
+
case 'mssql':
|
|
20
|
+
return new DialectMSSQL();
|
|
21
|
+
default:
|
|
22
|
+
throw new Error(`Unknown dialect '${name}': must be one of (${DIALECT_NAMES.join(', ')})`);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { DataTypes } from 'sequelize';
|
|
2
|
+
import type { AbstractDataTypeConstructor } from 'sequelize';
|
|
3
|
+
export type SequelizeDataTypeKey = keyof typeof DataTypes;
|
|
4
|
+
export type DataTypeArgument = string | number;
|
|
5
|
+
/**
|
|
6
|
+
* Format-neutral Sequelize data type: a DataTypes key plus its rendered arguments.
|
|
7
|
+
* Numeric arguments render bare; string arguments render single-quoted (ENUM values).
|
|
8
|
+
*/
|
|
9
|
+
export interface ISequelizeDataType {
|
|
10
|
+
key: SequelizeDataTypeKey;
|
|
11
|
+
args: DataTypeArgument[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Namespaces under which a data type expression is rendered.
|
|
15
|
+
*/
|
|
16
|
+
export declare const DATA_TYPE_NAMESPACES: {
|
|
17
|
+
readonly decorators: "DataType";
|
|
18
|
+
readonly native: "DataTypes";
|
|
19
|
+
};
|
|
20
|
+
export type DataTypeNamespace = typeof DATA_TYPE_NAMESPACES[keyof typeof DATA_TYPE_NAMESPACES];
|
|
21
|
+
/**
|
|
22
|
+
* Type guard for a Sequelize DataTypes key.
|
|
23
|
+
* @param {string} value
|
|
24
|
+
* @returns {boolean}
|
|
25
|
+
*/
|
|
26
|
+
export declare const isSequelizeDataTypeKey: (value: string) => value is SequelizeDataTypeKey;
|
|
27
|
+
/**
|
|
28
|
+
* Resolve the DataTypes key for a constructor. The first token of the constructor
|
|
29
|
+
* key is used so that 'DOUBLE PRECISION' resolves to 'DOUBLE'. Returns undefined when
|
|
30
|
+
* the first token is not a DataTypes member.
|
|
31
|
+
* @param {AbstractDataTypeConstructor} ctor
|
|
32
|
+
* @returns {SequelizeDataTypeKey | undefined}
|
|
33
|
+
*/
|
|
34
|
+
export declare const resolveSequelizeDataTypeKey: (ctor: AbstractDataTypeConstructor) => SequelizeDataTypeKey | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Build a format-neutral Sequelize data type from a constructor and its arguments.
|
|
37
|
+
* Falsy arguments (null, undefined, 0, empty string) are dropped, matching the
|
|
38
|
+
* precision signature behaviour. Returns undefined when the constructor key does not
|
|
39
|
+
* resolve to a DataTypes member.
|
|
40
|
+
* @param {AbstractDataTypeConstructor} ctor
|
|
41
|
+
* @param {Array<DataTypeArgument | null | undefined>} args
|
|
42
|
+
* @returns {ISequelizeDataType | undefined}
|
|
43
|
+
*/
|
|
44
|
+
export declare const buildSequelizeDataType: (ctor: AbstractDataTypeConstructor, args: Array<DataTypeArgument | null | undefined>) => ISequelizeDataType | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Render a data type expression, e.g. DataType.DECIMAL(7,3) or DataTypes.ENUM('AA','BB').
|
|
47
|
+
* @param {ISequelizeDataType} dataType
|
|
48
|
+
* @param {DataTypeNamespace} namespace
|
|
49
|
+
* @returns {string}
|
|
50
|
+
*/
|
|
51
|
+
export declare const renderDataTypeExpression: (dataType: ISequelizeDataType, namespace: DataTypeNamespace) => string;
|
|
52
|
+
/**
|
|
53
|
+
* Parse the value list of an enum column type, e.g. "enum('AA','BB')" -> ['AA', 'BB'].
|
|
54
|
+
* Doubled single quotes are unescaped. Returns an empty array when there is no list.
|
|
55
|
+
* @param {string} columnType
|
|
56
|
+
* @returns {string[]}
|
|
57
|
+
*/
|
|
58
|
+
export declare const parseEnumValues: (columnType: string) => string[];
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { DataTypes } from 'sequelize';
|
|
2
|
+
/**
|
|
3
|
+
* Namespaces under which a data type expression is rendered.
|
|
4
|
+
*/
|
|
5
|
+
export const DATA_TYPE_NAMESPACES = {
|
|
6
|
+
decorators: 'DataType',
|
|
7
|
+
native: 'DataTypes',
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Type guard for a Sequelize DataTypes key.
|
|
11
|
+
* @param {string} value
|
|
12
|
+
* @returns {boolean}
|
|
13
|
+
*/
|
|
14
|
+
export const isSequelizeDataTypeKey = (value) => Object.prototype.hasOwnProperty.call(DataTypes, value);
|
|
15
|
+
/**
|
|
16
|
+
* Resolve the DataTypes key for a constructor. The first token of the constructor
|
|
17
|
+
* key is used so that 'DOUBLE PRECISION' resolves to 'DOUBLE'. Returns undefined when
|
|
18
|
+
* the first token is not a DataTypes member.
|
|
19
|
+
* @param {AbstractDataTypeConstructor} ctor
|
|
20
|
+
* @returns {SequelizeDataTypeKey | undefined}
|
|
21
|
+
*/
|
|
22
|
+
export const resolveSequelizeDataTypeKey = (ctor) => {
|
|
23
|
+
const [firstToken] = ctor.key.split(' ');
|
|
24
|
+
return isSequelizeDataTypeKey(firstToken) ? firstToken : undefined;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Build a format-neutral Sequelize data type from a constructor and its arguments.
|
|
28
|
+
* Falsy arguments (null, undefined, 0, empty string) are dropped, matching the
|
|
29
|
+
* precision signature behaviour. Returns undefined when the constructor key does not
|
|
30
|
+
* resolve to a DataTypes member.
|
|
31
|
+
* @param {AbstractDataTypeConstructor} ctor
|
|
32
|
+
* @param {Array<DataTypeArgument | null | undefined>} args
|
|
33
|
+
* @returns {ISequelizeDataType | undefined}
|
|
34
|
+
*/
|
|
35
|
+
export const buildSequelizeDataType = (ctor, args) => {
|
|
36
|
+
const key = resolveSequelizeDataTypeKey(ctor);
|
|
37
|
+
if (key === undefined) {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
const filteredArgs = [];
|
|
41
|
+
for (const arg of args) {
|
|
42
|
+
if (arg) {
|
|
43
|
+
filteredArgs.push(arg);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return { key, args: filteredArgs };
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Render a single data type argument. Numbers render bare; strings render
|
|
50
|
+
* single-quoted with internal single quotes doubled.
|
|
51
|
+
* @param {DataTypeArgument} arg
|
|
52
|
+
* @returns {string}
|
|
53
|
+
*/
|
|
54
|
+
const renderDataTypeArgument = (arg) => typeof arg === 'number' ? String(arg) : `'${arg.replace(/'/g, "''")}'`;
|
|
55
|
+
/**
|
|
56
|
+
* Render a data type expression, e.g. DataType.DECIMAL(7,3) or DataTypes.ENUM('AA','BB').
|
|
57
|
+
* @param {ISequelizeDataType} dataType
|
|
58
|
+
* @param {DataTypeNamespace} namespace
|
|
59
|
+
* @returns {string}
|
|
60
|
+
*/
|
|
61
|
+
export const renderDataTypeExpression = (dataType, namespace) => {
|
|
62
|
+
const signature = dataType.args.length
|
|
63
|
+
? `(${dataType.args.map(renderDataTypeArgument).join(',')})`
|
|
64
|
+
: '';
|
|
65
|
+
return `${namespace}.${dataType.key}${signature}`;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Parse the value list of an enum column type, e.g. "enum('AA','BB')" -> ['AA', 'BB'].
|
|
69
|
+
* Doubled single quotes are unescaped. Returns an empty array when there is no list.
|
|
70
|
+
* @param {string} columnType
|
|
71
|
+
* @returns {string[]}
|
|
72
|
+
*/
|
|
73
|
+
export const parseEnumValues = (columnType) => {
|
|
74
|
+
if (!columnType.trim().toLowerCase().startsWith('enum')) {
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
const match = columnType.match(/\((.*)\)/);
|
|
78
|
+
if (!match) {
|
|
79
|
+
return [];
|
|
80
|
+
}
|
|
81
|
+
const [, inner] = match;
|
|
82
|
+
const values = [];
|
|
83
|
+
let current = '';
|
|
84
|
+
let isInsideQuotes = false;
|
|
85
|
+
for (let index = 0; index < inner.length; index++) {
|
|
86
|
+
const char = inner[index];
|
|
87
|
+
if (char === "'") {
|
|
88
|
+
if (isInsideQuotes && inner[index + 1] === "'") {
|
|
89
|
+
current += "'";
|
|
90
|
+
index++;
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
isInsideQuotes = !isInsideQuotes;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else if (char === ',' && !isInsideQuotes) {
|
|
97
|
+
values.push(current);
|
|
98
|
+
current = '';
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
current += char;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (current.length || values.length) {
|
|
105
|
+
values.push(current);
|
|
106
|
+
}
|
|
107
|
+
return values;
|
|
108
|
+
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { ITableMetadata, IForeignKeyConstraintMetadata } from './Dialect.js';
|
|
2
|
+
/**
|
|
3
|
+
* Referential actions supported by Sequelize for onDelete/onUpdate.
|
|
4
|
+
*/
|
|
5
|
+
export declare const REFERENTIAL_ACTIONS: readonly ["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"];
|
|
6
|
+
export type ReferentialAction = typeof REFERENTIAL_ACTIONS[number];
|
|
7
|
+
/**
|
|
8
|
+
* One row of a dialect foreign key query, one per (constraint, column position).
|
|
9
|
+
*/
|
|
10
|
+
export interface IForeignKeyColumnRow {
|
|
11
|
+
constraintName: string;
|
|
12
|
+
sourceTable: string;
|
|
13
|
+
sourceColumn: string;
|
|
14
|
+
targetSchema?: string;
|
|
15
|
+
targetTable: string;
|
|
16
|
+
targetColumn: string;
|
|
17
|
+
ordinalPosition: number;
|
|
18
|
+
onDelete: string;
|
|
19
|
+
onUpdate: string;
|
|
20
|
+
isSourceColumnUnique: boolean;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* One row returned by a dialect foreign key query, one per (constraint, column position).
|
|
24
|
+
* `is_source_column_unique` carries the uniqueness predicate in whatever shape the dialect
|
|
25
|
+
* returns it: a boolean (Postgres EXISTS), a 0/1 number (MySQL, MariaDB, MSSQL) or its
|
|
26
|
+
* string form.
|
|
27
|
+
*/
|
|
28
|
+
export interface IForeignKeyQueryRow {
|
|
29
|
+
constraint_name: string;
|
|
30
|
+
source_table: string;
|
|
31
|
+
source_column: string;
|
|
32
|
+
target_schema: string;
|
|
33
|
+
target_table: string;
|
|
34
|
+
target_column: string;
|
|
35
|
+
ordinal_position: number;
|
|
36
|
+
on_delete: string;
|
|
37
|
+
on_update: string;
|
|
38
|
+
is_source_column_unique: number | boolean | string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Map a dialect foreign key query row onto a normalized foreign key column row,
|
|
42
|
+
* coercing the dialect-specific uniqueness value into a boolean.
|
|
43
|
+
* @param {IForeignKeyQueryRow} row
|
|
44
|
+
* @returns {IForeignKeyColumnRow}
|
|
45
|
+
*/
|
|
46
|
+
export declare const mapForeignKeyQueryRow: (row: IForeignKeyQueryRow) => IForeignKeyColumnRow;
|
|
47
|
+
/**
|
|
48
|
+
* Build the information_schema query that lists foreign key columns for a table.
|
|
49
|
+
* MySQL and MariaDB expose identical referential_constraints, key_column_usage and
|
|
50
|
+
* statistics tables, so both dialects share this query. A source column is reported
|
|
51
|
+
* unique when it is covered by a single-column non-composite unique index.
|
|
52
|
+
* @param {string | undefined} database
|
|
53
|
+
* @param {string} table
|
|
54
|
+
* @returns {string}
|
|
55
|
+
*/
|
|
56
|
+
export declare const buildInformationSchemaForeignKeysQuery: (database: string | undefined, table: string) => string;
|
|
57
|
+
/**
|
|
58
|
+
* Type guard for a referential action.
|
|
59
|
+
* @param {string} value
|
|
60
|
+
* @returns {boolean}
|
|
61
|
+
*/
|
|
62
|
+
export declare const isReferentialAction: (value: string) => value is ReferentialAction;
|
|
63
|
+
/**
|
|
64
|
+
* Normalize a raw referential action into a Sequelize referential action.
|
|
65
|
+
* Handles underscore spellings ('NO_ACTION'), spaced spellings, mixed case and
|
|
66
|
+
* Postgres single-letter codes (a/r/c/n/d). Unknown values fall back to 'NO ACTION'.
|
|
67
|
+
* @param {string | null | undefined} raw
|
|
68
|
+
* @returns {ReferentialAction}
|
|
69
|
+
*/
|
|
70
|
+
export declare const normalizeReferentialAction: (raw: string | null | undefined) => ReferentialAction;
|
|
71
|
+
/**
|
|
72
|
+
* Group foreign key rows by constraint, ordering columns by ordinal position.
|
|
73
|
+
* The source column unique flag is only meaningful for single-column constraints
|
|
74
|
+
* and is forced to false for composite ones.
|
|
75
|
+
* @param {IForeignKeyColumnRow[]} rows
|
|
76
|
+
* @returns {IForeignKeyConstraintMetadata[]}
|
|
77
|
+
*/
|
|
78
|
+
export declare const groupForeignKeyRows: (rows: IForeignKeyColumnRow[]) => IForeignKeyConstraintMetadata[];
|
|
79
|
+
/**
|
|
80
|
+
* Reasons a foreign key constraint cannot become a Sequelize association.
|
|
81
|
+
*/
|
|
82
|
+
export declare const FOREIGN_KEY_SKIP_REASONS: readonly ["composite", "cross-schema", "excluded-target"];
|
|
83
|
+
export type ForeignKeySkipReason = typeof FOREIGN_KEY_SKIP_REASONS[number];
|
|
84
|
+
/**
|
|
85
|
+
* Outcome of testing a foreign key constraint for association eligibility: eligible,
|
|
86
|
+
* or the first rule it fails.
|
|
87
|
+
*/
|
|
88
|
+
export type ForeignKeyClassification = {
|
|
89
|
+
isEligible: true;
|
|
90
|
+
} | {
|
|
91
|
+
isEligible: false;
|
|
92
|
+
reason: ForeignKeySkipReason;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Classify a foreign key constraint for association eligibility. A single-column
|
|
96
|
+
* constraint whose target table is generated and whose target schema matches the
|
|
97
|
+
* source schema is eligible; otherwise the first failing rule is returned in the
|
|
98
|
+
* order composite, cross-schema, excluded-target.
|
|
99
|
+
* @param {IForeignKeyConstraintMetadata} constraint
|
|
100
|
+
* @param {string | undefined} sourceSchema
|
|
101
|
+
* @param {ReadonlySet<string>} generatedTables
|
|
102
|
+
* @returns {ForeignKeyClassification}
|
|
103
|
+
*/
|
|
104
|
+
export declare const classifyForeignKeyConstraint: (constraint: IForeignKeyConstraintMetadata, sourceSchema: string | undefined, generatedTables: ReadonlySet<string>) => ForeignKeyClassification;
|
|
105
|
+
/**
|
|
106
|
+
* Copy single-column foreign key constraints onto the matching column metadata.
|
|
107
|
+
* A constraint is copied only when it targets a single column, the target table is
|
|
108
|
+
* among the generated tables and the target schema matches the source table schema.
|
|
109
|
+
* Composite, cross-schema and excluded-target constraints stay only in
|
|
110
|
+
* tableMetadata.foreignKeys. Returns a new table metadata without mutating the input.
|
|
111
|
+
* @param {ITableMetadata} tableMetadata
|
|
112
|
+
* @param {ReadonlySet<string>} generatedTables
|
|
113
|
+
* @returns {ITableMetadata}
|
|
114
|
+
*/
|
|
115
|
+
export declare const applyForeignKeyConstraintsToColumns: (tableMetadata: ITableMetadata, generatedTables: ReadonlySet<string>) => ITableMetadata;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Referential actions supported by Sequelize for onDelete/onUpdate.
|
|
3
|
+
*/
|
|
4
|
+
export const REFERENTIAL_ACTIONS = ['NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT'];
|
|
5
|
+
/**
|
|
6
|
+
* Map a dialect foreign key query row onto a normalized foreign key column row,
|
|
7
|
+
* coercing the dialect-specific uniqueness value into a boolean.
|
|
8
|
+
* @param {IForeignKeyQueryRow} row
|
|
9
|
+
* @returns {IForeignKeyColumnRow}
|
|
10
|
+
*/
|
|
11
|
+
export const mapForeignKeyQueryRow = (row) => ({
|
|
12
|
+
constraintName: row.constraint_name,
|
|
13
|
+
sourceTable: row.source_table,
|
|
14
|
+
sourceColumn: row.source_column,
|
|
15
|
+
targetSchema: row.target_schema,
|
|
16
|
+
targetTable: row.target_table,
|
|
17
|
+
targetColumn: row.target_column,
|
|
18
|
+
ordinalPosition: row.ordinal_position,
|
|
19
|
+
onDelete: row.on_delete,
|
|
20
|
+
onUpdate: row.on_update,
|
|
21
|
+
isSourceColumnUnique: row.is_source_column_unique === true || Number(row.is_source_column_unique) === 1,
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* Build the information_schema query that lists foreign key columns for a table.
|
|
25
|
+
* MySQL and MariaDB expose identical referential_constraints, key_column_usage and
|
|
26
|
+
* statistics tables, so both dialects share this query. A source column is reported
|
|
27
|
+
* unique when it is covered by a single-column non-composite unique index.
|
|
28
|
+
* @param {string | undefined} database
|
|
29
|
+
* @param {string} table
|
|
30
|
+
* @returns {string}
|
|
31
|
+
*/
|
|
32
|
+
export const buildInformationSchemaForeignKeysQuery = (database, table) => `
|
|
33
|
+
SELECT
|
|
34
|
+
rc.CONSTRAINT_NAME AS constraint_name,
|
|
35
|
+
kcu.TABLE_NAME AS source_table,
|
|
36
|
+
kcu.COLUMN_NAME AS source_column,
|
|
37
|
+
kcu.REFERENCED_TABLE_SCHEMA AS target_schema,
|
|
38
|
+
kcu.REFERENCED_TABLE_NAME AS target_table,
|
|
39
|
+
kcu.REFERENCED_COLUMN_NAME AS target_column,
|
|
40
|
+
kcu.ORDINAL_POSITION AS ordinal_position,
|
|
41
|
+
rc.DELETE_RULE AS on_delete,
|
|
42
|
+
rc.UPDATE_RULE AS on_update,
|
|
43
|
+
EXISTS (
|
|
44
|
+
SELECT 1
|
|
45
|
+
FROM information_schema.statistics s
|
|
46
|
+
WHERE s.TABLE_SCHEMA = kcu.TABLE_SCHEMA
|
|
47
|
+
AND s.TABLE_NAME = kcu.TABLE_NAME
|
|
48
|
+
AND s.COLUMN_NAME = kcu.COLUMN_NAME
|
|
49
|
+
AND s.NON_UNIQUE = 0
|
|
50
|
+
AND NOT EXISTS (
|
|
51
|
+
SELECT 1
|
|
52
|
+
FROM information_schema.statistics s2
|
|
53
|
+
WHERE s2.TABLE_SCHEMA = s.TABLE_SCHEMA
|
|
54
|
+
AND s2.TABLE_NAME = s.TABLE_NAME
|
|
55
|
+
AND s2.INDEX_NAME = s.INDEX_NAME
|
|
56
|
+
AND s2.SEQ_IN_INDEX > 1
|
|
57
|
+
)
|
|
58
|
+
) AS is_source_column_unique
|
|
59
|
+
FROM information_schema.referential_constraints rc
|
|
60
|
+
JOIN information_schema.key_column_usage kcu
|
|
61
|
+
ON kcu.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
|
|
62
|
+
AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
|
|
63
|
+
AND kcu.TABLE_NAME = rc.TABLE_NAME
|
|
64
|
+
WHERE rc.CONSTRAINT_SCHEMA = '${database}' AND rc.TABLE_NAME = '${table}'
|
|
65
|
+
ORDER BY rc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION;
|
|
66
|
+
`;
|
|
67
|
+
/**
|
|
68
|
+
* Type guard for a referential action.
|
|
69
|
+
* @param {string} value
|
|
70
|
+
* @returns {boolean}
|
|
71
|
+
*/
|
|
72
|
+
export const isReferentialAction = (value) => REFERENTIAL_ACTIONS.some(action => action === value);
|
|
73
|
+
const REFERENTIAL_ACTION_ALIASES = {
|
|
74
|
+
'NO ACTION': 'NO ACTION',
|
|
75
|
+
'RESTRICT': 'RESTRICT',
|
|
76
|
+
'CASCADE': 'CASCADE',
|
|
77
|
+
'SET NULL': 'SET NULL',
|
|
78
|
+
'SET DEFAULT': 'SET DEFAULT',
|
|
79
|
+
// Postgres pg_constraint single-letter codes
|
|
80
|
+
'A': 'NO ACTION',
|
|
81
|
+
'R': 'RESTRICT',
|
|
82
|
+
'C': 'CASCADE',
|
|
83
|
+
'N': 'SET NULL',
|
|
84
|
+
'D': 'SET DEFAULT',
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Normalize a raw referential action into a Sequelize referential action.
|
|
88
|
+
* Handles underscore spellings ('NO_ACTION'), spaced spellings, mixed case and
|
|
89
|
+
* Postgres single-letter codes (a/r/c/n/d). Unknown values fall back to 'NO ACTION'.
|
|
90
|
+
* @param {string | null | undefined} raw
|
|
91
|
+
* @returns {ReferentialAction}
|
|
92
|
+
*/
|
|
93
|
+
export const normalizeReferentialAction = (raw) => {
|
|
94
|
+
if (raw === null || raw === undefined) {
|
|
95
|
+
return 'NO ACTION';
|
|
96
|
+
}
|
|
97
|
+
const normalized = raw.trim().toUpperCase().replace(/_/g, ' ');
|
|
98
|
+
return REFERENTIAL_ACTION_ALIASES[normalized] ?? 'NO ACTION';
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Group foreign key rows by constraint, ordering columns by ordinal position.
|
|
102
|
+
* The source column unique flag is only meaningful for single-column constraints
|
|
103
|
+
* and is forced to false for composite ones.
|
|
104
|
+
* @param {IForeignKeyColumnRow[]} rows
|
|
105
|
+
* @returns {IForeignKeyConstraintMetadata[]}
|
|
106
|
+
*/
|
|
107
|
+
export const groupForeignKeyRows = (rows) => {
|
|
108
|
+
const rowsByConstraint = new Map();
|
|
109
|
+
for (const row of rows) {
|
|
110
|
+
const group = rowsByConstraint.get(row.constraintName) ?? [];
|
|
111
|
+
group.push(row);
|
|
112
|
+
rowsByConstraint.set(row.constraintName, group);
|
|
113
|
+
}
|
|
114
|
+
const constraints = [];
|
|
115
|
+
for (const [constraintName, group] of rowsByConstraint) {
|
|
116
|
+
const ordered = [...group].sort((a, b) => a.ordinalPosition - b.ordinalPosition);
|
|
117
|
+
const first = ordered[0];
|
|
118
|
+
const isComposite = ordered.length > 1;
|
|
119
|
+
constraints.push({
|
|
120
|
+
constraintName,
|
|
121
|
+
sourceTable: first.sourceTable,
|
|
122
|
+
sourceColumns: ordered.map(row => row.sourceColumn),
|
|
123
|
+
...first.targetSchema !== undefined && { targetSchema: first.targetSchema },
|
|
124
|
+
targetTable: first.targetTable,
|
|
125
|
+
targetColumns: ordered.map(row => row.targetColumn),
|
|
126
|
+
onDelete: normalizeReferentialAction(first.onDelete),
|
|
127
|
+
onUpdate: normalizeReferentialAction(first.onUpdate),
|
|
128
|
+
isSourceColumnUnique: isComposite ? false : first.isSourceColumnUnique,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return constraints;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Reasons a foreign key constraint cannot become a Sequelize association.
|
|
135
|
+
*/
|
|
136
|
+
export const FOREIGN_KEY_SKIP_REASONS = ['composite', 'cross-schema', 'excluded-target'];
|
|
137
|
+
/**
|
|
138
|
+
* Classify a foreign key constraint for association eligibility. A single-column
|
|
139
|
+
* constraint whose target table is generated and whose target schema matches the
|
|
140
|
+
* source schema is eligible; otherwise the first failing rule is returned in the
|
|
141
|
+
* order composite, cross-schema, excluded-target.
|
|
142
|
+
* @param {IForeignKeyConstraintMetadata} constraint
|
|
143
|
+
* @param {string | undefined} sourceSchema
|
|
144
|
+
* @param {ReadonlySet<string>} generatedTables
|
|
145
|
+
* @returns {ForeignKeyClassification}
|
|
146
|
+
*/
|
|
147
|
+
export const classifyForeignKeyConstraint = (constraint, sourceSchema, generatedTables) => {
|
|
148
|
+
if (constraint.sourceColumns.length !== 1) {
|
|
149
|
+
return { isEligible: false, reason: 'composite' };
|
|
150
|
+
}
|
|
151
|
+
if (constraint.targetSchema !== undefined &&
|
|
152
|
+
sourceSchema !== undefined &&
|
|
153
|
+
constraint.targetSchema !== sourceSchema) {
|
|
154
|
+
return { isEligible: false, reason: 'cross-schema' };
|
|
155
|
+
}
|
|
156
|
+
if (!generatedTables.has(constraint.targetTable)) {
|
|
157
|
+
return { isEligible: false, reason: 'excluded-target' };
|
|
158
|
+
}
|
|
159
|
+
return { isEligible: true };
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* Copy single-column foreign key constraints onto the matching column metadata.
|
|
163
|
+
* A constraint is copied only when it targets a single column, the target table is
|
|
164
|
+
* among the generated tables and the target schema matches the source table schema.
|
|
165
|
+
* Composite, cross-schema and excluded-target constraints stay only in
|
|
166
|
+
* tableMetadata.foreignKeys. Returns a new table metadata without mutating the input.
|
|
167
|
+
* @param {ITableMetadata} tableMetadata
|
|
168
|
+
* @param {ReadonlySet<string>} generatedTables
|
|
169
|
+
* @returns {ITableMetadata}
|
|
170
|
+
*/
|
|
171
|
+
export const applyForeignKeyConstraintsToColumns = (tableMetadata, generatedTables) => {
|
|
172
|
+
const constraints = tableMetadata.foreignKeys ?? [];
|
|
173
|
+
const columns = { ...tableMetadata.columns };
|
|
174
|
+
for (const constraint of constraints) {
|
|
175
|
+
const classification = classifyForeignKeyConstraint(constraint, tableMetadata.schema, generatedTables);
|
|
176
|
+
if (!classification.isEligible) {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const [sourceColumn] = constraint.sourceColumns;
|
|
180
|
+
const [targetColumn] = constraint.targetColumns;
|
|
181
|
+
const entry = Object.entries(columns).find(([, column]) => column.originName === sourceColumn);
|
|
182
|
+
if (!entry) {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const [columnName, columnMetadata] = entry;
|
|
186
|
+
const foreignKey = {
|
|
187
|
+
name: columnMetadata.name,
|
|
188
|
+
targetModel: constraint.targetTable,
|
|
189
|
+
targetKey: targetColumn,
|
|
190
|
+
constraintName: constraint.constraintName,
|
|
191
|
+
onDelete: constraint.onDelete,
|
|
192
|
+
onUpdate: constraint.onUpdate,
|
|
193
|
+
isUnique: constraint.isSourceColumnUnique,
|
|
194
|
+
};
|
|
195
|
+
columns[columnName] = { ...columnMetadata, foreignKey };
|
|
196
|
+
}
|
|
197
|
+
return { ...tableMetadata, columns };
|
|
198
|
+
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { DialectMySQL } from './DialectMySQL';
|
|
2
|
-
export { DialectPostgres } from './DialectPostgres';
|
|
3
|
-
export { DialectMSSQL } from './DialectMSSQL';
|
|
4
|
-
export { DialectMariaDB } from './DialectMariaDB';
|
|
5
|
-
export { DialectSQLite } from './DialectSQLite';
|
|
1
|
+
export { DialectMySQL } from './DialectMySQL.js';
|
|
2
|
+
export { DialectPostgres } from './DialectPostgres.js';
|
|
3
|
+
export { DialectMSSQL } from './DialectMSSQL.js';
|
|
4
|
+
export { DialectMariaDB } from './DialectMariaDB.js';
|
|
5
|
+
export { DialectSQLite } from './DialectSQLite.js';
|
package/build/dialects/index.js
CHANGED
|
@@ -1,13 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
var DialectPostgres_1 = require("./DialectPostgres");
|
|
7
|
-
Object.defineProperty(exports, "DialectPostgres", { enumerable: true, get: function () { return DialectPostgres_1.DialectPostgres; } });
|
|
8
|
-
var DialectMSSQL_1 = require("./DialectMSSQL");
|
|
9
|
-
Object.defineProperty(exports, "DialectMSSQL", { enumerable: true, get: function () { return DialectMSSQL_1.DialectMSSQL; } });
|
|
10
|
-
var DialectMariaDB_1 = require("./DialectMariaDB");
|
|
11
|
-
Object.defineProperty(exports, "DialectMariaDB", { enumerable: true, get: function () { return DialectMariaDB_1.DialectMariaDB; } });
|
|
12
|
-
var DialectSQLite_1 = require("./DialectSQLite");
|
|
13
|
-
Object.defineProperty(exports, "DialectSQLite", { enumerable: true, get: function () { return DialectSQLite_1.DialectSQLite; } });
|
|
1
|
+
export { DialectMySQL } from './DialectMySQL.js';
|
|
2
|
+
export { DialectPostgres } from './DialectPostgres.js';
|
|
3
|
+
export { DialectMSSQL } from './DialectMSSQL.js';
|
|
4
|
+
export { DialectMariaDB } from './DialectMariaDB.js';
|
|
5
|
+
export { DialectSQLite } from './DialectSQLite.js';
|