@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.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");
@@ -110,6 +149,16 @@ function decodeListCursor(cursor) {
110
149
  };
111
150
  }
112
151
  __name(decodeListCursor, "decodeListCursor");
152
+ function isEncodedListCursor(cursor) {
153
+ const decoded = Buffer.from(cursor, "base64").toString("utf8");
154
+ if (Buffer.from(decoded, "utf8").toString("base64") !== cursor) return false;
155
+ const separator = decoded.indexOf("|");
156
+ if (separator === -1 || separator === decoded.length - 1) return false;
157
+ const createdAt = decoded.slice(0, separator);
158
+ const date = new Date(createdAt);
159
+ return !Number.isNaN(date.getTime()) && date.toISOString() === createdAt;
160
+ }
161
+ __name(isEncodedListCursor, "isEncodedListCursor");
113
162
 
114
163
  // src/tenancy.ts
115
164
  var import_nestjs_media_core = require("@dudousxd/nestjs-media-core");
@@ -135,6 +184,14 @@ async function assertTenantColumn(table, probe, fix) {
135
184
  }
136
185
  }
137
186
  __name(assertTenantColumn, "assertTenantColumn");
187
+ function nameContainsCondition(name, fileName, text3) {
188
+ const pattern = `%${text3.toLowerCase().replace(/[!%_]/g, (c) => `!${c}`)}%`;
189
+ return (0, import_drizzle_orm2.or)(import_drizzle_orm2.sql`lower(${name}) like ${pattern} escape '!'`, import_drizzle_orm2.sql`lower(${fileName}) like ${pattern} escape '!'`);
190
+ }
191
+ __name(nameContainsCondition, "nameContainsCondition");
192
+
193
+ // src/pg/schema.ts
194
+ var import_pg_core2 = require("drizzle-orm/pg-core");
138
195
 
139
196
  // src/pg/columns.ts
140
197
  var import_pg_core = require("drizzle-orm/pg-core");
@@ -192,44 +249,69 @@ function uploadSessionPgColumns() {
192
249
  };
193
250
  }
194
251
  __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
252
 
198
253
  // 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
- ]);
254
+ function tableIn(schema) {
255
+ if (schema === void 0) return import_pg_core2.pgTable;
256
+ assertSchemaName(schema);
257
+ if (schema === "public") {
258
+ throw new TypeError("[nestjs-media] `schema: 'public'` is Postgres' default schema: leave `schema` unset to use it.");
259
+ }
260
+ return (0, import_pg_core2.pgSchema)(schema).table;
261
+ }
262
+ __name(tableIn, "tableIn");
263
+ function mediaPgTables(schema) {
264
+ const table = tableIn(schema);
265
+ const media = table("media", {
266
+ ...mediaPgColumns(),
267
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
268
+ tenantId: (0, import_pg_core2.text)("tenant_id")
269
+ }, (t) => [
270
+ (0, import_pg_core2.index)("idx_media_owner").on(t.ownerType, t.ownerId, t.collection),
271
+ (0, import_pg_core2.index)("idx_media_collection").on(t.collection),
272
+ (0, import_pg_core2.index)("idx_media_disk").on(t.disk),
273
+ (0, import_pg_core2.index)("idx_media_created_at").on(t.createdAt),
274
+ (0, import_pg_core2.index)("idx_media_collection_created_at").on(t.collection, t.createdAt, t.id),
275
+ (0, import_pg_core2.index)("idx_media_tenant").on(t.tenantId, t.ownerType, t.ownerId, t.collection)
276
+ ]);
277
+ const uploadSessions = table("media_upload_sessions", {
278
+ ...uploadSessionPgColumns(),
279
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
280
+ tenantId: (0, import_pg_core2.text)("tenant_id")
281
+ }, (t) => [
282
+ (0, import_pg_core2.index)("idx_media_upload_sessions_tenant").on(t.tenantId)
283
+ ]);
284
+ const uploadParts = table("media_upload_parts", {
285
+ sessionId: (0, import_pg_core2.text)("session_id").notNull().references(() => uploadSessions.id, {
286
+ onDelete: "cascade"
287
+ }),
288
+ partNumber: (0, import_pg_core2.integer)("part_number").notNull(),
289
+ etag: (0, import_pg_core2.text)("etag").notNull()
290
+ }, (t) => [
291
+ (0, import_pg_core2.primaryKey)({
292
+ columns: [
293
+ t.sessionId,
294
+ t.partNumber
295
+ ]
296
+ })
297
+ ]);
298
+ return {
299
+ media,
300
+ uploadSessions,
301
+ uploadParts,
302
+ /**
303
+ * Internal: the tables without `tenant_id`. The stores insert through them while tenancy is
304
+ * off, because Drizzle lists every column of a table in an `INSERT`.
305
+ */
306
+ mediaWithoutTenant: table("media", mediaPgColumns()),
307
+ uploadSessionsWithoutTenant: table("media_upload_sessions", uploadSessionPgColumns())
308
+ };
309
+ }
310
+ __name(mediaPgTables, "mediaPgTables");
311
+ var unqualified = mediaPgTables();
312
+ var mediaPgTable = unqualified.media;
313
+ var mediaUploadSessionsPgTable = unqualified.uploadSessions;
314
+ var mediaUploadPartsPgTable = unqualified.uploadParts;
233
315
 
