@forinda/kickjs-db 6.0.0-alpha.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.0.0-alpha.0
2
+ * @forinda/kickjs-db v6.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.0.0-alpha.0
2
+ * @forinda/kickjs-db v6.0.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{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-BPEyCTZ_.mjs";import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{createToken,defineAdapter}from"@forinda/kickjs";import{BinaryOperationNode,ColumnNode,ColumnUpdateNode,InsertQueryNode,Kysely,OperationNodeTransformer,OperatorNode,ParseJSONResultsPlugin,PrimitiveValueListNode,ReferenceNode,SelectAllNode,SelectQueryNode,SelectionNode,TableNode,UpdateQueryNode,ValueListNode,ValueNode,ValuesNode,sql}from"kysely";import{EventEmitter}from"node:events";import{jsonArrayFrom,jsonObjectFrom}from"kysely/helpers/postgres";import{jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from"kysely/helpers/sqlite";import{jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from"kysely/helpers/mysql";import{pathToFileURL}from"node:url";var KickDbError=class extends Error{code;constructor(code,message){super(message),this.name=this.constructor.name,this.code=code}},RemovedValueAsDefaultError=class extends KickDbError{enum;table;column;value;constructor(enumName,table,column,value){super(`removed_value_as_default`,`Cannot remove value '${value}' from enum '${enumName}': the column ${table}.${column} declares it as the default. Update the column's default to a surviving enum value (or drop the default) before re-running \`kick db generate\`.`),this.enum=enumName,this.table=table,this.column=column,this.value=value}},RelationalQueryUnknownRelationError=class extends KickDbError{sourceTable;relationKey;constructor(sourceTable,relationKey){super(`KICK_DB_RELATIONAL_UNKNOWN_RELATION`,`Unknown relation \`${sourceTable}.${relationKey}\` — declare it via \`relations()\` before referencing it inside \`db.query.${sourceTable}.findMany({ with })\`.`),this.sourceTable=sourceTable,this.relationKey=relationKey}},RelationalQueryDepthError=class extends KickDbError{maxDepth;trace;constructor(maxDepth,trace){super(`KICK_DB_RELATIONAL_DEPTH_EXCEEDED`,`Relational query exceeds maxDepth=${maxDepth}. Path: ${trace.join(` → `)}. Override with \`{ maxDepth: N }\` on the call site if intentional.`),this.maxDepth=maxDepth,this.trace=trace}},RelationalQueryAliasCollisionError=class extends KickDbError{sourceTable;conflictingName;constructor(sourceTable,conflictingName){super(`KICK_DB_RELATIONAL_ALIAS_COLLISION`,`Relation \`${sourceTable}.${conflictingName}\` collides with a column of the same name. Rename the relation or the column to disambiguate.`),this.sourceTable=sourceTable,this.conflictingName=conflictingName}},RelationalQueryCancelledError=class extends KickDbError{cause;constructor(cause){let reasonText=formatCancelCause(cause);super(`relational_query_cancelled`,`Relational query cancelled by AbortSignal${reasonText?` — ${reasonText}`:`.`}`),this.cause=cause}};function formatCancelCause(cause){if(cause==null)return``;if(cause instanceof Error)return cause.message;if(typeof cause==`string`)return cause;try{return JSON.stringify(cause)}catch{return String(cause)}}var RelationalQueryNotSupportedError=class extends KickDbError{dialect;constructor(dialect){super(`KICK_DB_RELATIONAL_NOT_SUPPORTED`,`Relational query compiler for dialect \`${dialect}\` lands in M4. Use layer 1 / 2 (\`db.selectFrom(...)\`) with manual joins for now.`),this.dialect=dialect}},RelationalQueryAmbiguousRelationNameError=class extends KickDbError{sourceTable;targetTable;relationName;conflicting;constructor(sourceTable,targetTable,relationName,conflicting){super(`KICK_DB_RELATIONAL_AMBIGUOUS_RELATION_NAME`,`Cannot pair \`${sourceTable}\`'s \`many\` with relationName='${relationName}' — multiple \`one\` relations on \`${targetTable}\` share that tag and point back at \`${sourceTable}\` (${conflicting.map(c=>`\`${targetTable}.${c}\``).join(`, `)}). The pairing tag must be unique per (source, target, name) triple — rename one of the \`one\` relations on \`${targetTable}\` or split the schema.`),this.sourceTable=sourceTable,this.targetTable=targetTable,this.relationName=relationName,this.conflicting=conflicting}},RelationalQueryMissingInverseError=class extends KickDbError{sourceTable;relationName;targetTable;constructor(sourceTable,relationName,targetTable){super(`KICK_DB_RELATIONAL_MISSING_INVERSE`,`Cannot resolve \`many\` relation \`${sourceTable}.${relationName}\` — no inverse \`one\` relation declared on \`${targetTable}\` pointing back to \`${sourceTable}\`, and ${targetTable}'s foreign keys to ${sourceTable} are either zero or ambiguous. If the target has multiple FKs to the source, tag both sides with the same \`relationName: 'foo'\` to pair them — see docs/db/spec-relation-name.md. Otherwise add e.g. \`relations(${targetTable}, h => ({ ${sourceTable}: h.one(${sourceTable}, { fields: [${targetTable}.${sourceTable}Id], references: [${sourceTable}.id] }) }))\` so the compiler knows which columns join the two tables.`),this.sourceTable=sourceTable,this.relationName=relationName,this.targetTable=targetTable}};function isRelations(v){return!!(v&&typeof v==`object`&&v.__isRelations===!0)}function extractRelations(schema,tables){let declsBySource={};for(let value of Object.values(schema))isRelations(value)&&(declsBySource[value.__sourceTable]={...declsBySource[value.__sourceTable],...value.__relations});if(Object.keys(declsBySource).length===0)return;let out={};for(let[sourceTable,relations]of Object.entries(declsBySource)){let tableSnapshot=tables[sourceTable];if(tableSnapshot){out[sourceTable]={};for(let[relationName,rel]of Object.entries(relations)){if(relationName in tableSnapshot.columns)throw new RelationalQueryAliasCollisionError(sourceTable,relationName);if(rel.kind===`one`){out[sourceTable][relationName]={kind:`one`,target:rel.target.__name,sourceColumns:rel.fields.map(f=>f.__name),targetColumns:rel.references.map(r=>r.__name),...rel.relationName===void 0?{}:{relationName:rel.relationName}};continue}let target=rel.target.__name,targetRelations=declsBySource[target]??{},relNameSpread=rel.relationName===void 0?{}:{relationName:rel.relationName};if(rel.relationName!==void 0){let matchingInverses=findInversesByRelationName(targetRelations,sourceTable,rel.relationName);if(matchingInverses.length>1)throw new RelationalQueryAmbiguousRelationNameError(sourceTable,target,rel.relationName,matchingInverses.map(m=>m.relationKey));if(matchingInverses.length===1){let inverse=matchingInverses[0].relation;out[sourceTable][relationName]={kind:`many`,target,sourceColumns:inverse.references.map(r=>r.__name),targetColumns:inverse.fields.map(f=>f.__name),...relNameSpread};continue}}let untaggedInverse=findUniqueUntaggedInverse(targetRelations,sourceTable);if(untaggedInverse){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:untaggedInverse.references.map(r=>r.__name),targetColumns:untaggedInverse.fields.map(f=>f.__name),...relNameSpread};continue}let fkFallback=resolveByForeignKey(tables[target],sourceTable);if(fkFallback){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:fkFallback.refColumns,targetColumns:fkFallback.columns,...relNameSpread};continue}throw new RelationalQueryMissingInverseError(sourceTable,relationName,target)}}}return out}function findInversesByRelationName(targetRelations,sourceTable,relationName){let matches=[];for(let[key,rel]of Object.entries(targetRelations))rel.kind===`one`&&rel.target.__name===sourceTable&&rel.relationName===relationName&&matches.push({relationKey:key,relation:rel});return matches}function findUniqueUntaggedInverse(targetRelations,sourceTable){let unique=null;for(let rel of Object.values(targetRelations))if(rel.kind===`one`&&rel.target.__name===sourceTable&&rel.relationName===void 0){if(unique)return null;unique=rel}return unique}function resolveByForeignKey(targetTable,sourceTable){if(!targetTable)return null;let matches=targetTable.foreignKeys.filter(fk=>fk.refTable===sourceTable);if(matches.length!==1)return null;let fk=matches[0];return{columns:fk.columns,refColumns:fk.refColumns}}function isTable(v){return!!(v&&typeof v==`object`&&v.__isTable===!0)}function isPgEnum(v){if(typeof v!=`function`)return!1;let f=v;return typeof f.enumName==`string`&&Array.isArray(f.values)}function extractSnapshot(schema,dialect){let tables={},enums={};for(let value of Object.values(schema))isTable(value)?tables[value.__name]=extractTable(value):isPgEnum(value)&&(enums[value.enumName]={name:value.enumName,values:[...value.values]});let relations=extractRelations(schema,tables),snapshot={version:1,dialect,tables};return dialect===`postgres`&&Object.keys(enums).length>0&&(snapshot.enums=enums),relations&&(snapshot.relations=relations),snapshot}function extractTable(t){let columns={},indexes=[...t.__indexes],foreignKeys=[];for(let[colKey,builder]of Object.entries(t.__columns)){columns[colKey]=builder.toJSON(colKey);let state=builder.__state();if(state.unique&&indexes.push({name:`${t.__name}_${colKey}_unique`,columns:[colKey],unique:!0}),state.references){let ref=state.references.thunk();foreignKeys.push({name:`${t.__name}_${colKey}_fk`,columns:[colKey],refTable:ref.__tableName,refColumns:[ref.__name],onDelete:state.references.onDelete,onUpdate:state.references.onUpdate})}}return{name:t.__name,columns,indexes,foreignKeys,checks:[]}}function renderSchemaSource(snapshot){let usedColumnHelpers=new Set,tableSources=[];for(let table of Object.values(snapshot.tables))tableSources.push(renderTable(table,usedColumnHelpers));let helpers=[`table`,...Array.from(usedColumnHelpers).toSorted()];return Object.values(snapshot.tables).some(t=>t.indexes.some(i=>!isAutoUniqueName(t.name,i)))&&helpers.push(`index`),Object.values(snapshot.tables).some(t=>t.indexes.some(i=>i.unique&&!isAutoUniqueName(t.name,i)))&&!helpers.includes(`unique`)&&helpers.push(`unique`),[`import { ${helpers.join(`, `)} } from '@forinda/kickjs-db'`,``,...tableSources].join(`
11
+ import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-CnOQetrD.mjs";import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{createToken,defineAdapter}from"@forinda/kickjs";import{BinaryOperationNode,ColumnNode,ColumnUpdateNode,InsertQueryNode,Kysely,OperationNodeTransformer,OperatorNode,ParseJSONResultsPlugin,PrimitiveValueListNode,ReferenceNode,SelectAllNode,SelectQueryNode,SelectionNode,TableNode,UpdateQueryNode,ValueListNode,ValueNode,ValuesNode,sql}from"kysely";import{EventEmitter}from"node:events";import{jsonArrayFrom,jsonObjectFrom}from"kysely/helpers/postgres";import{jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from"kysely/helpers/sqlite";import{jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from"kysely/helpers/mysql";import{pathToFileURL}from"node:url";var KickDbError=class extends Error{code;constructor(code,message){super(message),this.name=this.constructor.name,this.code=code}},RemovedValueAsDefaultError=class extends KickDbError{enum;table;column;value;constructor(enumName,table,column,value){super(`removed_value_as_default`,`Cannot remove value '${value}' from enum '${enumName}': the column ${table}.${column} declares it as the default. Update the column's default to a surviving enum value (or drop the default) before re-running \`kick db generate\`.`),this.enum=enumName,this.table=table,this.column=column,this.value=value}},RelationalQueryUnknownRelationError=class extends KickDbError{sourceTable;relationKey;constructor(sourceTable,relationKey){super(`KICK_DB_RELATIONAL_UNKNOWN_RELATION`,`Unknown relation \`${sourceTable}.${relationKey}\` — declare it via \`relations()\` before referencing it inside \`db.query.${sourceTable}.findMany({ with })\`.`),this.sourceTable=sourceTable,this.relationKey=relationKey}},RelationalQueryDepthError=class extends KickDbError{maxDepth;trace;constructor(maxDepth,trace){super(`KICK_DB_RELATIONAL_DEPTH_EXCEEDED`,`Relational query exceeds maxDepth=${maxDepth}. Path: ${trace.join(` → `)}. Override with \`{ maxDepth: N }\` on the call site if intentional.`),this.maxDepth=maxDepth,this.trace=trace}},RelationalQueryAliasCollisionError=class extends KickDbError{sourceTable;conflictingName;constructor(sourceTable,conflictingName){super(`KICK_DB_RELATIONAL_ALIAS_COLLISION`,`Relation \`${sourceTable}.${conflictingName}\` collides with a column of the same name. Rename the relation or the column to disambiguate.`),this.sourceTable=sourceTable,this.conflictingName=conflictingName}},RelationalQueryCancelledError=class extends KickDbError{cause;constructor(cause){let reasonText=formatCancelCause(cause);super(`relational_query_cancelled`,`Relational query cancelled by AbortSignal${reasonText?` — ${reasonText}`:`.`}`),this.cause=cause}};function formatCancelCause(cause){if(cause==null)return``;if(cause instanceof Error)return cause.message;if(typeof cause==`string`)return cause;try{return JSON.stringify(cause)}catch{return String(cause)}}var RelationalQueryNotSupportedError=class extends KickDbError{dialect;constructor(dialect){super(`KICK_DB_RELATIONAL_NOT_SUPPORTED`,`Relational query compiler for dialect \`${dialect}\` lands in M4. Use layer 1 / 2 (\`db.selectFrom(...)\`) with manual joins for now.`),this.dialect=dialect}},RelationalQueryAmbiguousRelationNameError=class extends KickDbError{sourceTable;targetTable;relationName;conflicting;constructor(sourceTable,targetTable,relationName,conflicting){super(`KICK_DB_RELATIONAL_AMBIGUOUS_RELATION_NAME`,`Cannot pair \`${sourceTable}\`'s \`many\` with relationName='${relationName}' — multiple \`one\` relations on \`${targetTable}\` share that tag and point back at \`${sourceTable}\` (${conflicting.map(c=>`\`${targetTable}.${c}\``).join(`, `)}). The pairing tag must be unique per (source, target, name) triple — rename one of the \`one\` relations on \`${targetTable}\` or split the schema.`),this.sourceTable=sourceTable,this.targetTable=targetTable,this.relationName=relationName,this.conflicting=conflicting}},RelationalQueryMissingInverseError=class extends KickDbError{sourceTable;relationName;targetTable;constructor(sourceTable,relationName,targetTable){super(`KICK_DB_RELATIONAL_MISSING_INVERSE`,`Cannot resolve \`many\` relation \`${sourceTable}.${relationName}\` — no inverse \`one\` relation declared on \`${targetTable}\` pointing back to \`${sourceTable}\`, and ${targetTable}'s foreign keys to ${sourceTable} are either zero or ambiguous. If the target has multiple FKs to the source, tag both sides with the same \`relationName: 'foo'\` to pair them — see docs/db/spec-relation-name.md. Otherwise add e.g. \`relations(${targetTable}, h => ({ ${sourceTable}: h.one(${sourceTable}, { fields: [${targetTable}.${sourceTable}Id], references: [${sourceTable}.id] }) }))\` so the compiler knows which columns join the two tables.`),this.sourceTable=sourceTable,this.relationName=relationName,this.targetTable=targetTable}};function isRelations(v){return!!(v&&typeof v==`object`&&v.__isRelations===!0)}function extractRelations(schema,tables){let declsBySource={};for(let value of Object.values(schema))isRelations(value)&&(declsBySource[value.__sourceTable]={...declsBySource[value.__sourceTable],...value.__relations});if(Object.keys(declsBySource).length===0)return;let out={};for(let[sourceTable,relations]of Object.entries(declsBySource)){let tableSnapshot=tables[sourceTable];if(tableSnapshot){out[sourceTable]={};for(let[relationName,rel]of Object.entries(relations)){if(relationName in tableSnapshot.columns)throw new RelationalQueryAliasCollisionError(sourceTable,relationName);if(rel.kind===`one`){out[sourceTable][relationName]={kind:`one`,target:rel.target.__name,sourceColumns:rel.fields.map(f=>f.__name),targetColumns:rel.references.map(r=>r.__name),...rel.relationName===void 0?{}:{relationName:rel.relationName}};continue}let target=rel.target.__name,targetRelations=declsBySource[target]??{},relNameSpread=rel.relationName===void 0?{}:{relationName:rel.relationName};if(rel.relationName!==void 0){let matchingInverses=findInversesByRelationName(targetRelations,sourceTable,rel.relationName);if(matchingInverses.length>1)throw new RelationalQueryAmbiguousRelationNameError(sourceTable,target,rel.relationName,matchingInverses.map(m=>m.relationKey));if(matchingInverses.length===1){let inverse=matchingInverses[0].relation;out[sourceTable][relationName]={kind:`many`,target,sourceColumns:inverse.references.map(r=>r.__name),targetColumns:inverse.fields.map(f=>f.__name),...relNameSpread};continue}}let untaggedInverse=findUniqueUntaggedInverse(targetRelations,sourceTable);if(untaggedInverse){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:untaggedInverse.references.map(r=>r.__name),targetColumns:untaggedInverse.fields.map(f=>f.__name),...relNameSpread};continue}let fkFallback=resolveByForeignKey(tables[target],sourceTable);if(fkFallback){out[sourceTable][relationName]={kind:`many`,target,sourceColumns:fkFallback.refColumns,targetColumns:fkFallback.columns,...relNameSpread};continue}throw new RelationalQueryMissingInverseError(sourceTable,relationName,target)}}}return out}function findInversesByRelationName(targetRelations,sourceTable,relationName){let matches=[];for(let[key,rel]of Object.entries(targetRelations))rel.kind===`one`&&rel.target.__name===sourceTable&&rel.relationName===relationName&&matches.push({relationKey:key,relation:rel});return matches}function findUniqueUntaggedInverse(targetRelations,sourceTable){let unique=null;for(let rel of Object.values(targetRelations))if(rel.kind===`one`&&rel.target.__name===sourceTable&&rel.relationName===void 0){if(unique)return null;unique=rel}return unique}function resolveByForeignKey(targetTable,sourceTable){if(!targetTable)return null;let matches=targetTable.foreignKeys.filter(fk=>fk.refTable===sourceTable);if(matches.length!==1)return null;let fk=matches[0];return{columns:fk.columns,refColumns:fk.refColumns}}function isTable(v){return!!(v&&typeof v==`object`&&v.__isTable===!0)}function isPgEnum(v){if(typeof v!=`function`)return!1;let f=v;return typeof f.enumName==`string`&&Array.isArray(f.values)}function extractSnapshot(schema,dialect){let tables={},enums={};for(let value of Object.values(schema))isTable(value)?tables[value.__name]=extractTable(value):isPgEnum(value)&&(enums[value.enumName]={name:value.enumName,values:[...value.values]});let relations=extractRelations(schema,tables),snapshot={version:1,dialect,tables};return dialect===`postgres`&&Object.keys(enums).length>0&&(snapshot.enums=enums),relations&&(snapshot.relations=relations),snapshot}function extractTable(t){let columns={},indexes=[...t.__indexes],foreignKeys=[];for(let[colKey,builder]of Object.entries(t.__columns)){columns[colKey]=builder.toJSON(colKey);let state=builder.__state();if(state.unique&&indexes.push({name:`${t.__name}_${colKey}_unique`,columns:[colKey],unique:!0}),state.references){let ref=state.references.thunk();foreignKeys.push({name:`${t.__name}_${colKey}_fk`,columns:[colKey],refTable:ref.__tableName,refColumns:[ref.__name],onDelete:state.references.onDelete,onUpdate:state.references.onUpdate})}}return{name:t.__name,columns,indexes,foreignKeys,checks:[]}}function renderSchemaSource(snapshot){let usedColumnHelpers=new Set,tableSources=[];for(let table of Object.values(snapshot.tables))tableSources.push(renderTable(table,usedColumnHelpers));let helpers=[`table`,...Array.from(usedColumnHelpers).toSorted()];return Object.values(snapshot.tables).some(t=>t.indexes.some(i=>!isAutoUniqueName(t.name,i)))&&helpers.push(`index`),Object.values(snapshot.tables).some(t=>t.indexes.some(i=>i.unique&&!isAutoUniqueName(t.name,i)))&&!helpers.includes(`unique`)&&helpers.push(`unique`),[`import { ${helpers.join(`, `)} } from '@forinda/kickjs-db'`,``,...tableSources].join(`
12
12
  `).trimEnd()+`
13
13
  `}function renderTable(table,helpers){let ident=jsIdent(table.name),columns=[];for(let col of Object.values(table.columns)){let fk=table.foreignKeys.find(f=>f.columns.length===1&&f.columns[0]===col.name&&f.name===`${table.name}_${col.name}_fk`),inlineUnique=table.indexes.find(i=>i.unique&&i.columns.length===1&&i.columns[0]===col.name&&isAutoUniqueName(table.name,i))!==void 0;columns.push(` ${jsKey(col.name)}: ${renderColumn(col,helpers,fk,inlineUnique)},`)}let explicitIndexes=table.indexes.filter(i=>!isAutoUniqueName(table.name,i)),explicitFks=table.foreignKeys.filter(f=>f.name!==`${table.name}_${f.columns[0]}_fk`||f.columns.length!==1),hasThirdArg=explicitIndexes.length>0,tableArgs=[`'${table.name}'`,`{\n${columns.join(`
14
14
  `)}\n}`];if(hasThirdArg){let callbacks=explicitIndexes.map(i=>` ${jsKey(i.name)}: ${renderIndexCall(i)}`).join(`,
package/dist/pg.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.0.0-alpha.0
2
+ * @forinda/kickjs-db v6.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as ColumnBuilder}from"./types-BPEyCTZ_.mjs";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`)}export{PgEnumColumnBuilder,cidr,citext,inet,money,pgEnum,tsvector,vector,xml};
11
+ import{t as ColumnBuilder}from"./types-CnOQetrD.mjs";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`)}export{PgEnumColumnBuilder,cidr,citext,inet,money,pgEnum,tsvector,vector,xml};
12
12
  //# sourceMappingURL=pg.mjs.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-db v6.0.0-alpha.0
