@magnet-cms/adapter-db-drizzle 2.0.0 → 3.0.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.
Files changed (3) hide show
  1. package/dist/index.cjs +10478 -10477
  2. package/dist/index.js +201 -200
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { __commonJS, __name, __require, __toESM, __export } from './chunk-AAIPPTI5.js';
2
2
  import 'reflect-metadata';
3
- import { QueryBuilder, DatabaseAdapter, getModelToken, setDatabaseAdapter, getSchemaOptions, Model, DatabaseError, fromDrizzleError, DocumentNotFoundError } from '@magnet-cms/common';
3
+ import { QueryBuilder, DatabaseAdapter, getModelToken, setDatabaseAdapter, registerDatabaseAdapterSingletonForFeature, Model, DatabaseError, fromDrizzleError, DocumentNotFoundError, getSchemaOptions } from '@magnet-cms/common';
4
4
  import { Logger, Module, Injectable, Inject } from '@nestjs/common';
5
- import { createHash, randomUUID } from 'node:crypto';
6
- import { toSnakeCase, toCamelCase, pluralize } from '@magnet-cms/utils';
7
5
  import { and, or, eq, desc, asc, sql, isNotNull, isNull, ilike, like, notInArray, inArray, lte, lt, gte, gt, ne } from 'drizzle-orm';
8
- import { getTableConfig, varchar, timestamp, uuid, pgTable, uniqueIndex, index, text, doublePrecision, boolean, jsonb } from 'drizzle-orm/pg-core';
9
6
  import { drizzle } from 'drizzle-orm/node-postgres';
7
+ import { getTableConfig, varchar, timestamp, uuid, pgTable, uniqueIndex, index, text, doublePrecision, boolean, jsonb } from 'drizzle-orm/pg-core';
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { toSnakeCase, toCamelCase, pluralize } from '@magnet-cms/utils';
10
10
  import { readdir, mkdir, writeFile, readFile } from 'node:fs/promises';
11
11
  import { join } from 'node:path';
12
12
 
@@ -5249,189 +5249,19 @@ var require_lib2 = __commonJS({
5249
5249
  }
5250
5250
  });
5251
5251
 
