@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.89 kB
JavaScript
import{AdapterErrorCode as e,BaseAdapterError as t}from"./baseAdapterError.mjs";var n=class{constructor(e,t={verbosity:0}){this.db=e,this.options=t,this.queryAll=e=>{let{sql:t,paramsOrder:n}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let r=e?n.map(t=>e[t]):[],{results:a}=await i.bind(...r).all();return this.options.verbosity&&this.logSql(t,r,this.options.verbosity),a}catch(e){throw r.createFromD1(e)}}},this.queryFirst=e=>{let{sql:t,paramsOrder:n}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let r=e?n.map(t=>e[t]):[],a=await i.bind(...r).first()??void 0;return this.options.verbosity&&this.logSql(t,r,this.options.verbosity),a}catch(e){throw r.createFromD1(e)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return async e=>{let n=await t(e);if(n===void 0)throw new r(`No result`,`NO_RESULT`);return n}},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`)}}},r=class e extends t{static{this.createFromD1=t=>new e(t.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`})(t.message),t)}};export{n as D1Adapter,r as SchemQlAdapterError,e as SchemQlAdapterErrorCode};