@forinda/kickjs-db 6.1.0 → 6.1.1
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.mjs +2 -2
- package/dist/devtools-events.mjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/mysql.mjs +2 -2
- package/dist/pg.mjs +2 -2
- package/dist/sqlite.mjs +2 -2
- package/dist/{src-lL141oWK.mjs → src-Dpz7lQYB.mjs} +2 -2
- package/dist/{src-lL141oWK.mjs.map → src-Dpz7lQYB.mjs.map} +1 -1
- package/package.json +2 -2
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v6.1.
|
|
2
|
+
* @forinda/kickjs-db v6.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{A as generate,G as migrateLatest,J as migrateUp,K as migrateRollback,M as reviewMigration,Tt as renderSchemaSource,W as migrateDown,q as migrateStatus,xt as detectCompositeReferences}from"./src-
|
|
11
|
+
import{A as generate,G as migrateLatest,J as migrateUp,K as migrateRollback,M as reviewMigration,Tt as renderSchemaSource,W as migrateDown,q as migrateStatus,xt as detectCompositeReferences}from"./src-Dpz7lQYB.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";const DEFAULT_SCHEMA_PATHS=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],kickDbTypegen=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(ctx){let schemaAbs=resolveSchema(ctx.cwd);if(!schemaAbs)return null;let typesDir=path.resolve(ctx.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${posix(path.relative(typesDir,schemaAbs)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
|
|
12
12
|
`)}});function resolveSchema(cwd){for(let candidate of DEFAULT_SCHEMA_PATHS){let abs=path.resolve(cwd,candidate);if(candidate.endsWith(`.ts`)){if(existsSync(abs))return abs}else{let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}}return null}function posix(p){return p.replace(/\\/g,`/`)}function defineKickDbConfig(cfg){return cfg}function mergeKickDbConfig(...configs){return Object.assign({},...configs.filter(Boolean))}function resolveKickDbConfig(block){let db=block??{};return{schemaPath:db.schemaPath??`src/db/schema.ts`,migrationsDir:db.migrationsDir??`db/migrations`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck}}async function resolveAdapter(config){if(config.adapter){let adapter=await config.adapter();return{adapter,cleanup:async()=>adapter.close()}}if(!config.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory`);let dialect=config.dialect??`postgres`;if(dialect!==`postgres`)throw Error(`kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`);let[{pgAdapter},pg]=await Promise.all([import(`./pg.mjs`),import(`pg`)]),pool=new pg.default.Pool({connectionString:config.connectionString}),adapter=pgAdapter({pool});return{adapter,cleanup:async()=>{await adapter.close(),await pool.end()}}}async function tryResolvePgQueryRunner(config){if(config.adapter||(config.dialect??`postgres`)!==`postgres`||!config.connectionString)return null;let pool=new(await(import(`pg`))).default.Pool({connectionString:config.connectionString});return{runner:pool,cleanup:async()=>void await pool.end()}}function printStatusTable(status){if(status.length===0){console.log(`No migrations.`);return}console.table(status.map(s=>({id:s.id,state:s.state,batch:s.batch??`-`,reviewed:s.reviewed,applied:s.appliedAt??`-`})))}function registerDbCommands(parent,getConfig){parent.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(name,opts)=>{let cwd=process.cwd(),config=await getConfig(),probe=await tryResolvePgQueryRunner(config),detectCompositeRefs=probe?enumName=>detectCompositeReferences(probe.runner,enumName):void 0;try{let result=await generate({name,config,cwd,empty:opts.empty,detectCompositeRefs});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`);return}let plural=result.changeCount===1?``:`s`;console.log(`Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`)}finally{await probe?.cleanup()}});let migrate=parent.command(`migrate`).description(`Migration runner subcommands`);migrate.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateLatest({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`up`).description(`Apply the next single pending migration`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateUp({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await cleanup()}}),migrate.command(`down`).description(`Reverse the most recent applied migration`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateDown({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed?`Reversed ${r.reversed}.`:`Nothing to reverse.`)}finally{await cleanup()}}),migrate.command(`rollback`).description(`Reverse the entire last batch as a single unit`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateRollback({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed.length===0?`Nothing to roll back.`:`Rolled back batch ${r.batch}: ${r.reversed.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`status`).description(`Print applied + pending migrations`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{printStatusTable(await migrateStatus({adapter,migrationsDir:config.migrationsDir}))}finally{await cleanup()}}),migrate.command(`review <id>`).description(`Mark a migration reviewed (flips meta.json + the -- REVIEWED markers)`).action(async id=>{let r=await reviewMigration((await getConfig()).migrationsDir,id);console.log(r.alreadyReviewed?`${r.id} was already reviewed.`:`Reviewed ${r.id} — it can now be applied.`)}),parent.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let snapshot=await adapter.introspect();if(opts.json){console.log(JSON.stringify(snapshot,null,2));return}let out=opts.out??config.schemaPath;await writeFile(out,renderSchemaSource(snapshot),`utf8`);let n=Object.keys(snapshot.tables).length;console.log(`Wrote ${out} (${n} table${n===1?``:`s`}).`)}finally{await cleanup()}})}function dbBlockOf(config){return config?.db}const dbCliPlugin=defineCliPlugin({name:`kick/db`,register(program,ctx){registerDbCommands(program.command(`db`).description(`Database commands (kickjs-db)`),()=>resolveKickDbConfig(dbBlockOf(ctx.config)))},typegens:[kickDbTypegen()]});export{dbCliPlugin,defineKickDbConfig,kickDbTypegen,mergeKickDbConfig,registerDbCommands,resolveKickDbConfig};
|
|
13
13
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/devtools-events.mjs
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v6.1.
|
|
2
|
+
* @forinda/kickjs-db v6.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{$ as introspectMysql,A as generate,At as RelationalQueryDepthError,B as DB_CLIENT,C as smallint,Ct as invertChanges,D as timestamptz,Dt as RelationalQueryAliasCollisionError,E as timestamp,Et as extractSnapshot,F as CustomColumnBuilder,Ft as RemovedValueAsDefaultError,G as migrateLatest,H as DB_REPLICA,I as customType,J as migrateUp,K as migrateRollback,L as ColumnBuilder,M as reviewMigration,Mt as RelationalQueryNotSupportedError,N as safeNullComparison,Nt as RelationalQueryUnknownRelationError,O as uuid,Ot as RelationalQueryAmbiguousRelationNameError,P as createDbClient,Pt as KickDbError,Q as emitSqlite,R as KICK_GENERATED,S as smallSerial,St as hasAmbiguousReverse,T as time,Tt as renderSchemaSource,U as kickDbAdapter,V as DB_PRIMARY,W as migrateDown,X as emitMysql,Y as checkDrift,Z as SqliteRebuildRequiredError,_ as json,_t as MigrationHashError,a as TimestampBuilder,at as lockTableDdl,b as real,bt as CompositeEnumReferenceError,c as bigint,ct as computeMigrationHash,d as char,dt as enforceEnumDropGate,et as introspectSqlite,f as date,ft as parseEnumDropHeader,g as interval,gt as MigrationError,h as integer,ht as MigrationEnumDropError,i as table,it as KICK_MIGRATIONS_TABLE,j as resolveDbConfig,jt as RelationalQueryMissingInverseError,k as varchar,kt as RelationalQueryCancelledError,l as boolean,lt as readJournal,m as doublePrecision,mt as MigrationDriftError,n as index,nt as MemoryMigrationAdapter,o as UuidBuilder,ot as migrationsTableDdl,p as decimal,pt as emitPg,q as migrateStatus,r as unique,rt as KICK_LOCK_TABLE,s as bigSerial,st as appendJournalEntry,t as relations,tt as introspectPg,u as bytea,ut as verifyMigrationHash,v as jsonb,vt as MigrationLockError,w as text,wt as diff,x as serial,xt as detectCompositeReferences,y as numeric,yt as UnreviewedMigrationError,z as KICK_NOT_NULL}from"./src-
|
|
11
|
+
import{$ as introspectMysql,A as generate,At as RelationalQueryDepthError,B as DB_CLIENT,C as smallint,Ct as invertChanges,D as timestamptz,Dt as RelationalQueryAliasCollisionError,E as timestamp,Et as extractSnapshot,F as CustomColumnBuilder,Ft as RemovedValueAsDefaultError,G as migrateLatest,H as DB_REPLICA,I as customType,J as migrateUp,K as migrateRollback,L as ColumnBuilder,M as reviewMigration,Mt as RelationalQueryNotSupportedError,N as safeNullComparison,Nt as RelationalQueryUnknownRelationError,O as uuid,Ot as RelationalQueryAmbiguousRelationNameError,P as createDbClient,Pt as KickDbError,Q as emitSqlite,R as KICK_GENERATED,S as smallSerial,St as hasAmbiguousReverse,T as time,Tt as renderSchemaSource,U as kickDbAdapter,V as DB_PRIMARY,W as migrateDown,X as emitMysql,Y as checkDrift,Z as SqliteRebuildRequiredError,_ as json,_t as MigrationHashError,a as TimestampBuilder,at as lockTableDdl,b as real,bt as CompositeEnumReferenceError,c as bigint,ct as computeMigrationHash,d as char,dt as enforceEnumDropGate,et as introspectSqlite,f as date,ft as parseEnumDropHeader,g as interval,gt as MigrationError,h as integer,ht as MigrationEnumDropError,i as table,it as KICK_MIGRATIONS_TABLE,j as resolveDbConfig,jt as RelationalQueryMissingInverseError,k as varchar,kt as RelationalQueryCancelledError,l as boolean,lt as readJournal,m as doublePrecision,mt as MigrationDriftError,n as index,nt as MemoryMigrationAdapter,o as UuidBuilder,ot as migrationsTableDdl,p as decimal,pt as emitPg,q as migrateStatus,r as unique,rt as KICK_LOCK_TABLE,s as bigSerial,st as appendJournalEntry,t as relations,tt as introspectPg,u as bytea,ut as verifyMigrationHash,v as jsonb,vt as MigrationLockError,w as text,wt as diff,x as serial,xt as detectCompositeReferences,y as numeric,yt as UnreviewedMigrationError,z as KICK_NOT_NULL}from"./src-Dpz7lQYB.mjs";export{ColumnBuilder,CompositeEnumReferenceError,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,KICK_GENERATED,KICK_LOCK_TABLE,KICK_MIGRATIONS_TABLE,KICK_NOT_NULL,KickDbError,MemoryMigrationAdapter,MigrationDriftError,MigrationEnumDropError,MigrationError,MigrationHashError,MigrationLockError,RelationalQueryAliasCollisionError,RelationalQueryAmbiguousRelationNameError,RelationalQueryCancelledError,RelationalQueryDepthError,RelationalQueryMissingInverseError,RelationalQueryNotSupportedError,RelationalQueryUnknownRelationError,RemovedValueAsDefaultError,SqliteRebuildRequiredError,TimestampBuilder,UnreviewedMigrationError,UuidBuilder,appendJournalEntry,bigSerial,bigint,boolean,bytea,char,checkDrift,computeMigrationHash,createDbClient,customType,date,decimal,detectCompositeReferences,diff,doublePrecision,emitMysql,emitPg,emitSqlite,enforceEnumDropGate,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectMysql,introspectPg,introspectSqlite,invertChanges,json,jsonb,kickDbAdapter,lockTableDdl,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,readJournal,real,relations,renderSchemaSource,resolveDbConfig,reviewMigration,safeNullComparison,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
|
package/dist/mysql.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v6.1.
|
|
2
|
+
* @forinda/kickjs-db v6.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{$ as introspectMysql,Pt as KickDbError,at as lockTableDdl,ot as migrationsTableDdl}from"./src-
|
|
11
|
+
import{$ as introspectMysql,Pt as KickDbError,at as lockTableDdl,ot as migrationsTableDdl}from"./src-Dpz7lQYB.mjs";import{MysqlDialect}from"kysely";function parseMysqlVersion(version){let trimmed=version.trim();if(/MariaDB/i.test(trimmed)){let m=/(\d+)\.(\d+)(?:\.\d+)?-MariaDB/i.exec(trimmed);if(m){let major=Number(m[1]),minor=Number(m[2]);if(Number.isFinite(major)&&Number.isFinite(minor))return{flavor:`mariadb`,major,minor}}let fallback=/^(\d+)\.(\d+)/.exec(trimmed);if(!fallback)return null;let major=Number(fallback[1]),minor=Number(fallback[2]);return!Number.isFinite(major)||!Number.isFinite(minor)?null:{flavor:`mariadb`,major,minor}}let m=/^(\d+)\.(\d+)/.exec(trimmed);if(!m)return null;let major=Number(m[1]),minor=Number(m[2]);return!Number.isFinite(major)||!Number.isFinite(minor)?null:{flavor:`mysql`,major,minor}}function parseMysqlMajorVersion(version){return parseMysqlVersion(version)?.major??null}function checkVersionSupport(parsed,raw){return parsed==null?`unparseable version string: ${raw||`<empty>`}`:parsed.flavor===`mariadb`?parsed.major>10?null:parsed.major<10||parsed.minor<5?`MariaDB 10.5+ required (detected: ${raw})`:null:parsed.major<8?`MySQL 8.0+ required (detected: ${raw})`:null}function splitMysqlStatements(sql){let out=[],buf=``,inSingle=!1,inDouble=!1,inBacktick=!1,inLineComment=!1,inBlockComment=!1,isCommentWhitespace=c=>c===` `||c===` `||c===`
|
|
12
12
|
`||c===`\r`||c===`\f`||c===`\v`;for(let i=0;i<sql.length;i++){let ch=sql[i],next=i+1<sql.length?sql[i+1]:``,after=i+2<sql.length?sql[i+2]:``;if(inLineComment){buf+=ch,ch===`
|
|
13
13
|
`&&(inLineComment=!1);continue}if(inBlockComment){buf+=ch,ch===`*`&&next===`/`&&(buf+=next,i++,inBlockComment=!1);continue}if(inSingle){if(ch===`'`&&next===`'`){buf+=ch,buf+=next,i++;continue}if(buf+=ch,ch===`\\`&&next!==``){buf+=next,i++;continue}ch===`'`&&(inSingle=!1);continue}if(inDouble){if(ch===`"`&&next===`"`){buf+=ch,buf+=next,i++;continue}if(buf+=ch,ch===`\\`&&next!==``){buf+=next,i++;continue}ch===`"`&&(inDouble=!1);continue}if(inBacktick){buf+=ch,ch==="`"&&(inBacktick=!1);continue}if(ch===`-`&&next===`-`&&(after===``||isCommentWhitespace(after))){buf+=ch,inLineComment=!0;continue}if(ch===`/`&&next===`*`){buf+=ch,inBlockComment=!0;continue}if(ch===`'`){buf+=ch,inSingle=!0;continue}if(ch===`"`){buf+=ch,inDouble=!0;continue}if(ch==="`"){buf+=ch,inBacktick=!0;continue}if(ch===`;`){let trimmed=buf.trim();trimmed.length>0&&out.push(trimmed),buf=``;continue}buf+=ch}let tail=buf.trim();return tail.length>0&&out.push(tail),out}function mysqlAdapter(opts){let dialect=`mysql`,{pool}=opts,versionVerified=!1;async function assertVersion(){if(versionVerified)return;let[rows]=await pool.query("SELECT VERSION() AS `version`"),versionString=rows[0]?.version??``,failure=checkVersionSupport(parseMysqlVersion(versionString),versionString);if(failure)throw new KickDbError(`KICK_DB_RELATIONAL_NOT_SUPPORTED`,`${failure}. JSON_ARRAYAGG (required by the relational query layer) shipped in MySQL 8.0 and MariaDB 10.5. Use layer-1/layer-2 queries (selectFrom / selectAll) on older versions.`);versionVerified=!0}async function runStatements(sql){for(let stmt of splitMysqlStatements(sql))await pool.query(stmt)}async function runStatementsOnConn(conn,sql){for(let stmt of splitMysqlStatements(sql))await conn.query(stmt)}return{dialect,async ensureMigrationTables(){await assertVersion(),await runStatements(migrationsTableDdl(dialect)),await runStatements(lockTableDdl(dialect))},async listApplied(){let[rows]=await pool.query(`SELECT id, name, hash, batch, applied_at, direction
|
|
14
14
|
FROM \`kick_migrations\`
|
package/dist/pg.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v6.1.
|
|
2
|
+
* @forinda/kickjs-db v6.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{L as ColumnBuilder,at as lockTableDdl,ot as migrationsTableDdl,tt as introspectPg}from"./src-
|
|
11
|
+
import{L as ColumnBuilder,at as lockTableDdl,ot as migrationsTableDdl,tt as introspectPg}from"./src-Dpz7lQYB.mjs";import{PostgresDialect}from"kysely";var PgEnumColumnBuilder=class extends ColumnBuilder{enumName;values;constructor(enumName,values){super(enumName),this.enumName=enumName,this.values=values}};function pgEnum(name,...values){return Object.assign(()=>new PgEnumColumnBuilder(name,values),{enumName:name,values})}function tsvector(){return new ColumnBuilder(`tsvector`)}function vector(dim){return new ColumnBuilder(dim===void 0?`vector`:`vector(${dim})`)}function citext(){return new ColumnBuilder(`citext`)}function money(){return new ColumnBuilder(`money`)}function inet(){return new ColumnBuilder(`inet`)}function cidr(){return new ColumnBuilder(`cidr`)}function xml(){return new ColumnBuilder(`xml`)}const SAFE_SCHEMA_NAME=/^[a-z_][a-z0-9_]*$/i;function pgAdapter(opts){let dialect=`postgres`,{pool}=opts,schema=opts.schema??`public`;if(!SAFE_SCHEMA_NAME.test(schema))throw Error(`Invalid PG schema name: ${schema}`);return{dialect,async ensureMigrationTables(){await pool.query(migrationsTableDdl(dialect)),await pool.query(lockTableDdl(dialect))},async listApplied(){return(await pool.query(`SELECT id, name, hash, batch, applied_at, direction
|
|
12
12
|
FROM kick_migrations
|
|
13
13
|
ORDER BY applied_at ASC, id ASC`)).rows.map(row=>({id:row.id,name:row.name,hash:row.hash,batch:Number(row.batch),appliedAt:row.applied_at instanceof Date?row.applied_at.toISOString():String(row.applied_at),direction:row.direction}))},async recordApplied(row){await pool.query(`INSERT INTO kick_migrations (id, name, hash, batch, direction)
|
|
14
14
|
VALUES ($1, $2, $3, $4, $5)`,[row.id,row.name,row.hash,row.batch,row.direction])},async removeApplied(id){await pool.query(`DELETE FROM kick_migrations WHERE id = $1`,[id])},async acquireLock(owner){return(await pool.query(`UPDATE kick_migrations_lock
|
package/dist/sqlite.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v6.1.
|
|
2
|
+
* @forinda/kickjs-db v6.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{at as lockTableDdl,et as introspectSqlite,ot as migrationsTableDdl}from"./src-
|
|
11
|
+
import{at as lockTableDdl,et as introspectSqlite,ot as migrationsTableDdl}from"./src-Dpz7lQYB.mjs";import{SqliteDialect}from"kysely";function sqliteAdapter(opts){let dialect=`sqlite`,{database}=opts,runBatch=sql=>database.exec(sql);return{dialect,async ensureMigrationTables(){runBatch(migrationsTableDdl(dialect)),runBatch(lockTableDdl(dialect))},async listApplied(){return database.prepare(`SELECT id, name, hash, batch, applied_at, direction
|
|
12
12
|
FROM kick_migrations
|
|
13
13
|
ORDER BY applied_at ASC, id ASC`).all().map(row=>({id:row.id,name:row.name,hash:row.hash,batch:Number(row.batch),appliedAt:row.applied_at,direction:row.direction}))},async recordApplied(row){database.prepare(`INSERT INTO kick_migrations (id, name, hash, batch, direction)
|
|
14
14
|
VALUES (?, ?, ?, ?, ?)`).run(row.id,row.name,row.hash,row.batch,row.direction)},async removeApplied(id){database.prepare(`DELETE FROM kick_migrations WHERE id = ?`).run(id)},async acquireLock(owner){return database.prepare(`UPDATE kick_migrations_lock
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v6.1.
|
|
2
|
+
* @forinda/kickjs-db v6.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -155,4 +155,4 @@ import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from
|
|
|
155
155
|
`:``);await writeFile(path.join(dir,`down.sql`),downSql,`utf8`),await writeFile(path.join(dir,`snapshot.json`),JSON.stringify(p.target,null,2)+`
|
|
156
156
|
`,`utf8`),await writeFile(path.join(dir,`meta.json`),JSON.stringify({id,name:p.opts.name,createdAt:(p.opts.now?.()??new Date).toISOString(),reviewed:!1,dialect:p.opts.config.dialect,previousId:p.previousId,downIsDraft:p.draft,empty:p.empty},null,2)+`
|
|
157
157
|
`,`utf8`);let hash=await computeMigrationHash(dir);return await appendJournalEntry(p.migrationsAbs,p.opts.config.dialect,{id,tag:p.opts.name,hash,createdAt:(p.opts.now?.()??new Date).toISOString()}),{status:`created`,migrationDir:dir,changeCount:p.changeCount,empty:p.empty}}async function readLatestSnapshotEntry(migrationsDir,dialect){let empty={version:1,dialect,tables:{}};if(!existsSync(migrationsDir))return{snapshot:empty,id:null};let dirs=(await readdir(migrationsDir)).filter(e=>/^\d{8}_\d{6}_/.test(e)).toSorted();if(dirs.length===0)return{snapshot:empty,id:null};let latest=dirs[dirs.length-1],file=path.join(migrationsDir,latest,`snapshot.json`);return{snapshot:JSON.parse(await readFile(file,`utf8`)),id:latest}}async function assertNoCompositeReferences(changes,detect){if(!detect)return;let removals=changes.filter(c=>c.kind===`removeEnumValue`);if(removals.length===0)return;let allRefs=[],seen=new Set;for(let r of removals){if(seen.has(r.enum))continue;seen.add(r.enum);let refs=await detect(r.enum);allRefs.push(...refs)}if(allRefs.length>0)throw new CompositeEnumReferenceError(allRefs)}function formatId(date,name){let pad=n=>n.toString().padStart(2,`0`);return`${date.getUTCFullYear().toString()+pad(date.getUTCMonth()+1)+pad(date.getUTCDate())+`_`+pad(date.getUTCHours())+pad(date.getUTCMinutes())+pad(date.getUTCSeconds())}_${name.replace(/[^a-z0-9]+/gi,`_`).toLowerCase()}`}function brandGenerated(col){return col}function brandNotNull(col){return col}function formatNumeric(base,precision,scale){return precision===void 0?base:scale===void 0?`${base}(${precision})`:`${base}(${precision}, ${scale})`}function serial(){return brandNotNull(brandGenerated(new ColumnBuilder(`serial`,{nullable:!1})))}function bigSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`bigserial`,{nullable:!1})))}function smallSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`smallserial`,{nullable:!1})))}function integer(){return new ColumnBuilder(`integer`)}function bigint(){return new ColumnBuilder(`bigint`)}function smallint(){return new ColumnBuilder(`smallint`)}function decimal(precision,scale){return new ColumnBuilder(formatNumeric(`decimal`,precision,scale))}function numeric(precision,scale){return new ColumnBuilder(formatNumeric(`numeric`,precision,scale))}function real(){return new ColumnBuilder(`real`)}function doublePrecision(){return new ColumnBuilder(`double precision`)}function varchar(length=255){return new ColumnBuilder(`varchar(${length})`)}function char(length=1){return new ColumnBuilder(`char(${length})`)}function text(){return new ColumnBuilder(`text`)}function boolean(){return new ColumnBuilder(`boolean`)}var TimestampBuilder=class extends ColumnBuilder{constructor(typeName=`timestamp`){super(typeName)}defaultNow(){return this.state.default=`CURRENT_TIMESTAMP`,brandGenerated(this)}};function timestamp(){return new TimestampBuilder(`timestamp`)}function timestamptz(){return new TimestampBuilder(`timestamptz`)}function date(){return new ColumnBuilder(`date`)}function time(){return new ColumnBuilder(`time`)}function interval(){return new ColumnBuilder(`interval`)}var UuidBuilder=class extends ColumnBuilder{constructor(){super(`uuid`)}defaultRandom(){return this.state.default=`gen_random_uuid()`,brandGenerated(this)}};function uuid(){return new UuidBuilder}function json(){return new ColumnBuilder(`json`)}function jsonb(){return new ColumnBuilder(`jsonb`)}function bytea(){return new ColumnBuilder(`bytea`)}function table(name,columns,constraints){let decl={__isTable:!0,__name:name,__columns:columns,__indexes:[]},refs={};for(let[key,builder]of Object.entries(columns))refs[key]={__tableName:name,__name:key,__builder:builder,__state:()=>builder.__state()};if(constraints){let declared=constraints(refs);decl.__indexes=Object.values(declared)}return Object.assign(decl,refs)}function index(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!1}}}}function unique(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!0}}}}function relations(source,builder){return{__isRelations:!0,__sourceTable:source.__name,__relations:builder({one:(target,opts)=>({kind:`one`,target,fields:opts.fields,references:opts.references,...opts.relationName===void 0?{}:{relationName:opts.relationName}}),many:(target,opts)=>({kind:`many`,target,...opts?.relationName===void 0?{}:{relationName:opts.relationName}})})}}export{introspectMysql as $,generate as A,RelationalQueryDepthError as At,DB_CLIENT as B,smallint as C,invertChanges as Ct,timestamptz as D,RelationalQueryAliasCollisionError as Dt,timestamp as E,extractSnapshot as Et,CustomColumnBuilder as F,RemovedValueAsDefaultError as Ft,migrateLatest as G,DB_REPLICA as H,customType as I,migrateUp as J,migrateRollback as K,ColumnBuilder as L,reviewMigration as M,RelationalQueryNotSupportedError as Mt,safeNullComparison as N,RelationalQueryUnknownRelationError as Nt,uuid as O,RelationalQueryAmbiguousRelationNameError as Ot,createDbClient as P,KickDbError as Pt,emitSqlite as Q,KICK_GENERATED as R,smallSerial as S,hasAmbiguousReverse as St,time as T,renderSchemaSource as Tt,kickDbAdapter as U,DB_PRIMARY as V,migrateDown as W,emitMysql as X,checkDrift as Y,SqliteRebuildRequiredError as Z,json as _,MigrationHashError as _t,TimestampBuilder as a,lockTableDdl as at,real as b,CompositeEnumReferenceError as bt,bigint as c,computeMigrationHash as ct,char as d,enforceEnumDropGate as dt,introspectSqlite as et,date as f,parseEnumDropHeader as ft,interval as g,MigrationError as gt,integer as h,MigrationEnumDropError as ht,table as i,KICK_MIGRATIONS_TABLE as it,resolveDbConfig as j,RelationalQueryMissingInverseError as jt,varchar as k,RelationalQueryCancelledError as kt,boolean as l,readJournal as lt,doublePrecision as m,MigrationDriftError as mt,index as n,MemoryMigrationAdapter as nt,UuidBuilder as o,migrationsTableDdl as ot,decimal as p,emitPg as pt,migrateStatus as q,unique as r,KICK_LOCK_TABLE as rt,bigSerial as s,appendJournalEntry as st,relations as t,introspectPg as tt,bytea as u,verifyMigrationHash as ut,jsonb as v,MigrationLockError as vt,text as w,diff as wt,serial as x,detectCompositeReferences as xt,numeric as y,UnreviewedMigrationError as yt,KICK_NOT_NULL as z};
|
|
158
|
-
//# sourceMappingURL=src-
|
|
158
|
+
//# sourceMappingURL=src-Dpz7lQYB.mjs.map
|