5252
- // src/decorators/schema.decorator.ts
5253
- var DRIZZLE_SCHEMA_KEY = "drizzle:schema";
5254
- function Schema(options) {
5255
- return (target) => {
5256
- Reflect.defineMetadata(DRIZZLE_SCHEMA_KEY, {
5257
- name: target.name,
5258
- tableName: `${target.name.toLowerCase()}s`,
5259
- i18n: options?.i18n ?? true,
5260
- versioning: options?.versioning ?? true
5261
- }, target);
5262
- };
5263
- }
5264
- __name(Schema, "Schema");
5265
- function getDrizzleSchemaMetadata(target) {
5266
- return Reflect.getMetadata(DRIZZLE_SCHEMA_KEY, target) || null;
5267
- }
5268
- __name(getDrizzleSchemaMetadata, "getDrizzleSchemaMetadata");
5269
-
5270
- // src/decorators/prop.decorator.ts
5271
- var DRIZZLE_PROPS_KEY = "drizzle:props";
5272
- function Prop(options) {
5273
- return (target, propertyKey) => {
5274
- const existingProps = Reflect.getMetadata(DRIZZLE_PROPS_KEY, target.constructor) || /* @__PURE__ */ new Map();
5275
- existingProps.set(propertyKey, {
5276
- ...options,
5277
- type: options?.type || Reflect.getMetadata("design:type", target, propertyKey)
5278
- });
5279
- Reflect.defineMetadata(DRIZZLE_PROPS_KEY, existingProps, target.constructor);
5280
- };
5281
- }
5282
- __name(Prop, "Prop");
5283
- function getDrizzlePropsMetadata(target) {
5284
- return Reflect.getMetadata(DRIZZLE_PROPS_KEY, target) || /* @__PURE__ */ new Map();
5285
- }
5286
- __name(getDrizzlePropsMetadata, "getDrizzlePropsMetadata");
5287
- function InjectModel(schema) {
5288
- return Inject(getModelToken(schema));
5289
- }
5290
- __name(InjectModel, "InjectModel");
5291
- var DOCUMENT_STATUS = {
5292
- DRAFT: "draft",
5293
- PUBLISHED: "published",
5294
- ARCHIVED: "archived"
5295
- };
5296
- var DEFAULT_LOCALE = "en";
5297
- function applyDocumentColumns(options) {
5298
- const columns = {};
5299
- if (options.hasI18n || options.hasVersioning) {
5300
- columns.documentId = varchar("document_id", {
5301
- length: 36
5302
- }).notNull();
5303
- columns.locale = varchar("locale", {
5304
- length: 10
5305
- }).notNull().default(DEFAULT_LOCALE);
5306
- columns.status = varchar("status", {
5307
- length: 20
5308
- }).notNull().default(DOCUMENT_STATUS.DRAFT);
5309
- columns.publishedAt = timestamp("published_at");
5310
- }
5311
- return columns;
5312
- }
5313
- __name(applyDocumentColumns, "applyDocumentColumns");
5314
- function isDraft(record) {
5315
- return record.status === DOCUMENT_STATUS.DRAFT;
5316
- }
5317
- __name(isDraft, "isDraft");
5318
- function isPublished(record) {
5319
- return record.status === DOCUMENT_STATUS.PUBLISHED;
5320
- }
5321
- __name(isPublished, "isPublished");
5322
-
5323
- // src/schema/schema.generator.ts
5324
- var schemaRegistry = /* @__PURE__ */ new Map();
5325
- function getOrGenerateSchema(schemaClass) {
5326
- const className = schemaClass.name;
5327
- if (schemaRegistry.has(className)) {
5328
- return schemaRegistry.get(className);
5329
- }
5330
- const generated = generateSchema(schemaClass);
5331
- schemaRegistry.set(className, generated);
5332
- return generated;
5333
- }
5334
- __name(getOrGenerateSchema, "getOrGenerateSchema");
5335
- function generateSchema(schemaClass) {
5336
- const schemaOptions = getSchemaOptions(schemaClass);
5337
- const propsMetadata = getDrizzlePropsMetadata(schemaClass);
5338
- const tableName = pluralize(schemaClass.name.toLowerCase());
5339
- const hasI18n = schemaOptions.i18n !== false;
5340
- const hasVersioning = schemaOptions.versioning !== false;
5341
- let hasIntlProps = false;
5342
- propsMetadata.forEach((options) => {
5343
- if (options.intl) {
5344
- hasIntlProps = true;
5345
- }
5346
- });
5347
- const columns = {
5348
- // Primary key - always UUID
5349
- // $defaultFn generates UUIDs in JS (works on all dialects: PostgreSQL, MySQL, SQLite)
5350
- // Note: SQL .default(gen_random_uuid()) is intentionally omitted because it conflicts
5351
- // with $defaultFn when using pg-core types on non-PostgreSQL drivers.
5352
- // The createTableFromConfig() method adds dialect-appropriate SQL DEFAULT for direct inserts.
5353
- id: uuid("id").primaryKey().$defaultFn(() => randomUUID())
5354
- };
5355
- if (hasI18n || hasVersioning || hasIntlProps) {
5356
- const docOptions = {
5357
- hasI18n: hasI18n || hasIntlProps,
5358
- hasVersioning
5359
- };
5360
- Object.assign(columns, applyDocumentColumns(docOptions));
5361
- }
5362
- propsMetadata.forEach((options, propertyKey) => {
5363
- const columnName = String(propertyKey);
5364
- const column = generateColumn(columnName, options);
5365
- if (column) {
5366
- columns[columnName] = column;
5367
- }
5368
- });
5369
- columns.createdAt = timestamp("created_at").notNull();
5370
- columns.updatedAt = timestamp("updated_at").notNull();
5371
- const table = pgTable(tableName, columns, (table2) => {
5372
- const tableIndexes = {};
5373
- const t = table2;
5374
- if (hasI18n || hasIntlProps) {
5375
- tableIndexes.documentLocaleStatusIdx = uniqueIndex(`${tableName}_document_locale_status_idx`).on(t.documentId, t.locale, t.status);
5376
- tableIndexes.documentLocaleIdx = index(`${tableName}_document_locale_idx`).on(t.documentId, t.locale);
5377
- tableIndexes.statusLocaleIdx = index(`${tableName}_status_locale_idx`).on(t.status, t.locale);
5378
- }
5379
- propsMetadata.forEach((options, propertyKey) => {
5380
- if (options.unique) {
5381
- const columnName = String(propertyKey);
5382
- if (hasI18n || hasIntlProps) {
5383
- const whereCondition = and(eq(t.locale, "en"), eq(t.status, "draft"));
5384
- tableIndexes[`${columnName}UniqueI18n`] = uniqueIndex(`${tableName}_${columnName}_unique_i18n`).on(t[columnName]).where(whereCondition);
5385
- } else {
5386
- tableIndexes[`${columnName}Unique`] = uniqueIndex(`${tableName}_${columnName}_unique`).on(t[columnName]);
5387
- }
5388
- }
5389
- });
5390
- return tableIndexes;
5391
- });
5392
- return {
5393
- table,
5394
- tableName
5395
- };
5396
- }
5397
- __name(generateSchema, "generateSchema");
5398
- function generateColumn(columnName, options) {
5399
- const snakeCaseName = toSnakeCase(columnName);
5400
- let column;
5401
- const type = options.type;
5402
- if (type === String || type === void 0) {
5403
- column = text(snakeCaseName);
5404
- } else if (type === Number) {
5405
- column = doublePrecision(snakeCaseName);
5406
- } else if (type === Boolean) {
5407
- column = boolean(snakeCaseName);
5408
- } else if (type === Date) {
5409
- column = timestamp(snakeCaseName);
5410
- } else if (Array.isArray(type) || type === Array) {
5411
- column = jsonb(snakeCaseName);
5412
- } else if (typeof type === "object") {
5413
- column = jsonb(snakeCaseName);
5414
- } else if (options.ref) {
5415
- column = uuid(snakeCaseName);
5416
- } else {
5417
- column = text(snakeCaseName);
5418
- }
5419
- if (options.default !== void 0) {
5420
- if (Array.isArray(options.default) && options.default.length === 0) ; else {
5421
- column = column.default(options.default);
5422
- }
5423
- }
5424
- return column;
5425
- }
5426
- __name(generateColumn, "generateColumn");
5427
- function getRegisteredSchemas() {
5428
- return schemaRegistry;
5429
- }
5430
- __name(getRegisteredSchemas, "getRegisteredSchemas");
5431
- function clearSchemaRegistry() {
5432
- schemaRegistry.clear();
5433
- }
5434
- __name(clearSchemaRegistry, "clearSchemaRegistry");
5252
+ // ../../../node_modules/pg/esm/index.mjs
5253
+ var import_lib = __toESM(require_lib2(), 1);
5254
+ import_lib.default.Client;
5255
+ var Pool = import_lib.default.Pool;
5256
+ import_lib.default.Connection;
5257
+ import_lib.default.types;
5258
+ import_lib.default.Query;
5259
+ import_lib.default.DatabaseError;
5260
+ import_lib.default.escapeIdentifier;
5261
+ import_lib.default.escapeLiteral;
5262
+ import_lib.default.Result;
5263
+ import_lib.default.TypeOverrides;
5264
+ import_lib.default.defaults;
5435
5265
 