234
316
  // src/pg/drizzle-pg-media-store.ts
235
317
  function toRecord(row) {
@@ -253,12 +335,18 @@ var DrizzlePgMediaStore = class {
253
335
  }
254
336
  db;
255
337
  tenancy = false;
256
- constructor(db) {
338
+ t;
339
+ /**
340
+ * `schema`: the Postgres schema the `media` table lives in. Every statement names it
341
+ * (`search_path` is never used). Default: unqualified, the connection's current schema.
342
+ */
343
+ constructor(db, options = {}) {
257
344
  this.db = db;
345
+ this.t = mediaPgTables(options.schema);
258
346
  }
259
347
  /** The columns to read: `tenant_id` only once tenancy is on. */
260
348
  get columns() {
261
- return selectable((0, import_drizzle_orm3.getTableColumns)(mediaPgTable), this.tenancy);
349
+ return selectable((0, import_drizzle_orm3.getTableColumns)(this.t.media), this.tenancy);
262
350
  }
263
351
  /**
264
352
  * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the
@@ -266,66 +354,66 @@ var DrizzlePgMediaStore = class {
266
354
  */
267
355
  async enableTenancy() {
268
356
  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);`.");
357
+ tenantId: this.t.media.tenantId
358
+ }).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
359
  this.tenancy = true;
272
360
  }
273
361
  async save(record) {
274
362
  const row = toRow(record, this.tenancy);
275
363
  const { id: _id, ...rest } = row;
276
- await this.db.insert(this.tenancy ? mediaPgTable : mediaPgTableWithoutTenant).values(row).onConflictDoUpdate({
277
- target: mediaPgTable.id,
364
+ await this.db.insert(this.tenancy ? this.t.media : this.t.mediaWithoutTenant).values(row).onConflictDoUpdate({
365
+ target: this.t.media.id,
278
366
  set: rest
279
367
  });
280
368
  return row;
281
369
  }
282
370
  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);
371
+ 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
372
  const row = rows[0];
285
373
  return row ? toRecord(row) : null;
286
374
  }
287
375
  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));
376
+ 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));
377
+ 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
378
  return rows.map(toRecord);
291
379
  }
292
380
  async delete(id) {
293
- await this.db.delete(mediaPgTable).where((0, import_drizzle_orm3.eq)(mediaPgTable.id, id));
381
+ await this.db.delete(this.t.media).where((0, import_drizzle_orm3.eq)(this.t.media.id, id));
294
382
  }
295
383
  async nextOrder(ownerType, ownerId, collection) {
296
384
  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)));
385
+ max: (0, import_drizzle_orm3.max)(this.t.media.order)
386
+ }).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
387
  const top = rows[0]?.max;
300
388
  return top == null ? 0 : Number(top) + 1;
301
389
  }
302
390
  async count(filter = {}) {
303
391
  const conditions = [
304
392
  ...filter.ownerType !== void 0 ? [
305
- (0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, filter.ownerType)
393
+ (0, import_drizzle_orm3.eq)(this.t.media.ownerType, filter.ownerType)
306
394
  ] : [],
307
395
  ...filter.collection !== void 0 ? [
308
- (0, import_drizzle_orm3.eq)(mediaPgTable.collection, filter.collection)
396
+ (0, import_drizzle_orm3.eq)(this.t.media.collection, filter.collection)
309
397
  ] : [],
310
398
  ...filter.disk !== void 0 ? [
311
- (0, import_drizzle_orm3.eq)(mediaPgTable.disk, filter.disk)
399
+ (0, import_drizzle_orm3.eq)(this.t.media.disk, filter.disk)
312
400
  ] : [],
313
401
  ...filter.tenant ? [
314
- tenantCondition(mediaPgTable.tenantId, filter.tenant)
402
+ tenantCondition(this.t.media.tenantId, filter.tenant)
315
403
  ] : []
316
404
  ];
317
405
  const rows = await this.db.select({
318
406
  value: (0, import_drizzle_orm3.count)()
319
- }).from(mediaPgTable).where(conditions.length ? (0, import_drizzle_orm3.and)(...conditions) : void 0);
407
+ }).from(this.t.media).where(conditions.length ? (0, import_drizzle_orm3.and)(...conditions) : void 0);
320
408
  return Number(rows[0]?.value ?? 0);
321
409
  }
322
410
  async aggregate(query) {
323
- const column = query.groupBy === "collection" ? mediaPgTable.collection : mediaPgTable.disk;
411
+ const column = query.groupBy === "collection" ? this.t.media.collection : this.t.media.disk;
324
412
  const rows = await this.db.select({
325
413
  key: column,
326
414
  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);
415
+ sumSize: (0, import_drizzle_orm3.sum)(this.t.media.size)
416
+ }).from(this.t.media).where(query.tenant ? tenantCondition(this.t.media.tenantId, query.tenant) : void 0).groupBy(column);
329
417
  return rows.map((row) => ({
330
418
  key: row.key,
331
419
  count: Number(row.count),
@@ -333,27 +421,34 @@ var DrizzlePgMediaStore = class {
333
421
  sumSize: query.sum === "size" ? Number(row.sumSize ?? 0) : 0
334
422
  }));
335
423
  }
424
+ /** {@inheritDoc MediaStore.isListCursor} */
425
+ isListCursor(cursor) {
426
+ return isEncodedListCursor(cursor);
427
+ }
336
428
  async list(filter = {}, page = {}) {
337
429
  const limit = page.limit ?? 50;
338
430
  const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
339
431
  const filterConditions = [
340
432
  ...filter.ownerType !== void 0 ? [
341
- (0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, filter.ownerType)
433
+ (0, import_drizzle_orm3.eq)(this.t.media.ownerType, filter.ownerType)
342
434
  ] : [],
343
435
  ...filter.collection !== void 0 ? [
344
- (0, import_drizzle_orm3.eq)(mediaPgTable.collection, filter.collection)
436
+ (0, import_drizzle_orm3.eq)(this.t.media.collection, filter.collection)
345
437
  ] : [],
346
438
  ...filter.disk !== void 0 ? [
347
- (0, import_drizzle_orm3.eq)(mediaPgTable.disk, filter.disk)
439
+ (0, import_drizzle_orm3.eq)(this.t.media.disk, filter.disk)
440
+ ] : [],
441
+ ...filter.nameContains !== void 0 ? [
442
+ nameContainsCondition(this.t.media.name, this.t.media.fileName, filter.nameContains)
348
443
  ] : [],
349
444
  ...filter.tenant ? [
350
- tenantCondition(mediaPgTable.tenantId, filter.tenant)
445
+ tenantCondition(this.t.media.tenantId, filter.tenant)
351
446
  ] : [],
352
447
  ...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)))
448
+ (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
449
  ] : []
355
450
  ];
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);
451
+ 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
452
  const hasMore = rows.length > limit;
358
453
  const records = rows.slice(0, limit).map(toRecord);
359
454
  const result = {
@@ -412,16 +507,22 @@ var DrizzlePgUploadSessionStore = class {
412
507
  }
413
508
  db;
414
509
  tenancy = false;
415
- constructor(db) {
510
+ t;
511
+ /**
512
+ * `schema`: the Postgres schema of `media_upload_sessions` / `media_upload_parts`. Every
513
+ * statement names it (`search_path` is never used). Default: unqualified.
514
+ */
515
+ constructor(db, options = {}) {
416
516
  this.db = db;
517
+ this.t = mediaPgTables(options.schema);
417
518
  }
418
519
  /** Off: the table without `tenant_id`, which Drizzle would otherwise list in an INSERT. */
419
520
  get sessionsTable() {
420
- return this.tenancy ? mediaUploadSessionsPgTable : mediaUploadSessionsPgTableWithoutTenant;
521
+ return this.tenancy ? this.t.uploadSessions : this.t.uploadSessionsWithoutTenant;
421
522
  }
422
523
  /** The columns to read: `tenant_id` only once tenancy is on. */
423
524
  get columns() {
424
- return selectable((0, import_drizzle_orm4.getTableColumns)(mediaUploadSessionsPgTable), this.tenancy);
525
+ return selectable((0, import_drizzle_orm4.getTableColumns)(this.t.uploadSessions), this.tenancy);
425
526
  }
426
527
  /**
427
528
  * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the upload
@@ -429,8 +530,8 @@ var DrizzlePgUploadSessionStore = class {
429
530
  */
430
531
  async enableTenancy() {
431
532
  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);`.");
533
+ tenantId: this.t.uploadSessions.tenantId
534
+ }).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
535
  this.tenancy = true;
