Skip to content

Commit 506cf99

Browse files
authored
fix: assign default value to field which uses auth() in @default when generating logical schema (#1962)
1 parent 1a9cf5a commit 506cf99

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

packages/schema/src/plugins/prisma/schema-generator.ts

+26-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import {
3232
} from '@zenstackhq/language/ast';
3333
import { getIdFields } from '@zenstackhq/sdk';
3434
import { getPrismaVersion } from '@zenstackhq/sdk/prisma';
35-
import { match } from 'ts-pattern';
35+
import { match, P } from 'ts-pattern';
3636

3737
import { DELEGATE_AUX_RELATION_PREFIX, PRISMA_MINIMUM_VERSION } from '@zenstackhq/runtime';
3838
import {
@@ -869,9 +869,34 @@ export class PrismaSchemaGenerator {
869869
const docs = [...field.comments, ...this.getCustomAttributesAsComments(field)];
870870
const result = model.addField(field.name, type, attributes, docs, addToFront);
871871

872+
if (this.mode === 'logical') {
873+
if (field.attributes.some((attr) => isDefaultWithAuth(attr))) {
874+
// field has `@default` with `auth()`, turn it into a dummy default value, and the
875+
// real default value setting is handled outside Prisma
876+
this.setDummyDefault(result, field);
877+
}
878+
}
879+
872880
return result;
873881
}
874882

883+
private setDummyDefault(result: ModelField, field: DataModelField) {
884+
const dummyDefaultValue = match(field.type.type)
885+
.with('String', () => new AttributeArgValue('String', ''))
886+
.with(P.union('Int', 'BigInt', 'Float', 'Decimal'), () => new AttributeArgValue('Number', '0'))
887+
.with('Boolean', () => new AttributeArgValue('Boolean', 'false'))
888+
.with('DateTime', () => new AttributeArgValue('FunctionCall', new PrismaFunctionCall('now')))
889+
.with('Json', () => new AttributeArgValue('String', '{}'))
890+
.with('Bytes', () => new AttributeArgValue('String', ''))
891+
.otherwise(() => {
892+
throw new PluginError(name, `Unsupported field type with default value: ${field.type.type}`);
893+
});
894+
895+
result.attributes.push(
896+
new PrismaFieldAttribute('@default', [new PrismaAttributeArg(undefined, dummyDefaultValue)])
897+
);
898+
}
899+
875900
private ensureSupportingTypeDefFields(zmodel: Model) {
876901
const dsProvider = getDataSourceProvider(zmodel);
877902
if (dsProvider && !PROVIDERS_SUPPORTING_TYPEDEF_FIELDS.includes(dsProvider)) {

0 commit comments

Comments
 (0)