@dudousxd/nestjs-media-database-drizzle 0.5.4 → 0.5.6

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/index.cjs CHANGED
@@ -54,7 +54,12 @@ var mediaTable = (0, import_sqlite_core.sqliteTable)("media", {
54
54
  updatedAt: (0, import_sqlite_core.integer)("updated_at", {
55
55
  mode: "timestamp_ms"
56
56
  }).notNull()
57
- });
57
+ }, (table) => ({
58
+ ownerIdx: (0, import_sqlite_core.index)("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
59
+ collectionIdx: (0, import_sqlite_core.index)("idx_media_collection").on(table.collection),
60
+ diskIdx: (0, import_sqlite_core.index)("idx_media_disk").on(table.disk),
61
+ createdAtIdx: (0, import_sqlite_core.index)("idx_media_created_at").on(table.createdAt)
62
+ }));
58
63
 
59
64
  // src/drizzle-media-store.ts
60
65
  var import_drizzle_orm = require("drizzle-orm");
@@ -78,6 +83,9 @@ function createMediaTable(db) {
78
83
  updated_at integer NOT NULL
79
84
  )
80
85
  `);
86
+ db.run(import_drizzle_orm.sql`CREATE INDEX IF NOT EXISTS idx_media_collection ON media (collection)`);
87
+ db.run(import_drizzle_orm.sql`CREATE INDEX IF NOT EXISTS idx_media_disk ON media (disk)`);
88
+ db.run(import_drizzle_orm.sql`CREATE INDEX IF NOT EXISTS idx_media_created_at ON media (created_at)`);
81
89
  }
82
90
  __name(createMediaTable, "createMediaTable");
83
91
  var DrizzleMediaStore = class {
@@ -114,6 +122,36 @@ var DrizzleMediaStore = class {
114
122
  const top = rows[0]?.max;
115
123
  return top == null ? 0 : Number(top) + 1;
116
124
  }
125
+ async count(filter = {}) {
126
+ const conditions = [
127
+ ...filter.ownerType !== void 0 ? [
128
+ (0, import_drizzle_orm.eq)(mediaTable.ownerType, filter.ownerType)
129
+ ] : [],
130
+ ...filter.collection !== void 0 ? [
131
+ (0, import_drizzle_orm.eq)(mediaTable.collection, filter.collection)
132
+ ] : [],
133
+ ...filter.disk !== void 0 ? [
134
+ (0, import_drizzle_orm.eq)(mediaTable.disk, filter.disk)
135
+ ] : []
136
+ ];
137
+ const rows = await this.db.select({
138
+ value: (0, import_drizzle_orm.count)()
139
+ }).from(mediaTable).where(conditions.length ? (0, import_drizzle_orm.and)(...conditions) : void 0);
140
+ return Number(rows[0]?.value ?? 0);
141
+ }
142
+ async aggregate(query) {
143
+ const column = query.groupBy === "collection" ? mediaTable.collection : mediaTable.disk;
144
+ const rows = await this.db.select({
145
+ key: column,
146
+ count: (0, import_drizzle_orm.count)(),
147
+ sumSize: (0, import_drizzle_orm.sum)(mediaTable.size)
148
+ }).from(mediaTable).groupBy(column);
149
+ return rows.map((row) => ({
150
+ key: row.key,
151
+ count: Number(row.count),
152
+ sumSize: query.sum === "size" ? Number(row.sumSize ?? 0) : 0
153
+ }));
154
+ }
117
155
  };
118
156
 
119
157
  // src/attachment.column.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/media.schema.ts","../src/drizzle-media-store.ts","../src/attachment.column.ts"],"sourcesContent":["export * from './media.schema';\nexport * from './drizzle-media-store';\nexport * from './attachment.column';\n","import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) media table. `order` maps to the `position` column. JSON columns\n * use text(mode:'json'). Postgres/MySQL variants follow the same shape via their\n * respective drizzle cores.\n */\nexport const mediaTable = sqliteTable('media', {\n id: text('id').primaryKey(),\n ownerType: text('owner_type').notNull(),\n ownerId: text('owner_id').notNull(),\n collection: text('collection').notNull(),\n name: text('name').notNull(),\n fileName: text('file_name').notNull(),\n mimeType: text('mime_type').notNull(),\n size: integer('size').notNull(),\n disk: text('disk').notNull(),\n path: text('path').notNull(),\n order: integer('position').notNull(),\n customProperties: text('custom_properties', { mode: 'json' }).notNull(),\n conversions: text('conversions', { mode: 'json' }).notNull(),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n});\n","import type { MediaRecord, MediaStore } from '@dudousxd/nestjs-media-core';\nimport { and, asc, eq, max, sql } from 'drizzle-orm';\nimport type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';\nimport { mediaTable } from './media.schema';\n\ntype DB = BetterSQLite3Database<Record<string, never>>;\n\n/**\n * Migration-first (§3.10): Drizzle has no auto-ensure. Run migrations with\n * drizzle-kit in production; this helper creates the table for tests/dev.\n */\nexport function createMediaTable(db: DB): void {\n db.run(sql`\n CREATE TABLE IF NOT EXISTS media (\n id text PRIMARY KEY NOT NULL,\n owner_type text NOT NULL,\n owner_id text NOT NULL,\n collection text NOT NULL,\n name text NOT NULL,\n file_name text NOT NULL,\n mime_type text NOT NULL,\n size integer NOT NULL,\n disk text NOT NULL,\n path text NOT NULL,\n position integer NOT NULL,\n custom_properties text NOT NULL,\n conversions text NOT NULL,\n created_at integer NOT NULL,\n updated_at integer NOT NULL\n )\n `);\n}\n\n/** MediaStore backed by Drizzle (better-sqlite3). POJO receiving the drizzle db. */\nexport class DrizzleMediaStore implements MediaStore {\n constructor(private readonly db: DB) {}\n\n async save(record: MediaRecord): Promise<MediaRecord> {\n await this.db\n .insert(mediaTable)\n .values(record)\n .onConflictDoUpdate({ target: mediaTable.id, set: record });\n return record;\n }\n\n async find(id: string): Promise<MediaRecord | null> {\n const rows = await this.db.select().from(mediaTable).where(eq(mediaTable.id, id)).limit(1);\n return (rows[0] as MediaRecord | undefined) ?? null;\n }\n\n async listByOwner(\n ownerType: string,\n ownerId: string,\n collection?: string,\n ): Promise<MediaRecord[]> {\n const where =\n collection === undefined\n ? and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId))\n : and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n );\n const rows = await this.db\n .select()\n .from(mediaTable)\n .where(where)\n .orderBy(asc(mediaTable.order));\n return rows as MediaRecord[];\n }\n\n async delete(id: string): Promise<void> {\n await this.db.delete(mediaTable).where(eq(mediaTable.id, id));\n }\n\n async nextOrder(ownerType: string, ownerId: string, collection: string): Promise<number> {\n const rows = await this.db\n .select({ max: max(mediaTable.order) })\n .from(mediaTable)\n .where(\n and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n ),\n );\n const top = rows[0]?.max;\n return top == null ? 0 : Number(top) + 1;\n }\n}\n","import { Attachment, type AttachmentData } from '@dudousxd/nestjs-media-core';\nimport { customType } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) custom column for an Attachment value:\n * `avatar: attachment('avatar')` → stored as JSON text, rehydrated to an `Attachment`.\n */\nexport const attachment = customType<{ data: Attachment | null; driverData: string }>({\n dataType() {\n return 'text';\n },\n toDriver(value: Attachment | null): string {\n return JSON.stringify(value ? value.toJSON() : null);\n },\n fromDriver(value: string): Attachment | null {\n return Attachment.fromJSON(value ? (JSON.parse(value) as AttachmentData) : null);\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;ACAA,yBAA2C;AAOpC,IAAMA,iBAAaC,gCAAY,SAAS;EAC7CC,QAAIC,yBAAK,IAAA,EAAMC,WAAU;EACzBC,eAAWF,yBAAK,YAAA,EAAcG,QAAO;EACrCC,aAASJ,yBAAK,UAAA,EAAYG,QAAO;EACjCE,gBAAYL,yBAAK,YAAA,EAAcG,QAAO;EACtCG,UAAMN,yBAAK,MAAA,EAAQG,QAAO;EAC1BI,cAAUP,yBAAK,WAAA,EAAaG,QAAO;EACnCK,cAAUR,yBAAK,WAAA,EAAaG,QAAO;EACnCM,UAAMC,4BAAQ,MAAA,EAAQP,QAAO;EAC7BQ,UAAMX,yBAAK,MAAA,EAAQG,QAAO;EAC1BS,UAAMZ,yBAAK,MAAA,EAAQG,QAAO;EAC1BU,WAAOH,4BAAQ,UAAA,EAAYP,QAAO;EAClCW,sBAAkBd,yBAAK,qBAAqB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B,KAAK,CAAA;AAC/B,WAAOd;EACT;EAEA,MAAMe,OAAOlB,IAA2B;AACtC,UAAM,KAAKX,GAAG6B,OAAOtB,UAAAA,EAAYU,UAAMC,uBAAGX,WAAWI,IAAIA,EAAAA,CAAAA;EAC3D;EAEA,MAAMmB,UAAUT,WAAmBC,SAAiBC,YAAqC;AACvF,UAAMT,OAAO,MAAM,KAAKd,GACrBe,OAAO;MAAEgB,SAAKA,wBAAIxB,WAAWqB,KAAK;IAAE,CAAA,EACpCZ,KAAKT,UAAAA,EACLU,UACCQ,4BACEP,uBAAGX,WAAWc,WAAWA,SAAAA,OACzBH,uBAAGX,WAAWe,SAASA,OAAAA,OACvBJ,uBAAGX,WAAWgB,YAAYA,UAAAA,CAAAA,CAAAA;AAGhC,UAAMS,MAAMlB,KAAK,CAAA,GAAIiB;AACrB,WAAOC,OAAO,OAAO,IAAIC,OAAOD,GAAAA,IAAO;EACzC;AACF;;;ACzFA,+BAAgD;AAChD,IAAAE,sBAA2B;AAMpB,IAAMC,iBAAaC,gCAA4D;EACpFC,WAAAA;AACE,WAAO;EACT;EACAC,SAASC,OAAwB;AAC/B,WAAOC,KAAKC,UAAUF,QAAQA,MAAMG,OAAM,IAAK,IAAA;EACjD;EACAC,WAAWJ,OAAa;AACtB,WAAOK,oCAAWC,SAASN,QAASC,KAAKM,MAAMP,KAAAA,IAA4B,IAAA;EAC7E;AACF,CAAA;","names":["mediaTable","sqliteTable","id","text","primaryKey","ownerType","notNull","ownerId","collection","name","fileName","mimeType","size","integer","disk","path","order","customProperties","mode","conversions","createdAt","updatedAt","createMediaTable","db","run","sql","DrizzleMediaStore","save","record","insert","mediaTable","values","onConflictDoUpdate","target","id","set","find","rows","select","from","where","eq","limit","listByOwner","ownerType","ownerId","collection","undefined","and","orderBy","asc","order","delete","nextOrder","max","top","Number","import_sqlite_core","attachment","customType","dataType","toDriver","value","JSON","stringify","toJSON","fromDriver","Attachment","fromJSON","parse"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/media.schema.ts","../src/drizzle-media-store.ts","../src/attachment.column.ts"],"sourcesContent":["export * from './media.schema';\nexport * from './drizzle-media-store';\nexport * from './attachment.column';\n","import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) media table. `order` maps to the `position` column. JSON columns\n * use text(mode:'json'). Postgres/MySQL variants follow the same shape via their\n * respective drizzle cores.\n */\nexport const mediaTable = sqliteTable(\n 'media',\n {\n id: text('id').primaryKey(),\n ownerType: text('owner_type').notNull(),\n ownerId: text('owner_id').notNull(),\n collection: text('collection').notNull(),\n name: text('name').notNull(),\n fileName: text('file_name').notNull(),\n mimeType: text('mime_type').notNull(),\n size: integer('size').notNull(),\n disk: text('disk').notNull(),\n path: text('path').notNull(),\n order: integer('position').notNull(),\n customProperties: text('custom_properties', { mode: 'json' }).notNull(),\n conversions: text('conversions', { mode: 'json' }).notNull(),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => ({\n ownerIdx: index('idx_media_owner').on(table.ownerType, table.ownerId, table.collection),\n collectionIdx: index('idx_media_collection').on(table.collection),\n diskIdx: index('idx_media_disk').on(table.disk),\n createdAtIdx: index('idx_media_created_at').on(table.createdAt),\n }),\n);\n","import type {\n MediaAggregateQuery,\n MediaAggregateResult,\n MediaCountFilter,\n MediaRecord,\n MediaStore,\n} from '@dudousxd/nestjs-media-core';\nimport { and, asc, count, eq, max, sql, sum } from 'drizzle-orm';\nimport type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';\nimport { mediaTable } from './media.schema';\n\ntype DB = BetterSQLite3Database<Record<string, never>>;\n\n/**\n * Migration-first (§3.10): Drizzle has no auto-ensure. Run migrations with\n * drizzle-kit in production; this helper creates the table for tests/dev.\n */\nexport function createMediaTable(db: DB): void {\n db.run(sql`\n CREATE TABLE IF NOT EXISTS media (\n id text PRIMARY KEY NOT NULL,\n owner_type text NOT NULL,\n owner_id text NOT NULL,\n collection text NOT NULL,\n name text NOT NULL,\n file_name text NOT NULL,\n mime_type text NOT NULL,\n size integer NOT NULL,\n disk text NOT NULL,\n path text NOT NULL,\n position integer NOT NULL,\n custom_properties text NOT NULL,\n conversions text NOT NULL,\n created_at integer NOT NULL,\n updated_at integer NOT NULL\n )\n `);\n db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_collection ON media (collection)`);\n db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_disk ON media (disk)`);\n db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_created_at ON media (created_at)`);\n}\n\n/** MediaStore backed by Drizzle (better-sqlite3). POJO receiving the drizzle db. */\nexport class DrizzleMediaStore implements MediaStore {\n constructor(private readonly db: DB) {}\n\n async save(record: MediaRecord): Promise<MediaRecord> {\n await this.db\n .insert(mediaTable)\n .values(record)\n .onConflictDoUpdate({ target: mediaTable.id, set: record });\n return record;\n }\n\n async find(id: string): Promise<MediaRecord | null> {\n const rows = await this.db.select().from(mediaTable).where(eq(mediaTable.id, id)).limit(1);\n return (rows[0] as MediaRecord | undefined) ?? null;\n }\n\n async listByOwner(\n ownerType: string,\n ownerId: string,\n collection?: string,\n ): Promise<MediaRecord[]> {\n const where =\n collection === undefined\n ? and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId))\n : and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n );\n const rows = await this.db\n .select()\n .from(mediaTable)\n .where(where)\n .orderBy(asc(mediaTable.order));\n return rows as MediaRecord[];\n }\n\n async delete(id: string): Promise<void> {\n await this.db.delete(mediaTable).where(eq(mediaTable.id, id));\n }\n\n async nextOrder(ownerType: string, ownerId: string, collection: string): Promise<number> {\n const rows = await this.db\n .select({ max: max(mediaTable.order) })\n .from(mediaTable)\n .where(\n and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n ),\n );\n const top = rows[0]?.max;\n return top == null ? 0 : Number(top) + 1;\n }\n\n async count(filter: MediaCountFilter = {}): Promise<number> {\n const conditions = [\n ...(filter.ownerType !== undefined ? [eq(mediaTable.ownerType, filter.ownerType)] : []),\n ...(filter.collection !== undefined ? [eq(mediaTable.collection, filter.collection)] : []),\n ...(filter.disk !== undefined ? [eq(mediaTable.disk, filter.disk)] : []),\n ];\n const rows = await this.db\n .select({ value: count() })\n .from(mediaTable)\n .where(conditions.length ? and(...conditions) : undefined);\n return Number(rows[0]?.value ?? 0);\n }\n\n async aggregate(query: MediaAggregateQuery): Promise<MediaAggregateResult> {\n const column = query.groupBy === 'collection' ? mediaTable.collection : mediaTable.disk;\n const rows = await this.db\n .select({ key: column, count: count(), sumSize: sum(mediaTable.size) })\n .from(mediaTable)\n .groupBy(column);\n return rows.map((row) => ({\n key: row.key,\n count: Number(row.count),\n sumSize: query.sum === 'size' ? Number(row.sumSize ?? 0) : 0,\n }));\n }\n}\n","import { Attachment, type AttachmentData } from '@dudousxd/nestjs-media-core';\nimport { customType } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) custom column for an Attachment value:\n * `avatar: attachment('avatar')` → stored as JSON text, rehydrated to an `Attachment`.\n */\nexport const attachment = customType<{ data: Attachment | null; driverData: string }>({\n dataType() {\n return 'text';\n },\n toDriver(value: Attachment | null): string {\n return JSON.stringify(value ? value.toJSON() : null);\n },\n fromDriver(value: string): Attachment | null {\n return Attachment.fromJSON(value ? (JSON.parse(value) as AttachmentData) : null);\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;ACAA,yBAAkD;AAO3C,IAAMA,iBAAaC,gCACxB,SACA;EACEC,QAAIC,yBAAK,IAAA,EAAMC,WAAU;EACzBC,eAAWF,yBAAK,YAAA,EAAcG,QAAO;EACrCC,aAASJ,yBAAK,UAAA,EAAYG,QAAO;EACjCE,gBAAYL,yBAAK,YAAA,EAAcG,QA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AA;EACjD;EACAC,WAAWJ,OAAa;AACtB,WAAOK,oCAAWC,SAASN,QAASC,KAAKM,MAAMP,KAAAA,IAA4B,IAAA;EAC7E;AACF,CAAA;","names":["mediaTable","sqliteTable","id","text","primaryKey","ownerType","notNull","ownerId","collection","name","fileName","mimeType","size","integer","disk","path","order","customProperties","mode","conversions","createdAt","updatedAt","table","ownerIdx","index","on","collectionIdx","diskIdx","createdAtIdx","createMediaTable","db","run","sql","DrizzleMediaStore","save","record","insert","mediaTable","values","onConflictDoUpdate","target","id","set","find","rows","select","from","where","eq","limit","listByOwner","ownerType","ownerId","collection","undefined","and","orderBy","asc","order","delete","nextOrder","max","top","Number","count","filter","conditions","disk","value","length","aggregate","query","column","groupBy","key","sumSize","sum","size","map","row","import_sqlite_core","attachment","customType","dataType","toDriver","value","JSON","stringify","toJSON","fromDriver","Attachment","fromJSON","parse"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
2
- import { MediaStore, MediaRecord, Attachment } from '@dudousxd/nestjs-media-core';
2
+ import { MediaStore, MediaRecord, MediaCountFilter, MediaAggregateQuery, MediaAggregateResult, Attachment } from '@dudousxd/nestjs-media-core';
3
3
  import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
4
4
 
5
5
  /**
@@ -303,6 +303,8 @@ declare class DrizzleMediaStore implements MediaStore {
303
303
  listByOwner(ownerType: string, ownerId: string, collection?: string): Promise<MediaRecord[]>;
304
304
  delete(id: string): Promise<void>;
305
305
  nextOrder(ownerType: string, ownerId: string, collection: string): Promise<number>;
306
+ count(filter?: MediaCountFilter): Promise<number>;
307
+ aggregate(query: MediaAggregateQuery): Promise<MediaAggregateResult>;
306
308
  }
307
309
 
308
310
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
2
- import { MediaStore, MediaRecord, Attachment } from '@dudousxd/nestjs-media-core';
2
+ import { MediaStore, MediaRecord, MediaCountFilter, MediaAggregateQuery, MediaAggregateResult, Attachment } from '@dudousxd/nestjs-media-core';
3
3
  import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
4
4
 
5
5
  /**
@@ -303,6 +303,8 @@ declare class DrizzleMediaStore implements MediaStore {
303
303
  listByOwner(ownerType: string, ownerId: string, collection?: string): Promise<MediaRecord[]>;
304
304
  delete(id: string): Promise<void>;
305
305
  nextOrder(ownerType: string, ownerId: string, collection: string): Promise<number>;
306
+ count(filter?: MediaCountFilter): Promise<number>;
307
+ aggregate(query: MediaAggregateQuery): Promise<MediaAggregateResult>;
306
308
  }
307
309
 
308
310
  /**
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ var __defProp = Object.defineProperty;
2
2
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
3
 
4
4
  // src/media.schema.ts
5
- import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
5
+ import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
6
6
  var mediaTable = sqliteTable("media", {
7
7
  id: text("id").primaryKey(),
8
8
  ownerType: text("owner_type").notNull(),
@@ -27,10 +27,15 @@ var mediaTable = sqliteTable("media", {
27
27
  updatedAt: integer("updated_at", {
28
28
  mode: "timestamp_ms"
29
29
  }).notNull()
30
- });
30
+ }, (table) => ({
31
+ ownerIdx: index("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
32
+ collectionIdx: index("idx_media_collection").on(table.collection),
33
+ diskIdx: index("idx_media_disk").on(table.disk),
34
+ createdAtIdx: index("idx_media_created_at").on(table.createdAt)
35
+ }));
31
36
 
32
37
  // src/drizzle-media-store.ts
33
- import { and, asc, eq, max, sql } from "drizzle-orm";
38
+ import { and, asc, count, eq, max, sql, sum } from "drizzle-orm";
34
39
  function createMediaTable(db) {
35
40
  db.run(sql`
36
41
  CREATE TABLE IF NOT EXISTS media (
@@ -51,6 +56,9 @@ function createMediaTable(db) {
51
56
  updated_at integer NOT NULL
52
57
  )
53
58
  `);
59
+ db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_collection ON media (collection)`);
60
+ db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_disk ON media (disk)`);
61
+ db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_created_at ON media (created_at)`);
54
62
  }
55
63
  __name(createMediaTable, "createMediaTable");
56
64
  var DrizzleMediaStore = class {
@@ -87,6 +95,36 @@ var DrizzleMediaStore = class {
87
95
  const top = rows[0]?.max;
88
96
  return top == null ? 0 : Number(top) + 1;
89
97
  }
98
+ async count(filter = {}) {
99
+ const conditions = [
100
+ ...filter.ownerType !== void 0 ? [
101
+ eq(mediaTable.ownerType, filter.ownerType)
102
+ ] : [],
103
+ ...filter.collection !== void 0 ? [
104
+ eq(mediaTable.collection, filter.collection)
105
+ ] : [],
106
+ ...filter.disk !== void 0 ? [
107
+ eq(mediaTable.disk, filter.disk)
108
+ ] : []
109
+ ];
110
+ const rows = await this.db.select({
111
+ value: count()
112
+ }).from(mediaTable).where(conditions.length ? and(...conditions) : void 0);
113
+ return Number(rows[0]?.value ?? 0);
114
+ }
115
+ async aggregate(query) {
116
+ const column = query.groupBy === "collection" ? mediaTable.collection : mediaTable.disk;
117
+ const rows = await this.db.select({
118
+ key: column,
119
+ count: count(),
120
+ sumSize: sum(mediaTable.size)
121
+ }).from(mediaTable).groupBy(column);
122
+ return rows.map((row) => ({
123
+ key: row.key,
124
+ count: Number(row.count),
125
+ sumSize: query.sum === "size" ? Number(row.sumSize ?? 0) : 0
126
+ }));
127
+ }
90
128
  };
91
129
 
92
130
  // src/attachment.column.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/media.schema.ts","../src/drizzle-media-store.ts","../src/attachment.column.ts"],"sourcesContent":["import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) media table. `order` maps to the `position` column. JSON columns\n * use text(mode:'json'). Postgres/MySQL variants follow the same shape via their\n * respective drizzle cores.\n */\nexport const mediaTable = sqliteTable('media', {\n id: text('id').primaryKey(),\n ownerType: text('owner_type').notNull(),\n ownerId: text('owner_id').notNull(),\n collection: text('collection').notNull(),\n name: text('name').notNull(),\n fileName: text('file_name').notNull(),\n mimeType: text('mime_type').notNull(),\n size: integer('size').notNull(),\n disk: text('disk').notNull(),\n path: text('path').notNull(),\n order: integer('position').notNull(),\n customProperties: text('custom_properties', { mode: 'json' }).notNull(),\n conversions: text('conversions', { mode: 'json' }).notNull(),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n});\n","import type { MediaRecord, MediaStore } from '@dudousxd/nestjs-media-core';\nimport { and, asc, eq, max, sql } from 'drizzle-orm';\nimport type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';\nimport { mediaTable } from './media.schema';\n\ntype DB = BetterSQLite3Database<Record<string, never>>;\n\n/**\n * Migration-first (§3.10): Drizzle has no auto-ensure. Run migrations with\n * drizzle-kit in production; this helper creates the table for tests/dev.\n */\nexport function createMediaTable(db: DB): void {\n db.run(sql`\n CREATE TABLE IF NOT EXISTS media (\n id text PRIMARY KEY NOT NULL,\n owner_type text NOT NULL,\n owner_id text NOT NULL,\n collection text NOT NULL,\n name text NOT NULL,\n file_name text NOT NULL,\n mime_type text NOT NULL,\n size integer NOT NULL,\n disk text NOT NULL,\n path text NOT NULL,\n position integer NOT NULL,\n custom_properties text NOT NULL,\n conversions text NOT NULL,\n created_at integer NOT NULL,\n updated_at integer NOT NULL\n )\n `);\n}\n\n/** MediaStore backed by Drizzle (better-sqlite3). POJO receiving the drizzle db. */\nexport class DrizzleMediaStore implements MediaStore {\n constructor(private readonly db: DB) {}\n\n async save(record: MediaRecord): Promise<MediaRecord> {\n await this.db\n .insert(mediaTable)\n .values(record)\n .onConflictDoUpdate({ target: mediaTable.id, set: record });\n return record;\n }\n\n async find(id: string): Promise<MediaRecord | null> {\n const rows = await this.db.select().from(mediaTable).where(eq(mediaTable.id, id)).limit(1);\n return (rows[0] as MediaRecord | undefined) ?? null;\n }\n\n async listByOwner(\n ownerType: string,\n ownerId: string,\n collection?: string,\n ): Promise<MediaRecord[]> {\n const where =\n collection === undefined\n ? and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId))\n : and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n );\n const rows = await this.db\n .select()\n .from(mediaTable)\n .where(where)\n .orderBy(asc(mediaTable.order));\n return rows as MediaRecord[];\n }\n\n async delete(id: string): Promise<void> {\n await this.db.delete(mediaTable).where(eq(mediaTable.id, id));\n }\n\n async nextOrder(ownerType: string, ownerId: string, collection: string): Promise<number> {\n const rows = await this.db\n .select({ max: max(mediaTable.order) })\n .from(mediaTable)\n .where(\n and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n ),\n );\n const top = rows[0]?.max;\n return top == null ? 0 : Number(top) + 1;\n }\n}\n","import { Attachment, type AttachmentData } from '@dudousxd/nestjs-media-core';\nimport { customType } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) custom column for an Attachment value:\n * `avatar: attachment('avatar')` → stored as JSON text, rehydrated to an `Attachment`.\n */\nexport const attachment = customType<{ data: Attachment | null; driverData: string }>({\n dataType() {\n return 'text';\n },\n toDriver(value: Attachment | null): string {\n return JSON.stringify(value ? value.toJSON() : null);\n },\n fromDriver(value: string): Attachment | null {\n return Attachment.fromJSON(value ? (JSON.parse(value) as AttachmentData) : null);\n },\n});\n"],"mappings":";;;;AAAA,SAASA,SAASC,aAAaC,YAAY;AAOpC,IAAMC,aAAaF,YAAY,SAAS;EAC7CG,IAAIF,KAAK,IAAA,EAAMG,WAAU;EACzBC,WAAWJ,KAAK,YAAA,EAAcK,QAAO;EACrCC,SAASN,KAAK,U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A4B,IAAA;EAC7E;AACF,CAAA;","names":["integer","sqliteTable","text","mediaTable","id","primaryKey","ownerType","notNull","ownerId","collection","name","fileName","mimeType","size","disk","path","order","customProperties","mode","conversions","createdAt","updatedAt","and","asc","eq","max","sql","createMediaTable","db","run","sql","DrizzleMediaStore","save","record","insert","mediaTable","values","onConflictDoUpdate","target","id","set","find","rows","select","from","where","eq","limit","listByOwner","ownerType","ownerId","collection","undefined","and","orderBy","asc","order","delete","nextOrder","max","top","Number","Attachment","customType","attachment","dataType","toDriver","value","JSON","stringify","toJSON","fromDriver","fromJSON","parse"]}
1
+ {"version":3,"sources":["../src/media.schema.ts","../src/drizzle-media-store.ts","../src/attachment.column.ts"],"sourcesContent":["import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) media table. `order` maps to the `position` column. JSON columns\n * use text(mode:'json'). Postgres/MySQL variants follow the same shape via their\n * respective drizzle cores.\n */\nexport const mediaTable = sqliteTable(\n 'media',\n {\n id: text('id').primaryKey(),\n ownerType: text('owner_type').notNull(),\n ownerId: text('owner_id').notNull(),\n collection: text('collection').notNull(),\n name: text('name').notNull(),\n fileName: text('file_name').notNull(),\n mimeType: text('mime_type').notNull(),\n size: integer('size').notNull(),\n disk: text('disk').notNull(),\n path: text('path').notNull(),\n order: integer('position').notNull(),\n customProperties: text('custom_properties', { mode: 'json' }).notNull(),\n conversions: text('conversions', { mode: 'json' }).notNull(),\n createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),\n updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),\n },\n (table) => ({\n ownerIdx: index('idx_media_owner').on(table.ownerType, table.ownerId, table.collection),\n collectionIdx: index('idx_media_collection').on(table.collection),\n diskIdx: index('idx_media_disk').on(table.disk),\n createdAtIdx: index('idx_media_created_at').on(table.createdAt),\n }),\n);\n","import type {\n MediaAggregateQuery,\n MediaAggregateResult,\n MediaCountFilter,\n MediaRecord,\n MediaStore,\n} from '@dudousxd/nestjs-media-core';\nimport { and, asc, count, eq, max, sql, sum } from 'drizzle-orm';\nimport type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';\nimport { mediaTable } from './media.schema';\n\ntype DB = BetterSQLite3Database<Record<string, never>>;\n\n/**\n * Migration-first (§3.10): Drizzle has no auto-ensure. Run migrations with\n * drizzle-kit in production; this helper creates the table for tests/dev.\n */\nexport function createMediaTable(db: DB): void {\n db.run(sql`\n CREATE TABLE IF NOT EXISTS media (\n id text PRIMARY KEY NOT NULL,\n owner_type text NOT NULL,\n owner_id text NOT NULL,\n collection text NOT NULL,\n name text NOT NULL,\n file_name text NOT NULL,\n mime_type text NOT NULL,\n size integer NOT NULL,\n disk text NOT NULL,\n path text NOT NULL,\n position integer NOT NULL,\n custom_properties text NOT NULL,\n conversions text NOT NULL,\n created_at integer NOT NULL,\n updated_at integer NOT NULL\n )\n `);\n db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_collection ON media (collection)`);\n db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_disk ON media (disk)`);\n db.run(sql`CREATE INDEX IF NOT EXISTS idx_media_created_at ON media (created_at)`);\n}\n\n/** MediaStore backed by Drizzle (better-sqlite3). POJO receiving the drizzle db. */\nexport class DrizzleMediaStore implements MediaStore {\n constructor(private readonly db: DB) {}\n\n async save(record: MediaRecord): Promise<MediaRecord> {\n await this.db\n .insert(mediaTable)\n .values(record)\n .onConflictDoUpdate({ target: mediaTable.id, set: record });\n return record;\n }\n\n async find(id: string): Promise<MediaRecord | null> {\n const rows = await this.db.select().from(mediaTable).where(eq(mediaTable.id, id)).limit(1);\n return (rows[0] as MediaRecord | undefined) ?? null;\n }\n\n async listByOwner(\n ownerType: string,\n ownerId: string,\n collection?: string,\n ): Promise<MediaRecord[]> {\n const where =\n collection === undefined\n ? and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId))\n : and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n );\n const rows = await this.db\n .select()\n .from(mediaTable)\n .where(where)\n .orderBy(asc(mediaTable.order));\n return rows as MediaRecord[];\n }\n\n async delete(id: string): Promise<void> {\n await this.db.delete(mediaTable).where(eq(mediaTable.id, id));\n }\n\n async nextOrder(ownerType: string, ownerId: string, collection: string): Promise<number> {\n const rows = await this.db\n .select({ max: max(mediaTable.order) })\n .from(mediaTable)\n .where(\n and(\n eq(mediaTable.ownerType, ownerType),\n eq(mediaTable.ownerId, ownerId),\n eq(mediaTable.collection, collection),\n ),\n );\n const top = rows[0]?.max;\n return top == null ? 0 : Number(top) + 1;\n }\n\n async count(filter: MediaCountFilter = {}): Promise<number> {\n const conditions = [\n ...(filter.ownerType !== undefined ? [eq(mediaTable.ownerType, filter.ownerType)] : []),\n ...(filter.collection !== undefined ? [eq(mediaTable.collection, filter.collection)] : []),\n ...(filter.disk !== undefined ? [eq(mediaTable.disk, filter.disk)] : []),\n ];\n const rows = await this.db\n .select({ value: count() })\n .from(mediaTable)\n .where(conditions.length ? and(...conditions) : undefined);\n return Number(rows[0]?.value ?? 0);\n }\n\n async aggregate(query: MediaAggregateQuery): Promise<MediaAggregateResult> {\n const column = query.groupBy === 'collection' ? mediaTable.collection : mediaTable.disk;\n const rows = await this.db\n .select({ key: column, count: count(), sumSize: sum(mediaTable.size) })\n .from(mediaTable)\n .groupBy(column);\n return rows.map((row) => ({\n key: row.key,\n count: Number(row.count),\n sumSize: query.sum === 'size' ? Number(row.sumSize ?? 0) : 0,\n }));\n }\n}\n","import { Attachment, type AttachmentData } from '@dudousxd/nestjs-media-core';\nimport { customType } from 'drizzle-orm/sqlite-core';\n\n/**\n * Drizzle (sqlite) custom column for an Attachment value:\n * `avatar: attachment('avatar')` → stored as JSON text, rehydrated to an `Attachment`.\n */\nexport const attachment = customType<{ data: Attachment | null; driverData: string }>({\n dataType() {\n return 'text';\n },\n toDriver(value: Attachment | null): string {\n return JSON.stringify(value ? value.toJSON() : null);\n },\n fromDriver(value: string): Attachment | null {\n return Attachment.fromJSON(value ? (JSON.parse(value) as AttachmentData) : null);\n },\n});\n"],"mappings":";;;;AAAA,SAASA,OAAOC,SAASC,aAAaC,YAAY;AAO3C,IAAMC,aAAaF,YACxB,SACA;EACEG,IAAIF,KAAK,IAAA,EAAMG,WAAU;EACzBC,WAAWJ,KAAK,YAAA,EAAcK,QAAO;EACrCC,SAASN,KAAK,UAAA,EAAYK,QAAO;EACjCE,YAAYP,KAAK,YAAA,EAAcK,QAAO;EACtCG,MAAMR,KAAK,MAAA,EAAQK,QAAO;EAC1BI,UAAUT,KAAK,WAAA,EAAaK,QAAO;EACnCK,UAAUV,KAAK,WAAA,EAAaK,QAAO;EACnCM,MAAMb,QAAQ,MAAA,EAAQO,QAAO;EAC7BO,MAAMZ,KAAK,MAAA,EAAQK,QAAO;EAC1BQ,MAAMb,KAAK,MAAA,EAAQK,QAAO;EAC1BS,OAAOhB,QAAQ,UAAA,EAAYO,QAAO;EAClCU,kBAAkBf,KAAK,qBAAqB;IAAEgB,MAAM;EAAO,CAAA,EAAGX,QAAO;EACrEY,aAAajB,KAAK,eAAe;IAAEgB,MAAM;EAAO,CAAA,EAAGX,QAAO;EAC1Da,WAAWpB,QAAQ,cAAc;IAAEkB,MAAM;EAAe,CAAA,EAAGX,QAAO;EAClEc,WAAWrB,QAAQ,cAAc;IAAEkB,MAAM;EAAe,CAAA,EAAGX,QAAO;AACpE,GACA,CAACe,WAAW;EACVC,UAAUxB,MAAM,iBAAA,EAAmByB,GAAGF,MAAMhB,WAAWgB,MAAMd,SAASc,MAAMb,UAAU;EACtFgB,eAAe1B,MAAM,sBAAA,EAAwByB,GAAGF,MAAMb,UAAU;EAChEiB,SAAS3B,MAAM,gBAAA,EAAkByB,GAAGF,MAAMR,IAAI;EAC9Ca,cAAc5B,MAAM,sBAAA,EAAwByB,GAAGF,MAAMF,SAAS;AAChE,EAAA;;;ACxBF,SAASQ,KAAKC,KAAKC,OAAOC,IAAIC,KAAKC,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AKK,IAAIL;MACTV,OAAOD,OAAOgB,IAAIf,KAAK;MACvBW,SAASJ,MAAMK,QAAQ,SAASb,OAAOgB,IAAIJ,WAAW,CAAA,IAAK;IAC7D,EAAA;EACF;AACF;;;AC5HA,SAASK,kBAAuC;AAChD,SAASC,kBAAkB;AAMpB,IAAMC,aAAaD,WAA4D;EACpFE,WAAAA;AACE,WAAO;EACT;EACAC,SAASC,OAAwB;AAC/B,WAAOC,KAAKC,UAAUF,QAAQA,MAAMG,OAAM,IAAK,IAAA;EACjD;EACAC,WAAWJ,OAAa;AACtB,WAAOL,WAAWU,SAASL,QAASC,KAAKK,MAAMN,KAAAA,IAA4B,IAAA;EAC7E;AACF,CAAA;","names":["index","integer","sqliteTable","text","mediaTable","id","primaryKey","ownerType","notNull","ownerId","collection","name","fileName","mimeType","size","disk","path","order","customProperties","mode","conversions","createdAt","updatedAt","table","ownerIdx","on","collectionIdx","diskIdx","createdAtIdx","and","asc","count","eq","max","sql","sum","createMediaTable","db","run","sql","DrizzleMediaStore","save","record","insert","mediaTable","values","onConflictDoUpdate","target","id","set","find","rows","select","from","where","eq","limit","listByOwner","ownerType","ownerId","collection","undefined","and","orderBy","asc","order","delete","nextOrder","max","top","Number","count","filter","conditions","disk","value","length","aggregate","query","column","groupBy","key","sumSize","sum","size","map","row","Attachment","customType","attachment","dataType","toDriver","value","JSON","stringify","toJSON","fromDriver","fromJSON","parse"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudousxd/nestjs-media-database-drizzle",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "description": "nestjs-media Drizzle media store (sqlite)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -24,15 +24,15 @@
24
24
  ],
25
25
  "peerDependencies": {
26
26
  "drizzle-orm": "^0.38.0",
27
- "@dudousxd/nestjs-media-core": "0.6.4"
27
+ "@dudousxd/nestjs-media-core": "0.6.6"
28
28
  },
29
29
  "devDependencies": {
30
30
  "better-sqlite3": "11.8.1",
31
31
  "drizzle-orm": "0.38.4",
32
32
  "tsup": "8.3.5",
33
33
  "typescript": "5.9.3",
34
- "@dudousxd/nestjs-media-core": "0.6.4",
35
- "@dudousxd/nestjs-media-testing": "0.5.4"
34
+ "@dudousxd/nestjs-media-core": "0.6.6",
35
+ "@dudousxd/nestjs-media-testing": "0.5.6"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "tsup",