435
536
  }
436
537
  /** The session as persisted: off, no `tenantId`; on, `tenantId` or `null`. */
@@ -455,7 +556,7 @@ var DrizzlePgUploadSessionStore = class {
455
556
  };
456
557
  }
457
558
  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);
559
+ 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
560
  const row = rows[0];
460
561
  return row ? toSession(row) : null;
461
562
  }
@@ -471,23 +572,23 @@ var DrizzlePgUploadSessionStore = class {
471
572
  id: session.id,
472
573
  ...columns
473
574
  }).onConflictDoUpdate({
474
- target: mediaUploadSessionsPgTable.id,
575
+ target: this.t.uploadSessions.id,
475
576
  set: columns
476
577
  });
477
578
  return this.persisted(session);
478
579
  }
479
580
  async delete(id) {
480
- await this.db.delete(mediaUploadSessionsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.id, id));
581
+ await this.db.delete(this.t.uploadSessions).where((0, import_drizzle_orm4.eq)(this.t.uploadSessions.id, id));
481
582
  }
482
583
  async addPart(id, part) {
483
- await this.db.insert(mediaUploadPartsPgTable).values({
584
+ await this.db.insert(this.t.uploadParts).values({
484
585
  sessionId: id,
485
586
  partNumber: part.partNumber,
486
587
  etag: part.etag
487
588
  }).onConflictDoUpdate({
488
589
  target: [
489
- mediaUploadPartsPgTable.sessionId,
490
- mediaUploadPartsPgTable.partNumber
590
+ this.t.uploadParts.sessionId,
591
+ this.t.uploadParts.partNumber
491
592
  ],
492
593
  set: {
493
594
  etag: import_drizzle_orm4.sql`excluded.etag`
@@ -496,9 +597,9 @@ var DrizzlePgUploadSessionStore = class {
496
597
  }
497
598
  async listParts(id) {
498
599
  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));
600
+ partNumber: this.t.uploadParts.partNumber,
601
+ etag: this.t.uploadParts.etag
602
+ }).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
603
  return rows.map((row) => ({
503
604
  partNumber: Number(row.partNumber),
504
605
  etag: row.etag
@@ -507,16 +608,16 @@ var DrizzlePgUploadSessionStore = class {
507
608
  async list(filter = {}) {
508
609
  const conditions = [
509
610
  ...filter.disk !== void 0 ? [
510
- (0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.disk, filter.disk)
611
+ (0, import_drizzle_orm4.eq)(this.t.uploadSessions.disk, filter.disk)
511
612
  ] : [],
512
613
  ...filter.keyPrefix !== void 0 ? [
513
- (0, import_drizzle_orm4.like)(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
614
+ (0, import_drizzle_orm4.like)(this.t.uploadSessions.key, `${escapeLike(filter.keyPrefix)}%`)
514
615
  ] : [],
515
616
  ...filter.tenant ? [
516
- tenantCondition(mediaUploadSessionsPgTable.tenantId, filter.tenant)
617
+ tenantCondition(this.t.uploadSessions.tenantId, filter.tenant)
517
618
  ] : []
518
619
  ];
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));
620
+ 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
621
  return rows.map(toSession);
521
622
  }
522
623
  };
@@ -526,7 +627,9 @@ var DrizzlePgUploadSessionStore = class {
526
627
  DrizzlePgUploadSessionStore,
527
628
  MEDIA_PG_DDL,
528
629
  createMediaPgTables,
630
+ mediaPgDdl,
529
631
  mediaPgTable,
632
+ mediaPgTables,
530
633
  mediaUploadPartsPgTable,
531
634
  mediaUploadSessionsPgTable
532
635
  });