UNPKG

drizzle-edge-pg-proxy-client

Version:

PostgreSQL HTTP client compatible with Neon's interface for edge environments

2 lines 13.9 kB
'use strict';var neonHttp=require('drizzle-orm/neon-http');var X=Object.defineProperty;var Z=(t,r,s)=>r in t?X(t,r,{enumerable:true,configurable:true,writable:true,value:s}):t[r]=s;var f=(t,r,s)=>Z(t,typeof r!="symbol"?r+"":r,s);var _=(l=>(l[l.Debug=1]="Debug",l[l.Info=2]="Info",l[l.Warn=3]="Warn",l[l.Error=4]="Error",l[l.None=5]="None",l))(_||{});var g=class t extends Error{constructor(s){super(s);f(this,"name","PgError");f(this,"severity");f(this,"code");f(this,"detail");f(this,"hint");f(this,"position");f(this,"internalPosition");f(this,"internalQuery");f(this,"where");f(this,"schema");f(this,"table");f(this,"column");f(this,"dataType");f(this,"constraint");f(this,"file");f(this,"line");f(this,"routine");f(this,"sourceError");"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,t);}},W=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function v(t){let r=new g(t.message||"Unknown PostgreSQL error");for(let s of W)t[s]!==void 0&&(r[s]=t[s]);return t instanceof Error&&(r.sourceError=t),r}var U=(e=>(e[e.BOOL=16]="BOOL",e[e.BYTEA=17]="BYTEA",e[e.CHAR=18]="CHAR",e[e.INT8=20]="INT8",e[e.INT2=21]="INT2",e[e.INT4=23]="INT4",e[e.REGPROC=24]="REGPROC",e[e.TEXT=25]="TEXT",e[e.OID=26]="OID",e[e.TID=27]="TID",e[e.XID=28]="XID",e[e.CID=29]="CID",e[e.JSON=114]="JSON",e[e.XML=142]="XML",e[e.PG_NODE_TREE=194]="PG_NODE_TREE",e[e.JSONB=3802]="JSONB",e[e.FLOAT4=700]="FLOAT4",e[e.FLOAT8=701]="FLOAT8",e[e.ABSTIME=702]="ABSTIME",e[e.RELTIME=703]="RELTIME",e[e.TINTERVAL=704]="TINTERVAL",e[e.CIRCLE=718]="CIRCLE",e[e.MONEY=790]="MONEY",e[e.MACADDR=829]="MACADDR",e[e.INET=869]="INET",e[e.CIDR=650]="CIDR",e[e.MACADDR8=774]="MACADDR8",e[e.ACLITEM=1033]="ACLITEM",e[e.BPCHAR=1042]="BPCHAR",e[e.VARCHAR=1043]="VARCHAR",e[e.DATE=1082]="DATE",e[e.TIME=1083]="TIME",e[e.TIMESTAMP=1114]="TIMESTAMP",e[e.TIMESTAMPTZ=1184]="TIMESTAMPTZ",e[e.INTERVAL=1186]="INTERVAL",e[e.TIMETZ=1266]="TIMETZ",e[e.BIT=1560]="BIT",e[e.VARBIT=1562]="VARBIT",e[e.NUMERIC=1700]="NUMERIC",e[e.REFCURSOR=1790]="REFCURSOR",e[e.REGPROCEDURE=2202]="REGPROCEDURE",e[e.REGOPER=2203]="REGOPER",e[e.REGOPERATOR=2204]="REGOPERATOR",e[e.REGCLASS=2205]="REGCLASS",e[e.REGTYPE=2206]="REGTYPE",e[e.UUID=2950]="UUID",e[e.TXID_SNAPSHOT=2970]="TXID_SNAPSHOT",e[e.PG_LSN=3220]="PG_LSN",e[e.PG_NDISTINCT=3361]="PG_NDISTINCT",e[e.PG_DEPENDENCIES=3402]="PG_DEPENDENCIES",e[e.TSVECTOR=3614]="TSVECTOR",e[e.TSQUERY=3615]="TSQUERY",e[e.GTSVECTOR=3642]="GTSVECTOR",e[e.REGCONFIG=3734]="REGCONFIG",e[e.REGDICTIONARY=3769]="REGDICTIONARY",e[e.JSONPATH=4072]="JSONPATH",e[e.REGNAMESPACE=4089]="REGNAMESPACE",e[e.REGROLE=4096]="REGROLE",e[e.BOOL_ARRAY=1e3]="BOOL_ARRAY",e[e.BYTEA_ARRAY=1001]="BYTEA_ARRAY",e[e.CHAR_ARRAY=1002]="CHAR_ARRAY",e[e.INT8_ARRAY=1016]="INT8_ARRAY",e[e.INT2_ARRAY=1005]="INT2_ARRAY",e[e.INT4_ARRAY=1007]="INT4_ARRAY",e[e.TEXT_ARRAY=1009]="TEXT_ARRAY",e[e.JSON_ARRAY=199]="JSON_ARRAY",e[e.JSONB_ARRAY=3807]="JSONB_ARRAY",e[e.FLOAT4_ARRAY=1021]="FLOAT4_ARRAY",e[e.FLOAT8_ARRAY=1022]="FLOAT8_ARRAY",e[e.NUMERIC_ARRAY=1231]="NUMERIC_ARRAY",e[e.DATE_ARRAY=1182]="DATE_ARRAY",e[e.TIMESTAMP_ARRAY=1115]="TIMESTAMP_ARRAY",e[e.TIMESTAMPTZ_ARRAY=1185]="TIMESTAMPTZ_ARRAY",e[e.UUID_ARRAY=2951]="UUID_ARRAY",e[e.VARCHAR_ARRAY=1015]="VARCHAR_ARRAY",e))(U||{});function G(t){return t>=1e3&&t<=1099||t>=1115&&t<=1185||t===199||t===3807||t===1231||t===2951}function j(t){return {1e3:16,1001:17,1002:18,1005:21,1007:23,1009:25,1016:20,1021:700,1022:701,1231:1700,1015:1043,1182:1082,1115:1114,1185:1184,199:114,3807:3802,2951:2950}[t]||0}var M=class{constructor(r){f(this,"parsers",{});this.initializeDefaultParsers(),r&&Object.keys(r).forEach(s=>{let o=parseInt(s,10);!isNaN(o)&&r[o]&&this.setTypeParser(o,r[o]);});}initializeDefaultParsers(){this.setTypeParser(16,r=>r==="t"||r==="true"),this.setTypeParser(21,r=>parseInt(r,10)),this.setTypeParser(23,r=>parseInt(r,10)),this.setTypeParser(20,r=>BigInt(r)),this.setTypeParser(26,r=>parseInt(r,10)),this.setTypeParser(700,r=>parseFloat(r)),this.setTypeParser(701,r=>parseFloat(r)),this.setTypeParser(1700,r=>parseFloat(r)),this.setTypeParser(114,r=>JSON.parse(r)),this.setTypeParser(3802,r=>JSON.parse(r)),this.setTypeParser(1082,r=>new Date(r)),this.setTypeParser(1114,r=>new Date(r)),this.setTypeParser(1184,r=>new Date(r)),this.setTypeParser(2950,r=>r),this.setupArrayTypeParsers();}setupArrayTypeParsers(){this.setTypeParser(1e3,r=>E(r,this.getTypeParser(16))),this.setTypeParser(1005,r=>E(r,this.getTypeParser(21))),this.setTypeParser(1007,r=>E(r,this.getTypeParser(23))),this.setTypeParser(1016,r=>E(r,this.getTypeParser(20))),this.setTypeParser(1021,r=>E(r,this.getTypeParser(700))),this.setTypeParser(1022,r=>E(r,this.getTypeParser(701))),this.setTypeParser(1231,r=>E(r,this.getTypeParser(1700))),this.setTypeParser(1009,r=>E(r,this.getTypeParser(25))),this.setTypeParser(1015,r=>E(r,this.getTypeParser(1043))),this.setTypeParser(199,r=>E(r,this.getTypeParser(114))),this.setTypeParser(3807,r=>E(r,this.getTypeParser(3802))),this.setTypeParser(1182,r=>E(r,this.getTypeParser(1082))),this.setTypeParser(1115,r=>E(r,this.getTypeParser(1114))),this.setTypeParser(1185,r=>E(r,this.getTypeParser(1184))),this.setTypeParser(2951,r=>E(r,this.getTypeParser(2950)));}setTypeParser(r,s){this.parsers[r]=s;}getTypeParser(r){if(G(r)&&!this.parsers[r]){let s=j(r);if(s){let o=this.getTypeParser(s);return m=>E(m,o)}}return this.parsers[r]||(s=>s)}};function E(t,r){if(!t||t==="{}")return [];if(t[0]!=="{"||t[t.length-1]!=="}")throw new Error(`Invalid PostgreSQL array format: ${t}`);let s=t.substring(1,t.length-1);if(!s)return [];let o=[],m=false,l=false,u="",d=0;for(let T=0;T<s.length;T++){let a=s[T];if(l){u+=a,l=false;continue}if(a==="\\"){l=true;continue}if(a==='"'){m=!m;continue}if(a==="{"){d++,u+=a;continue}if(a==="}"){d--,u+=a;continue}if(m||d>0){u+=a;continue}if(a===","){o.push($(u,r)),u="";continue}u+=a;}return u&&o.push($(u,r)),o}function $(t,r){return t=t.trim(),t==="NULL"||t===""?null:t[0]==="{"&&t[t.length-1]==="}"?E(t,r):r(t)}function B(t,r,s){if(!t)return null;let o=t.fields||[],m=t.rows||[],l=o.map(T=>{let a=T.dataTypeID;if(G(a)){let i=j(a),b=r.getTypeParser(i);return C=>E(C,b)}return r.getTypeParser(a)}),u=o.map(T=>T.name),d=[];return Array.isArray(m)&&(d=s?m.map(T=>Array.isArray(T)?T.map((a,i)=>a===null?null:l[i](a)):T):m.map(T=>{if(!Array.isArray(T))return T;let a={};return T.forEach((i,b)=>{b<u.length&&(a[u[b]]=i===null?null:l[b](i));}),a})),{...t,rows:d,rowAsArray:s,_parsers:l,_types:r}}var J,N=class{constructor(r,s,o){this.executeFn=r;f(this,J,"Promise");f(this,"queryData");f(this,"opts");this.queryData=s,this.opts=o;}then(r,s){return this.executeFn(this.queryData.query,this.queryData.params).then(r,s)}catch(r){return this.executeFn(this.queryData.query,this.queryData.params).catch(r)}finally(r){return this.executeFn(this.queryData.query,this.queryData.params).finally(r)}[(J=Symbol.toStringTag,Symbol.iterator)](){let r=this,s=false,o;return {next(){return s?{done:true,value:void 0}:o===void 0?r.then(m=>(o=m,{done:false,value:m})):(s=true,{done:true,value:void 0})}}}};var q=class{constructor(r){this.sql=r;}};function Y(t){return typeof Buffer<"u"&&(t instanceof Buffer||ArrayBuffer.isView(t))?"\\x"+Buffer.from(t).toString("hex"):t}function k(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let r=Math.random()*16|0;return (t==="x"?r:r&3|8).toString(16)})}function H(t,r){let s="",o=[];for(let m=0,l=t.length;m<l;m++)if(s+=t[m],m<r.length){let u=r[m];if(u instanceof q)s+=u.sql;else if(u instanceof N)if(u.queryData){if(u.queryData.params&&u.queryData.params.length>0)throw new Error("Cannot compose a query promise that has parameters.");s+=u.queryData.query;}else throw new Error("Invalid QueryPromise encountered during composition.");else o.push(u),s+=`$${o.length}`,typeof Buffer<"u"&&(u instanceof Buffer||ArrayBuffer.isView(u))&&(s+="::bytea");}return {query:s,params:o}}function z({proxyUrl:t,authToken:r,fetch:s,arrayMode:o=false,fullResults:m=false,typeParser:l,sessionId:u,logger:d}){let T=d?.level??3,a=d?.logFn,i=(p,A,O)=>{if(p>=T&&T!==5)if(a)a(p,A,O);else {let h=O?{data:O}:{},n=`[PG-HTTP-CLIENT][${_[p]}] ${A}`;switch(p){case 1:case 2:console.log(n,h);break;case 3:console.warn(n,h);break;case 4:console.error(n,h);break}}},b=s||globalThis.fetch,C=t.endsWith("/")?t.slice(0,-1):t,Q=l instanceof M?l:new M(l),y=u||k();if(!b)throw new g("fetch is not available in the current environment. Please provide a fetch implementation.");let I=async(p,A=[])=>{i(1,"Executing query",{query:p,paramsCount:A.length,sessionId:y});let O=Date.now(),h={method:"POST",headers:{"Content-Type":"application/json","Neon-Raw-Text-Output":"true","Neon-Array-Mode":String(o),"X-Session-ID":y,...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({query:p,params:Array.isArray(A)?A.map(n=>Y(n)):[]})};try{let n=await b(`${C}/query`,h);if(!n.ok){let S={error:n.statusText};try{S=await n.json();}catch{S={error:`Status ${n.status}: ${n.statusText}`};}let P=v(S);throw i(4,`Query failed with status ${n.status}`,{error:P,query:p,sessionId:y}),P}let D=await n.json(),R=Date.now()-O;return i(2,"Query executed successfully",{durationMs:R,query:p,sessionId:y}),B(D,Q,o)}catch(n){if(n instanceof g)throw n;let D=new g(`Failed to execute query: ${n instanceof Error?n.message:String(n)}`);throw D.sourceError=n instanceof Error?n:void 0,i(4,"Query execution failed",{error:D,query:p,sessionId:y}),D}};return {execute:I,query:async(p,A,O)=>{i(1,"Executing direct query",{query:p,paramsCount:A?.length,options:O,sessionId:y});let h=Date.now(),n=O?.arrayMode??o,D={method:"POST",headers:{"Content-Type":"application/json","Neon-Raw-Text-Output":"true","Neon-Array-Mode":String(n),"X-Session-ID":y,...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({query:p,params:Array.isArray(A)?A.map(R=>Y(R)):[]})};try{let R=await b(`${C}/query`,D);if(!R.ok){let P={error:R.statusText};try{P=await R.json();}catch{P={error:`Status ${R.status}: ${R.statusText}`};}let L=v(P);throw i(4,`Direct query failed with status ${R.status}`,{error:L,query:p,sessionId:y}),L}let x=await R.json(),S=Date.now()-h;return i(2,"Direct query executed successfully",{durationMs:S,query:p,sessionId:y}),B(x,Q,n)}catch(R){if(R instanceof g)throw R;let x=new g(`Direct query failed: ${R instanceof Error?R.message:String(R)}`);throw x.sourceError=R instanceof Error?R:void 0,i(4,"Direct query execution failed",{error:x,query:p,sessionId:y}),x}},sql:(p,...A)=>{let O=H(p,A);return new N((h,n)=>I(h,n),O,{arrayMode:o,fullResults:m})},unsafe:p=>new q(p),transaction:async(p,A)=>{i(1,"Executing transaction",{queryCount:p.length,options:A,sessionId:y});let O=Date.now();try{if(!Array.isArray(p)){let c=new g("Input to transaction must be an array of queries.");throw i(4,"Transaction failed: Invalid input",{error:c,sessionId:y}),c}let h=p.map(c=>{let w,F;if(c instanceof N){if(!c.queryData)throw new g("Invalid QueryPromise passed to transaction.");w=c.queryData.query,F=c.queryData.params;}else if(typeof c=="object"&&c!==null&&typeof c.text=="string")w=c.text,F=Array.isArray(c.values)?c.values:[];else throw new g("Invalid query type passed to transaction. Use sql`` or { text: string, values: any[] }.");return {query:w,params:F.map(V=>Y(V))}}),n=A?.arrayMode??o,D=A?.fullResults??m,R={"Content-Type":"application/json","Neon-Raw-Text-Output":"true","Neon-Array-Mode":String(n),"X-Session-ID":y,...r?{Authorization:`Bearer ${r}`}:{}};A?.isolationLevel&&(R["Neon-Batch-Isolation-Level"]=A.isolationLevel),A?.readOnly!==void 0&&(R["Neon-Batch-Read-Only"]=String(A.readOnly)),A?.deferrable!==void 0&&(R["Neon-Batch-Deferrable"]=String(A.deferrable));let x=await b(`${C}/transaction`,{method:"POST",headers:R,body:JSON.stringify({queries:h})});if(!x.ok){let c={};try{c=await x.json();}catch{c={error:`Status ${x.status}: ${x.statusText}`};}let w=v(c);throw i(4,`Transaction failed with status ${x.status}`,{error:w,queryCount:h.length,sessionId:y}),w}let S=[];try{let c=await x.json();S=c.results||(Array.isArray(c)?c:[]);}catch(c){let w=new g(`Error parsing transaction response: ${c.message}`);throw i(4,"Transaction failed: Response parse error",{error:w,sessionId:y}),w}let P=Array.isArray(S)?S.map(c=>{let w=B(c,Q,n);return D?w:w.rows}):[],L=Date.now()-O;return i(2,"Transaction executed successfully",{durationMs:L,queryCount:h.length,sessionId:y}),P}catch(h){if(h instanceof g)throw h;let n=new g(`Failed to execute transaction: ${h instanceof Error?h.message:String(h)}`);throw n.sourceError=h instanceof Error?h:void 0,i(4,"Transaction execution failed",{error:n,sessionId:y}),n}},typeParser:Q}}function ee(t){let{proxyUrl:r,authToken:s,schema:o,fetch:m,arrayMode:l=false,fullResults:u=false,typeParser:d,logger:T}=t,a=z({proxyUrl:r,authToken:s,fetch:m,arrayMode:l,fullResults:u,typeParser:d,logger:T}),i=neonHttp.drizzle(a,{schema:o});return Object.defineProperty(i,"query",{enumerable:true,configurable:true,writable:true,value:async function(b,C,Q){try{let y=await a.query(b,C||[],Q);return !y||!y.rows?{command:"SELECT",rowCount:0,fields:[],rows:[],rowAsArray:!1}:y}catch(y){throw console.error("Error in query method:",y),y}}}),Object.defineProperty(i,"sql",{enumerable:true,configurable:true,writable:true,value:a.sql}),Object.defineProperty(i,"transaction",{enumerable:true,configurable:true,writable:true,value:a.transaction.bind(a)}),Object.defineProperty(i,"client",{enumerable:true,configurable:true,writable:false,value:a}),Object.defineProperty(i,"typeParser",{enumerable:true,configurable:true,writable:false,value:a.typeParser}),i}exports.LogLevel=_;exports.PgError=g;exports.PgTypeId=U;exports.TypeParser=M;exports.UnsafeRawSql=q;exports.createPgHttpClient=z;exports.drizzle=ee;//# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map