2
+ * @forinda/kickjs-db v6.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  const KICK_GENERATED=Symbol.for(`@forinda/kickjs-db/Generated`),KICK_NOT_NULL=Symbol.for(`@forinda/kickjs-db/NotNull`);var ColumnBuilder=class{state;constructor(type,defaults={}){this.state={type,nullable:defaults.nullable??!0,default:defaults.default??null,primaryKey:defaults.primaryKey??!1,unique:defaults.unique??!1,references:defaults.references??null}}notNull(){return this.state.nullable=!1,this}primaryKey(){return this.state.primaryKey=!0,this.state.nullable=!1,this}unique(){return this.state.unique=!0,this}array(){return this.state.type=`${this.state.type}[]`,this}references(target,opts={}){return this.state.references={thunk:target,onDelete:opts.onDelete??`no_action`,onUpdate:opts.onUpdate??`no_action`},this}default(value){return this.state.default=value,this}toJSON(name){return{name,type:this.state.type,nullable:this.state.nullable,default:this.state.default,primaryKey:this.state.primaryKey}}__state(){return this.state}};export{KICK_GENERATED as n,KICK_NOT_NULL as r,ColumnBuilder as t};
12
- //# sourceMappingURL=types-BPEyCTZ_.mjs.map
12
+ //# sourceMappingURL=types-CnOQetrD.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"types-BPEyCTZ_.mjs","names":[],"sources":["../src/dsl/columns/types.ts"],"sourcesContent":["import type { ColumnSnapshot, FkAction } from '../../snapshot/types'\n\n/**\n * Runtime + type representation of a column reference (e.g. `users.id`).\n * Carries the parent table name, the column's own name, plus runtime\n * accessors used by FK thunks and constraint builders.\n *\n * Exported so adopters can annotate self-referencing thunks without\n * spelling the shape inline:\n *\n * parentId: uuid().references((): ColumnRef => categories.id)\n *\n * Without the annotation the initializer of a self-referencing const\n * trips TS7022 — TS needs to infer the const while the initializer\n * already references it.\n */\nexport interface ColumnRef {\n __tableName: string\n __name: string\n __builder: ColumnBuilder\n __state: () => ReturnType<ColumnBuilder['__state']>\n}\n\n/**\n * Resolved FK spec — `table` / `column` are pulled by invoking `thunk()`\n * lazily. The thunk pattern lets self-referencing tables work:\n *\n * const categories = table('categories', {\n * id: uuid().primaryKey().defaultRandom(),\n * parentId: uuid().references((): ColumnRef => categories.id),\n * })\n *\n * If we resolved at `.references()` call time, `categories` would TDZ-fail\n * inside its own initializer. Storing the thunk and resolving on read\n * (extract / render / emit) defers until after the const binding lands.\n */\nexport interface FkSpec {\n thunk: () => ColumnRef\n onDelete: FkAction\n onUpdate: FkAction\n}\n\nexport interface ColumnState {\n type: string\n nullable: boolean\n default: string | null\n primaryKey: boolean\n unique: boolean\n references: FkSpec | null\n}\n\n/**\n * Type-only brand attached to a column when it's auto-assigned by the\n * database (serial / bigserial / smallserial), has a runtime default\n * (`.default(...)`), or carries an expression default\n * (`uuid().defaultRandom()`, `timestamp().defaultNow()`). `SchemaToTypes<S>`\n * reads this marker and wraps the column type in Kysely's `Generated<T>` so\n * adopters can omit the column on insert.\n *\n * Runtime is a no-op — the symbol never reaches a value.\n */\nexport const KICK_GENERATED = Symbol.for('@forinda/kickjs-db/Generated')\nexport type GeneratedBrand = { readonly [KICK_GENERATED]?: true }\n\n/**\n * Type-only brand attached to a column when `.notNull()` or `.primaryKey()`\n * is called. `SchemaToTypes<S>` reads this brand to decide whether the\n * column type is `T` (NOT NULL) or `T | null` (default nullable).\n *\n * Why a brand instead of a class generic: chained methods (notNull,\n * primaryKey) can return `this & NotNullBrand` to narrow nullability while\n * preserving the subclass identity — so `uuid().primaryKey().defaultRandom()`\n * still resolves `defaultRandom()` on `UuidBuilder`. A class generic\n * `<TNullable>` would collapse the subclass back to the parent.\n */\nexport const KICK_NOT_NULL = Symbol.for('@forinda/kickjs-db/NotNull')\nexport type NotNullBrand = { readonly [KICK_NOT_NULL]?: true }\n\n/**\n * Phantom-typed column builder. The `T` generic carries the column's TS\n * value type (number / string / Date / etc.); nullability is tracked via\n * the `NotNullBrand` intersection rather than a class generic so chain\n * methods preserve subclass identity.\n *\n * Both `T` and the brand are erased at runtime; they exist purely so\n * `SchemaToTypes<S>` can pull them out per column.\n */\nexport class ColumnBuilder<T = unknown> {\n // Phantom param shows up in the public surface so the type system sees\n // it. Reading it at runtime is intentionally not supported.\n declare readonly __t?: T\n\n protected state: ColumnState\n\n constructor(type: string, defaults: Partial<ColumnState> = {}) {\n this.state = {\n type,\n nullable: defaults.nullable ?? true,\n default: defaults.default ?? null,\n primaryKey: defaults.primaryKey ?? false,\n unique: defaults.unique ?? false,\n references: defaults.references ?? null,\n }\n }\n\n notNull(): this & NotNullBrand {\n this.state.nullable = false\n return this as this & NotNullBrand\n }\n\n primaryKey(): this & NotNullBrand {\n this.state.primaryKey = true\n this.state.nullable = false\n return this as this & NotNullBrand\n }\n\n unique(): this {\n this.state.unique = true\n return this\n }\n\n array(): ColumnBuilder<T[]> {\n this.state.type = `${this.state.type}[]`\n return this as unknown as ColumnBuilder<T[]>\n }\n\n references(\n target: () => ColumnRef,\n opts: { onDelete?: FkAction; onUpdate?: FkAction } = {},\n ): this {\n // Store the thunk — do NOT invoke it here. Self-referencing tables\n // pass `() => self.id` whose binding does not exist yet.\n this.state.references = {\n thunk: target,\n onDelete: opts.onDelete ?? 'no_action',\n onUpdate: opts.onUpdate ?? 'no_action',\n }\n return this\n }\n\n /**\n * Mark the column as having a runtime / DB-assigned default. The\n * `GeneratedBrand` flows into `SchemaToTypes<S>` so the column wraps\n * in `Generated<T>` — adopters can `INSERT` without specifying it.\n */\n default(value: string): this & GeneratedBrand {\n this.state.default = value\n return this as this & GeneratedBrand\n }\n\n toJSON(name: string): ColumnSnapshot {\n return {\n name,\n type: this.state.type,\n nullable: this.state.nullable,\n default: this.state.default,\n primaryKey: this.state.primaryKey,\n }\n }\n\n // Internal accessor for table()/diff to read full state including unique/references.\n __state(): Readonly<ColumnState> {\n return this.state\n }\n}\n"],"mappings":";;;;;;;;;;AA6DA,MAAa,eAAiB,OAAO,IAAI,8BAA8B,EAc1D,cAAgB,OAAO,IAAI,4BAA4B,EAYpE,IAAa,cAAb,KAAwC,CAKtC,MAEA,YAAY,KAAc,SAAiC,CAAC,EAAG,CAC7D,KAAK,MAAQ,CACX,KACA,SAAU,SAAS,UAAY,GAC/B,QAAS,SAAS,SAAW,KAC7B,WAAY,SAAS,YAAc,GACnC,OAAQ,SAAS,QAAU,GAC3B,WAAY,SAAS,YAAc,IACrC,CACF,CAEA,SAA+B,CAE7B,MADA,MAAK,MAAM,SAAW,GACf,IACT,CAEA,YAAkC,CAGhC,MAFA,MAAK,MAAM,WAAa,GACxB,KAAK,MAAM,SAAW,GACf,IACT,CAEA,QAAe,CAEb,MADA,MAAK,MAAM,OAAS,GACb,IACT,CAEA,OAA4B,CAE1B,MADA,MAAK,MAAM,KAAO,GAAG,KAAK,MAAM,KAAK,IAC9B,IACT,CAEA,WACE,OACA,KAAqD,CAAC,EAChD,CAQN,MALA,MAAK,MAAM,WAAa,CACtB,MAAO,OACP,SAAU,KAAK,UAAY,YAC3B,SAAU,KAAK,UAAY,WAC7B,EACO,IACT,CAOA,QAAQ,MAAsC,CAE5C,MADA,MAAK,MAAM,QAAU,MACd,IACT,CAEA,OAAO,KAA8B,CACnC,MAAO,CACL,KACA,KAAM,KAAK,MAAM,KACjB,SAAU,KAAK,MAAM,SACrB,QAAS,KAAK,MAAM,QACpB,WAAY,KAAK,MAAM,UACzB,CACF,CAGA,SAAiC,CAC/B,OAAO,KAAK,KACd,CACF"}
1
+ {"version":3,"file":"types-CnOQetrD.mjs","names":[],"sources":["../src/dsl/columns/types.ts"],"sourcesContent":["import type { ColumnSnapshot, FkAction } from '../../snapshot/types'\n\n/**\n * Runtime + type representation of a column reference (e.g. `users.id`).\n * Carries the parent table name, the column's own name, plus runtime\n * accessors used by FK thunks and constraint builders.\n *\n * Exported so adopters can annotate self-referencing thunks without\n * spelling the shape inline:\n *\n * parentId: uuid().references((): ColumnRef => categories.id)\n *\n * Without the annotation the initializer of a self-referencing const\n * trips TS7022 — TS needs to infer the const while the initializer\n * already references it.\n */\nexport interface ColumnRef {\n __tableName: string\n __name: string\n __builder: ColumnBuilder\n __state: () => ReturnType<ColumnBuilder['__state']>\n}\n\n/**\n * Resolved FK spec — `table` / `column` are pulled by invoking `thunk()`\n * lazily. The thunk pattern lets self-referencing tables work:\n *\n * const categories = table('categories', {\n * id: uuid().primaryKey().defaultRandom(),\n * parentId: uuid().references((): ColumnRef => categories.id),\n * })\n *\n * If we resolved at `.references()` call time, `categories` would TDZ-fail\n * inside its own initializer. Storing the thunk and resolving on read\n * (extract / render / emit) defers until after the const binding lands.\n */\nexport interface FkSpec {\n thunk: () => ColumnRef\n onDelete: FkAction\n onUpdate: FkAction\n}\n\nexport interface ColumnState {\n type: string\n nullable: boolean\n default: string | null\n primaryKey: boolean\n unique: boolean\n references: FkSpec | null\n}\n\n/**\n * Type-only brand attached to a column when it's auto-assigned by the\n * database (serial / bigserial / smallserial), has a runtime default\n * (`.default(...)`), or carries an expression default\n * (`uuid().defaultRandom()`, `timestamp().defaultNow()`). `SchemaToTypes<S>`\n * reads this marker and wraps the column type in Kysely's `Generated<T>` so\n * adopters can omit the column on insert.\n *\n * Runtime is a no-op — the symbol never reaches a value.\n */\nexport const KICK_GENERATED = Symbol.for('@forinda/kickjs-db/Generated')\nexport type GeneratedBrand = { readonly [KICK_GENERATED]?: true }\n\n/**\n * Type-only brand attached to a column when `.notNull()` or `.primaryKey()`\n * is called. `SchemaToTypes<S>` reads this brand to decide whether the\n * column type is `T` (NOT NULL) or `T | null` (default nullable).\n *\n * Why a brand instead of a class generic: chained methods (notNull,\n * primaryKey) can return `this & NotNullBrand` to narrow nullability while\n * preserving the subclass identity — so `uuid().primaryKey().defaultRandom()`\n * still resolves `defaultRandom()` on `UuidBuilder`. A class generic\n * `<TNullable>` would collapse the subclass back to the parent.\n */\nexport const KICK_NOT_NULL = Symbol.for('@forinda/kickjs-db/NotNull')\nexport type NotNullBrand = { readonly [KICK_NOT_NULL]?: true }\n\n/**\n * Phantom-typed column builder. The `T` generic carries the column's TS\n * value type (number / string / Date / etc.); nullability is tracked via\n * the `NotNullBrand` intersection rather than a class generic so chain\n * methods preserve subclass identity.\n *\n * Both `T` and the brand are erased at runtime; they exist purely so\n * `SchemaToTypes<S>` can pull them out per column.\n */\nexport class ColumnBuilder<T = unknown> {\n // Phantom param shows up in the public surface so the type system sees\n // it. Reading it at runtime is intentionally not supported.\n declare readonly __t?: T\n\n protected state: ColumnState\n\n constructor(type: string, defaults: Partial<ColumnState> = {}) {\n this.state = {\n type,\n nullable: defaults.nullable ?? true,\n default: defaults.default ?? null,\n primaryKey: defaults.primaryKey ?? false,\n unique: defaults.unique ?? false,\n references: defaults.references ?? null,\n }\n }\n\n notNull(): this & NotNullBrand {\n this.state.nullable = false\n return this as this & NotNullBrand\n }\n\n primaryKey(): this & NotNullBrand {\n this.state.primaryKey = true\n this.state.nullable = false\n return this as this & NotNullBrand\n }\n\n unique(): this {\n this.state.unique = true\n return this\n }\n\n array(): ColumnBuilder<T[]> {\n this.state.type = `${this.state.type}[]`\n return this as unknown as ColumnBuilder<T[]>\n }\n\n references(\n target: () => ColumnRef,\n opts: { onDelete?: FkAction; onUpdate?: FkAction } = {},\n ): this {\n // Store the thunk — do NOT invoke it here. Self-referencing tables\n // pass `() => self.id` whose binding does not exist yet.\n this.state.references = {\n thunk: target,\n onDelete: opts.onDelete ?? 'no_action',\n onUpdate: opts.onUpdate ?? 'no_action',\n }\n return this\n }\n\n /**\n * Mark the column as having a runtime / DB-assigned default. The\n * `GeneratedBrand` flows into `SchemaToTypes<S>` so the column wraps\n * in `Generated<T>` — adopters can `INSERT` without specifying it.\n */\n default(value: string): this & GeneratedBrand {\n this.state.default = value\n return this as this & GeneratedBrand\n }\n\n toJSON(name: string): ColumnSnapshot {\n return {\n name,\n type: this.state.type,\n nullable: this.state.nullable,\n default: this.state.default,\n primaryKey: this.state.primaryKey,\n }\n }\n\n // Internal accessor for table()/diff to read full state including unique/references.\n __state(): Readonly<ColumnState> {\n return this.state\n }\n}\n"],"mappings":";;;;;;;;;;AA6DA,MAAa,eAAiB,OAAO,IAAI,8BAA8B,EAc1D,cAAgB,OAAO,IAAI,4BAA4B,EAYpE,IAAa,cAAb,KAAwC,CAKtC,MAEA,YAAY,KAAc,SAAiC,CAAC,EAAG,CAC7D,KAAK,MAAQ,CACX,KACA,SAAU,SAAS,UAAY,GAC/B,QAAS,SAAS,SAAW,KAC7B,WAAY,SAAS,YAAc,GACnC,OAAQ,SAAS,QAAU,GAC3B,WAAY,SAAS,YAAc,IACrC,CACF,CAEA,SAA+B,CAE7B,MADA,MAAK,MAAM,SAAW,GACf,IACT,CAEA,YAAkC,CAGhC,MAFA,MAAK,MAAM,WAAa,GACxB,KAAK,MAAM,SAAW,GACf,IACT,CAEA,QAAe,CAEb,MADA,MAAK,MAAM,OAAS,GACb,IACT,CAEA,OAA4B,CAE1B,MADA,MAAK,MAAM,KAAO,GAAG,KAAK,MAAM,KAAK,IAC9B,IACT,CAEA,WACE,OACA,KAAqD,CAAC,EAChD,CAQN,MALA,MAAK,MAAM,WAAa,CACtB,MAAO,OACP,SAAU,KAAK,UAAY,YAC3B,SAAU,KAAK,UAAY,WAC7B,EACO,IACT,CAOA,QAAQ,MAAsC,CAE5C,MADA,MAAK,MAAM,QAAU,MACd,IACT,CAEA,OAAO,KAA8B,CACnC,MAAO,CACL,KACA,KAAM,KAAK,MAAM,KACjB,SAAU,KAAK,MAAM,SACrB,QAAS,KAAK,MAAM,QACpB,WAAY,KAAK,MAAM,UACzB,CACF,CAGA,SAAiC,CAC/B,OAAO,KAAK,KACd,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs-db",
3
- "version": "6.0.0-alpha.0",
3
+ "version": "6.0.0",
4
4
  "description": "KickJS-native ORM — code-first schema, reversible migrations, multi-dialect SQL builder",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -71,8 +71,8 @@
71
71
  "kysely": "^0.29.2",
72
72
  "pg": "^8.21.0",
73
73
  "typescript": "^6.0.3",
74
- "@forinda/kickjs": "5.14.0-alpha.0",
75
- "@forinda/kickjs-devtools-kit": "6.0.0-alpha.0"
74
+ "@forinda/kickjs": "5.14.1",
75
+ "@forinda/kickjs-devtools-kit": "6.0.0"
76
76
  },
77
77
  "publishConfig": {
78
78
  "access": "public"