@dudousxd/nestjs-media-database-drizzle 0.9.0 → 0.11.0

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/dist/pg/index.js CHANGED
@@ -3,8 +3,29 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
3
3
 
4
4
  // src/pg/ddl.ts
5
5
  import { sql } from "drizzle-orm";
6
- var MEDIA_PG_DDL = [
7
- `CREATE TABLE IF NOT EXISTS "media" (
6
+
7
+ // src/schema-name.ts
8
+ var SCHEMA_NAME = /^[A-Za-z_][A-Za-z0-9_$]*$/;
9
+ function assertSchemaName(schema) {
10
+ if (typeof schema !== "string" || !SCHEMA_NAME.test(schema) || schema.length > 63) {
11
+ throw new TypeError(`[nestjs-media] \`schema\` must match /^[A-Za-z_][A-Za-z0-9_$]*$/ and be at most 63 characters, got ${JSON.stringify(schema)}`);
12
+ }
13
+ }
14
+ __name(assertSchemaName, "assertSchemaName");
15
+ function qualified(schema, table) {
16
+ return schema === void 0 ? `"${table}"` : `"${schema}"."${table}"`;
17
+ }
18
+ __name(qualified, "qualified");
19
+
20
+ // src/pg/ddl.ts
21
+ function mediaPgDdl(schema) {
22
+ if (schema !== void 0) assertSchemaName(schema);
23
+ const t = /* @__PURE__ */ __name((table) => qualified(schema, table), "t");
24
+ return [
25
+ ...schema !== void 0 ? [
26
+ `CREATE SCHEMA IF NOT EXISTS "${schema}"`
27
+ ] : [],
28
+ `CREATE TABLE IF NOT EXISTS ${t("media")} (
8
29
  "id" text PRIMARY KEY NOT NULL,
9
30
  "owner_type" text NOT NULL,
10
31
  "owner_id" text NOT NULL,
@@ -22,14 +43,14 @@ var MEDIA_PG_DDL = [
22
43
  "updated_at" timestamp with time zone NOT NULL,
23
44
  "tenant_id" text
24
45
  )`,
25
- `ALTER TABLE "media" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
26
- `CREATE INDEX IF NOT EXISTS "idx_media_owner" ON "media" ("owner_type", "owner_id", "collection")`,
27
- `CREATE INDEX IF NOT EXISTS "idx_media_collection" ON "media" ("collection")`,
28
- `CREATE INDEX IF NOT EXISTS "idx_media_disk" ON "media" ("disk")`,
29
- `CREATE INDEX IF NOT EXISTS "idx_media_created_at" ON "media" ("created_at")`,
30
- `CREATE INDEX IF NOT EXISTS "idx_media_collection_created_at" ON "media" ("collection", "created_at", "id")`,
31
- `CREATE INDEX IF NOT EXISTS "idx_media_tenant" ON "media" ("tenant_id", "owner_type", "owner_id", "collection")`,
32
- `CREATE TABLE IF NOT EXISTS "media_upload_sessions" (
46
+ `ALTER TABLE ${t("media")} ADD COLUMN IF NOT EXISTS "tenant_id" text`,
47
+ `CREATE INDEX IF NOT EXISTS "idx_media_owner" ON ${t("media")} ("owner_type", "owner_id", "collection")`,
48
+ `CREATE INDEX IF NOT EXISTS "idx_media_collection" ON ${t("media")} ("collection")`,
49
+ `CREATE INDEX IF NOT EXISTS "idx_media_disk" ON ${t("media")} ("disk")`,
50
+ `CREATE INDEX IF NOT EXISTS "idx_media_created_at" ON ${t("media")} ("created_at")`,
51
+ `CREATE INDEX IF NOT EXISTS "idx_media_collection_created_at" ON ${t("media")} ("collection", "created_at", "id")`,
52
+ `CREATE INDEX IF NOT EXISTS "idx_media_tenant" ON ${t("media")} ("tenant_id", "owner_type", "owner_id", "collection")`,
53
+ `CREATE TABLE IF NOT EXISTS ${t("media_upload_sessions")} (
33
54
  "id" text PRIMARY KEY NOT NULL,
34
55
  "disk" text NOT NULL,
35
56
  "key" text NOT NULL,
@@ -43,18 +64,34 @@ var MEDIA_PG_DDL = [
43
64
  "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
44
65
  "tenant_id" text
45
66
  )`,
46
- `ALTER TABLE "media_upload_sessions" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
47
- `CREATE INDEX IF NOT EXISTS "idx_media_upload_sessions_tenant" ON "media_upload_sessions" ("tenant_id")`,
48
- `CREATE TABLE IF NOT EXISTS "media_upload_parts" (
49
- "session_id" text NOT NULL REFERENCES "media_upload_sessions" ("id") ON DELETE CASCADE,
67
+ `ALTER TABLE ${t("media_upload_sessions")} ADD COLUMN IF NOT EXISTS "tenant_id" text`,
68
+ `CREATE INDEX IF NOT EXISTS "idx_media_upload_sessions_tenant" ON ${t("media_upload_sessions")} ("tenant_id")`,
69
+ `CREATE TABLE IF NOT EXISTS ${t("media_upload_parts")} (
70
+ "session_id" text NOT NULL REFERENCES ${t("media_upload_sessions")} ("id") ON DELETE CASCADE,
50
71
  "part_number" integer NOT NULL,
51
72
  "etag" text NOT NULL,
52
73
  PRIMARY KEY ("session_id", "part_number")
53
74
  )`
54
- ];
55
- async function createMediaPgTables(db) {
56
- for (const statement of MEDIA_PG_DDL) {
57
- await db.execute(sql.raw(statement));
75
+ ];
76
+ }
77
+ __name(mediaPgDdl, "mediaPgDdl");
78
+ var MEDIA_PG_DDL = mediaPgDdl();
79
+ async function createMediaPgTables(db, options = {}) {
80
+ const [first, ...rest] = mediaPgDdl(options.schema);
81
+ if (options.schema !== void 0 && first !== void 0) {
82
+ try {
83
+ await db.execute(sql.raw(first));
84
+ } catch (error) {
85
+ throw Object.assign(new Error(`[nestjs-media] could not create the schema "${options.schema}". Create it yourself, or grant the role CREATE on the database: GRANT CREATE ON DATABASE <db> TO <role>. (${error.message})`), {
86
+ cause: error
87
+ });
88
+ }
89
+ }
90
+ for (const statement of options.schema !== void 0 ? rest : [
91
+ first,
92
+ ...rest
93
+ ]) {
94
+ if (statement !== void 0) await db.execute(sql.raw(statement));
58
95
  }
59
96
  }
60
97
  __name(createMediaPgTables, "createMediaPgTables");
@@ -80,10 +117,20 @@ function decodeListCursor(cursor) {
80
117
  };
81
118
  }
82
119
  __name(decodeListCursor, "decodeListCursor");
120
+ function isEncodedListCursor(cursor) {
121
+ const decoded = Buffer.from(cursor, "base64").toString("utf8");
122
+ if (Buffer.from(decoded, "utf8").toString("base64") !== cursor) return false;
123
+ const separator = decoded.indexOf("|");
124
+ if (separator === -1 || separator === decoded.length - 1) return false;
125
+ const createdAt = decoded.slice(0, separator);
126
+ const date = new Date(createdAt);
127
+ return !Number.isNaN(date.getTime()) && date.toISOString() === createdAt;
128
+ }
129
+ __name(isEncodedListCursor, "isEncodedListCursor");
83
130
 
84
131
  // src/tenancy.ts
85
132
  import { MediaTenancyUnavailableError } from "@dudousxd/nestjs-media-core";
86
- import { eq, isNull, or } from "drizzle-orm";
133
+ import { eq, isNull, or, sql as sql2 } from "drizzle-orm";
87
134
  function tenantCondition(column, match) {
88
135
  if (match.id === null) return isNull(column);
89
136
  return match.orNull ? or(eq(column, match.id), isNull(column)) : eq(column, match.id);
@@ -105,9 +152,17 @@ async function assertTenantColumn(table, probe, fix) {
105
152
  }
106
153
  }
107
154
  __name(assertTenantColumn, "assertTenantColumn");
155
+ function nameContainsCondition(name, fileName, text3) {
156
+ const pattern = `%${text3.toLowerCase().replace(/[!%_]/g, (c) => `!${c}`)}%`;
157
+ return or(sql2`lower(${name}) like ${pattern} escape '!'`, sql2`lower(${fileName}) like ${pattern} escape '!'`);
158
+ }
159
+ __name(nameContainsCondition, "nameContainsCondition");
160
+
161
+ // src/pg/schema.ts
162
+ import { index, integer as integer2, pgSchema, pgTable, primaryKey, text as text2 } from "drizzle-orm/pg-core";
108
163
 
109
164
  // src/pg/columns.ts
110
- import { bigint, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
165
+ import { bigint, integer, jsonb, text, timestamp } from "drizzle-orm/pg-core";
111
166
  function mediaPgColumns() {
112
167
  return {
113
168
  id: text("id").primaryKey(),
@@ -162,44 +217,69 @@ function uploadSessionPgColumns() {
162
217
  };
163
218
  }
164
219
  __name(uploadSessionPgColumns, "uploadSessionPgColumns");
165
- var mediaPgTableWithoutTenant = pgTable("media", mediaPgColumns());
166
- var mediaUploadSessionsPgTableWithoutTenant = pgTable("media_upload_sessions", uploadSessionPgColumns());
167
220
 
168
221
  // src/pg/schema.ts
169
- import { index, integer as integer2, pgTable as pgTable2, primaryKey, text as text2 } from "drizzle-orm/pg-core";
170
- var mediaPgTable = pgTable2("media", {
171
- ...mediaPgColumns(),
172
- /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
173
- tenantId: text2("tenant_id")
174
- }, (table) => [
175
- index("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
176
- index("idx_media_collection").on(table.collection),
177
- index("idx_media_disk").on(table.disk),
178
- index("idx_media_created_at").on(table.createdAt),
179
- index("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id),
180
- index("idx_media_tenant").on(table.tenantId, table.ownerType, table.ownerId, table.collection)
181
- ]);
182
- var mediaUploadSessionsPgTable = pgTable2("media_upload_sessions", {
183
- ...uploadSessionPgColumns(),
184
- /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
185
- tenantId: text2("tenant_id")
186
- }, (table) => [
187
- index("idx_media_upload_sessions_tenant").on(table.tenantId)
188
- ]);
189
- var mediaUploadPartsPgTable = pgTable2("media_upload_parts", {
190
- sessionId: text2("session_id").notNull().references(() => mediaUploadSessionsPgTable.id, {
191
- onDelete: "cascade"
192
- }),
193
- partNumber: integer2("part_number").notNull(),
194
- etag: text2("etag").notNull()
195
- }, (table) => [
196
- primaryKey({
197
- columns: [
198
- table.sessionId,
199
- table.partNumber
200
- ]
201
- })
202
- ]);
222
+ function tableIn(schema) {
223
+ if (schema === void 0) return pgTable;
224
+ assertSchemaName(schema);
225
+ if (schema === "public") {
226
+ throw new TypeError("[nestjs-media] `schema: 'public'` is Postgres' default schema: leave `schema` unset to use it.");
227
+ }
228
+ return pgSchema(schema).table;
229
+ }
230
+ __name(tableIn, "tableIn");
231
+ function mediaPgTables(schema) {
232
+ const table = tableIn(schema);
233
+ const media = table("media", {
234
+ ...mediaPgColumns(),
235
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
236
+ tenantId: text2("tenant_id")
237
+ }, (t) => [
238
+ index("idx_media_owner").on(t.ownerType, t.ownerId, t.collection),
239
+ index("idx_media_collection").on(t.collection),
240
+ index("idx_media_disk").on(t.disk),
241
+ index("idx_media_created_at").on(t.createdAt),
242
+ index("idx_media_collection_created_at").on(t.collection, t.createdAt, t.id),
243
+ index("idx_media_tenant").on(t.tenantId, t.ownerType, t.ownerId, t.collection)
244
+ ]);
245
+ const uploadSessions = table("media_upload_sessions", {
246
+ ...uploadSessionPgColumns(),
247
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
248
+ tenantId: text2("tenant_id")
249
+ }, (t) => [
250
+ index("idx_media_upload_sessions_tenant").on(t.tenantId)
251
+ ]);
252
+ const uploadParts = table("media_upload_parts", {
253
+ sessionId: text2("session_id").notNull().references(() => uploadSessions.id, {
254
+ onDelete: "cascade"
255
+ }),
256
+ partNumber: integer2("part_number").notNull(),
257
+ etag: text2("etag").notNull()
258
+ }, (t) => [
259
+ primaryKey({
260
+ columns: [
261
+ t.sessionId,
262
+ t.partNumber
263
+ ]
264
+ })
265
+ ]);
266
+ return {
267
+ media,
268
+ uploadSessions,
269
+ uploadParts,
270
+ /**
271
+ * Internal: the tables without `tenant_id`. The stores insert through them while tenancy is
272
+ * off, because Drizzle lists every column of a table in an `INSERT`.
273
+ */
274
+ mediaWithoutTenant: table("media", mediaPgColumns()),
275
+ uploadSessionsWithoutTenant: table("media_upload_sessions", uploadSessionPgColumns())
276
+ };
277
+ }
278
+ __name(mediaPgTables, "mediaPgTables");
279
+ var unqualified = mediaPgTables();
280
+ var mediaPgTable = unqualified.media;
281
+ var mediaUploadSessionsPgTable = unqualified.uploadSessions;
282
+ var mediaUploadPartsPgTable = unqualified.uploadParts;
203
283
 
204
284
  // src/pg/drizzle-pg-media-store.ts
205
285
  function toRecord(row) {
@@ -223,12 +303,18 @@ var DrizzlePgMediaStore = class {
223
303
  }
224
304
  db;
225
305
  tenancy = false;
226
- constructor(db) {
306
+ t;
307
+ /**
308
+ * `schema`: the Postgres schema the `media` table lives in. Every statement names it
309
+ * (`search_path` is never used). Default: unqualified, the connection's current schema.
310
+ */
311
+ constructor(db, options = {}) {
227
312
  this.db = db;
313
+ this.t = mediaPgTables(options.schema);
228
314
  }
229
315
  /** The columns to read: `tenant_id` only once tenancy is on. */
230
316
  get columns() {
231
- return selectable(getTableColumns(mediaPgTable), this.tenancy);
317
+ return selectable(getTableColumns(this.t.media), this.tenancy);
232
318
  }
233
319
  /**
234
320
  * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the
@@ -236,66 +322,66 @@ var DrizzlePgMediaStore = class {
236
322
  */
237
323
  async enableTenancy() {
238
324
  await assertTenantColumn("media", () => this.db.select({
239
- tenantId: mediaPgTable.tenantId
240
- }).from(mediaPgTable).limit(1), "Generate a migration with drizzle-kit from `mediaPgTable` (it declares `tenant_id` and the `idx_media_tenant` index), or run `ALTER TABLE media ADD COLUMN tenant_id text; CREATE INDEX idx_media_tenant ON media (tenant_id, owner_type, owner_id, collection);`.");
325
+ tenantId: this.t.media.tenantId
326
+ }).from(this.t.media).limit(1), "Generate a migration with drizzle-kit from `mediaPgTable` (or the tables of `mediaPgTables(schema)`; it declares `tenant_id` and the `idx_media_tenant` index), or run `ALTER TABLE media ADD COLUMN tenant_id text; CREATE INDEX idx_media_tenant ON media (tenant_id, owner_type, owner_id, collection);`.");
241
327
  this.tenancy = true;
242
328
  }
243
329
  async save(record) {
244
330
  const row = toRow(record, this.tenancy);
245
331
  const { id: _id, ...rest } = row;
246
- await this.db.insert(this.tenancy ? mediaPgTable : mediaPgTableWithoutTenant).values(row).onConflictDoUpdate({
247
- target: mediaPgTable.id,
332
+ await this.db.insert(this.tenancy ? this.t.media : this.t.mediaWithoutTenant).values(row).onConflictDoUpdate({
333
+ target: this.t.media.id,
248
334
  set: rest
249
335
  });
250
336
  return row;
251
337
  }
252
338
  async find(id) {
253
- const rows = await this.db.select(this.columns).from(mediaPgTable).where(eq2(mediaPgTable.id, id)).limit(1);
339
+ const rows = await this.db.select(this.columns).from(this.t.media).where(eq2(this.t.media.id, id)).limit(1);
254
340
  const row = rows[0];
255
341
  return row ? toRecord(row) : null;
256
342
  }
257
343
  async listByOwner(ownerType, ownerId, collection) {
258
- const where = collection === void 0 ? and(eq2(mediaPgTable.ownerType, ownerType), eq2(mediaPgTable.ownerId, ownerId)) : and(eq2(mediaPgTable.ownerType, ownerType), eq2(mediaPgTable.ownerId, ownerId), eq2(mediaPgTable.collection, collection));
259
- const rows = await this.db.select(this.columns).from(mediaPgTable).where(where).orderBy(asc(mediaPgTable.order), asc(mediaPgTable.id));
344
+ const where = collection === void 0 ? and(eq2(this.t.media.ownerType, ownerType), eq2(this.t.media.ownerId, ownerId)) : and(eq2(this.t.media.ownerType, ownerType), eq2(this.t.media.ownerId, ownerId), eq2(this.t.media.collection, collection));
345
+ const rows = await this.db.select(this.columns).from(this.t.media).where(where).orderBy(asc(this.t.media.order), asc(this.t.media.id));
260
346
  return rows.map(toRecord);
261
347
  }
262
348
  async delete(id) {
263
- await this.db.delete(mediaPgTable).where(eq2(mediaPgTable.id, id));
349
+ await this.db.delete(this.t.media).where(eq2(this.t.media.id, id));
264
350
  }
265
351
  async nextOrder(ownerType, ownerId, collection) {
266
352
  const rows = await this.db.select({
267
- max: max(mediaPgTable.order)
268
- }).from(mediaPgTable).where(and(eq2(mediaPgTable.ownerType, ownerType), eq2(mediaPgTable.ownerId, ownerId), eq2(mediaPgTable.collection, collection)));
353
+ max: max(this.t.media.order)
354
+ }).from(this.t.media).where(and(eq2(this.t.media.ownerType, ownerType), eq2(this.t.media.ownerId, ownerId), eq2(this.t.media.collection, collection)));
269
355
  const top = rows[0]?.max;
270
356
  return top == null ? 0 : Number(top) + 1;
271
357
  }
272
358
  async count(filter = {}) {
273
359
  const conditions = [
274
360
  ...filter.ownerType !== void 0 ? [
275
- eq2(mediaPgTable.ownerType, filter.ownerType)
361
+ eq2(this.t.media.ownerType, filter.ownerType)
276
362
  ] : [],
277
363
  ...filter.collection !== void 0 ? [
278
- eq2(mediaPgTable.collection, filter.collection)
364
+ eq2(this.t.media.collection, filter.collection)
279
365
  ] : [],
280
366
  ...filter.disk !== void 0 ? [
281
- eq2(mediaPgTable.disk, filter.disk)
367
+ eq2(this.t.media.disk, filter.disk)
282
368
  ] : [],
283
369
  ...filter.tenant ? [
284
- tenantCondition(mediaPgTable.tenantId, filter.tenant)
370
+ tenantCondition(this.t.media.tenantId, filter.tenant)
285
371
  ] : []
286
372
  ];
287
373
  const rows = await this.db.select({
288
374
  value: count()
289
- }).from(mediaPgTable).where(conditions.length ? and(...conditions) : void 0);
375
+ }).from(this.t.media).where(conditions.length ? and(...conditions) : void 0);
290
376
  return Number(rows[0]?.value ?? 0);
291
377
  }
292
378
  async aggregate(query) {
293
- const column = query.groupBy === "collection" ? mediaPgTable.collection : mediaPgTable.disk;
379
+ const column = query.groupBy === "collection" ? this.t.media.collection : this.t.media.disk;
294
380
  const rows = await this.db.select({
295
381
  key: column,
296
382
  count: count(),
297
- sumSize: sum(mediaPgTable.size)
298
- }).from(mediaPgTable).where(query.tenant ? tenantCondition(mediaPgTable.tenantId, query.tenant) : void 0).groupBy(column);
383
+ sumSize: sum(this.t.media.size)
384
+ }).from(this.t.media).where(query.tenant ? tenantCondition(this.t.media.tenantId, query.tenant) : void 0).groupBy(column);
299
385
  return rows.map((row) => ({
300
386
  key: row.key,
301
387
  count: Number(row.count),
@@ -303,27 +389,34 @@ var DrizzlePgMediaStore = class {
303
389
  sumSize: query.sum === "size" ? Number(row.sumSize ?? 0) : 0
304
390
  }));
305
391
  }
392
+ /** {@inheritDoc MediaStore.isListCursor} */
393
+ isListCursor(cursor) {
394
+ return isEncodedListCursor(cursor);
395
+ }
306
396
  async list(filter = {}, page = {}) {
307
397
  const limit = page.limit ?? 50;
308
398
  const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
309
399
  const filterConditions = [
310
400
  ...filter.ownerType !== void 0 ? [
311
- eq2(mediaPgTable.ownerType, filter.ownerType)
401
+ eq2(this.t.media.ownerType, filter.ownerType)
312
402
  ] : [],
313
403
  ...filter.collection !== void 0 ? [
314
- eq2(mediaPgTable.collection, filter.collection)
404
+ eq2(this.t.media.collection, filter.collection)
315
405
  ] : [],
316
406
  ...filter.disk !== void 0 ? [
317
- eq2(mediaPgTable.disk, filter.disk)
407
+ eq2(this.t.media.disk, filter.disk)
408
+ ] : [],
409
+ ...filter.nameContains !== void 0 ? [
410
+ nameContainsCondition(this.t.media.name, this.t.media.fileName, filter.nameContains)
318
411
  ] : [],
319
412
  ...filter.tenant ? [
320
- tenantCondition(mediaPgTable.tenantId, filter.tenant)
413
+ tenantCondition(this.t.media.tenantId, filter.tenant)
321
414
  ] : [],
322
415
  ...cursor ? [
323
- or2(gt(mediaPgTable.createdAt, cursor.createdAt), and(eq2(mediaPgTable.createdAt, cursor.createdAt), gt(mediaPgTable.id, cursor.id)))
416
+ or2(gt(this.t.media.createdAt, cursor.createdAt), and(eq2(this.t.media.createdAt, cursor.createdAt), gt(this.t.media.id, cursor.id)))
324
417
  ] : []
325
418
  ];
326
- const rows = await this.db.select(this.columns).from(mediaPgTable).where(filterConditions.length ? and(...filterConditions) : void 0).orderBy(asc(mediaPgTable.createdAt), asc(mediaPgTable.id)).limit(limit + 1);
419
+ const rows = await this.db.select(this.columns).from(this.t.media).where(filterConditions.length ? and(...filterConditions) : void 0).orderBy(asc(this.t.media.createdAt), asc(this.t.media.id)).limit(limit + 1);
327
420
  const hasMore = rows.length > limit;
328
421
  const records = rows.slice(0, limit).map(toRecord);
329
422
  const result = {
@@ -338,7 +431,7 @@ var DrizzlePgMediaStore = class {
338
431
  };
339
432
 
340
433
  // src/pg/drizzle-pg-upload-session-store.ts
341
- import { and as and2, asc as asc2, eq as eq3, getTableColumns as getTableColumns2, like, sql as sql2 } from "drizzle-orm";
434
+ import { and as and2, asc as asc2, eq as eq3, getTableColumns as getTableColumns2, like, sql as sql3 } from "drizzle-orm";
342
435
  function escapeLike(value) {
343
436
  return value.replace(/[\\%_]/g, (char) => `\\${char}`);
344
437
  }
@@ -382,16 +475,22 @@ var DrizzlePgUploadSessionStore = class {
382
475
  }
383
476
  db;
384
477
  tenancy = false;
385
- constructor(db) {
478
+ t;
479
+ /**
480
+ * `schema`: the Postgres schema of `media_upload_sessions` / `media_upload_parts`. Every
481
+ * statement names it (`search_path` is never used). Default: unqualified.
482
+ */
483
+ constructor(db, options = {}) {
386
484
  this.db = db;
485
+ this.t = mediaPgTables(options.schema);
387
486
  }
388
487
  /** Off: the table without `tenant_id`, which Drizzle would otherwise list in an INSERT. */
389
488
  get sessionsTable() {
390
- return this.tenancy ? mediaUploadSessionsPgTable : mediaUploadSessionsPgTableWithoutTenant;
489
+ return this.tenancy ? this.t.uploadSessions : this.t.uploadSessionsWithoutTenant;
391
490
  }
392
491
  /** The columns to read: `tenant_id` only once tenancy is on. */
393
492
  get columns() {
394
- return selectable(getTableColumns2(mediaUploadSessionsPgTable), this.tenancy);
493
+ return selectable(getTableColumns2(this.t.uploadSessions), this.tenancy);
395
494
  }
396
495
  /**
397
496
  * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the upload
@@ -399,8 +498,8 @@ var DrizzlePgUploadSessionStore = class {
399
498
  */
400
499
  async enableTenancy() {
401
500
  await assertTenantColumn("media_upload_sessions", () => this.db.select({
402
- tenantId: mediaUploadSessionsPgTable.tenantId
403
- }).from(mediaUploadSessionsPgTable).limit(1), "Generate a migration with drizzle-kit from `mediaUploadSessionsPgTable` (it declares `tenant_id` and its index), or run `ALTER TABLE media_upload_sessions ADD COLUMN tenant_id text; CREATE INDEX idx_media_upload_sessions_tenant ON media_upload_sessions (tenant_id);`.");
501
+ tenantId: this.t.uploadSessions.tenantId
502
+ }).from(this.t.uploadSessions).limit(1), "Generate a migration with drizzle-kit from `mediaUploadSessionsPgTable` (or the tables of `mediaPgTables(schema)`; it declares `tenant_id` and its index), or run `ALTER TABLE media_upload_sessions ADD COLUMN tenant_id text; CREATE INDEX idx_media_upload_sessions_tenant ON media_upload_sessions (tenant_id);`.");
404
503
  this.tenancy = true;
405
504
  }
406
505
  /** The session as persisted: off, no `tenantId`; on, `tenantId` or `null`. */
@@ -425,7 +524,7 @@ var DrizzlePgUploadSessionStore = class {
425
524
  };
426
525
  }
427
526
  async get(id) {
428
- const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(eq3(mediaUploadSessionsPgTable.id, id)).limit(1);
527
+ const rows = await this.db.select(this.columns).from(this.t.uploadSessions).where(eq3(this.t.uploadSessions.id, id)).limit(1);
429
528
  const row = rows[0];
430
529
  return row ? toSession(row) : null;
431
530
  }
@@ -441,34 +540,34 @@ var DrizzlePgUploadSessionStore = class {
441
540
  id: session.id,
442
541
  ...columns
443
542
  }).onConflictDoUpdate({
444
- target: mediaUploadSessionsPgTable.id,
543
+ target: this.t.uploadSessions.id,
445
544
  set: columns
446
545
  });
