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