Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: migrate updateQuery to typescript #17063

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 10 additions & 3 deletions packages/core/src/abstract-dialect/dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ export type DialectSupports = {
DEFAULT: boolean;
'DEFAULT VALUES': boolean;
'VALUES ()': boolean;
// TODO: rename to `update.limit`
'LIMIT ON UPDATE': boolean;
'ON DUPLICATE KEY': boolean;
'ORDER NULLS': boolean;
UNION: boolean;
Expand Down Expand Up @@ -266,6 +264,11 @@ export type DialectSupports = {
delete: {
limit: boolean;
};
update: {
ignoreDuplicates: boolean;
limit: boolean;
returning: boolean;
};
};

type TypeParser = (...params: any[]) => unknown;
Expand Down Expand Up @@ -310,7 +313,6 @@ export abstract class AbstractDialect<
DEFAULT: true,
'DEFAULT VALUES': false,
'VALUES ()': false,
'LIMIT ON UPDATE': false,
'ON DUPLICATE KEY': true,
'ORDER NULLS': false,
UNION: true,
Expand Down Expand Up @@ -490,6 +492,11 @@ export abstract class AbstractDialect<
delete: {
limit: true,
},
update: {
ignoreDuplicates: false,
limit: true,
returning: false,
},
});

protected static extendSupport(supportsOverwrite: DeepPartial<DialectSupports>): DialectSupports {
Expand Down
71 changes: 68 additions & 3 deletions packages/core/src/abstract-dialect/query-generator-internal.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import { EMPTY_ARRAY } from '@sequelize/utils';
import { inspect } from 'node:util';
import { Deferrable } from '../deferrable.js';
import type { AssociationPath } from '../expression-builders/association-path.js';
import type { Attribute } from '../expression-builders/attribute.js';
import { BaseSqlExpression } from '../expression-builders/base-sql-expression.js';
import type { Cast } from '../expression-builders/cast.js';
import type { Col } from '../expression-builders/col.js';
import { col, type Col } from '../expression-builders/col.js';
import type { DialectAwareFn } from '../expression-builders/dialect-aware-fn.js';
import type { Fn } from '../expression-builders/fn.js';
import type { JsonPath } from '../expression-builders/json-path.js';
import type { Literal } from '../expression-builders/literal.js';
import type { ModelDefinition } from '../model-definition.js';
import type { Sequelize } from '../sequelize.js';
import { extractModelDefinition } from '../utils/model-utils.js';
import { injectReplacements } from '../utils/sql.js';
import { attributeTypeToSql } from './data-types-utils.js';
import type { AbstractDialect } from './dialect.js';
import type { EscapeOptions } from './query-generator-typescript.js';
import type { AddLimitOffsetOptions } from './query-generator.internal-types.js';
import type {
AddLimitOffsetOptions,
GetReturnFieldsOptions,
} from './query-generator.internal-types.js';
import type { GetConstraintSnippetQueryOptions, TableOrModel } from './query-generator.types.js';
import { WhereSqlBuilder, wrapAmbiguousWhere } from './where-sql-builder.js';

Expand Down Expand Up @@ -344,11 +349,71 @@ Only named replacements (:name) are allowed in literal() because we cannot guara
}

/**
* Returns an SQL fragment for adding result constraints.
* Returns an SQL fragment for adding LIMIT/OFFSET to a query.
*
* @param _options
*/
addLimitAndOffset(_options: AddLimitOffsetOptions): string {
throw new Error(`addLimitAndOffset has not been implemented in ${this.dialect.name}.`);
}

normalizeReturning(
options: GetReturnFieldsOptions,
modelDefinition?: ModelDefinition | null,
): ReadonlyArray<string | BaseSqlExpression> {
if (options.returning === true) {
const returnFields: Array<string | BaseSqlExpression> = [];
if (modelDefinition) {
for (const attribute of modelDefinition.physicalAttributes.values()) {
returnFields.push(attribute.columnName);
}
}

if (returnFields.length === 0) {
returnFields.push(col('*'));
}

return returnFields;
}

if (options.returning === false || options.returning === undefined) {
return EMPTY_ARRAY;
}

if (Array.isArray(options.returning)) {
return options.returning;
}

throw new Error(
`Unsupported value in "returning" option: ${inspect(options.returning)}. This option only accepts true, false, an array of strings and sql expressions.`,
);
}

/**
* Returns the SQL fragment to handle returning the attributes from an insert/update query.
*
* @param options An object with options.
* @param modelDefinition A map with the model attributes.
*/
formatReturnFields(
options: GetReturnFieldsOptions,
modelDefinition?: ModelDefinition | null,
): string[] {
const returnFields = this.normalizeReturning(options, modelDefinition);

return returnFields.map(field => {
if (typeof field === 'string') {
return this.queryGenerator.quoteIdentifier(field);
} else if (field instanceof BaseSqlExpression) {
return this.queryGenerator.formatSqlExpression(field, {
...options,
model: modelDefinition,
});
}

throw new Error(
`Unsupported value in "returning" option: ${inspect(field)}. This option only accepts true, false, an array of strings and sql expressions.`,
);
});
}
}
153 changes: 152 additions & 1 deletion packages/core/src/abstract-dialect/query-generator-typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ import {
extractTableIdentifier,
isModelStatic,
} from '../utils/model-utils.js';
import type { BindParamOptions, DataType } from './data-types.js';
import { createBindParamGenerator } from '../utils/sql.js';
import type { BindParamOptions, DataType, NormalizedDataType } from './data-types.js';
import { AbstractDataType } from './data-types.js';
import type { AbstractDialect } from './dialect.js';
import { AbstractQueryGeneratorInternal } from './query-generator-internal.js';
Expand All @@ -50,6 +51,7 @@ import type {
ListDatabasesQueryOptions,
ListSchemasQueryOptions,
ListTablesQueryOptions,
QueryWithBindParams,
QuoteTableOptions,
RemoveColumnQueryOptions,
RemoveConstraintQueryOptions,
Expand All @@ -59,6 +61,7 @@ import type {
StartTransactionQueryOptions,
TableOrModel,
TruncateTableQueryOptions,
UpdateQueryOptions,
} from './query-generator.types.js';
import type { TableNameWithSchema } from './query-interface.js';
import type { WhereOptions } from './where-sql-builder-types.js';
Expand Down Expand Up @@ -122,6 +125,10 @@ export const TRUNCATE_TABLE_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof TruncateTa
'cascade',
'restartIdentity',
]);
export const UPDATE_QUERY_SUPPORTABLE_OPTIONS = new Set<keyof UpdateQueryOptions>([
'ignoreDuplicates',
'returning',
]);

