@forinda/kickjs-db 6.3.0 → 7.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-7nwDY1yI.mjs → src-B2O8DgLh.mjs} +2 -2
- package/dist/{src-7nwDY1yI.mjs.map → src-B2O8DgLh.mjs.map} +1 -1
- package/package.json +5 -5
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db
|
|
2
|
+
* @forinda/kickjs-db v7.0.0-alpha.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{$ as migrateStatus,Dt as detectCompositeReferences,M as generate,P as reviewMigration,Q as migrateRollback,X as migrateDown,Z as migrateLatest,et as migrateUp,jt as renderSchemaSource}from"./src-
|
|
11
|
+
import{$ as migrateStatus,Dt as detectCompositeReferences,M as generate,P as reviewMigration,Q as migrateRollback,X as migrateDown,Z as migrateLatest,et as migrateUp,jt as renderSchemaSource}from"./src-B2O8DgLh.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,ctx.config?.db?.schemaPath);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,configuredPath){if(configuredPath){let abs=path.resolve(cwd,configuredPath);if(existsSync(abs))return abs;let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}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; migrates legacy -- 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
|
|
2
|
+
* @forinda/kickjs-db v7.0.0-alpha.0
|
|
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 migrateStatus,A as uuid,At as diff,B as readDialectMark,Bt as KickDbError,C as serial,Ct as MigrationHashError,D as time,Dt as detectCompositeReferences,E as text,Et as CompositeEnumReferenceError,F as safeNullComparison,Ft as RelationalQueryCancelledError,G as KICK_NOT_NULL,H as customType,I as createDbClient,It as RelationalQueryDepthError,J as DB_REPLICA,K as DB_CLIENT,L as KICK_DIALECT,Lt as RelationalQueryMissingInverseError,M as generate,Mt as extractSnapshot,N as resolveDbConfig,Nt as RelationalQueryAliasCollisionError,O as timestamp,Ot as hasAmbiguousReverse,P as reviewMigration,Pt as RelationalQueryAmbiguousRelationNameError,Q as migrateRollback,R as isDialectTag,Rt as RelationalQueryNotSupportedError,S as real,St as MigrationError,T as smallint,Tt as UnreviewedMigrationError,U as ColumnBuilder,V as CustomColumnBuilder,Vt as RemovedValueAsDefaultError,W as KICK_GENERATED,X as migrateDown,Y as kickDbAdapter,Z as migrateLatest,_ as integer,_t as enforceEnumDropGate,a as unique,at as introspectMysql,b as jsonb,bt as MigrationDriftError,c as UuidBuilder,ct as MemoryMigrationAdapter,d as boolean,dt as lockTableDdl,et as migrateUp,f as bytea,ft as migrationsTableDdl,g as doublePrecision,gt as verifyMigrationHash,h as decimal,ht as readJournal,i as index,it as emitSqlite,j as varchar,jt as renderSchemaSource,k as timestamptz,kt as invertChanges,l as bigSerial,lt as KICK_LOCK_TABLE,m as date,mt as computeMigrationHash,n as likePattern,nt as emitMysql,o as table,ot as introspectSqlite,p as char,pt as appendJournalEntry,q as DB_PRIMARY,r as relations,rt as SqliteRebuildRequiredError,s as TimestampBuilder,st as introspectPg,t as escapeLike,tt as checkDrift,u as bigint,ut as KICK_MIGRATIONS_TABLE,v as interval,vt as parseEnumDropHeader,w as smallSerial,wt as MigrationLockError,x as numeric,xt as MigrationEnumDropError,y as json,yt as emitPg,z as markDialect,zt as RelationalQueryUnknownRelationError}from"./src-
|
|
11
|
+
import{$ as migrateStatus,A as uuid,At as diff,B as readDialectMark,Bt as KickDbError,C as serial,Ct as MigrationHashError,D as time,Dt as detectCompositeReferences,E as text,Et as CompositeEnumReferenceError,F as safeNullComparison,Ft as RelationalQueryCancelledError,G as KICK_NOT_NULL,H as customType,I as createDbClient,It as RelationalQueryDepthError,J as DB_REPLICA,K as DB_CLIENT,L as KICK_DIALECT,Lt as RelationalQueryMissingInverseError,M as generate,Mt as extractSnapshot,N as resolveDbConfig,Nt as RelationalQueryAliasCollisionError,O as timestamp,Ot as hasAmbiguousReverse,P as reviewMigration,Pt as RelationalQueryAmbiguousRelationNameError,Q as migrateRollback,R as isDialectTag,Rt as RelationalQueryNotSupportedError,S as real,St as MigrationError,T as smallint,Tt as UnreviewedMigrationError,U as ColumnBuilder,V as CustomColumnBuilder,Vt as RemovedValueAsDefaultError,W as KICK_GENERATED,X as migrateDown,Y as kickDbAdapter,Z as migrateLatest,_ as integer,_t as enforceEnumDropGate,a as unique,at as introspectMysql,b as jsonb,bt as MigrationDriftError,c as UuidBuilder,ct as MemoryMigrationAdapter,d as boolean,dt as lockTableDdl,et as migrateUp,f as bytea,ft as migrationsTableDdl,g as doublePrecision,gt as verifyMigrationHash,h as decimal,ht as readJournal,i as index,it as emitSqlite,j as varchar,jt as renderSchemaSource,k as timestamptz,kt as invertChanges,l as bigSerial,lt as KICK_LOCK_TABLE,m as date,mt as computeMigrationHash,n as likePattern,nt as emitMysql,o as table,ot as introspectSqlite,p as char,pt as appendJournalEntry,q as DB_PRIMARY,r as relations,rt as SqliteRebuildRequiredError,s as TimestampBuilder,st as introspectPg,t as escapeLike,tt as checkDrift,u as bigint,ut as KICK_MIGRATIONS_TABLE,v as interval,vt as parseEnumDropHeader,w as smallSerial,wt as MigrationLockError,x as numeric,xt as MigrationEnumDropError,y as json,yt as emitPg,z as markDialect,zt as RelationalQueryUnknownRelationError}from"./src-B2O8DgLh.mjs";export{ColumnBuilder,CompositeEnumReferenceError,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,KICK_DIALECT,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,escapeLike,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectMysql,introspectPg,introspectSqlite,invertChanges,isDialectTag,json,jsonb,kickDbAdapter,likePattern,lockTableDdl,markDialect,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,parseEnumDropHeader,readDialectMark,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
|
|
2
|
+
* @forinda/kickjs-db v7.0.0-alpha.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Bt as KickDbError,at as introspectMysql,dt as lockTableDdl,ft as migrationsTableDdl,z as markDialect}from"./src-
|
|
11
|
+
import{Bt as KickDbError,at as introspectMysql,dt as lockTableDdl,ft as migrationsTableDdl,z as markDialect}from"./src-B2O8DgLh.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
|
|
2
|
+
* @forinda/kickjs-db v7.0.0-alpha.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{U as ColumnBuilder,dt as lockTableDdl,ft as migrationsTableDdl,st as introspectPg,z as markDialect}from"./src-
|
|
11
|
+
import{U as ColumnBuilder,dt as lockTableDdl,ft as migrationsTableDdl,st as introspectPg,z as markDialect}from"./src-B2O8DgLh.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
|
|
2
|
+
* @forinda/kickjs-db v7.0.0-alpha.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{dt as lockTableDdl,ft as migrationsTableDdl,ot as introspectSqlite,z as markDialect}from"./src-
|
|
11
|
+
import{dt as lockTableDdl,ft as migrationsTableDdl,ot as introspectSqlite,z as markDialect}from"./src-B2O8DgLh.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
|
|
2
|
+
* @forinda/kickjs-db v7.0.0-alpha.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -153,4 +153,4 @@ import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from
|
|
|
153
153
|
`:``);await writeFile(path.join(dir,`down.sql`),downSql,`utf8`),await writeFile(path.join(dir,`snapshot.json`),JSON.stringify(p.target,null,2)+`
|
|
154
154
|
`,`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)+`
|
|
155
155
|
`,`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}})})}}function escapeLike(input,escapeChar=`\\`){if(escapeChar.length!==1||escapeChar===`%`||escapeChar===`_`)throw Error(`escapeLike: escapeChar must be a single character other than '%' or '_'`);let e=escapeChar;return input.replaceAll(e,e+e).replaceAll(`%`,e+`%`).replaceAll(`_`,e+`_`)}function likePattern(input,mode=`contains`,escapeChar=`\\`){let safe=escapeLike(input,escapeChar);switch(mode){case`contains`:return`%${safe}%`;case`startsWith`:return`${safe}%`;case`endsWith`:return`%${safe}`;case`exact`:return safe;default:throw Error(`likePattern: unsupported match mode ${String(mode)}`)}}export{migrateStatus as $,uuid as A,diff as At,readDialectMark as B,KickDbError as Bt,serial as C,MigrationHashError as Ct,time as D,detectCompositeReferences as Dt,text as E,CompositeEnumReferenceError as Et,safeNullComparison as F,RelationalQueryCancelledError as Ft,KICK_NOT_NULL as G,customType as H,createDbClient as I,RelationalQueryDepthError as It,DB_REPLICA as J,DB_CLIENT as K,KICK_DIALECT as L,RelationalQueryMissingInverseError as Lt,generate as M,extractSnapshot as Mt,resolveDbConfig as N,RelationalQueryAliasCollisionError as Nt,timestamp as O,hasAmbiguousReverse as Ot,reviewMigration as P,RelationalQueryAmbiguousRelationNameError as Pt,migrateRollback as Q,isDialectTag as R,RelationalQueryNotSupportedError as Rt,real as S,MigrationError as St,smallint as T,UnreviewedMigrationError as Tt,ColumnBuilder as U,CustomColumnBuilder as V,RemovedValueAsDefaultError as Vt,KICK_GENERATED as W,migrateDown as X,kickDbAdapter as Y,migrateLatest as Z,integer as _,enforceEnumDropGate as _t,unique as a,introspectMysql as at,jsonb as b,MigrationDriftError as bt,UuidBuilder as c,MemoryMigrationAdapter as ct,boolean as d,lockTableDdl as dt,migrateUp as et,bytea as f,migrationsTableDdl as ft,doublePrecision as g,verifyMigrationHash as gt,decimal as h,readJournal as ht,index as i,emitSqlite as it,varchar as j,renderSchemaSource as jt,timestamptz as k,invertChanges as kt,bigSerial as l,KICK_LOCK_TABLE as lt,date as m,computeMigrationHash as mt,likePattern as n,emitMysql as nt,table as o,introspectSqlite as ot,char as p,appendJournalEntry as pt,DB_PRIMARY as q,relations as r,SqliteRebuildRequiredError as rt,TimestampBuilder as s,introspectPg as st,escapeLike as t,checkDrift as tt,bigint as u,KICK_MIGRATIONS_TABLE as ut,interval as v,parseEnumDropHeader as vt,smallSerial as w,MigrationLockError as wt,numeric as x,MigrationEnumDropError as xt,json as y,emitPg as yt,markDialect as z,RelationalQueryUnknownRelationError as zt};
|
|
156
|
-
//# sourceMappingURL=src-
|
|
156
|
+
//# sourceMappingURL=src-B2O8DgLh.mjs.map
|