@pgxsinkit/server 0.1.27 → 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/server",
3
- "version": "0.1.27",
3
+ "version": "0.1.29",
4
4
  "bin": {
5
5
  "pgxsinkit-generate": "src/cli/generate.ts"
6
6
  },
@@ -25,11 +25,10 @@
25
25
  "build": "bun --cwd ../.. run build:public-packages"
26
26
  },
27
27
  "dependencies": {
28
- "@pgxsinkit/contracts": "^0.1.27"
28
+ "@pgxsinkit/contracts": "^0.1.28"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "drizzle-orm": "1.0.0-rc.2",
32
- "hono": "^4.12.23",
33
- "postgres": "^3.4.9"
32
+ "hono": "^4.12.23"
34
33
  }
35
34
  }
package/src/index.ts CHANGED
@@ -1,9 +1,6 @@
1
- import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
2
- import { drizzle } from "drizzle-orm/postgres-js";
3
- import { defineRelations } from "drizzle-orm/relations";
1
+ import type { PgAsyncDatabase } from "drizzle-orm/pg-core";
4
2
  import { Hono } from "hono";
5
3
  import { cors } from "hono/cors";
6
- import postgres from "postgres";
7
4
 
8
5
  import type {
9
6
  RegistryRelations,
@@ -33,12 +30,12 @@ interface BunNamespace {
33
30
  }) => BunServerHandle;
34
31
  }
35
32
 