/**
* Options accepted by {@link AbstractQueryGeneratorTypeScript#escape}
Expand Down Expand Up @@ -959,6 +966,150 @@ export class AbstractQueryGeneratorTypeScript<Dialect extends AbstractDialect =
]);
}

/**
* Returns an update query
*
* @param tableOrModel
* @param valueHash
* @param options
*/
updateQuery(
tableOrModel: TableOrModel,
valueHash: Record<string, unknown>,
options?: UpdateQueryOptions,
): QueryWithBindParams {
if (options) {
rejectInvalidOptions(
'updateQuery',
this.dialect,
UPDATE_QUERY_SUPPORTABLE_OPTIONS,
this.dialect.supports.update,
options,
);
}

if (!isPlainObject(valueHash)) {
throw new Error(`Invalid value: ${NodeUtil.inspect(valueHash)}. Expected an object.`);
}

const bind = Object.create(null);
const attributeMap = new Map<string, NormalizedDataType>();
const modelDefinition = extractModelDefinition(tableOrModel);
const updateOptions: UpdateQueryOptions = {
...options,
model: modelDefinition,
bindParam:
options?.bindParam === undefined ? createBindParamGenerator(bind) : options.bindParam,
};

if (this.sequelize.options.prependSearchPath || updateOptions.searchPath) {
// Not currently supported with search path (requires output of multiple queries)
updateOptions.bindParam = undefined;
}

if (modelDefinition && updateOptions.columnTypes) {
throw new Error(
'Using options.columnTypes in updateQuery is not allowed if a model or model definition is specified.',
);
} else if (updateOptions.columnTypes) {
for (const column of Object.keys(updateOptions.columnTypes)) {
attributeMap.set(
column,
this.sequelize.normalizeDataType(updateOptions.columnTypes[column]),
);
}
}

const updateFragment: string[] = [];
for (const column of Object.keys(valueHash)) {
const rowValue = valueHash[column];
if (rowValue === undefined) {
// Treat undefined values as non-existent
continue;
}

if (modelDefinition) {
const columnName = modelDefinition.getColumnName(column);
const attribute = modelDefinition.physicalAttributes.getOrThrow(column);
if (attribute.autoIncrement && !this.dialect.supports.autoIncrement.update) {
// Skip auto-increment fields if the dialect does not support updating them
throw new Error(
`The ${this.dialect.name} dialect does not support updating auto-increment fields.`,
);
}

updateFragment.push(
`${this.quoteIdentifier(columnName)}=${this.escape(rowValue, {
...updateOptions,
type: attribute.type,
})}`,
);
} else {
updateFragment.push(
`${this.quoteIdentifier(column)}=${this.escape(rowValue, {
...updateOptions,
type: attributeMap.get(column),
})}`,
);
}
}

if (updateFragment.length === 0) {
throw new Error('No values to update');
}

const table = this.quoteTable(tableOrModel);
const queryFragments = [
'UPDATE',
updateOptions.ignoreDuplicates ? 'IGNORE' : '',
table,
'SET',
updateFragment.join(','),
];
const whereFragment = updateOptions.where
? this.whereQuery(updateOptions.where, updateOptions)
: '';

if (updateOptions.limit && !this.dialect.supports.update.limit) {
if (!modelDefinition) {
throw new Error(
'Using options.limit in updateQuery is not allowed if no model or model definition is specified.',
);
}

const pks = join(
map(modelDefinition.primaryKeysAttributeNames, attrName => {
return this.quoteIdentifier(modelDefinition.getColumnName(attrName));
}),
', ',
);

const primaryKeys = modelDefinition.primaryKeysAttributeNames.size > 1 ? `(${pks})` : pks;

queryFragments.push(
`WHERE ${primaryKeys} IN (`,
`SELECT ${pks} FROM ${table}`,
whereFragment,
`ORDER BY ${pks}`,
this.#internals.addLimitAndOffset(updateOptions),
')',
);
} else {
queryFragments.push(whereFragment, this.#internals.addLimitAndOffset(updateOptions));
}

if (updateOptions.returning) {
queryFragments.push(
`RETURNING ${this.#internals.formatReturnFields(updateOptions, modelDefinition).join(', ')}`,
);
}

return {
query: joinSQLFragments(queryFragments),
bind: typeof updateOptions.bindParam === 'function' ? bind : undefined,
};
}

__TEST__getInternals() {
if (process.env.npm_lifecycle_event !== 'mocha') {
throw new Error('You can only access the internals of the query generator in test mode.');
Expand Down