447
546
  return this.persisted(session);
448
547
  }
449
548
  async delete(id) {
450
- await this.db.delete(mediaUploadSessionsPgTable).where(eq3(mediaUploadSessionsPgTable.id, id));
549
+ await this.db.delete(this.t.uploadSessions).where(eq3(this.t.uploadSessions.id, id));
451
550
  }
452
551
  async addPart(id, part) {
453
- await this.db.insert(mediaUploadPartsPgTable).values({
552
+ await this.db.insert(this.t.uploadParts).values({
454
553
  sessionId: id,
455
554
  partNumber: part.partNumber,
456
555
  etag: part.etag
457
556
  }).onConflictDoUpdate({
458
557
  target: [
459
- mediaUploadPartsPgTable.sessionId,
460
- mediaUploadPartsPgTable.partNumber
558
+ this.t.uploadParts.sessionId,
559
+ this.t.uploadParts.partNumber
461
560
  ],
462
561
  set: {
463
- etag: sql2`excluded.etag`
562
+ etag: sql3`excluded.etag`
464
563
  }
465
564
  });
466
565
  }
467
566
  async listParts(id) {
468
567
  const rows = await this.db.select({
469
- partNumber: mediaUploadPartsPgTable.partNumber,
470
- etag: mediaUploadPartsPgTable.etag
471
- }).from(mediaUploadPartsPgTable).where(eq3(mediaUploadPartsPgTable.sessionId, id)).orderBy(asc2(mediaUploadPartsPgTable.partNumber));
568
+ partNumber: this.t.uploadParts.partNumber,
569
+ etag: this.t.uploadParts.etag
570
+ }).from(this.t.uploadParts).where(eq3(this.t.uploadParts.sessionId, id)).orderBy(asc2(this.t.uploadParts.partNumber));
472
571
  return rows.map((row) => ({
473
572
  partNumber: Number(row.partNumber),
474
573
  etag: row.etag
@@ -477,16 +576,16 @@ var DrizzlePgUploadSessionStore = class {
477
576
  async list(filter = {}) {
478
577
  const conditions = [
479
578
  ...filter.disk !== void 0 ? [
480
- eq3(mediaUploadSessionsPgTable.disk, filter.disk)
579
+ eq3(this.t.uploadSessions.disk, filter.disk)
481
580
  ] : [],
482
581
  ...filter.keyPrefix !== void 0 ? [
483
- like(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
582
+ like(this.t.uploadSessions.key, `${escapeLike(filter.keyPrefix)}%`)
484
583
  ] : [],
485
584
  ...filter.tenant ? [
486
- tenantCondition(mediaUploadSessionsPgTable.tenantId, filter.tenant)
585
+ tenantCondition(this.t.uploadSessions.tenantId, filter.tenant)
487
586
  ] : []
488
587
  ];
489
- const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(conditions.length ? and2(...conditions) : void 0).orderBy(asc2(mediaUploadSessionsPgTable.createdAt), asc2(mediaUploadSessionsPgTable.id));
588
+ const rows = await this.db.select(this.columns).from(this.t.uploadSessions).where(conditions.length ? and2(...conditions) : void 0).orderBy(asc2(this.t.uploadSessions.createdAt), asc2(this.t.uploadSessions.id));
490
589
  return rows.map(toSession);
491
590
  }
492
591
  };
@@ -495,7 +594,9 @@ export {
495
594
  DrizzlePgUploadSessionStore,
496
595
  MEDIA_PG_DDL,
497
596
  createMediaPgTables,
597
+ mediaPgDdl,
498
598
  mediaPgTable,
599
+ mediaPgTables,
499
600
  mediaUploadPartsPgTable,
500
601
  mediaUploadSessionsPgTable
501
602
  };