UNPKG

@a2lix/schemql

Version:

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

7 lines (6 loc) 2.1 kB
var f=Object.defineProperty;var m=(u,h)=>f(u,"name",{value:h,configurable:!0});var c;import{BaseAdapterError as q,AdapterErrorCode as l}from"./baseAdapterError.mjs";const E=class E{constructor(h,e={verbosity:0}){this.db=h,this.options=e,this.queryAll=r=>{const{sql:t,paramsOrder:i}=this.transformToAnonymousParams(r),o=this.db.prepare(t);return async n=>{try{const s=n?i.map(y=>n[y]):[],{results:a}=await o.bind(...s).all();return this.options.verbosity&&this.logSql(t,s,this.options.verbosity),a}catch(s){throw p.createFromD1(s)}}},this.queryFirst=r=>{const{sql:t,paramsOrder:i}=this.transformToAnonymousParams(r),o=this.db.prepare(t);return async n=>{try{const s=n?i.map(y=>n[y]):[],a=await o.bind(...s).first()??void 0;return this.options.verbosity&&this.logSql(t,s,this.options.verbosity),a}catch(s){throw p.createFromD1(s)}}},this.queryFirstOrThrow=r=>{const t=this.queryFirst(r);return async i=>{const o=await t(i);if(o===void 0)throw new p("No result",l.NoResult);return o}},this.queryIterate=r=>t=>{throw new Error("Not implemented")},this.transformToAnonymousParams=r=>{const t=[];return{sql:r.replace(/:([a-zA-Z0-9_]+)/g,(o,n)=>(t.push(n),"?")),paramsOrder:t}},this.logSql=(r,t,i)=>{const o=t.map(a=>typeof a=="string"?`'${a}'`:a===null?"NULL":a);let n=0;const s=r.replace(/\?/g,()=>o[n++]??"?");console.log(`${i>1?` -- PREPARED -- ${r}`:""} ++ EXECUTED ++ ${s} `)}}};m(E,"D1Adapter");let d=E;const R=(c=class extends q{},m(c,"_SchemQlAdapterError"),c);R.createFromD1=u=>{const h=m(e=>{if(e.startsWith("D1_ERROR:")){if(e.startsWith("D1_ERROR: UNIQUE constraint failed"))return l.UniqueConstraint;if(e.startsWith("D1_ERROR: FOREIGN KEY constraint failed"))return l.ForeignkeyConstraint;if(e.startsWith("D1_ERROR: NOT NULL constraint failed"))return l.NotnullConstraint;if(e.startsWith("D1_ERROR: CHECK constraint failed"))return l.CheckConstraint;if(e.startsWith("D1_ERROR: PRIMARY KEY constraint failed"))return l.PrimarykeyConstraint}return l.Generic},"computeCode");return new R(u.message,h(u.message),u)};let p=R;export{d as D1Adapter,p as SchemQlAdapterError,l as SchemQlAdapterErrorCode};