Skip to content

Commit

Permalink
fix(datasource-sql): improve management of literal values to avoid bu…
Browse files Browse the repository at this point in the history
…gs when introspection is stringified (#720)
  • Loading branch information
Scra3 authored Jun 8, 2023
1 parent 66a2a56 commit 615dcda
Show file tree
Hide file tree
Showing 6 changed files with 261 additions and 162 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ export default class DefaultValueParser {
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
isLiteral(expression: any, columnType: ColumnType): boolean {
return this.parse(expression, columnType)?.constructor.name === 'Literal';
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
private parseGeneric(expression: any, columnType: ColumnType): unknown {
let sanitizedExpression = expression;
Expand Down
7 changes: 5 additions & 2 deletions packages/datasource-sql/src/introspection/introspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default class Introspector {

try {
const type = await typeConverter.convert(tableName, name, description);
const defaultValue = new DefaultValueParser(dialect).parse(description.defaultValue, type);
const parser = new DefaultValueParser(dialect);

// Workaround autoincrement flag not being properly set when using postgres
const autoIncrement = Boolean(
Expand All @@ -87,7 +87,10 @@ export default class Introspector {
return {
type,
autoIncrement,
defaultValue: autoIncrement ? null : defaultValue,
defaultValue: autoIncrement ? null : parser.parse(description.defaultValue, type),
isLiteralDefaultValue: autoIncrement
? false
: parser.isLiteral(description.defaultValue, type),
name,
allowNull: description.allowNull,
primaryKey: description.primaryKey,
Expand Down
1 change: 1 addition & 0 deletions packages/datasource-sql/src/introspection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export type Table = {
name: string;
type: ColumnType;
defaultValue: unknown;
isLiteralDefaultValue: boolean;
allowNull: boolean;
autoIncrement: boolean;
primaryKey: boolean;
Expand Down
5 changes: 5 additions & 0 deletions packages/datasource-sql/src/orm-builder/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ export default class ModelBuilder {
!(hasTimestamps && (column.name === 'updatedAt' || column.name === 'createdAt')) &&
!(isParanoid && column.name === 'deletedAt');

if (column.defaultValue && column.isLiteralDefaultValue) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
column.defaultValue = Sequelize.literal((column.defaultValue as any).val);
}

// Clone object, because sequelize modifies it.
if (isExplicit)
modelAttrs[column.name] = {
Expand Down
Loading

0 comments on commit 615dcda

Please sign in to comment.