@dotaz/server 0.0.12 → 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/dotaz.js +43 -43
- package/dist/assets/{index-DASn2UQ6.js → index-DyYBJ2ae.js} +29 -29
- package/dist/index.html +1 -1
- package/package.json +1 -1
package/bin/dotaz.js
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var M=($,Z)=>()=>($&&(Z=$($=0)),Z);var
|
|
3
|
+
var M=($,Z)=>()=>($&&(Z=$($=0)),Z);var z5=import.meta.require;function h($){let Z=new Set,Q=[];for(let B of $)for(let X of Object.keys(B))if(!Z.has(X))Z.add(X),Q.push(X);return Q}function A5($){if($===null||$===void 0)return"";if(typeof $==="object")return JSON.stringify($);return String($)}function j$($){if($===null||$===void 0)return"NULL";if(typeof $==="number")return String($);if(typeof $==="boolean")return $?"TRUE":"FALSE";if(typeof $==="string")return`'${$.replace(/'/g,"''")}'`;if(typeof $==="object")return`'${JSON.stringify($).replace(/'/g,"''")}'`;return String($)}function R5($){if($===null||$===void 0)return"NULL";if(typeof $==="object")return JSON.stringify($);return String($)}function e$($){return $.replace(/\|/g,"\\|").replace(/\n/g," ")}function U$($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function $0($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function O5($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");if(!/^[a-zA-Z_]/.test(Z))Z="_"+Z;return Z}function L5($,Z){return`"${$.replace(/"/g,'""')}"."${Z.replace(/"/g,'""')}"`}function Z0($){let Z=$.qualifiedTableName??L5($.schema,$.table);switch($.format){case"csv":return new Q0($.delimiter??",",$.includeHeaders??!0);case"json":return new B0;case"sql":return new X0(Z,$.batchSize??100);case"markdown":return new W0;case"sql_update":return new Y0(Z);case"html":return new G0;case"xml":return new H0}}class Q0{delimiter;includeHeaders;columns=null;constructor($,Z){this.delimiter=$;this.includeHeaders=Z}preamble(){return""}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=h($);let Q=this.columns,B=[];if(Z&&this.includeHeaders)B.push(Q.map((X)=>this.escapeField(X)).join(this.delimiter));for(let X of $){let W=Q.map((Y)=>this.escapeField(A5(X[Y])));B.push(W.join(this.delimiter))}return B.join(`
|
|
4
4
|
`)+`
|
|
5
5
|
`}epilogue(){return""}escapeField($){if($.includes(this.delimiter)||$.includes('"')||$.includes(`
|
|
6
|
-
`)||$.includes("\r"))return`"${$.replace(/"/g,'""')}"`;return $}}class
|
|
7
|
-
`}formatBatch($){if($.length===0)return"";return $.map((Q)=>{let
|
|
8
|
-
`:"";return this.hasWritten=!0,
|
|
6
|
+
`)||$.includes("\r"))return`"${$.replace(/"/g,'""')}"`;return $}}class B0{hasWritten=!1;preamble(){return`[
|
|
7
|
+
`}formatBatch($){if($.length===0)return"";return $.map((Q)=>{let B=this.hasWritten?`,
|
|
8
|
+
`:"";return this.hasWritten=!0,B+" "+JSON.stringify(Q)}).join("")}epilogue(){return`
|
|
9
9
|
]
|
|
10
|
-
`}}class
|
|
10
|
+
`}}class X0{tableName;batchSize;columns=null;constructor($,Z){this.tableName=$;this.batchSize=Z}preamble(){return""}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=h($);let Z=this.columns,B=Z.map((W)=>`"${W.replace(/"/g,'""')}"`).join(", "),X=[];for(let W=0;W<$.length;W+=this.batchSize){let G=$.slice(W,W+this.batchSize).map((H)=>{return`(${Z.map((U)=>j$(H[U])).join(", ")})`});X.push(`INSERT INTO ${this.tableName} (${B}) VALUES
|
|
11
11
|
${G.join(`,
|
|
12
12
|
`)};
|
|
13
|
-
`)}return
|
|
14
|
-
`)}epilogue(){return""}}class
|
|
13
|
+
`)}return X.join(`
|
|
14
|
+
`)}epilogue(){return""}}class W0{columns=null;preamble(){return""}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=h($);let Q=this.columns,B=[];if(Z)B.push("| "+Q.map(e$).join(" | ")+" |"),B.push("| "+Q.map(()=>"---").join(" | ")+" |");for(let X of $){let W=Q.map((Y)=>e$(R5(X[Y])));B.push("| "+W.join(" | ")+" |")}return B.join(`
|
|
15
15
|
`)+`
|
|
16
|
-
`}epilogue(){return""}}class
|
|
17
|
-
`)}return
|
|
18
|
-
`}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=h($);let Q=this.columns,
|
|
16
|
+
`}epilogue(){return""}}class Y0{tableName;columns=null;constructor($){this.tableName=$}preamble(){return""}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=h($);let Z=this.columns,Q=Z[0],B=Z.slice(1),X=[];for(let W of $){if(B.length===0)continue;let Y=B.map((H)=>`"${H.replace(/"/g,'""')}" = ${j$(W[H])}`).join(", "),G=`"${Q.replace(/"/g,'""')}" = ${j$(W[Q])}`;X.push(`UPDATE ${this.tableName} SET ${Y} WHERE ${G};
|
|
17
|
+
`)}return X.join("")}epilogue(){return""}}class G0{columns=null;preamble(){return`<table>
|
|
18
|
+
`}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=h($);let Q=this.columns,B=[];if(Z){B.push(" <thead>"),B.push(" <tr>");for(let X of Q)B.push(` <th>${U$(X)}</th>`);B.push(" </tr>"),B.push(" </thead>"),B.push(" <tbody>")}for(let X of $){B.push(" <tr>");for(let W of Q){let Y=X[W],G=Y===null||Y===void 0?"":typeof Y==="object"?U$(JSON.stringify(Y)):U$(String(Y));B.push(` <td>${G}</td>`)}B.push(" </tr>")}return B.join(`
|
|
19
19
|
`)+`
|
|
20
20
|
`}epilogue(){return` </tbody>
|
|
21
21
|
</table>
|
|
22
|
-
`}}class
|
|
22
|
+
`}}class H0{columns=null;preamble(){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
23
23
|
<rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
|
24
|
-
`}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=h($);let Z=this.columns,Q=[];for(let
|
|
24
|
+
`}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=h($);let Z=this.columns,Q=[];for(let B of $){Q.push(" <row>");for(let X of Z){let W=B[X],Y=O5(X);if(W===null||W===void 0)Q.push(` <${Y} xsi:nil="true"/>`);else{let G=typeof W==="object"?$0(JSON.stringify(W)):$0(String(W));Q.push(` <${Y}>${G}</${Y}>`)}}Q.push(" </row>")}return Q.join(`
|
|
25
25
|
`)+`
|
|
26
26
|
`}epilogue(){return`</rows>
|
|
27
|
-
`}}var
|
|
28
|
-
`)
|
|
27
|
+
`}}var S7;var g=M(()=>{S7=Object.freeze({__dotaz_sentinel:"DEFAULT"})});function V0($){return $.includes(".")}function U0($){let Z=$.indexOf(".");return{table:$.substring(0,Z),column:$.substring(Z+1)}}function j0($,Z){return(Q)=>{if(V0(Q)){let{table:B,column:X}=U0(Q),W=$.find((Y)=>Y.referencedTable===B);if(W)return`${Z.quoteIdentifier(W.alias)}.${Z.quoteIdentifier(X)}`}return`t0.${Z.quoteIdentifier(Q)}`}}function J$($,Z,Q=0,B){if(!$||$.length===0)return{sql:"",params:[]};let X=[],W=[],Y=Q;for(let G of $){let H=B?B(G.column):Z.quoteIdentifier(G.column);switch(G.operator){case"eq":Y++,X.push(`${H} = ${Z.placeholder(Y)}`),W.push(G.value);break;case"neq":Y++,X.push(`${H} != ${Z.placeholder(Y)}`),W.push(G.value);break;case"gt":Y++,X.push(`${H} > ${Z.placeholder(Y)}`),W.push(G.value);break;case"gte":Y++,X.push(`${H} >= ${Z.placeholder(Y)}`),W.push(G.value);break;case"lt":Y++,X.push(`${H} < ${Z.placeholder(Y)}`),W.push(G.value);break;case"lte":Y++,X.push(`${H} <= ${Z.placeholder(Y)}`),W.push(G.value);break;case"like":Y++,X.push(`${H} LIKE ${Z.placeholder(Y)}`),W.push(G.value);break;case"notLike":Y++,X.push(`${H} NOT LIKE ${Z.placeholder(Y)}`),W.push(G.value);break;case"in":{let V=Array.isArray(G.value)?G.value:[G.value],U=V.map(()=>{return Y++,Z.placeholder(Y)});X.push(`${H} IN (${U.join(", ")})`),W.push(...V);break}case"notIn":{let V=Array.isArray(G.value)?G.value:[G.value],U=V.map(()=>{return Y++,Z.placeholder(Y)});X.push(`${H} NOT IN (${U.join(", ")})`),W.push(...V);break}case"isNull":X.push(`${H} IS NULL`);break;case"isNotNull":X.push(`${H} IS NOT NULL`);break}}if(X.length===0)return{sql:"",params:[]};return{sql:`WHERE ${X.join(" AND ")}`,params:W}}function K$($,Z,Q){if(!$||$.length===0)return"";return`ORDER BY ${$.map((X)=>{let W=Q?Q(X.column):Z.quoteIdentifier(X.column),Y=X.direction==="desc"?"DESC":"ASC";return`${W} ${Y}`}).join(", ")}`}function J0($,Z){return $.map((Q)=>{let B=Z.qualifyTable(Q.referencedSchema,Q.referencedTable),X=Z.quoteIdentifier(Q.alias),W;if(V0(Q.fkColumn)){let{table:G,column:H}=U0(Q.fkColumn),V=$.find((U)=>U.referencedTable===G);if(V)W=`${Z.quoteIdentifier(V.alias)}.${Z.quoteIdentifier(H)}`;else W=`t0.${Z.quoteIdentifier(Q.fkColumn)}`}else W=`t0.${Z.quoteIdentifier(Q.fkColumn)}`;let Y=`${X}.${Z.quoteIdentifier(Q.referencedColumn)}`;return`LEFT JOIN ${B} AS ${X} ON ${W} = ${Y}`}).join(" ")}var z$=M(()=>{g()});async function A$($,Z,Q,B,X){let W=N5(Z.format==="csv"?Z.encoding:void 0),Y=A0(Z,$),G=0;if(Z.format==="csv"&&Z.utf8Bom&&(Z.encoding??"utf-8")==="utf-8")await Q.write(new Uint8Array([239,187,191]));let H=Y.preamble();if(H)await Q.write(W(H));let{sql:V,params:U}=r(Z,$),j=Z.batchSize??_5,J=$.iterate(V,U,j,B),A=!0;for await(let R of J){let z=R;if(Z.limit!==void 0){let L=Z.limit-G;if(L<=0)break;if(z.length>L)z=z.slice(0,L)}let O=Y.formatBatch(z,A);if(await Q.write(W(O)),G+=z.length,X?.(G),A=!1,Z.limit!==void 0&&G>=Z.limit)break}let K=Y.epilogue();if(K)await Q.write(W(K));return await Q.end(),{rowCount:G}}async function K0($,Z,Q,B,X){let Y=Bun.file(Q).writer(),G={write(H){Y.write(H)},async end(){await Y.end()}};try{let H=await A$($,Z,G,B,X),V=await Bun.file(Q).stat();return{rowCount:H.rowCount,sizeBytes:V?.size??0}}catch(H){await Y.end();try{let{unlink:V}=await import("fs/promises");await V(Q)}catch{}throw H}}async function z0($,Z){let Q=Z.limit??10,{sql:B,params:X}=r(Z,$),W=X.length;W++;let Y=$.placeholder(W),G=`${B} LIMIT ${Y}`,V=(await $.execute(G,[...X,Q])).rows,U=A0(Z,$),j=[],J=U.preamble();if(J)j.push(J);j.push(U.formatBatch(V,!0));let A=U.epilogue();if(A)j.push(A);return j.join("")}function r($,Z){let Q=$.autoJoins,B=Q&&Q.length>0,X=Z.qualifyTable($.schema,$.table),W=B?j0(Q,Z):void 0,Y=J$($.filters,Z,0,W),G=K$($.sort,Z,W);if(B){let U=J0(Q,Z),j="t0.*";if($.columns&&$.columns.length>0)j=$.columns.map((A)=>{if(A.includes("."))return`${W(A)} AS ${Z.quoteIdentifier(A)}`;return`t0.${Z.quoteIdentifier(A)}`}).join(", ");let J=[`SELECT ${j} FROM ${X} AS t0 ${U}`];if(Y.sql)J.push(Y.sql);if(G)J.push(G);return{sql:J.join(" "),params:[...Y.params]}}let V=[`SELECT ${$.columns&&$.columns.length>0?$.columns.map((U)=>Z.quoteIdentifier(U)).join(", "):"*"} FROM ${X}`];if(Y.sql)V.push(Y.sql);if(G)V.push(G);return{sql:V.join(" "),params:[...Y.params]}}function A0($,Z){return Z0({format:$.format,schema:$.schema,table:$.table,delimiter:$.delimiter,includeHeaders:$.includeHeaders,batchSize:$.batchSize,qualifiedTableName:Z.qualifyTable($.schema,$.table)})}function x5($){let Z=new Uint8Array($.length);for(let Q=0;Q<$.length;Q++){let B=$.charCodeAt(Q);Z[Q]=B<=255?B:63}return Z}function F5($){let Z=new Uint8Array($.length);for(let Q=0;Q<$.length;Q++){let B=$.charCodeAt(Q);if(B<=255)Z[Q]=B;else Z[Q]=M5[B]??63}return Z}function N5($){switch($){case"iso-8859-1":return x5;case"windows-1252":return F5;default:return(Z)=>Z}}var _5=1000,M5;var R$=M(()=>{z$();M5={8364:128,8218:130,402:131,8222:132,8230:133,8224:134,8225:135,710:136,8240:137,352:138,8249:139,338:140,381:142,8216:145,8217:146,8220:147,8221:148,8226:149,8211:150,8212:151,732:152,8482:153,353:154,8250:155,339:156,382:158,376:159}});async function*O$($,Z){let{delimiter:Q,hasHeader:B,batchSize:X,maxRows:W,maxBufferSize:Y=67108864}=Z,G=new TextDecoder("utf-8"),H=$.getReader(),V="",U=0,j=!1,J="",A=[],K=1,R=null,z=0,O=[],L=!1;function F(x){if(x.length===1&&x[0]==="")return 0;if(R===null){if(B)return R=x,0;R=x.map((N,P)=>`col${P+1}`)}if(O.push(P5(x,R)),z++,W!==void 0&&z>=W)return 2;if(O.length>=X)return 1;return 0}try{while(!L){let x=await H.read();if(x.done)V+=G.decode(new Uint8Array(0),{stream:!1}),L=!0;else V+=G.decode(x.value,{stream:!0});if(V.length>Y)throw new a(`buffer size exceeded ${Y/1048576}MB \u2014 possible malformed input or extremely large field`,K);while(U<V.length){let N=V[U];if(j)if(N==='"')if(U+1<V.length)if(V[U+1]==='"')J+='"',U+=2;else j=!1,U++;else if(L)j=!1,U++;else break;else{if(N===`
|
|
28
|
+
`)K++;else if(N==="\r"){if(K++,U+1<V.length){if(V[U+1]===`
|
|
29
29
|
`){J+=`\r
|
|
30
|
-
`,U+=2;continue}}else if(!
|
|
30
|
+
`,U+=2;continue}}else if(!L)break}J+=N,U++}else if(N==='"')j=!0,U++;else if(N===Q)A.push(J),J="",U++;else if(N==="\r"||N===`
|
|
31
31
|
`){if(N==="\r")if(U+1<V.length){if(U++,V[U]===`
|
|
32
|
-
`)U++}else if(
|
|
33
|
-
`,
|
|
34
|
-
`)Q++,
|
|
35
|
-
`);return{nodes:P,rawText:d,durationMs:N}}let J=Q?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",A=U!==void 0?await Y.execute(`${J} ${Z}`,void 0,U):await Y.execute(`${J} ${Z}`),
|
|
36
|
-
`)}catch{F=JSON.stringify(
|
|
32
|
+
`)U++}else if(L)U++;else break;else U++;A.push(J),J="",K++;let P=F(A);switch(A=[],P){case 2:if(O.length>0)yield{columns:R,rows:O},O=[];return;case 1:yield{columns:R,rows:O},O=[];break}}else J+=N,U++}if(U>0)V=V.slice(U),U=0}if(j)throw new a("Unclosed quote",K);if(J!==""||A.length>0)A.push(J),F(A);if(O.length>0)yield{columns:R??[],rows:O}}finally{H.releaseLock()}}function P5($,Z){let Q={};for(let B=0;B<Z.length;B++){let X=B<$.length?$[B]:null;Q[Z[B]]=X===""?null:k5(X)}return Q}function k5($){if($===null||$==="")return null;let Z=$.toLowerCase();if(Z==="true")return!0;if(Z==="false")return!1;if(/^-?\d+$/.test($)){let Q=parseInt($,10);if(Number.isSafeInteger(Q))return Q}if(/^-?\d+\.\d+$/.test($)){let Q=parseFloat($);if(Number.isFinite(Q))return Q}return $}var a;var R0=M(()=>{a=class a extends Error{lineNumber;constructor($,Z){super(`CSV parse error at line ${Z}: ${$}`);this.name="CsvParseError",this.lineNumber=Z}}});async function s($,Z,Q,B,X){let W=Q.mappings.filter((j)=>j.tableColumn!==null);if(W.length===0)throw Error("No columns mapped for import");if(Q.format==="json")return C5($,Z,Q,W,B,X);let Y=$.qualifyTable(Q.schema,Q.table),G=W.map((j)=>j.tableColumn),H=Q.batchSize??O0,V={delimiter:Q.delimiter??",",hasHeader:Q.hasHeader??!0,batchSize:H},U=`__import_${crypto.randomUUID()}`;await $.reserveSession(U);try{await $.beginTransaction(U);let j=0;for await(let{rows:J}of O$(Z,V)){if(B?.aborted)throw Error("Import cancelled");let A=J.map((K)=>M0(K,W));await $.importBatch(Y,G,A,U),j+=J.length,X?.(j)}return await $.commit(U),{rowCount:j}}catch(j){try{await $.rollback(U)}catch(J){console.debug("Rollback after import error failed:",J instanceof Error?J.message:J)}throw j}finally{await $.releaseSession(U)}}async function L0($,Z){let Q=Z.limit??20;if(Z.format==="json")return E5($);let B={delimiter:Z.delimiter??",",hasHeader:Z.hasHeader??!0,batchSize:Q,maxRows:Q},X=[],W=[];for await(let Y of O$($,B))W=Y.columns,X.push(...Y.rows);return{fileColumns:W,rows:X.slice(0,Q),totalRows:void 0}}async function C5($,Z,Q,B,X,W){let Y=await x0(Z),G=_0(Y),H=$.qualifyTable(Q.schema,Q.table),V=B.map((J)=>J.tableColumn),U=Q.batchSize??O0,j=`__import_${crypto.randomUUID()}`;await $.reserveSession(j);try{await $.beginTransaction(j);let J=0;for(let A=0;A<G.length;A+=U){if(X?.aborted)throw Error("Import cancelled");let K=G.slice(A,A+U),R=K.map((z)=>M0(z,B));await $.importBatch(H,V,R,j),J+=K.length,W?.(J)}return await $.commit(j),{rowCount:J}}catch(J){try{await $.rollback(j)}catch(A){console.debug("Rollback after import error failed:",A instanceof Error?A.message:A)}throw J}finally{await $.releaseSession(j)}}async function E5($){let Z=await x0($),Q=_0(Z);return{fileColumns:D5(Q),rows:Q.slice(0,20),totalRows:Q.length}}function _0($){let Z=JSON.parse($);if(!Array.isArray(Z))throw Error("JSON import expects an array of objects");let Q=[];for(let B of Z){if(typeof B!=="object"||B===null||Array.isArray(B))throw Error("Each JSON array element must be an object");Q.push(B)}return Q}function M0($,Z){let Q={};for(let B of Z)Q[B.tableColumn]=$[B.fileColumn]??null;return Q}function D5($){let Z=new Set,Q=[];for(let B of $)for(let X of Object.keys(B))if(!Z.has(X))Z.add(X),Q.push(X);return Q}async function x0($){let Z=$.getReader(),Q=new TextDecoder("utf-8"),B="";while(!0){let{done:X,value:W}=await Z.read();if(X)break;B+=Q.decode(W,{stream:!0})}return B+=Q.decode(new Uint8Array(0),{stream:!1}),Z.releaseLock(),B}var O0=100;var L$=M(()=>{R0()});var _,C,e,D,E;var q=M(()=>{_=class _ extends Error{code;constructor($,Z,Q){super(Z,Q);this.name="DatabaseError",this.code=$}};C=class C extends _{constructor($,Z,Q){super($,Z,Q);this.name="ConnectionError"}};e=class e extends _{constructor($,Z){super("AUTH_FAILED",$,Z);this.name="AuthenticationError"}};D=class D extends _{constructor($,Z,Q){super($,Z,Q);this.name="QueryError"}};E=class E extends _{constructor($,Z,Q){super($,Z,Q);this.name="ConstraintError"}}});function M$($){let Z=[],Q="",B=0;while(B<$.length){let W=$[B],Y=B+1<$.length?$[B+1]:"";if(W==="-"&&Y==="-"){let G=$.indexOf(`
|
|
33
|
+
`,B);if(G===-1)Q+=$.slice(B),B=$.length;else Q+=$.slice(B,G+1),B=G+1;continue}if(W==="/"&&Y==="*"){let G=$.indexOf("*/",B+2);if(G===-1)Q+=$.slice(B),B=$.length;else Q+=$.slice(B,G+2),B=G+2;continue}if(W==="$"){let G=$.slice(B).match(/^(\$[a-zA-Z0-9_]*\$)/);if(G){let H=G[1],V=$.indexOf(H,B+H.length);if(V===-1)Q+=$.slice(B),B=$.length;else Q+=$.slice(B,V+H.length),B=V+H.length;continue}}if(W==="'"){Q+=W,B++;while(B<$.length)if($[B]==="'")if(Q+=$[B],B++,B<$.length&&$[B]==="'")Q+=$[B],B++;else break;else Q+=$[B],B++;continue}if(W==='"'){Q+=W,B++;while(B<$.length)if($[B]==='"')if(Q+=$[B],B++,B<$.length&&$[B]==='"')Q+=$[B],B++;else break;else Q+=$[B],B++;continue}if(W===";"){let G=Q.trim();if(G.length>0)Z.push(G);Q="",B++;continue}Q+=W,B++}let X=Q.trim();if(X.length>0)Z.push(X);return Z}function _$($,Z){let Q=1,B=1,X=Math.min(Z-1,$.length);for(let W=0;W<X;W++)if($[W]===`
|
|
34
|
+
`)Q++,B=1;else B++;return{line:Q,column:B}}function x$($,Z){if(!$||typeof $!=="object")return;let Q=$;if(Q.position!=null){let B=Number(Q.position);if(!Number.isNaN(B)&&B>0){let{line:X,column:W}=_$(Z,B);return{line:X,column:W,offset:B}}}if($ instanceof Error){let B=$.message.match(/at offset (\d+)/);if(B){let X=Number(B[1])+1,{line:W,column:Y}=_$(Z,X);return{line:W,column:Y,offset:X}}}return}class F0{logs=new Map;pendingCounts=new Map;key($,Z){return Z?`${$}:${Z}`:$}add($,Z,Q,B,X,W,Y){let G=this.key($,Y);if(!this.logs.has(G))this.logs.set(G,[]);this.logs.get(G).push({id:crypto.randomUUID(),sql:Z,status:Q,durationMs:B,rowCount:X,errorMessage:W,executedAt:new Date().toISOString()}),this.pendingCounts.set(G,(this.pendingCounts.get(G)??0)+1)}getEntries($,Z){return this.logs.get(this.key($,Z))??[]}getPendingCount($,Z){return this.pendingCounts.get(this.key($,Z))??0}resetPendingCount($,Z){this.pendingCounts.set(this.key($,Z),0)}clear($,Z){let Q=this.key($,Z);this.logs.delete(Q),this.pendingCounts.delete(Q)}}class c{connectionManager;runningQueries=new Map;defaultTimeoutMs;appDb;sessionLog=new F0;constructor($,Z=30000,Q){this.connectionManager=$,this.defaultTimeoutMs=Z,this.appDb=Q}async executeQuery($,Z,Q,B,X,W,Y,G){let H=this.connectionManager.getDriver($,W),V=M$(Z);if(V.length===0)return[];let U;if(!Y&&(V.length>1||G))U=`__ephemeral_${crypto.randomUUID()}`,await H.reserveSession(U);let j=Y??U,J=X??crypto.randomUUID(),A={queryId:J,connectionId:$,cancelled:!1,sessionId:j};this.runningQueries.set(J,A);let K=B??this.defaultTimeoutMs,R=[],z;try{if(G&&j!==void 0)z=(await H.execute("SHOW search_path",void 0,j)).rows[0]?.search_path,await H.execute(`SET search_path TO ${G}`,void 0,j);for(let O of V){if(A.cancelled){R.push(F$());break}let L=await this.executeSingle(H,O,V.length===1?Q:void 0,K,A,j);if(R.push(L),L.error)break}}finally{if(z!==void 0&&j!==void 0)try{await H.execute(`SET search_path TO ${z}`,void 0,j)}catch{}if(this.runningQueries.delete(J),U)await H.releaseSession(U);this.logHistory($,Z,R,W)}return R}async cancelQuery($){let Z=this.runningQueries.get($);if(!Z)return!1;Z.cancelled=!0;try{let Q=this.connectionManager.getDriver(Z.connectionId);if(Z.sessionId!==void 0)await Q.cancel(Z.sessionId);else await Q.cancel()}catch(Q){console.debug("Cancel query failed (driver may have completed):",Q instanceof Error?Q.message:Q)}return!0}async cancelAllForConnection($){let Z=[];for(let[B,X]of this.runningQueries)if(X.connectionId===$)Z.push(B);let Q=0;for(let B of Z)if(await this.cancelQuery(B))Q++;return Q}getRunningQueryIds(){return[...this.runningQueries.keys()]}async explainQuery($,Z,Q,B,X,W){let Y=this.connectionManager.getDriver($,B),G=Y.getDriverType(),H=performance.now(),V;if(!X&&W)V=`__ephemeral_${crypto.randomUUID()}`,await Y.reserveSession(V);let U=X??V,j;try{if(W&&U!==void 0)j=(await Y.execute("SHOW search_path",void 0,U)).rows[0]?.search_path,await Y.execute(`SET search_path TO ${W}`,void 0,U);if(G==="sqlite"){let x=U!==void 0?await Y.execute(`EXPLAIN QUERY PLAN ${Z}`,void 0,U):await Y.execute(`EXPLAIN QUERY PLAN ${Z}`),N=Math.round(performance.now()-H),P=S5(x.rows),d=x.rows.map((v)=>`${v.id}|${v.parent}|${v.notused??0}|${v.detail}`).join(`
|
|
35
|
+
`);return{nodes:P,rawText:d,durationMs:N}}let J=Q?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",A=U!==void 0?await Y.execute(`${J} ${Z}`,void 0,U):await Y.execute(`${J} ${Z}`),K=Math.round(performance.now()-H),R=A.rows[0]?.["QUERY PLAN"]??A.rows[0]?.EXPLAIN??JSON.stringify(A.rows),z=typeof R==="string"?JSON.parse(R):R,L=(Array.isArray(z)?z:[z]).map((x)=>N0(x.Plan??x)),F;try{let x=Q?"EXPLAIN (ANALYZE)":"EXPLAIN";F=(U!==void 0?await Y.execute(`${x} ${Z}`,void 0,U):await Y.execute(`${x} ${Z}`)).rows.map((P)=>Object.values(P)[0]).join(`
|
|
36
|
+
`)}catch{F=JSON.stringify(z,null,2)}return{nodes:L,rawText:F,durationMs:K}}catch(J){let A=Math.round(performance.now()-H);return{nodes:[],rawText:"",durationMs:A,error:J instanceof Error?J.message:String(J)}}finally{if(j!==void 0&&U!==void 0)try{await Y.execute(`SET search_path TO ${j}`,void 0,U)}catch{}if(V)await Y.releaseSession(V)}}async executeSingle($,Z,Q,B,X,W){let Y=performance.now(),{promise:G,cancel:H}=this.createTimeout(B);try{let V=await Promise.race([W!==void 0?$.execute(Z,Q,W):$.execute(Z,Q),G]);if(X.cancelled)return F$(performance.now()-Y);return{...V,durationMs:Math.round(performance.now()-Y)}}catch(V){let U=Math.round(performance.now()-Y);if(X.cancelled)return F$(U);let j=x$(V,Z),J=V instanceof _?V.code:void 0;return{columns:[],rows:[],rowCount:0,durationMs:U,error:V instanceof Error?V.message:String(V),errorCode:J,errorPosition:j}}finally{H()}}createTimeout($){let Z;return{promise:new Promise((B,X)=>{Z=setTimeout(()=>X(Error(`Query timed out after ${$}ms`)),$)}),cancel:()=>clearTimeout(Z)}}logHistory($,Z,Q,B){let X=Q.some((H)=>H.error),W=Q.reduce((H,V)=>H+(V.durationMs??0),0),Y=Q.reduce((H,V)=>H+(V.affectedRows??V.rowCount),0),G=Q.find((H)=>H.error)?.error;if(this.sessionLog.add($,Z,X?"error":"success",Math.round(W),Y,G,B),!this.appDb)return;try{this.appDb.addHistory({connectionId:$,database:B,sql:Z,status:X?"error":"success",durationMs:Math.round(W),rowCount:Y,errorMessage:G})}catch(H){console.debug("History logging failed:",H instanceof Error?H.message:H)}}}function F$($=0){return{columns:[],rows:[],rowCount:0,durationMs:Math.round($),error:"Query was cancelled"}}function N0($){let Z=$.Plans??[],{"Node Type":Q,"Relation Name":B,Plans:X,...W}=$;return{operation:String($["Node Type"]??"Unknown"),relation:$["Relation Name"]?String($["Relation Name"]):void 0,cost:typeof $["Total Cost"]==="number"?$["Total Cost"]:void 0,actualTime:typeof $["Actual Total Time"]==="number"?$["Actual Total Time"]:void 0,estimatedRows:typeof $["Plan Rows"]==="number"?$["Plan Rows"]:void 0,actualRows:typeof $["Actual Rows"]==="number"?$["Actual Rows"]:void 0,extra:Object.keys(W).length>0?W:void 0,children:Z.map((Y)=>N0(Y))}}function S5($){let Z=new Map,Q=new Map;for(let B of $){let X=Number(B.id??B.selectid??0),W=Number(B.parent??0),Y=String(B.detail??""),G={operation:Y,children:[]},H=Y.match(/^(SCAN|SEARCH|USE TEMP B-TREE)\s+(.*)/i);if(H){G.operation=H[1];let U=H[2].match(/^(\S+)/);if(U)G.relation=U[1]}if(Z.set(X,G),!Q.has(W))Q.set(W,[]);Q.get(W).push(G)}for(let[B,X]of Z)X.children=Q.get(B)??[];return Q.get(0)??[...Z.values()].filter((B,X)=>{let W=$[X],Y=Number(W?.parent??0);return!Z.has(Y)})}var N$=M(()=>{q();z$()});function I($){switch($.type){case"postgresql":return $.database;case"sqlite":return $.path;case"mysql":return $.database}}function b($){return y[$.type].hasHost}var y;var P$=M(()=>{y={postgresql:{label:"PostgreSQL",hasPassword:!0,hasHost:!0,defaultPort:5432,supportsMultiDatabase:!0},sqlite:{label:"SQLite",hasPassword:!1,hasHost:!1,supportsMultiDatabase:!1},mysql:{label:"MySQL",hasPassword:!0,hasHost:!0,defaultPort:3306,supportsMultiDatabase:!1}}});import{createCipheriv as T5,createDecipheriv as q5,hkdfSync as W9,randomBytes as y5}from"crypto";class E${keyPromise;constructor($){this.keyPromise=h5($)}async encrypt($){let Z=await this.keyPromise,Q=crypto.getRandomValues(new Uint8Array(k$)),B=new TextEncoder().encode($),X=await crypto.subtle.encrypt({name:C$,iv:Q},Z,B),W=new Uint8Array(Q.length+X.byteLength);return W.set(Q,0),W.set(new Uint8Array(X),Q.length),Buffer.from(W).toString("base64")}async decrypt($){let Z=await this.keyPromise,Q=new Uint8Array(Buffer.from($,"base64")),B=Q.slice(0,k$),X=Q.slice(k$),W=await crypto.subtle.decrypt({name:C$,iv:B},Z,X);return new TextDecoder().decode(W)}}async function h5($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.importKey("raw",Z,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new TextEncoder().encode("dotaz-encryption-salt"),info:new TextEncoder().encode("dotaz-aes-key")},Q,{name:C$,length:v5},!1,["encrypt","decrypt"])}function w($,Z){let Q=new Uint8Array(y5(i)),B=T5("aes-256-gcm",Z,Q),X=B.update($,"utf8"),W=B.final(),Y=new Uint8Array(B.getAuthTag()),G=new Uint8Array(X.length+W.length);G.set(X,0),G.set(W,X.length);let H=new Uint8Array(Q.length+Y.length+G.length);return H.set(Q,0),H.set(Y,Q.length),H.set(G,Q.length+Y.length),$$+Buffer.from(H).toString("base64")}function Z$($,Z){if(!$.startsWith($$))return $;let Q=new Uint8Array(Buffer.from($.slice($$.length),"base64")),B=Q.subarray(0,i),X=Q.subarray(i,i+P0),W=Q.subarray(i+P0),Y=q5("aes-256-gcm",Z,B);return Y.setAuthTag(X),Y.update(W).toString("utf8")+Y.final("utf8")}function f($){return $.startsWith($$)}var C$="AES-GCM",k$=12,v5=256,$$="enc:v1:",i=12,P0=16;var D$=()=>{};function w5($){$.run(`
|
|
37
37
|
CREATE TABLE IF NOT EXISTS schema_version (
|
|
38
38
|
version INTEGER PRIMARY KEY,
|
|
39
39
|
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
40
40
|
)
|
|
41
|
-
`)}function
|
|
41
|
+
`)}function f5($){return $.prepare("SELECT MAX(version) as version FROM schema_version").get()?.version??0}function k0($){w5($);let Z=f5($),Q=b5.filter((B)=>B.version>Z);for(let B of Q){$.run("BEGIN");try{B.up($),$.run("INSERT INTO schema_version (version) VALUES (?)",[B.version]),$.run("COMMIT")}catch(X){throw $.run("ROLLBACK"),X}}return Q.length}var b5;var C0=M(()=>{b5=[{version:1,description:"Create connections, query_history, saved_views, settings tables",up:($)=>{$.run(`
|
|
42
42
|
CREATE TABLE connections (
|
|
43
43
|
id TEXT PRIMARY KEY,
|
|
44
44
|
name TEXT NOT NULL,
|
|
@@ -76,7 +76,7 @@ ${G.join(`,
|
|
|
76
76
|
key TEXT PRIMARY KEY,
|
|
77
77
|
value TEXT NOT NULL
|
|
78
78
|
)
|
|
79
|
-
`)}},{version:2,description:"Migrate SSL boolean to SSLMode string in connection configs",up:($)=>{let Z=$.prepare("SELECT id, config FROM connections WHERE type = 'postgresql' OR type = 'mysql'").all(),Q=$.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let
|
|
79
|
+
`)}},{version:2,description:"Migrate SSL boolean to SSLMode string in connection configs",up:($)=>{let Z=$.prepare("SELECT id, config FROM connections WHERE type = 'postgresql' OR type = 'mysql'").all(),Q=$.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let B of Z){let X=JSON.parse(B.config);if(typeof X.ssl==="boolean")X.ssl=X.ssl?"require":"disable",Q.run(JSON.stringify(X),B.id)}}},{version:3,description:"Add read_only column to connections table",up:($)=>{$.run("ALTER TABLE connections ADD COLUMN read_only INTEGER NOT NULL DEFAULT 0")}},{version:4,description:"Create query_bookmarks table",up:($)=>{$.run(`
|
|
80
80
|
CREATE TABLE query_bookmarks (
|
|
81
81
|
id TEXT PRIMARY KEY,
|
|
82
82
|
connection_id TEXT NOT NULL,
|
|
@@ -93,8 +93,8 @@ ${G.join(`,
|
|
|
93
93
|
data TEXT NOT NULL,
|
|
94
94
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
95
95
|
)
|
|
96
|
-
`)}},{version:7,description:"Add database column to query_history and query_bookmarks",up:($)=>{$.run("ALTER TABLE query_history ADD COLUMN database TEXT DEFAULT NULL"),$.run("ALTER TABLE query_bookmarks ADD COLUMN database TEXT DEFAULT NULL")}},{version:8,description:"Add group_name column to connections table",up:($)=>{$.run("ALTER TABLE connections ADD COLUMN group_name TEXT DEFAULT NULL")}}]});import b7 from"bun:sqlite";class t{db;localKey=null;constructor($){this.db=new b7($,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),N5(this.db)}static getInstance($){if(!u){let Z=$??w7();u=new t(Z)}return u}static create($){return new t($)}close(){this.db.close()}transaction($){return this.db.transaction($)()}static resetInstance(){if(u)u.db.close(),u=null}setLocalKey($){this.localKey=$,this.migratePasswords()}encryptConfigJson($){if(this.localKey&&b($)){let Z={...$,password:w($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let Q={...$.sshTunnel};if(Q.password)Q.password=w(Q.password,this.localKey);if(Q.keyPassphrase)Q.keyPassphrase=w(Q.keyPassphrase,this.localKey);Z={...Z,sshTunnel:Q}}return JSON.stringify(Z)}return JSON.stringify($)}decryptConfig($){if(this.localKey&&b($)&&g($.password)){let Z={...$,password:Z0($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let Q={...$.sshTunnel};if(Q.password&&g(Q.password))Q.password=Z0(Q.password,this.localKey);if(Q.keyPassphrase&&g(Q.keyPassphrase))Q.keyPassphrase=Z0(Q.keyPassphrase,this.localKey);Z={...Z,sshTunnel:Q}}return Z}return $}migratePasswords(){if(!this.localKey)return;this.transaction(()=>{let $=this.db.prepare("SELECT id, config FROM connections").all(),Z=this.db.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let Q of $)try{let X=JSON.parse(Q.config);if(b(X)){let B=!1,W={...X};if(!g(X.password))W={...W,password:w(X.password,this.localKey)},B=!0;if(X.type==="postgresql"&&X.sshTunnel){let Y={...X.sshTunnel};if(Y.password&&!g(Y.password))Y.password=w(Y.password,this.localKey),B=!0;if(Y.keyPassphrase&&!g(Y.keyPassphrase))Y.keyPassphrase=w(Y.keyPassphrase,this.localKey),B=!0;if(B)W={...W,sshTunnel:Y}}if(B)Z.run(JSON.stringify(W),Q.id)}}catch{}})}toConnectionInfo($){let Z=E5($.config,`connection "${$.name}"`);return{id:$.id,name:$.name,config:this.decryptConfig(Z),state:"disconnected",readOnly:$.read_only===1?!0:void 0,color:$.color??void 0,groupName:$.group_name??void 0,createdAt:$.created_at,updatedAt:$.updated_at}}listConnections(){return this.db.prepare("SELECT * FROM connections ORDER BY group_name NULLS LAST, name").all().map((Z)=>this.toConnectionInfo(Z))}getConnectionById($){let Z=this.db.prepare("SELECT * FROM connections WHERE id = ?").get($);return Z?this.toConnectionInfo(Z):null}createConnection($){let Z=crypto.randomUUID();return this.createConnectionWithId(Z,$)}createConnectionWithId($,Z){let Q=new Date().toISOString();return this.db.prepare("INSERT INTO connections (id, name, type, config, read_only, color, group_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run($,Z.name,Z.config.type,this.encryptConfigJson(Z.config),Z.readOnly?1:0,Z.color||null,Z.groupName||null,Q,Q),this.getConnectionById($)}updateConnection($){let Z=new Date().toISOString();this.db.prepare("UPDATE connections SET name = ?, type = ?, config = ?, read_only = ?, color = ?, group_name = ?, updated_at = ? WHERE id = ?").run($.name,$.config.type,this.encryptConfigJson($.config),$.readOnly?1:0,$.color||null,$.groupName!==void 0?$.groupName||null:null,Z,$.id);let Q=this.getConnectionById($.id);if(!Q)throw Error(`Connection not found: ${$.id}`);return Q}setConnectionGroup($,Z){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(Z,$);let Q=this.getConnectionById($);if(!Q)throw Error(`Connection not found: ${$}`);return Q}listConnectionGroups(){return this.db.prepare("SELECT DISTINCT group_name FROM connections WHERE group_name IS NOT NULL ORDER BY group_name").all().map((Z)=>Z.group_name)}renameConnectionGroup($,Z){this.db.prepare("UPDATE connections SET group_name = ? WHERE group_name = ?").run(Z,$)}deleteConnectionGroup($){this.db.prepare("UPDATE connections SET group_name = NULL WHERE group_name = ?").run($)}setConnectionReadOnly($,Z){this.db.prepare("UPDATE connections SET read_only = ? WHERE id = ?").run(Z?1:0,$);let Q=this.getConnectionById($);if(!Q)throw Error(`Connection not found: ${$}`);return Q}deleteConnection($){this.db.prepare("DELETE FROM connections WHERE id = ?").run($)}getSetting($){return this.db.prepare("SELECT value FROM settings WHERE key = ?").get($)?.value??null}getNumberSetting($){let Z=this.getSetting($)??Q0[$]??null;if(Z===null)return null;let Q=Number(Z);return Number.isFinite(Q)?Q:null}getBooleanSetting($){let Z=this.getSetting($)??Q0[$]??null;if(Z===null)return null;if(Z==="true")return!0;if(Z==="false")return!1;return null}setSetting($,Z){this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run($,Z)}getAllSettings(){let $=this.db.prepare("SELECT key, value FROM settings").all(),Z={};for(let Q of $)Z[Q.key]=Q.value;return Z}listSavedViews($,Z,Q){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all($,Z,Q).map(E0)}createSavedView($){let Z=crypto.randomUUID(),Q=new Date().toISOString();return this.db.prepare("INSERT INTO saved_views (id, connection_id, schema_name, table_name, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(Z,$.connectionId,$.schemaName,$.tableName,$.name,JSON.stringify($.config),Q,Q),this.getSavedViewById(Z)}updateSavedView($){let Z=new Date().toISOString();this.db.prepare("UPDATE saved_views SET name = ?, config = ?, updated_at = ? WHERE id = ?").run($.name,JSON.stringify($.config),Z,$.id);let Q=this.getSavedViewById($.id);if(!Q)throw Error(`Saved view not found: ${$.id}`);return Q}deleteSavedView($){this.db.prepare("DELETE FROM saved_views WHERE id = ?").run($)}listSavedViewsByConnection($){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? ORDER BY table_name, name").all($).map(E0)}getSavedViewById($){let Z=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get($);return Z?E0(Z):null}addHistory($){let Z=this.db.prepare("INSERT INTO query_history (connection_id, database, sql, status, duration_ms, row_count, error_message) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *").get($.connectionId,$.database??null,$.sql,$.status,$.durationMs??null,$.rowCount??null,$.errorMessage??null);return this.pruneHistory(),k5(Z)}pruneHistory(){let $=this.getNumberSetting("maxHistoryEntries");if($===null||$<=0)return;this.db.prepare("DELETE FROM query_history WHERE id NOT IN (SELECT id FROM query_history ORDER BY executed_at DESC, id DESC LIMIT ?)").run($)}listHistory($){let Z=$.limit??100,Q=$.offset??0,X=[],B=[];if($.connectionId)X.push("connection_id = ?"),B.push($.connectionId);if($.search)X.push("sql LIKE ?"),B.push(`%${$.search}%`);if($.startDate)X.push("executed_at >= ?"),B.push($.startDate+" 00:00:00");if($.endDate){let H=new Date($.endDate+"T00:00:00Z");H.setUTCDate(H.getUTCDate()+1);let V=H.getUTCFullYear(),U=String(H.getUTCMonth()+1).padStart(2,"0"),j=String(H.getUTCDate()).padStart(2,"0");X.push("executed_at < ?"),B.push(`${V}-${U}-${j} 00:00:00`)}let Y=`SELECT * FROM query_history ${X.length>0?`WHERE ${X.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return B.push(Z,Q),this.db.prepare(Y).all(...B).map(k5)}clearHistory($){if($)this.db.prepare("DELETE FROM query_history WHERE connection_id = ?").run($);else this.db.prepare("DELETE FROM query_history").run()}listBookmarks($,Z){if(Z)return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? AND (name LIKE ? OR sql LIKE ?) ORDER BY name").all($,`%${Z}%`,`%${Z}%`).map(D0);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all($).map(D0)}createBookmark($){let Z=crypto.randomUUID(),Q=new Date().toISOString();return this.db.prepare("INSERT INTO query_bookmarks (id, connection_id, database, name, description, sql, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(Z,$.connectionId,$.database??null,$.name,$.description??"",$.sql,Q,Q),this.getBookmarkById(Z)}updateBookmark($){let Z=new Date().toISOString();this.db.prepare("UPDATE query_bookmarks SET name = ?, description = ?, sql = ?, updated_at = ? WHERE id = ?").run($.name,$.description??"",$.sql,Z,$.id);let Q=this.getBookmarkById($.id);if(!Q)throw Error(`Bookmark not found: ${$.id}`);return Q}deleteBookmark($){this.db.prepare("DELETE FROM query_bookmarks WHERE id = ?").run($)}getBookmarkById($){let Z=this.db.prepare("SELECT * FROM query_bookmarks WHERE id = ?").get($);return Z?D0(Z):null}saveWorkspace($){this.db.prepare("INSERT INTO workspace (id, data, updated_at) VALUES ('default', ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')").run($)}loadWorkspace(){return this.db.prepare("SELECT data FROM workspace WHERE id = 'default'").get()?.data??null}}function E5($,Z){try{return JSON.parse($)}catch{throw Error(`Corrupted JSON in ${Z}: ${$.slice(0,100)}`)}}function E0($){return{id:$.id,connectionId:$.connection_id,schemaName:$.schema_name,tableName:$.table_name,name:$.name,config:E5($.config,`saved view "${$.name}"`),createdAt:$.created_at,updatedAt:$.updated_at}}function D0($){return{id:$.id,connectionId:$.connection_id,database:$.database??void 0,name:$.name,description:$.description,sql:$.sql,createdAt:$.created_at,updatedAt:$.updated_at}}function k5($){return{id:$.id,connectionId:$.connection_id,database:$.database??void 0,sql:$.sql,status:$.status,durationMs:$.duration_ms??void 0,rowCount:$.row_count??void 0,errorMessage:$.error_message??void 0,executedAt:$.executed_at}}function w7(){if(!C5)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return C5()}var Q0,u=null,C5;var S0=M(()=>{F0();C0();P5();Q0={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5"}});class T0{cm;appDb;sessions=new Map;labelCounters=new Map;constructor($,Z){this.cm=$,this.appDb=Z}async createSession($,Z){let Q=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(Q0.maxSessionsPerConnection),B=this.sessions.get($)?.size??0;if(Q!==null&&B>=Q)throw Error(`Maximum sessions per connection (${Q}) reached. Destroy an existing session first.`);let W=crypto.randomUUID();await this.cm.getDriver($,Z).reserveSession(W);let G=(this.labelCounters.get($)??0)+1;this.labelCounters.set($,G);let H={sessionId:W,connectionId:$,database:Z,label:`Session ${G}`,inTransaction:!1,createdAt:Date.now()};if(!this.sessions.has($))this.sessions.set($,new Map);return this.sessions.get($).set(W,H),H}async destroySession($){let Z=this.findSession($);if(!Z)throw Error(`Session not found: ${$}`);await this.cm.getDriver(Z.connectionId,Z.database).releaseSession($);let X=this.sessions.get(Z.connectionId);if(X){if(X.delete($),X.size===0)this.sessions.delete(Z.connectionId)}}listSessions($){let Z=this.sessions.get($);if(!Z)return[];let Q=[];for(let X of Z.values()){try{let B=this.cm.getDriver(X.connectionId,X.database);X.inTransaction=B.inTransaction(X.sessionId)}catch{}Q.push({...X})}return Q}getSession($){let Z=this.findSession($);if(!Z)return;try{let Q=this.cm.getDriver(Z.connectionId,Z.database);Z.inTransaction=Q.inTransaction(Z.sessionId)}catch{}return{...Z}}handleConnectionLost($){this.sessions.delete($)}findSession($){for(let Z of this.sessions.values()){let Q=Z.get($);if(Q)return Q}return}}var D5=M(()=>{S0()});function I7($){return f7.includes($)}function S5($){let Z=(X)=>$[`${g7}${X}`],Q=Z("provider");return{provider:I7(Q)?Q:X0.provider,apiKey:Z("apiKey")??X0.apiKey,model:Z("model")??X0.model,endpoint:Z("endpoint")??X0.endpoint}}var X0,g7="ai.",f7;var T5=M(()=>{X0={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},f7=["anthropic","openai","custom"]});function q5($,Z=50){let Q=[],X=0;for(let[B,W]of Object.entries($.tables))for(let Y of W){if(X>=Z)break;X++;let G=$.columns[`${B}.${Y.name}`]??[],H=$.foreignKeys[`${B}.${Y.name}`]??[],V=G.map((j)=>{let J=[j.name,j.dataType];if(j.isPrimaryKey)J.push("PK");if(!j.nullable)J.push("NOT NULL");if(j.isAutoIncrement)J.push("AUTO_INCREMENT");return J.join(" ")}),U=B==="main"||B==="public"?Y.name:`${B}.${Y.name}`;Q.push(`TABLE ${U} (${V.join(", ")})`);for(let j of H){let J=j.referencedSchema==="main"||j.referencedSchema==="public"?j.referencedTable:`${j.referencedSchema}.${j.referencedTable}`;Q.push(` FK ${j.columns.join(",")} -> ${J}(${j.referencedColumns.join(",")})`)}}return Q.join(`
|
|
97
|
-
`)}async function
|
|
96
|
+
`)}},{version:7,description:"Add database column to query_history and query_bookmarks",up:($)=>{$.run("ALTER TABLE query_history ADD COLUMN database TEXT DEFAULT NULL"),$.run("ALTER TABLE query_bookmarks ADD COLUMN database TEXT DEFAULT NULL")}},{version:8,description:"Add group_name column to connections table",up:($)=>{$.run("ALTER TABLE connections ADD COLUMN group_name TEXT DEFAULT NULL")}}]});import g5 from"bun:sqlite";class t{db;localKey=null;constructor($){this.db=new g5($,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),k0(this.db)}static getInstance($){if(!u){let Z=$??I5();u=new t(Z)}return u}static create($){return new t($)}close(){this.db.close()}transaction($){return this.db.transaction($)()}static resetInstance(){if(u)u.db.close(),u=null}setLocalKey($){this.localKey=$,this.migratePasswords()}encryptConfigJson($){if(this.localKey&&b($)){let Z={...$,password:w($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let Q={...$.sshTunnel};if(Q.password)Q.password=w(Q.password,this.localKey);if(Q.keyPassphrase)Q.keyPassphrase=w(Q.keyPassphrase,this.localKey);Z={...Z,sshTunnel:Q}}return JSON.stringify(Z)}return JSON.stringify($)}decryptConfig($){if(this.localKey&&b($)&&f($.password)){let Z={...$,password:Z$($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let Q={...$.sshTunnel};if(Q.password&&f(Q.password))Q.password=Z$(Q.password,this.localKey);if(Q.keyPassphrase&&f(Q.keyPassphrase))Q.keyPassphrase=Z$(Q.keyPassphrase,this.localKey);Z={...Z,sshTunnel:Q}}return Z}return $}migratePasswords(){if(!this.localKey)return;this.transaction(()=>{let $=this.db.prepare("SELECT id, config FROM connections").all(),Z=this.db.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let Q of $)try{let B=JSON.parse(Q.config);if(b(B)){let X=!1,W={...B};if(!f(B.password))W={...W,password:w(B.password,this.localKey)},X=!0;if(B.type==="postgresql"&&B.sshTunnel){let Y={...B.sshTunnel};if(Y.password&&!f(Y.password))Y.password=w(Y.password,this.localKey),X=!0;if(Y.keyPassphrase&&!f(Y.keyPassphrase))Y.keyPassphrase=w(Y.keyPassphrase,this.localKey),X=!0;if(X)W={...W,sshTunnel:Y}}if(X)Z.run(JSON.stringify(W),Q.id)}}catch{}})}toConnectionInfo($){let Z=S0($.config,`connection "${$.name}"`);return{id:$.id,name:$.name,config:this.decryptConfig(Z),state:"disconnected",readOnly:$.read_only===1?!0:void 0,color:$.color??void 0,groupName:$.group_name??void 0,createdAt:$.created_at,updatedAt:$.updated_at}}listConnections(){return this.db.prepare("SELECT * FROM connections ORDER BY group_name NULLS LAST, name").all().map((Z)=>this.toConnectionInfo(Z))}getConnectionById($){let Z=this.db.prepare("SELECT * FROM connections WHERE id = ?").get($);return Z?this.toConnectionInfo(Z):null}createConnection($){let Z=crypto.randomUUID();return this.createConnectionWithId(Z,$)}createConnectionWithId($,Z){let Q=new Date().toISOString();return this.db.prepare("INSERT INTO connections (id, name, type, config, read_only, color, group_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run($,Z.name,Z.config.type,this.encryptConfigJson(Z.config),Z.readOnly?1:0,Z.color||null,Z.groupName||null,Q,Q),this.getConnectionById($)}updateConnection($){let Z=new Date().toISOString();this.db.prepare("UPDATE connections SET name = ?, type = ?, config = ?, read_only = ?, color = ?, group_name = ?, updated_at = ? WHERE id = ?").run($.name,$.config.type,this.encryptConfigJson($.config),$.readOnly?1:0,$.color||null,$.groupName!==void 0?$.groupName||null:null,Z,$.id);let Q=this.getConnectionById($.id);if(!Q)throw Error(`Connection not found: ${$.id}`);return Q}setConnectionGroup($,Z){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(Z,$);let Q=this.getConnectionById($);if(!Q)throw Error(`Connection not found: ${$}`);return Q}listConnectionGroups(){return this.db.prepare("SELECT DISTINCT group_name FROM connections WHERE group_name IS NOT NULL ORDER BY group_name").all().map((Z)=>Z.group_name)}renameConnectionGroup($,Z){this.db.prepare("UPDATE connections SET group_name = ? WHERE group_name = ?").run(Z,$)}deleteConnectionGroup($){this.db.prepare("UPDATE connections SET group_name = NULL WHERE group_name = ?").run($)}setConnectionReadOnly($,Z){this.db.prepare("UPDATE connections SET read_only = ? WHERE id = ?").run(Z?1:0,$);let Q=this.getConnectionById($);if(!Q)throw Error(`Connection not found: ${$}`);return Q}deleteConnection($){this.db.prepare("DELETE FROM connections WHERE id = ?").run($)}getSetting($){return this.db.prepare("SELECT value FROM settings WHERE key = ?").get($)?.value??null}getNumberSetting($){let Z=this.getSetting($)??Q$[$]??null;if(Z===null)return null;let Q=Number(Z);return Number.isFinite(Q)?Q:null}getBooleanSetting($){let Z=this.getSetting($)??Q$[$]??null;if(Z===null)return null;if(Z==="true")return!0;if(Z==="false")return!1;return null}setSetting($,Z){this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run($,Z)}getAllSettings(){let $=this.db.prepare("SELECT key, value FROM settings").all(),Z={};for(let Q of $)Z[Q.key]=Q.value;return Z}listSavedViews($,Z,Q){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all($,Z,Q).map(S$)}createSavedView($){let Z=crypto.randomUUID(),Q=new Date().toISOString();return this.db.prepare("INSERT INTO saved_views (id, connection_id, schema_name, table_name, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(Z,$.connectionId,$.schemaName,$.tableName,$.name,JSON.stringify($.config),Q,Q),this.getSavedViewById(Z)}updateSavedView($){let Z=new Date().toISOString();this.db.prepare("UPDATE saved_views SET name = ?, config = ?, updated_at = ? WHERE id = ?").run($.name,JSON.stringify($.config),Z,$.id);let Q=this.getSavedViewById($.id);if(!Q)throw Error(`Saved view not found: ${$.id}`);return Q}deleteSavedView($){this.db.prepare("DELETE FROM saved_views WHERE id = ?").run($)}listSavedViewsByConnection($){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? ORDER BY table_name, name").all($).map(S$)}getSavedViewById($){let Z=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get($);return Z?S$(Z):null}addHistory($){let Z=this.db.prepare("INSERT INTO query_history (connection_id, database, sql, status, duration_ms, row_count, error_message) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *").get($.connectionId,$.database??null,$.sql,$.status,$.durationMs??null,$.rowCount??null,$.errorMessage??null);return this.pruneHistory(),E0(Z)}pruneHistory(){let $=this.getNumberSetting("maxHistoryEntries");if($===null||$<=0)return;this.db.prepare("DELETE FROM query_history WHERE id NOT IN (SELECT id FROM query_history ORDER BY executed_at DESC, id DESC LIMIT ?)").run($)}listHistory($){let Z=$.limit??100,Q=$.offset??0,B=[],X=[];if($.connectionId)B.push("connection_id = ?"),X.push($.connectionId);if($.search)B.push("sql LIKE ?"),X.push(`%${$.search}%`);if($.startDate)B.push("executed_at >= ?"),X.push($.startDate+" 00:00:00");if($.endDate){let H=new Date($.endDate+"T00:00:00Z");H.setUTCDate(H.getUTCDate()+1);let V=H.getUTCFullYear(),U=String(H.getUTCMonth()+1).padStart(2,"0"),j=String(H.getUTCDate()).padStart(2,"0");B.push("executed_at < ?"),X.push(`${V}-${U}-${j} 00:00:00`)}let Y=`SELECT * FROM query_history ${B.length>0?`WHERE ${B.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return X.push(Z,Q),this.db.prepare(Y).all(...X).map(E0)}clearHistory($){if($)this.db.prepare("DELETE FROM query_history WHERE connection_id = ?").run($);else this.db.prepare("DELETE FROM query_history").run()}listBookmarks($,Z){if(Z)return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? AND (name LIKE ? OR sql LIKE ?) ORDER BY name").all($,`%${Z}%`,`%${Z}%`).map(T$);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all($).map(T$)}createBookmark($){let Z=crypto.randomUUID(),Q=new Date().toISOString();return this.db.prepare("INSERT INTO query_bookmarks (id, connection_id, database, name, description, sql, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(Z,$.connectionId,$.database??null,$.name,$.description??"",$.sql,Q,Q),this.getBookmarkById(Z)}updateBookmark($){let Z=new Date().toISOString();this.db.prepare("UPDATE query_bookmarks SET name = ?, description = ?, sql = ?, updated_at = ? WHERE id = ?").run($.name,$.description??"",$.sql,Z,$.id);let Q=this.getBookmarkById($.id);if(!Q)throw Error(`Bookmark not found: ${$.id}`);return Q}deleteBookmark($){this.db.prepare("DELETE FROM query_bookmarks WHERE id = ?").run($)}getBookmarkById($){let Z=this.db.prepare("SELECT * FROM query_bookmarks WHERE id = ?").get($);return Z?T$(Z):null}saveWorkspace($){this.db.prepare("INSERT INTO workspace (id, data, updated_at) VALUES ('default', ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')").run($)}loadWorkspace(){return this.db.prepare("SELECT data FROM workspace WHERE id = 'default'").get()?.data??null}}function S0($,Z){try{return JSON.parse($)}catch{throw Error(`Corrupted JSON in ${Z}: ${$.slice(0,100)}`)}}function S$($){return{id:$.id,connectionId:$.connection_id,schemaName:$.schema_name,tableName:$.table_name,name:$.name,config:S0($.config,`saved view "${$.name}"`),createdAt:$.created_at,updatedAt:$.updated_at}}function T$($){return{id:$.id,connectionId:$.connection_id,database:$.database??void 0,name:$.name,description:$.description,sql:$.sql,createdAt:$.created_at,updatedAt:$.updated_at}}function E0($){return{id:$.id,connectionId:$.connection_id,database:$.database??void 0,sql:$.sql,status:$.status,durationMs:$.duration_ms??void 0,rowCount:$.row_count??void 0,errorMessage:$.error_message??void 0,executedAt:$.executed_at}}function I5(){if(!D0)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return D0()}var Q$,u=null,D0;var q$=M(()=>{P$();D$();C0();Q$={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5"}});class y${cm;appDb;sessions=new Map;labelCounters=new Map;constructor($,Z){this.cm=$,this.appDb=Z}async createSession($,Z){let Q=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(Q$.maxSessionsPerConnection),X=this.sessions.get($)?.size??0;if(Q!==null&&X>=Q)throw Error(`Maximum sessions per connection (${Q}) reached. Destroy an existing session first.`);let W=crypto.randomUUID();await this.cm.getDriver($,Z).reserveSession(W);let G=(this.labelCounters.get($)??0)+1;this.labelCounters.set($,G);let H={sessionId:W,connectionId:$,database:Z,label:`Session ${G}`,inTransaction:!1,createdAt:Date.now()};if(!this.sessions.has($))this.sessions.set($,new Map);return this.sessions.get($).set(W,H),H}async destroySession($){let Z=this.findSession($);if(!Z)throw Error(`Session not found: ${$}`);await this.cm.getDriver(Z.connectionId,Z.database).releaseSession($);let B=this.sessions.get(Z.connectionId);if(B){if(B.delete($),B.size===0)this.sessions.delete(Z.connectionId)}}listSessions($){let Z=this.sessions.get($);if(!Z)return[];let Q=[];for(let B of Z.values()){try{let X=this.cm.getDriver(B.connectionId,B.database);B.inTransaction=X.inTransaction(B.sessionId)}catch{}Q.push({...B})}return Q}getSession($){let Z=this.findSession($);if(!Z)return;try{let Q=this.cm.getDriver(Z.connectionId,Z.database);Z.inTransaction=Q.inTransaction(Z.sessionId)}catch{}return{...Z}}handleConnectionLost($){this.sessions.delete($)}findSession($){for(let Z of this.sessions.values()){let Q=Z.get($);if(Q)return Q}return}}var T0=M(()=>{q$()});function m5($){return p5.includes($)}function q0($){let Z=(B)=>$[`${u5}${B}`],Q=Z("provider");return{provider:m5(Q)?Q:B$.provider,apiKey:Z("apiKey")??B$.apiKey,model:Z("model")??B$.model,endpoint:Z("endpoint")??B$.endpoint}}var B$,u5="ai.",p5;var y0=M(()=>{B$={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},p5=["anthropic","openai","custom"]});function v0($,Z=50){let Q=[],B=0;for(let[X,W]of Object.entries($.tables))for(let Y of W){if(B>=Z)break;B++;let G=$.columns[`${X}.${Y.name}`]??[],H=$.foreignKeys[`${X}.${Y.name}`]??[],V=G.map((j)=>{let J=[j.name,j.dataType];if(j.isPrimaryKey)J.push("PK");if(!j.nullable)J.push("NOT NULL");if(j.isAutoIncrement)J.push("AUTO_INCREMENT");return J.join(" ")}),U=X==="main"||X==="public"?Y.name:`${X}.${Y.name}`;Q.push(`TABLE ${U} (${V.join(", ")})`);for(let j of H){let J=j.referencedSchema==="main"||j.referencedSchema==="public"?j.referencedTable:`${j.referencedSchema}.${j.referencedTable}`;Q.push(` FK ${j.columns.join(",")} -> ${J}(${j.referencedColumns.join(",")})`)}}return Q.join(`
|
|
97
|
+
`)}async function l5($,Z){let B=`${$.endpoint||"https://api.anthropic.com"}/v1/messages`,X=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:$.model,max_tokens:2048,system:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
|
|
98
98
|
|
|
99
99
|
Rules:
|
|
100
100
|
- Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
|
|
@@ -108,7 +108,7 @@ Rules:
|
|
|
108
108
|
Database schema:
|
|
109
109
|
${Z.schemaContext}
|
|
110
110
|
|
|
111
|
-
Request: ${Z.prompt}`}]})});if(!
|
|
111
|
+
Request: ${Z.prompt}`}]})});if(!X.ok){let G=await X.text().catch(()=>"");if(X.status===401)throw Error("Invalid API key. Check your AI settings.");if(X.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`Anthropic API error (${X.status}): ${G.slice(0,200)}`)}let Y=(await X.json()).content?.find((G)=>G.type==="text");return b0(Y?.text??"")}async function h0($,Z){let B=`${$.endpoint||"https://api.openai.com"}/v1/chat/completions`,X=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$.apiKey}`},body:JSON.stringify({model:$.model||"gpt-4o",max_tokens:2048,messages:[{role:"system",content:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
|
|
112
112
|
|
|
113
113
|
Rules:
|
|
114
114
|
- Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
|
|
@@ -122,8 +122,8 @@ Rules:
|
|
|
122
122
|
Database schema:
|
|
123
123
|
${Z.schemaContext}
|
|
124
124
|
|
|
125
|
-
Request: ${Z.prompt}`}]})});if(!
|
|
126
|
-
`)}var g5,f5,l7,d7;var u5=M(()=>{g5=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],f5=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],l7=["ON","AND","OR"],d7=["SELECT","DISTINCT","FROM","WHERE","AND","OR","NOT","IN","EXISTS","BETWEEN","LIKE","ILIKE","IS","NULL","TRUE","FALSE","AS","ON","USING","JOIN","INNER","LEFT","RIGHT","FULL","OUTER","CROSS","NATURAL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","INTERSECT","EXCEPT","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","PRIMARY","KEY","FOREIGN","REFERENCES","UNIQUE","CHECK","DEFAULT","CONSTRAINT","CASCADE","RESTRICT","BEGIN","COMMIT","ROLLBACK","TRANSACTION","CASE","WHEN","THEN","ELSE","END","ASC","DESC","NULLS","FIRST","LAST","COUNT","SUM","AVG","MIN","MAX","CAST","COALESCE","NULLIF","WITH","RECURSIVE","RETURNING"]});class q0{cm;constructor($){this.cm=$}async begin($,Z,Q){let X=this.cm.getDriver($,Z);if(X.inTransaction(Q))throw Error("Transaction already active on this connection");await X.beginTransaction(Q)}async commit($,Z,Q){let X=this.cm.getDriver($,Z);if(!X.inTransaction(Q))throw Error("No active transaction to commit");await X.commit(Q)}async rollback($,Z,Q){let X=this.cm.getDriver($,Z);if(!X.inTransaction(Q))throw Error("No active transaction to rollback");await X.rollback(Q)}isActive($,Z,Q){try{return this.cm.getDriver($,Z).inTransaction(Q)}catch{return!1}}async rollbackIfActive($,Z,Q){if(this.isActive($,Z,Q))await this.rollback($,Z,Q)}}class y0{cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;constructor($,Z,Q,X){this.cm=$;this.queryExecutor=Z;this.appDb=Q;this.txManager=new q0($),this.encryption=X?.encryption,this.Utils=X?.Utils,this.emitMessage=X?.emitMessage,this.sessionManager=X?.sessionManager,this.demoDbSourcePath=X?.demoDbSourcePath,this.demoDbTargetPath=X?.demoDbTargetPath}listConnections(){return this.cm.listConnections()}createConnection($){return this.cm.createConnection($)}updateConnection($){return this.cm.updateConnection($)}setConnectionReadOnly($,Z){return this.cm.setConnectionReadOnly($,Z)}setConnectionGroup($,Z){return this.appDb.setConnectionGroup($,Z)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup($,Z){this.appDb.renameConnectionGroup($,Z)}deleteConnectionGroup($){this.appDb.deleteConnectionGroup($)}async deleteConnection($){await this.cm.deleteConnection($)}async testConnection($){return this.cm.testConnection($)}async connect($,Z,Q,X){if(Q&&this.encryption){let B=await this.encryption.decrypt(Q),W=JSON.parse(B),Y=this.appDb.getConnectionById($);if(!Y)this.appDb.createConnectionWithId($,{name:X??$,config:W});else this.appDb.updateConnection({id:$,name:X??Y.name,config:W})}await this.cm.connect($,Z?{password:Z}:void 0)}async disconnect($){await this.cm.disconnect($)}async createSession($,Z){if(!this.sessionManager)throw Error("SessionManager not available");let Q=await this.sessionManager.createSession($,Z);return this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)}),Q}async destroySession($){if(!this.sessionManager)throw Error("SessionManager not available");let Z=this.sessionManager.getSession($);if(await this.sessionManager.destroySession($),Z)this.emitMessage?.("session.changed",{connectionId:Z.connectionId,sessions:this.sessionManager.listSessions(Z.connectionId)})}listSessions($){if(!this.sessionManager)return[];return this.sessionManager.listSessions($)}getDriver($,Z){return this.cm.getDriver($,Z)}async listDatabases($){return this.cm.listDatabases($)}async activateDatabase($,Z){await this.cm.activateDatabase($,Z)}async deactivateDatabase($,Z){await this.cm.deactivateDatabase($,Z)}async executeQuery($,Z,Q,X,B,W,Y){return this.queryExecutor.executeQuery($,Z,Q,void 0,X,B,W,Y)}async executeStatements($,Z,Q,X){let B=this.cm.getDriver($,Q),W=B.inTransaction(X);if(!W)await B.beginTransaction(X);try{let Y=[];for(let G of Z){let H=performance.now(),V=X!==void 0?await B.execute(G.sql,G.params,X):await B.execute(G.sql,G.params);Y.push({...V,durationMs:Math.round(performance.now()-H)})}if(!W)await B.commit(X);return Y}catch(Y){if(!W)try{await B.rollback(X)}catch(G){console.debug("Rollback after error failed:",G instanceof Error?G.message:G)}throw Y}}async cancelQuery($){await this.queryExecutor.cancelQuery($)}async explainQuery($,Z,Q,X,B,W){return this.queryExecutor.explainQuery($,Z,Q,X,B,W)}async beginTransaction($,Z,Q){await this.txManager.begin($,Z,Q)}async commitTransaction($,Z,Q){await this.txManager.commit($,Z,Q),this.queryExecutor.sessionLog.resetPendingCount($,Z)}async rollbackTransaction($,Z,Q){await this.txManager.rollback($,Z,Q),this.queryExecutor.sessionLog.resetPendingCount($,Z)}getTransactionLog($){let Z=this.queryExecutor.sessionLog.getEntries($.connectionId,$.database);if($.statusFilter)Z=Z.filter((B)=>B.status===$.statusFilter);if($.search){let B=$.search.toLowerCase();Z=Z.filter((W)=>W.sql.toLowerCase().includes(B))}let Q=this.txManager.isActive($.connectionId,$.database,$.sessionId),X=Q?this.queryExecutor.sessionLog.getPendingCount($.connectionId,$.database):0;return{entries:Z,pendingStatementCount:X,inTransaction:Q}}clearTransactionLog($,Z,Q){this.queryExecutor.sessionLog.clear($,Z)}listHistory($){return this.appDb.listHistory($)}clearHistory($){this.appDb.clearHistory($)}listSavedViews($,Z,Q){return this.appDb.listSavedViews($,Z,Q)}createSavedView($){return this.appDb.createSavedView($)}updateSavedView($){return this.appDb.updateSavedView($)}deleteSavedView($){this.appDb.deleteSavedView($)}listSavedViewsByConnection($){return this.appDb.listSavedViewsByConnection($)}getSavedViewById($){return this.appDb.getSavedViewById($)}listBookmarks($,Z){return this.appDb.listBookmarks($,Z)}createBookmark($){return this.appDb.createBookmark($)}updateBookmark($){return this.appDb.updateBookmark($)}deleteBookmark($){this.appDb.deleteBookmark($)}async searchDatabase($){let Z=this.cm.getDriver($.connectionId,$.database);return b5(Z,{searchTerm:$.searchTerm,scope:$.scope,schemaName:$.schemaName,tableNames:$.tableNames,resultsPerTable:$.resultsPerTable??50},()=>{},()=>!1)}async exportData($){let Z=this.cm.getDriver($.connectionId,$.database);if(!$.filePath)throw Error("Export requires a file path");let Q=this.emitMessage?(B)=>this.emitMessage("export.progress",{rowCount:B}):void 0;return{...await j5(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,includeHeaders:$.includeHeaders,delimiter:$.delimiter,encoding:$.encoding,utf8Bom:$.utf8Bom,batchSize:$.batchSize,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins},$.filePath,void 0,Q),filePath:$.filePath}}async exportPreview($){let Z=this.cm.getDriver($.connectionId,$.database);return J5(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,delimiter:$.delimiter,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins})}async exportPreviewRows($){let Z=this.cm.getDriver($.connectionId,$.database),{sql:Q,params:X}=r({schema:$.schema,table:$.table,format:"csv",columns:$.columns,filters:$.filters,sort:$.sort,autoJoins:$.autoJoins},Z),B=X.length+1,W=`${Q} LIMIT ${Z.placeholder(B)}`,G=(await Z.execute(W,[...X,$.limit])).rows,H=G.length>0?Object.keys(G[0]):$.columns??[];return{rows:G,columns:H}}async importData($){let Z=this.cm.getDriver($.connectionId,$.database),Q=this.resolveImportStream($.filePath,$.fileContent),X=this.emitMessage?(B)=>this.emitMessage("import.progress",{rowCount:B}):void 0;return s(Z,Q,{schema:$.schema,table:$.table,format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,mappings:$.mappings,batchSize:$.batchSize},void 0,X)}async importPreview($){let Z=this.resolveImportPreviewStream($.filePath,$.fileContent),Q=await O5(Z,{format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,limit:$.limit});if($.filePath)try{let X=Bun.file($.filePath);Q.fileSizeBytes=X.size}catch{}return Q}resolveImportStream($,Z){if($)return Bun.file($).stream();if(Z!==void 0)return new ReadableStream({start(Q){Q.enqueue(new TextEncoder().encode(Z)),Q.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream($,Z){if($){let B=Bun.file($).stream().getReader(),W=65536,Y=0;return new ReadableStream({async pull(G){let{done:H,value:V}=await B.read();if(H){G.close();return}if(Y+=V.byteLength,Y>=65536){G.enqueue(V),G.close(),B.releaseLock();return}G.enqueue(V)},cancel(){B.releaseLock()}})}if(Z!==void 0)return new ReadableStream({start(Q){Q.enqueue(new TextEncoder().encode(Z)),Q.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting($,Z){this.appDb.setSetting($,Z)}async encrypt($){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt($)}async showOpenDialog({filters:$,multiple:Z}){if(!this.Utils)throw Error("Utils not available");let Q=$&&$.length>0?$.flatMap((W)=>W.extensions.map((Y)=>`*.${Y}`)).join(","):"*",B=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:Q,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:Z??!1})).filter((W)=>W!=="");return{paths:B,cancelled:B.length===0}}async showSaveDialog({defaultName:$}){if(!this.Utils)throw Error("Utils not available");let Q=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!Q||Q==="")return{path:null,cancelled:!0};return{path:$?`${Q}/${$}`:Q,cancelled:!1}}formatSql($){return I5($)}async generateSql($){let Z=this.cm.getDriver($.connectionId,$.database),Q=await Z.loadSchema(),X=q5(Q),B=S5(this.appDb.getAllSettings());return{sql:await h5(B,{prompt:$.prompt,schemaContext:X,dialect:Z.getDriverType()})}}saveWorkspace($){this.appDb.saveWorkspace($)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let $=Bun.file(this.demoDbSourcePath);if(!await $.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,$);let Z={type:"sqlite",path:this.demoDbTargetPath},Q=this.appDb.createConnection({name:"Bookstore (Demo)",config:Z});return await this.cm.connect(Q.id),Q}getSessionManager(){return this.sessionManager}}var p5=M(()=>{T5();z0();O0();w5();u5()});function m5($){return{"connections.list":()=>{return $.listConnections()},"connections.create":({name:Z,config:Q,readOnly:X,color:B,groupName:W})=>{return $.createConnection({name:Z,config:Q,readOnly:X,color:B,groupName:W})},"connections.update":({id:Z,name:Q,config:X,readOnly:B,color:W,groupName:Y})=>{return $.updateConnection({id:Z,name:Q,config:X,readOnly:B,color:W,groupName:Y})},"connections.setReadOnly":({id:Z,readOnly:Q})=>{return $.setConnectionReadOnly(Z,Q)},"connections.setGroup":({id:Z,groupName:Q})=>{return $.setConnectionGroup(Z,Q)},"connections.listGroups":()=>{return $.listConnectionGroups()},"connections.renameGroup":({oldName:Z,newName:Q})=>{$.renameConnectionGroup(Z,Q)},"connections.deleteGroup":({groupName:Z})=>{$.deleteConnectionGroup(Z)},"connections.delete":async({id:Z})=>{await $.deleteConnection(Z)},"connections.test":async({config:Z})=>{return $.testConnection(Z)},"connections.connect":async({connectionId:Z,password:Q,encryptedConfig:X,name:B})=>{await $.connect(Z,Q,X,B)},"connections.disconnect":async({connectionId:Z})=>{await $.disconnect(Z)},"session.create":async({connectionId:Z,database:Q})=>{return $.createSession(Z,Q)},"session.destroy":async({sessionId:Z})=>{await $.destroySession(Z)},"session.list":({connectionId:Z})=>{return $.listSessions(Z)},"databases.list":async({connectionId:Z})=>{return $.listDatabases(Z)},"databases.activate":async({connectionId:Z,database:Q})=>{await $.activateDatabase(Z,Q)},"databases.deactivate":async({connectionId:Z,database:Q})=>{await $.deactivateDatabase(Z,Q)},"schema.load":async({connectionId:Z,database:Q,sessionId:X})=>{return $.getDriver(Z,Q).loadSchema(X)},"query.execute":async({connectionId:Z,sql:Q,queryId:X,params:B,database:W,statements:Y,sessionId:G,searchPath:H})=>{if(Y&&Y.length>0)return $.executeStatements(Z,Y,W,G);return $.executeQuery(Z,Q,B,X,W,G,H)},"query.cancel":async({queryId:Z})=>{await $.cancelQuery(Z)},"query.format":({sql:Z})=>{return{sql:$.formatSql(Z)}},"query.explain":async({connectionId:Z,sql:Q,analyze:X,database:B,sessionId:W,searchPath:Y})=>{return $.explainQuery(Z,Q,X??!1,B,W,Y)},"tx.begin":async({connectionId:Z,database:Q,sessionId:X})=>{await $.beginTransaction(Z,Q,X)},"tx.commit":async({connectionId:Z,database:Q,sessionId:X})=>{await $.commitTransaction(Z,Q,X)},"tx.rollback":async({connectionId:Z,database:Q,sessionId:X})=>{await $.rollbackTransaction(Z,Q,X)},"transaction.getLog":(Z)=>{return $.getTransactionLog(Z)},"transaction.clearLog":({connectionId:Z,database:Q,sessionId:X})=>{$.clearTransactionLog(Z,Q,X)},"search.searchDatabase":async(Z)=>{return $.searchDatabase(Z)},"export.exportData":async(Z)=>{return $.exportData(Z)},"export.preview":async(Z)=>{return{content:await $.exportPreview(Z)}},"export.previewRows":async(Z)=>{return $.exportPreviewRows(Z)},"import.importData":async(Z)=>{return $.importData(Z)},"import.preview":async(Z)=>{return $.importPreview(Z)},"history.list":(Z)=>{return $.listHistory(Z)},"history.clear":({connectionId:Z})=>{$.clearHistory(Z)},"views.save":({connectionId:Z,schemaName:Q,tableName:X,name:B,config:W})=>{if(!B||!B.trim())throw Error("View name is required");if(!Z)throw Error("connectionId is required");if(!X)throw Error("tableName is required");if($.listSavedViews(Z,Q,X).some((G)=>G.name===B.trim()))throw Error(`A view named "${B.trim()}" already exists for this table`);return $.createSavedView({connectionId:Z,schemaName:Q,tableName:X,name:B.trim(),config:W})},"views.update":({id:Z,name:Q,config:X})=>{if(!Z)throw Error("View id is required");if(!Q||!Q.trim())throw Error("View name is required");let B=$.getSavedViewById(Z);if(!B)throw Error(`Saved view not found: ${Z}`);if($.listSavedViews(B.connectionId,B.schemaName,B.tableName).some((Y)=>Y.id!==Z&&Y.name===Q.trim()))throw Error(`A view named "${Q.trim()}" already exists for this table`);return $.updateSavedView({id:Z,name:Q.trim(),config:X})},"views.delete":({id:Z})=>{$.deleteSavedView(Z)},"views.listByConnection":({connectionId:Z})=>{return $.listSavedViewsByConnection(Z)},"bookmarks.list":({connectionId:Z,search:Q})=>{return $.listBookmarks(Z,Q)},"bookmarks.create":({connectionId:Z,database:Q,name:X,description:B,sql:W})=>{if(!X||!X.trim())throw Error("Bookmark name is required");return $.createBookmark({connectionId:Z,database:Q,name:X.trim(),description:B,sql:W})},"bookmarks.update":({id:Z,name:Q,description:X,sql:B})=>{if(!Z)throw Error("Bookmark id is required");if(!Q||!Q.trim())throw Error("Bookmark name is required");return $.updateBookmark({id:Z,name:Q.trim(),description:X,sql:B})},"bookmarks.delete":({id:Z})=>{$.deleteBookmark(Z)},"settings.getAll":()=>{return $.getAllSettings()},"settings.set":({key:Z,value:Q})=>{$.setSetting(Z,Q)},"storage.encrypt":async({config:Z})=>{if(!$.encrypt)throw Error("Encryption not available");return{encryptedConfig:await $.encrypt(Z)}},"ai.generateSql":async(Z)=>{return $.generateSql(Z)},"workspace.save":({data:Z})=>{$.saveWorkspace(Z)},"workspace.load":()=>{return $.loadWorkspace()},"system.showOpenDialog":async(Z)=>{if(!$.showOpenDialog)return{paths:[],cancelled:!0};return $.showOpenDialog(Z)},"system.showSaveDialog":async(Z)=>{if(!$.showSaveDialog)return{path:null,cancelled:!0};return $.showSaveDialog(Z)},"demo.initialize":async()=>{if(!$.initializeDemo)throw Error("Demo initialization is not available");return $.initializeDemo()}}}function t7($){if(!$)throw Error("AppDatabase is required");return $}function l5($,Z,Q,X,B){let W=t7(Q),Y=Z??new c($,void 0,W),G=new T0($,W),H=new y0($,Y,W,{encryption:B?.encryption,Utils:X,emitMessage:B?.emitMessage,sessionManager:G,demoDbSourcePath:B?.demoDbSourcePath,demoDbTargetPath:B?.demoDbTargetPath});return{handlers:m5(H),sessionManager:G,adapter:H}}var d5=M(()=>{x0();D5();p5()});class v0{inner;constructor($){this.inner=$}log($,Z,Q,X){let B=$.replace(/\s+/g," ").trim(),W=Z&&Z.length>0;if(X)console.debug(`[SQL ERROR] ${B}${W?` -- params: ${JSON.stringify(Z)}`:""} (${Q}ms)`,X);else if(Q!==void 0)console.debug(`[SQL] ${B}${W?` -- params: ${JSON.stringify(Z)}`:""} (${Q}ms)`);else console.debug(`[SQL] ${B}${W?` -- params: ${JSON.stringify(Z)}`:""}`)}async execute($,Z,Q){let X=performance.now();try{let B=await this.inner.execute($,Z,Q);return this.log($,Z,Math.round(performance.now()-X)),B}catch(B){throw this.log($,Z,Math.round(performance.now()-X),B),B}}async*iterate($,Z,Q,X,B){this.log($,Z),yield*this.inner.iterate($,Z,Q,X,B)}async importBatch($,Z,Q,X){let B=`INSERT INTO ${$} (${Z.join(", ")}) VALUES ... [${Q.length} rows]`,W=performance.now();try{let Y=await this.inner.importBatch($,Z,Q,X);return this.log(B,void 0,Math.round(performance.now()-W)),Y}catch(Y){throw this.log(B,void 0,Math.round(performance.now()-W),Y),Y}}connect($){return this.inner.connect($)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession($){return this.inner.reserveSession($)}releaseSession($){return this.inner.releaseSession($)}getSessionIds(){return this.inner.getSessionIds()}cancel($){return this.inner.cancel($)}loadSchema($){return this.inner.loadSchema($)}beginTransaction($){return this.inner.beginTransaction($)}commit($){return this.inner.commit($)}rollback($){return this.inner.rollback($)}inTransaction($){return this.inner.inTransaction($)}getDriverType(){return this.inner.getDriverType()}quoteIdentifier($){return this.inner.quoteIdentifier($)}qualifyTable($,Z){return this.inner.qualifyTable($,Z)}emptyInsertSql($){return this.inner.emptyInsertSql($)}placeholder($){return this.inner.placeholder($)}}function h0($){let Z=$ instanceof Error?$.message:String($),Q=$?.code;if(/ECONNREFUSED|connection refused/i.test(Z))return new k("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new k("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new k("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections|connection limit/i.test(Z))return new k("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new k("SSL_ERROR",Z,{cause:$});if(Q?.startsWith("28")||/authentication failed|password authentication/i.test(Z))return new e(Z,{cause:$});if(Q==="3D000"||/database .* does not exist/i.test(Z))return new k("DATABASE_NOT_FOUND",Z,{cause:$});if(Q==="23505"||/violates unique constraint|duplicate key/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(Q==="23503"||/violates foreign key constraint/i.test(Z))return new C("CONSTRAINT_FK",Z,{cause:$});if(Q==="23514"||/violates check constraint/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(Q==="23502"||/violates not-null constraint/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(Q==="42601"||/syntax error/i.test(Z))return new D("QUERY_SYNTAX",Z,{cause:$});if(Q==="42P01"||/relation .* does not exist/i.test(Z))return new D("TABLE_NOT_FOUND",Z,{cause:$});if(Q==="42703"||/column .* does not exist/i.test(Z))return new D("COLUMN_NOT_FOUND",Z,{cause:$});if(Q==="42501"||/permission denied/i.test(Z))return new L("PERMISSION_DENIED",Z,{cause:$});if(Q?.startsWith("42")||Q?.startsWith("22"))return new D("QUERY_EXECUTION",Z,{cause:$});return new L("UNKNOWN",Z,{cause:$})}function b0($){let Z=$ instanceof Error?$.message:String($);if(/unable to open database|cannot open/i.test(Z))return new k("CONNECTION_REFUSED",Z,{cause:$});if(/UNIQUE constraint failed/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(/FOREIGN KEY constraint failed/i.test(Z))return new C("CONSTRAINT_FK",Z,{cause:$});if(/CHECK constraint failed/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(/NOT NULL constraint failed/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(/no such table/i.test(Z))return new D("TABLE_NOT_FOUND",Z,{cause:$});if(/no such column/i.test(Z))return new D("COLUMN_NOT_FOUND",Z,{cause:$});if(/syntax error|near /i.test(Z))return new D("QUERY_SYNTAX",Z,{cause:$});if(/authorization denied|not authorized/i.test(Z))return new L("PERMISSION_DENIED",Z,{cause:$});return new L("UNKNOWN",Z,{cause:$})}function w0($){let Z=$ instanceof Error?$.message:String($),Q=$?.errno;if(/ECONNREFUSED|connection refused/i.test(Z)||Q===2003)return new k("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new k("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new k("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections/i.test(Z)||Q===1040)return new k("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new k("SSL_ERROR",Z,{cause:$});if(Q===1045||/access denied/i.test(Z))return new e(Z,{cause:$});if(Q===1049||/unknown database/i.test(Z))return new k("DATABASE_NOT_FOUND",Z,{cause:$});if(Q===1062||/duplicate entry/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(Q===1451||Q===1452||/foreign key constraint/i.test(Z)||/cannot delete or update a parent row/i.test(Z)||/cannot add or update a child row/i.test(Z))return new C("CONSTRAINT_FK",Z,{cause:$});if(Q===3819||/check constraint/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(Q===1048||/cannot be null/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(Q===1064||/syntax error|you have an error in your sql syntax/i.test(Z))return new D("QUERY_SYNTAX",Z,{cause:$});if(Q===1146||/table .* doesn't exist/i.test(Z))return new D("TABLE_NOT_FOUND",Z,{cause:$});if(Q===1054||/unknown column/i.test(Z))return new D("COLUMN_NOT_FOUND",Z,{cause:$});if(Q===1142||Q===1143||/command denied|access denied/i.test(Z))return new L("PERMISSION_DENIED",Z,{cause:$});return new L("UNKNOWN",Z,{cause:$})}var B0=M(()=>{q()});function p($){let Z=$;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;return 0}var{SQL:n7}=globalThis.Bun;function o7($){switch($.toLowerCase()){case"int":case"integer":case"bigint":case"smallint":case"tinyint":case"mediumint":return"integer";case"float":case"double":return"float";case"decimal":case"numeric":return"numeric";case"bit":case"boolean":case"bool":return"boolean";case"text":case"tinytext":case"mediumtext":case"longtext":return"text";case"varchar":return"varchar";case"char":return"char";case"date":return"date";case"time":return"time";case"datetime":case"timestamp":return"timestamp";case"json":return"json";case"binary":case"varbinary":case"blob":case"tinyblob":case"mediumblob":case"longblob":return"binary";case"enum":case"set":return"enum";default:return"unknown"}}class g0{db=null;connected=!1;sessions=new Map;poolActiveQuery=null;async connect($){if($.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let Z=`mysql://${encodeURIComponent($.user)}:${encodeURIComponent($.password)}@${$.host}:${$.port}/${encodeURIComponent($.database)}`;this.db=new n7({url:Z});try{await this.db`SELECT 1`}catch(Q){throw this.db=null,Q instanceof L?Q:w0(Q)}this.connected=!0}async disconnect(){for(let[,$]of this.sessions){if($.txActive)try{await $.conn.unsafe("ROLLBACK")}catch{}$.conn.release()}if(this.sessions.clear(),this.db)await this.db.close(),this.db=null,this.connected=!1}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=await this.db.reserve();this.sessions.set($,{conn:Z,txActive:!1,activeQuery:null})}async releaseSession($){let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);if(Z.txActive)try{await Z.conn.unsafe("ROLLBACK")}catch{}Z.conn.release(),this.sessions.delete($)}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==S)}async execute($,Z,Q){this.ensureConnected();let X=this.resolveSession(Q),B=X?X.conn:this.db,W=performance.now(),Y=B.unsafe($,Z??[]);if(X)X.activeQuery=Y;else this.poolActiveQuery=Y;try{let G=await Y,H=Math.round(performance.now()-W),V=[...G];return{columns:V.length>0?Object.keys(V[0]).map((j)=>({name:j,dataType:"unknown"})):[],rows:V,rowCount:V.length,affectedRows:p(G),durationMs:H}}catch(G){throw G instanceof L?G:w0(G)}finally{if(X)X.activeQuery=null;else this.poolActiveQuery=null}}async cancel($){if($){let Z=this.sessions.get($);if(Z?.activeQuery)Z.activeQuery.cancel(),Z.activeQuery=null}else if(this.poolActiveQuery)this.poolActiveQuery.cancel(),this.poolActiveQuery=null}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),Q=Z?Z.conn:this.db,X=await this.getSchemas(),B=X.map((z)=>z.name),W={};for(let z of X)W[z.name]=await this.getTables(z.name);let[Y,G,H,V]=await Promise.all([Q.unsafe(`SELECT
|
|
125
|
+
Request: ${Z.prompt}`}]})});if(!X.ok){let Y=await X.text().catch(()=>"");if(X.status===401)throw Error("Invalid API key. Check your AI settings.");if(X.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`OpenAI API error (${X.status}): ${Y.slice(0,200)}`)}let W=await X.json();return b0(W.choices?.[0]?.message?.content??"")}async function d5($,Z){if(!$.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return h0($,Z)}function b0($){let Z=$.trim(),Q=Z.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(Q)Z=Q[1].trim();return Z}async function w0($,Z){if(!$.apiKey)throw Error("AI API key not configured. Go to AI Settings (command palette) to set it up.");switch($.provider){case"anthropic":return l5($,Z);case"openai":return h0($,Z);case"custom":return d5($,Z);default:throw Error(`Unknown AI provider: ${$.provider}`)}}function c5($){return $.dataType!=="binary"}async function f0($,Z,Q,B){let X=performance.now(),W=await $.loadSchema(),Y=[];for(let[J,A]of Object.entries(W.tables)){if(Z.scope==="schema"&&Z.schemaName&&J!==Z.schemaName)continue;for(let K of A){if(K.type!=="table")continue;if(Z.scope==="tables"&&Z.tableNames){if(!Z.tableNames.includes(K.name))continue}Y.push(K)}}let G=[],H=0,V=0,U=$.getDriverType()==="postgresql",j=U?"ILIKE":"LIKE";for(let J of Y){if(B())return{matches:G,searchedTables:V,totalMatches:H,cancelled:!0,elapsedMs:Math.round(performance.now()-X)};Q(J.name,V,Y.length);let A=`${J.schema}.${J.name}`,R=(W.columns[A]??[]).filter(c5);if(R.length===0){V++;continue}let z=[],O=[],L=0;for(let P of R){L++;let d=$.quoteIdentifier(P.name);z.push(`CAST(${d} AS TEXT) ${j} ${$.placeholder(L)}`),O.push(`%${Z.searchTerm}%`)}let F=$.qualifyTable(J.schema,J.name);L++;let x=$.placeholder(L),N=`SELECT * FROM ${F} WHERE ${z.join(" OR ")} LIMIT ${x}`;O.push(Z.resultsPerTable);try{let P=await $.execute(N,O);for(let d of P.rows){let v=d;for(let r$ of R){let a$=v[r$.name];if(a$==null)continue;let s$=String(a$);if(U?s$.toLowerCase().includes(Z.searchTerm.toLowerCase()):s$.toLowerCase().includes(Z.searchTerm.toLowerCase())){G.push({schema:J.schema,table:J.name,column:r$.name,row:v}),H++;break}}}}catch(P){console.debug(`Search: skipped ${J.schema}.${J.name}:`,P instanceof Error?P.message:P)}V++}return{matches:G,searchedTables:V,totalMatches:H,cancelled:!1,elapsedMs:Math.round(performance.now()-X)}}var g0=M(()=>{g()});function n5($){let Z=[],Q=0;while(Q<$.length){let B=$[Q];if(B==="'"||B==='"'){let X=B,W=B;Q++;while(Q<$.length)if($[Q]===X)if(W+=$[Q],Q++,Q<$.length&&$[Q]===X)W+=$[Q],Q++;else break;else W+=$[Q],Q++;Z.push({type:"string",value:W,upper:W});continue}if(/\s/.test(B)){let X="";while(Q<$.length&&/\s/.test($[Q]))X+=$[Q],Q++;Z.push({type:"whitespace",value:X,upper:X});continue}if(/[a-zA-Z_]/.test(B)){let X="";while(Q<$.length&&/[a-zA-Z0-9_]/.test($[Q]))X+=$[Q],Q++;Z.push({type:"word",value:X,upper:X.toUpperCase()});continue}Z.push({type:"symbol",value:B,upper:B}),Q++}return Z}function o5($,Z,Q){let B=Q.split(" "),X=Z,W=0;while(W<B.length&&X<$.length){if($[X].type==="whitespace"){X++;continue}if($[X].upper!==B[W])return 0;W++,X++}return W===B.length?X-Z:0}function p0($){let Z=$.trim();if(!Z)return"";let Q=n5(Z);for(let H of Q)if(H.type==="word"){if(t5.includes(H.upper))H.value=H.upper}let B=[],X="",W=0,Y=0;while(W<Q.length){let H=Q[W];if(H.type==="symbol"&&H.value==="("){Y++,X+=H.value,W++;continue}if(H.type==="symbol"&&H.value===")"){if(Y>0)Y--;X+=H.value,W++;continue}if(Y>0){X+=H.value,W++;continue}if(H.type==="word"){let V=!1,U=[...I0,...u0].sort((j,J)=>J.split(" ").length-j.split(" ").length);for(let j of U){let J=o5(Q,W,j);if(J>0){let A=[];for(let O=W;O<W+J;O++)A.push(Q[O].value);let K=A.filter((O)=>O.trim()).join(" "),R=u0.includes(j);if(I0.includes(j)||R){let O=X.trimEnd();if(O)B.push(O);X=K}else X+=K;W+=J,V=!0;break}}if(V)continue;if(i5.includes(H.upper)){let j=X.trimEnd();if(j)B.push(j);X=" "+H.value,W++;continue}}if(H.type==="whitespace"){if(X.trimEnd())X+=" "}else X+=H.value;W++}let G=X.trimEnd();if(G)B.push(G);return B.join(`
|
|
126
|
+
`)}var I0,u0,i5,t5;var m0=M(()=>{I0=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],u0=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],i5=["ON","AND","OR"],t5=["SELECT","DISTINCT","FROM","WHERE","AND","OR","NOT","IN","EXISTS","BETWEEN","LIKE","ILIKE","IS","NULL","TRUE","FALSE","AS","ON","USING","JOIN","INNER","LEFT","RIGHT","FULL","OUTER","CROSS","NATURAL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","INTERSECT","EXCEPT","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","PRIMARY","KEY","FOREIGN","REFERENCES","UNIQUE","CHECK","DEFAULT","CONSTRAINT","CASCADE","RESTRICT","BEGIN","COMMIT","ROLLBACK","TRANSACTION","CASE","WHEN","THEN","ELSE","END","ASC","DESC","NULLS","FIRST","LAST","COUNT","SUM","AVG","MIN","MAX","CAST","COALESCE","NULLIF","WITH","RECURSIVE","RETURNING"]});class v${cm;constructor($){this.cm=$}async begin($,Z,Q){let B=this.cm.getDriver($,Z);if(B.inTransaction(Q))throw Error("Transaction already active on this connection");await B.beginTransaction(Q)}async commit($,Z,Q){let B=this.cm.getDriver($,Z);if(!B.inTransaction(Q))throw Error("No active transaction to commit");await B.commit(Q)}async rollback($,Z,Q){let B=this.cm.getDriver($,Z);if(!B.inTransaction(Q))throw Error("No active transaction to rollback");await B.rollback(Q)}isActive($,Z,Q){try{return this.cm.getDriver($,Z).inTransaction(Q)}catch{return!1}}async rollbackIfActive($,Z,Q){if(this.isActive($,Z,Q))await this.rollback($,Z,Q)}}class h${cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;constructor($,Z,Q,B){this.cm=$;this.queryExecutor=Z;this.appDb=Q;this.txManager=new v$($),this.encryption=B?.encryption,this.Utils=B?.Utils,this.emitMessage=B?.emitMessage,this.sessionManager=B?.sessionManager,this.demoDbSourcePath=B?.demoDbSourcePath,this.demoDbTargetPath=B?.demoDbTargetPath}listConnections(){return this.cm.listConnections()}createConnection($){return this.cm.createConnection($)}updateConnection($){return this.cm.updateConnection($)}setConnectionReadOnly($,Z){return this.cm.setConnectionReadOnly($,Z)}setConnectionGroup($,Z){return this.appDb.setConnectionGroup($,Z)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup($,Z){this.appDb.renameConnectionGroup($,Z)}deleteConnectionGroup($){this.appDb.deleteConnectionGroup($)}async deleteConnection($){await this.cm.deleteConnection($)}async testConnection($){return this.cm.testConnection($)}async connect($,Z,Q,B){if(Q&&this.encryption){let X=await this.encryption.decrypt(Q),W=JSON.parse(X),Y=this.appDb.getConnectionById($);if(!Y)this.appDb.createConnectionWithId($,{name:B??$,config:W});else this.appDb.updateConnection({id:$,name:B??Y.name,config:W})}await this.cm.connect($,Z?{password:Z}:void 0)}async disconnect($){await this.cm.disconnect($)}async createSession($,Z){if(!this.sessionManager)throw Error("SessionManager not available");let Q=await this.sessionManager.createSession($,Z);return this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)}),Q}async destroySession($){if(!this.sessionManager)throw Error("SessionManager not available");let Z=this.sessionManager.getSession($);if(await this.sessionManager.destroySession($),Z)this.emitMessage?.("session.changed",{connectionId:Z.connectionId,sessions:this.sessionManager.listSessions(Z.connectionId)})}listSessions($){if(!this.sessionManager)return[];return this.sessionManager.listSessions($)}getDriver($,Z){return this.cm.getDriver($,Z)}async listDatabases($){return this.cm.listDatabases($)}async activateDatabase($,Z){await this.cm.activateDatabase($,Z)}async deactivateDatabase($,Z){await this.cm.deactivateDatabase($,Z)}async executeQuery($,Z,Q,B,X,W,Y){return this.queryExecutor.executeQuery($,Z,Q,void 0,B,X,W,Y)}async executeStatements($,Z,Q,B){let X=this.cm.getDriver($,Q),W=X.inTransaction(B);if(!W)await X.beginTransaction(B);try{let Y=[];for(let G of Z){let H=performance.now(),V=B!==void 0?await X.execute(G.sql,G.params,B):await X.execute(G.sql,G.params);Y.push({...V,durationMs:Math.round(performance.now()-H)})}if(!W)await X.commit(B);return Y}catch(Y){if(!W)try{await X.rollback(B)}catch(G){console.debug("Rollback after error failed:",G instanceof Error?G.message:G)}throw Y}}async cancelQuery($){await this.queryExecutor.cancelQuery($)}async explainQuery($,Z,Q,B,X,W){return this.queryExecutor.explainQuery($,Z,Q,B,X,W)}async beginTransaction($,Z,Q){await this.txManager.begin($,Z,Q)}async commitTransaction($,Z,Q){await this.txManager.commit($,Z,Q),this.queryExecutor.sessionLog.resetPendingCount($,Z)}async rollbackTransaction($,Z,Q){await this.txManager.rollback($,Z,Q),this.queryExecutor.sessionLog.resetPendingCount($,Z)}getTransactionLog($){let Z=this.queryExecutor.sessionLog.getEntries($.connectionId,$.database);if($.statusFilter)Z=Z.filter((X)=>X.status===$.statusFilter);if($.search){let X=$.search.toLowerCase();Z=Z.filter((W)=>W.sql.toLowerCase().includes(X))}let Q=this.txManager.isActive($.connectionId,$.database,$.sessionId),B=Q?this.queryExecutor.sessionLog.getPendingCount($.connectionId,$.database):0;return{entries:Z,pendingStatementCount:B,inTransaction:Q}}clearTransactionLog($,Z,Q){this.queryExecutor.sessionLog.clear($,Z)}listHistory($){return this.appDb.listHistory($)}clearHistory($){this.appDb.clearHistory($)}listSavedViews($,Z,Q){return this.appDb.listSavedViews($,Z,Q)}createSavedView($){return this.appDb.createSavedView($)}updateSavedView($){return this.appDb.updateSavedView($)}deleteSavedView($){this.appDb.deleteSavedView($)}listSavedViewsByConnection($){return this.appDb.listSavedViewsByConnection($)}getSavedViewById($){return this.appDb.getSavedViewById($)}listBookmarks($,Z){return this.appDb.listBookmarks($,Z)}createBookmark($){return this.appDb.createBookmark($)}updateBookmark($){return this.appDb.updateBookmark($)}deleteBookmark($){this.appDb.deleteBookmark($)}async searchDatabase($){let Z=this.cm.getDriver($.connectionId,$.database);return f0(Z,{searchTerm:$.searchTerm,scope:$.scope,schemaName:$.schemaName,tableNames:$.tableNames,resultsPerTable:$.resultsPerTable??50},()=>{},()=>!1)}async exportData($){let Z=this.cm.getDriver($.connectionId,$.database);if(!$.filePath)throw Error("Export requires a file path");let Q=this.emitMessage?(X)=>this.emitMessage("export.progress",{rowCount:X}):void 0;return{...await K0(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,includeHeaders:$.includeHeaders,delimiter:$.delimiter,encoding:$.encoding,utf8Bom:$.utf8Bom,batchSize:$.batchSize,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins},$.filePath,void 0,Q),filePath:$.filePath}}async exportPreview($){let Z=this.cm.getDriver($.connectionId,$.database);return z0(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,delimiter:$.delimiter,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins})}async exportPreviewRows($){let Z=this.cm.getDriver($.connectionId,$.database),{sql:Q,params:B}=r({schema:$.schema,table:$.table,format:"csv",columns:$.columns,filters:$.filters,sort:$.sort,autoJoins:$.autoJoins},Z),X=B.length+1,W=`${Q} LIMIT ${Z.placeholder(X)}`,G=(await Z.execute(W,[...B,$.limit])).rows,H=G.length>0?Object.keys(G[0]):$.columns??[];return{rows:G,columns:H}}async importData($){let Z=this.cm.getDriver($.connectionId,$.database),Q=this.resolveImportStream($.filePath,$.fileContent),B=this.emitMessage?(X)=>this.emitMessage("import.progress",{rowCount:X}):void 0;return s(Z,Q,{schema:$.schema,table:$.table,format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,mappings:$.mappings,batchSize:$.batchSize},void 0,B)}async importPreview($){let Z=this.resolveImportPreviewStream($.filePath,$.fileContent),Q=await L0(Z,{format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,limit:$.limit});if($.filePath)try{let B=Bun.file($.filePath);Q.fileSizeBytes=B.size}catch{}return Q}resolveImportStream($,Z){if($)return Bun.file($).stream();if(Z!==void 0)return new ReadableStream({start(Q){Q.enqueue(new TextEncoder().encode(Z)),Q.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream($,Z){if($){let X=Bun.file($).stream().getReader(),W=65536,Y=0;return new ReadableStream({async pull(G){let{done:H,value:V}=await X.read();if(H){G.close();return}if(Y+=V.byteLength,Y>=65536){G.enqueue(V),G.close(),X.releaseLock();return}G.enqueue(V)},cancel(){X.releaseLock()}})}if(Z!==void 0)return new ReadableStream({start(Q){Q.enqueue(new TextEncoder().encode(Z)),Q.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting($,Z){this.appDb.setSetting($,Z)}async encrypt($){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt($)}async showOpenDialog({filters:$,multiple:Z}){if(!this.Utils)throw Error("Utils not available");let Q=$&&$.length>0?$.flatMap((W)=>W.extensions.map((Y)=>`*.${Y}`)).join(","):"*",X=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:Q,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:Z??!1})).filter((W)=>W!=="");return{paths:X,cancelled:X.length===0}}async showSaveDialog({defaultName:$}){if(!this.Utils)throw Error("Utils not available");let Q=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!Q||Q==="")return{path:null,cancelled:!0};return{path:$?`${Q}/${$}`:Q,cancelled:!1}}formatSql($){return p0($)}async generateSql($){let Z=this.cm.getDriver($.connectionId,$.database),Q=await Z.loadSchema(),B=v0(Q),X=q0(this.appDb.getAllSettings());return{sql:await w0(X,{prompt:$.prompt,schemaContext:B,dialect:Z.getDriverType()})}}saveWorkspace($){this.appDb.saveWorkspace($)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let $=Bun.file(this.demoDbSourcePath);if(!await $.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,$);let Z={type:"sqlite",path:this.demoDbTargetPath},Q=this.appDb.createConnection({name:"Bookstore (Demo)",config:Z});return await this.cm.connect(Q.id),Q}getSessionManager(){return this.sessionManager}}var l0=M(()=>{y0();R$();L$();g0();m0()});function d0($){return{"connections.list":()=>{return $.listConnections()},"connections.create":({name:Z,config:Q,readOnly:B,color:X,groupName:W})=>{return $.createConnection({name:Z,config:Q,readOnly:B,color:X,groupName:W})},"connections.update":({id:Z,name:Q,config:B,readOnly:X,color:W,groupName:Y})=>{return $.updateConnection({id:Z,name:Q,config:B,readOnly:X,color:W,groupName:Y})},"connections.setReadOnly":({id:Z,readOnly:Q})=>{return $.setConnectionReadOnly(Z,Q)},"connections.setGroup":({id:Z,groupName:Q})=>{return $.setConnectionGroup(Z,Q)},"connections.listGroups":()=>{return $.listConnectionGroups()},"connections.renameGroup":({oldName:Z,newName:Q})=>{$.renameConnectionGroup(Z,Q)},"connections.deleteGroup":({groupName:Z})=>{$.deleteConnectionGroup(Z)},"connections.delete":async({id:Z})=>{await $.deleteConnection(Z)},"connections.test":async({config:Z})=>{return $.testConnection(Z)},"connections.connect":async({connectionId:Z,password:Q,encryptedConfig:B,name:X})=>{await $.connect(Z,Q,B,X)},"connections.disconnect":async({connectionId:Z})=>{await $.disconnect(Z)},"session.create":async({connectionId:Z,database:Q})=>{return $.createSession(Z,Q)},"session.destroy":async({sessionId:Z})=>{await $.destroySession(Z)},"session.list":({connectionId:Z})=>{return $.listSessions(Z)},"databases.list":async({connectionId:Z})=>{return $.listDatabases(Z)},"databases.activate":async({connectionId:Z,database:Q})=>{await $.activateDatabase(Z,Q)},"databases.deactivate":async({connectionId:Z,database:Q})=>{await $.deactivateDatabase(Z,Q)},"schema.load":async({connectionId:Z,database:Q,sessionId:B})=>{return $.getDriver(Z,Q).loadSchema(B)},"query.execute":async({connectionId:Z,sql:Q,queryId:B,params:X,database:W,statements:Y,sessionId:G,searchPath:H})=>{if(Y&&Y.length>0)return $.executeStatements(Z,Y,W,G);return $.executeQuery(Z,Q,X,B,W,G,H)},"query.cancel":async({queryId:Z})=>{await $.cancelQuery(Z)},"query.format":({sql:Z})=>{return{sql:$.formatSql(Z)}},"query.explain":async({connectionId:Z,sql:Q,analyze:B,database:X,sessionId:W,searchPath:Y})=>{return $.explainQuery(Z,Q,B??!1,X,W,Y)},"tx.begin":async({connectionId:Z,database:Q,sessionId:B})=>{await $.beginTransaction(Z,Q,B)},"tx.commit":async({connectionId:Z,database:Q,sessionId:B})=>{await $.commitTransaction(Z,Q,B)},"tx.rollback":async({connectionId:Z,database:Q,sessionId:B})=>{await $.rollbackTransaction(Z,Q,B)},"transaction.getLog":(Z)=>{return $.getTransactionLog(Z)},"transaction.clearLog":({connectionId:Z,database:Q,sessionId:B})=>{$.clearTransactionLog(Z,Q,B)},"search.searchDatabase":async(Z)=>{return $.searchDatabase(Z)},"export.exportData":async(Z)=>{return $.exportData(Z)},"export.preview":async(Z)=>{return{content:await $.exportPreview(Z)}},"export.previewRows":async(Z)=>{return $.exportPreviewRows(Z)},"import.importData":async(Z)=>{return $.importData(Z)},"import.preview":async(Z)=>{return $.importPreview(Z)},"history.list":(Z)=>{return $.listHistory(Z)},"history.clear":({connectionId:Z})=>{$.clearHistory(Z)},"views.save":({connectionId:Z,schemaName:Q,tableName:B,name:X,config:W})=>{if(!X||!X.trim())throw Error("View name is required");if(!Z)throw Error("connectionId is required");if(!B)throw Error("tableName is required");if($.listSavedViews(Z,Q,B).some((G)=>G.name===X.trim()))throw Error(`A view named "${X.trim()}" already exists for this table`);return $.createSavedView({connectionId:Z,schemaName:Q,tableName:B,name:X.trim(),config:W})},"views.update":({id:Z,name:Q,config:B})=>{if(!Z)throw Error("View id is required");if(!Q||!Q.trim())throw Error("View name is required");let X=$.getSavedViewById(Z);if(!X)throw Error(`Saved view not found: ${Z}`);if($.listSavedViews(X.connectionId,X.schemaName,X.tableName).some((Y)=>Y.id!==Z&&Y.name===Q.trim()))throw Error(`A view named "${Q.trim()}" already exists for this table`);return $.updateSavedView({id:Z,name:Q.trim(),config:B})},"views.delete":({id:Z})=>{$.deleteSavedView(Z)},"views.listByConnection":({connectionId:Z})=>{return $.listSavedViewsByConnection(Z)},"bookmarks.list":({connectionId:Z,search:Q})=>{return $.listBookmarks(Z,Q)},"bookmarks.create":({connectionId:Z,database:Q,name:B,description:X,sql:W})=>{if(!B||!B.trim())throw Error("Bookmark name is required");return $.createBookmark({connectionId:Z,database:Q,name:B.trim(),description:X,sql:W})},"bookmarks.update":({id:Z,name:Q,description:B,sql:X})=>{if(!Z)throw Error("Bookmark id is required");if(!Q||!Q.trim())throw Error("Bookmark name is required");return $.updateBookmark({id:Z,name:Q.trim(),description:B,sql:X})},"bookmarks.delete":({id:Z})=>{$.deleteBookmark(Z)},"settings.getAll":()=>{return $.getAllSettings()},"settings.set":({key:Z,value:Q})=>{$.setSetting(Z,Q)},"storage.encrypt":async({config:Z})=>{if(!$.encrypt)throw Error("Encryption not available");return{encryptedConfig:await $.encrypt(Z)}},"ai.generateSql":async(Z)=>{return $.generateSql(Z)},"workspace.save":({data:Z})=>{$.saveWorkspace(Z)},"workspace.load":()=>{return $.loadWorkspace()},"system.showOpenDialog":async(Z)=>{if(!$.showOpenDialog)return{paths:[],cancelled:!0};return $.showOpenDialog(Z)},"system.showSaveDialog":async(Z)=>{if(!$.showSaveDialog)return{path:null,cancelled:!0};return $.showSaveDialog(Z)},"demo.initialize":async()=>{if(!$.initializeDemo)throw Error("Demo initialization is not available");return $.initializeDemo()}}}function r5($){if(!$)throw Error("AppDatabase is required");return $}function c0($,Z,Q,B,X){let W=r5(Q),Y=Z??new c($,void 0,W),G=new y$($,W),H=new h$($,Y,W,{encryption:X?.encryption,Utils:B,emitMessage:X?.emitMessage,sessionManager:G,demoDbSourcePath:X?.demoDbSourcePath,demoDbTargetPath:X?.demoDbTargetPath});return{handlers:d0(H),sessionManager:G,adapter:H}}var i0=M(()=>{N$();T0();l0()});class b${inner;constructor($){this.inner=$}log($,Z,Q,B){let X=$.replace(/\s+/g," ").trim(),W=Z&&Z.length>0;if(B)console.debug(`[SQL ERROR] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""} (${Q}ms)`,B);else if(Q!==void 0)console.debug(`[SQL] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""} (${Q}ms)`);else console.debug(`[SQL] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""}`)}async execute($,Z,Q){let B=performance.now();try{let X=await this.inner.execute($,Z,Q);return this.log($,Z,Math.round(performance.now()-B)),X}catch(X){throw this.log($,Z,Math.round(performance.now()-B),X),X}}async*iterate($,Z,Q,B,X){this.log($,Z),yield*this.inner.iterate($,Z,Q,B,X)}async importBatch($,Z,Q,B){let X=`INSERT INTO ${$} (${Z.join(", ")}) VALUES ... [${Q.length} rows]`,W=performance.now();try{let Y=await this.inner.importBatch($,Z,Q,B);return this.log(X,void 0,Math.round(performance.now()-W)),Y}catch(Y){throw this.log(X,void 0,Math.round(performance.now()-W),Y),Y}}connect($){return this.inner.connect($)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession($){return this.inner.reserveSession($)}releaseSession($){return this.inner.releaseSession($)}getSessionIds(){return this.inner.getSessionIds()}cancel($){return this.inner.cancel($)}loadSchema($){return this.inner.loadSchema($)}beginTransaction($){return this.inner.beginTransaction($)}commit($){return this.inner.commit($)}rollback($){return this.inner.rollback($)}inTransaction($){return this.inner.inTransaction($)}getDriverType(){return this.inner.getDriverType()}quoteIdentifier($){return this.inner.quoteIdentifier($)}qualifyTable($,Z){return this.inner.qualifyTable($,Z)}emptyInsertSql($){return this.inner.emptyInsertSql($)}placeholder($){return this.inner.placeholder($)}}function w$($){let Z=$ instanceof Error?$.message:String($),Q=$?.code;if(/ECONNREFUSED|connection refused/i.test(Z))return new C("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new C("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new C("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections|connection limit/i.test(Z))return new C("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new C("SSL_ERROR",Z,{cause:$});if(Q?.startsWith("28")||/authentication failed|password authentication/i.test(Z))return new e(Z,{cause:$});if(Q==="3D000"||/database .* does not exist/i.test(Z))return new C("DATABASE_NOT_FOUND",Z,{cause:$});if(Q==="23505"||/violates unique constraint|duplicate key/i.test(Z))return new E("CONSTRAINT_UNIQUE",Z,{cause:$});if(Q==="23503"||/violates foreign key constraint/i.test(Z))return new E("CONSTRAINT_FK",Z,{cause:$});if(Q==="23514"||/violates check constraint/i.test(Z))return new E("CONSTRAINT_CHECK",Z,{cause:$});if(Q==="23502"||/violates not-null constraint/i.test(Z))return new E("CONSTRAINT_NOT_NULL",Z,{cause:$});if(Q==="42601"||/syntax error/i.test(Z))return new D("QUERY_SYNTAX",Z,{cause:$});if(Q==="42P01"||/relation .* does not exist/i.test(Z))return new D("TABLE_NOT_FOUND",Z,{cause:$});if(Q==="42703"||/column .* does not exist/i.test(Z))return new D("COLUMN_NOT_FOUND",Z,{cause:$});if(Q==="42501"||/permission denied/i.test(Z))return new _("PERMISSION_DENIED",Z,{cause:$});if(Q?.startsWith("42")||Q?.startsWith("22"))return new D("QUERY_EXECUTION",Z,{cause:$});return new _("UNKNOWN",Z,{cause:$})}function f$($){let Z=$ instanceof Error?$.message:String($);if(/unable to open database|cannot open/i.test(Z))return new C("CONNECTION_REFUSED",Z,{cause:$});if(/UNIQUE constraint failed/i.test(Z))return new E("CONSTRAINT_UNIQUE",Z,{cause:$});if(/FOREIGN KEY constraint failed/i.test(Z))return new E("CONSTRAINT_FK",Z,{cause:$});if(/CHECK constraint failed/i.test(Z))return new E("CONSTRAINT_CHECK",Z,{cause:$});if(/NOT NULL constraint failed/i.test(Z))return new E("CONSTRAINT_NOT_NULL",Z,{cause:$});if(/no such table/i.test(Z))return new D("TABLE_NOT_FOUND",Z,{cause:$});if(/no such column/i.test(Z))return new D("COLUMN_NOT_FOUND",Z,{cause:$});if(/syntax error|near /i.test(Z))return new D("QUERY_SYNTAX",Z,{cause:$});if(/authorization denied|not authorized/i.test(Z))return new _("PERMISSION_DENIED",Z,{cause:$});return new _("UNKNOWN",Z,{cause:$})}function g$($){let Z=$ instanceof Error?$.message:String($),Q=$?.errno;if(/ECONNREFUSED|connection refused/i.test(Z)||Q===2003)return new C("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new C("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new C("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections/i.test(Z)||Q===1040)return new C("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new C("SSL_ERROR",Z,{cause:$});if(Q===1045||/access denied/i.test(Z))return new e(Z,{cause:$});if(Q===1049||/unknown database/i.test(Z))return new C("DATABASE_NOT_FOUND",Z,{cause:$});if(Q===1062||/duplicate entry/i.test(Z))return new E("CONSTRAINT_UNIQUE",Z,{cause:$});if(Q===1451||Q===1452||/foreign key constraint/i.test(Z)||/cannot delete or update a parent row/i.test(Z)||/cannot add or update a child row/i.test(Z))return new E("CONSTRAINT_FK",Z,{cause:$});if(Q===3819||/check constraint/i.test(Z))return new E("CONSTRAINT_CHECK",Z,{cause:$});if(Q===1048||/cannot be null/i.test(Z))return new E("CONSTRAINT_NOT_NULL",Z,{cause:$});if(Q===1064||/syntax error|you have an error in your sql syntax/i.test(Z))return new D("QUERY_SYNTAX",Z,{cause:$});if(Q===1146||/table .* doesn't exist/i.test(Z))return new D("TABLE_NOT_FOUND",Z,{cause:$});if(Q===1054||/unknown column/i.test(Z))return new D("COLUMN_NOT_FOUND",Z,{cause:$});if(Q===1142||Q===1143||/command denied|access denied/i.test(Z))return new _("PERMISSION_DENIED",Z,{cause:$});return new _("UNKNOWN",Z,{cause:$})}var X$=M(()=>{q()});function p($){let Z=$;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;return 0}var{SQL:a5}=globalThis.Bun;function s5($){switch($.toLowerCase()){case"int":case"integer":case"bigint":case"smallint":case"tinyint":case"mediumint":return"integer";case"float":case"double":return"float";case"decimal":case"numeric":return"numeric";case"bit":case"boolean":case"bool":return"boolean";case"text":case"tinytext":case"mediumtext":case"longtext":return"text";case"varchar":return"varchar";case"char":return"char";case"date":return"date";case"time":return"time";case"datetime":case"timestamp":return"timestamp";case"json":return"json";case"binary":case"varbinary":case"blob":case"tinyblob":case"mediumblob":case"longblob":return"binary";case"enum":case"set":return"enum";default:return"unknown"}}class I${db=null;connected=!1;sessions=new Map;poolActiveQuery=null;async connect($){if($.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let Z=`mysql://${encodeURIComponent($.user)}:${encodeURIComponent($.password)}@${$.host}:${$.port}/${encodeURIComponent($.database)}`;this.db=new a5({url:Z});try{await this.db`SELECT 1`}catch(Q){throw this.db=null,Q instanceof _?Q:g$(Q)}this.connected=!0}async disconnect(){for(let[,$]of this.sessions){if($.txActive)try{await $.conn.unsafe("ROLLBACK")}catch{}$.conn.release()}if(this.sessions.clear(),this.db)await this.db.close(),this.db=null,this.connected=!1}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=await this.db.reserve();this.sessions.set($,{conn:Z,txActive:!1,activeQuery:null})}async releaseSession($){let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);if(Z.txActive)try{await Z.conn.unsafe("ROLLBACK")}catch{}Z.conn.release(),this.sessions.delete($)}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==S)}async execute($,Z,Q){this.ensureConnected();let B=this.resolveSession(Q),X=B?B.conn:this.db,W=performance.now(),Y=X.unsafe($,Z??[]);if(B)B.activeQuery=Y;else this.poolActiveQuery=Y;try{let G=await Y,H=Math.round(performance.now()-W),V=[...G];return{columns:V.length>0?Object.keys(V[0]).map((j)=>({name:j,dataType:"unknown"})):[],rows:V,rowCount:V.length,affectedRows:p(G),durationMs:H}}catch(G){throw G instanceof _?G:g$(G)}finally{if(B)B.activeQuery=null;else this.poolActiveQuery=null}}async cancel($){if($){let Z=this.sessions.get($);if(Z?.activeQuery)Z.activeQuery.cancel(),Z.activeQuery=null}else if(this.poolActiveQuery)this.poolActiveQuery.cancel(),this.poolActiveQuery=null}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),Q=Z?Z.conn:this.db,B=await this.getSchemas(),X=B.map((K)=>K.name),W={};for(let K of B)W[K.name]=await this.getTables(K.name);let[Y,G,H,V]=await Promise.all([Q.unsafe(`SELECT
|
|
127
127
|
c.TABLE_SCHEMA AS table_schema,
|
|
128
128
|
c.TABLE_NAME AS table_name,
|
|
129
129
|
c.COLUMN_NAME AS column_name,
|
|
@@ -135,17 +135,17 @@ Request: ${Z.prompt}`}]})});if(!B.ok){let Y=await B.text().catch(()=>"");if(B.st
|
|
|
135
135
|
c.COLUMN_KEY AS column_key,
|
|
136
136
|
c.EXTRA AS extra
|
|
137
137
|
FROM information_schema.columns c
|
|
138
|
-
WHERE c.TABLE_SCHEMA IN (${
|
|
139
|
-
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION`,
|
|
138
|
+
WHERE c.TABLE_SCHEMA IN (${X.map(()=>"?").join(",")})
|
|
139
|
+
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION`,X),Q.unsafe(`SELECT
|
|
140
140
|
TABLE_SCHEMA AS table_schema,
|
|
141
141
|
TABLE_NAME AS table_name,
|
|
142
142
|
INDEX_NAME AS index_name,
|
|
143
143
|
NON_UNIQUE AS non_unique,
|
|
144
144
|
GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) AS \`columns\`
|
|
145
145
|
FROM information_schema.STATISTICS
|
|
146
|
-
WHERE TABLE_SCHEMA IN (${
|
|
146
|
+
WHERE TABLE_SCHEMA IN (${X.map(()=>"?").join(",")})
|
|
147
147
|
GROUP BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, NON_UNIQUE
|
|
148
|
-
ORDER BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME`,
|
|
148
|
+
ORDER BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME`,X),Q.unsafe(`SELECT
|
|
149
149
|
kcu.TABLE_SCHEMA AS table_schema,
|
|
150
150
|
kcu.TABLE_NAME AS table_name,
|
|
151
151
|
kcu.CONSTRAINT_NAME AS constraint_name,
|
|
@@ -159,12 +159,12 @@ Request: ${Z.prompt}`}]})});if(!B.ok){let Y=await B.text().catch(()=>"");if(B.st
|
|
|
159
159
|
JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
|
|
160
160
|
ON rc.CONSTRAINT_SCHEMA = kcu.TABLE_SCHEMA
|
|
161
161
|
AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
|
|
162
|
-
WHERE kcu.TABLE_SCHEMA IN (${
|
|
162
|
+
WHERE kcu.TABLE_SCHEMA IN (${X.map(()=>"?").join(",")})
|
|
163
163
|
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
|
|
164
164
|
GROUP BY kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME,
|
|
165
165
|
kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME,
|
|
166
166
|
rc.UPDATE_RULE, rc.DELETE_RULE
|
|
167
|
-
ORDER BY kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME`,
|
|
167
|
+
ORDER BY kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME`,X),Q.unsafe(`SELECT
|
|
168
168
|
kcu.REFERENCED_TABLE_SCHEMA AS referenced_schema,
|
|
169
169
|
kcu.REFERENCED_TABLE_NAME AS referenced_table,
|
|
170
170
|
kcu.CONSTRAINT_NAME AS constraint_name,
|
|
@@ -173,14 +173,14 @@ Request: ${Z.prompt}`}]})});if(!B.ok){let Y=await B.text().catch(()=>"");if(B.st
|
|
|
173
173
|
GROUP_CONCAT(kcu.COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION) AS referencing_columns,
|
|
174
174
|
GROUP_CONCAT(kcu.REFERENCED_COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION) AS referenced_columns
|
|
175
175
|
FROM information_schema.KEY_COLUMN_USAGE kcu
|
|
176
|
-
WHERE kcu.REFERENCED_TABLE_SCHEMA IN (${
|
|
176
|
+
WHERE kcu.REFERENCED_TABLE_SCHEMA IN (${X.map(()=>"?").join(",")})
|
|
177
177
|
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
|
|
178
178
|
GROUP BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME,
|
|
179
179
|
kcu.CONSTRAINT_NAME, kcu.TABLE_SCHEMA, kcu.TABLE_NAME
|
|
180
|
-
ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,
|
|
180
|
+
ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,X)]),U={};for(let K of Y){let R=`${K.table_schema}.${K.table_name}`;if(!U[R])U[R]=[];U[R].push({name:K.column_name,dataType:s5(K.data_type),nullable:K.is_nullable==="YES",defaultValue:K.column_default,isPrimaryKey:K.column_key==="PRI",isAutoIncrement:(K.extra??"").includes("auto_increment"),maxLength:K.character_maximum_length??void 0})}let j={};for(let K of G){let R=`${K.table_schema}.${K.table_name}`;if(!j[R])j[R]=[];j[R].push({name:K.index_name,columns:typeof K.columns==="string"?K.columns.split(","):[K.columns],isUnique:K.non_unique===0||K.non_unique==="0",isPrimary:K.index_name==="PRIMARY"})}let J={};for(let K of H){let R=`${K.table_schema}.${K.table_name}`;if(!J[R])J[R]=[];J[R].push({name:K.constraint_name,columns:typeof K.columns==="string"?K.columns.split(","):[K.columns],referencedSchema:K.referenced_schema,referencedTable:K.referenced_table,referencedColumns:typeof K.referenced_columns==="string"?K.referenced_columns.split(","):[K.referenced_columns],onUpdate:K.on_update,onDelete:K.on_delete})}let A={};for(let K of V){let R=`${K.referenced_schema}.${K.referenced_table}`;if(!A[R])A[R]=[];A[R].push({constraintName:K.constraint_name,referencingSchema:K.referencing_schema,referencingTable:K.referencing_table,referencingColumns:typeof K.referencing_columns==="string"?K.referencing_columns.split(","):[K.referencing_columns],referencedColumns:typeof K.referenced_columns==="string"?K.referenced_columns.split(","):[K.referenced_columns]})}for(let K of B)for(let R of W[K.name]){let z=`${K.name}.${R.name}`;if(!U[z])U[z]=[];if(!j[z])j[z]=[];if(!J[z])J[z]=[];if(!A[z])A[z]=[]}return{schemas:B,tables:W,columns:U,indexes:j,foreignKeys:J,referencingForeignKeys:A}}async getSchemas(){return this.ensureConnected(),[...await this.db.unsafe("SELECT DATABASE() AS name")]}async getTables($){return this.ensureConnected(),[...await this.db.unsafe(`SELECT table_name AS name, table_type
|
|
181
181
|
FROM information_schema.tables
|
|
182
182
|
WHERE table_schema = ?
|
|
183
|
-
ORDER BY table_name`,[$])].map((
|
|
183
|
+
ORDER BY table_name`,[$])].map((B)=>({schema:$,name:B.name,type:B.table_type==="VIEW"?"view":"table"}))}async*iterate($,Z,Q=1000,B,X){this.ensureConnected();let W=this.resolveSession(X),Y=W?W.conn:this.db,G=0;while(!0){if(B?.aborted)throw new DOMException("Aborted","AbortError");let H=`${$} LIMIT ? OFFSET ?`,U=[...await Y.unsafe(H,[...Z??[],Q,G])];if(U.length===0)break;if(yield U,U.length<Q)break;G+=Q}}async importBatch($,Z,Q,B){if(this.ensureConnected(),Q.length===0)return 0;let X=Z.map((V)=>this.quoteIdentifier(V)).join(", "),W=[],Y=[];for(let V=0;V<Q.length;V++){let U=[];for(let j=0;j<Z.length;j++)W.push(Q[V][Z[j]]),U.push(this.placeholder(W.length));Y.push(`(${U.join(", ")})`)}let G=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(G,W,B)).affectedRows??Q.length}async beginTransaction($){if(this.ensureConnected(),$){let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);await Z.conn.unsafe("START TRANSACTION"),Z.txActive=!0}else{let Z=await this.db.reserve();try{await Z.unsafe("START TRANSACTION")}catch(Q){throw Z.release(),Q}this.sessions.set(S,{conn:Z,txActive:!0,activeQuery:null})}}async commit($){this.ensureConnected();let Z=$??S,Q=this.sessions.get(Z);if(!Q)throw Error("No active transaction");if(await Q.conn.unsafe("COMMIT"),Q.txActive=!1,Z===S)Q.conn.release(),this.sessions.delete(S)}async rollback($){this.ensureConnected();let Z=$??S,Q=this.sessions.get(Z);if(!Q)throw Error("No active transaction");if(await Q.conn.unsafe("ROLLBACK"),Q.txActive=!1,Z===S)Q.conn.release(),this.sessions.delete(S)}inTransaction($){let Z=$??S;return this.sessions.get(Z)?.txActive??!1}getDriverType(){return"mysql"}quoteIdentifier($){return`\`${$.replace(/`/g,"``")}\``}qualifyTable($,Z){return`${this.quoteIdentifier($)}.${this.quoteIdentifier(Z)}`}emptyInsertSql($){return`INSERT INTO ${$} () VALUES ()`}placeholder($){return"?"}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}resolveSession($){if(!$)return this.sessions.get(S);let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);return Z}}var S="__default__";var t0=M(()=>{g();q();X$()});var{SQL:e5}=globalThis.Bun;function $7($){switch($.toLowerCase()){case"integer":case"bigint":case"smallint":return"integer";case"serial":case"bigserial":case"smallserial":return"serial";case"real":case"double precision":return"float";case"numeric":case"decimal":case"money":return"numeric";case"boolean":return"boolean";case"text":return"text";case"character varying":return"varchar";case"character":return"char";case"date":return"date";case"time without time zone":case"time with time zone":return"time";case"timestamp without time zone":case"timestamp with time zone":return"timestamp";case"json":case"jsonb":return"json";case"uuid":return"uuid";case"bytea":case"bit":case"bit varying":return"binary";default:return"unknown"}}class u${db=null;connected=!1;sessions=new Map;poolActiveQuery=null;async connect($){if($.type!=="postgresql")throw Error("PostgresDriver requires a postgresql connection config");let Z=$.ssl?`?sslmode=${$.ssl}`:"",Q=`postgres://${encodeURIComponent($.user)}:${encodeURIComponent($.password)}@${$.host}:${$.port}/${encodeURIComponent($.database)}${Z}`;this.db=new e5({url:Q});try{await this.db`SELECT 1`}catch(B){throw this.db=null,B instanceof _?B:w$(B)}this.connected=!0}async disconnect(){for(let[,$]of this.sessions){if($.txActive)try{await $.conn.unsafe("ROLLBACK")}catch{}$.conn.release()}if(this.sessions.clear(),this.db)await this.db.close(),this.db=null,this.connected=!1}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=await this.db.reserve();this.sessions.set($,{conn:Z,txActive:!1,activeQuery:null})}async releaseSession($){let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);if(Z.txActive)try{await Z.conn.unsafe("ROLLBACK")}catch{}Z.conn.release(),this.sessions.delete($)}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==T)}async execute($,Z,Q){this.ensureConnected();let B=this.resolveSession(Q),X=B?B.conn:this.db,W=performance.now(),Y=X.unsafe($,Z??[]);if(B)B.activeQuery=Y;else this.poolActiveQuery=Y;try{let G=await Y,H=Math.round(performance.now()-W),V=[...G];return{columns:V.length>0?Object.keys(V[0]).map((j)=>({name:j,dataType:"unknown"})):[],rows:V,rowCount:V.length,affectedRows:p(G),durationMs:H}}catch(G){throw G instanceof _?G:w$(G)}finally{if(B)B.activeQuery=null;else this.poolActiveQuery=null}}async cancel($){if($){let Z=this.sessions.get($);if(Z?.activeQuery)Z.activeQuery.cancel(),Z.activeQuery=null}else if(this.poolActiveQuery)this.poolActiveQuery.cancel(),this.poolActiveQuery=null}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),Q=Z?Z.conn:this.db,B=await this.getSchemas(Q),W=`{${B.map((z)=>z.name).join(",")}}`,Y={};for(let z of B){let O=await this.getTables(Q,z.name),L=await this.getMaterializedViews(Q,z.name);Y[z.name]=[...O,...L]}let G=new Map;for(let z of B){let O=Y[z.name].filter((L)=>L.type==="materialized-view");if(O.length>0)G.set(z.name,O.map((L)=>L.name))}let[H,V,U,j]=await Promise.all([Q.unsafe(`SELECT
|
|
184
184
|
c.table_schema,
|
|
185
185
|
c.table_name,
|
|
186
186
|
c.column_name,
|
|
@@ -280,7 +280,7 @@ Request: ${Z.prompt}`}]})});if(!B.ok){let Y=await B.text().catch(()=>"");if(B.st
|
|
|
280
280
|
AND nsp_ref.nspname = ANY($1)
|
|
281
281
|
GROUP BY nsp_ref.nspname, cl_ref.relname, con.conname,
|
|
282
282
|
nsp_src.nspname, cl_src.relname
|
|
283
|
-
ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[W])]);for(let[
|
|
283
|
+
ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[W])]);for(let[z,O]of G){let L=await Q.unsafe(`SELECT
|
|
284
284
|
n.nspname AS schema_name,
|
|
285
285
|
c.relname AS table_name,
|
|
286
286
|
a.attname AS column_name,
|
|
@@ -298,21 +298,21 @@ Request: ${Z.prompt}`}]})});if(!B.ok){let Y=await B.text().catch(()=>"");if(B.st
|
|
|
298
298
|
AND c.relname = ANY($2)
|
|
299
299
|
AND a.attnum > 0
|
|
300
300
|
AND NOT a.attisdropped
|
|
301
|
-
ORDER BY n.nspname, c.relname, a.attnum`,[
|
|
301
|
+
ORDER BY n.nspname, c.relname, a.attnum`,[z,`{${O.join(",")}}`]);for(let F of L)H.push({table_schema:F.schema_name,table_name:F.table_name,column_name:F.column_name,data_type:F.data_type,udt_name:F.udt_name,is_nullable:F.is_nullable,column_default:F.column_default,character_maximum_length:null,is_primary_key:!1})}let J={};for(let z of H){let O=`${z.table_schema}.${z.table_name}`;if(!J[O])J[O]=[];J[O].push({name:z.column_name,dataType:this.mapDataType(z.data_type,z.udt_name),nullable:z.is_nullable==="YES",defaultValue:z.column_default,isPrimaryKey:z.is_primary_key,isAutoIncrement:z.is_primary_key&&typeof z.column_default==="string"&&z.column_default.startsWith("nextval("),maxLength:z.character_maximum_length??void 0})}let A={};for(let z of V){let O=`${z.table_schema}.${z.table_name}`;if(!A[O])A[O]=[];A[O].push({name:z.index_name,columns:typeof z.columns==="string"?z.columns.replace(/^\{|\}$/g,"").split(","):z.columns,isUnique:z.is_unique,isPrimary:z.is_primary})}let K={};for(let z of U){let O=`${z.table_schema}.${z.table_name}`;if(!K[O])K[O]=[];K[O].push({name:z.constraint_name,columns:typeof z.columns==="string"?z.columns.replace(/^\{|\}$/g,"").split(","):z.columns,referencedSchema:z.referenced_schema,referencedTable:z.referenced_table,referencedColumns:typeof z.referenced_columns==="string"?z.referenced_columns.replace(/^\{|\}$/g,"").split(","):z.referenced_columns,onUpdate:z.on_update,onDelete:z.on_delete})}let R={};for(let z of j){let O=`${z.referenced_schema}.${z.referenced_table}`;if(!R[O])R[O]=[];R[O].push({constraintName:z.constraint_name,referencingSchema:z.referencing_schema,referencingTable:z.referencing_table,referencingColumns:typeof z.referencing_columns==="string"?z.referencing_columns.replace(/^\{|\}$/g,"").split(","):z.referencing_columns,referencedColumns:typeof z.referenced_columns==="string"?z.referenced_columns.replace(/^\{|\}$/g,"").split(","):z.referenced_columns})}for(let z of B)for(let O of Y[z.name]){let L=`${z.name}.${O.name}`;if(!J[L])J[L]=[];if(!A[L])A[L]=[];if(!K[L])K[L]=[];if(!R[L])R[L]=[]}return{schemas:B,tables:Y,columns:J,indexes:A,foreignKeys:K,referencingForeignKeys:R}}async getSchemas($){return this.ensureConnected(),[...await $.unsafe(`SELECT schema_name AS name
|
|
302
302
|
FROM information_schema.schemata
|
|
303
303
|
WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
|
|
304
304
|
ORDER BY schema_name`)]}async getTables($,Z){return this.ensureConnected(),[...await $.unsafe(`SELECT table_name AS name, table_type
|
|
305
305
|
FROM information_schema.tables
|
|
306
306
|
WHERE table_schema = $1
|
|
307
|
-
ORDER BY table_name`,[Z])].map((
|
|
307
|
+
ORDER BY table_name`,[Z])].map((B)=>({schema:Z,name:B.name,type:B.table_type==="VIEW"?"view":"table"}))}async getMaterializedViews($,Z){return this.ensureConnected(),[...await $.unsafe(`SELECT matviewname
|
|
308
308
|
FROM pg_matviews
|
|
309
309
|
WHERE schemaname = $1
|
|
310
|
-
ORDER BY matviewname`,[Z])].map((
|
|
311
|
-
echo '${$.password.replace(/'/g,"'\\''")}'`)
|
|
312
|
-
`);for(let Q of Z){let X=Q.toLowerCase();if(X.includes("permission denied")||X.includes("authentication"))return`SSH authentication failed: ${Q.trim()}`;if(X.includes("connection refused"))return`SSH host unreachable: ${Q.trim()}`;if(X.includes("timed out")||X.includes("timeout"))return`SSH connection timed out: ${Q.trim()}`;if(X.includes("no such file")||X.includes("no such identity"))return`SSH key file not found: ${Q.trim()}`;if(X.includes("could not resolve"))return`SSH host unreachable: ${Q.trim()}`}return Z[Z.length-1]?.trim()||null}function j9($){let Z=$.message.toLowerCase();if(Z.includes("authentication")||Z.includes("permission denied"))return Error(`SSH authentication failed: ${$.message}`);if(Z.includes("econnrefused")||Z.includes("connection refused")||Z.includes("unreachable"))return Error(`SSH host unreachable: ${$.message}`);if(Z.includes("timeout")||Z.includes("timed out"))return Error(`SSH connection timed out: ${$.message}`);return Error(`SSH tunnel error: ${$.message}`)}var W9=15000,Y9=100;var o5=()=>{};class p0{drivers=new Map;passwords=new Map;states=new Map;listeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;connectAttempt=new Map;constructor($,Z){this.appDb=$,this.opts={...J9,...Z}}async connect($,Z){let Q=this.appDb.getConnectionById($);if(!Q)throw Error(`Connection not found: ${$}`);this.cancelAutoReconnect($);let X=(this.connectAttempt.get($)??0)+1;if(this.connectAttempt.set($,X),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),this.setConnectionState($,"connecting");try{let B=Z?{...Q.config,...Z}:Q.config;if(Y0(B),b(B))this.passwords.set($,B.password);B=await this.setupSshTunnel($,B);let W=I(B),Y=W0(B);if(await Y.connect(B),this.connectAttempt.get($)!==X){await Y.disconnect().catch(()=>{});return}let G=new Map;if(G.set(W,Y),this.drivers.set($,G),y[B.type].supportsMultiDatabase&&"activeDatabases"in B&&B.activeDatabases){let H=B.activeDatabases.filter((V)=>V!==B.database).map((V)=>this.connectDatabase($,B,V));await Promise.allSettled(H)}this.setConnectionState($,"connected"),this.startHealthCheck($)}catch(B){if(this.connectAttempt.get($)!==X)return;await this.closeTunnel($);let W=B instanceof Error?B.message:"Unknown connection error",Y=B instanceof L?B.code:void 0;throw this.setConnectionState($,"error",W,Y),B}}async disconnect($){this.connectAttempt.set($,(this.connectAttempt.get($)??0)+1),this.cancelAutoReconnect($),this.stopHealthCheck($),await this.gracefulDisconnect($),await this.closeTunnel($),this.passwords.delete($),this.setConnectionState($,"disconnected")}async reconnect($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.gracefulDisconnect($);await this.connect($)}getDriver($,Z){let Q=this.drivers.get($);if(!Q)throw Error(`No active connection for id: ${$}`);let X=Z??this.getDefaultDatabaseName($),B=Q.get(X);if(!B)throw Error(`No active driver for database "${X}" on connection ${$}`);return B}getConnectionState($){return this.states.get($)?.state??"disconnected"}async listDatabases($){let Z=this.appDb.getConnectionById($);if(!Z||!y[Z.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let Q=I(Z.config),B=await this.getDriver($,Q).execute("SELECT datname FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname"),W=this.drivers.get($),Y=W?[...W.keys()]:[Q];return B.rows.map((G)=>({name:G.datname,isDefault:G.datname===Q,isActive:Y.includes(G.datname)}))}async activateDatabase($,Z){let Q=this.appDb.getConnectionById($);if(!Q||!y[Q.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let X=Q.config,B=this.drivers.get($);if(!B)throw Error(`No active connection for id: ${$}`);if(B.has(Z))return;if(this.getActiveDatabaseCount()>=this.opts.maxActiveDatabases)throw Error(`Cannot activate database "${Z}": maximum number of active databases (${this.opts.maxActiveDatabases}) reached. Deactivate an unused database first.`);let Y=this.passwords.get($)??X.password,G={...X,database:Z,password:Y};await this.connectDatabase($,G,Z);let H=[...new Set([...X.activeDatabases??[],Z])];this.appDb.updateConnection({id:$,name:Q.name,config:{...X,activeDatabases:H}})}async deactivateDatabase($,Z){let Q=this.appDb.getConnectionById($);if(!Q||!y[Q.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let X=Q.config;if(Z===I(X))throw Error("Cannot deactivate the default database");let B=this.drivers.get($);if(B){let Y=B.get(Z);if(Y)try{await Y.disconnect()}finally{B.delete(Z)}}let W=(X.activeDatabases??[]).filter((Y)=>Y!==Z);this.appDb.updateConnection({id:$,name:Q.name,config:{...X,activeDatabases:W.length>0?W:void 0}})}listConnections(){return this.appDb.listConnections().map((Z)=>({...Z,state:this.getConnectionState(Z.id),error:this.states.get(Z.id)?.error}))}createConnection($,Z=!1){return Y0($.config,Z),this.appDb.createConnection($)}updateConnection($){return Y0($.config),{...this.appDb.updateConnection($),state:this.getConnectionState($.id),error:this.states.get($.id)?.error}}setConnectionReadOnly($,Z){return{...this.appDb.setConnectionReadOnly($,Z),state:this.getConnectionState($),error:this.states.get($)?.error}}async deleteConnection($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),this.passwords.delete($),this.states.delete($),this.appDb.deleteConnection($)}async testConnection($){Y0($);let Z=null,Q=$;try{if($.type==="postgresql"&&$.sshTunnel?.enabled)Z=await u0($.sshTunnel,$.host,$.port),Q={...$,host:"127.0.0.1",port:Z.localPort};let X=W0(Q);return await X.connect(Q),await X.disconnect(),{success:!0}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Unknown connection error"}}finally{if(Z)await Z.close()}}onStatusChanged($){return this.listeners.push($),()=>{let Z=this.listeners.indexOf($);if(Z>=0)this.listeners.splice(Z,1)}}async disconnectAll(){for(let Z of[...this.reconnectStates.keys()])this.cancelAutoReconnect(Z);for(let Z of[...this.healthTimers.keys()])this.stopHealthCheck(Z);let $=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let Z of $)await this.disconnect(Z)}startHealthCheck($){this.stopHealthCheck($);let Z=setInterval(()=>{this.performHealthCheck($)},this.opts.healthCheckIntervalMs);this.healthTimers.set($,Z)}stopHealthCheck($){let Z=this.healthTimers.get($);if(Z)clearInterval(Z),this.healthTimers.delete($)}async performHealthCheck($){let Z=this.drivers.get($);if(!Z)return;let Q=this.getDefaultDatabaseName($),X=Z.get(Q);if(!X)return;try{await X.execute("SELECT 1")}catch{let B=!1;for(let W of Z.values())if(W.inTransaction()){B=!0;break}this.stopHealthCheck($),await this.disconnectAllDrivers($),this.setConnectionState($,"disconnected","Connection lost"),this.startAutoReconnect($,B)}}startAutoReconnect($,Z=!1){this.cancelAutoReconnect($);let Q={attempt:0,timer:null,cancelled:!1,hadTransaction:Z};this.reconnectStates.set($,Q),this.scheduleReconnectAttempt($,Q)}cancelAutoReconnect($){let Z=this.reconnectStates.get($);if(Z){if(Z.cancelled=!0,Z.timer)clearTimeout(Z.timer);this.reconnectStates.delete($)}}scheduleReconnectAttempt($,Z){if(Z.cancelled)return;if(Z.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete($),this.setConnectionState($,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let Q=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,Z.attempt),this.opts.reconnectMaxDelayMs);Z.timer=setTimeout(()=>{if(Z.cancelled)return;this.attemptReconnect($,Z)},Q)}async attemptReconnect($,Z){if(Z.cancelled)return;let Q=this.appDb.getConnectionById($);if(!Q){this.cancelAutoReconnect($);return}Z.attempt++,this.setConnectionState($,"reconnecting");try{await this.closeTunnel($);let X=this.passwords.get($),B=X?{...Q.config,password:X}:Q.config;B=await this.setupSshTunnel($,B);let W=I(B),Y=W0(B);if(await Y.connect(B),Z.cancelled){await Y.disconnect(),await this.closeTunnel($);return}let G=new Map;if(G.set(W,Y),this.drivers.set($,G),y[B.type].supportsMultiDatabase&&"activeDatabases"in B&&B.activeDatabases){let V=B.activeDatabases.filter((U)=>U!==B.database).map((U)=>this.connectDatabase($,B,U));await Promise.allSettled(V)}let H=Z.hadTransaction;this.reconnectStates.delete($),this.setConnectionState($,"connected",void 0,void 0,H),this.startHealthCheck($)}catch{if(Z.cancelled)return;await this.closeTunnel($),this.scheduleReconnectAttempt($,Z)}}async gracefulDisconnect($){let Z=this.drivers.get($);if(!Z)return;for(let[Q,X]of Z)try{if(X.inTransaction())try{await X.rollback()}catch{}try{await X.cancel()}catch{}}finally{try{await X.disconnect()}finally{Z.delete(Q)}}this.drivers.delete($)}async disconnectAllDrivers($){let Z=this.drivers.get($);if(!Z)return;for(let[Q,X]of Z)try{await X.disconnect()}finally{Z.delete(Q)}this.drivers.delete($)}async connectDatabase($,Z,Q){let X=this.drivers.get($);if(!X)throw Error(`No active connection for id: ${$}`);let B=this.tunnels.get($),W=B?{host:"127.0.0.1",port:B.localPort}:{},Y={...Z,...W,database:Q},G=W0(Y);await G.connect(Y),X.set(Q,G)}async setupSshTunnel($,Z){if(Z.type!=="postgresql"||!Z.sshTunnel?.enabled)return Z;let Q=await u0(Z.sshTunnel,Z.host,Z.port);return this.tunnels.set($,Q),{...Z,host:"127.0.0.1",port:Q.localPort}}async closeTunnel($){let Z=this.tunnels.get($);if(Z)await Z.close(),this.tunnels.delete($)}getActiveDatabaseCount(){let $=0;for(let Z of this.drivers.values())$+=Z.size;return $}getDefaultDatabaseName($){let Z=this.appDb.getConnectionById($);if(!Z)throw Error(`Connection not found: ${$}`);return I(Z.config)}setConnectionState($,Z,Q,X,B){this.states.set($,{state:Z,error:Q});for(let W of this.listeners)W({connectionId:$,state:Z,error:Q,errorCode:X,transactionLost:B||void 0})}}function W0($){let Z;switch($.type){case"postgresql":Z=new f0;break;case"sqlite":Z=new I0;break;case"mysql":Z=new g0;break;default:throw Error(`Unsupported connection type: ${$.type}`)}if(process.env.DEBUG_SQL)Z=new v0(Z);return Z}function Y0($,Z=!1){if(!$||!$.type)throw Error("Connection config must have a type");let Q=y[$.type];if(!Q)throw Error(`Unsupported connection type: ${$.type}`);if(Q.hasHost&&b($)){let X=Q.label;if(!$.host)throw Error(`${X} host is required`);if(!$.port)throw Error(`${X} port is required`);if(!$.database)throw Error(`${X} database is required`);if(!$.user)throw Error(`${X} user is required`);if(!Z&&($.password===void 0||$.password===null))throw Error(`${X} password is required`)}else if($.type==="sqlite"){if(!$.path)throw Error("SQLite path is required")}}var J9;var r5=M(()=>{F0();q();c5();i5();t5();o5();J9={healthCheckIntervalMs:30000,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5,maxActiveDatabases:10}});function l0(){return G0}function s5($,Z){let Q=crypto.randomUUID(),X=t.create(":memory:"),B=new p0(X),W=new c(B,void 0,X),Y=new k0(Z),G=(J,A)=>{if(j.ws)j.ws.send(JSON.stringify({type:"message",channel:J,payload:A}))},{handlers:H,sessionManager:V}=l5(B,W,X,void 0,{encryption:Y,emitMessage:G}),U=B.onStatusChanged((J)=>{if(j.ws)j.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:J.connectionId,state:J.state,error:J.error,errorCode:J.errorCode,transactionLost:J.transactionLost}}));if(J.state==="disconnected"||J.state==="error"){if(V.handleConnectionLost(J.connectionId),j.ws)j.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:[]}}))}}),j={id:Q,appDb:X,connectionManager:B,queryExecutor:W,handlers:H,sessionManager:V,unsubscribe:U,ws:$,activeStreams:0,disconnectedAt:null,ttlTimer:null};return G0.set(Q,j),j}async function n($){if(G0.delete($.id),$.ttlTimer)clearTimeout($.ttlTimer),$.ttlTimer=null;$.unsubscribe();for(let Z of $.queryExecutor.getRunningQueryIds())await $.queryExecutor.cancelQuery(Z);await $.connectionManager.disconnectAll(),$.appDb.close()}async function e5($){if($.ws=null,$.disconnectedAt=Date.now(),$.activeStreams===0)await n($);else $.ttlTimer=setTimeout(async()=>{if(G0.has($.id))await n($)},m0)}async function d0($){if($.activeStreams--,$.ws===null&&$.activeStreams===0)await n($)}function c0($,Z,Q,X,B){let W=crypto.randomUUID();return m.set(W,{session:$,connectionId:Q,database:X,params:B,type:Z,createdAt:Date.now()}),W}function i0($,Z){let Q=m.get($);if(!Q)return null;if(Q.type!==Z)return null;if(Date.now()-Q.createdAt>a5)return m.delete($),null;return m.delete($),Q}function $7(){let $=Date.now();for(let[Z,Q]of m)if($-Q.createdAt>a5)m.delete(Z)}var m0=300000,a5=300000,G0,m;var Z7=M(()=>{d5();r5();C0();x0();S0();G0=new Map;m=new Map});var M9={};import{resolve as t0}from"path";async function R9($,Z){let Q=i0(Z,"export");if(!Q)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:X,connectionId:B,database:W,params:Y}=Q,G=Y,H;try{H=X.connectionManager.getDriver(B,W)}catch(z){return new Response(JSON.stringify({error:z?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}X.activeStreams++;let V=A9[G.format]??"application/octet-stream",U=O9[G.format]??"dat",j=`${G.table}.${U}`,J=new AbortController;$.signal.addEventListener("abort",()=>J.abort());let A=new ReadableStream({async start(z){let R={write(K){if(typeof K==="string")z.enqueue(new TextEncoder().encode(K));else z.enqueue(K)},async end(){}};try{let K=await K0(H,G,R,J.signal,(O)=>{if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:O}}))});if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:K.rowCount}}));z.close()}catch(K){if(J.signal.aborted)try{z.close()}catch{}else z.error(K)}finally{await d0(X)}}});return new Response(A,{headers:{"Content-Type":V,"Content-Disposition":`attachment; filename="${j}"`}})}async function _9($,Z){let Q=i0(Z,"import");if(!Q)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:X,connectionId:B,database:W,params:Y}=Q,G=Y,H;try{H=X.connectionManager.getDriver(B,W)}catch(U){return new Response(JSON.stringify({error:U?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!$.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});X.activeStreams++;let V=new AbortController;$.signal.addEventListener("abort",()=>V.abort());try{let U=await s(H,$.body,G,V.signal,(j)=>{if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:j}}))});return new Response(JSON.stringify({rowCount:U.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(U){return new Response(JSON.stringify({error:U?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await d0(X)}}var K9,X7,Q7,B7,z9=60000,A9,O9,L9;var W7=M(()=>{z0();O0();q();Z7();K9=Number(process.env.DOTAZ_PORT)||6401,X7=process.env.DOTAZ_HOST||"localhost",Q7=process.env.DOTAZ_DIST_DIR||t0(import.meta.dir,"../../dist"),B7=process.env.DOTAZ_ENCRYPTION_KEY;if(!B7)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{$7()},60000);setInterval(async()=>{let $=Date.now();for(let[,Z]of l0())if(Z.disconnectedAt!==null&&$-Z.disconnectedAt>m0)await n(Z)},z9);A9={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},O9={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};L9=Bun.serve({port:K9,hostname:X7,async fetch($,Z){let Q=new URL($.url);if(Q.pathname==="/rpc"){if(Z.upgrade($,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let X=Q.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(X&&$.method==="GET")return R9($,X[1]);let B=Q.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(B&&$.method==="POST")return _9($,B[1]);if(Q.pathname==="/api/menu-action"&&$.method==="POST")try{let H=(await $.json())?.action;if(!H)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,V]of l0())if(V.ws)V.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:H}}));return new Response(JSON.stringify({ok:!0}),{headers:{"Content-Type":"application/json"}})}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}let W=t0(Q7,Q.pathname.slice(1)),Y=Bun.file(W);if(await Y.exists())return new Response(Y);if(W=t0(Q7,"index.html"),Y=Bun.file(W),await Y.exists())return new Response(Y,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open($){let Z=s5($,B7);Object.assign($.data,Z)},async close($){await e5($.data)},async message($,Z){let Q;try{Q=JSON.parse(typeof Z==="string"?Z:new TextDecoder().decode(Z))}catch{$.send(JSON.stringify({type:"response",id:0,success:!1,error:"Invalid JSON"}));return}if(Q.type==="request"){if(Q.method==="stream.createExportToken"){let{connectionId:B,database:W,...Y}=Q.params,G=c0($.data,"export",B,W,Y);$.send(JSON.stringify({type:"response",id:Q.id,success:!0,payload:{token:G}}));return}if(Q.method==="stream.createImportToken"){let{connectionId:B,database:W,...Y}=Q.params,G=c0($.data,"import",B,W,Y);$.send(JSON.stringify({type:"response",id:Q.id,success:!0,payload:{token:G}}));return}let X=$.data.handlers[Q.method];if(!X){$.send(JSON.stringify({type:"response",id:Q.id,success:!1,error:`Unknown method: ${Q.method}`}));return}try{let B=await X(Q.params);$.send(JSON.stringify({type:"response",id:Q.id,success:!0,payload:B}))}catch(B){$.send(JSON.stringify({type:"response",id:Q.id,success:!1,error:B?.message??String(B),errorCode:B instanceof L?B.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${X7}:${L9.port}`)});var{secrets:Y7}=globalThis.Bun;import{randomBytes as x9}from"crypto";import{resolve as F9}from"path";var G7="dev.dotaz.server",H7="encryption-key",l=process.argv.slice(2),V7=6401,U7="localhost";for(let $=0;$<l.length;$++){let Z=l[$];if((Z==="--port"||Z==="-p")&&l[$+1])V7=Number(l[$+1]),$++;else if((Z==="--host"||Z==="-H")&&l[$+1])U7=l[$+1],$++;else if(Z==="--help")console.log(`Usage: dotaz [options]
|
|
310
|
+
ORDER BY matviewname`,[Z])].map((B)=>({schema:Z,name:B.matviewname,type:"materialized-view"}))}async beginTransaction($){if(this.ensureConnected(),$){let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);await Z.conn.unsafe("BEGIN"),Z.txActive=!0}else{let Z=await this.db.reserve();try{await Z.unsafe("BEGIN")}catch(Q){throw Z.release(),Q}this.sessions.set(T,{conn:Z,txActive:!0,activeQuery:null})}}async commit($){this.ensureConnected();let Z=$??T,Q=this.sessions.get(Z);if(!Q)throw Error("No active transaction");if(await Q.conn.unsafe("COMMIT"),Q.txActive=!1,Z===T)Q.conn.release(),this.sessions.delete(T)}async rollback($){this.ensureConnected();let Z=$??T,Q=this.sessions.get(Z);if(!Q)throw Error("No active transaction");if(await Q.conn.unsafe("ROLLBACK"),Q.txActive=!1,Z===T)Q.conn.release(),this.sessions.delete(T)}inTransaction($){let Z=$??T;return this.sessions.get(Z)?.txActive??!1}getDriverType(){return"postgresql"}quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}qualifyTable($,Z){return`${this.quoteIdentifier($)}.${this.quoteIdentifier(Z)}`}emptyInsertSql($){return`INSERT INTO ${$} DEFAULT VALUES`}placeholder($){return`$${$}`}async*iterate($,Z,Q=1000,B,X){this.ensureConnected();let W=`dotaz_iter_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Y=X?this.sessions.get(X):void 0;if(X&&!Y)throw Error(`Session "${X}" not found`);let G=Y?Y.conn:await this.db.reserve(),H=!Y;try{await G.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await G.unsafe(`DECLARE ${W} NO SCROLL CURSOR FOR ${$}`,Z??[]);try{while(!0){if(B?.aborted)throw new DOMException("Aborted","AbortError");let U=[...await G.unsafe(`FETCH FORWARD ${Q} FROM ${W}`)];if(U.length===0)break;if(yield U,U.length<Q)break}}finally{await G.unsafe(`CLOSE ${W}`)}await G.unsafe("COMMIT")}catch(V){try{await G.unsafe("ROLLBACK")}catch{}throw V}finally{if(H)G.release()}}async importBatch($,Z,Q,B){if(this.ensureConnected(),Q.length===0)return 0;let X=Z.map((V)=>this.quoteIdentifier(V)).join(", "),W=[],Y=[];for(let V=0;V<Q.length;V++){let U=[];for(let j=0;j<Z.length;j++)W.push(Q[V][Z[j]]),U.push(this.placeholder(W.length));Y.push(`(${U.join(", ")})`)}let G=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(G,W,B)).affectedRows??Q.length}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}resolveSession($){if(!$)return this.sessions.get(T);let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);return Z}mapDataType($,Z){if($==="ARRAY")return"array";if($==="USER-DEFINED"){let Q=Z.toLowerCase();if(Q==="json"||Q==="jsonb")return"json";return"enum"}return $7($)}}var T="__default__";var n0=M(()=>{g();q();X$()});var{SQL:Z7}=globalThis.Bun;function Q7($){let Z=$.toUpperCase();if(Z==="INTEGER"||Z==="INT"||Z==="BIGINT"||Z==="SMALLINT"||Z==="TINYINT"||Z==="MEDIUMINT")return"integer";if(Z==="REAL"||Z==="FLOAT"||Z==="DOUBLE")return"float";if(Z==="NUMERIC"||Z==="DECIMAL")return"numeric";if(Z==="BOOLEAN"||Z==="BOOL")return"boolean";if(Z==="TEXT")return"text";if(Z.includes("VARCHAR")||Z.includes("VARYING"))return"varchar";if(Z.includes("CHAR")&&!Z.includes("VARCHAR"))return"char";if(Z==="DATE")return"date";if(Z==="TIME")return"time";if(Z==="DATETIME"||Z.includes("TIMESTAMP"))return"timestamp";if(Z==="JSON"||Z==="JSONB")return"json";if(Z==="BLOB"||Z==="BINARY"||Z.includes("VARBINARY"))return"binary";return"unknown"}class p${db=null;connected=!1;txActive=!1;sessionIds=new Set;async connect($){if($.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");try{this.db=new Z7(`sqlite:${$.path}`),await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON")}catch(Z){throw this.db=null,Z instanceof _?Z:f$(Z)}this.connected=!0}async disconnect(){if(this.db)await this.db.close(),this.db=null,this.connected=!1,this.txActive=!1,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession($){this.sessionIds.add($)}async releaseSession($){this.sessionIds.delete($)}getSessionIds(){return[...this.sessionIds]}async execute($,Z,Q){this.ensureConnected();let B=performance.now();try{let X=await this.db.unsafe($,Z??[]),W=Math.round(performance.now()-B),Y=[...X];return{columns:Y.length>0?Object.keys(Y[0]).map((H)=>({name:H,dataType:"unknown"})):[],rows:Y,rowCount:Y.length,affectedRows:p(X),durationMs:W}}catch(X){throw X instanceof _?X:f$(X)}}async cancel($){}async loadSchema($){this.ensureConnected();let Z=await this.getSchemas(),Q=Z[0].name,B=await this.getTables(Q),X={[Q]:B},W={},Y={},G={},H={},V=new Map;for(let U of B){let j=`${Q}.${U.name}`;W[j]=await this.getColumns(Q,U.name),Y[j]=await this.getIndexes(Q,U.name);let J=await this.getForeignKeys(Q,U.name);G[j]=J;for(let A of J){let K=`${A.referencedSchema}.${A.referencedTable}`;if(!V.has(K))V.set(K,[]);V.get(K).push({constraintName:A.name,referencingSchema:Q,referencingTable:U.name,referencingColumns:A.columns,referencedColumns:A.referencedColumns})}}for(let U of B){let j=`${Q}.${U.name}`;H[j]=V.get(j)??[]}return{schemas:Z,tables:X,columns:W,indexes:Y,foreignKeys:G,referencingForeignKeys:H}}async getSchemas(){return[{name:"main"}]}async getTables($){return this.ensureConnected(),[...await this.db.unsafe("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name")].map((Q)=>({schema:$,name:Q.name,type:Q.type}))}async getColumns($,Z){this.ensureConnected();let Q=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(Z)})`)],B=Q.filter((X)=>X.pk>0).length;return Q.map((X)=>({name:X.name,dataType:Q7(X.type||"BLOB"),nullable:X.notnull===0&&X.pk===0,defaultValue:X.dflt_value,isPrimaryKey:X.pk>0,isAutoIncrement:X.pk>0&&B===1&&X.type?.toUpperCase()==="INTEGER"}))}async getIndexes($,Z){this.ensureConnected();let Q=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(Z)})`)],B=[];for(let X of Q){let W=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(X.name)})`)];B.push({name:X.name,columns:W.map((Y)=>Y.name),isUnique:X.unique===1,isPrimary:X.origin==="pk"})}return B}async getForeignKeys($,Z){this.ensureConnected();let Q=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(Z)})`)],B=new Map;for(let X of Q){let W=B.get(X.id);if(W)W.columns.push(X.from),W.referencedColumns.push(X.to);else B.set(X.id,{name:`fk_${Z}_${X.id}`,columns:[X.from],referencedSchema:"main",referencedTable:X.table,referencedColumns:[X.to],onUpdate:X.on_update,onDelete:X.on_delete})}return Array.from(B.values())}async*iterate($,Z,Q=1000,B,X){this.ensureConnected();let W=0;while(!0){if(B?.aborted)throw new DOMException("Aborted","AbortError");let Y=`${$} LIMIT ? OFFSET ?`,H=[...await this.db.unsafe(Y,[...Z??[],Q,W])];if(H.length===0)break;if(yield H,H.length<Q)break;W+=Q}}async importBatch($,Z,Q,B){if(this.ensureConnected(),Q.length===0)return 0;let X=Z.map((V)=>this.quoteIdentifier(V)).join(", "),W=[],Y=[];for(let V=0;V<Q.length;V++){let U=[];for(let j=0;j<Z.length;j++)W.push(Q[V][Z[j]]),U.push(this.placeholder(W.length));Y.push(`(${U.join(", ")})`)}let G=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(G,W)).affectedRows??Q.length}async beginTransaction($){this.ensureConnected(),await this.db.unsafe("BEGIN"),this.txActive=!0}async commit($){this.ensureConnected(),await this.db.unsafe("COMMIT"),this.txActive=!1}async rollback($){this.ensureConnected(),await this.db.unsafe("ROLLBACK"),this.txActive=!1}inTransaction($){return this.txActive}getDriverType(){return"sqlite"}quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}qualifyTable($,Z){if($==="main")return this.quoteIdentifier(Z);return`${this.quoteIdentifier($)}.${this.quoteIdentifier(Z)}`}emptyInsertSql($){return`INSERT INTO ${$} DEFAULT VALUES`}placeholder($){return`$${$}`}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}}var o0=M(()=>{g();q();X$()});import{chmodSync as B7,unlinkSync as X7,writeFileSync as W7}from"fs";import{tmpdir as Y7}from"os";import{join as G7}from"path";async function U7(){return new Promise(($,Z)=>{let Q=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),B=Q.port;if(Q.stop(!0),B>0)$(B);else Z(Error("Could not find a free port"))})}async function j7($,Z,Q){let B=Date.now()+Z;while(Date.now()<B){if(Q&&Q.exitCode!==null)return;try{(await Bun.connect({hostname:"127.0.0.1",port:$,socket:{data(){},open(W){W.end()},close(){},error(){}}})).end();return}catch{await Bun.sleep(V7)}}throw Error(`SSH tunnel port ${$} did not become available within ${Z/1000}s`)}async function m$($,Z,Q){let B=$.localPort||await U7(),X=null,W=null;try{let Y=["ssh","-N","-L",`${B}:${Z}:${Q}`,"-p",String($.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],G={...process.env};if($.authMethod==="key"&&$.keyPath)Y.push("-i",$.keyPath),Y.push("-o","BatchMode=yes");else if($.password)X=G7(Y7(),`dotaz-askpass-${process.pid}-${Date.now()}`),W7(X,`#!/bin/sh
|
|
311
|
+
echo '${$.password.replace(/'/g,"'\\''")}'`),B7(X,448),G.SSH_ASKPASS=X,G.SSH_ASKPASS_REQUIRE="force",G.DISPLAY=G.DISPLAY||":0";if(Y.push(`${$.username}@${$.host}`),W=Bun.spawn(Y,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:G}),W.stdin&&typeof W.stdin!=="number")W.stdin.end();let H=W.stderr&&typeof W.stderr!=="number"?W.stderr:null,V=j7(B,H7,W),U=W.exited.then(async(J)=>{if(J!==0){let A=await J7(H),K=K7(A)||`SSH process exited with code ${J}`;throw Error(K)}});return await Promise.race([V,U]),{localPort:B,close:async()=>{if(W)W.kill(),W=null;r0(X)}}}catch(Y){if(W)W.kill();if(r0(X),Y instanceof Error)throw z7(Y);throw Error(`SSH tunnel error: ${String(Y)}`)}}function r0($){if($)try{X7($)}catch{}}async function J7($){if(!$)return"";try{let Z=$.getReader(),Q=[];while(!0){let{done:B,value:X}=await Z.read();if(B)break;Q.push(X)}return Buffer.concat(Q).toString("utf-8")}catch{return""}}function K7($){if(!$.trim())return null;let Z=$.trim().split(`
|
|
312
|
+
`);for(let Q of Z){let B=Q.toLowerCase();if(B.includes("permission denied")||B.includes("authentication"))return`SSH authentication failed: ${Q.trim()}`;if(B.includes("connection refused"))return`SSH host unreachable: ${Q.trim()}`;if(B.includes("timed out")||B.includes("timeout"))return`SSH connection timed out: ${Q.trim()}`;if(B.includes("no such file")||B.includes("no such identity"))return`SSH key file not found: ${Q.trim()}`;if(B.includes("could not resolve"))return`SSH host unreachable: ${Q.trim()}`}return Z[Z.length-1]?.trim()||null}function z7($){let Z=$.message.toLowerCase();if(Z.includes("authentication")||Z.includes("permission denied"))return Error(`SSH authentication failed: ${$.message}`);if(Z.includes("econnrefused")||Z.includes("connection refused")||Z.includes("unreachable"))return Error(`SSH host unreachable: ${$.message}`);if(Z.includes("timeout")||Z.includes("timed out"))return Error(`SSH connection timed out: ${$.message}`);return Error(`SSH tunnel error: ${$.message}`)}var H7=15000,V7=100;var a0=()=>{};class l${drivers=new Map;passwords=new Map;states=new Map;listeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;connectAttempt=new Map;constructor($,Z){this.appDb=$,this.opts={...A7,...Z}}async connect($,Z){let Q=this.appDb.getConnectionById($);if(!Q)throw Error(`Connection not found: ${$}`);this.cancelAutoReconnect($);let B=(this.connectAttempt.get($)??0)+1;if(this.connectAttempt.set($,B),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),this.setConnectionState($,"connecting");try{let X=Z?{...Q.config,...Z}:Q.config;if(Y$(X),b(X))this.passwords.set($,X.password);X=await this.setupSshTunnel($,X);let W=I(X),Y=W$(X);if(await Y.connect(X),this.connectAttempt.get($)!==B){await Y.disconnect().catch(()=>{});return}let G=new Map;if(G.set(W,Y),this.drivers.set($,G),y[X.type].supportsMultiDatabase&&"activeDatabases"in X&&X.activeDatabases){let H=X.activeDatabases.filter((V)=>V!==X.database).map((V)=>this.connectDatabase($,X,V));await Promise.allSettled(H)}this.setConnectionState($,"connected"),this.startHealthCheck($)}catch(X){if(this.connectAttempt.get($)!==B)return;await this.closeTunnel($);let W=X instanceof Error?X.message:"Unknown connection error",Y=X instanceof _?X.code:void 0;throw this.setConnectionState($,"error",W,Y),X}}async disconnect($){this.connectAttempt.set($,(this.connectAttempt.get($)??0)+1),this.cancelAutoReconnect($),this.stopHealthCheck($),await this.gracefulDisconnect($),await this.closeTunnel($),this.passwords.delete($),this.setConnectionState($,"disconnected")}async reconnect($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.gracefulDisconnect($);await this.connect($)}getDriver($,Z){let Q=this.drivers.get($);if(!Q)throw Error(`No active connection for id: ${$}`);let B=Z??this.getDefaultDatabaseName($),X=Q.get(B);if(!X)throw Error(`No active driver for database "${B}" on connection ${$}`);return X}getConnectionState($){return this.states.get($)?.state??"disconnected"}async listDatabases($){let Z=this.appDb.getConnectionById($);if(!Z||!y[Z.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let Q=I(Z.config),X=await this.getDriver($,Q).execute("SELECT datname FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname"),W=this.drivers.get($),Y=W?[...W.keys()]:[Q];return X.rows.map((G)=>({name:G.datname,isDefault:G.datname===Q,isActive:Y.includes(G.datname)}))}async activateDatabase($,Z){let Q=this.appDb.getConnectionById($);if(!Q||!y[Q.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let B=Q.config,X=this.drivers.get($);if(!X)throw Error(`No active connection for id: ${$}`);if(X.has(Z))return;if(this.getActiveDatabaseCount()>=this.opts.maxActiveDatabases)throw Error(`Cannot activate database "${Z}": maximum number of active databases (${this.opts.maxActiveDatabases}) reached. Deactivate an unused database first.`);let Y=this.passwords.get($)??B.password,G={...B,database:Z,password:Y};await this.connectDatabase($,G,Z);let H=[...new Set([...B.activeDatabases??[],Z])];this.appDb.updateConnection({id:$,name:Q.name,config:{...B,activeDatabases:H}})}async deactivateDatabase($,Z){let Q=this.appDb.getConnectionById($);if(!Q||!y[Q.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let B=Q.config;if(Z===I(B))throw Error("Cannot deactivate the default database");let X=this.drivers.get($);if(X){let Y=X.get(Z);if(Y)try{await Y.disconnect()}finally{X.delete(Z)}}let W=(B.activeDatabases??[]).filter((Y)=>Y!==Z);this.appDb.updateConnection({id:$,name:Q.name,config:{...B,activeDatabases:W.length>0?W:void 0}})}listConnections(){return this.appDb.listConnections().map((Z)=>({...Z,state:this.getConnectionState(Z.id),error:this.states.get(Z.id)?.error}))}createConnection($,Z=!1){return Y$($.config,Z),this.appDb.createConnection($)}updateConnection($){return Y$($.config),{...this.appDb.updateConnection($),state:this.getConnectionState($.id),error:this.states.get($.id)?.error}}setConnectionReadOnly($,Z){return{...this.appDb.setConnectionReadOnly($,Z),state:this.getConnectionState($),error:this.states.get($)?.error}}async deleteConnection($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),this.passwords.delete($),this.states.delete($),this.appDb.deleteConnection($)}async testConnection($){Y$($);let Z=null,Q=$;try{if($.type==="postgresql"&&$.sshTunnel?.enabled)Z=await m$($.sshTunnel,$.host,$.port),Q={...$,host:"127.0.0.1",port:Z.localPort};let B=W$(Q);return await B.connect(Q),await B.disconnect(),{success:!0}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Unknown connection error"}}finally{if(Z)await Z.close()}}onStatusChanged($){return this.listeners.push($),()=>{let Z=this.listeners.indexOf($);if(Z>=0)this.listeners.splice(Z,1)}}async disconnectAll(){for(let Z of[...this.reconnectStates.keys()])this.cancelAutoReconnect(Z);for(let Z of[...this.healthTimers.keys()])this.stopHealthCheck(Z);let $=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let Z of $)await this.disconnect(Z)}startHealthCheck($){this.stopHealthCheck($);let Z=setInterval(()=>{this.performHealthCheck($)},this.opts.healthCheckIntervalMs);this.healthTimers.set($,Z)}stopHealthCheck($){let Z=this.healthTimers.get($);if(Z)clearInterval(Z),this.healthTimers.delete($)}async performHealthCheck($){let Z=this.drivers.get($);if(!Z)return;let Q=this.getDefaultDatabaseName($),B=Z.get(Q);if(!B)return;try{await B.execute("SELECT 1")}catch{let X=!1;for(let W of Z.values())if(W.inTransaction()){X=!0;break}this.stopHealthCheck($),await this.disconnectAllDrivers($),this.setConnectionState($,"disconnected","Connection lost"),this.startAutoReconnect($,X)}}startAutoReconnect($,Z=!1){this.cancelAutoReconnect($);let Q={attempt:0,timer:null,cancelled:!1,hadTransaction:Z};this.reconnectStates.set($,Q),this.scheduleReconnectAttempt($,Q)}cancelAutoReconnect($){let Z=this.reconnectStates.get($);if(Z){if(Z.cancelled=!0,Z.timer)clearTimeout(Z.timer);this.reconnectStates.delete($)}}scheduleReconnectAttempt($,Z){if(Z.cancelled)return;if(Z.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete($),this.setConnectionState($,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let Q=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,Z.attempt),this.opts.reconnectMaxDelayMs);Z.timer=setTimeout(()=>{if(Z.cancelled)return;this.attemptReconnect($,Z)},Q)}async attemptReconnect($,Z){if(Z.cancelled)return;let Q=this.appDb.getConnectionById($);if(!Q){this.cancelAutoReconnect($);return}Z.attempt++,this.setConnectionState($,"reconnecting");try{await this.closeTunnel($);let B=this.passwords.get($),X=B?{...Q.config,password:B}:Q.config;X=await this.setupSshTunnel($,X);let W=I(X),Y=W$(X);if(await Y.connect(X),Z.cancelled){await Y.disconnect(),await this.closeTunnel($);return}let G=new Map;if(G.set(W,Y),this.drivers.set($,G),y[X.type].supportsMultiDatabase&&"activeDatabases"in X&&X.activeDatabases){let V=X.activeDatabases.filter((U)=>U!==X.database).map((U)=>this.connectDatabase($,X,U));await Promise.allSettled(V)}let H=Z.hadTransaction;this.reconnectStates.delete($),this.setConnectionState($,"connected",void 0,void 0,H),this.startHealthCheck($)}catch{if(Z.cancelled)return;await this.closeTunnel($),this.scheduleReconnectAttempt($,Z)}}async gracefulDisconnect($){let Z=this.drivers.get($);if(!Z)return;for(let[Q,B]of Z)try{if(B.inTransaction())try{await B.rollback()}catch{}try{await B.cancel()}catch{}}finally{try{await B.disconnect()}finally{Z.delete(Q)}}this.drivers.delete($)}async disconnectAllDrivers($){let Z=this.drivers.get($);if(!Z)return;for(let[Q,B]of Z)try{await B.disconnect()}finally{Z.delete(Q)}this.drivers.delete($)}async connectDatabase($,Z,Q){let B=this.drivers.get($);if(!B)throw Error(`No active connection for id: ${$}`);let X=this.tunnels.get($),W=X?{host:"127.0.0.1",port:X.localPort}:{},Y={...Z,...W,database:Q},G=W$(Y);await G.connect(Y),B.set(Q,G)}async setupSshTunnel($,Z){if(Z.type!=="postgresql"||!Z.sshTunnel?.enabled)return Z;let Q=await m$(Z.sshTunnel,Z.host,Z.port);return this.tunnels.set($,Q),{...Z,host:"127.0.0.1",port:Q.localPort}}async closeTunnel($){let Z=this.tunnels.get($);if(Z)await Z.close(),this.tunnels.delete($)}getActiveDatabaseCount(){let $=0;for(let Z of this.drivers.values())$+=Z.size;return $}getDefaultDatabaseName($){let Z=this.appDb.getConnectionById($);if(!Z)throw Error(`Connection not found: ${$}`);return I(Z.config)}setConnectionState($,Z,Q,B,X){this.states.set($,{state:Z,error:Q});for(let W of this.listeners)W({connectionId:$,state:Z,error:Q,errorCode:B,transactionLost:X||void 0})}}function W$($){let Z;switch($.type){case"postgresql":Z=new u$;break;case"sqlite":Z=new p$;break;case"mysql":Z=new I$;break;default:throw Error(`Unsupported connection type: ${$.type}`)}if(process.env.DEBUG_SQL)Z=new b$(Z);return Z}function Y$($,Z=!1){if(!$||!$.type)throw Error("Connection config must have a type");let Q=y[$.type];if(!Q)throw Error(`Unsupported connection type: ${$.type}`);if(Q.hasHost&&b($)){let B=Q.label;if(!$.host)throw Error(`${B} host is required`);if(!$.port)throw Error(`${B} port is required`);if(!$.database)throw Error(`${B} database is required`);if(!$.user)throw Error(`${B} user is required`);if(!Z&&($.password===void 0||$.password===null))throw Error(`${B} password is required`)}else if($.type==="sqlite"){if(!$.path)throw Error("SQLite path is required")}}var A7;var s0=M(()=>{P$();q();t0();n0();o0();a0();A7={healthCheckIntervalMs:30000,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5,maxActiveDatabases:10}});function e0(){let $=process.env.DATABASE_URL;if(!$)return null;let Z;try{Z=new URL($)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let Q=Z.protocol.replace(/:$/,"");if(Q==="postgresql"||Q==="postgres"){let B=Z.hostname||"localhost",X=Z.port?Number(Z.port):5432,W=Z.pathname.replace(/^\//,"")||"postgres",Y=decodeURIComponent(Z.username||"postgres"),G=decodeURIComponent(Z.password||"");return{name:`${B}/${W}`,config:{type:"postgresql",host:B,port:X,database:W,user:Y,password:G}}}if(Q==="mysql"){let B=Z.hostname||"localhost",X=Z.port?Number(Z.port):3306,W=Z.pathname.replace(/^\//,"")||"mysql",Y=decodeURIComponent(Z.username||"root"),G=decodeURIComponent(Z.password||"");return{name:`${B}/${W}`,config:{type:"mysql",host:B,port:X,database:W,user:Y,password:G}}}return console.warn(`DATABASE_URL: unsupported scheme "${Q}", ignoring`),null}var G$="env-default";function c$(){return V$}function Z5($,Z){let Q=crypto.randomUUID(),B=t.create(":memory:"),X=new l$(B),W=new c(X,void 0,B),Y=new E$(Z),G=(A,K)=>{if(J.ws)J.ws.send(JSON.stringify({type:"message",channel:A,payload:K}))},{handlers:H,sessionManager:V}=c0(X,W,B,void 0,{encryption:Y,emitMessage:G}),U=new Set;if(H$){B.createConnectionWithId(G$,{name:H$.name,config:H$.config}),U.add(G$);let A=H["connections.list"];H["connections.list"]=()=>{return A().map((R)=>U.has(R.id)?{...R,serverManaged:!0}:R)}}let j=X.onStatusChanged((A)=>{if(J.ws)J.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:A.connectionId,state:A.state,error:A.error,errorCode:A.errorCode,transactionLost:A.transactionLost}}));if(A.state==="disconnected"||A.state==="error"){if(V.handleConnectionLost(A.connectionId),J.ws)J.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:A.connectionId,sessions:[]}}))}}),J={id:Q,appDb:B,connectionManager:X,queryExecutor:W,handlers:H,sessionManager:V,serverManagedIds:U,unsubscribe:j,ws:$,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(V$.set(Q,J),H$)X.connect(G$).catch((A)=>{console.warn("DATABASE_URL auto-connect failed:",A?.message??A)});return J}async function n($){if(V$.delete($.id),$.ttlTimer)clearTimeout($.ttlTimer),$.ttlTimer=null;$.unsubscribe();for(let Z of $.queryExecutor.getRunningQueryIds())await $.queryExecutor.cancelQuery(Z);await $.connectionManager.disconnectAll(),$.appDb.close()}async function Q5($){if($.ws=null,$.disconnectedAt=Date.now(),$.activeStreams===0)await n($);else $.ttlTimer=setTimeout(async()=>{if(V$.has($.id))await n($)},d$)}async function i$($){if($.activeStreams--,$.ws===null&&$.activeStreams===0)await n($)}function t$($,Z,Q,B,X){let W=crypto.randomUUID();return m.set(W,{session:$,connectionId:Q,database:B,params:X,type:Z,createdAt:Date.now()}),W}function n$($,Z){let Q=m.get($);if(!Q)return null;if(Q.type!==Z)return null;if(Date.now()-Q.createdAt>$5)return m.delete($),null;return m.delete($),Q}function B5(){let $=Date.now();for(let[Z,Q]of m)if($-Q.createdAt>$5)m.delete(Z)}var d$=300000,$5=300000,H$,V$,m;var X5=M(()=>{i0();s0();D$();N$();q$();H$=e0(),V$=new Map;m=new Map});var N7={};import{resolve as o$}from"path";async function M7($,Z){let Q=n$(Z,"export");if(!Q)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:B,connectionId:X,database:W,params:Y}=Q,G=Y,H;try{H=B.connectionManager.getDriver(X,W)}catch(K){return new Response(JSON.stringify({error:K?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}B.activeStreams++;let V=L7[G.format]??"application/octet-stream",U=_7[G.format]??"dat",j=`${G.table}.${U}`,J=new AbortController;$.signal.addEventListener("abort",()=>J.abort());let A=new ReadableStream({async start(K){let R={write(z){if(typeof z==="string")K.enqueue(new TextEncoder().encode(z));else K.enqueue(z)},async end(){}};try{let z=await A$(H,G,R,J.signal,(O)=>{if(B.ws)B.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:O}}))});if(B.ws)B.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:z.rowCount}}));K.close()}catch(z){if(J.signal.aborted)try{K.close()}catch{}else K.error(z)}finally{await i$(B)}}});return new Response(A,{headers:{"Content-Type":V,"Content-Disposition":`attachment; filename="${j}"`}})}async function x7($,Z){let Q=n$(Z,"import");if(!Q)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:B,connectionId:X,database:W,params:Y}=Q,G=Y,H;try{H=B.connectionManager.getDriver(X,W)}catch(U){return new Response(JSON.stringify({error:U?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!$.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});B.activeStreams++;let V=new AbortController;$.signal.addEventListener("abort",()=>V.abort());try{let U=await s(H,$.body,G,V.signal,(j)=>{if(B.ws)B.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:j}}))});return new Response(JSON.stringify({rowCount:U.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(U){return new Response(JSON.stringify({error:U?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await i$(B)}}var R7,Y5,W5,G5,O7=60000,L7,_7,F7;var H5=M(()=>{R$();L$();q();X5();R7=Number(process.env.DOTAZ_PORT)||6401,Y5=process.env.DOTAZ_HOST||"localhost",W5=process.env.DOTAZ_DIST_DIR||o$(import.meta.dir,"../../dist"),G5=process.env.DOTAZ_ENCRYPTION_KEY;if(!G5)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{B5()},60000);setInterval(async()=>{let $=Date.now();for(let[,Z]of c$())if(Z.disconnectedAt!==null&&$-Z.disconnectedAt>d$)await n(Z)},O7);L7={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},_7={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};F7=Bun.serve({port:R7,hostname:Y5,async fetch($,Z){let Q=new URL($.url);if(Q.pathname==="/rpc"){if(Z.upgrade($,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let B=Q.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(B&&$.method==="GET")return M7($,B[1]);let X=Q.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(X&&$.method==="POST")return x7($,X[1]);if(Q.pathname==="/api/menu-action"&&$.method==="POST")try{let H=(await $.json())?.action;if(!H)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,V]of c$())if(V.ws)V.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:H}}));return new Response(JSON.stringify({ok:!0}),{headers:{"Content-Type":"application/json"}})}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}let W=o$(W5,Q.pathname.slice(1)),Y=Bun.file(W);if(await Y.exists())return new Response(Y);if(W=o$(W5,"index.html"),Y=Bun.file(W),await Y.exists())return new Response(Y,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open($){let Z=Z5($,G5);Object.assign($.data,Z)},async close($){await Q5($.data)},async message($,Z){let Q;try{Q=JSON.parse(typeof Z==="string"?Z:new TextDecoder().decode(Z))}catch{$.send(JSON.stringify({type:"response",id:0,success:!1,error:"Invalid JSON"}));return}if(Q.type==="request"){if(Q.method==="stream.createExportToken"){let{connectionId:X,database:W,...Y}=Q.params,G=t$($.data,"export",X,W,Y);$.send(JSON.stringify({type:"response",id:Q.id,success:!0,payload:{token:G}}));return}if(Q.method==="stream.createImportToken"){let{connectionId:X,database:W,...Y}=Q.params,G=t$($.data,"import",X,W,Y);$.send(JSON.stringify({type:"response",id:Q.id,success:!0,payload:{token:G}}));return}let B=$.data.handlers[Q.method];if(!B){$.send(JSON.stringify({type:"response",id:Q.id,success:!1,error:`Unknown method: ${Q.method}`}));return}try{let X=await B(Q.params);$.send(JSON.stringify({type:"response",id:Q.id,success:!0,payload:X}))}catch(X){$.send(JSON.stringify({type:"response",id:Q.id,success:!1,error:X?.message??String(X),errorCode:X instanceof _?X.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${Y5}:${F7.port}`)});var{secrets:V5}=globalThis.Bun;import{randomBytes as P7}from"crypto";import{resolve as k7}from"path";var U5="dev.dotaz.server",j5="encryption-key",l=process.argv.slice(2),J5=6401,K5="localhost";for(let $=0;$<l.length;$++){let Z=l[$];if((Z==="--port"||Z==="-p")&&l[$+1])J5=Number(l[$+1]),$++;else if((Z==="--host"||Z==="-H")&&l[$+1])K5=l[$+1],$++;else if(Z==="--help")console.log(`Usage: dotaz [options]
|
|
313
313
|
|
|
314
314
|
Options:
|
|
315
315
|
-p, --port <port> Port to listen on (default: 6401)
|
|
316
316
|
-H, --host <host> Host to bind to (default: localhost)
|
|
317
317
|
--help Show this help message
|
|
318
|
-
`),process.exit(0)}if(!process.env.DOTAZ_ENCRYPTION_KEY){let $=await
|
|
318
|
+
`),process.exit(0)}if(!process.env.DOTAZ_ENCRYPTION_KEY){let $=await V5.get({service:U5,name:j5});if(!$){$=P7(32).toString("hex");try{await V5.set({service:U5,name:j5,value:$})}catch{}}process.env.DOTAZ_ENCRYPTION_KEY=$}process.env.DOTAZ_PORT=String(J5);process.env.DOTAZ_HOST=K5;process.env.DOTAZ_DIST_DIR=k7(import.meta.dir,"../dist");await Promise.resolve().then(() => (H5(),N7));
|