Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
34 changes: 31 additions & 3 deletions packages/orm/src/client/crud/dialects/base-dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,22 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> {

// #endregion

// #region type mapping

/**
* Maps a ZModel type to the corresponding SQL type for this dialect.
*/
protected abstract getSqlType(zmodelType: string): string | undefined;

/**
* Checks if a field has a native database type attribute (e.g., `@db.Uuid`).
*/
protected hasNativeTypeAttribute(fieldDef: FieldDef): boolean {
return !!fieldDef.attributes?.some((a) => a.name.startsWith('@db.'));
}

// #endregion

// #region value transformation

/**
Expand Down Expand Up @@ -1134,7 +1150,7 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> {
const descendants = getDelegateDescendantModels(this.schema, model);
for (const subModel of descendants) {
result = this.buildDelegateJoin(model, modelAlias, subModel.name, result);
result = result.select((eb) => {
result = result.select(() => {
const jsonObject: Record<string, Expression<any>> = {};
for (const field of Object.keys(subModel.fields)) {
if (
Expand All @@ -1143,7 +1159,7 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> {
) {
continue;
}
jsonObject[field] = eb.ref(`${subModel.name}.${field}`);
jsonObject[field] = this.fieldRef(subModel.name, field, subModel.name);
}
return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
});
Expand Down Expand Up @@ -1344,7 +1360,19 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> {

if (!fieldDef.computed) {
// regular field
return this.eb.ref(modelAlias ? `${modelAlias}.${field}` : field);
const ref = modelAlias ? `${modelAlias}.${field}` : field;

// if the field has a native database type annotation (e.g., @db.Uuid), cast it
// back to the base SQL type to avoid type mismatch in comparisons
if (this.hasNativeTypeAttribute(fieldDef)) {
const sqlType = this.getSqlType(fieldDef.type);
if (sqlType) {
const castType = fieldDef.array ? sql`${sql.raw(sqlType)}[]` : sql.raw(sqlType);
return sql`CAST(${sql.ref(ref)} AS ${castType})`;
}
}

return this.eb.ref(ref);
} else {
// computed field
if (!inlineComputedField) {
Expand Down
19 changes: 18 additions & 1 deletion packages/orm/src/client/crud/dialects/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type { BuiltinType, FieldDef, SchemaDef } from '../../../schema';
import type { SortOrder } from '../../crud-types';
import { createInvalidInputError, createNotSupportedError } from '../../errors';
import type { ClientOptions } from '../../options';
import { isTypeDef } from '../../query-utils';
import { isEnum, isTypeDef } from '../../query-utils';
import { LateralJoinDialectBase } from './lateral-join-dialect-base';

export class MySqlCrudDialect<Schema extends SchemaDef> extends LateralJoinDialectBase<Schema> {
Expand Down Expand Up @@ -318,6 +318,23 @@ export class MySqlCrudDialect<Schema extends SchemaDef> extends LateralJoinDiale
);
}

protected override getSqlType(zmodelType: string) {
if (isEnum(this.schema, zmodelType)) {
return 'varchar(191)';
}
return match(zmodelType)
.with('String', () => 'char')
.with('Boolean', () => 'unsigned')
.with('Int', () => 'signed')
.with('BigInt', () => 'signed')
.with('Float', () => 'double')
.with('Decimal', () => 'decimal(65,30)')
.with('DateTime', () => 'datetime(3)')
.with('Bytes', () => 'binary')
.with('Json', () => 'json')
.otherwise(() => undefined);
}

override getStringCasingBehavior() {
// MySQL LIKE is case-insensitive by default (depends on collation), no ILIKE support
return { supportsILike: false, likeCaseSensitive: false };
Expand Down
43 changes: 24 additions & 19 deletions packages/orm/src/client/crud/dialects/postgresql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,11 @@ export class PostgresCrudDialect<Schema extends SchemaDef> extends LateralJoinDi
override buildArrayValue(values: Expression<unknown>[], elemType: string): AliasableExpression<unknown> {
const arr = sql`ARRAY[${sql.join(values, sql.raw(','))}]`;
const mappedType = this.getSqlType(elemType);
return this.eb.cast(arr, sql`${sql.raw(mappedType)}[]`);
if (mappedType) {
return this.eb.cast(arr, sql`${sql.raw(mappedType)}[]`);
} else {
return arr;
}
}

override buildArrayContains(
Expand All @@ -293,7 +297,7 @@ export class PostgresCrudDialect<Schema extends SchemaDef> extends LateralJoinDi
const arrayExpr = sql`ARRAY[${value}]`;
if (elemType) {
const mappedType = this.getSqlType(elemType);
const typedArray = this.eb.cast(arrayExpr, sql`${sql.raw(mappedType)}[]`);
const typedArray = mappedType ? this.eb.cast(arrayExpr, sql`${sql.raw(mappedType)}[]`) : arrayExpr;
return this.eb(field, '@>', typedArray);
} else {
return this.eb(field, '@>', arrayExpr);
Expand Down Expand Up @@ -357,25 +361,22 @@ export class PostgresCrudDialect<Schema extends SchemaDef> extends LateralJoinDi
);
}

private getSqlType(zmodelType: string) {
protected override getSqlType(zmodelType: string) {
if (isEnum(this.schema, zmodelType)) {
// reduce enum to text for type compatibility
return 'text';
} else {
return (
match(zmodelType)
.with('String', () => 'text')
.with('Boolean', () => 'boolean')
.with('Int', () => 'integer')
.with('BigInt', () => 'bigint')
.with('Float', () => 'double precision')
.with('Decimal', () => 'decimal')
.with('DateTime', () => 'timestamp')
.with('Bytes', () => 'bytea')
.with('Json', () => 'jsonb')
// fallback to text
.otherwise(() => 'text')
);
return match(zmodelType)
.with('String', () => 'text')
.with('Boolean', () => 'boolean')
.with('Int', () => 'integer')
.with('BigInt', () => 'bigint')
.with('Float', () => 'double precision')
.with('Decimal', () => 'decimal(65,30)')
.with('DateTime', () => 'timestamp(3)')
.with('Bytes', () => 'bytea')
.with('Json', () => 'jsonb')
.otherwise(() => undefined);
}
}

Expand Down Expand Up @@ -414,8 +415,12 @@ export class PostgresCrudDialect<Schema extends SchemaDef> extends LateralJoinDi
.select(
fields.map((f, i) => {
const mappedType = this.getSqlType(f.type);
const castType = f.array ? sql`${sql.raw(mappedType)}[]` : sql.raw(mappedType);
return this.eb.cast(sql.ref(`$values.column${i + 1}`), castType).as(f.name);
if (mappedType) {
const castType = f.array ? sql`${sql.raw(mappedType)}[]` : sql.raw(mappedType);
return this.eb.cast(sql.ref(`$values.column${i + 1}`), castType).as(f.name);
} else {
return sql.ref(`$values.column${i + 1}`).as(f.name);
}
}),
);
}
Expand Down
18 changes: 18 additions & 0 deletions packages/orm/src/client/crud/dialects/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
getDelegateDescendantModels,
getManyToManyRelation,
getRelationForeignKeyFieldPairs,
isEnum,
requireField,
requireIdFields,
requireModel,
Expand Down Expand Up @@ -488,6 +489,23 @@ export class SqliteCrudDialect<Schema extends SchemaDef> extends BaseCrudDialect
return this.eb.fn('trim', [expression, sql.lit('"')]) as unknown as T;
}

protected override getSqlType(zmodelType: string) {
if (isEnum(this.schema, zmodelType)) {
return 'text';
}
return match(zmodelType)
.with('String', () => 'text')
.with('Boolean', () => 'integer')
.with('Int', () => 'integer')
.with('BigInt', () => 'integer')
.with('Float', () => 'real')
.with('Decimal', () => 'decimal')
.with('DateTime', () => 'numeric')
.with('Bytes', () => 'blob')
.with('Json', () => 'jsonb')
.otherwise(() => undefined);
}

override getStringCasingBehavior() {
// SQLite `LIKE` is case-insensitive, and there is no `ILIKE`
return { supportsILike: false, likeCaseSensitive: false };
Expand Down
6 changes: 4 additions & 2 deletions packages/plugins/policy/src/expression-transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@ export class ExpressionTransformer<Schema extends SchemaDef> {

const fieldDef = QueryUtils.requireField(this.schema, context.modelOrType, column);
if (!fieldDef.originModel || fieldDef.originModel === context.modelOrType) {
return ReferenceNode.create(ColumnNode.create(column), TableNode.create(tableName));
return this.dialect.fieldRef(context.modelOrType, column, tableName, false).toOperationNode();
}

return this.buildDelegateBaseFieldSelect(context.modelOrType, tableName, column, fieldDef.originModel);
Expand Down Expand Up @@ -936,7 +936,9 @@ export class ExpressionTransformer<Schema extends SchemaDef> {
kind: 'SelectQueryNode',
from: FromNode.create([TableNode.create(baseModel)]),
selections: [
SelectionNode.create(ReferenceNode.create(ColumnNode.create(field), TableNode.create(baseModel))),
SelectionNode.create(
this.dialect.fieldRef(baseModel, field, baseModel, false).toOperationNode()
),
],
where: WhereNode.create(
conjunction(
Expand Down
13 changes: 12 additions & 1 deletion packages/plugins/policy/src/policy-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,18 @@ export class PolicyHandler<Schema extends SchemaDef> extends OperationNodeTransf
() => new ExpressionWrapper(beforeUpdateTable!).as('$before'),
(join) => {
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
return idFields.reduce((acc, f) => acc.onRef(`${model}.${f}`, '=', `$before.${f}`), join);
const eb = expressionBuilder<any, any>();
return idFields.reduce(
(acc, f) =>
acc.on(() =>
eb(
this.dialect.fieldRef(model, f, model, false),
'=',
this.dialect.fieldRef(model, f, '$before', false),
),
),
join,
);
},
),
);
Expand Down
10 changes: 7 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions tests/regression/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,18 @@
},
"dependencies": {
"@zenstackhq/testtools": "workspace:*",
"decimal.js": "catalog:"
"decimal.js": "catalog:",
"uuid": "^11.0.5"
},
"devDependencies": {
"@types/node": "catalog:",
"@zenstackhq/cli": "workspace:*",
"@zenstackhq/language": "workspace:*",
"@zenstackhq/schema": "workspace:*",
"@zenstackhq/orm": "workspace:*",
"@zenstackhq/sdk": "workspace:*",
"@zenstackhq/plugin-policy": "workspace:*",
"@zenstackhq/schema": "workspace:*",
"@zenstackhq/sdk": "workspace:*",
"@zenstackhq/typescript-config": "workspace:*",
"@zenstackhq/vitest-config": "workspace:*",
"@types/node": "catalog:"
"@zenstackhq/vitest-config": "workspace:*"
}
}
44 changes: 44 additions & 0 deletions tests/regression/test/issue-2394.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { createPolicyTestClient } from '@zenstackhq/testtools';
import { v4 as uuid } from 'uuid';
import { describe, expect, it } from 'vitest';

describe('Regression for issue #2394', () => {
const UUID_SCHEMA = `
model Foo {
id String @id @db.Uuid @default(dbgenerated("gen_random_uuid()"))
x String

@@allow('all', id == x)
}
`;

it('works with policies', async () => {
const db = await createPolicyTestClient(UUID_SCHEMA, {
provider: 'postgresql',
usePrismaPush: true,
});

await db.$unuseAll().foo.create({ data: { x: uuid() } });
await expect(db.foo.findMany()).toResolveTruthy();
});

it('works with post-update policies', async () => {
const db = await createPolicyTestClient(
`
model ExchangeRequest {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
status String

@@allow('all', true)
@@deny('post-update', before().status == status) // triggers buildValuesTableSelect
}
`,
{ provider: 'postgresql', usePrismaPush: true },
);

const request = await db.exchangeRequest.create({ data: { status: 'pending' } });
await expect(
db.exchangeRequest.update({ where: { id: request.id }, data: { status: 'done' } }),
).toResolveTruthy();
});
});
Loading