driftsql 2.0.0-beta.5 → 2.0.1-beta
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/cli/index.d.ts +1 -2
- package/dist/cli/index.js +69 -2
- package/dist/cli/postgres-9C7eE0wB.js +5 -0
- package/dist/cli/postgres-DWtAqXNK.js +1 -0
- package/dist/cli/type-generator-Ba8bgnMm.js +7 -0
- package/dist/cli/type-generator-DbcqBk-4.js +1 -0
- package/dist/index.d.ts +45 -3
- package/dist/index.js +68 -3
- package/package.json +5 -3
- package/dist/index-CHiXYO9-.d.ts +0 -1
- package/dist/src-i3Ru40FK.js +0 -1742
package/dist/cli/index.d.ts
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import "../index-CHiXYO9-.js";
|
|
1
|
+
export { };
|
package/dist/cli/index.js
CHANGED
|
@@ -1,4 +1,71 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import "
|
|
2
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./postgres-9C7eE0wB.js";import"./type-generator-Ba8bgnMm.js";import{Command as o}from"commander";import s from"consola";import c from"node:fs/promises";import l from"node:path";import"chalk";import"postgres";import"@neondatabase/serverless";import"bun";var u=e({MySQLGenerator:()=>d}),d,f=t((()=>{d=class{generateCreateTable(e){let t=[];t.push(`CREATE TABLE \`${e.name}\` (`);let n=[];for(let t of e.columns)n.push(` `+this.generateColumnDefinition(t));if(e.primaryKey&&e.primaryKey.length>0){let t=e.primaryKey.map(e=>`\`${e}\``).join(`, `);n.push(` PRIMARY KEY (${t})`)}if(e.checks&&e.checks.length>0)for(let t of e.checks)n.push(` CONSTRAINT \`${t.name}\` CHECK (${t.expression})`);t.push(n.join(`,
|
|
3
|
+
`)),t.push(`) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`);let r=[t.join(`
|
|
4
|
+
`)];if(e.indexes&&e.indexes.length>0)for(let t of e.indexes)r.push(this.generateIndex(e.name,t));return r.join(`
|
|
3
5
|
|
|
4
|
-
|
|
6
|
+
`)}generateDropTable(e){return`DROP TABLE IF EXISTS \`${e}\`;`}generateColumnDefinition(e){let t=[`\`${e.name}\``];if(t.push(this.getColumnType(e)),e.notNull&&!e.primaryKey&&e.type!==`serial`&&e.type!==`bigserial`&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),(e.type===`serial`||e.type===`bigserial`)&&t.push(`AUTO_INCREMENT`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),e.references){let n=e.references;t.push(`REFERENCES \`${n.table}\`(\`${n.column}\`)`),n.onDelete&&t.push(`ON DELETE ${n.onDelete}`),n.onUpdate&&t.push(`ON UPDATE ${n.onUpdate}`)}return e.check&&t.push(`CHECK (${e.check})`),t.join(` `)}getColumnType(e){let t=e.type;if(t===`serial`)return`INT`;if(t===`bigserial`)return`BIGINT`;if(t===`timestamptz`)return`TIMESTAMP`;if(t===`jsonb`)return`JSON`;if(t===`bytea`)return`BLOB`;if(t===`double precision`)return`DOUBLE`;let n=t.toUpperCase();return e.length?n+=`(${e.length})`:e.precision&&(e.scale===void 0?n+=`(${e.precision})`:n+=`(${e.precision}, ${e.scale})`),n}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?`CURRENT_TIMESTAMP`:`'${e}'`:typeof e==`boolean`?e?`1`:`0`:String(e)}generateIndex(e,t){let n=t.unique?`UNIQUE `:``,r=t.type&&t.type!==`btree`?` USING ${t.type.toUpperCase()}`:``,i=t.columns.map(e=>`\`${e}\``).join(`, `);return`CREATE ${n}INDEX \`${t.name}\` ON \`${e}\`${r} (${i});`}}})),p=e({SQLiteGenerator:()=>m}),m,h=t((()=>{m=class{generateCreateTable(e){let t=[];t.push(`CREATE TABLE "${e.name}" (`);let n=[];for(let t of e.columns)n.push(` `+this.generateColumnDefinition(t));if(e.primaryKey&&e.primaryKey.length>0){let t=e.primaryKey.map(e=>`"${e}"`).join(`, `);n.push(` PRIMARY KEY (${t})`)}if(e.checks&&e.checks.length>0)for(let t of e.checks)n.push(` CONSTRAINT "${t.name}" CHECK (${t.expression})`);t.push(n.join(`,
|
|
7
|
+
`)),t.push(`);`);let r=[t.join(`
|
|
8
|
+
`)];if(e.indexes&&e.indexes.length>0)for(let t of e.indexes)r.push(this.generateIndex(e.name,t));return r.join(`
|
|
9
|
+
|
|
10
|
+
`)}generateDropTable(e){return`DROP TABLE IF EXISTS "${e}";`}generateColumnDefinition(e){let t=[`"${e.name}"`];if(t.push(this.getColumnType(e)),e.primaryKey&&(t.push(`PRIMARY KEY`),(e.type===`serial`||e.type===`bigserial`)&&t.push(`AUTOINCREMENT`)),e.notNull&&!e.primaryKey&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),e.references){let n=e.references;t.push(`REFERENCES "${n.table}"("${n.column}")`),n.onDelete&&t.push(`ON DELETE ${n.onDelete}`),n.onUpdate&&t.push(`ON UPDATE ${n.onUpdate}`)}return e.check&&t.push(`CHECK (${e.check})`),t.join(` `)}getColumnType(e){let t=e.type;return t===`serial`||t===`bigserial`||t===`bigint`||t===`smallint`?`INTEGER`:t===`varchar`||t===`char`||t===`timestamptz`||t===`timestamp`||t===`date`||t===`time`||t===`uuid`||t===`json`||t===`jsonb`?`TEXT`:t===`bytea`?`BLOB`:t===`decimal`||t===`numeric`||t===`real`||t===`double precision`?`REAL`:t===`boolean`?`INTEGER`:t.toUpperCase()}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?`CURRENT_TIMESTAMP`:`'${e}'`:typeof e==`boolean`?e?`1`:`0`:String(e)}generateIndex(e,t){let n=t.unique?`UNIQUE `:``,r=t.columns.map(e=>`"${e}"`).join(`, `);return`CREATE ${n}INDEX "${t.name}" ON "${e}" (${r});`}}}));n(),f(),h();var g=class{upStatements=[];downStatements=[];dialect;constructor(e=`postgres`){this.dialect=e}createTable(e){let t=e.getDefinition(),n=this.getGenerator();return this.upStatements.push(n.generateCreateTable(t)),this.downStatements.unshift(n.generateDropTable(t.name)),this}dropTable(e){let t=this.getGenerator();return this.upStatements.push(t.generateDropTable(e)),this}addColumn(e,t){return this.upStatements.push(`ALTER TABLE "${e}" ADD COLUMN ${t};`),this}dropColumn(e,t){return this.upStatements.push(`ALTER TABLE "${e}" DROP COLUMN "${t}";`),this}renameTable(e,t){return this.dialect===`postgres`?this.upStatements.push(`ALTER TABLE "${e}" RENAME TO "${t}";`):this.dialect===`mysql`?this.upStatements.push(`RENAME TABLE \`${e}\` TO \`${t}\`;`):this.upStatements.push(`ALTER TABLE "${e}" RENAME TO "${t}";`),this}raw(e,t){return this.upStatements.push(e),t&&this.downStatements.unshift(t),this}build(e,t){return{version:e,name:t,up:this.upStatements,down:this.downStatements}}getGenerator(){switch(this.dialect){case`postgres`:return new a;case`mysql`:return new d;case`sqlite`:return new m;default:return new a}}},_=class{client;constructor(e){this.client=e}async ensureMigrationsTable(){await this.client.query(`
|
|
11
|
+
CREATE TABLE IF NOT EXISTS _migrations (
|
|
12
|
+
version VARCHAR(255) PRIMARY KEY,
|
|
13
|
+
name VARCHAR(255) NOT NULL,
|
|
14
|
+
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
15
|
+
);
|
|
16
|
+
`)}async getAppliedMigrations(){return await this.ensureMigrationsTable(),(await this.client.query(`SELECT version FROM _migrations ORDER BY version`)).rows.map(e=>e.version)}async up(e){if((await this.getAppliedMigrations()).includes(e.version)){s.info(`Migration ${e.version} (${e.name}) already applied`);return}s.start(`Running migration ${e.version} (${e.name})`);for(let t of e.up)await this.client.query(t);await this.client.query(`INSERT INTO _migrations (version, name) VALUES ($1, $2)`,[e.version,e.name]),s.success(`Migration ${e.version} (${e.name}) applied successfully`)}async down(e){if(!(await this.getAppliedMigrations()).includes(e.version)){s.info(`Migration ${e.version} (${e.name}) not applied`);return}s.start(`Rolling back migration ${e.version} (${e.name})`);for(let t of e.down)await this.client.query(t);await this.client.query(`DELETE FROM _migrations WHERE version = $1`,[e.version]),s.success(`Migration ${e.version} (${e.name}) rolled back successfully`)}async upAll(e){let t=await this.getAppliedMigrations(),n=e.filter(e=>!t.includes(e.version));if(n.length===0){s.info(`No pending migrations`);return}s.info(`Found ${n.length} pending migrations`);for(let e of n)await this.up(e)}async downAll(e){let t=await this.getAppliedMigrations(),n=e.filter(e=>t.includes(e.version)).reverse();if(n.length===0){s.info(`No migrations to rollback`);return}s.info(`Rolling back ${n.length} migrations`);for(let e of n)await this.down(e)}async reset(e){await this.downAll(e),await this.upAll(e)}},v=class{dialect;constructor(e=`postgres`){this.dialect=e}detectChanges(e,t){let n=[],r=new Map(e.map(e=>[e.name,e])),i=new Map(t.map(e=>[e.name,e]));for(let[e,t]of i){let i=r.get(e);i?(n.push(...this.detectColumnChanges(i,t)),n.push(...this.detectIndexChanges(i,t))):n.push({type:`create_table`,table:e,details:t})}for(let[e]of r)i.has(e)||n.push({type:`drop_table`,table:e});return n}detectColumnChanges(e,t){let n=[],r=new Map(e.columns.map(e=>[e.name,e])),i=new Map(t.columns.map(e=>[e.name,e]));for(let[e,a]of i){let i=r.get(e);i?this.hasColumnChanged(i,a)&&n.push({type:`modify_column`,table:t.name,details:{old:i,new:a}}):n.push({type:`add_column`,table:t.name,details:a})}for(let[e]of r)i.has(e)||n.push({type:`drop_column`,table:t.name,details:{name:e}});return n}detectIndexChanges(e,t){let n=[],r=new Map((e.indexes||[]).map(e=>[e.name,e])),i=new Map((t.indexes||[]).map(e=>[e.name,e]));for(let[e,a]of i)r.has(e)||n.push({type:`create_index`,table:t.name,details:a});for(let[e]of r)i.has(e)||n.push({type:`drop_index`,table:t.name,details:{name:e}});return n}hasColumnChanged(e,t){return e.type!==t.type||e.length!==t.length||e.precision!==t.precision||e.scale!==t.scale||e.notNull!==t.notNull||e.unique!==t.unique||e.default!==t.default||JSON.stringify(e.references)!==JSON.stringify(t.references)}generateMigration(e,t,n){let r=new g(this.dialect);for(let t of e)switch(t.type){case`create_table`:{let e=t.details,n=this.getGenerator(),i=n.generateCreateTable(e);r.raw(i,n.generateDropTable(e.name));break}case`drop_table`:{let e=this.getGenerator();r.raw(e.generateDropTable(t.table));break}case`add_column`:{let e=t.details,n=this.generateColumnSQL(e);r.raw(`ALTER TABLE "${t.table}" ADD COLUMN ${n};`,`ALTER TABLE "${t.table}" DROP COLUMN "${e.name}";`);break}case`drop_column`:{let e=t.details.name;r.raw(`ALTER TABLE "${t.table}" DROP COLUMN "${e}";`);break}case`create_index`:{let e=t.details,n=this.generateIndexSQL(t.table,e);r.raw(n,`DROP INDEX "${e.name}";`);break}case`drop_index`:{let e=t.details.name;r.raw(`DROP INDEX "${e}";`);break}}return r}generateColumnSQL(e){let t=[`"${e.name}"`];return t.push(e.type.toUpperCase()),e.length&&(t[1]+=`(${e.length})`),e.notNull&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),t.join(` `)}generateIndexSQL(e,t){let n=t.unique?`UNIQUE `:``,r=t.columns.map(e=>`"${e}"`).join(`, `);return`CREATE ${n}INDEX "${t.name}" ON "${e}" (${r});`}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?e.toUpperCase():`'${e}'`:typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e)}getGenerator(){let{PostgresGenerator:e}=(n(),r(i)),{MySQLGenerator:t}=(f(),r(u)),{SQLiteGenerator:a}=(h(),r(p));switch(this.dialect){case`postgres`:return new e;case`mysql`:return new t;case`sqlite`:return new a;default:return new e}}};function y(e,t,n=`postgres`){return new v(n).detectChanges(e,t)}function b(e,t,n,r=`postgres`){return new v(r).generateMigration(e,t,n)}var x=class{snapshotPath;constructor(e=`./.driftsql/snapshot.json`){this.snapshotPath=e}async save(e){let t={version:`1`,timestamp:Date.now(),tables:e},n=l.dirname(this.snapshotPath);await c.mkdir(n,{recursive:!0}),await c.writeFile(this.snapshotPath,JSON.stringify(t,null,2),`utf8`)}async load(){try{let e=await c.readFile(this.snapshotPath,`utf8`);return JSON.parse(e)}catch{return null}}async exists(){try{return await c.access(this.snapshotPath),!0}catch{return!1}}};const S=new o;S.name(`driftsql`).description(`DriftSQL CLI - Database migrations and schema management`).version(`0.0.1`),S.command(`migrate:up`).description(`Run all pending migrations`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).option(`-c, --config <path>`,`Config file path`,`./driftsql.config.ts`).action(async e=>{try{let{client:t,migrations:n}=await w(e.dir,e.config);await new _(t).upAll(n),await t.close(),s.success(`All migrations applied successfully`)}catch(e){s.error(`Migration failed:`,e),process.exit(1)}}),S.command(`migrate:down`).description(`Rollback the last migration`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).option(`-c, --config <path>`,`Config file path`,`./driftsql.config.ts`).action(async e=>{try{let{client:t,migrations:n}=await w(e.dir,e.config),r=new _(t),i=await r.getAppliedMigrations(),a=n.find(e=>e.version===i[i.length-1]);a?await r.down(a):s.info(`No migrations to rollback`),await t.close()}catch(e){s.error(`Rollback failed:`,e),process.exit(1)}}),S.command(`migrate:reset`).description(`Reset all migrations (down then up)`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).option(`-c, --config <path>`,`Config file path`,`./driftsql.config.ts`).action(async e=>{try{let{client:t,migrations:n}=await w(e.dir,e.config);await new _(t).reset(n),await t.close(),s.success(`All migrations reset successfully`)}catch(e){s.error(`Reset failed:`,e),process.exit(1)}}),S.command(`migrate:status`).description(`Show migration status`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).option(`-c, --config <path>`,`Config file path`,`./driftsql.config.ts`).action(async e=>{try{let{client:t,migrations:n}=await w(e.dir,e.config),r=await new _(t).getAppliedMigrations();s.info(`Migration Status:
|
|
17
|
+
`);for(let e of n){let t=r.includes(e.version)?`✓ Applied`:`✗ Pending`;s.log(`${t} - ${e.version} (${e.name})`)}await t.close()}catch(e){s.error(`Failed to get status:`,e),process.exit(1)}}),S.command(`migrate:create <name>`).description(`Create a new migration file`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).action(async(e,t)=>{try{let n=new Date().toISOString().replace(/[-:T.]/g,``).slice(0,14),r=`${n}_${e}.ts`,i=l.join(t.dir,r);await c.mkdir(t.dir,{recursive:!0});let a=`import { createMigration } from 'driftsql'
|
|
18
|
+
|
|
19
|
+
export const migration = createMigration('postgres')
|
|
20
|
+
.raw('-- Add your migration SQL here')
|
|
21
|
+
.build('${n}', '${e}')
|
|
22
|
+
`;await c.writeFile(i,a,`utf8`),s.success(`Created migration: ${r}`)}catch(e){s.error(`Failed to create migration:`,e),process.exit(1)}}),S.command(`migrate:generate [name]`).description(`Automatically generate migration from schema changes`).option(`-s, --schema <path>`,`Schema file path`,`./schema.ts`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).action(async(e,t)=>{try{let n=new x,r=l.resolve(process.cwd(),t.schema);s.start(`Loading schema...`);let i=await import(r),a=i.default||i.schema;(!a||!Array.isArray(a))&&(s.error(`Schema file must export default or named "schema" as an array of table definitions`),s.info(`Example: export default [usersTable.getDefinition(), postsTable.getDefinition()]`),process.exit(1));let o=a,u=await n.load();if(!u){s.info(`No previous schema snapshot found, creating initial migration...`);let r=new Date().toISOString().replace(/[-:T.]/g,``).slice(0,14),i=e||`initial`,a=`${r}_${i}.ts`,u=l.join(t.dir,a);await c.mkdir(t.dir,{recursive:!0});let{PostgresGenerator:d}=await import(`./postgres-DWtAqXNK.js`),f=new d,p=o.map(e=>f.generateCreateTable(e)).map(e=>` .raw(\`${e.replace(/`/g,"\\`")}\`)`).join(`
|
|
23
|
+
`),m=`import { createMigration } from 'driftsql'
|
|
24
|
+
|
|
25
|
+
// Initial migration - automatically generated
|
|
26
|
+
// Generated at: ${new Date().toISOString()}
|
|
27
|
+
|
|
28
|
+
export const migration = createMigration('postgres')
|
|
29
|
+
${p}
|
|
30
|
+
.build('${r}', '${i}')
|
|
31
|
+
`;await c.writeFile(u,m,`utf8`),await n.save(o);let{generateTypesFromSchema:h}=await import(`./type-generator-DbcqBk-4.js`);await h(o,l.join(process.cwd(),`db-types.ts`)),s.success(`\nCreated initial migration: ${a}`),s.success(`Generated TypeScript types: db-types.ts`),s.info(`Snapshot saved. Run "driftsql migrate:up" to apply changes.`);return}s.info(`Detecting changes...`);let d=y(u.tables,o,`postgres`);if(d.length===0){s.success(`No schema changes detected!`);return}s.info(`Found ${d.length} change(s):`),d.forEach((e,t)=>{s.log(` ${t+1}. ${e.type} - ${e.table}`)});let f=new Date().toISOString().replace(/[-:T.]/g,``).slice(0,14),p=e||`auto_migration`,m=`${f}_${p}.ts`,h=l.join(t.dir,m);await c.mkdir(t.dir,{recursive:!0});let g=b(d,f,p).build(f,p).up.map(e=>` .raw(\`${e.replace(/`/g,"\\`")}\``).join(`
|
|
32
|
+
`),_=`import { createMigration } from 'driftsql'
|
|
33
|
+
|
|
34
|
+
// This migration was automatically generated
|
|
35
|
+
// Generated at: ${new Date().toISOString()}
|
|
36
|
+
// Changes: ${d.length}
|
|
37
|
+
|
|
38
|
+
export const migration = createMigration('postgres')
|
|
39
|
+
${g}
|
|
40
|
+
.build('${f}', '${p}')
|
|
41
|
+
`;await c.writeFile(h,_,`utf8`),await n.save(o);let{generateTypesFromSchema:v}=await import(`./type-generator-DbcqBk-4.js`);await v(o,l.join(process.cwd(),`db-types.ts`)),s.success(`\nGenerated migration: ${m}`),s.success(`Updated TypeScript types: db-types.ts`),s.info(`Snapshot updated. Run "driftsql migrate:up" to apply changes.`)}catch(e){s.error(`Failed to generate migration:`,e),process.exit(1)}}),S.command(`db:inspect`).description(`Inspect database and generate TypeScript types`).option(`-c, --config <path>`,`Config file path`,`./driftsql.config.ts`).option(`-o, --output <path>`,`Output file path`,`./db-types.ts`).action(async e=>{try{let t=await C(e.config);await t.inspectDB({driver:t.getDriver(),outputFile:e.output}),await t.close()}catch(e){s.error(`Inspection failed:`,e),process.exit(1)}}),S.command(`generate:types`).description(`Generate TypeScript types from schema file`).option(`-s, --schema <path>`,`Schema file path`,`./schema.ts`).option(`-o, --output <path>`,`Output file path`,`./db-types.ts`).action(async e=>{try{let t=l.resolve(process.cwd(),e.schema),n=l.resolve(process.cwd(),e.output);s.start(`Loading schema...`);let r=await import(t),i=r.default||r.schema;(!i||!Array.isArray(i))&&(s.error(`Schema file must export default or named "schema" as an array of table definitions`),process.exit(1));let{generateTypesFromSchema:a}=await import(`./type-generator-DbcqBk-4.js`);await a(i,n),s.success(`TypeScript types generated: ${e.output}`)}catch(e){s.error(`Type generation failed:`,e),process.exit(1)}}),S.command(`init`).description(`Initialize DriftSQL with a basic notes schema`).option(`-d, --dir <directory>`,`Migrations directory`,`./migrations`).action(async e=>{try{await c.mkdir(e.dir,{recursive:!0});let t=`.driftsql/
|
|
42
|
+
.env
|
|
43
|
+
`,n=l.join(process.cwd(),`driftsql.config.ts`),r=l.join(process.cwd(),`schema.ts`),i=l.join(process.cwd(),`.env.example`),a=l.join(process.cwd(),`.gitignore`),o=[{path:n,content:`import { SQLClient, PostgresDriver } from 'driftsql'
|
|
44
|
+
|
|
45
|
+
export default new SQLClient({
|
|
46
|
+
driver: new PostgresDriver({
|
|
47
|
+
connectionString: process.env.DATABASE_URL!,
|
|
48
|
+
}),
|
|
49
|
+
})
|
|
50
|
+
`,name:`driftsql.config.ts`},{path:r,content:`import { createTable, serial, varchar, text, timestamp, boolean } from 'driftsql'
|
|
51
|
+
|
|
52
|
+
const notesTable = createTable('notes', (table) => {
|
|
53
|
+
table
|
|
54
|
+
.column(serial('id').primaryKey())
|
|
55
|
+
.column(varchar('title', 255).notNull())
|
|
56
|
+
.column(text('content'))
|
|
57
|
+
.column(boolean('is_archived').default(false).notNull())
|
|
58
|
+
.column(timestamp('created_at').default('CURRENT_TIMESTAMP').notNull())
|
|
59
|
+
.column(timestamp('updated_at').default('CURRENT_TIMESTAMP').notNull())
|
|
60
|
+
.index('idx_notes_archived', ['is_archived'])
|
|
61
|
+
.index('idx_notes_created_at', ['created_at'])
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
// Export array of table definitions
|
|
65
|
+
export default [notesTable.getDefinition()]
|
|
66
|
+
`,name:`schema.ts`},{path:i,content:`DATABASE_URL=postgresql://user:password@localhost:5432/mydb
|
|
67
|
+
`,name:`.env.example`}];for(let e of o)try{await c.access(e.path),s.warn(`${e.name} already exists, skipping...`)}catch{await c.writeFile(e.path,e.content,`utf8`),s.success(`Created ${e.name}`)}try{(await c.readFile(a,`utf8`)).includes(`.driftsql/`)||(await c.appendFile(a,`
|
|
68
|
+
`+t),s.success(`Updated .gitignore`))}catch{await c.writeFile(a,t,`utf8`),s.success(`Created .gitignore`)}s.success(`
|
|
69
|
+
✨ DriftSQL initialized successfully!
|
|
70
|
+
`),s.info(`Next steps:`),s.info(`1. Copy .env.example to .env and update DATABASE_URL`),s.info(`2. Run: driftsql migrate:generate initial (generates migration + types)`),s.info(`3. Run: driftsql migrate:up`),s.info(`4. Import Database type from db-types.ts for type safety`),s.info(`5. Edit schema.ts and run migrate:generate to auto-detect changes!
|
|
71
|
+
`)}catch(e){s.error(`Initialization failed:`,e),process.exit(1)}});async function C(e){try{let t=await import(l.resolve(process.cwd(),e));return t.default||t.client}catch(t){throw s.error(`Failed to load config from ${e}`),t}}async function w(e,t){let n=await C(t),r=[];try{let t=l.resolve(process.cwd(),e),i=(await c.readdir(t)).filter(e=>e.endsWith(`.ts`)||e.endsWith(`.js`)).sort();for(let e of i){let n=await import(l.join(t,e)),i=n.migration||n.default;i&&r.push(i)}return{client:n,migrations:r}}catch(t){throw s.error(`Failed to load migrations from ${e}`),t}}S.parse();export{};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(e,t)=>()=>(e&&(t=e(e=0)),t),a=t=>{let n={};for(var r in t)e(n,r,{get:t[r],enumerable:!0});return n},o=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(var c=n(a),l=0,u=c.length,d;l<u;l++)d=c[l],!r.call(i,d)&&d!==o&&e(i,d,{get:(e=>a[e]).bind(null,d),enumerable:!(s=t(a,d))||s.enumerable});return i},s=t=>o(e({},`__esModule`,{value:!0}),t),c=a({PostgresGenerator:()=>l}),l,u=i((()=>{l=class{generateCreateTable(e){let t=[];t.push(`CREATE TABLE "${e.name}" (`);let n=[];for(let t of e.columns)n.push(` `+this.generateColumnDefinition(t));if(e.primaryKey&&e.primaryKey.length>0){let t=e.primaryKey.map(e=>`"${e}"`).join(`, `);n.push(` PRIMARY KEY (${t})`)}if(e.checks&&e.checks.length>0)for(let t of e.checks)n.push(` CONSTRAINT "${t.name}" CHECK (${t.expression})`);t.push(n.join(`,
|
|
2
|
+
`)),t.push(`);`);let r=[t.join(`
|
|
3
|
+
`)];if(e.indexes&&e.indexes.length>0)for(let t of e.indexes)r.push(this.generateIndex(e.name,t));return r.join(`
|
|
4
|
+
|
|
5
|
+
`)}generateDropTable(e){return`DROP TABLE IF EXISTS "${e}" CASCADE;`}generateColumnDefinition(e){let t=[`"${e.name}"`];if(t.push(this.getColumnType(e)),e.primaryKey&&!e.type.includes(`serial`)&&t.push(`PRIMARY KEY`),e.notNull&&!e.primaryKey&&!e.type.includes(`serial`)&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),e.references){let n=e.references;t.push(`REFERENCES "${n.table}"("${n.column}")`),n.onDelete&&t.push(`ON DELETE ${n.onDelete}`),n.onUpdate&&t.push(`ON UPDATE ${n.onUpdate}`)}return e.check&&t.push(`CHECK (${e.check})`),t.join(` `)}getColumnType(e){let t=e.type.toUpperCase();return e.length?t+=`(${e.length})`:e.precision&&(e.scale===void 0?t+=`(${e.precision})`:t+=`(${e.precision}, ${e.scale})`),t}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?e.toUpperCase():`'${e}'`:typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e)}generateIndex(e,t){let n=t.unique?`UNIQUE `:``,r=t.type?` USING ${t.type.toUpperCase()}`:``,i=t.columns.map(e=>`"${e}"`).join(`, `);return`CREATE ${n}INDEX "${t.name}" ON "${e}"${r} (${i});`}}}));export{a,i,u as n,s as o,c as r,l as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./postgres-9C7eE0wB.js";e();export{t as PostgresGenerator};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import e from"node:fs/promises";var t=class{generateTypes(e){let t=`// This file was automatically generated - DO NOT EDIT
|
|
2
|
+
|
|
3
|
+
`;for(let n of e)t+=this.generateTableInterface(n),t+=`
|
|
4
|
+
|
|
5
|
+
`;return t+=this.generateDatabaseInterface(e),t}generateTableInterface(e){let t=[`export interface ${this.pascalCase(e.name)} {`];for(let n of e.columns){let e=this.columnToTypeScript(n),r=!n.notNull&&!n.primaryKey?`?`:``;t.push(` ${n.name}${r}: ${e}`)}return t.push(`}`),t.join(`
|
|
6
|
+
`)}generateDatabaseInterface(e){let t=[`export interface Database {`];for(let n of e){let e=this.pascalCase(n.name);t.push(` ${n.name}: ${e}`)}return t.push(`}`),t.join(`
|
|
7
|
+
`)}columnToTypeScript(e){let t=!e.notNull&&!e.primaryKey,n;switch(e.type.toLowerCase()){case`serial`:case`bigserial`:case`integer`:case`int`:case`bigint`:case`smallint`:case`numeric`:case`decimal`:case`real`:case`double precision`:n=`number`;break;case`text`:case`varchar`:case`char`:case`uuid`:n=`string`;break;case`boolean`:n=`boolean`;break;case`timestamp`:case`timestamptz`:case`date`:case`time`:n=`Date | string`;break;case`json`:case`jsonb`:n=`any`;break;case`bytea`:n=`Buffer`;break;default:n=`any`}return t?`${n} | null`:n}pascalCase(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``)}async writeToFile(t,n){let r=this.generateTypes(t);await e.writeFile(n,r,`utf8`)}};async function n(e,n){await new t().writeToFile(e,n)}export{n,t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./type-generator-Ba8bgnMm.js";export{t as TypeGenerator,e as generateTypesFromSchema};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import "./index-CHiXYO9-.js";
|
|
1
|
+
import { PoolConfig } from "@neondatabase/serverless";
|
|
3
2
|
|
|
4
3
|
//#region src/types.d.ts
|
|
5
4
|
interface QueryResult<T = any> {
|
|
@@ -70,6 +69,49 @@ declare class PostgresDriver implements DatabaseDriver {
|
|
|
70
69
|
close(): Promise<void>;
|
|
71
70
|
}
|
|
72
71
|
//#endregion
|
|
72
|
+
//#region src/drivers/neon.d.ts
|
|
73
|
+
interface NeonDriverConfig extends PoolConfig {
|
|
74
|
+
connectionString: string;
|
|
75
|
+
}
|
|
76
|
+
declare class NeonDriver implements DatabaseDriver {
|
|
77
|
+
private pool;
|
|
78
|
+
findFirst?: (table: string, where?: Record<string, any>) => Promise<QueryResult<any> | null>;
|
|
79
|
+
findMany?: (table: string, options?: {
|
|
80
|
+
where?: Record<string, any>;
|
|
81
|
+
limit?: number;
|
|
82
|
+
offset?: number;
|
|
83
|
+
}) => Promise<QueryResult<any>>;
|
|
84
|
+
insert?: (table: string, data: Record<string, any>) => Promise<QueryResult<any>>;
|
|
85
|
+
update?: (table: string, data: Record<string, any>, where: Record<string, any>) => Promise<QueryResult<any>>;
|
|
86
|
+
delete?: (table: string, where: Record<string, any>) => Promise<number>;
|
|
87
|
+
constructor(config: NeonDriverConfig);
|
|
88
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
89
|
+
close(): Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/drivers/bun.d.ts
|
|
93
|
+
interface BunSQLDriverConfig {
|
|
94
|
+
connectionString?: string;
|
|
95
|
+
url?: string;
|
|
96
|
+
adapter?: 'postgres' | 'mysql' | 'sqlite';
|
|
97
|
+
[key: string]: any;
|
|
98
|
+
}
|
|
99
|
+
declare class BunSQLDriver implements DatabaseDriver {
|
|
100
|
+
private client;
|
|
101
|
+
findFirst?: (table: string, where?: Record<string, any>) => Promise<QueryResult<any> | null>;
|
|
102
|
+
findMany?: (table: string, options?: {
|
|
103
|
+
where?: Record<string, any>;
|
|
104
|
+
limit?: number;
|
|
105
|
+
offset?: number;
|
|
106
|
+
}) => Promise<QueryResult<any>>;
|
|
107
|
+
insert?: (table: string, data: Record<string, any>) => Promise<QueryResult<any>>;
|
|
108
|
+
update?: (table: string, data: Record<string, any>, where: Record<string, any>) => Promise<QueryResult<any>>;
|
|
109
|
+
delete?: (table: string, where: Record<string, any>) => Promise<number>;
|
|
110
|
+
constructor(config: BunSQLDriverConfig);
|
|
111
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
112
|
+
close(): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
73
115
|
//#region src/drivers/helpers/postgres.d.ts
|
|
74
116
|
interface PostgresHelpers {
|
|
75
117
|
findFirst?(table: string, where?: Record<string, any>): Promise<QueryResult<any> | null>;
|
|
@@ -360,4 +402,4 @@ declare class SQLClient<DT = any> {
|
|
|
360
402
|
}
|
|
361
403
|
declare const DriftSQLClient: typeof SQLClient;
|
|
362
404
|
//#endregion
|
|
363
|
-
export { ClientOptions, Column, ColumnDefinition, ColumnType, type ConnectionError, type DatabaseDriver, DriftSQLClient, IndexDefinition, Migration, MigrationBuilder, MigrationRunner, MySQLGenerator, MySQLHelpers, PostgresDriver, PostgresGenerator, PostgresHelpers, type QueryError, type QueryField, type QueryResult, SQLClient, SQLDialect, SQLiteGenerator, SQLiteHelpers, SchemaChange, SchemaDiffer, SchemaSnapshot, SnapshotManager, Table, TableDefinition, TypeGenerator, bigint, bigserial, boolean, bytea, char, createMigration, createMySQLHelpers, createPostgresHelpers, createSQLiteHelpers, createTable, date, decimal, detectChanges, doublePrecision, generateMigrationFromChanges, generateTypesFromSchema, integer, json, jsonb, numeric, real, serial, smallint, text, time, timestamp, timestamptz, uuid, varchar };
|
|
405
|
+
export { BunSQLDriver, ClientOptions, Column, ColumnDefinition, ColumnType, type ConnectionError, type DatabaseDriver, DriftSQLClient, IndexDefinition, Migration, MigrationBuilder, MigrationRunner, MySQLGenerator, MySQLHelpers, NeonDriver, PostgresDriver, PostgresGenerator, PostgresHelpers, type QueryError, type QueryField, type QueryResult, SQLClient, SQLDialect, SQLiteGenerator, SQLiteHelpers, SchemaChange, SchemaDiffer, SchemaSnapshot, SnapshotManager, Table, TableDefinition, TypeGenerator, bigint, bigserial, boolean, bytea, char, createMigration, createMySQLHelpers, createPostgresHelpers, createSQLiteHelpers, createTable, date, decimal, detectChanges, doublePrecision, generateMigrationFromChanges, generateTypesFromSchema, integer, json, jsonb, numeric, real, serial, smallint, text, time, timestamp, timestamptz, uuid, varchar };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,69 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import e from"consola";import t from"chalk";import n from"node:fs/promises";import r from"postgres";import{Pool as i}from"@neondatabase/serverless";import{SQL as a}from"bun";import o from"node:path";var s=Object.defineProperty,c=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,d=(e,t)=>()=>(e&&(t=e(e=0)),t),f=e=>{let t={};for(var n in e)s(t,n,{get:e[n],enumerable:!0});return t},ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=l(t),a=0,o=i.length,d;a<o;a++)d=i[a],!u.call(e,d)&&d!==n&&s(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=c(t,d))||r.enumerable});return e},p=e=>ee(s({},`__esModule`,{value:!0}),e);function m(e){return`transaction`in e&&typeof e.transaction==`function`}function h(e){return`prepare`in e&&typeof e.prepare==`function`}var g=class extends Error{constructor(e,t,n){super(e),this.driverType=t,this.originalError=n,this.name=`DatabaseError`}},_=class extends g{constructor(e,t,n){super(`Query failed: ${t}`,e,n),this.name=`QueryError`}};const v=(e,t=3e4)=>Promise.race([e,new Promise((e,n)=>setTimeout(()=>n(Error(`Query timeout after ${t}ms`)),t))]),y=async(t,n=3,r=1e3)=>{for(let i=1;i<=n;i++)try{return await t()}catch(t){if(i===n)throw t;let a=r*2**(i-1);e.warn(`Query attempt ${i} failed, retrying in ${a}ms...`,t),await new Promise(e=>setTimeout(e,a))}throw Error(`Max retries exceeded`)},te=(t,n=!1,r=`postgres`)=>{let i=n?` | null`:``;switch(t.toLowerCase()){case`uuid`:return`string${i}`;case`character varying`:case`varchar`:case`text`:case`char`:case`character`:case`longtext`:case`mediumtext`:case`tinytext`:return`string${i}`;case`integer`:case`int`:case`int4`:case`smallint`:case`int2`:case`bigint`:case`int8`:case`serial`:case`bigserial`:case`numeric`:case`decimal`:case`real`:case`float4`:case`double precision`:case`float8`:case`tinyint`:case`mediumint`:case`float`:case`double`:return`number${i}`;case`boolean`:case`bool`:case`bit`:return`boolean${i}`;case`timestamp`:case`timestamp with time zone`:case`timestamp without time zone`:case`timestamptz`:case`date`:case`time`:case`time with time zone`:case`time without time zone`:case`timetz`:case`interval`:case`datetime`:case`year`:return`Date${i}`;case`json`:case`jsonb`:return`any${i}`;case`array`:return`any[]${i}`;case`bytea`:case`binary`:case`varbinary`:case`blob`:case`longblob`:case`mediumblob`:case`tinyblob`:return`Buffer${i}`;case`enum`:case`set`:return`string${i}`;default:return e.warn(`Unknown ${r} type: ${t}, defaulting to 'any'`),`any${i}`}},ne=e=>`${e.constructor.name||`unknown driver`}`;var re=async r=>{e.warn(`inspectDB is experimental and may make mistakes when inspecting your database. However it will not destroy your database.`);let{driver:i,outputFile:a=`db-types.ts`}=r,o=ne(i);e.start(`Inspecting database using ${o} driver`);let s=new $({driver:i}),c=``;try{let r,i;if(o===`mysql`){let t=(await v(y(()=>s.query("SELECT DATABASE() as `database`",[])),1e4)).rows[0]?.database;if(!t)throw Error(`Could not determine current MySQL database name`);e.success(`Using MySQL database: ${t}`),r=`SELECT TABLE_NAME as table_name
|
|
2
|
+
FROM information_schema.tables
|
|
3
|
+
WHERE TABLE_SCHEMA = ?
|
|
4
|
+
AND TABLE_TYPE = 'BASE TABLE'
|
|
5
|
+
ORDER BY TABLE_NAME`,i=t}else if(o===`postgres`||o===`neon`)r=`SELECT table_name
|
|
6
|
+
FROM information_schema.tables
|
|
7
|
+
WHERE table_schema = $1
|
|
8
|
+
AND table_type = 'BASE TABLE'
|
|
9
|
+
ORDER BY table_name`,i=`public`;else if(o===`libsql`||o===`sqlite`||o===`sqlitecloud`)r=`SELECT name as table_name
|
|
10
|
+
FROM sqlite_master
|
|
11
|
+
WHERE type = 'table'
|
|
12
|
+
ORDER BY name`,i=void 0;else throw Error(`Unsupported driver type: ${o}`);let l=await v(y(()=>s.query(r,i?[i]:[])),3e4);e.info(`Tables in the database:`,l.rows.map(e=>e.table_name).join(`, `));let u=0,d=l.rows.length;for(let n of l.rows){let r=n.table_name;if(!(r.startsWith(`sqlite_sequence`)||r.startsWith(`_prisma_migrations`))){u++,e.info(`[${u}/${d}] Inspecting table: ${r}`);try{let n,a;o===`mysql`?(n=`
|
|
13
|
+
SELECT
|
|
14
|
+
COLUMN_NAME as column_name,
|
|
15
|
+
DATA_TYPE as data_type,
|
|
16
|
+
IS_NULLABLE as is_nullable,
|
|
17
|
+
COLUMN_DEFAULT as column_default
|
|
18
|
+
FROM information_schema.columns
|
|
19
|
+
WHERE TABLE_NAME = ?
|
|
20
|
+
AND TABLE_SCHEMA = ?
|
|
21
|
+
ORDER BY ORDINAL_POSITION
|
|
22
|
+
`,a=[r,i]):o===`postgres`||o===`neon`?(n=`
|
|
23
|
+
SELECT
|
|
24
|
+
column_name,
|
|
25
|
+
data_type,
|
|
26
|
+
is_nullable,
|
|
27
|
+
column_default
|
|
28
|
+
FROM information_schema.columns
|
|
29
|
+
WHERE table_name = $1
|
|
30
|
+
AND table_schema = $2
|
|
31
|
+
ORDER BY ordinal_position
|
|
32
|
+
`,a=[r,i]):(n=`
|
|
33
|
+
SELECT
|
|
34
|
+
name as column_name,
|
|
35
|
+
type as data_type,
|
|
36
|
+
CASE WHEN "notnull" = 0 THEN 'YES' ELSE 'NO' END as is_nullable,
|
|
37
|
+
dflt_value as column_default
|
|
38
|
+
FROM pragma_table_info(?)
|
|
39
|
+
ORDER BY cid
|
|
40
|
+
`,a=[r]);let l=await v(y(()=>s.query(n,a)),15e3);if(l.rows.length===0){e.info(`No columns found for table: ${r}`);continue}e.info(`Columns in '${r}'`),l.rows.forEach(n=>{let r=n.data_type+(n.is_nullable===`YES`?` (nullable)`:``);e.info(` > ${t.bold.yellow(r)} > ${n.column_name}`)});let u=new Map;l.rows.forEach(e=>{u.has(e.column_name)||u.set(e.column_name,e)}),c+=`export interface ${r.charAt(0).toUpperCase()+r.slice(1)} {\n`;for(let e of u.values()){let t=te(e.data_type,e.is_nullable===`YES`,o);c+=` ${e.column_name}: ${t};\n`}c+=`}
|
|
3
41
|
|
|
4
|
-
|
|
42
|
+
`}catch(t){e.error(`Failed to process table ${r}:`,t),e.info(`Skipping table ${r} and continuing...`);continue}}}c+=`export interface Database {
|
|
43
|
+
`;for(let e of l.rows){if(e.table_name.startsWith(`sqlite_sequence`)||e.table_name.startsWith(`_prisma_migrations`))continue;let t=e.table_name.charAt(0).toUpperCase()+e.table_name.slice(1);c+=` ${e.table_name}: ${t};\n`}c+=`}
|
|
44
|
+
|
|
45
|
+
`,await n.writeFile(a,c,`utf8`),e.success(`TypeScript types written to ${a}`),e.success(`Successfully processed ${u} tables`)}catch(t){throw e.error(`Fatal error during database inspection:`,t),t}finally{await s.close().catch(t=>e.error(`Error closing client:`,t))}};function b(e){return{async findFirst(t,n){let r=[],i=[],a=1;if(n)for(let[e,t]of Object.entries(n))r.push(`"${e}" = $${a}`),i.push(t),a++;let o=`SELECT * FROM "${t}" ${r.length>0?`WHERE ${r.join(` AND `)}`:``} LIMIT 1`;return await e.query(o,i)},async findMany(t,n){let r=[],i=[],a=1;if(n?.where)for(let[e,t]of Object.entries(n.where))r.push(`"${e}" = $${a}`),i.push(t),a++;let o=r.length>0?`WHERE ${r.join(` AND `)}`:``,s=n?.limit?`LIMIT $${a++}`:``,c=n?.offset?`OFFSET $${a++}`:``;n?.limit&&i.push(n.limit),n?.offset&&i.push(n.offset);let l=`SELECT * FROM "${t}" ${o} ${s} ${c}`.trim();return await e.query(l,i)},async insert(t,n){let r=Object.keys(n),i=Object.values(n),a=`INSERT INTO "${t}" (${r.map(e=>`"${e}"`).join(`, `)}) VALUES (${r.map((e,t)=>`$${t+1}`).join(`, `)}) RETURNING *`;return await e.query(a,i)},async update(t,n,r){let i=Object.entries(n),a=Object.entries(r),o=[],s=1,c=i.map(([e,t])=>(o.push(t),`"${e}" = $${s++}`)),l=a.map(([e,t])=>(o.push(t),`"${e}" = $${s++}`)),u=`UPDATE "${t}" SET ${c.join(`, `)} WHERE ${l.join(` AND `)} RETURNING *`;return await e.query(u,o)},async delete(t,n){let r=[],i=[],a=1;for(let[e,t]of Object.entries(n))r.push(`"${e}" = $${a}`),i.push(t),a++;let o=`DELETE FROM "${t}" WHERE ${r.join(` AND `)}`;return(await e.query(o,i)).rowCount}}}var ie=class{client;findFirst;findMany;insert;update;delete;constructor(e){this.client=r(e.connectionString,{max:e.max??10,idle_timeout:e.idle_timeout??30,connect_timeout:e.connect_timeout??10,prepare:!1,transform:{undefined:null}});let t=b(this);this.findFirst=t.findFirst,this.findMany=t.findMany,this.insert=t.insert,this.update=t.update,this.delete=t.delete}async query(e,t){try{let n=await this.client.unsafe(e,t||[]),r=Array.isArray(n)?[...n]:[];return{rows:r,rowCount:r.length,command:n.command}}catch(t){throw new _(`postgres`,e,t)}}async close(){await this.client.end()}},ae=class{pool;findFirst;findMany;insert;update;delete;constructor(e){this.pool=new i(e);let t=b(this);this.findFirst=t.findFirst,this.findMany=t.findMany,this.insert=t.insert,this.update=t.update,this.delete=t.delete}async query(e,t){try{let n=await this.pool.query(e,t);return{rows:n.rows,rowCount:n.rowCount||0,command:n.command,fields:n.fields?.map(e=>({name:e.name,dataTypeID:e.dataTypeID}))}}catch(t){throw new _(`neon`,e,t)}}async close(){await this.pool.end()}};function x(e){return{async findFirst(t,n){let r=[],i=[];if(n)for(let[e,t]of Object.entries(n))r.push(`\`${e}\` = ?`),i.push(t);let a=`SELECT * FROM \`${t}\` ${r.length>0?`WHERE ${r.join(` AND `)}`:``} LIMIT 1`;return await e.query(a,i)},async findMany(t,n){let r=[],i=[];if(n?.where)for(let[e,t]of Object.entries(n.where))r.push(`\`${e}\` = ?`),i.push(t);let a=r.length>0?`WHERE ${r.join(` AND `)}`:``,o=n?.limit?`LIMIT ?`:``,s=n?.offset?`OFFSET ?`:``;n?.limit&&i.push(n.limit),n?.offset&&i.push(n.offset);let c=`SELECT * FROM \`${t}\` ${a} ${o} ${s}`.trim();return await e.query(c,i)},async insert(t,n){let r=Object.keys(n),i=Object.values(n),a=`INSERT INTO \`${t}\` (${r.map(e=>`\`${e}\``).join(`, `)}) VALUES (${r.map(()=>`?`).join(`, `)})`;await e.query(a,i);let o=`SELECT * FROM \`${t}\` WHERE id = LAST_INSERT_ID()`;return await e.query(o)},async update(t,n,r){let i=Object.entries(n),a=Object.entries(r),o=[],s=i.map(([e,t])=>(o.push(t),`\`${e}\` = ?`)),c=a.map(([e,t])=>(o.push(t),`\`${e}\` = ?`)),l=`UPDATE \`${t}\` SET ${s.join(`, `)} WHERE ${c.join(` AND `)}`;await e.query(l,o);let u=Object.values(r),d=`SELECT * FROM \`${t}\` WHERE ${Object.keys(r).map(e=>`\`${e}\` = ?`).join(` AND `)}`;return await e.query(d,u)},async delete(t,n){let r=[],i=[];for(let[e,t]of Object.entries(n))r.push(`\`${e}\` = ?`),i.push(t);let a=`DELETE FROM \`${t}\` WHERE ${r.join(` AND `)}`;return(await e.query(a,i)).rowCount}}}function S(e){return{async findFirst(t,n){let r=[],i=[];if(n)for(let[e,t]of Object.entries(n))r.push(`"${e}" = ?`),i.push(t);let a=`SELECT * FROM "${t}" ${r.length>0?`WHERE ${r.join(` AND `)}`:``} LIMIT 1`;return await e.query(a,i)},async findMany(t,n){let r=[],i=[];if(n?.where)for(let[e,t]of Object.entries(n.where))r.push(`"${e}" = ?`),i.push(t);let a=r.length>0?`WHERE ${r.join(` AND `)}`:``,o=n?.limit?`LIMIT ?`:``,s=n?.offset?`OFFSET ?`:``;n?.limit&&i.push(n.limit),n?.offset&&i.push(n.offset);let c=`SELECT * FROM "${t}" ${a} ${o} ${s}`.trim();return await e.query(c,i)},async insert(t,n){let r=Object.keys(n),i=Object.values(n),a=`INSERT INTO "${t}" (${r.map(e=>`"${e}"`).join(`, `)}) VALUES (${r.map(()=>`?`).join(`, `)}) RETURNING *`;return await e.query(a,i)},async update(t,n,r){let i=Object.entries(n),a=Object.entries(r),o=[],s=i.map(([e,t])=>(o.push(t),`"${e}" = ?`)),c=a.map(([e,t])=>(o.push(t),`"${e}" = ?`)),l=`UPDATE "${t}" SET ${s.join(`, `)} WHERE ${c.join(` AND `)} RETURNING *`;return await e.query(l,o)},async delete(t,n){let r=[],i=[];for(let[e,t]of Object.entries(n))r.push(`"${e}" = ?`),i.push(t);let a=`DELETE FROM "${t}" WHERE ${r.join(` AND `)}`;return(await e.query(a,i)).rowCount}}}var oe=class{client;findFirst;findMany;insert;update;delete;constructor(e){let t=e.connectionString||e.url;t?this.client=new a(t):this.client=new a(e);let n,r=(t||``).toLowerCase();if(e.adapter)switch(e.adapter){case`mysql`:n=x(this);break;case`sqlite`:n=S(this);break;default:n=b(this);break}else n=r.startsWith(`mysql`)?x(this):r.startsWith(`sqlite`)||r.startsWith(`file:`)||r.endsWith(`.db`)||r===`:memory:`?S(this):b(this);this.findFirst=n.findFirst,this.findMany=n.findMany,this.insert=n.insert,this.update=n.update,this.delete=n.delete}async query(e,t){try{let n=await this.client.unsafe(e,t||[]),r=Array.isArray(n)?[...n]:[];return{rows:r,rowCount:n.affectedRows??r.length,command:n.command}}catch(t){throw new _(`bun`,e,t)}}async close(){this.client.end?await this.client.end():this.client.close&&await this.client.close()}},C=class{definition;constructor(e,t){this.definition={name:e,type:t}}length(e){return this.definition.length=e,this}precision(e,t){return this.definition.precision=e,t!==void 0&&(this.definition.scale=t),this}primaryKey(){return this.definition.primaryKey=!0,this.definition.notNull=!0,this}notNull(){return this.definition.notNull=!0,this}unique(){return this.definition.unique=!0,this}default(e){return this.definition.default=e,this}references(e,t=`id`){return this.definition.references={table:e,column:t},this}onDelete(e){return this.definition.references&&(this.definition.references.onDelete=e),this}onUpdate(e){return this.definition.references&&(this.definition.references.onUpdate=e),this}check(e){return this.definition.check=e,this}getDefinition(){return this.definition}};function se(e){return new C(e,`serial`)}function ce(e){return new C(e,`bigserial`)}function w(e){return new C(e,`integer`)}function le(e){return new C(e,`bigint`)}function ue(e){return new C(e,`smallint`)}function de(e){return new C(e,`text`)}function T(e,t){let n=new C(e,`varchar`);return t&&n.length(t),n}function E(e,t){let n=new C(e,`char`);return t&&n.length(t),n}function D(e){return new C(e,`boolean`)}function O(e){return new C(e,`timestamp`)}function k(e){return new C(e,`timestamptz`)}function A(e){return new C(e,`date`)}function j(e){return new C(e,`time`)}function M(e){return new C(e,`json`)}function N(e){return new C(e,`jsonb`)}function P(e){return new C(e,`uuid`)}function F(e,t,n){let r=new C(e,`decimal`);return t&&r.precision(t,n),r}function I(e,t,n){let r=new C(e,`numeric`);return t&&r.precision(t,n),r}function L(e){return new C(e,`real`)}function R(e){return new C(e,`double precision`)}function z(e){return new C(e,`bytea`)}var B=class{definition;constructor(e){this.definition={name:e,columns:[],indexes:[],checks:[]}}column(e){return this.definition.columns.push(e.getDefinition()),this}primaryKey(...e){return this.definition.primaryKey=e,this}index(e,t,n){let r={name:e,columns:t,unique:n?.unique,type:n?.type};return this.definition.indexes?.push(r),this}unique(e,...t){return this.index(e,t,{unique:!0})}check(e,t){return this.definition.checks?.push({name:e,expression:t}),this}getDefinition(){return this.definition}};function V(e,t){let n=new B(e);return t(n),n}var H=f({PostgresGenerator:()=>U}),U,W=d((()=>{U=class{generateCreateTable(e){let t=[];t.push(`CREATE TABLE "${e.name}" (`);let n=[];for(let t of e.columns)n.push(` `+this.generateColumnDefinition(t));if(e.primaryKey&&e.primaryKey.length>0){let t=e.primaryKey.map(e=>`"${e}"`).join(`, `);n.push(` PRIMARY KEY (${t})`)}if(e.checks&&e.checks.length>0)for(let t of e.checks)n.push(` CONSTRAINT "${t.name}" CHECK (${t.expression})`);t.push(n.join(`,
|
|
46
|
+
`)),t.push(`);`);let r=[t.join(`
|
|
47
|
+
`)];if(e.indexes&&e.indexes.length>0)for(let t of e.indexes)r.push(this.generateIndex(e.name,t));return r.join(`
|
|
48
|
+
|
|
49
|
+
`)}generateDropTable(e){return`DROP TABLE IF EXISTS "${e}" CASCADE;`}generateColumnDefinition(e){let t=[`"${e.name}"`];if(t.push(this.getColumnType(e)),e.primaryKey&&!e.type.includes(`serial`)&&t.push(`PRIMARY KEY`),e.notNull&&!e.primaryKey&&!e.type.includes(`serial`)&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),e.references){let n=e.references;t.push(`REFERENCES "${n.table}"("${n.column}")`),n.onDelete&&t.push(`ON DELETE ${n.onDelete}`),n.onUpdate&&t.push(`ON UPDATE ${n.onUpdate}`)}return e.check&&t.push(`CHECK (${e.check})`),t.join(` `)}getColumnType(e){let t=e.type.toUpperCase();return e.length?t+=`(${e.length})`:e.precision&&(e.scale===void 0?t+=`(${e.precision})`:t+=`(${e.precision}, ${e.scale})`),t}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?e.toUpperCase():`'${e}'`:typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e)}generateIndex(e,t){let n=t.unique?`UNIQUE `:``,r=t.type?` USING ${t.type.toUpperCase()}`:``,i=t.columns.map(e=>`"${e}"`).join(`, `);return`CREATE ${n}INDEX "${t.name}" ON "${e}"${r} (${i});`}}})),fe=f({MySQLGenerator:()=>G}),G,K=d((()=>{G=class{generateCreateTable(e){let t=[];t.push(`CREATE TABLE \`${e.name}\` (`);let n=[];for(let t of e.columns)n.push(` `+this.generateColumnDefinition(t));if(e.primaryKey&&e.primaryKey.length>0){let t=e.primaryKey.map(e=>`\`${e}\``).join(`, `);n.push(` PRIMARY KEY (${t})`)}if(e.checks&&e.checks.length>0)for(let t of e.checks)n.push(` CONSTRAINT \`${t.name}\` CHECK (${t.expression})`);t.push(n.join(`,
|
|
50
|
+
`)),t.push(`) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`);let r=[t.join(`
|
|
51
|
+
`)];if(e.indexes&&e.indexes.length>0)for(let t of e.indexes)r.push(this.generateIndex(e.name,t));return r.join(`
|
|
52
|
+
|
|
53
|
+
`)}generateDropTable(e){return`DROP TABLE IF EXISTS \`${e}\`;`}generateColumnDefinition(e){let t=[`\`${e.name}\``];if(t.push(this.getColumnType(e)),e.notNull&&!e.primaryKey&&e.type!==`serial`&&e.type!==`bigserial`&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),(e.type===`serial`||e.type===`bigserial`)&&t.push(`AUTO_INCREMENT`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),e.references){let n=e.references;t.push(`REFERENCES \`${n.table}\`(\`${n.column}\`)`),n.onDelete&&t.push(`ON DELETE ${n.onDelete}`),n.onUpdate&&t.push(`ON UPDATE ${n.onUpdate}`)}return e.check&&t.push(`CHECK (${e.check})`),t.join(` `)}getColumnType(e){let t=e.type;if(t===`serial`)return`INT`;if(t===`bigserial`)return`BIGINT`;if(t===`timestamptz`)return`TIMESTAMP`;if(t===`jsonb`)return`JSON`;if(t===`bytea`)return`BLOB`;if(t===`double precision`)return`DOUBLE`;let n=t.toUpperCase();return e.length?n+=`(${e.length})`:e.precision&&(e.scale===void 0?n+=`(${e.precision})`:n+=`(${e.precision}, ${e.scale})`),n}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?`CURRENT_TIMESTAMP`:`'${e}'`:typeof e==`boolean`?e?`1`:`0`:String(e)}generateIndex(e,t){let n=t.unique?`UNIQUE `:``,r=t.type&&t.type!==`btree`?` USING ${t.type.toUpperCase()}`:``,i=t.columns.map(e=>`\`${e}\``).join(`, `);return`CREATE ${n}INDEX \`${t.name}\` ON \`${e}\`${r} (${i});`}}})),pe=f({SQLiteGenerator:()=>q}),q,J=d((()=>{q=class{generateCreateTable(e){let t=[];t.push(`CREATE TABLE "${e.name}" (`);let n=[];for(let t of e.columns)n.push(` `+this.generateColumnDefinition(t));if(e.primaryKey&&e.primaryKey.length>0){let t=e.primaryKey.map(e=>`"${e}"`).join(`, `);n.push(` PRIMARY KEY (${t})`)}if(e.checks&&e.checks.length>0)for(let t of e.checks)n.push(` CONSTRAINT "${t.name}" CHECK (${t.expression})`);t.push(n.join(`,
|
|
54
|
+
`)),t.push(`);`);let r=[t.join(`
|
|
55
|
+
`)];if(e.indexes&&e.indexes.length>0)for(let t of e.indexes)r.push(this.generateIndex(e.name,t));return r.join(`
|
|
56
|
+
|
|
57
|
+
`)}generateDropTable(e){return`DROP TABLE IF EXISTS "${e}";`}generateColumnDefinition(e){let t=[`"${e.name}"`];if(t.push(this.getColumnType(e)),e.primaryKey&&(t.push(`PRIMARY KEY`),(e.type===`serial`||e.type===`bigserial`)&&t.push(`AUTOINCREMENT`)),e.notNull&&!e.primaryKey&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),e.references){let n=e.references;t.push(`REFERENCES "${n.table}"("${n.column}")`),n.onDelete&&t.push(`ON DELETE ${n.onDelete}`),n.onUpdate&&t.push(`ON UPDATE ${n.onUpdate}`)}return e.check&&t.push(`CHECK (${e.check})`),t.join(` `)}getColumnType(e){let t=e.type;return t===`serial`||t===`bigserial`||t===`bigint`||t===`smallint`?`INTEGER`:t===`varchar`||t===`char`||t===`timestamptz`||t===`timestamp`||t===`date`||t===`time`||t===`uuid`||t===`json`||t===`jsonb`?`TEXT`:t===`bytea`?`BLOB`:t===`decimal`||t===`numeric`||t===`real`||t===`double precision`?`REAL`:t===`boolean`?`INTEGER`:t.toUpperCase()}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?`CURRENT_TIMESTAMP`:`'${e}'`:typeof e==`boolean`?e?`1`:`0`:String(e)}generateIndex(e,t){let n=t.unique?`UNIQUE `:``,r=t.columns.map(e=>`"${e}"`).join(`, `);return`CREATE ${n}INDEX "${t.name}" ON "${e}" (${r});`}}}));W(),K(),J();var Y=class{upStatements=[];downStatements=[];dialect;constructor(e=`postgres`){this.dialect=e}createTable(e){let t=e.getDefinition(),n=this.getGenerator();return this.upStatements.push(n.generateCreateTable(t)),this.downStatements.unshift(n.generateDropTable(t.name)),this}dropTable(e){let t=this.getGenerator();return this.upStatements.push(t.generateDropTable(e)),this}addColumn(e,t){return this.upStatements.push(`ALTER TABLE "${e}" ADD COLUMN ${t};`),this}dropColumn(e,t){return this.upStatements.push(`ALTER TABLE "${e}" DROP COLUMN "${t}";`),this}renameTable(e,t){return this.dialect===`postgres`?this.upStatements.push(`ALTER TABLE "${e}" RENAME TO "${t}";`):this.dialect===`mysql`?this.upStatements.push(`RENAME TABLE \`${e}\` TO \`${t}\`;`):this.upStatements.push(`ALTER TABLE "${e}" RENAME TO "${t}";`),this}raw(e,t){return this.upStatements.push(e),t&&this.downStatements.unshift(t),this}build(e,t){return{version:e,name:t,up:this.upStatements,down:this.downStatements}}getGenerator(){switch(this.dialect){case`postgres`:return new U;case`mysql`:return new G;case`sqlite`:return new q;default:return new U}}};function me(e=`postgres`){return new Y(e)}var he=class{client;constructor(e){this.client=e}async ensureMigrationsTable(){await this.client.query(`
|
|
58
|
+
CREATE TABLE IF NOT EXISTS _migrations (
|
|
59
|
+
version VARCHAR(255) PRIMARY KEY,
|
|
60
|
+
name VARCHAR(255) NOT NULL,
|
|
61
|
+
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
62
|
+
);
|
|
63
|
+
`)}async getAppliedMigrations(){return await this.ensureMigrationsTable(),(await this.client.query(`SELECT version FROM _migrations ORDER BY version`)).rows.map(e=>e.version)}async up(t){if((await this.getAppliedMigrations()).includes(t.version)){e.info(`Migration ${t.version} (${t.name}) already applied`);return}e.start(`Running migration ${t.version} (${t.name})`);for(let e of t.up)await this.client.query(e);await this.client.query(`INSERT INTO _migrations (version, name) VALUES ($1, $2)`,[t.version,t.name]),e.success(`Migration ${t.version} (${t.name}) applied successfully`)}async down(t){if(!(await this.getAppliedMigrations()).includes(t.version)){e.info(`Migration ${t.version} (${t.name}) not applied`);return}e.start(`Rolling back migration ${t.version} (${t.name})`);for(let e of t.down)await this.client.query(e);await this.client.query(`DELETE FROM _migrations WHERE version = $1`,[t.version]),e.success(`Migration ${t.version} (${t.name}) rolled back successfully`)}async upAll(t){let n=await this.getAppliedMigrations(),r=t.filter(e=>!n.includes(e.version));if(r.length===0){e.info(`No pending migrations`);return}e.info(`Found ${r.length} pending migrations`);for(let e of r)await this.up(e)}async downAll(t){let n=await this.getAppliedMigrations(),r=t.filter(e=>n.includes(e.version)).reverse();if(r.length===0){e.info(`No migrations to rollback`);return}e.info(`Rolling back ${r.length} migrations`);for(let e of r)await this.down(e)}async reset(e){await this.downAll(e),await this.upAll(e)}},X=class{dialect;constructor(e=`postgres`){this.dialect=e}detectChanges(e,t){let n=[],r=new Map(e.map(e=>[e.name,e])),i=new Map(t.map(e=>[e.name,e]));for(let[e,t]of i){let i=r.get(e);i?(n.push(...this.detectColumnChanges(i,t)),n.push(...this.detectIndexChanges(i,t))):n.push({type:`create_table`,table:e,details:t})}for(let[e]of r)i.has(e)||n.push({type:`drop_table`,table:e});return n}detectColumnChanges(e,t){let n=[],r=new Map(e.columns.map(e=>[e.name,e])),i=new Map(t.columns.map(e=>[e.name,e]));for(let[e,a]of i){let i=r.get(e);i?this.hasColumnChanged(i,a)&&n.push({type:`modify_column`,table:t.name,details:{old:i,new:a}}):n.push({type:`add_column`,table:t.name,details:a})}for(let[e]of r)i.has(e)||n.push({type:`drop_column`,table:t.name,details:{name:e}});return n}detectIndexChanges(e,t){let n=[],r=new Map((e.indexes||[]).map(e=>[e.name,e])),i=new Map((t.indexes||[]).map(e=>[e.name,e]));for(let[e,a]of i)r.has(e)||n.push({type:`create_index`,table:t.name,details:a});for(let[e]of r)i.has(e)||n.push({type:`drop_index`,table:t.name,details:{name:e}});return n}hasColumnChanged(e,t){return e.type!==t.type||e.length!==t.length||e.precision!==t.precision||e.scale!==t.scale||e.notNull!==t.notNull||e.unique!==t.unique||e.default!==t.default||JSON.stringify(e.references)!==JSON.stringify(t.references)}generateMigration(e,t,n){let r=new Y(this.dialect);for(let t of e)switch(t.type){case`create_table`:{let e=t.details,n=this.getGenerator(),i=n.generateCreateTable(e);r.raw(i,n.generateDropTable(e.name));break}case`drop_table`:{let e=this.getGenerator();r.raw(e.generateDropTable(t.table));break}case`add_column`:{let e=t.details,n=this.generateColumnSQL(e);r.raw(`ALTER TABLE "${t.table}" ADD COLUMN ${n};`,`ALTER TABLE "${t.table}" DROP COLUMN "${e.name}";`);break}case`drop_column`:{let e=t.details.name;r.raw(`ALTER TABLE "${t.table}" DROP COLUMN "${e}";`);break}case`create_index`:{let e=t.details,n=this.generateIndexSQL(t.table,e);r.raw(n,`DROP INDEX "${e.name}";`);break}case`drop_index`:{let e=t.details.name;r.raw(`DROP INDEX "${e}";`);break}}return r}generateColumnSQL(e){let t=[`"${e.name}"`];return t.push(e.type.toUpperCase()),e.length&&(t[1]+=`(${e.length})`),e.notNull&&t.push(`NOT NULL`),e.unique&&t.push(`UNIQUE`),e.default!==void 0&&t.push(`DEFAULT ${this.formatDefault(e.default)}`),t.join(` `)}generateIndexSQL(e,t){let n=t.unique?`UNIQUE `:``,r=t.columns.map(e=>`"${e}"`).join(`, `);return`CREATE ${n}INDEX "${t.name}" ON "${e}" (${r});`}formatDefault(e){return typeof e==`string`?e.toUpperCase()===`NOW()`||e.toUpperCase()===`CURRENT_TIMESTAMP`?e.toUpperCase():`'${e}'`:typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e)}getGenerator(){let{PostgresGenerator:e}=(W(),p(H)),{MySQLGenerator:t}=(K(),p(fe)),{SQLiteGenerator:n}=(J(),p(pe));switch(this.dialect){case`postgres`:return new e;case`mysql`:return new t;case`sqlite`:return new n;default:return new e}}};function Z(e,t,n=`postgres`){return new X(n).detectChanges(e,t)}function ge(e,t,n,r=`postgres`){return new X(r).generateMigration(e,t,n)}var _e=class{snapshotPath;constructor(e=`./.driftsql/snapshot.json`){this.snapshotPath=e}async save(e){let t={version:`1`,timestamp:Date.now(),tables:e},r=o.dirname(this.snapshotPath);await n.mkdir(r,{recursive:!0}),await n.writeFile(this.snapshotPath,JSON.stringify(t,null,2),`utf8`)}async load(){try{let e=await n.readFile(this.snapshotPath,`utf8`);return JSON.parse(e)}catch{return null}}async exists(){try{return await n.access(this.snapshotPath),!0}catch{return!1}}},Q=class{generateTypes(e){let t=`// This file was automatically generated - DO NOT EDIT
|
|
64
|
+
|
|
65
|
+
`;for(let n of e)t+=this.generateTableInterface(n),t+=`
|
|
66
|
+
|
|
67
|
+
`;return t+=this.generateDatabaseInterface(e),t}generateTableInterface(e){let t=[`export interface ${this.pascalCase(e.name)} {`];for(let n of e.columns){let e=this.columnToTypeScript(n),r=!n.notNull&&!n.primaryKey?`?`:``;t.push(` ${n.name}${r}: ${e}`)}return t.push(`}`),t.join(`
|
|
68
|
+
`)}generateDatabaseInterface(e){let t=[`export interface Database {`];for(let n of e){let e=this.pascalCase(n.name);t.push(` ${n.name}: ${e}`)}return t.push(`}`),t.join(`
|
|
69
|
+
`)}columnToTypeScript(e){let t=!e.notNull&&!e.primaryKey,n;switch(e.type.toLowerCase()){case`serial`:case`bigserial`:case`integer`:case`int`:case`bigint`:case`smallint`:case`numeric`:case`decimal`:case`real`:case`double precision`:n=`number`;break;case`text`:case`varchar`:case`char`:case`uuid`:n=`string`;break;case`boolean`:n=`boolean`;break;case`timestamp`:case`timestamptz`:case`date`:case`time`:n=`Date | string`;break;case`json`:case`jsonb`:n=`any`;break;case`bytea`:n=`Buffer`;break;default:n=`any`}return t?`${n} | null`:n}pascalCase(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``)}async writeToFile(e,t){let r=this.generateTypes(e);await n.writeFile(t,r,`utf8`)}};async function ve(e,t){await new Q().writeToFile(e,t)}W(),K(),J();var $=class t{primaryDriver;fallbackDrivers;queryCache;cacheTTL;maxCacheSize=100;constructor(e){this.primaryDriver=e.driver,this.fallbackDrivers=e.fallbackDrivers||[],this.queryCache=new Map,this.cacheTTL=e.cacheTTL??5e3}isCacheValid(e){return Date.now()-e.timestamp<this.cacheTTL}getCacheKey(e,t){return JSON.stringify({sql:e,params:t})}maintainCacheSize(){if(this.queryCache.size>this.maxCacheSize){let e=this.queryCache.keys().next().value;e!==void 0&&this.queryCache.delete(e)}}cacheResult(e,t){this.queryCache.set(e,{result:t,timestamp:Date.now()}),this.maintainCacheSize()}async tryFallbackDrivers(t,n){e.warn(`Query failed with ${this.primaryDriver.constructor.name}, trying fallbacks`);let r;for(let e of this.fallbackDrivers)try{return await e.query(t,n)}catch(e){r=e}throw r||new g(`All drivers failed to execute query`,`unknown`)}async query(e,t){let n=this.getCacheKey(e,t),r=this.queryCache.get(n);if(r&&this.isCacheValid(r))return r.result;try{let r=await this.primaryDriver.query(e,t);return this.cacheResult(n,r),r}catch(n){if(this.fallbackDrivers.length===0)throw n;return await this.tryFallbackDrivers(e,t)}}async transaction(e){if(!m(this.primaryDriver))throw new g(`Primary driver does not support transactions`,this.primaryDriver.constructor.name);return await this.primaryDriver.transaction(async n=>await e(new t({driver:n,fallbackDrivers:[]})))}async prepare(e){if(!h(this.primaryDriver))throw new g(`Primary driver does not support prepared statements`,this.primaryDriver.constructor.name);return await this.primaryDriver.prepare(e)}async findFirst(e,t){if(!this.primaryDriver.findFirst)throw new g(`Primary driver does not support findFirst`,this.primaryDriver.constructor.name);return(await this.primaryDriver.findFirst(e,t))?.rows[0]||null}async findMany(e,t){if(!this.primaryDriver.findMany)throw new g(`Primary driver does not support findMany`,this.primaryDriver.constructor.name);return(await this.primaryDriver.findMany(e,t)).rows}async insert(e,t){if(!this.primaryDriver.insert)throw new g(`Primary driver does not support insert`,this.primaryDriver.constructor.name);return(await this.primaryDriver.insert(e,t)).rows[0]}async update(e,t,n){if(!this.primaryDriver.update)throw new g(`Primary driver does not support update`,this.primaryDriver.constructor.name);return(await this.primaryDriver.update(e,t,n)).rows[0]||null}async delete(e,t){if(!this.primaryDriver.delete)throw new g(`Primary driver does not support delete`,this.primaryDriver.constructor.name);return await this.primaryDriver.delete(e,t)}getDriver(){return this.primaryDriver}async inspectDB(e){return await re({driver:this.getDriver(),...e})}supportsTransactions(){return m(this.primaryDriver)}supportsPreparedStatements(){return h(this.primaryDriver)}clearCache(){this.queryCache.clear()}getCacheStats(){return{size:this.queryCache.size,ttl:this.cacheTTL}}async close(){this.queryCache.clear();let t=[this.primaryDriver,...this.fallbackDrivers].map(t=>t.close().catch(n=>e.warn(`Error closing ${t.constructor.name}:`,n)));await Promise.all(t)}};const ye=$;export{oe as BunSQLDriver,C as Column,ye as DriftSQLClient,Y as MigrationBuilder,he as MigrationRunner,G as MySQLGenerator,ae as NeonDriver,ie as PostgresDriver,U as PostgresGenerator,$ as SQLClient,q as SQLiteGenerator,X as SchemaDiffer,_e as SnapshotManager,B as Table,Q as TypeGenerator,le as bigint,ce as bigserial,D as boolean,z as bytea,E as char,me as createMigration,x as createMySQLHelpers,b as createPostgresHelpers,S as createSQLiteHelpers,V as createTable,A as date,F as decimal,Z as detectChanges,R as doublePrecision,ge as generateMigrationFromChanges,ve as generateTypesFromSchema,w as integer,M as json,N as jsonb,I as numeric,L as real,se as serial,ue as smallint,de as text,j as time,O as timestamp,k as timestamptz,P as uuid,T as varchar};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "driftsql",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1-beta",
|
|
4
4
|
"description": "A modern, type-safe SQL client with built-in schema builder and migration system for TypeScript.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,19 +20,20 @@
|
|
|
20
20
|
"module": "./dist/index.js",
|
|
21
21
|
"types": "./dist/index.d.ts",
|
|
22
22
|
"bin": {
|
|
23
|
-
"driftsql": "
|
|
23
|
+
"driftsql": "dist/cli/index.js"
|
|
24
24
|
},
|
|
25
25
|
"exports": {
|
|
26
26
|
".": "./dist/index.js",
|
|
27
27
|
"./package.json": "./package.json"
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
|
-
"build": "tsdown",
|
|
30
|
+
"build": "tsdown src/index.ts --config tsdown.config.ts --format esm && tsdown src/cli/index.ts --config tsdown.config.ts --format esm --out-dir dist/cli --no-clean",
|
|
31
31
|
"dev": "tsdown --watch --minify=false",
|
|
32
32
|
"test": "vitest",
|
|
33
33
|
"typecheck": "tsc --noEmit"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
+
"@types/bun": "^1.3.4",
|
|
36
37
|
"@types/node": "^24.9.1",
|
|
37
38
|
"bumpp": "^10.3.1",
|
|
38
39
|
"tsdown": "^0.15.9",
|
|
@@ -40,6 +41,7 @@
|
|
|
40
41
|
"vitest": "^4.0.1"
|
|
41
42
|
},
|
|
42
43
|
"dependencies": {
|
|
44
|
+
"@neondatabase/serverless": "^1.0.2",
|
|
43
45
|
"chalk": "^5.6.2",
|
|
44
46
|
"commander": "^14.0.2",
|
|
45
47
|
"consola": "^3.4.2",
|
package/dist/index-CHiXYO9-.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { };
|