5436
5266
  // src/dialects/neon.ts
5437
5267
  async function createNeonConnection(config) {
@@ -5475,19 +5305,23 @@ async function createNeonWebSocketConnection(config) {
5475
5305
  }
5476
5306
  __name(createNeonWebSocketConnection, "createNeonWebSocketConnection");
5477
5307
 
5478
- // ../../../node_modules/pg/esm/index.mjs
5479
- var import_lib = __toESM(require_lib2(), 1);
5480
- import_lib.default.Client;
5481
- var Pool = import_lib.default.Pool;
5482
- import_lib.default.Connection;
5483
- import_lib.default.types;
5484
- import_lib.default.Query;
5485
- import_lib.default.DatabaseError;
5486
- import_lib.default.escapeIdentifier;
5487
- import_lib.default.escapeLiteral;
5488
- import_lib.default.Result;
5489
- import_lib.default.TypeOverrides;
5490
- import_lib.default.defaults;
5308
+ // src/decorators/prop.decorator.ts
5309
+ var DRIZZLE_PROPS_KEY = "drizzle:props";
5310
+ function Prop(options) {
5311
+ return (target, propertyKey) => {
5312
+ const existingProps = Reflect.getMetadata(DRIZZLE_PROPS_KEY, target.constructor) || /* @__PURE__ */ new Map();
5313
+ existingProps.set(propertyKey, {
5314
+ ...options,
5315
+ type: options?.type || Reflect.getMetadata("design:type", target, propertyKey)
5316
+ });
5317
+ Reflect.defineMetadata(DRIZZLE_PROPS_KEY, existingProps, target.constructor);
5318
+ };
5319
+ }
5320
+ __name(Prop, "Prop");
5321
+ function getDrizzlePropsMetadata(target) {
5322
+ return Reflect.getMetadata(DRIZZLE_PROPS_KEY, target) || /* @__PURE__ */ new Map();
5323
+ }
5324
+ __name(getDrizzlePropsMetadata, "getDrizzlePropsMetadata");
5491
5325
  var LazyQueryBuilder = class extends QueryBuilder {
5492
5326
  static {
5493
5327
  __name(this, "LazyQueryBuilder");
@@ -5910,6 +5744,37 @@ var DrizzleQueryBuilder = class extends QueryBuilder {
5910
5744
  return result;
5911
5745
  }
5912
5746
  };
5747
+ var DOCUMENT_STATUS = {
5748
+ DRAFT: "draft",
5749
+ PUBLISHED: "published",
5750
+ ARCHIVED: "archived"
5751
+ };
5752
+ var DEFAULT_LOCALE = "en";
5753
+ function applyDocumentColumns(options) {
5754
+ const columns = {};
5755
+ if (options.hasI18n || options.hasVersioning) {
5756
+ columns.documentId = varchar("document_id", {
5757
+ length: 36
5758
+ }).notNull();
5759
+ columns.locale = varchar("locale", {
5760
+ length: 10
5761
+ }).notNull().default(DEFAULT_LOCALE);
5762
+ columns.status = varchar("status", {
5763
+ length: 20
5764
+ }).notNull().default(DOCUMENT_STATUS.DRAFT);
5765
+ columns.publishedAt = timestamp("published_at");
5766
+ }
5767
+ return columns;
5768
+ }
5769
+ __name(applyDocumentColumns, "applyDocumentColumns");
5770
+ function isDraft(record) {
5771
+ return record.status === DOCUMENT_STATUS.DRAFT;
5772
+ }
5773
+ __name(isDraft, "isDraft");
5774
+ function isPublished(record) {
5775
+ return record.status === DOCUMENT_STATUS.PUBLISHED;
5776
+ }
5777
+ __name(isPublished, "isPublished");
5913
5778
 
5914
5779
  // src/drizzle.model.ts
5915
5780
  function isSQLiteDriver(db) {
@@ -6863,6 +6728,119 @@ var MigrationRunner = class {
6863
6728
  };
6864
6729
  }
6865
6730
  };
6731
+ var schemaRegistry = /* @__PURE__ */ new Map();
6732
+ function getOrGenerateSchema(schemaClass) {
6733
+ const className = schemaClass.name;
6734
+ if (schemaRegistry.has(className)) {
6735
+ return schemaRegistry.get(className);
6736
+ }
6737
+ const generated = generateSchema(schemaClass);
6738
+ schemaRegistry.set(className, generated);
6739
+ return generated;
6740
+ }
6741
+ __name(getOrGenerateSchema, "getOrGenerateSchema");
6742
+ function generateSchema(schemaClass) {
6743
+ const schemaOptions = getSchemaOptions(schemaClass);
6744
+ const propsMetadata = getDrizzlePropsMetadata(schemaClass);
6745
+ const tableName = pluralize(schemaClass.name.toLowerCase());
6746
+ const hasI18n = schemaOptions.i18n !== false;
6747
+ const hasVersioning = schemaOptions.versioning !== false;
6748
+ let hasIntlProps = false;
6749
+ propsMetadata.forEach((options) => {
6750
+ if (options.intl) {
6751
+ hasIntlProps = true;
6752
+ }
6753
+ });
6754
+ const columns = {
6755
+ // Primary key - always UUID
6756
+ // $defaultFn generates UUIDs in JS (works on all dialects: PostgreSQL, MySQL, SQLite)
6757
+ // Note: SQL .default(gen_random_uuid()) is intentionally omitted because it conflicts
6758
+ // with $defaultFn when using pg-core types on non-PostgreSQL drivers.
6759
+ // The createTableFromConfig() method adds dialect-appropriate SQL DEFAULT for direct inserts.
6760
+ id: uuid("id").primaryKey().$defaultFn(() => randomUUID())
6761
+ };
6762
+ if (hasI18n || hasVersioning || hasIntlProps) {
6763
+ const docOptions = {
6764
+ hasI18n: hasI18n || hasIntlProps,
6765
+ hasVersioning
6766
+ };
6767
+ Object.assign(columns, applyDocumentColumns(docOptions));
6768
+ }
6769
+ propsMetadata.forEach((options, propertyKey) => {
6770
+ const columnName = String(propertyKey);
6771
+ const column = generateColumn(columnName, options);
6772
+ if (column) {
6773
+ columns[columnName] = column;
6774
+ }
6775
+ });
6776
+ columns.createdAt = timestamp("created_at").notNull();
6777
+ columns.updatedAt = timestamp("updated_at").notNull();
6778
+ const table = pgTable(tableName, columns, (table2) => {
6779
+ const tableIndexes = {};
6780
+ const t = table2;
6781
+ if (hasI18n || hasIntlProps) {
6782
+ tableIndexes.documentLocaleStatusIdx = uniqueIndex(`${tableName}_document_locale_status_idx`).on(t.documentId, t.locale, t.status);
6783
+ tableIndexes.documentLocaleIdx = index(`${tableName}_document_locale_idx`).on(t.documentId, t.locale);
6784
+ tableIndexes.statusLocaleIdx = index(`${tableName}_status_locale_idx`).on(t.status, t.locale);
6785
+ }
6786
+ propsMetadata.forEach((options, propertyKey) => {
6787
+ if (options.unique) {
6788
+ const columnName = String(propertyKey);
6789
+ if (hasI18n || hasIntlProps) {
6790
+ const whereCondition = and(eq(t.locale, "en"), eq(t.status, "draft"));
6791
+ tableIndexes[`${columnName}UniqueI18n`] = uniqueIndex(`${tableName}_${columnName}_unique_i18n`).on(t[columnName]).where(whereCondition);
6792
+ } else {
6793
+ tableIndexes[`${columnName}Unique`] = uniqueIndex(`${tableName}_${columnName}_unique`).on(t[columnName]);
6794
+ }
6795
+ }
6796
+ });
6797
+ return tableIndexes;
6798
+ });
6799
+ return {
6800
+ table,
6801
+ tableName
6802
+ };
6803
+ }
6804
+ __name(generateSchema, "generateSchema");
6805
+ function generateColumn(columnName, options) {
6806
+ const snakeCaseName = toSnakeCase(columnName);
6807
+ let column;
6808
+ const type = options.type;
6809
+ if (type === String || type === void 0) {
6810
+ column = text(snakeCaseName);
6811
+ } else if (type === Number) {
6812
+ column = doublePrecision(snakeCaseName);
6813
+ } else if (type === Boolean) {
6814
+ column = boolean(snakeCaseName);
6815
+ } else if (type === Date) {
6816
+ column = timestamp(snakeCaseName);
6817
+ } else if (Array.isArray(type) || type === Array) {
6818
+ column = jsonb(snakeCaseName);
6819
+ } else if (typeof type === "object") {
6820
+ column = jsonb(snakeCaseName);
6821
+ } else if (options.ref) {
6822
+ column = uuid(snakeCaseName);
6823
+ } else {
6824
+ column = text(snakeCaseName);
6825
+ }
6826
+ if (options.default !== void 0) {
6827
+ if (Array.isArray(options.default) && options.default.length === 0) ; else {
6828
+ column = column.default(options.default);
6829
+ }
6830
+ }
6831
+ return column;
6832
+ }
6833
+ __name(generateColumn, "generateColumn");
6834
+ function getRegisteredSchemas() {
6835
+ return schemaRegistry;
6836
+ }
6837
+ __name(getRegisteredSchemas, "getRegisteredSchemas");
6838
+ function clearSchemaRegistry() {
6839
+ schemaRegistry.clear();
6840
+ }
6841
+ __name(clearSchemaRegistry, "clearSchemaRegistry");
6842
+
6843
+ // src/migrations/schema-bridge.ts
6866
6844
  function sanitizeExecutableMigrationSql(dialect, statement) {
6867
6845
  if (dialect !== "postgresql") return statement;
6868
6846
  if (!statement.includes("$")) return statement;
@@ -7766,6 +7744,28 @@ DrizzleDatabaseAdapter = _ts_decorate([
7766
7744
  ], DrizzleDatabaseAdapter);
7767
7745
  var Adapter = DrizzleDatabaseAdapter.getInstance();
7768
7746
 
7747
+ // src/decorators/schema.decorator.ts
7748
+ var DRIZZLE_SCHEMA_KEY = "drizzle:schema";
7749
+ function Schema(options) {
7750
+ return (target) => {
7751
+ Reflect.defineMetadata(DRIZZLE_SCHEMA_KEY, {
7752
+ name: target.name,
7753
+ tableName: `${target.name.toLowerCase()}s`,
7754
+ i18n: options?.i18n ?? true,
7755
+ versioning: options?.versioning ?? true
7756
+ }, target);
7757
+ };
7758
+ }
7759
+ __name(Schema, "Schema");
7760
+ function getDrizzleSchemaMetadata(target) {
7761
+ return Reflect.getMetadata(DRIZZLE_SCHEMA_KEY, target) || null;
7762
+ }
7763
+ __name(getDrizzleSchemaMetadata, "getDrizzleSchemaMetadata");
7764
+ function InjectModel(schema) {
7765
+ return Inject(getModelToken(schema));
7766
+ }
7767
+ __name(InjectModel, "InjectModel");
7768
+
7769
7769
  // src/migrations/sql-generators/index.ts
7770
7770
  var sql_generators_exports = {};
7771
7771
  __export(sql_generators_exports, {
@@ -7930,5 +7930,6 @@ __name(dropIndex3, "dropIndex");
7930
7930
 
7931
7931
  // src/index.ts
7932
7932
  setDatabaseAdapter("drizzle");
7933
+ registerDatabaseAdapterSingletonForFeature(() => DrizzleDatabaseAdapter.getInstance());
7933
7934
 
7934
7935
  export { Adapter, AutoMigration, DEFAULT_LOCALE, DEFAULT_MIGRATION_CONFIG, DOCUMENT_STATUS, DRIZZLE_CONFIG, DRIZZLE_DB, DrizzleDatabaseAdapter, DrizzleQueryBuilder, InjectModel, LazyQueryBuilder, MigrationChecksumError, MigrationError, MigrationGenerator, MigrationHistory, MigrationLock, MigrationLockError, MigrationRunner, Prop, SNAPSHOT_FILENAME, Schema, SchemaBridge, SchemaDiff, applyDocumentColumns, clearSchemaRegistry, createNeonConnection, createNeonWebSocketConnection, generateSchema, getDrizzleModelToken, getDrizzlePropsMetadata, getDrizzleSchemaMetadata, getOrGenerateSchema, getRegisteredSchemas, isDraft, isPublished, sanitizeExecutableMigrationSql, sql_generators_exports as sqlGenerators };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magnet-cms/adapter-db-drizzle",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "Drizzle ORM database adapter for Magnet CMS - supports PostgreSQL, MySQL, and SQLite",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -42,7 +42,7 @@
42
42
  "reflect-metadata": "0.2.2"
43
43
  },
44
44
  "peerDependencies": {
45
- "@magnet-cms/common": "^0.2.0",
45
+ "@magnet-cms/common": "^0.3.0",
46
46
  "@magnet-cms/utils": "^0.1.1",
47
47
  "@nestjs/common": "^11.1.12",
48
48
  "drizzle-orm": "^0.38.0",