36
- export interface CreateSyncServerOptions<TRegistry extends SyncTableRegistry> {
33
+ export interface CreateSyncServerOptions<
34
+ TRegistry extends SyncTableRegistry,
35
+ TDb extends PgAsyncDatabase<any, RegistryRelations<TRegistry>> = PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
36
+ > {
37
37
  registry: TRegistry;
38
- /** Existing Drizzle database instance. Mutually exclusive with databaseUrl. */
39
- db?: PostgresJsDatabase<RegistryRelations<TRegistry>>;
40
- /** PostgreSQL connection URL. Mutually exclusive with db. */
41
- databaseUrl?: string;
38
+ db: TDb;
42
39
  /** Existing Hono app to register routes on. If omitted, a new Hono app is created. */
43
40
  app?: Hono;
44
41
  backend?: BulkMutationBackend;
@@ -60,8 +57,11 @@ export interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {
60
57
  modes: Record<string, TRegistry[keyof TRegistry]["mode"]>;
61
58
  }
62
59
 
63
- export interface SyncServer<TRegistry extends SyncTableRegistry> {
64
- drizzle: PostgresJsDatabase<RegistryRelations<TRegistry>>;
60
+ export interface SyncServer<
61
+ TRegistry extends SyncTableRegistry,
62
+ TDb extends PgAsyncDatabase<any, RegistryRelations<TRegistry>> = PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
63
+ > {
64
+ drizzle: TDb;
65
65
  fetch: (request: Request) => Promise<Response>;
66
66
  request: (path: string, init?: RequestInit) => Promise<Response>;
67
67
  start: () => Promise<void>;
@@ -71,28 +71,12 @@ export interface SyncServer<TRegistry extends SyncTableRegistry> {
71
71
  diagnostics: () => ServerDiagnostics<TRegistry>;
72
72
  }
73
73
 
74
- export function createSyncServer<TRegistry extends SyncTableRegistry>(
75
- options: CreateSyncServerOptions<TRegistry>,
76
- ): SyncServer<TRegistry> {
74
+ export function createSyncServer<
75
+ TRegistry extends SyncTableRegistry,
76
+ TDb extends PgAsyncDatabase<any, RegistryRelations<TRegistry>> = PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
77
+ >(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {
77
78
  const ownsApp = !options.app;
78
- const ownsDb = !options.db;
79
-
80
- if (!ownsDb && !options.databaseUrl) {
81
- throw new Error("createSyncServer requires either db or databaseUrl");
82
- }
83
-
84
- let pgClient: ReturnType<typeof postgres> | undefined;
85
- let db: PostgresJsDatabase<RegistryRelations<TRegistry>>;
86
-
87
- if (options.db) {
88
- db = options.db;
89
- } else {
90
- pgClient = createPostgresClient(options.databaseUrl!);
91
- const schema = buildSchema(options.registry);
92
- const relations = defineRelations(schema) as RegistryRelations<TRegistry>;
93
- db = drizzle({ client: pgClient, relations }) as unknown as PostgresJsDatabase<RegistryRelations<TRegistry>>;
94
- }
95
-
79
+ const db = options.db;
96
80
  const app = options.app ?? new Hono();
97
81
  let bunServer: BunServerHandle | undefined;
98
82
 
@@ -203,7 +187,6 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
203
187
  bunServer?.stop();
204
188
  bunServer = undefined;
205
189
  status.isRunning = false;
206
- await pgClient?.end();
207
190
  options.onStatusChange?.(status);
208
191
  },
209
192
  status,
@@ -217,22 +200,9 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
217
200
  };
218
201
  }
219
202
 
220
- function createPostgresClient(connectionString: string) {
221
- const url = new URL(connectionString);
222
- const sslmode = url.searchParams.get("sslmode");
223
-
224
- return postgres({
225
- host: url.hostname,
226
- port: Number(url.port || "5432"),
227
- database: url.pathname.replace(/^\//, ""),
228
- user: decodeURIComponent(url.username),
229
- password: decodeURIComponent(url.password),
230
- ssl: sslmode === "disable" ? false : "prefer",
231
- max: 10,
232
- });
233
- }
234
-
235
- function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
203
+ export function buildRegistrySchema<TRegistry extends SyncTableRegistry>(
204
+ registry: TRegistry,
205
+ ): RegistryTables<TRegistry> {
236
206
  return Object.fromEntries(
237
207
  Object.entries(registry).map(([key, entry]) => [key, entry.table]),
238
208
  ) as RegistryTables<TRegistry>;
@@ -1,6 +1,5 @@
1
1
  import { getTableName, sql } from "drizzle-orm";
2
- import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
3
- import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
2
+ import { getTableConfig, type AnyPgTable, type PgAsyncDatabase } from "drizzle-orm/pg-core";
4
3
  import { getColumns } from "drizzle-orm/utils";
5
4
 
6
5
  import {
@@ -191,8 +190,18 @@ DECLARE
191
190
  v_client_timestamp_us bigint;
192
191
  _claims jsonb;
193
192
  _target_role text;
193
+ _previous_role text;
194
+ _previous_claims text;
195
+ _previous_claim_sub text;
194
196
  BEGIN
195
197
  IF p_rls_enabled THEN
198
+ -- Capture the caller's role/claims before switching into the RLS actor context, so the
199
+ -- batch does not leak that context into the rest of the caller's transaction. The HTTP
200
+ -- route RESET ROLEs after calling this function, but in-transaction callers cannot —
201
+ -- restoring here leaves every caller exactly as it was found.
202
+ _previous_role := current_setting('role', true);
203
+ _previous_claims := current_setting('request.jwt.claims', true);
204
+ _previous_claim_sub := current_setting('request.jwt.claim.sub', true);
196
205
  _claims := COALESCE(p_user_claims, '{}'::jsonb);
197
206
  _target_role := COALESCE(NULLIF(_claims ->> 'role', ''), 'authenticated');
198
207
  BEGIN
@@ -267,13 +276,24 @@ BEGIN
267
276
  );
268
277
  END IF;
269
278
  END LOOP;
279
+
280
+ IF p_rls_enabled THEN
281
+ -- Restore the caller's prior role/claims captured above, so the RLS context applied for
282
+ -- the batch does not persist into subsequent statements of the caller's transaction.
283
+ BEGIN
284
+ PERFORM set_config('role', COALESCE(NULLIF(_previous_role, ''), 'none'), true);
285
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
286
+ END;
287
+ PERFORM set_config('request.jwt.claims', COALESCE(_previous_claims, ''), true);
288
+ PERFORM set_config('request.jwt.claim.sub', COALESCE(_previous_claim_sub, ''), true);
289
+ END IF;
270
290
  END;
271
291
  $$;
272
292
  `.trim();
273
293
  }
274
294
 
275
295
  export async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(
276
- db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
296
+ db: PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
277
297
  registry: TRegistry,
278
298
  options: {
279
299
  functionSchema?: string;
@@ -288,7 +308,7 @@ type FunctionPresenceRow = {
288
308
  };
289
309
 
290
310
  export async function verifyPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(
291
- db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
311
+ db: PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
292
312
  options: {
293
313
  functionSchema?: string;
294
314
  } = {},
@@ -312,7 +332,7 @@ type AuthHelperPresenceRow = {
312
332
  };
313
333
 
314
334
  export async function verifyArtifactRlsAuthHelpers<TRegistry extends SyncTableRegistry>(
315
- db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
335
+ db: PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
316
336
  ): Promise<void> {
317
337
  const result = await db.execute<AuthHelperPresenceRow>(sql`
318
338
  SELECT
@@ -345,6 +365,6 @@ export async function executePlpgsqlBatch(
345
365
  const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
346
366
 
347
367
  await tx.execute(
348
- sql`SELECT ${sql.raw(functionName)}(${JSON.stringify(batch)}::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::jsonb)`,
368
+ sql`SELECT ${sql.raw(functionName)}(${JSON.stringify(batch)}::text::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::text::jsonb)`,
349
369
  );
350
370
  }
@@ -1,6 +1,6 @@
1
1
  import { and, eq, sql } from "drizzle-orm";
2
2
  import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
3
- import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
+ import type { PgAsyncDatabase } from "drizzle-orm/pg-core";
4
4
  import { getColumns } from "drizzle-orm/utils";
5
5
  import { createSchemaFactory } from "drizzle-orm/zod";
6
6
  import type { Context, Hono } from "hono";
@@ -26,11 +26,11 @@ const { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({
26
26
  coerce: { date: true },
27
27
  });
28
28
 
29
- type RouteReadQueryClient = Pick<PostgresJsDatabase<any>, "select">;
29
+ type RouteReadQueryClient = Pick<PgAsyncDatabase<any, any>, "select">;
30
30
 
31
31
  export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
32
32
  app: Hono,
33
- db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
33
+ db: PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
34
34
  registry: TRegistry,
35
35
  backend: BulkMutationBackend,
36
36
  operationsLogConfig: OperationsLogConfig,
@@ -567,7 +567,7 @@ async function readServerUpdatedAtUs(
567
567
  }
568
568
 
569
569
  async function installBulkStartupDdl<TRegistry extends SyncTableRegistry>(
570
- db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
570
+ db: PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
571
571
  registry: TRegistry,
572
572
  _backend: BulkMutationBackend,
573
573
  ): Promise<void> {
@@ -1,5 +1,5 @@
1
1
  import { sql } from "drizzle-orm";
2
- import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
2
+ import type { PgAsyncDatabase } from "drizzle-orm/pg-core";
3
3
 
4
4
  import type { RegistryRelations, SyncTableRegistry } from "@pgxsinkit/contracts";
5
5
 
@@ -17,7 +17,7 @@ type OperationsLogPresenceRow = {
17
17
  * in their Drizzle schema so `drizzle-kit generate`/`push` creates it.
18
18
  */
19
19
  export async function ensureOperationsLogSchema<TRegistry extends SyncTableRegistry>(
20
- db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
20
+ db: PgAsyncDatabase<any, RegistryRelations<TRegistry>>,
21
21
  config: OperationsLogConfig,
22
22
  ): Promise<boolean> {
23
23
  if (!config.enabled) {