Skip to content
Merged
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
12 changes: 10 additions & 2 deletions packages/language/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { PLUGIN_MODULE_NAME, STD_LIB_MODULE_NAME, type ExpressionContext } from './constants';
import {
InternalAttribute,
isArrayExpr,
isBinaryExpr,
isConfigArrayExpr,
Expand Down Expand Up @@ -173,7 +174,7 @@ export function getRecursiveBases(
bases.forEach((base) => {
// avoid using .ref since this function can be called before linking
const baseDecl = decl.$container.declarations.find(
(d): d is TypeDef | DataModel => isTypeDef(d) || (isDataModel(d) && d.name === base.$refText),
(d): d is TypeDef | DataModel => (isTypeDef(d) || isDataModel(d)) && d.name === base.$refText,
);
if (baseDecl) {
if (!includeDelegate && isDelegateModel(baseDecl)) {
Expand Down Expand Up @@ -321,8 +322,15 @@ function getArray(expr: Expression | ConfigExpr | undefined) {
return isArrayExpr(expr) || isConfigArrayExpr(expr) ? expr.items : undefined;
}

export function getAttributeArg(
attr: DataModelAttribute | DataFieldAttribute | InternalAttribute,
name: string,
): Expression | undefined {
return attr.args.find((arg) => arg.$resolvedParam?.name === name)?.value;
}

export function getAttributeArgLiteral<T extends string | number | boolean>(
attr: DataModelAttribute | DataFieldAttribute,
attr: DataModelAttribute | DataFieldAttribute | InternalAttribute,
name: string,
): T | undefined {
for (const arg of attr.args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from '../generated/ast';
import {
getAllAttributes,
getAttributeArg,
getStringLiteral,
hasAttribute,
isAuthOrAuthMemberAccess,
Expand Down Expand Up @@ -291,7 +292,7 @@ export default class AttributeApplicationValidator implements AstValidator<Attri
@check('@@index')
@check('@@unique')
private _checkConstraint(attr: AttributeApplication, accept: ValidationAcceptor) {
const fields = attr.args[0]?.value;
const fields = getAttributeArg(attr, 'fields');
const attrName = attr.decl.ref?.name;
if (!fields) {
accept('error', `expects an array of field references`, {
Expand Down
8 changes: 6 additions & 2 deletions packages/sdk/src/ts-schema-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
UnaryExpr,
type Model,
} from '@zenstackhq/language/ast';
import { getAllAttributes, getAllFields, isDataFieldReference } from '@zenstackhq/language/utils';
import { getAllAttributes, getAllFields, getAttributeArg, isDataFieldReference } from '@zenstackhq/language/utils';
import fs from 'node:fs';
import path from 'node:path';
import { match } from 'ts-pattern';
Expand Down Expand Up @@ -840,7 +840,11 @@ export class TsSchemaGenerator {
const seenKeys = new Set<string>();
for (const attr of allAttributes) {
if (attr.decl.$refText === '@@id' || attr.decl.$refText === '@@unique') {
const fieldNames = this.getReferenceNames(attr.args[0]!.value);
const fieldsArg = getAttributeArg(attr, 'fields');
if (!fieldsArg) {
continue;
}
const fieldNames = this.getReferenceNames(fieldsArg);
if (!fieldNames) {
continue;
}
Expand Down
63 changes: 38 additions & 25 deletions packages/testtools/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export type CreateTestClientOptions<Schema extends SchemaDef> = Omit<ClientOptio
extraSourceFiles?: Record<string, string>;
workDir?: string;
debug?: boolean;
dbFile?: string;
};

export async function createTestClient<Schema extends SchemaDef>(
Expand All @@ -57,7 +58,6 @@ export async function createTestClient<Schema extends SchemaDef>(
let workDir = options?.workDir;
let _schema: Schema;
const provider = options?.provider ?? getTestDbProvider() ?? 'sqlite';

const dbName = options?.dbName ?? getTestDbName(provider);

const dbUrl =
Expand Down Expand Up @@ -108,35 +108,48 @@ export async function createTestClient<Schema extends SchemaDef>(
console.log(`Work directory: ${workDir}`);
}

// copy db file to workDir if specified
if (options?.dbFile) {
if (provider !== 'sqlite') {
throw new Error('dbFile option is only supported for sqlite provider');
}
fs.copyFileSync(options.dbFile, path.join(workDir, dbName));
}

const { plugins, ...rest } = options ?? {};
const _options: ClientOptions<Schema> = {
...rest,
} as ClientOptions<Schema>;

if (options?.usePrismaPush) {
invariant(typeof schema === 'string' || schemaFile, 'a schema file must be provided when using prisma db push');
if (!model) {
const r = await loadDocumentWithPlugins(path.join(workDir, 'schema.zmodel'));
if (!r.success) {
throw new Error(r.errors.join('\n'));
if (!options?.dbFile) {
if (options?.usePrismaPush) {
invariant(
typeof schema === 'string' || schemaFile,
'a schema file must be provided when using prisma db push',
);
if (!model) {
const r = await loadDocumentWithPlugins(path.join(workDir, 'schema.zmodel'));
if (!r.success) {
throw new Error(r.errors.join('\n'));
}
model = r.model;
}
const prismaSchema = new PrismaSchemaGenerator(model);
const prismaSchemaText = await prismaSchema.generate();
fs.writeFileSync(path.resolve(workDir!, 'schema.prisma'), prismaSchemaText);
execSync('npx prisma db push --schema ./schema.prisma --skip-generate --force-reset', {
cwd: workDir,
stdio: 'ignore',
});
} else {
if (provider === 'postgresql') {
invariant(dbName, 'dbName is required');
const pgClient = new PGClient(TEST_PG_CONFIG);
await pgClient.connect();
await pgClient.query(`DROP DATABASE IF EXISTS "${dbName}"`);
await pgClient.query(`CREATE DATABASE "${dbName}"`);
await pgClient.end();
}
model = r.model;
}
const prismaSchema = new PrismaSchemaGenerator(model);
const prismaSchemaText = await prismaSchema.generate();
fs.writeFileSync(path.resolve(workDir!, 'schema.prisma'), prismaSchemaText);
execSync('npx prisma db push --schema ./schema.prisma --skip-generate --force-reset', {
cwd: workDir,
stdio: 'ignore',
});
} else {
if (provider === 'postgresql') {
invariant(dbName, 'dbName is required');
const pgClient = new PGClient(TEST_PG_CONFIG);
await pgClient.connect();
await pgClient.query(`DROP DATABASE IF EXISTS "${dbName}"`);
await pgClient.query(`CREATE DATABASE "${dbName}"`);
await pgClient.end();
}
}

Expand All @@ -155,7 +168,7 @@ export async function createTestClient<Schema extends SchemaDef>(

let client = new ZenStackClient(_schema, _options);

if (!options?.usePrismaPush) {
if (!options?.usePrismaPush && !options?.dbFile) {
await client.$pushSchema();
}

Expand Down
1 change: 1 addition & 0 deletions tests/regression/test/v2-migrated/issue-2283/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
!*.db
Binary file not shown.
Loading