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
8 changes: 8 additions & 0 deletions .coderabbit.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
language: 'en-US'
early_access: false
reviews:
auto_review:
enabled: true
chat:
auto_reply: true
2 changes: 1 addition & 1 deletion .github/workflows/bump-version.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ jobs:

- name: Bump version
id: bump
run: pnpm run bump-version
run: npx tsx scripts/bump-version.ts

- name: Create PR
uses: peter-evans/create-pull-request@v7
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
</picture>
</a>
<h1>ZenStack V3</h1>
<a href="https://www.npmjs.com/package/@zenstackhq/cli?activeTab=versions">
<img src="https://img.shields.io/npm/v/%40zenstackhq%2Fcli/next">
</a>
<img src="https://github.com/zenstackhq/zenstack-v3/actions/workflows/build-test.yml/badge.svg">
<a href="https://twitter.com/zenstackhq">
<img src="https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fzenstackhq%2Fzenstack">
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zenstack-v3",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "ZenStack",
"packageManager": "pnpm@10.12.1",
"scripts": {
Expand All @@ -10,7 +10,8 @@
"test": "turbo run test",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"pr": "gh pr create --fill-first --base dev",
"bump-version": "npx tsx scripts/bump-version.ts",
"merge-main": "gh pr create --title \"merge dev to main\" --body \"\" --base main --head dev",
"bump-version": "gh workflow run .github/workflows/bump-version.yml --ref dev",
"publish-all": "pnpm --filter \"./packages/**\" -r publish --access public --tag next",
"publish-preview": "pnpm --filter \"./packages/**\" -r publish --tag next --force --registry https://preview.registry.zenstack.dev/",
"unpublish-preview": "pnpm --filter \"./packages/**\" -r --shell-mode exec -- npm unpublish -f --registry https://preview.registry.zenstack.dev/ \"\\$PNPM_PACKAGE_NAME\""
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"publisher": "zenstack",
"displayName": "ZenStack CLI",
"description": "FullStack database toolkit with built-in access control and automatic API generation.",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"type": "module",
"author": {
"name": "ZenStack Team"
Expand Down
2 changes: 1 addition & 1 deletion packages/common-helpers/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/common-helpers",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "ZenStack Common Helpers",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/create-zenstack/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-zenstack",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "Create a new ZenStack project",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-config/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/eslint-config",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"type": "module",
"private": true,
"license": "MIT"
Expand Down
2 changes: 1 addition & 1 deletion packages/ide/vscode/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "zenstack",
"publisher": "zenstack",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"displayName": "ZenStack Language Tools",
"description": "VSCode extension for ZenStack ZModel language",
"private": true,
Expand Down
2 changes: 1 addition & 1 deletion packages/language/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/language",
"description": "ZenStack ZModel language specification",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"license": "MIT",
"author": "ZenStack Team",
"files": [
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/runtime",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "ZenStack Runtime",
"type": "module",
"scripts": {
Expand Down
37 changes: 37 additions & 0 deletions packages/runtime/src/client/client-impl.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { lowerCaseFirst } from '@zenstackhq/common-helpers';
import type { SqliteDialectConfig } from 'kysely';
import {
CompiledQuery,
DefaultConnectionProvider,
DefaultQueryExecutor,
Kysely,
Log,
PostgresDialect,
sql,
SqliteDialect,
type KyselyProps,
type PostgresDialectConfig,
Expand Down Expand Up @@ -209,6 +211,41 @@ export class ClientImpl<Schema extends SchemaDef> {
get $auth() {
return this.auth;
}

$executeRaw(query: TemplateStringsArray, ...values: any[]) {
return createDeferredPromise(async () => {
const result = await sql(query, ...values).execute(this.kysely);
return Number(result.numAffectedRows ?? 0);
});
}

$executeRawUnsafe(query: string, ...values: any[]) {
return createDeferredPromise(async () => {
const compiledQuery = this.createRawCompiledQuery(query, values);
const result = await this.kysely.executeQuery(compiledQuery);
return Number(result.numAffectedRows ?? 0);
});
}

$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]) {
return createDeferredPromise(async () => {
const result = await sql(query, ...values).execute(this.kysely);
return result.rows as T;
});
}

$queryRawUnsafe<T = unknown>(query: string, ...values: any[]) {
return createDeferredPromise(async () => {
const compiledQuery = this.createRawCompiledQuery(query, values);
const result = await this.kysely.executeQuery(compiledQuery);
return result.rows as T;
});
}

private createRawCompiledQuery(query: string, values: any[]) {
const q = CompiledQuery.raw(query, values);
return { ...q, $raw: true } as CompiledQuery;
}
}

function createClientProxy<Schema extends SchemaDef>(client: ClientImpl<Schema>): ClientImpl<Schema> {
Expand Down
38 changes: 38 additions & 0 deletions packages/runtime/src/client/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,44 @@ export type ClientContract<Schema extends SchemaDef> = {
*/
readonly $options: ClientOptions<Schema>;

/**
* Executes a prepared raw query and returns the number of affected rows.
* @example
* ```
* const result = await client.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`
* ```
*/
$executeRaw(query: TemplateStringsArray, ...values: any[]): Promise<number>;

/**
* Executes a raw query and returns the number of affected rows.
* This method is susceptible to SQL injections.
* @example
* ```
* const result = await client.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
* ```
*/
$executeRawUnsafe(query: string, ...values: any[]): Promise<number>;

/**
* Performs a prepared raw query and returns the `SELECT` data.
* @example
* ```
* const result = await client.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`
* ```
*/
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): Promise<T>;

/**
* Performs a raw query and returns the `SELECT` data.
* This method is susceptible to SQL injections.
* @example
* ```
* const result = await client.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
* ```
*/
$queryRawUnsafe<T = unknown>(query: string, ...values: any[]): Promise<T>;

/**
* The current user identity.
*/
Expand Down
19 changes: 14 additions & 5 deletions packages/runtime/src/client/executor/zenstack-query-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ export class ZenStackQueryExecutor<Schema extends SchemaDef> extends DefaultQuer
}

// proceed with the query with kysely interceptors
const result = await this.proceedQueryWithKyselyInterceptors(queryNode, queryId);
// if the query is a raw query, we need to carry over the parameters
const queryParams = (compiledQuery as any).$raw ? compiledQuery.parameters : undefined;
const result = await this.proceedQueryWithKyselyInterceptors(queryNode, queryParams, queryId);

// call after mutation hooks
await this.callAfterQueryInterceptionFilters(result, queryNode, mutationInterceptionInfo);
Expand All @@ -96,8 +98,12 @@ export class ZenStackQueryExecutor<Schema extends SchemaDef> extends DefaultQuer
return this.executeWithTransaction(task, !!mutationInterceptionInfo?.useTransactionForMutation);
}

private proceedQueryWithKyselyInterceptors(queryNode: RootOperationNode, queryId: QueryId) {
let proceed = (q: RootOperationNode) => this.proceedQuery(q, queryId);
private proceedQueryWithKyselyInterceptors(
queryNode: RootOperationNode,
parameters: readonly unknown[] | undefined,
queryId: QueryId,
) {
let proceed = (q: RootOperationNode) => this.proceedQuery(q, parameters, queryId);

const makeTx = (p: typeof proceed) => (callback: OnKyselyQueryTransactionCallback) => {
return this.executeWithTransaction(() => callback(p));
Expand Down Expand Up @@ -125,10 +131,13 @@ export class ZenStackQueryExecutor<Schema extends SchemaDef> extends DefaultQuer
return proceed(queryNode);
}

private async proceedQuery(query: RootOperationNode, queryId: QueryId) {
private async proceedQuery(query: RootOperationNode, parameters: readonly unknown[] | undefined, queryId: QueryId) {
// run built-in transformers
const finalQuery = this.nameMapper.transformNode(query);
const compiled = this.compileQuery(finalQuery);
let compiled = this.compileQuery(finalQuery);
if (parameters) {
compiled = { ...compiled, parameters };
}
try {
return this.driver.txConnection
? await super
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/test/client-api/client-specs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getSchema, schema } from '../test-schema';
import { makePostgresClient, makeSqliteClient } from '../utils';
import type { ClientContract } from '../../src';

export function createClientSpecs(dbName: string, logQueries = false, providers = ['sqlite', 'postgresql'] as const) {
export function createClientSpecs(dbName: string, logQueries = false, providers: string[] = ['sqlite', 'postgresql']) {
const logger = (provider: string) => (event: LogEvent) => {
if (event.level === 'query') {
console.log(`query(${provider}):`, event.query.sql, event.query.parameters);
Expand Down
79 changes: 79 additions & 0 deletions packages/runtime/test/client-api/raw-query.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { ClientContract } from '../../src/client';
import { schema } from '../test-schema';
import { createClientSpecs } from './client-specs';

const PG_DB_NAME = 'client-api-raw-query-tests';

describe.each(createClientSpecs(PG_DB_NAME, true))('Client raw query tests', ({ createClient, provider }) => {
let client: ClientContract<typeof schema>;

beforeEach(async () => {
client = await createClient();
});

afterEach(async () => {
await client?.$disconnect();
});

it('works with executeRaw', async () => {
await client.user.create({
data: {
id: '1',
email: 'u1@test.com',
},
});

await expect(
client.$executeRaw`UPDATE "User" SET "email" = ${'u2@test.com'} WHERE "id" = ${'1'}`,
).resolves.toBe(1);
await expect(client.user.findFirst()).resolves.toMatchObject({ email: 'u2@test.com' });
});

it('works with executeRawUnsafe', async () => {
await client.user.create({
data: {
id: '1',
email: 'u1@test.com',
},
});

const sql =
provider === 'postgresql'
? `UPDATE "User" SET "email" = $1 WHERE "id" = $2`
: `UPDATE "User" SET "email" = ? WHERE "id" = ?`;
await expect(client.$executeRawUnsafe(sql, 'u2@test.com', '1')).resolves.toBe(1);
await expect(client.user.findFirst()).resolves.toMatchObject({ email: 'u2@test.com' });
});

it('works with queryRaw', async () => {
await client.user.create({
data: {
id: '1',
email: 'u1@test.com',
},
});

const uid = '1';
const users = await client.$queryRaw<
{ id: string; email: string }[]
>`SELECT "User"."id", "User"."email" FROM "User" WHERE "User"."id" = ${uid}`;
expect(users).toEqual([{ id: '1', email: 'u1@test.com' }]);
});

it('works with queryRawUnsafe', async () => {
await client.user.create({
data: {
id: '1',
email: 'u1@test.com',
},
});

const sql =
provider === 'postgresql'
? `SELECT "User"."id", "User"."email" FROM "User" WHERE "User"."id" = $1`
: `SELECT "User"."id", "User"."email" FROM "User" WHERE "User"."id" = ?`;
const users = await client.$queryRawUnsafe<{ id: string; email: string }[]>(sql, '1');
expect(users).toEqual([{ id: '1', email: 'u1@test.com' }]);
});
});
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/sdk",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "ZenStack SDK",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/tanstack-query/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/tanstack-query",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "",
"main": "index.js",
"type": "module",
Expand Down
2 changes: 1 addition & 1 deletion packages/testtools/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/testtools",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "ZenStack Test Tools",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/testtools/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export async function generateTsSchema(
extraSourceFiles?: Record<string, string>,
) {
const workDir = createTestProject();
console.log(`Working directory: ${workDir}`);
console.log(`Work directory: ${workDir}`);

const zmodelPath = path.join(workDir, 'schema.zmodel');
const noPrelude = schemaText.includes('datasource ');
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript-config/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/typescript-config",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"private": true,
"license": "MIT"
}
2 changes: 1 addition & 1 deletion packages/zod/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/zod",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "",
"type": "module",
"main": "index.js",
Expand Down
2 changes: 1 addition & 1 deletion samples/blog/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sample-blog",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"description": "",
"main": "index.js",
"scripts": {
Expand Down
Loading