UNPKG

@a2lix/schemql

Version:

A lightweight TypeScript library that enhances your SQL workflow by combining raw SQL with targeted type safety and schema validation

1 lines 1.96 kB
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./baseAdapterError.cjs");var t=class{constructor(e,t={verbosity:0}){this.db=e,this.options=t,this.queryAll=e=>{let{sql:t,paramsOrder:r}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let n=e?r.map(t=>e[t]):[],{results:a}=await i.bind(...n).all();return this.options.verbosity&&this.logSql(t,n,this.options.verbosity),a}catch(e){throw n.createFromD1(e)}}},this.queryFirst=e=>{let{sql:t,paramsOrder:r}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let n=e?r.map(t=>e[t]):[],a=await i.bind(...n).first()??void 0;return this.options.verbosity&&this.logSql(t,n,this.options.verbosity),a}catch(e){throw n.createFromD1(e)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return async e=>{let r=await t(e);if(r===void 0)throw new n(`No result`,`NO_RESULT`);return r}},this.queryIterate=e=>e=>{throw Error(`Not implemented`)},this.transformToAnonymousParams=e=>{let t=[];return{sql:e.replace(/:([a-zA-Z0-9_]+)/g,(e,n)=>(t.push(n),`?`)),paramsOrder:t}},this.logSql=(e,t,n)=>{let r=t.map(e=>typeof e==`string`?`'${e}'`:e===null?`NULL`:e),i=0,a=e.replace(/\?/g,()=>r[i++]??`?`);console.log(`${n>1?`\n-- PREPARED --\n${e}`:``}\n++ EXECUTED ++\n${a}\n`)}}},n=class t extends e.BaseAdapterError{static{this.createFromD1=e=>new t(e.message,(e=>{if(e.startsWith(`D1_ERROR:`)){if(e.startsWith(`D1_ERROR: UNIQUE constraint failed`))return`UNIQUE_CONSTRAINT`;if(e.startsWith(`D1_ERROR: FOREIGN KEY constraint failed`))return`FOREIGNKEY_CONSTRAINT`;if(e.startsWith(`D1_ERROR: NOT NULL constraint failed`))return`NOTNULL_CONSTRAINT`;if(e.startsWith(`D1_ERROR: CHECK constraint failed`))return`CHECK_CONSTRAINT`;if(e.startsWith(`D1_ERROR: PRIMARY KEY constraint failed`))return`PRIMARYKEY_CONSTRAINT`}return`GENERIC`})(e.message),e)}};exports.D1Adapter=t,exports.SchemQlAdapterError=n,exports.SchemQlAdapterErrorCode=e.AdapterErrorCode;