@entro314labs/entro-auth-drizzle-adapter 0.0.0-stage → 1.8.0-beta.11

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/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the “Software”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # Entro Auth Drizzle Adapter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Drizzle ORM adapter for [Entro Auth](https://www.better-auth.com).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @entro314labs/entro-auth-drizzle-adapter
9
+ ```
10
+
11
+ ## Documentation
12
+
13
+ For full documentation, visit [better-auth.com/docs/adapters/drizzle](https://www.better-auth.com/docs/adapters/drizzle).
14
+
15
+ ## License
16
+
17
+ MIT
@@ -0,0 +1,16 @@
1
+ import { DrizzleAdapterConfig } from "./index.mjs";
2
+ import { DBAdapterSchemaCreation } from "@entro314labs/entro-auth-core/db/adapter";
3
+ import { EntroAuthDBSchema } from "@entro314labs/entro-auth-core/db";
4
+ import { EntroAuthOptions } from "@entro314labs/entro-auth-core";
5
+ interface SchemaGenerator {
6
+ <Options extends EntroAuthOptions>(opts: {
7
+ file?: string;
8
+ options: Options;
9
+ provider: "sqlite" | "mysql" | "pg";
10
+ adapterConfig: DrizzleAdapterConfig;
11
+ camelCase?: boolean;
12
+ tables?: EntroAuthDBSchema;
13
+ }): Promise<DBAdapterSchemaCreation>;
14
+ }
15
+ export declare const generateDrizzleSchema: SchemaGenerator;
16
+ export {};
@@ -0,0 +1,365 @@
1
+ import { initGetFieldName, initGetModelName } from "@entro314labs/entro-auth-core/db/adapter";
2
+ import { getDatabaseFieldIndexName, getDatabaseIndexStringLength, resolveDatabaseSchemaIndexes } from "@entro314labs/entro-auth-core/db/internal";
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { getAuthTables } from "@entro314labs/entro-auth-core/db";
6
+ // src/generate-drizzle-schema.ts
7
+ function convertToSnakeCase(str, camelCase) {
8
+ if (camelCase) return str;
9
+ return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").toLowerCase();
10
+ }
11
+ /**
12
+ * Convert a schema namespace into a valid JavaScript identifier so it can be
13
+ * used as the `export const <name>Schema = pgSchema(...)` variable name.
14
+ * e.g. "my-auth" -> "myAuth", "123schema" -> "_123schema".
15
+ */
16
+ function toValidIdentifier(str) {
17
+ let result = str.replace(/[^a-zA-Z0-9]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
18
+ if (result.length > 0 && /[A-Z]/.test(result[0])) result = result[0].toLowerCase() + result.slice(1);
19
+ return result || "schema";
20
+ }
21
+ const generateDrizzleSchema = async ({ options, file, provider, adapterConfig, camelCase, tables: propsTables }) => {
22
+ const tables = propsTables ?? getAuthTables(options);
23
+ const filePath = file || "./auth-schema.ts";
24
+ const databaseType = provider;
25
+ const schemaName = adapterConfig?.schemaName;
26
+ if (!databaseType) throw new Error(`Database provider type is undefined during Drizzle schema generation. Please define a \`provider\` in the Drizzle adapter config. Read more at https://better-auth.com/docs/adapters/drizzle`);
27
+ const fileExist = existsSync(filePath);
28
+ let code = generateImport({
29
+ databaseType,
30
+ tables,
31
+ options,
32
+ schemaName
33
+ });
34
+ let schemaVarName;
35
+ if (databaseType === "pg" && schemaName) {
36
+ schemaVarName = `${toValidIdentifier(schemaName)}Schema`;
37
+ if (schemaVarName === "pgSchema") schemaVarName = "pgCustomSchema";
38
+ code += `\nexport const ${schemaVarName} = pgSchema(${JSON.stringify(schemaName)});\n`;
39
+ }
40
+ const tableFunction = databaseType === "pg" && schemaName && schemaVarName ? `${schemaVarName}.table` : `${databaseType}Table`;
41
+ const getModelName = initGetModelName({
42
+ schema: tables,
43
+ usePlural: adapterConfig?.usePlural
44
+ });
45
+ const getSingularModelName = initGetModelName({
46
+ schema: tables,
47
+ usePlural: false
48
+ });
49
+ const getFieldName = initGetFieldName({
50
+ schema: tables,
51
+ usePlural: adapterConfig?.usePlural
52
+ });
53
+ /**
54
+ * Whether a model, named by its key, its custom name or either in plural
55
+ * form, belongs to a table whose migrations are disabled.
56
+ */
57
+ const isMigrationDisabled = (model) => Object.entries(tables).some(([tableKey, table]) => {
58
+ if (table.disableMigrations !== true) return false;
59
+ const customModelName = table.modelName || tableKey;
60
+ return model === tableKey || model === customModelName || model === getModelName(tableKey) || model === getModelName(customModelName);
61
+ });
62
+ const resolvedIndexesByTable = resolveDatabaseSchemaIndexes(Object.keys(tables).filter((tableKey) => !isMigrationDisabled(tableKey)).map((tableKey) => ({
63
+ fields: tables[tableKey].fields,
64
+ indexes: tables[tableKey].indexes,
65
+ tableName: getModelName(tableKey)
66
+ })));
67
+ for (const tableKey in tables) {
68
+ const table = tables[tableKey];
69
+ if (table.disableMigrations) continue;
70
+ const modelName = getModelName(tableKey);
71
+ const fields = table.fields;
72
+ const resolvedTableIndexes = resolvedIndexesByTable.get(modelName) ?? [];
73
+ function getType(name, field, tableIndexStringLength) {
74
+ if (!databaseType) throw new Error(`Database provider type is undefined during Drizzle schema generation. Please define a \`provider\` in the Drizzle adapter config. Read more at https://better-auth.com/docs/adapters/drizzle`);
75
+ name = convertToSnakeCase(name, camelCase);
76
+ if (field.references?.field === "id") {
77
+ const useNumberId = options.advanced?.database?.generateId === "serial";
78
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
79
+ if (useNumberId) {
80
+ if (databaseType === "pg") return `integer('${name}')`;
81
+ else if (databaseType === "mysql") return `int('${name}')`;
82
+ else return `integer('${name}')`;
83
+ }
84
+ if (useUUIDs && databaseType === "pg") return `uuid('${name}')`;
85
+ if (field.references.field) {
86
+ if (databaseType === "mysql") return `varchar('${name}', { length: 36 })`;
87
+ }
88
+ return `text('${name}')`;
89
+ }
90
+ const type = field.type;
91
+ if (typeof type !== "string") {
92
+ if (Array.isArray(type) && type.every((x) => typeof x === "string")) return {
93
+ sqlite: `text('${name}', { enum: [${type.map((x) => `'${x}'`).join(", ")}] })`,
94
+ pg: `text('${name}', { enum: [${type.map((x) => `'${x}'`).join(", ")}] })`,
95
+ mysql: `mysqlEnum('${name}', [${type.map((x) => `'${x}'`).join(", ")}])`
96
+ }[databaseType];
97
+ else throw new TypeError(`Invalid field type for field ${name} in model ${modelName}`);
98
+ }
99
+ const dbTypeMap = {
100
+ string: {
101
+ sqlite: `text('${name}')`,
102
+ pg: `text('${name}')`,
103
+ mysql: tableIndexStringLength ? `varchar('${name}', { length: ${tableIndexStringLength} })` : field.unique ? `varchar('${name}', { length: 255 })` : field.references ? `varchar('${name}', { length: 36 })` : field.sortable ? `varchar('${name}', { length: 255 })` : field.index ? `varchar('${name}', { length: 255 })` : `text('${name}')`
104
+ },
105
+ boolean: {
106
+ sqlite: `integer('${name}', { mode: 'boolean' })`,
107
+ pg: `boolean('${name}')`,
108
+ mysql: `boolean('${name}')`
109
+ },
110
+ number: {
111
+ sqlite: `integer('${name}')`,
112
+ pg: field.bigint ? `bigint('${name}', { mode: 'number' })` : `integer('${name}')`,
113
+ mysql: field.bigint ? `bigint('${name}', { mode: 'number' })` : `int('${name}')`
114
+ },
115
+ date: {
116
+ sqlite: `integer('${name}', { mode: 'timestamp_ms' })`,
117
+ pg: `timestamp('${name}')`,
118
+ mysql: `timestamp('${name}', { fsp: 3 })`
119
+ },
120
+ "number[]": {
121
+ sqlite: `text('${name}', { mode: "json" })`,
122
+ pg: field.bigint ? `bigint('${name}', { mode: 'number' }).array()` : `integer('${name}').array()`,
123
+ mysql: `json('${name}')`
124
+ },
125
+ "string[]": {
126
+ sqlite: `text('${name}', { mode: "json" })`,
127
+ pg: `text('${name}').array()`,
128
+ mysql: `json('${name}')`
129
+ },
130
+ json: {
131
+ sqlite: `text('${name}', { mode: "json" })`,
132
+ pg: `jsonb('${name}')`,
133
+ mysql: `json('${name}')`
134
+ }
135
+ }[type];
136
+ if (!dbTypeMap) throw new Error(`Unsupported field type '${field.type}' for field '${name}'.`);
137
+ return dbTypeMap[databaseType];
138
+ }
139
+ let id = "";
140
+ const useNumberId = options.advanced?.database?.generateId === "serial";
141
+ if (options.advanced?.database?.generateId === "uuid" && databaseType === "pg") id = `uuid("id").default(sql\`pg_catalog.gen_random_uuid()\`).primaryKey()`;
142
+ else if (useNumberId) {
143
+ if (databaseType === "pg") id = `integer("id").generatedByDefaultAsIdentity().primaryKey()`;
144
+ else if (databaseType === "sqlite") id = `integer("id", { mode: "number" }).primaryKey({ autoIncrement: true })`;
145
+ else id = `int("id").autoincrement().primaryKey()`;
146
+ } else if (databaseType === "mysql") id = `varchar('id', { length: 36 }).primaryKey()`;
147
+ else if (databaseType === "pg") id = `text('id').primaryKey()`;
148
+ else id = `text('id').primaryKey()`;
149
+ const indexes = [];
150
+ const assignIndexes = (indexes) => {
151
+ if (!indexes.length) return "";
152
+ const code = [`, (table) => [`];
153
+ for (const index of indexes) code.push(` ${index.type}(${JSON.stringify(index.name)}).on(${index.on.map((fieldName) => `table.${fieldName}`).join(", ")}),`);
154
+ code.push(`]`);
155
+ return code.join("\n");
156
+ };
157
+ for (const tableIndex of resolvedTableIndexes) indexes.push({
158
+ type: tableIndex.unique ? "uniqueIndex" : "index",
159
+ name: tableIndex.name,
160
+ on: tableIndex.columns
161
+ });
162
+ const schema = `export const ${modelName} = ${tableFunction}("${convertToSnakeCase(modelName, camelCase)}", {
163
+ id: ${id},
164
+ ${Object.keys(fields).map((field) => {
165
+ const attr = fields[field];
166
+ const fieldName = attr.fieldName || field;
167
+ let type = getType(fieldName, attr, databaseType === "mysql" ? getDatabaseIndexStringLength({
168
+ columnName: fieldName,
169
+ dialect: "mysql",
170
+ fields,
171
+ indexes: resolvedTableIndexes
172
+ }) : void 0);
173
+ if (attr.index && !attr.unique) indexes.push({
174
+ type: "index",
175
+ name: getDatabaseFieldIndexName(modelName, fieldName, false),
176
+ on: [fieldName]
177
+ });
178
+ if (attr.defaultValue !== null && typeof attr.defaultValue !== "undefined") {
179
+ if (typeof attr.defaultValue === "function") {
180
+ if (attr.type === "date" && attr.defaultValue.toString().includes("new Date()")) {
181
+ if (databaseType === "sqlite") type += `.default(sql\`(cast(unixepoch('subsecond') * 1000 as integer))\`)`;
182
+ else type += `.defaultNow()`;
183
+ }
184
+ } else if (typeof attr.defaultValue === "string") type += `.default(${JSON.stringify(attr.defaultValue)})`;
185
+ else if (Array.isArray(attr.defaultValue)) {
186
+ const elements = attr.defaultValue.map((value) => JSON.stringify(value)).join(", ");
187
+ type += `.default([${elements}])`;
188
+ } else if (typeof attr.defaultValue === "object" && attr.defaultValue !== null) type += `.default(${JSON.stringify(attr.defaultValue)})`;
189
+ else type += `.default(${attr.defaultValue})`;
190
+ }
191
+ if (attr.onUpdate && attr.type === "date") {
192
+ if (typeof attr.onUpdate === "function") type += `.$onUpdate(${attr.onUpdate})`;
193
+ }
194
+ const referencesDisabledModel = attr.references && isMigrationDisabled(attr.references.model);
195
+ return `${fieldName}: ${type}${attr.required !== false ? ".notNull()" : ""}${attr.unique ? ".unique()" : ""}${attr.references && !referencesDisabledModel ? `.references(()=> ${getModelName(attr.references.model)}.${getFieldName({
196
+ model: attr.references.model,
197
+ field: attr.references.field
198
+ })}, { onDelete: '${attr.references.onDelete || "cascade"}' })` : ""}`;
199
+ }).join(",\n ")}
200
+ }${assignIndexes(indexes)});`;
201
+ code += `\n${schema}\n`;
202
+ }
203
+ const schemaObjectKeys = [];
204
+ for (const tableKey in tables) {
205
+ if (tables[tableKey].disableMigrations) continue;
206
+ const modelName = getModelName(tableKey);
207
+ schemaObjectKeys.push(modelName);
208
+ }
209
+ const schemaObject = `{ ${schemaObjectKeys.join(", ")} }`;
210
+ const relationsMap = /* @__PURE__ */ new Map();
211
+ for (const tableKey in tables) {
212
+ const table = tables[tableKey];
213
+ if (table.disableMigrations) continue;
214
+ const modelName = getModelName(tableKey);
215
+ const modelRelations = [];
216
+ const foreignFields = Object.entries(table.fields).filter(([_, field]) => field.references);
217
+ for (const [fieldName, field] of foreignFields) {
218
+ const referencedModel = field.references.model;
219
+ if (isMigrationDisabled(referencedModel)) continue;
220
+ const targetModelName = getModelName(referencedModel);
221
+ const fromField = getFieldName({
222
+ model: tableKey,
223
+ field: fieldName
224
+ });
225
+ const toField = getFieldName({
226
+ model: referencedModel,
227
+ field: field.references.field || "id"
228
+ });
229
+ const existingToSameModel = modelRelations.filter((r) => r.targetModel === targetModelName && r.type === "one");
230
+ const singularName = getSingularModelName(referencedModel);
231
+ const relationKey = existingToSameModel.length > 0 ? `${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)}${singularName.charAt(0).toUpperCase() + singularName.slice(1)}` : singularName;
232
+ modelRelations.push({
233
+ key: relationKey,
234
+ type: "one",
235
+ targetModel: targetModelName,
236
+ fromField,
237
+ toField,
238
+ sourceModel: modelName
239
+ });
240
+ }
241
+ const otherModels = Object.entries(tables).filter(([modelName, otherTable]) => modelName !== tableKey && !otherTable.disableMigrations);
242
+ for (const [otherTableKey, otherTable] of otherModels) {
243
+ const foreignKeysPointingHere = Object.entries(otherTable.fields).filter(([_, field]) => field.references?.model === tableKey || field.references?.model === modelName);
244
+ if (foreignKeysPointingHere.length === 0) continue;
245
+ const otherModelName = getModelName(otherTableKey);
246
+ if (foreignKeysPointingHere.some(([_, field]) => !field.unique)) {
247
+ const nonUniqueFKs = foreignKeysPointingHere.filter(([_, field]) => !field.unique);
248
+ for (let i = 0; i < nonUniqueFKs.length; i++) {
249
+ const fkField = nonUniqueFKs[i];
250
+ if (!fkField) continue;
251
+ const [fkFieldName, fkFieldAttr] = fkField;
252
+ const fromField = getFieldName({
253
+ model: tableKey,
254
+ field: fkFieldAttr.references?.field || "id"
255
+ });
256
+ const toField = getFieldName({
257
+ model: otherTableKey,
258
+ field: fkFieldName
259
+ });
260
+ let relationKey = otherModelName;
261
+ if (!adapterConfig?.usePlural) relationKey = otherModelName.endsWith("s") ? otherModelName : `${otherModelName}s`;
262
+ if (nonUniqueFKs.length > 1) {
263
+ const capitalizedField = fkFieldName.charAt(0).toUpperCase() + fkFieldName.slice(1);
264
+ relationKey = `${relationKey}By${capitalizedField}`;
265
+ }
266
+ modelRelations.push({
267
+ key: relationKey,
268
+ type: "many",
269
+ targetModel: otherModelName,
270
+ fromField,
271
+ toField,
272
+ sourceModel: modelName
273
+ });
274
+ }
275
+ } else {
276
+ const fkField = foreignKeysPointingHere.find(([_, field]) => field.unique);
277
+ if (fkField) {
278
+ const [fkFieldName, fieldAttr] = fkField;
279
+ const fromField = getFieldName({
280
+ model: tableKey,
281
+ field: fieldAttr.references?.field || "id"
282
+ });
283
+ const toField = getFieldName({
284
+ model: otherTableKey,
285
+ field: fkFieldName
286
+ });
287
+ const relationKey = otherModelName;
288
+ modelRelations.push({
289
+ key: relationKey,
290
+ type: "one",
291
+ targetModel: otherModelName,
292
+ fromField,
293
+ toField,
294
+ sourceModel: modelName
295
+ });
296
+ }
297
+ }
298
+ }
299
+ if (modelRelations.length > 0) relationsMap.set(modelName, modelRelations);
300
+ }
301
+ let relationsString = "";
302
+ if (relationsMap.size > 0) {
303
+ const relationsEntries = [];
304
+ for (const [modelName, relations] of relationsMap.entries()) {
305
+ const relationDefs = [];
306
+ for (const relation of relations) if (relation.type === "one") relationDefs.push(` ${relation.key}: r.one.${relation.targetModel}({\n from: r.${relation.sourceModel}.${relation.fromField},\n to: r.${relation.targetModel}.${relation.toField},\n })`);
307
+ else relationDefs.push(` ${relation.key}: r.many.${relation.targetModel}({\n from: r.${relation.sourceModel}.${relation.fromField},\n to: r.${relation.targetModel}.${relation.toField},\n })`);
308
+ if (relationDefs.length > 0) relationsEntries.push(` ${modelName}: {\n${relationDefs.join(",\n")}\n }`);
309
+ }
310
+ if (relationsEntries.length > 0) relationsString = `\n\nexport const authRelations = defineRelationsPart(${schemaObject}, (r) => ({\n${relationsEntries.join(",\n")}\n}));\n`;
311
+ }
312
+ code += relationsString;
313
+ let formattedCode = code;
314
+ try {
315
+ const { format } = await new Function("moduleName", "return import(moduleName);")("prettier");
316
+ formattedCode = await format(code, { parser: "typescript" });
317
+ } catch {}
318
+ return {
319
+ code: formattedCode,
320
+ fileName: path.basename(filePath),
321
+ overwrite: fileExist,
322
+ path: filePath,
323
+ append: false
324
+ };
325
+ };
326
+ function generateImport({ databaseType, tables, options, schemaName }) {
327
+ const rootImports = ["defineRelationsPart"];
328
+ const coreImports = [];
329
+ if (databaseType === "pg" && schemaName) coreImports.push("pgSchema");
330
+ if (!(databaseType === "pg" && schemaName)) coreImports.push(`${databaseType}Table`);
331
+ let hasBigint = false;
332
+ let hasJson = false;
333
+ for (const table of Object.values(tables)) {
334
+ for (const field of Object.values(table.fields)) {
335
+ if (field.bigint) hasBigint = true;
336
+ if (field.type === "json" || databaseType === "mysql" && (field.type === "number[]" || field.type === "string[]")) hasJson = true;
337
+ }
338
+ if (hasJson && hasBigint) break;
339
+ }
340
+ const useNumberId = options.advanced?.database?.generateId === "serial";
341
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
342
+ coreImports.push(databaseType === "mysql" ? "varchar, text" : databaseType === "pg" ? "text" : "text");
343
+ coreImports.push(hasBigint ? databaseType !== "sqlite" ? "bigint" : "" : "");
344
+ coreImports.push(databaseType !== "sqlite" ? "timestamp, boolean" : "");
345
+ if (databaseType === "mysql") {
346
+ const hasNonBigintNumber = Object.values(tables).some((table) => Object.values(table.fields).some((field) => (field.type === "number" || field.type === "number[]") && !field.bigint));
347
+ if (!!useNumberId || hasNonBigintNumber) coreImports.push("int");
348
+ if (Object.values(tables).some((table) => Object.values(table.fields).some((field) => typeof field.type !== "string" && Array.isArray(field.type) && field.type.every((x) => typeof x === "string")))) coreImports.push("mysqlEnum");
349
+ } else if (databaseType === "pg") {
350
+ if (useUUIDs) rootImports.push("sql");
351
+ if (Object.values(tables).some((table) => Object.values(table.fields).some((field) => (field.type === "number" || field.type === "number[]") && !field.bigint)) || options.advanced?.database?.generateId === "serial") coreImports.push("integer");
352
+ } else coreImports.push("integer");
353
+ if (databaseType === "pg" && useUUIDs) coreImports.push("uuid");
354
+ if (hasJson) {
355
+ if (databaseType === "pg") coreImports.push("jsonb");
356
+ if (databaseType === "mysql") coreImports.push("json");
357
+ }
358
+ if (databaseType === "sqlite" && Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.type === "date" && field.defaultValue && typeof field.defaultValue === "function" && field.defaultValue.toString().includes("new Date()")))) rootImports.push("sql");
359
+ const hasIndexes = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.index && !field.unique) || (table.indexes?.some((index) => !index.unique) ?? false));
360
+ const hasUniqueIndexes = Object.values(tables).some((table) => Object.values(table.fields).some((field) => field.unique && field.index) || (table.indexes?.some((index) => index.unique) ?? false));
361
+ if (hasIndexes) coreImports.push("index");
362
+ if (hasUniqueIndexes) coreImports.push("uniqueIndex");
363
+ return `${rootImports.length > 0 ? `import { ${rootImports.join(", ")} } from "drizzle-orm";\n` : ""}import { ${coreImports.map((x) => x.trim()).filter((x) => x !== "").join(", ")} } from "drizzle-orm/${databaseType}-core";\n`;
364
+ }
365
+ export { generateDrizzleSchema };
@@ -0,0 +1,59 @@
1
+ import { DBAdapter, DBAdapterDebugLogOption } from "@entro314labs/entro-auth-core/db/adapter";
2
+ import { EntroAuthOptions } from "@entro314labs/entro-auth-core";
3
+ export interface DB {
4
+ [key: string]: any;
5
+ }
6
+ export interface DrizzleAdapterConfig {
7
+ /**
8
+ * The schema object that defines the tables and fields
9
+ */
10
+ schema?: Record<string, any> | undefined;
11
+ /**
12
+ * The database provider
13
+ */
14
+ provider: "pg" | "mysql" | "sqlite";
15
+ /**
16
+ * If the table names in the schema are plural
17
+ * set this to true. For example, if the schema
18
+ * has an object with a key "users" instead of "user"
19
+ */
20
+ usePlural?: boolean | undefined;
21
+ /**
22
+ * Enable debug logs for the adapter
23
+ *
24
+ * @default false
25
+ */
26
+ debugLogs?: DBAdapterDebugLogOption | undefined;
27
+ /**
28
+ * By default snake case is used for table and field names
29
+ * when the CLI is used to generate the schema. If you want
30
+ * to use camel case, set this to true.
31
+ * @default false
32
+ */
33
+ camelCase?: boolean | undefined;
34
+ /**
35
+ * Whether to execute multiple operations in a transaction.
36
+ *
37
+ * If the database doesn't support transactions,
38
+ * set this to `false` and operations will be executed sequentially.
39
+ * @default false
40
+ */
41
+ transaction?: boolean | undefined;
42
+ /**
43
+ * Database schema namespace, used during the Entro Auth CLI to generate the schema.
44
+ *
45
+ * Only applies to PostgreSQL. It will generate something like this:
46
+ *
47
+ * ```ts
48
+ * export const authSchema = pgSchema("auth");
49
+ *
50
+ * export const user = authSchema.table("user", {...});
51
+ * export const session = authSchema.table("session", {...});
52
+ * ```
53
+ *
54
+ * @example "auth"
55
+ * @default undefined
56
+ */
57
+ schemaName?: string | undefined;
58
+ }
59
+ export declare const drizzleAdapter: (db: DB, config: DrizzleAdapterConfig) => (options: EntroAuthOptions) => DBAdapter<EntroAuthOptions>;
package/dist/index.mjs ADDED
@@ -0,0 +1,704 @@
1
+ import { createAdapterFactory } from "@entro314labs/entro-auth-core/db/adapter";
2
+ import { checksSchema, createSchemaCheck, diffSchema, getExpectedSchema, registerSchemaCheck } from "@entro314labs/entro-auth-core/db/internal";
3
+ import { logger } from "@entro314labs/entro-auth-core/env";
4
+ import { EntroAuthError } from "@entro314labs/entro-auth-core/error";
5
+ import { Column, Table, and, asc, count, desc, eq, getTableColumns, gt, gte, inArray, is, isNotNull, isNull, lt, lte, ne, notInArray, or, sql } from "drizzle-orm";
6
+ // src/date-columns.ts
7
+ /**
8
+ * Whether a Drizzle column stores its value as a string and passes it to the
9
+ * driver unchanged, such as `timestamp({ mode: "string" })` or SQLite `text()`.
10
+ * Drizzle 0.x names that data type `"string"`, and 1.x names it `"string ..."`,
11
+ * for example `"string timestamp"`.
12
+ */
13
+ function isStringColumn(column) {
14
+ const dataType = column?.dataType;
15
+ return typeof dataType === "string" && dataType.split(" ")[0] === "string";
16
+ }
17
+ /**
18
+ * Converts a `Date` bound for a string column, or each `Date` in an `in` /
19
+ * `not_in` list, into the UTC text Drizzle's own date mode writes: ISO 8601,
20
+ * or `YYYY-MM-DD HH:MM:SS.mmm` for MySQL, which rejects the `T` and `Z`.
21
+ * Other values are returned unchanged.
22
+ */
23
+ function toDriverDate(value, column, provider) {
24
+ if (!isStringColumn(column)) return value;
25
+ const format = (item) => {
26
+ if (!(item instanceof Date)) return item;
27
+ const iso = item.toISOString();
28
+ return provider === "mysql" ? iso.replace("T", " ").replace("Z", "") : iso;
29
+ };
30
+ return Array.isArray(value) ? value.map(format) : format(value);
31
+ }
32
+ const DATE_TIME_WITHOUT_OFFSET = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
33
+ /**
34
+ * Reads a date column value. A date-time string without an offset is UTC,
35
+ * since that is how `toDriverDate` and Drizzle's date mode write it.
36
+ */
37
+ function fromDriverDate(value) {
38
+ if (typeof value === "string" && DATE_TIME_WITHOUT_OFFSET.test(value)) return /* @__PURE__ */ new Date(`${value.replace(" ", "T")}Z`);
39
+ return new Date(value);
40
+ }
41
+ // src/join-relation-key.ts
42
+ /**
43
+ * Reads the relation registry used to build Drizzle relational queries,
44
+ * `db._.relations`.
45
+ */
46
+ function buildRelationKeysByModel(relationRegistry) {
47
+ const relationKeysByModel = /* @__PURE__ */ new Map();
48
+ for (const [model, tableMetadata] of Object.entries(relationRegistry ?? {})) {
49
+ if (!tableMetadata.relations) continue;
50
+ relationKeysByModel.set(model, new Set(Object.keys(tableMetadata.relations)));
51
+ }
52
+ return relationKeysByModel;
53
+ }
54
+ function getOneToOneRelationKey({ baseModel, joinModel, baseModelKey, joinModelKey, relationKeys, schema, getDefaultModelName }) {
55
+ const defaultBaseModelName = baseModelKey ?? getDefaultModelName(baseModel);
56
+ const defaultJoinModelName = joinModelKey ?? getDefaultModelName(joinModel);
57
+ const joinModelFields = schema[defaultJoinModelName]?.fields ?? {};
58
+ const generatedRelationKey = Object.values(joinModelFields).some((field) => field.references?.model === defaultBaseModelName) ? joinModel : schema[defaultJoinModelName]?.modelName ?? defaultJoinModelName;
59
+ if (!relationKeys?.size) return joinModel;
60
+ if (relationKeys.has(generatedRelationKey)) return generatedRelationKey;
61
+ if (relationKeys.has(joinModel)) return joinModel;
62
+ return generatedRelationKey;
63
+ }
64
+ // src/query-builders.ts
65
+ /**
66
+ * LIKE/ILIKE with an explicit backslash escape character so callers can match a
67
+ * literal `%` or `_`. SQLite has no default LIKE escape, so the ESCAPE clause is
68
+ * always supplied. The escape character is passed as a bound parameter.
69
+ *
70
+ * This does not support MySQL's `NO_BACKSLASH_ESCAPES` sql_mode, under which the
71
+ * bound backslash is rejected as a two-character ESCAPE argument.
72
+ *
73
+ * @see https://www.sqlite.org/lang_expr.html
74
+ */
75
+ function escapedLike(column, pattern, provider, mode = "sensitive") {
76
+ const escape = "\\";
77
+ if (mode === "insensitive") return provider === "pg" ? sql`${column} ILIKE ${pattern} ESCAPE ${escape}` : sql`LOWER(${column}) LIKE LOWER(${pattern}) ESCAPE ${escape}`;
78
+ return sql`${column} LIKE ${pattern} ESCAPE ${escape}`;
79
+ }
80
+ /**
81
+ * Case-insensitive IN for string arrays.
82
+ */
83
+ function insensitiveInArray(column, values) {
84
+ if (values.length === 0) return sql`false`;
85
+ return sql`LOWER(${column}) IN (${sql.join(values.map((v) => sql`LOWER(${v})`), sql`, `)})`;
86
+ }
87
+ /**
88
+ * Case-insensitive NOT IN for string arrays.
89
+ */
90
+ function insensitiveNotInArray(column, values) {
91
+ if (values.length === 0) return sql`true`;
92
+ return sql`LOWER(${column}) NOT IN (${sql.join(values.map((v) => sql`LOWER(${v})`), sql`, `)})`;
93
+ }
94
+ /**
95
+ * Case-insensitive equality for strings.
96
+ */
97
+ function insensitiveEq(column, value) {
98
+ return sql`LOWER(${column}) = LOWER(${value})`;
99
+ }
100
+ /**
101
+ * Case-insensitive inequality for strings.
102
+ */
103
+ function insensitiveNe(column, value) {
104
+ return sql`LOWER(${column}) <> LOWER(${value})`;
105
+ }
106
+ // src/schema-check.ts
107
+ /**
108
+ * Reads a Drizzle schema object the way the adapter addresses it: each table
109
+ * by the key it is exported under, each column by its property name. Values
110
+ * that are not tables, such as relations, are skipped.
111
+ */
112
+ function introspectDrizzleSchema(schema) {
113
+ const tables = [];
114
+ for (const [name, table] of Object.entries(schema)) {
115
+ if (!is(table, Table)) continue;
116
+ const columns = Object.entries(getTableColumns(table)).map(([key, column]) => ({
117
+ name: key,
118
+ nullable: !column.notNull,
119
+ hasDefault: column.hasDefault || column.generated !== void 0 || column.generatedIdentity !== void 0
120
+ }));
121
+ tables.push({
122
+ name,
123
+ columns
124
+ });
125
+ }
126
+ return tables;
127
+ }
128
+ /**
129
+ * Compares a Drizzle schema object with the tables this configuration writes.
130
+ */
131
+ function findDrizzleSchemaProblems(schema, options, usePlural) {
132
+ return diffSchema(getExpectedSchema(options, { usePlural }), introspectDrizzleSchema(schema));
133
+ }
134
+ // src/drizzle-adapter.ts
135
+ function escapeLikePattern(value) {
136
+ if (value == null) return "";
137
+ return String(value).replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
138
+ }
139
+ function readDriverRowCount(result) {
140
+ if (!result || typeof result !== "object") return void 0;
141
+ if ("affectedRows" in result) return result.affectedRows;
142
+ if ("rowsAffected" in result) return result.rowsAffected;
143
+ if ("changes" in result) return result.changes;
144
+ if ("meta" in result) {
145
+ const meta = result.meta;
146
+ if (meta && typeof meta === "object" && "changes" in meta) return meta.changes;
147
+ }
148
+ }
149
+ function hasDriverRowCount(result) {
150
+ return readDriverRowCount(result) !== void 0;
151
+ }
152
+ function getAffectedRowCount(result, operation, context) {
153
+ let count = 0;
154
+ if (result && typeof result === "object" && "rowCount" in result) count = result.rowCount;
155
+ else if (result && typeof result === "object" && typeof result.count === "number") count = result.count;
156
+ else if (Array.isArray(result)) count = result.length > 0 && hasDriverRowCount(result[0]) ? readDriverRowCount(result[0]) : result.length;
157
+ else if (hasDriverRowCount(result)) count = readDriverRowCount(result);
158
+ if (typeof count !== "number" || !Number.isFinite(count)) {
159
+ logger.error(`[Drizzle Adapter] The result of the ${operation} operation is not a finite number. This is likely a bug in the adapter. Please report this issue to the Entro Auth team.`, {
160
+ result,
161
+ ...context
162
+ });
163
+ throw new EntroAuthError(`Drizzle adapter ${operation} returned an invalid affected row count`);
164
+ }
165
+ return count;
166
+ }
167
+ /**
168
+ * Maps a single Where entry to a drizzle SQL expression.
169
+ * Shared by convertWhereClause across single / AND / OR branches.
170
+ */
171
+ function applyWhereOperator(column, w, fieldLabel, provider) {
172
+ const isInsensitive = (w.mode ?? "sensitive") === "insensitive" && (typeof w.value === "string" || Array.isArray(w.value) && w.value.every((v) => typeof v === "string"));
173
+ if (w.operator === "in") {
174
+ if (!Array.isArray(w.value)) throw new EntroAuthError(`The value for the field "${fieldLabel}" must be an array when using the "in" operator.`);
175
+ if (isInsensitive) return insensitiveInArray(column, w.value);
176
+ return inArray(column, w.value);
177
+ }
178
+ if (w.operator === "not_in") {
179
+ if (!Array.isArray(w.value)) throw new EntroAuthError(`The value for the field "${fieldLabel}" must be an array when using the "not_in" operator.`);
180
+ if (isInsensitive) return insensitiveNotInArray(column, w.value);
181
+ return notInArray(column, w.value);
182
+ }
183
+ const likeMode = isInsensitive && typeof w.value === "string" ? "insensitive" : "sensitive";
184
+ if (w.operator === "contains") return escapedLike(column, `%${escapeLikePattern(w.value)}%`, provider, likeMode);
185
+ if (w.operator === "starts_with") return escapedLike(column, `${escapeLikePattern(w.value)}%`, provider, likeMode);
186
+ if (w.operator === "ends_with") return escapedLike(column, `%${escapeLikePattern(w.value)}`, provider, likeMode);
187
+ if (w.operator === "lt") return lt(column, w.value);
188
+ if (w.operator === "lte") return lte(column, w.value);
189
+ if (w.operator === "ne") {
190
+ if (w.value === null) return isNotNull(column);
191
+ if (isInsensitive && typeof w.value === "string") return insensitiveNe(column, w.value);
192
+ return ne(column, w.value);
193
+ }
194
+ if (w.operator === "gt") return gt(column, w.value);
195
+ if (w.operator === "gte") return gte(column, w.value);
196
+ if (w.value === null) return isNull(column);
197
+ if (isInsensitive && typeof w.value === "string") return insensitiveEq(column, w.value);
198
+ return eq(column, w.value);
199
+ }
200
+ const drizzleAdapter = (db, config) => {
201
+ let lazyOptions = null;
202
+ let mysqlNoIdWarned = false;
203
+ let relationKeysByModel;
204
+ const getRelationKeysByModel = () => relationKeysByModel ??= buildRelationKeysByModel(db._?.relations);
205
+ const createCustomAdapter = (db, inTransaction = false) => ({ getFieldName, getDefaultModelName, options, schema: baSchema }) => {
206
+ if (config.provider === "mysql" && options.advanced?.database?.generateId === false && !mysqlNoIdWarned) {
207
+ mysqlNoIdWarned = true;
208
+ logger.warn("[Drizzle Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Entro Auth's default ID generation, a custom generateId function, or generateId: \"serial\" for auto-increment.");
209
+ }
210
+ function getSchema(model) {
211
+ const schemaModel = config.schema?.[model] ?? db._?.relations?.[model]?.table ?? db._?.fullSchema?.[model];
212
+ if (!schemaModel) throw new EntroAuthError(`[# Drizzle Adapter]: The model "${model}" was not found in the schema object. Please pass the schema directly to the adapter options.`);
213
+ return schemaModel;
214
+ }
215
+ /**
216
+ * Resolve the `db.query` key for a model.
217
+ *
218
+ * `db.query` is keyed by the Drizzle schema export names, which are
219
+ * often plural ("users") even when Entro Auth uses singular model
220
+ * names. Try the model directly, then the `usePlural` variant, then
221
+ * scan the schema for the key pointing at the same table.
222
+ */
223
+ function getQueryModel(model) {
224
+ if (!db.query) return null;
225
+ if (db.query[model]) return model;
226
+ if (config.usePlural) {
227
+ const plural = `${model}s`;
228
+ if (db.query[plural]) return plural;
229
+ }
230
+ if (config.schema) {
231
+ const targetTable = config.schema[model];
232
+ if (targetTable) {
233
+ const relations = db._?.relations;
234
+ const fullSchema = db._?.fullSchema;
235
+ for (const key of Object.keys(db.query)) if ((relations?.[key]?.table ?? fullSchema?.[key]) === targetTable) return key;
236
+ }
237
+ }
238
+ return null;
239
+ }
240
+ function getJoinRelationKey(baseModel, joinModel, baseModelKey, joinModelKey, relationKeys, isUnique) {
241
+ if (isUnique) return getOneToOneRelationKey({
242
+ baseModel,
243
+ joinModel,
244
+ baseModelKey,
245
+ joinModelKey,
246
+ relationKeys,
247
+ schema: baSchema,
248
+ getDefaultModelName
249
+ });
250
+ if (config.usePlural || joinModel.endsWith("s")) return joinModel;
251
+ return `${joinModel}s`;
252
+ }
253
+ const withReturning = async (model, modelKey, builder, data, where) => {
254
+ if (config.provider !== "mysql") return (await builder.returning())[0];
255
+ const isSerialInsert = where === void 0 && options.advanced?.database?.generateId === "serial";
256
+ const insertResult = isSerialInsert ? await builder.$returningId().execute() : await builder.execute();
257
+ const schemaModel = getSchema(model);
258
+ const builderVal = builder.config?.values;
259
+ if (where?.length) {
260
+ const clause = convertWhereClause(where.map((w) => {
261
+ if (data[w.field] !== void 0) return {
262
+ ...w,
263
+ value: data[w.field]
264
+ };
265
+ return w;
266
+ }), model, modelKey);
267
+ return (await db.select().from(schemaModel).where(...clause))[0];
268
+ }
269
+ const fetchInserted = async (tx) => {
270
+ const builderId = builderVal?.[0]?.id?.value;
271
+ if (builderId) return (await tx.select().from(schemaModel).where(eq(schemaModel.id, builderId)).limit(1).execute())[0] ?? null;
272
+ if (data.id) return (await tx.select().from(schemaModel).where(eq(schemaModel.id, data.id)).limit(1).execute())[0] ?? null;
273
+ const insertId = isSerialInsert ? insertResult?.[0]?.id : void 0;
274
+ if (insertId && schemaModel.id) return (await tx.select().from(schemaModel).where(eq(schemaModel.id, insertId)).limit(1).execute())[0] ?? null;
275
+ const modelSchema = baSchema[modelKey]?.fields;
276
+ if (modelSchema) for (const [fieldKey, fieldAttr] of Object.entries(modelSchema)) {
277
+ if (!fieldAttr.unique) continue;
278
+ const dbFieldName = getFieldName({
279
+ model: modelKey,
280
+ field: fieldKey
281
+ });
282
+ const val = data[dbFieldName];
283
+ if (val === void 0 || val === null) continue;
284
+ if (!schemaModel[dbFieldName]) continue;
285
+ const res = await tx.select().from(schemaModel).where(eq(schemaModel[dbFieldName], val)).limit(1).execute();
286
+ if (res[0]) return res[0];
287
+ }
288
+ const conditions = [];
289
+ for (const [key, val] of Object.entries(data)) {
290
+ if (val === void 0 || !schemaModel[key]) continue;
291
+ conditions.push(val === null ? isNull(schemaModel[key]) : eq(schemaModel[key], val));
292
+ }
293
+ if (conditions.length > 0) {
294
+ const combined = and(...conditions);
295
+ if (combined) {
296
+ const res = await tx.select().from(schemaModel).where(combined).limit(2).execute();
297
+ if (res.length === 1) return res[0];
298
+ }
299
+ }
300
+ logger.warn(`[Drizzle Adapter] Unable to safely identify the inserted "${model}" row on MySQL. Enable Entro Auth ID generation or use generateId: "serial" for reliable behavior.`);
301
+ return null;
302
+ };
303
+ return inTransaction ? fetchInserted(db) : db.transaction(fetchInserted);
304
+ };
305
+ function resolveColumn(model, modelKey, w) {
306
+ const schemaModel = getSchema(model);
307
+ const field = getFieldName({
308
+ model: modelKey,
309
+ field: w.field
310
+ });
311
+ if (!is(schemaModel[field], Column)) throw new EntroAuthError(`The field "${w.field}" does not exist in the schema for the model "${model}". Please update your schema.`);
312
+ return {
313
+ column: schemaModel[field],
314
+ field
315
+ };
316
+ }
317
+ function convertWhereClause(where, model, modelKey) {
318
+ if (!where) return [];
319
+ if (where.length === 1) {
320
+ const w = where[0];
321
+ if (!w) return [];
322
+ const { column } = resolveColumn(model, modelKey, w);
323
+ return [applyWhereOperator(column, w, w.field, config.provider)];
324
+ }
325
+ const andGroup = where.filter((w) => w.connector === "AND" || !w.connector);
326
+ const orGroup = where.filter((w) => w.connector === "OR");
327
+ const andClause = and(...andGroup.map((w) => {
328
+ const { column } = resolveColumn(model, modelKey, w);
329
+ return applyWhereOperator(column, w, w.field, config.provider);
330
+ }));
331
+ const orClause = or(...orGroup.map((w) => {
332
+ const { column } = resolveColumn(model, modelKey, w);
333
+ return applyWhereOperator(column, w, w.field, config.provider);
334
+ }));
335
+ const combined = and(andClause, orClause);
336
+ return combined ? [combined] : [];
337
+ }
338
+ function convertNewWhereClause(where, model, modelKey) {
339
+ const schemaModel = getSchema(model);
340
+ if (!where || where.length === 0) return {};
341
+ const rawCondition = (w, field) => ({ RAW: (table) => applyWhereOperator(table[field], w, w.field, config.provider) });
342
+ const convertWhereToColumn = (w) => {
343
+ const field = getFieldName({
344
+ model: modelKey,
345
+ field: w.field
346
+ });
347
+ if (!is(schemaModel[field], Column)) throw new EntroAuthError(`The field "${w.field}" does not exist in the schema for the model "${model}". Please update your schema.`);
348
+ const columnObj = {};
349
+ let raw;
350
+ const isInsensitive = w.mode === "insensitive" && (typeof w.value === "string" || Array.isArray(w.value) && w.value.every((v) => typeof v === "string"));
351
+ if (w.operator === "contains" || w.operator === "starts_with" || w.operator === "ends_with" || isInsensitive) raw = rawCondition(w, field);
352
+ else if (w.operator === "in") {
353
+ if (!Array.isArray(w.value)) throw new EntroAuthError(`The value for the field "${w.field}" must be an array when using the "in" operator.`);
354
+ columnObj.in = w.value;
355
+ } else if (w.operator === "not_in") {
356
+ if (!Array.isArray(w.value)) throw new EntroAuthError(`The value for the field "${w.field}" must be an array when using the "not_in" operator.`);
357
+ columnObj.notIn = w.value;
358
+ } else if (w.operator === "lt") columnObj.lt = w.value;
359
+ else if (w.operator === "lte") columnObj.lte = w.value;
360
+ else if (w.operator === "ne") {
361
+ if (w.value === null) columnObj.isNotNull = true;
362
+ else columnObj.ne = w.value;
363
+ } else if (w.operator === "gt") columnObj.gt = w.value;
364
+ else if (w.operator === "gte") columnObj.gte = w.value;
365
+ else if (w.value === null) columnObj.isNull = true;
366
+ else columnObj.eq = w.value;
367
+ return {
368
+ field,
369
+ columnObj,
370
+ raw
371
+ };
372
+ };
373
+ if (where.length === 1) {
374
+ const w = where[0];
375
+ if (!w) return {};
376
+ const { field, columnObj, raw } = convertWhereToColumn(w);
377
+ return raw ?? { [field]: columnObj };
378
+ }
379
+ const andGroup = where.filter((w) => w.connector === "AND" || !w.connector);
380
+ const orGroup = where.filter((w) => w.connector === "OR");
381
+ const result = {};
382
+ if (andGroup.length > 0) {
383
+ const fieldMap = {};
384
+ const rawConditions = [];
385
+ for (const w of andGroup) {
386
+ const { field, columnObj, raw } = convertWhereToColumn(w);
387
+ if (raw) {
388
+ rawConditions.push(raw);
389
+ continue;
390
+ }
391
+ if (!fieldMap[field]) fieldMap[field] = [];
392
+ fieldMap[field].push(columnObj);
393
+ }
394
+ for (const [field, conditions] of Object.entries(fieldMap)) if (conditions.length === 1) result[field] = conditions[0];
395
+ else result[field] = { AND: conditions };
396
+ if (rawConditions.length > 0) result.AND = rawConditions;
397
+ }
398
+ if (orGroup.length > 0) {
399
+ const orConditions = [];
400
+ for (const w of orGroup) {
401
+ const { field, columnObj, raw } = convertWhereToColumn(w);
402
+ orConditions.push(raw ?? { [field]: columnObj });
403
+ }
404
+ if (orConditions.length > 0) result.OR = orConditions;
405
+ }
406
+ return result;
407
+ }
408
+ function checkMissingFields(schema, model, values) {
409
+ if (!schema) throw new EntroAuthError("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.");
410
+ for (const key in values) if (!schema[key]) throw new EntroAuthError(`The field "${key}" does not exist in the "${model}" Drizzle schema. Please update your drizzle schema or re-generate using "npx @entro314labs/entro-auth-cli@latest generate".`);
411
+ }
412
+ return {
413
+ async create({ model, modelKey = model, data: values }) {
414
+ const table = getSchema(model);
415
+ checkMissingFields(table, modelKey, values);
416
+ const builder = db.insert(table).values(values);
417
+ return await withReturning(model, modelKey, builder, values);
418
+ },
419
+ async findOne({ model, modelKey = model, where, select, join }) {
420
+ const table = getSchema(model);
421
+ const clause = convertWhereClause(where, model, modelKey);
422
+ if (join) {
423
+ const queryModel = getQueryModel(model);
424
+ if (!db.query || !queryModel) {
425
+ logger.error(`[# Drizzle Adapter]: The model "${model}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx @entro314labs/entro-auth-cli@latest generate".`);
426
+ logger.info("Falling back to regular query");
427
+ } else {
428
+ let includes;
429
+ const renamedJoinResults = [];
430
+ const relationKeys = getRelationKeysByModel().get(queryModel);
431
+ includes = {};
432
+ const joinEntries = Object.entries(join);
433
+ for (const [joinModel, joinAttr] of joinEntries) {
434
+ const limit = joinAttr.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
435
+ const isUnique = joinAttr.relation === "one-to-one";
436
+ const relationKey = getJoinRelationKey(model, joinModel, modelKey, joinAttr.modelKey ?? joinModel, relationKeys, isUnique);
437
+ includes[relationKey] = isUnique ? true : { limit };
438
+ if (relationKey !== joinModel) renamedJoinResults.push({
439
+ key: relationKey,
440
+ target: joinModel
441
+ });
442
+ }
443
+ const clause = convertNewWhereClause(where, model, modelKey);
444
+ const res = await db.query[queryModel].findFirst({
445
+ where: clause,
446
+ columns: select?.length && select.length > 0 ? select.reduce((acc, field) => {
447
+ acc[getFieldName({
448
+ model: modelKey,
449
+ field
450
+ })] = true;
451
+ return acc;
452
+ }, {}) : void 0,
453
+ with: includes
454
+ });
455
+ if (res) for (const { key, target } of renamedJoinResults) {
456
+ res[target] = res[key];
457
+ delete res[key];
458
+ }
459
+ return res;
460
+ }
461
+ }
462
+ const res = await db.select(select?.length && select.length > 0 ? select.reduce((acc, field) => {
463
+ const fieldName = getFieldName({
464
+ model: modelKey,
465
+ field
466
+ });
467
+ return {
468
+ ...acc,
469
+ [fieldName]: table[fieldName]
470
+ };
471
+ }, {}) : void 0).from(table).where(...clause);
472
+ if (!res.length) return null;
473
+ return res[0];
474
+ },
475
+ async findMany({ model, modelKey = model, where, sortBy, limit, select, offset, join }) {
476
+ const table = getSchema(model);
477
+ const clause = where ? convertWhereClause(where, model, modelKey) : [];
478
+ const sortFn = sortBy?.direction === "desc" ? desc : asc;
479
+ if (join) {
480
+ const queryModel = getQueryModel(model);
481
+ if (!db.query || !queryModel) {
482
+ logger.error(`[# Drizzle Adapter]: The model "${model}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx @entro314labs/entro-auth-cli@latest generate".`);
483
+ logger.info("Falling back to regular query");
484
+ } else {
485
+ let includes;
486
+ const renamedJoinResults = [];
487
+ const relationKeys = getRelationKeysByModel().get(queryModel);
488
+ includes = {};
489
+ const joinEntries = Object.entries(join);
490
+ for (const [joinModel, joinAttr] of joinEntries) {
491
+ const isUnique = joinAttr.relation === "one-to-one";
492
+ const limit = joinAttr.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
493
+ const relationKey = getJoinRelationKey(model, joinModel, modelKey, joinAttr.modelKey ?? joinModel, relationKeys, isUnique);
494
+ includes[relationKey] = isUnique ? true : { limit };
495
+ if (relationKey !== joinModel) renamedJoinResults.push({
496
+ key: relationKey,
497
+ target: joinModel
498
+ });
499
+ }
500
+ let orderBy = void 0;
501
+ if (sortBy?.field) orderBy = { [getFieldName({
502
+ model: modelKey,
503
+ field: sortBy.field
504
+ })]: sortBy.direction === "desc" ? "desc" : "asc" };
505
+ const res = await db.query[queryModel].findMany({
506
+ ...where?.length ? { where: convertNewWhereClause(where, model, modelKey) } : {},
507
+ with: includes,
508
+ columns: select?.length && select.length > 0 ? select.reduce((acc, field) => {
509
+ acc[getFieldName({
510
+ model: modelKey,
511
+ field
512
+ })] = true;
513
+ return acc;
514
+ }, {}) : void 0,
515
+ limit: limit ?? 100,
516
+ offset: offset ?? 0,
517
+ orderBy
518
+ });
519
+ if (res) for (const item of res) for (const { key, target } of renamedJoinResults) {
520
+ item[target] = item[key];
521
+ delete item[key];
522
+ }
523
+ return res;
524
+ }
525
+ }
526
+ let builder = db.select(select?.length && select.length > 0 ? select.reduce((acc, field) => {
527
+ const fieldName = getFieldName({
528
+ model: modelKey,
529
+ field
530
+ });
531
+ return {
532
+ ...acc,
533
+ [fieldName]: table[fieldName]
534
+ };
535
+ }, {}) : void 0).from(table);
536
+ const effectiveLimit = limit;
537
+ const effectiveOffset = offset;
538
+ if (typeof effectiveLimit !== "undefined") builder = builder.limit(effectiveLimit);
539
+ if (typeof effectiveOffset !== "undefined") builder = builder.offset(effectiveOffset);
540
+ if (sortBy?.field) builder = builder.orderBy(sortFn(table[getFieldName({
541
+ model: modelKey,
542
+ field: sortBy?.field
543
+ })]));
544
+ return await builder.where(...clause);
545
+ },
546
+ async count({ model, modelKey = model, where }) {
547
+ const table = getSchema(model);
548
+ const clause = where ? convertWhereClause(where, model, modelKey) : [];
549
+ return (await db.select({ count: count() }).from(table).where(...clause))[0].count;
550
+ },
551
+ async update({ model, modelKey = model, where, update: values }) {
552
+ const table = getSchema(model);
553
+ const clause = convertWhereClause(where, model, modelKey);
554
+ const builder = db.update(table).set(values).where(...clause);
555
+ return await withReturning(model, modelKey, builder, values, where);
556
+ },
557
+ async updateMany({ model, modelKey = model, where, update: values }) {
558
+ const table = getSchema(model);
559
+ const clause = convertWhereClause(where, model, modelKey);
560
+ return getAffectedRowCount(await db.update(table).set(values).where(...clause), "updateMany", {
561
+ model,
562
+ where
563
+ });
564
+ },
565
+ async delete({ model, modelKey = model, where }) {
566
+ const table = getSchema(model);
567
+ const clause = convertWhereClause(where, model, modelKey);
568
+ return await db.delete(table).where(...clause);
569
+ },
570
+ async deleteMany({ model, modelKey = model, where }) {
571
+ const table = getSchema(model);
572
+ const clause = convertWhereClause(where, model, modelKey);
573
+ return getAffectedRowCount(await db.delete(table).where(...clause), "deleteMany", {
574
+ model,
575
+ where
576
+ });
577
+ },
578
+ async consumeOne({ model, modelKey = model, where }) {
579
+ const table = getSchema(model);
580
+ const clause = convertWhereClause(where, model, modelKey);
581
+ const idField = getFieldName({
582
+ model: modelKey,
583
+ field: "id"
584
+ });
585
+ const idColumn = table[idField];
586
+ if (config.provider === "mysql") {
587
+ const claimFromTransaction = async (tx) => {
588
+ const target = (await tx.select().from(table).where(...clause).for("update").limit(1))[0];
589
+ if (!target) return null;
590
+ const targetId = target[idField] ?? target.id;
591
+ if (targetId === void 0 || targetId === null || !idColumn) return null;
592
+ return getAffectedRowCount(await tx.delete(table).where(eq(idColumn, targetId)).execute(), "consumeOne", {
593
+ model,
594
+ where
595
+ }) > 0 ? target : null;
596
+ };
597
+ return inTransaction ? claimFromTransaction(db) : db.transaction(claimFromTransaction);
598
+ }
599
+ if (!idColumn) return null;
600
+ const targetIds = db.select({ id: idColumn }).from(table).where(...clause).limit(1);
601
+ return (await db.delete(table).where(inArray(idColumn, targetIds)).returning())[0] ?? null;
602
+ },
603
+ async incrementOne({ model, modelKey = model, where, increment, set }) {
604
+ const table = getSchema(model);
605
+ const clause = convertWhereClause(where, model, modelKey);
606
+ const idField = getFieldName({
607
+ model: modelKey,
608
+ field: "id"
609
+ });
610
+ const idColumn = table[idField];
611
+ const assignments = {};
612
+ for (const [field, delta] of Object.entries(increment)) {
613
+ const columnName = getFieldName({
614
+ model: modelKey,
615
+ field
616
+ });
617
+ const column = table[columnName];
618
+ if (!column) throw new EntroAuthError(`The field "${field}" does not exist in the schema for the model "${model}". Please update your schema.`);
619
+ assignments[columnName] = sql`${column} + ${sql.param(delta)}`;
620
+ }
621
+ if (set) for (const [field, value] of Object.entries(set)) {
622
+ const columnName = getFieldName({
623
+ model: modelKey,
624
+ field
625
+ });
626
+ if (!table[columnName]) throw new EntroAuthError(`The field "${field}" does not exist in the schema for the model "${model}". Please update your schema.`);
627
+ assignments[columnName] = value;
628
+ }
629
+ if (config.provider === "mysql") {
630
+ const mutateInTransaction = async (tx) => {
631
+ const target = (await tx.select().from(table).where(...clause).for("update").limit(1))[0];
632
+ if (!target) return null;
633
+ const targetId = target[idField] ?? target.id;
634
+ if (targetId === void 0 || targetId === null || !idColumn) return null;
635
+ await tx.update(table).set(assignments).where(eq(idColumn, targetId)).execute();
636
+ return (await tx.select().from(table).where(eq(idColumn, targetId)).limit(1).execute())[0] ?? null;
637
+ };
638
+ return inTransaction ? mutateInTransaction(db) : db.transaction(mutateInTransaction);
639
+ }
640
+ if (!idColumn) return null;
641
+ const targetIds = db.select({ id: idColumn }).from(table).where(...clause).limit(1);
642
+ return (await db.update(table).set(assignments).where(and(...clause, inArray(idColumn, targetIds))).returning())[0] ?? null;
643
+ },
644
+ async createSchema(props) {
645
+ const { generateDrizzleSchema } = await import("./generate-drizzle-schema.mjs");
646
+ return await generateDrizzleSchema({
647
+ adapterConfig: config,
648
+ options,
649
+ provider: config.provider,
650
+ camelCase: config.camelCase,
651
+ file: props.file,
652
+ tables: props.tables
653
+ });
654
+ },
655
+ options: config
656
+ };
657
+ };
658
+ let adapterOptions = null;
659
+ adapterOptions = {
660
+ config: {
661
+ adapterId: "drizzle",
662
+ adapterName: "Drizzle Adapter",
663
+ usePlural: config.usePlural ?? false,
664
+ debugLogs: config.debugLogs ?? false,
665
+ supportsUUIDs: config.provider === "pg" ? true : false,
666
+ supportsJSON: true,
667
+ supportsArrays: true,
668
+ customTransformInput: ({ data, fieldAttributes, model, field }) => {
669
+ if (fieldAttributes.type !== "date") return data;
670
+ return toDriverDate(data, (config.schema?.[model] ?? db._?.relations?.[model]?.table ?? db._?.fullSchema?.[model])?.[field], config.provider);
671
+ },
672
+ customTransformOutput: ({ data, fieldAttributes }) => {
673
+ if (fieldAttributes.type !== "date" || data == null) return data;
674
+ return fromDriverDate(data);
675
+ },
676
+ transaction: config.transaction ?? false ? (cb) => db.transaction((tx) => {
677
+ return cb(createAdapterFactory({
678
+ config: {
679
+ ...adapterOptions.config,
680
+ transaction: false
681
+ },
682
+ adapter: createCustomAdapter(tx, true)
683
+ })(lazyOptions));
684
+ }) : false
685
+ },
686
+ adapter: createCustomAdapter(db)
687
+ };
688
+ const adapter = createAdapterFactory(adapterOptions);
689
+ return (options) => {
690
+ lazyOptions = options;
691
+ const instance = adapter(options);
692
+ const schemaCheck = createSchemaCheck(() => {
693
+ const relations = db._?.relations ?? {};
694
+ return findDrizzleSchemaProblems({
695
+ ...db._?.fullSchema,
696
+ ...Object.fromEntries(Object.entries(relations).map(([name, relation]) => [name, relation.table])),
697
+ ...config.schema
698
+ }, options, config.usePlural);
699
+ }, "drizzle");
700
+ registerSchemaCheck(instance, schemaCheck, { runtimeEnabled: checksSchema(options) });
701
+ return instance;
702
+ };
703
+ };
704
+ export { drizzleAdapter };
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@entro314labs/entro-auth-drizzle-adapter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.8.0-beta.11",
4
+ "bugs": {
5
+ "url": "https://github.com/better-auth/better-auth/issues"
6
+ },
7
+ "description": "Drizzle adapter for Entro Auth",
8
+ "type": "module",
9
+ "license": "MIT",
10
+ "homepage": "https://github.com/entro314-labs/entro-auth#readme",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/entro314-labs/entro-auth.git",
14
+ "directory": "packages/drizzle-adapter"
15
+ },
16
+ "keywords": [
17
+ "auth",
18
+ "drizzle",
19
+ "adapter",
20
+ "typescript",
21
+ "entro-auth"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "sideEffects": false,
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "main": "./dist/index.mjs",
31
+ "module": "./dist/index.mjs",
32
+ "types": "./dist/index.d.mts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.mts",
36
+ "dev-source": "./src/index.ts",
37
+ "default": "./dist/index.mjs"
38
+ },
39
+ "./generate-schema": {
40
+ "types": "./dist/generate-drizzle-schema.d.mts",
41
+ "dev-source": "./src/generate-drizzle-schema.ts",
42
+ "default": "./dist/generate-drizzle-schema.mjs"
43
+ }
44
+ },
45
+ "peerDependencies": {
46
+ "@entro314labs/entro-auth-core": "^1.8.0-beta.11",
47
+ "@better-auth/utils": "^0.4.2 || ^0.5.0",
48
+ "drizzle-orm": ">=1.0.0-rc.6 <2.0.0"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "drizzle-orm": {
52
+ "optional": true
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@entro314labs/entro-auth-core": "1.8.0-beta.11",
57
+ "@better-auth/utils": "0.5.1",
58
+ "drizzle-orm": "1.0.0-rc.6",
59
+ "tsdown": "0.23.1",
60
+ "typescript": "^6.0.3"
61
+ },
62
+ "scripts": {
63
+ "build": "tsdown",
64
+ "dev": "tsdown --watch",
65
+ "lint:package": "publint run --strict --pack false",
66
+ "lint:types": "attw --profile esm-only --pack .",
67
+ "typecheck": "tsc --noEmit",
68
+ "test": "vitest",
69
+ "coverage": "vitest run --coverage --coverage.provider=istanbul"
70
+ }
6
71
  }