@dudousxd/nestjs-media-database-drizzle 0.8.0 → 0.10.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.cjs CHANGED
@@ -25,7 +25,9 @@ __export(pg_exports, {
25
25
  DrizzlePgUploadSessionStore: () => DrizzlePgUploadSessionStore,
26
26
  MEDIA_PG_DDL: () => MEDIA_PG_DDL,
27
27
  createMediaPgTables: () => createMediaPgTables,
28
+ mediaPgDdl: () => mediaPgDdl,
28
29
  mediaPgTable: () => mediaPgTable,
30
+ mediaPgTables: () => mediaPgTables,
29
31
  mediaUploadPartsPgTable: () => mediaUploadPartsPgTable,
30
32
  mediaUploadSessionsPgTable: () => mediaUploadSessionsPgTable
31
33
  });
@@ -33,8 +35,29 @@ module.exports = __toCommonJS(pg_exports);
33
35
 
34
36
  // src/pg/ddl.ts
35
37
  var import_drizzle_orm = require("drizzle-orm");
36
- var MEDIA_PG_DDL = [
37
- `CREATE TABLE IF NOT EXISTS "media" (
38
+
39
+ // src/schema-name.ts
40
+ var SCHEMA_NAME = /^[A-Za-z_][A-Za-z0-9_$]*$/;
41
+ function assertSchemaName(schema) {
42
+ if (typeof schema !== "string" || !SCHEMA_NAME.test(schema) || schema.length > 63) {
43
+ 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)}`);
44
+ }
45
+ }
46
+ __name(assertSchemaName, "assertSchemaName");
47
+ function qualified(schema, table) {
48
+ return schema === void 0 ? `"${table}"` : `"${schema}"."${table}"`;
49
+ }
50
+ __name(qualified, "qualified");
51
+
52
+ // src/pg/ddl.ts
53
+ function mediaPgDdl(schema) {
54
+ if (schema !== void 0) assertSchemaName(schema);
55
+ const t = /* @__PURE__ */ __name((table) => qualified(schema, table), "t");
56
+ return [
57
+ ...schema !== void 0 ? [
58
+ `CREATE SCHEMA IF NOT EXISTS "${schema}"`
59
+ ] : [],
60
+ `CREATE TABLE IF NOT EXISTS ${t("media")} (
38
61
  "id" text PRIMARY KEY NOT NULL,
39
62
  "owner_type" text NOT NULL,
40
63
  "owner_id" text NOT NULL,
@@ -52,14 +75,14 @@ var MEDIA_PG_DDL = [
52
75
  "updated_at" timestamp with time zone NOT NULL,
53
76
  "tenant_id" text
54
77
  )`,
55
- `ALTER TABLE "media" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
56
- `CREATE INDEX IF NOT EXISTS "idx_media_owner" ON "media" ("owner_type", "owner_id", "collection")`,
57
- `CREATE INDEX IF NOT EXISTS "idx_media_collection" ON "media" ("collection")`,
58
- `CREATE INDEX IF NOT EXISTS "idx_media_disk" ON "media" ("disk")`,
59
- `CREATE INDEX IF NOT EXISTS "idx_media_created_at" ON "media" ("created_at")`,
60
- `CREATE INDEX IF NOT EXISTS "idx_media_collection_created_at" ON "media" ("collection", "created_at", "id")`,
61
- `CREATE INDEX IF NOT EXISTS "idx_media_tenant" ON "media" ("tenant_id", "owner_type", "owner_id", "collection")`,
62
- `CREATE TABLE IF NOT EXISTS "media_upload_sessions" (
78
+ `ALTER TABLE ${t("media")} ADD COLUMN IF NOT EXISTS "tenant_id" text`,
79
+ `CREATE INDEX IF NOT EXISTS "idx_media_owner" ON ${t("media")} ("owner_type", "owner_id", "collection")`,
80
+ `CREATE INDEX IF NOT EXISTS "idx_media_collection" ON ${t("media")} ("collection")`,
81
+ `CREATE INDEX IF NOT EXISTS "idx_media_disk" ON ${t("media")} ("disk")`,
82
+ `CREATE INDEX IF NOT EXISTS "idx_media_created_at" ON ${t("media")} ("created_at")`,
83
+ `CREATE INDEX IF NOT EXISTS "idx_media_collection_created_at" ON ${t("media")} ("collection", "created_at", "id")`,
84
+ `CREATE INDEX IF NOT EXISTS "idx_media_tenant" ON ${t("media")} ("tenant_id", "owner_type", "owner_id", "collection")`,
85
+ `CREATE TABLE IF NOT EXISTS ${t("media_upload_sessions")} (
63
86
  "id" text PRIMARY KEY NOT NULL,
64
87
  "disk" text NOT NULL,
65
88
  "key" text NOT NULL,
@@ -73,18 +96,34 @@ var MEDIA_PG_DDL = [
73
96
  "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
74
97
  "tenant_id" text
75
98
  )`,
76
- `ALTER TABLE "media_upload_sessions" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
77
- `CREATE INDEX IF NOT EXISTS "idx_media_upload_sessions_tenant" ON "media_upload_sessions" ("tenant_id")`,
78
- `CREATE TABLE IF NOT EXISTS "media_upload_parts" (
79
- "session_id" text NOT NULL REFERENCES "media_upload_sessions" ("id") ON DELETE CASCADE,
99
+ `ALTER TABLE ${t("media_upload_sessions")} ADD COLUMN IF NOT EXISTS "tenant_id" text`,
100
+ `CREATE INDEX IF NOT EXISTS "idx_media_upload_sessions_tenant" ON ${t("media_upload_sessions")} ("tenant_id")`,
101
+ `CREATE TABLE IF NOT EXISTS ${t("media_upload_parts")} (
102
+ "session_id" text NOT NULL REFERENCES ${t("media_upload_sessions")} ("id") ON DELETE CASCADE,
80
103
  "part_number" integer NOT NULL,
81
104
  "etag" text NOT NULL,
82
105
  PRIMARY KEY ("session_id", "part_number")
83
106
  )`
84
- ];
85
- async function createMediaPgTables(db) {
86
- for (const statement of MEDIA_PG_DDL) {
87
- await db.execute(import_drizzle_orm.sql.raw(statement));
107
+ ];
108
+ }
109
+ __name(mediaPgDdl, "mediaPgDdl");
110
+ var MEDIA_PG_DDL = mediaPgDdl();
111
+ async function createMediaPgTables(db, options = {}) {
112
+ const [first, ...rest] = mediaPgDdl(options.schema);
113
+ if (options.schema !== void 0 && first !== void 0) {
114
+ try {
115
+ await db.execute(import_drizzle_orm.sql.raw(first));
116
+ } catch (error) {
117
+ 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})`), {
118
+ cause: error
119
+ });
120
+ }
121
+ }
122
+ for (const statement of options.schema !== void 0 ? rest : [
123
+ first,
124
+ ...rest
125
+ ]) {
126
+ if (statement !== void 0) await db.execute(import_drizzle_orm.sql.raw(statement));
88
127
  }
89
128
  }
90
129
  __name(createMediaPgTables, "createMediaPgTables");
@@ -135,6 +174,14 @@ async function assertTenantColumn(table, probe, fix) {
135
174
  }
136
175
  }
137
176
  __name(assertTenantColumn, "assertTenantColumn");
177
+ function nameContainsCondition(name, fileName, text3) {
178
+ const pattern = `%${text3.toLowerCase().replace(/[!%_]/g, (c) => `!${c}`)}%`;
179
+ return (0, import_drizzle_orm2.or)(import_drizzle_orm2.sql`lower(${name}) like ${pattern} escape '!'`, import_drizzle_orm2.sql`lower(${fileName}) like ${pattern} escape '!'`);
180
+ }
181
+ __name(nameContainsCondition, "nameContainsCondition");
182
+
183
+ // src/pg/schema.ts
184
+ var import_pg_core2 = require("drizzle-orm/pg-core");
138
185
 
139
186
  // src/pg/columns.ts
140
187
  var import_pg_core = require("drizzle-orm/pg-core");
@@ -192,44 +239,69 @@ function uploadSessionPgColumns() {
192
239
  };
193
240
  }
194
241
  __name(uploadSessionPgColumns, "uploadSessionPgColumns");
195
- var mediaPgTableWithoutTenant = (0, import_pg_core.pgTable)("media", mediaPgColumns());
196
- var mediaUploadSessionsPgTableWithoutTenant = (0, import_pg_core.pgTable)("media_upload_sessions", uploadSessionPgColumns());
197
242
 
198
243
  // src/pg/schema.ts
199
- var import_pg_core2 = require("drizzle-orm/pg-core");
200
- var mediaPgTable = (0, import_pg_core2.pgTable)("media", {
201
- ...mediaPgColumns(),
202
- /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
203
- tenantId: (0, import_pg_core2.text)("tenant_id")
204
- }, (table) => [
205
- (0, import_pg_core2.index)("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
206
- (0, import_pg_core2.index)("idx_media_collection").on(table.collection),
207
- (0, import_pg_core2.index)("idx_media_disk").on(table.disk),
208
- (0, import_pg_core2.index)("idx_media_created_at").on(table.createdAt),
209
- (0, import_pg_core2.index)("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id),
210
- (0, import_pg_core2.index)("idx_media_tenant").on(table.tenantId, table.ownerType, table.ownerId, table.collection)
211
- ]);
212
- var mediaUploadSessionsPgTable = (0, import_pg_core2.pgTable)("media_upload_sessions", {
213
- ...uploadSessionPgColumns(),
214
- /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
215
- tenantId: (0, import_pg_core2.text)("tenant_id")
216
- }, (table) => [
217
- (0, import_pg_core2.index)("idx_media_upload_sessions_tenant").on(table.tenantId)
218
- ]);
219
- var mediaUploadPartsPgTable = (0, import_pg_core2.pgTable)("media_upload_parts", {
220
- sessionId: (0, import_pg_core2.text)("session_id").notNull().references(() => mediaUploadSessionsPgTable.id, {
221
- onDelete: "cascade"
222
- }),
223
- partNumber: (0, import_pg_core2.integer)("part_number").notNull(),
224
- etag: (0, import_pg_core2.text)("etag").notNull()
225
- }, (table) => [
226
- (0, import_pg_core2.primaryKey)({
227
- columns: [
228
- table.sessionId,
229
- table.partNumber
230
- ]
231
- })
232
- ]);
244
+ function tableIn(schema) {
245
+ if (schema === void 0) return import_pg_core2.pgTable;
246
+ assertSchemaName(schema);
247
+ if (schema === "public") {
248
+ throw new TypeError("[nestjs-media] `schema: 'public'` is Postgres' default schema: leave `schema` unset to use it.");
249
+ }
250
+ return (0, import_pg_core2.pgSchema)(schema).table;
251
+ }
252
+ __name(tableIn, "tableIn");
253
+ function mediaPgTables(schema) {
254
+ const table = tableIn(schema);
255
+ const media = table("media", {
256
+ ...mediaPgColumns(),
257
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
258
+ tenantId: (0, import_pg_core2.text)("tenant_id")
259
+ }, (t) => [
260
+ (0, import_pg_core2.index)("idx_media_owner").on(t.ownerType, t.ownerId, t.collection),
261
+ (0, import_pg_core2.index)("idx_media_collection").on(t.collection),
262
+ (0, import_pg_core2.index)("idx_media_disk").on(t.disk),
263
+ (0, import_pg_core2.index)("idx_media_created_at").on(t.createdAt),
264
+ (0, import_pg_core2.index)("idx_media_collection_created_at").on(t.collection, t.createdAt, t.id),
265
+ (0, import_pg_core2.index)("idx_media_tenant").on(t.tenantId, t.ownerType, t.ownerId, t.collection)
266
+ ]);
267
+ const uploadSessions = table("media_upload_sessions", {
268
+ ...uploadSessionPgColumns(),
269
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
270
+ tenantId: (0, import_pg_core2.text)("tenant_id")
271
+ }, (t) => [
272
+ (0, import_pg_core2.index)("idx_media_upload_sessions_tenant").on(t.tenantId)
273
+ ]);
274
+ const uploadParts = table("media_upload_parts", {
275
+ sessionId: (0, import_pg_core2.text)("session_id").notNull().references(() => uploadSessions.id, {
276
+ onDelete: "cascade"
277
+ }),
278
+ partNumber: (0, import_pg_core2.integer)("part_number").notNull(),
279
+ etag: (0, import_pg_core2.text)("etag").notNull()
280
+ }, (t) => [
281
+ (0, import_pg_core2.primaryKey)({
282
+ columns: [
283
+ t.sessionId,
284
+ t.partNumber
285
+ ]
286
+ })
287
+ ]);
288
+ return {
289
+ media,
290
+ uploadSessions,
291
+ uploadParts,
292
+ /**
293
+ * Internal: the tables without `tenant_id`. The stores insert through them while tenancy is
294
+ * off, because Drizzle lists every column of a table in an `INSERT`.
295
+ */
296
+ mediaWithoutTenant: table("media", mediaPgColumns()),
297
+ uploadSessionsWithoutTenant: table("media_upload_sessions", uploadSessionPgColumns())
298
+ };
299
+ }
300
+ __name(mediaPgTables, "mediaPgTables");
301
+ var unqualified = mediaPgTables();
302
+ var mediaPgTable = unqualified.media;
303
+ var mediaUploadSessionsPgTable = unqualified.uploadSessions;
304
+ var mediaUploadPartsPgTable = unqualified.uploadParts;
233
305
 
234
306
  // src/pg/drizzle-pg-media-store.ts
235
307
  function toRecord(row) {
@@ -253,12 +325,18 @@ var DrizzlePgMediaStore = class {
253
325
  }
254
326
  db;
255
327
  tenancy = false;
256
- constructor(db) {
328
+ t;
329
+ /**
330
+ * `schema`: the Postgres schema the `media` table lives in. Every statement names it
331
+ * (`search_path` is never used). Default: unqualified, the connection's current schema.
332
+ */
333
+ constructor(db, options = {}) {
257
334
  this.db = db;
335
+ this.t = mediaPgTables(options.schema);
258
336
  }
259
337
  /** The columns to read: `tenant_id` only once tenancy is on. */
260
338
  get columns() {
261
- return selectable((0, import_drizzle_orm3.getTableColumns)(mediaPgTable), this.tenancy);
339
+ return selectable((0, import_drizzle_orm3.getTableColumns)(this.t.media), this.tenancy);
262
340
  }
263
341
  /**
264
342
  * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the
@@ -266,66 +344,66 @@ var DrizzlePgMediaStore = class {
266
344
  */
267
345
  async enableTenancy() {
268
346
  await assertTenantColumn("media", () => this.db.select({
269
- tenantId: mediaPgTable.tenantId
270
- }).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);`.");
347
+ tenantId: this.t.media.tenantId
348
+ }).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);`.");
271
349
  this.tenancy = true;
272
350
  }
273
351
  async save(record) {
274
352
  const row = toRow(record, this.tenancy);
275
353
  const { id: _id, ...rest } = row;
276
- await this.db.insert(this.tenancy ? mediaPgTable : mediaPgTableWithoutTenant).values(row).onConflictDoUpdate({
277
- target: mediaPgTable.id,
354
+ await this.db.insert(this.tenancy ? this.t.media : this.t.mediaWithoutTenant).values(row).onConflictDoUpdate({
355
+ target: this.t.media.id,
278
356
  set: rest
279
357
  });
280
358
  return row;
281
359
  }
282
360
  async find(id) {
283
- const rows = await this.db.select(this.columns).from(mediaPgTable).where((0, import_drizzle_orm3.eq)(mediaPgTable.id, id)).limit(1);
361
+ const rows = await this.db.select(this.columns).from(this.t.media).where((0, import_drizzle_orm3.eq)(this.t.media.id, id)).limit(1);
284
362
  const row = rows[0];
285
363
  return row ? toRecord(row) : null;
286
364
  }
287
365
  async listByOwner(ownerType, ownerId, collection) {
288
- const where = collection === void 0 ? (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm3.eq)(mediaPgTable.ownerId, ownerId)) : (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm3.eq)(mediaPgTable.ownerId, ownerId), (0, import_drizzle_orm3.eq)(mediaPgTable.collection, collection));
289
- const rows = await this.db.select(this.columns).from(mediaPgTable).where(where).orderBy((0, import_drizzle_orm3.asc)(mediaPgTable.order), (0, import_drizzle_orm3.asc)(mediaPgTable.id));
366
+ const where = collection === void 0 ? (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.media.ownerType, ownerType), (0, import_drizzle_orm3.eq)(this.t.media.ownerId, ownerId)) : (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.media.ownerType, ownerType), (0, import_drizzle_orm3.eq)(this.t.media.ownerId, ownerId), (0, import_drizzle_orm3.eq)(this.t.media.collection, collection));
367
+ const rows = await this.db.select(this.columns).from(this.t.media).where(where).orderBy((0, import_drizzle_orm3.asc)(this.t.media.order), (0, import_drizzle_orm3.asc)(this.t.media.id));
290
368
  return rows.map(toRecord);
291
369
  }
292
370
  async delete(id) {
293
- await this.db.delete(mediaPgTable).where((0, import_drizzle_orm3.eq)(mediaPgTable.id, id));
371
+ await this.db.delete(this.t.media).where((0, import_drizzle_orm3.eq)(this.t.media.id, id));
294
372
  }
295
373
  async nextOrder(ownerType, ownerId, collection) {
296
374
  const rows = await this.db.select({
297
- max: (0, import_drizzle_orm3.max)(mediaPgTable.order)
298
- }).from(mediaPgTable).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm3.eq)(mediaPgTable.ownerId, ownerId), (0, import_drizzle_orm3.eq)(mediaPgTable.collection, collection)));
375
+ max: (0, import_drizzle_orm3.max)(this.t.media.order)
376
+ }).from(this.t.media).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.media.ownerType, ownerType), (0, import_drizzle_orm3.eq)(this.t.media.ownerId, ownerId), (0, import_drizzle_orm3.eq)(this.t.media.collection, collection)));
299
377
  const top = rows[0]?.max;
300
378
  return top == null ? 0 : Number(top) + 1;
301
379
  }
302
380
  async count(filter = {}) {
303
381
  const conditions = [
304
382
  ...filter.ownerType !== void 0 ? [
305
- (0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, filter.ownerType)
383
+ (0, import_drizzle_orm3.eq)(this.t.media.ownerType, filter.ownerType)
306
384
  ] : [],
307
385
  ...filter.collection !== void 0 ? [
308
- (0, import_drizzle_orm3.eq)(mediaPgTable.collection, filter.collection)
386
+ (0, import_drizzle_orm3.eq)(this.t.media.collection, filter.collection)
309
387
  ] : [],
310
388
  ...filter.disk !== void 0 ? [
311
- (0, import_drizzle_orm3.eq)(mediaPgTable.disk, filter.disk)
389
+ (0, import_drizzle_orm3.eq)(this.t.media.disk, filter.disk)
312
390
  ] : [],
313
391
  ...filter.tenant ? [
314
- tenantCondition(mediaPgTable.tenantId, filter.tenant)
392
+ tenantCondition(this.t.media.tenantId, filter.tenant)
315
393
  ] : []
316
394
  ];
317
395
  const rows = await this.db.select({
318
396
  value: (0, import_drizzle_orm3.count)()
319
- }).from(mediaPgTable).where(conditions.length ? (0, import_drizzle_orm3.and)(...conditions) : void 0);
397
+ }).from(this.t.media).where(conditions.length ? (0, import_drizzle_orm3.and)(...conditions) : void 0);
320
398
  return Number(rows[0]?.value ?? 0);
321
399
  }
322
400
  async aggregate(query) {
323
- const column = query.groupBy === "collection" ? mediaPgTable.collection : mediaPgTable.disk;
401
+ const column = query.groupBy === "collection" ? this.t.media.collection : this.t.media.disk;
324
402
  const rows = await this.db.select({
325
403
  key: column,
326
404
  count: (0, import_drizzle_orm3.count)(),
327
- sumSize: (0, import_drizzle_orm3.sum)(mediaPgTable.size)
328
- }).from(mediaPgTable).where(query.tenant ? tenantCondition(mediaPgTable.tenantId, query.tenant) : void 0).groupBy(column);
405
+ sumSize: (0, import_drizzle_orm3.sum)(this.t.media.size)
406
+ }).from(this.t.media).where(query.tenant ? tenantCondition(this.t.media.tenantId, query.tenant) : void 0).groupBy(column);
329
407
  return rows.map((row) => ({
330
408
  key: row.key,
331
409
  count: Number(row.count),
@@ -338,22 +416,25 @@ var DrizzlePgMediaStore = class {
338
416
  const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
339
417
  const filterConditions = [
340
418
  ...filter.ownerType !== void 0 ? [
341
- (0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, filter.ownerType)
419
+ (0, import_drizzle_orm3.eq)(this.t.media.ownerType, filter.ownerType)
342
420
  ] : [],
343
421
  ...filter.collection !== void 0 ? [
344
- (0, import_drizzle_orm3.eq)(mediaPgTable.collection, filter.collection)
422
+ (0, import_drizzle_orm3.eq)(this.t.media.collection, filter.collection)
345
423
  ] : [],
346
424
  ...filter.disk !== void 0 ? [
347
- (0, import_drizzle_orm3.eq)(mediaPgTable.disk, filter.disk)
425
+ (0, import_drizzle_orm3.eq)(this.t.media.disk, filter.disk)
426
+ ] : [],
427
+ ...filter.nameContains !== void 0 ? [
428
+ nameContainsCondition(this.t.media.name, this.t.media.fileName, filter.nameContains)
348
429
  ] : [],
349
430
  ...filter.tenant ? [
350
- tenantCondition(mediaPgTable.tenantId, filter.tenant)
431
+ tenantCondition(this.t.media.tenantId, filter.tenant)
351
432
  ] : [],
352
433
  ...cursor ? [
353
- (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.gt)(mediaPgTable.createdAt, cursor.createdAt), (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.createdAt, cursor.createdAt), (0, import_drizzle_orm3.gt)(mediaPgTable.id, cursor.id)))
434
+ (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.gt)(this.t.media.createdAt, cursor.createdAt), (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(this.t.media.createdAt, cursor.createdAt), (0, import_drizzle_orm3.gt)(this.t.media.id, cursor.id)))
354
435
  ] : []
355
436
  ];
356
- const rows = await this.db.select(this.columns).from(mediaPgTable).where(filterConditions.length ? (0, import_drizzle_orm3.and)(...filterConditions) : void 0).orderBy((0, import_drizzle_orm3.asc)(mediaPgTable.createdAt), (0, import_drizzle_orm3.asc)(mediaPgTable.id)).limit(limit + 1);
437
+ const rows = await this.db.select(this.columns).from(this.t.media).where(filterConditions.length ? (0, import_drizzle_orm3.and)(...filterConditions) : void 0).orderBy((0, import_drizzle_orm3.asc)(this.t.media.createdAt), (0, import_drizzle_orm3.asc)(this.t.media.id)).limit(limit + 1);
357
438
  const hasMore = rows.length > limit;
358
439
  const records = rows.slice(0, limit).map(toRecord);
359
440
  const result = {
@@ -412,16 +493,22 @@ var DrizzlePgUploadSessionStore = class {
412
493
  }
413
494
  db;
414
495
  tenancy = false;
415
- constructor(db) {
496
+ t;
497
+ /**
498
+ * `schema`: the Postgres schema of `media_upload_sessions` / `media_upload_parts`. Every
499
+ * statement names it (`search_path` is never used). Default: unqualified.
500
+ */
501
+ constructor(db, options = {}) {
416
502
  this.db = db;
503
+ this.t = mediaPgTables(options.schema);
417
504
  }
418
505
  /** Off: the table without `tenant_id`, which Drizzle would otherwise list in an INSERT. */
419
506
  get sessionsTable() {
420
- return this.tenancy ? mediaUploadSessionsPgTable : mediaUploadSessionsPgTableWithoutTenant;
507
+ return this.tenancy ? this.t.uploadSessions : this.t.uploadSessionsWithoutTenant;
421
508
  }
422
509
  /** The columns to read: `tenant_id` only once tenancy is on. */
423
510
  get columns() {
424
- return selectable((0, import_drizzle_orm4.getTableColumns)(mediaUploadSessionsPgTable), this.tenancy);
511
+ return selectable((0, import_drizzle_orm4.getTableColumns)(this.t.uploadSessions), this.tenancy);
425
512
  }
426
513
  /**
427
514
  * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the upload
@@ -429,8 +516,8 @@ var DrizzlePgUploadSessionStore = class {
429
516
  */
430
517
  async enableTenancy() {
431
518
  await assertTenantColumn("media_upload_sessions", () => this.db.select({
432
- tenantId: mediaUploadSessionsPgTable.tenantId
433
- }).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);`.");
519
+ tenantId: this.t.uploadSessions.tenantId
520
+ }).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);`.");
434
521
  this.tenancy = true;
435
522
  }
436
523
  /** The session as persisted: off, no `tenantId`; on, `tenantId` or `null`. */
@@ -455,7 +542,7 @@ var DrizzlePgUploadSessionStore = class {
455
542
  };
456
543
  }
457
544
  async get(id) {
458
- const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.id, id)).limit(1);
545
+ const rows = await this.db.select(this.columns).from(this.t.uploadSessions).where((0, import_drizzle_orm4.eq)(this.t.uploadSessions.id, id)).limit(1);
459
546
  const row = rows[0];
460
547
  return row ? toSession(row) : null;
461
548
  }
@@ -471,23 +558,23 @@ var DrizzlePgUploadSessionStore = class {
471
558
  id: session.id,
472
559
  ...columns
473
560
  }).onConflictDoUpdate({
474
- target: mediaUploadSessionsPgTable.id,
561
+ target: this.t.uploadSessions.id,
475
562
  set: columns
476
563
  });
477
564
  return this.persisted(session);
478
565
  }
479
566
  async delete(id) {
480
- await this.db.delete(mediaUploadSessionsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.id, id));
567
+ await this.db.delete(this.t.uploadSessions).where((0, import_drizzle_orm4.eq)(this.t.uploadSessions.id, id));
481
568
  }
482
569
  async addPart(id, part) {
483
- await this.db.insert(mediaUploadPartsPgTable).values({
570
+ await this.db.insert(this.t.uploadParts).values({
484
571
  sessionId: id,
485
572
  partNumber: part.partNumber,
486
573
  etag: part.etag
487
574
  }).onConflictDoUpdate({
488
575
  target: [
489
- mediaUploadPartsPgTable.sessionId,
490
- mediaUploadPartsPgTable.partNumber
576
+ this.t.uploadParts.sessionId,
577
+ this.t.uploadParts.partNumber
491
578
  ],
492
579
  set: {
493
580
  etag: import_drizzle_orm4.sql`excluded.etag`
@@ -496,9 +583,9 @@ var DrizzlePgUploadSessionStore = class {
496
583
  }
497
584
  async listParts(id) {
498
585
  const rows = await this.db.select({
499
- partNumber: mediaUploadPartsPgTable.partNumber,
500
- etag: mediaUploadPartsPgTable.etag
501
- }).from(mediaUploadPartsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadPartsPgTable.sessionId, id)).orderBy((0, import_drizzle_orm4.asc)(mediaUploadPartsPgTable.partNumber));
586
+ partNumber: this.t.uploadParts.partNumber,
587
+ etag: this.t.uploadParts.etag
588
+ }).from(this.t.uploadParts).where((0, import_drizzle_orm4.eq)(this.t.uploadParts.sessionId, id)).orderBy((0, import_drizzle_orm4.asc)(this.t.uploadParts.partNumber));
502
589
  return rows.map((row) => ({
503
590
  partNumber: Number(row.partNumber),
504
591
  etag: row.etag
@@ -507,16 +594,16 @@ var DrizzlePgUploadSessionStore = class {
507
594
  async list(filter = {}) {
508
595
  const conditions = [
509
596
  ...filter.disk !== void 0 ? [
510
- (0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.disk, filter.disk)
597
+ (0, import_drizzle_orm4.eq)(this.t.uploadSessions.disk, filter.disk)
511
598
  ] : [],
512
599
  ...filter.keyPrefix !== void 0 ? [
513
- (0, import_drizzle_orm4.like)(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
600
+ (0, import_drizzle_orm4.like)(this.t.uploadSessions.key, `${escapeLike(filter.keyPrefix)}%`)
514
601
  ] : [],
515
602
  ...filter.tenant ? [
516
- tenantCondition(mediaUploadSessionsPgTable.tenantId, filter.tenant)
603
+ tenantCondition(this.t.uploadSessions.tenantId, filter.tenant)
517
604
  ] : []
518
605
  ];
519
- const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(conditions.length ? (0, import_drizzle_orm4.and)(...conditions) : void 0).orderBy((0, import_drizzle_orm4.asc)(mediaUploadSessionsPgTable.createdAt), (0, import_drizzle_orm4.asc)(mediaUploadSessionsPgTable.id));
606
+ const rows = await this.db.select(this.columns).from(this.t.uploadSessions).where(conditions.length ? (0, import_drizzle_orm4.and)(...conditions) : void 0).orderBy((0, import_drizzle_orm4.asc)(this.t.uploadSessions.createdAt), (0, import_drizzle_orm4.asc)(this.t.uploadSessions.id));
520
607
  return rows.map(toSession);
521
608
  }
522
609
  };
@@ -526,7 +613,9 @@ var DrizzlePgUploadSessionStore = class {
526
613
  DrizzlePgUploadSessionStore,
527
614
  MEDIA_PG_DDL,
528
615
  createMediaPgTables,
616
+ mediaPgDdl,
529
617
  mediaPgTable,
618
+ mediaPgTables,
530
619
  mediaUploadPartsPgTable,
531
620
  mediaUploadSessionsPgTable
532
621
  });