@dotaz/server 0.0.15 → 0.0.17
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 +49 -33
- package/dist/assets/{index-BUtih2z7.js → index-BUq169v0.js} +39 -38
- package/dist/index.html +1 -1
- package/package.json +1 -1
package/bin/dotaz.js
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var x=($,Z)=>()=>($&&(Z=$($=0)),Z);var
|
|
3
|
+
var x=($,Z)=>()=>($&&(Z=$($=0)),Z);var D5=import.meta.require;function b($){let Z=new Set,B=[];for(let G of $)for(let X of Object.keys(G))if(!Z.has(X))Z.add(X),B.push(X);return B}function C5($){if($===null||$===void 0)return"";if(typeof $==="object")return JSON.stringify($);return String($)}function P$($){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 E5($){if($===null||$===void 0)return"NULL";if(typeof $==="object")return JSON.stringify($);return String($)}function J0($){return $.replace(/\|/g,"\\|").replace(/\n/g," ")}function N$($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function z0($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function T5($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");if(!/^[a-zA-Z_]/.test(Z))Z="_"+Z;return Z}function S5($,Z){return`"${$.replace(/"/g,'""')}"."${Z.replace(/"/g,'""')}"`}function K0($){let Z=$.qualifiedTableName??S5($.schema,$.table);switch($.format){case"csv":return new A0($.delimiter??",",$.includeHeaders??!0);case"json":return new R0;case"sql":return new O0(Z,$.batchSize??100);case"markdown":return new L0;case"sql_update":return new _0(Z);case"html":return new x0;case"xml":return new F0}}class A0{delimiter;includeHeaders;columns=null;constructor($,Z){this.delimiter=$;this.includeHeaders=Z}preamble(){return""}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=b($);let B=this.columns,G=[];if(Z&&this.includeHeaders)G.push(B.map((X)=>this.escapeField(X)).join(this.delimiter));for(let X of $){let W=B.map((Y)=>this.escapeField(C5(X[Y])));G.push(W.join(this.delimiter))}return G.join(`
|
|
4
4
|
`)+`
|
|
5
5
|
`}epilogue(){return""}escapeField($){if($.includes(this.delimiter)||$.includes('"')||$.includes(`
|
|
6
|
-
`)||$.includes("\r"))return`"${$.replace(/"/g,'""')}"`;return $}}class
|
|
6
|
+
`)||$.includes("\r"))return`"${$.replace(/"/g,'""')}"`;return $}}class R0{hasWritten=!1;preamble(){return`[
|
|
7
7
|
`}formatBatch($){if($.length===0)return"";return $.map((B)=>{let G=this.hasWritten?`,
|
|
8
8
|
`:"";return this.hasWritten=!0,G+" "+JSON.stringify(B)}).join("")}epilogue(){return`
|
|
9
9
|
]
|
|
10
|
-
`}}class O0{tableName;batchSize;columns=null;constructor($,Z){this.tableName=$;this.batchSize=Z}preamble(){return""}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=
|
|
10
|
+
`}}class O0{tableName;batchSize;columns=null;constructor($,Z){this.tableName=$;this.batchSize=Z}preamble(){return""}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=b($);let Z=this.columns,G=Z.map((W)=>`"${W.replace(/"/g,'""')}"`).join(", "),X=[];for(let W=0;W<$.length;W+=this.batchSize){let H=$.slice(W,W+this.batchSize).map((V)=>{return`(${Z.map((Q)=>P$(V[Q])).join(", ")})`});X.push(`INSERT INTO ${this.tableName} (${G}) VALUES
|
|
11
11
|
${H.join(`,
|
|
12
12
|
`)};
|
|
13
13
|
`)}return X.join(`
|
|
14
|
-
`)}epilogue(){return""}}class
|
|
14
|
+
`)}epilogue(){return""}}class L0{columns=null;preamble(){return""}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=b($);let B=this.columns,G=[];if(Z)G.push("| "+B.map(J0).join(" | ")+" |"),G.push("| "+B.map(()=>"---").join(" | ")+" |");for(let X of $){let W=B.map((Y)=>J0(E5(X[Y])));G.push("| "+W.join(" | ")+" |")}return G.join(`
|
|
15
15
|
`)+`
|
|
16
|
-
`}epilogue(){return""}}class _0{tableName;columns=null;constructor($){this.tableName=$}preamble(){return""}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=
|
|
17
|
-
`)}return X.join("")}epilogue(){return""}}class
|
|
18
|
-
`}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=
|
|
16
|
+
`}epilogue(){return""}}class _0{tableName;columns=null;constructor($){this.tableName=$}preamble(){return""}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=b($);let Z=this.columns,B=Z[0],G=Z.slice(1),X=[];for(let W of $){if(G.length===0)continue;let Y=G.map((V)=>`"${V.replace(/"/g,'""')}" = ${P$(W[V])}`).join(", "),H=`"${B.replace(/"/g,'""')}" = ${P$(W[B])}`;X.push(`UPDATE ${this.tableName} SET ${Y} WHERE ${H};
|
|
17
|
+
`)}return X.join("")}epilogue(){return""}}class x0{columns=null;preamble(){return`<table>
|
|
18
|
+
`}formatBatch($,Z){if($.length===0)return"";if(!this.columns)this.columns=b($);let B=this.columns,G=[];if(Z){G.push(" <thead>"),G.push(" <tr>");for(let X of B)G.push(` <th>${N$(X)}</th>`);G.push(" </tr>"),G.push(" </thead>"),G.push(" <tbody>")}for(let X of $){G.push(" <tr>");for(let W of B){let Y=X[W],H=Y===null||Y===void 0?"":typeof Y==="object"?N$(JSON.stringify(Y)):N$(String(Y));G.push(` <td>${H}</td>`)}G.push(" </tr>")}return G.join(`
|
|
19
19
|
`)+`
|
|
20
20
|
`}epilogue(){return` </tbody>
|
|
21
21
|
</table>
|
|
22
|
-
`}}class
|
|
22
|
+
`}}class F0{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=
|
|
24
|
+
`}formatBatch($){if($.length===0)return"";if(!this.columns)this.columns=b($);let Z=this.columns,B=[];for(let G of $){B.push(" <row>");for(let X of Z){let W=G[X],Y=T5(X);if(W===null||W===void 0)B.push(` <${Y} xsi:nil="true"/>`);else{let H=typeof W==="object"?z0(JSON.stringify(W)):z0(String(W));B.push(` <${Y}>${H}</${Y}>`)}}B.push(" </row>")}return B.join(`
|
|
25
25
|
`)+`
|
|
26
26
|
`}epilogue(){return`</rows>
|
|
27
|
-
`}}var
|
|
28
|
-
`)J++;else if(
|
|
27
|
+
`}}var r7;var I=x(()=>{r7=Object.freeze({__dotaz_sentinel:"DEFAULT"})});function k$($){return $.includes(".")}function D$($){let Z=$.indexOf(".");return{table:$.substring(0,Z),column:$.substring(Z+1)}}function C$($,Z){return(B)=>{if(k$(B)){let{table:G,column:X}=D$(B),W=$.find((Y)=>Y.referencedTable===G);if(W)return`${Z.quoteIdentifier(W.alias)}.${Z.quoteIdentifier(X)}`}return`t0.${Z.quoteIdentifier(B)}`}}function B$($,Z,B=0,G){if(!$||$.length===0)return{sql:"",params:[]};let X=[],W=[],Y=B;for(let H of $){let V=G?G(H.column):Z.quoteIdentifier(H.column);switch(H.operator){case"eq":Y++,X.push(`${V} = ${Z.placeholder(Y)}`),W.push(H.value);break;case"neq":Y++,X.push(`${V} != ${Z.placeholder(Y)}`),W.push(H.value);break;case"gt":Y++,X.push(`${V} > ${Z.placeholder(Y)}`),W.push(H.value);break;case"gte":Y++,X.push(`${V} >= ${Z.placeholder(Y)}`),W.push(H.value);break;case"lt":Y++,X.push(`${V} < ${Z.placeholder(Y)}`),W.push(H.value);break;case"lte":Y++,X.push(`${V} <= ${Z.placeholder(Y)}`),W.push(H.value);break;case"like":Y++,X.push(`${V} LIKE ${Z.placeholder(Y)}`),W.push(H.value);break;case"notLike":Y++,X.push(`${V} NOT LIKE ${Z.placeholder(Y)}`),W.push(H.value);break;case"in":{let U=Array.isArray(H.value)?H.value:[H.value],Q=U.map(()=>{return Y++,Z.placeholder(Y)});X.push(`${V} IN (${Q.join(", ")})`),W.push(...U);break}case"notIn":{let U=Array.isArray(H.value)?H.value:[H.value],Q=U.map(()=>{return Y++,Z.placeholder(Y)});X.push(`${V} NOT IN (${Q.join(", ")})`),W.push(...U);break}case"isNull":X.push(`${V} IS NULL`);break;case"isNotNull":X.push(`${V} IS NOT NULL`);break}}if(X.length===0)return{sql:"",params:[]};return{sql:`WHERE ${X.join(" AND ")}`,params:W}}function G$($,Z,B){if(!$||$.length===0)return"";return`ORDER BY ${$.map((X)=>{let W=B?B(X.column):Z.quoteIdentifier(X.column),Y=X.direction==="desc"?"DESC":"ASC";return`${W} ${Y}`}).join(", ")}`}function E$($,Z){return $.map((B)=>{let G=Z.qualifyTable(B.referencedSchema,B.referencedTable),X=Z.quoteIdentifier(B.alias),W;if(k$(B.fkColumn)){let{table:H,column:V}=D$(B.fkColumn),U=$.find((Q)=>Q.referencedTable===H);if(U)W=`${Z.quoteIdentifier(U.alias)}.${Z.quoteIdentifier(V)}`;else W=`t0.${Z.quoteIdentifier(B.fkColumn)}`}else W=`t0.${Z.quoteIdentifier(B.fkColumn)}`;let Y=`${X}.${Z.quoteIdentifier(B.referencedColumn)}`;return`LEFT JOIN ${G} AS ${X} ON ${W} = ${Y}`}).join(" ")}var X$=x(()=>{I()});async function T$($,Z,B,G,X){let W=b5(Z.format==="csv"?Z.encoding:void 0),Y=P0(Z,$),H=0;if(Z.format==="csv"&&Z.utf8Bom&&(Z.encoding??"utf-8")==="utf-8")await B.write(new Uint8Array([239,187,191]));let V=Y.preamble();if(V)await B.write(W(V));let{sql:U,params:Q}=W$(Z,$),j=Z.batchSize??q5,K=$.iterate(U,Q,j,G),A=!0;for await(let R of K){let z=R;if(Z.limit!==void 0){let L=Z.limit-H;if(L<=0)break;if(z.length>L)z=z.slice(0,L)}let O=Y.formatBatch(z,A);if(await B.write(W(O)),H+=z.length,X?.(H),A=!1,Z.limit!==void 0&&H>=Z.limit)break}let J=Y.epilogue();if(J)await B.write(W(J));return await B.end(),{rowCount:H}}async function M0($,Z,B,G,X){let Y=Bun.file(B).writer(),H={write(V){Y.write(V)},async end(){await Y.end()}};try{let V=await T$($,Z,H,G,X),U=await Bun.file(B).stat();return{rowCount:V.rowCount,sizeBytes:U?.size??0}}catch(V){await Y.end();try{let{unlink:U}=await import("fs/promises");await U(B)}catch{}throw V}}async function N0($,Z){let B=Z.limit??10,{sql:G,params:X}=W$(Z,$),W=X.length;W++;let Y=$.placeholder(W),H=`${G} LIMIT ${Y}`,U=(await $.execute(H,[...X,B])).rows,Q=P0(Z,$),j=[],K=Q.preamble();if(K)j.push(K);j.push(Q.formatBatch(U,!0));let A=Q.epilogue();if(A)j.push(A);return j.join("")}function W$($,Z){let B=$.autoJoins,G=B&&B.length>0,X=Z.qualifyTable($.schema,$.table),W=G?C$(B,Z):void 0,Y=B$($.filters,Z,0,W),H=G$($.sort,Z,W);if(G){let Q=E$(B,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 K=[`SELECT ${j} FROM ${X} AS t0 ${Q}`];if(Y.sql)K.push(Y.sql);if(H)K.push(H);return{sql:K.join(" "),params:[...Y.params]}}let U=[`SELECT ${$.columns&&$.columns.length>0?$.columns.map((Q)=>Z.quoteIdentifier(Q)).join(", "):"*"} FROM ${X}`];if(Y.sql)U.push(Y.sql);if(H)U.push(H);return{sql:U.join(" "),params:[...Y.params]}}function P0($,Z){return K0({format:$.format,schema:$.schema,table:$.table,delimiter:$.delimiter,includeHeaders:$.includeHeaders,batchSize:$.batchSize,qualifiedTableName:Z.qualifyTable($.schema,$.table)})}function h5($){let Z=new Uint8Array($.length);for(let B=0;B<$.length;B++){let G=$.charCodeAt(B);Z[B]=G<=255?G:63}return Z}function w5($){let Z=new Uint8Array($.length);for(let B=0;B<$.length;B++){let G=$.charCodeAt(B);if(G<=255)Z[B]=G;else Z[B]=y5[G]??63}return Z}function b5($){switch($){case"iso-8859-1":return h5;case"windows-1252":return w5;default:return(Z)=>Z}}var q5=1000,y5;var S$=x(()=>{X$();y5={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*q$($,Z){let{delimiter:B,hasHeader:G,batchSize:X,maxRows:W,maxBufferSize:Y=67108864}=Z,H=new TextDecoder("utf-8"),V=$.getReader(),U="",Q=0,j=!1,K="",A=[],J=1,R=null,z=0,O=[],L=!1;function P(T){if(T.length===1&&T[0]==="")return 0;if(R===null){if(G)return R=T,0;R=T.map((F,k)=>`col${k+1}`)}if(O.push(v5(T,R)),z++,W!==void 0&&z>=W)return 2;if(O.length>=X)return 1;return 0}try{while(!L){let T=await V.read();if(T.done)U+=H.decode(new Uint8Array(0),{stream:!1}),L=!0;else U+=H.decode(T.value,{stream:!0});if(U.length>Y)throw new Y$(`buffer size exceeded ${Y/1048576}MB \u2014 possible malformed input or extremely large field`,J);while(Q<U.length){let F=U[Q];if(j)if(F==='"')if(Q+1<U.length)if(U[Q+1]==='"')K+='"',Q+=2;else j=!1,Q++;else if(L)j=!1,Q++;else break;else{if(F===`
|
|
28
|
+
`)J++;else if(F==="\r"){if(J++,Q+1<U.length){if(U[Q+1]===`
|
|
29
29
|
`){K+=`\r
|
|
30
|
-
`,Q+=2;continue}}else if(!
|
|
31
|
-
`){if(
|
|
32
|
-
`)Q++}else if(
|
|
30
|
+
`,Q+=2;continue}}else if(!L)break}K+=F,Q++}else if(F==='"')j=!0,Q++;else if(F===B)A.push(K),K="",Q++;else if(F==="\r"||F===`
|
|
31
|
+
`){if(F==="\r")if(Q+1<U.length){if(Q++,U[Q]===`
|
|
32
|
+
`)Q++}else if(L)Q++;else break;else Q++;A.push(K),K="",J++;let k=P(A);switch(A=[],k){case 2:if(O.length>0)yield{columns:R,rows:O},O=[];return;case 1:yield{columns:R,rows:O},O=[];break}}else K+=F,Q++}if(Q>0)U=U.slice(Q),Q=0}if(j)throw new Y$("Unclosed quote",J);if(K!==""||A.length>0)A.push(K),P(A);if(O.length>0)yield{columns:R??[],rows:O}}finally{V.releaseLock()}}function v5($,Z){let B={};for(let G=0;G<Z.length;G++){let X=G<$.length?$[G]:null;B[Z[G]]=X===""?null:g5(X)}return B}function g5($){if($===null||$==="")return null;let Z=$.toLowerCase();if(Z==="true")return!0;if(Z==="false")return!1;if(/^-?\d+$/.test($)){let B=parseInt($,10);if(Number.isSafeInteger(B))return B}if(/^-?\d+\.\d+$/.test($)){let B=parseFloat($);if(Number.isFinite(B))return B}return $}var Y$;var k0=x(()=>{Y$=class Y$ extends Error{lineNumber;constructor($,Z){super(`CSV parse error at line ${Z}: ${$}`);this.name="CsvParseError",this.lineNumber=Z}}});async function H$($,Z,B,G,X){let W=B.mappings.filter((j)=>j.tableColumn!==null);if(W.length===0)throw Error("No columns mapped for import");if(B.format==="json")return f5($,Z,B,W,G,X);let Y=$.qualifyTable(B.schema,B.table),H=W.map((j)=>j.tableColumn),V=B.batchSize??D0,U={delimiter:B.delimiter??",",hasHeader:B.hasHeader??!0,batchSize:V},Q=`__import_${crypto.randomUUID()}`;await $.reserveSession(Q);try{await $.beginTransaction(Q);let j=0;for await(let{rows:K}of q$(Z,U)){if(G?.aborted)throw Error("Import cancelled");let A=K.map((J)=>T0(J,W));await $.importBatch(Y,H,A,Q),j+=K.length,X?.(j)}return await $.commit(Q),{rowCount:j}}catch(j){try{await $.rollback(Q)}catch(K){console.debug("Rollback after import error failed:",K instanceof Error?K.message:K)}throw j}finally{await $.releaseSession(Q)}}async function C0($,Z){let B=Z.limit??20;if(Z.format==="json")return u5($);let G={delimiter:Z.delimiter??",",hasHeader:Z.hasHeader??!0,batchSize:B,maxRows:B},X=[],W=[];for await(let Y of q$($,G))W=Y.columns,X.push(...Y.rows);return{fileColumns:W,rows:X.slice(0,B),totalRows:void 0}}async function f5($,Z,B,G,X,W){let Y=await S0(Z),H=E0(Y),V=$.qualifyTable(B.schema,B.table),U=G.map((K)=>K.tableColumn),Q=B.batchSize??D0,j=`__import_${crypto.randomUUID()}`;await $.reserveSession(j);try{await $.beginTransaction(j);let K=0;for(let A=0;A<H.length;A+=Q){if(X?.aborted)throw Error("Import cancelled");let J=H.slice(A,A+Q),R=J.map((z)=>T0(z,G));await $.importBatch(V,U,R,j),K+=J.length,W?.(K)}return await $.commit(j),{rowCount:K}}catch(K){try{await $.rollback(j)}catch(A){console.debug("Rollback after import error failed:",A instanceof Error?A.message:A)}throw K}finally{await $.releaseSession(j)}}async function u5($){let Z=await S0($),B=E0(Z);return{fileColumns:I5(B),rows:B.slice(0,20),totalRows:B.length}}function E0($){let Z=JSON.parse($);if(!Array.isArray(Z))throw Error("JSON import expects an array of objects");let B=[];for(let G of Z){if(typeof G!=="object"||G===null||Array.isArray(G))throw Error("Each JSON array element must be an object");B.push(G)}return B}function T0($,Z){let B={};for(let G of Z)B[G.tableColumn]=$[G.fileColumn]??null;return B}function I5($){let Z=new Set,B=[];for(let G of $)for(let X of Object.keys(G))if(!Z.has(X))Z.add(X),B.push(X);return B}async function S0($){let Z=$.getReader(),B=new TextDecoder("utf-8"),G="";while(!0){let{done:X,value:W}=await Z.read();if(X)break;G+=B.decode(W,{stream:!0})}return G+=B.decode(new Uint8Array(0),{stream:!1}),Z.releaseLock(),G}var D0=100;var y$=x(()=>{k0()});var _,D,V$,N,C;var q=x(()=>{_=class _ extends Error{code;constructor($,Z,B){super(Z,B);this.name="DatabaseError",this.code=$}};D=class D extends _{constructor($,Z,B){super($,Z,B);this.name="ConnectionError"}};V$=class V$ extends _{constructor($,Z){super("AUTH_FAILED",$,Z);this.name="AuthenticationError"}};N=class N extends _{constructor($,Z,B){super($,Z,B);this.name="QueryError"}};C=class C extends _{constructor($,Z,B){super($,Z,B);this.name="ConstraintError"}}});function Q$($){let Z=[],B="",G=0;while(G<$.length){let W=$[G],Y=G+1<$.length?$[G+1]:"";if(W==="-"&&Y==="-"){let H=$.indexOf(`
|
|
33
33
|
`,G);if(H===-1)B+=$.slice(G),G=$.length;else B+=$.slice(G,H+1),G=H+1;continue}if(W==="/"&&Y==="*"){let H=$.indexOf("*/",G+2);if(H===-1)B+=$.slice(G),G=$.length;else B+=$.slice(G,H+2),G=H+2;continue}if(W==="$"){let H=$.slice(G).match(/^(\$[a-zA-Z0-9_]*\$)/);if(H){let V=H[1],U=$.indexOf(V,G+V.length);if(U===-1)B+=$.slice(G),G=$.length;else B+=$.slice(G,U+V.length),G=U+V.length;continue}}if(W==="'"){B+=W,G++;while(G<$.length)if($[G]==="'")if(B+=$[G],G++,G<$.length&&$[G]==="'")B+=$[G],G++;else break;else B+=$[G],G++;continue}if(W==='"'){B+=W,G++;while(G<$.length)if($[G]==='"')if(B+=$[G],G++,G<$.length&&$[G]==='"')B+=$[G],G++;else break;else B+=$[G],G++;continue}if(W===";"){let H=B.trim();if(H.length>0)Z.push(H);B="",G++;continue}B+=W,G++}let X=B.trim();if(X.length>0)Z.push(X);return Z}function U$($,Z){let B=1,G=1,X=Math.min(Z-1,$.length);for(let W=0;W<X;W++)if($[W]===`
|
|
34
34
|
`)B++,G=1;else G++;return{line:B,column:G}}function h$($){let Z="",B=0;while(B<$.length){let G=$[B],X=B+1<$.length?$[B+1]:"";if(G==="-"&&X==="-"){let W=$.indexOf(`
|
|
35
|
-
`,B);Z+=" ",B=W===-1?$.length:W+1;continue}if(G==="/"&&X==="*"){let W=$.indexOf("*/",B+2);Z+=" ",B=W===-1?$.length:W+2;continue}if(G==="$"){let W=$.slice(B).match(/^(\$[a-zA-Z0-9_]*\$)/);if(W){let Y=W[1],H=$.indexOf(Y,B+Y.length);Z+=" ",B=H===-1?$.length:H+Y.length;continue}}if(G==="'"){Z+=" ",B++;while(B<$.length)if($[B]==="'")if(B++,B<$.length&&$[B]==="'")B++;else break;else B++;continue}if(G==='"'){Z+=" ",B++;while(B<$.length)if($[B]==='"')if(B++,B<$.length&&$[B]==='"')B++;else break;else B++;continue}Z+=G,B++}return Z}function j$($,Z){if(!$||typeof $!=="object")return;let B=$;if(B.position!=null){let G=Number(B.position);if(!Number.isNaN(G)&&G>0){let{line:X,column:W}=U$(Z,G);return{line:X,column:W,offset:G}}}if($ instanceof Error){let G=$.message.match(/at offset (\d+)/);if(G){let X=Number(G[1])+1,{line:W,column:Y}=U$(Z,X);return{line:W,column:Y,offset:X}}}return}async function i($,Z){let B=`__ephemeral_${crypto.randomUUID()}`;await $.reserveSession(B);try{return await Z(B)}finally{try{await $.cancel(B)}catch{}try{await $.releaseSession(B)}catch{}}}class
|
|
36
|
-
`);return{nodes:
|
|
37
|
-
`),
|
|
38
|
-
`)}catch{
|
|
35
|
+
`,B);Z+=" ",B=W===-1?$.length:W+1;continue}if(G==="/"&&X==="*"){let W=$.indexOf("*/",B+2);Z+=" ",B=W===-1?$.length:W+2;continue}if(G==="$"){let W=$.slice(B).match(/^(\$[a-zA-Z0-9_]*\$)/);if(W){let Y=W[1],H=$.indexOf(Y,B+Y.length);Z+=" ",B=H===-1?$.length:H+Y.length;continue}}if(G==="'"){Z+=" ",B++;while(B<$.length)if($[B]==="'")if(B++,B<$.length&&$[B]==="'")B++;else break;else B++;continue}if(G==='"'){Z+=" ",B++;while(B<$.length)if($[B]==='"')if(B++,B<$.length&&$[B]==='"')B++;else break;else B++;continue}Z+=G,B++}return Z}function j$($,Z){if(!$||typeof $!=="object")return;let B=$;if(B.position!=null){let G=Number(B.position);if(!Number.isNaN(G)&&G>0){let{line:X,column:W}=U$(Z,G);return{line:X,column:W,offset:G}}}if($ instanceof Error){let G=$.message.match(/at offset (\d+)/);if(G){let X=Number(G[1])+1,{line:W,column:Y}=U$(Z,X);return{line:W,column:Y,offset:X}}}return}async function i($,Z){let B=`__ephemeral_${crypto.randomUUID()}`;await $.reserveSession(B);try{return await Z(B)}finally{try{await $.cancel(B)}catch{}try{await $.releaseSession(B)}catch{}}}class q0{logs=new Map;pendingCounts=new Map;key($,Z){return Z?`${$}:${Z}`:$}pendingKey($,Z,B){let G=this.key($,Z);return B?`${G}:${B}`:G}add($,Z,B,G,X,W,Y,H){let V=this.key($,Y);if(!this.logs.has(V))this.logs.set(V,[]);this.logs.get(V).push({id:crypto.randomUUID(),sql:Z,status:B,durationMs:G,rowCount:X,errorMessage:W,executedAt:new Date().toISOString()});let U=this.pendingKey($,Y,H);this.pendingCounts.set(U,(this.pendingCounts.get(U)??0)+1);let Q=Z.trim().toUpperCase();if(/^(COMMIT|END|ROLLBACK)\b/.test(Q)&&!/^ROLLBACK\s+TO\b/.test(Q))this.resetPendingCount($,Y,H);else if(/^(BEGIN|START\s+TRANSACTION)\b/.test(Q))this.resetPendingCount($,Y,H)}getEntries($,Z){return this.logs.get(this.key($,Z))??[]}getPendingCount($,Z,B){return this.pendingCounts.get(this.pendingKey($,Z,B))??0}resetPendingCount($,Z,B){this.pendingCounts.delete(this.pendingKey($,Z,B))}clear($,Z){let B=this.key($,Z);this.logs.delete(B),this.pendingCounts.delete(B);let G=`${B}:`;for(let X of this.pendingCounts.keys())if(X.startsWith(G))this.pendingCounts.delete(X)}}class n{connectionManager;runningQueries=new Map;defaultTimeoutMs;appDb;sessionLog=new q0;constructor($,Z=30000,B){this.connectionManager=$,this.defaultTimeoutMs=Z,this.appDb=B}async executeQuery($,Z,B,G,X,W,Y,H){let V=this.connectionManager.getDriver($,W),U=Q$(Z);if(U.length===0)return[];if(!Y&&U.length===1){let j=U[0].trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION|COMMIT|END|ROLLBACK)\b/.test(j)&&!/^ROLLBACK\s+TO\b/.test(j))return[{columns:[],rows:[],rowCount:0,durationMs:0,error:"Transaction control statements (BEGIN, COMMIT, ROLLBACK) require a session. Open a session tab to use manual transactions."}]}let Q=async(j)=>{let K=X??crypto.randomUUID(),A={queryId:K,connectionId:$,database:W,cancelled:!1,sessionId:j};this.runningQueries.set(K,A);let J=G??this.defaultTimeoutMs,R=[],z;try{if(H&&j!==void 0){z=(await V.execute("SHOW search_path",void 0,j)).rows[0]?.search_path;let L=J$(H,V);await V.execute(`SET search_path TO ${L}`,void 0,j)}for(let O of U){if(A.cancelled){R.push(w$());break}let L=await this.executeSingle(V,O,U.length===1?B:void 0,J,A,j);if(R.push(L),L.error)break}}finally{if(z!==void 0&&j!==void 0)try{let O=J$(z,V);await V.execute(`SET search_path TO ${O}`,void 0,j)}catch{}this.runningQueries.delete(K),this.logHistory($,Z,R,W,Y)}return R};if(!Y&&(U.length>1||H))return i(V,Q);return Q(Y)}async cancelQuery($){let Z=this.runningQueries.get($);if(!Z)return!1;Z.cancelled=!0;try{let B=this.connectionManager.getDriver(Z.connectionId,Z.database);if(Z.sessionId!==void 0)await B.cancel(Z.sessionId);else await B.cancel(void 0,Z.poolQueryKey)}catch(B){console.debug("Cancel query failed (driver may have completed):",B instanceof Error?B.message:B)}return!0}async cancelAllForConnection($){let Z=[];for(let[G,X]of this.runningQueries)if(X.connectionId===$)Z.push(G);let B=0;for(let G of Z)if(await this.cancelQuery(G))B++;return B}getRunningQueryIds(){return[...this.runningQueries.keys()]}async explainQuery($,Z,B,G,X,W){let Y=this.connectionManager.getDriver($,G),H=Y.getDriverType(),V=performance.now(),U=async(Q)=>{let j;try{if(W&&Q!==void 0){j=(await Y.execute("SHOW search_path",void 0,Q)).rows[0]?.search_path;let k=J$(W,Y);await Y.execute(`SET search_path TO ${k}`,void 0,Q)}if(H==="sqlite"){let F=Q!==void 0?await Y.execute(`EXPLAIN QUERY PLAN ${Z}`,void 0,Q):await Y.execute(`EXPLAIN QUERY PLAN ${Z}`),k=Math.round(performance.now()-V),h=r5(F.rows),$$=F.rows.map((w)=>`${w.id}|${w.parent}|${w.notused??0}|${w.detail}`).join(`
|
|
36
|
+
`);return{nodes:h,rawText:$$,durationMs:k}}let K=H==="mysql",A=K?B?"EXPLAIN ANALYZE":"EXPLAIN FORMAT=JSON":B?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",J=Q!==void 0?await Y.execute(`${A} ${Z}`,void 0,Q):await Y.execute(`${A} ${Z}`),R=Math.round(performance.now()-V),z,O,L;if(K&&B)return L=J.rows.map((F)=>Object.values(F)[0]).join(`
|
|
37
|
+
`),O=[{operation:L,children:[]}],{nodes:O,rawText:L,durationMs:R};let P=J.rows[0]?.["QUERY PLAN"]??J.rows[0]?.EXPLAIN??JSON.stringify(J.rows);if(z=typeof P==="string"?JSON.parse(P):P,O=(Array.isArray(z)?z:[z]).map((F)=>y0(F.Plan??F)),B)L=JSON.stringify(z,null,2);else try{L=(Q!==void 0?await Y.execute(`EXPLAIN ${Z}`,void 0,Q):await Y.execute(`EXPLAIN ${Z}`)).rows.map((h)=>Object.values(h)[0]).join(`
|
|
38
|
+
`)}catch{L=JSON.stringify(z,null,2)}return{nodes:O,rawText:L,durationMs:R}}catch(K){let A=Math.round(performance.now()-V);return{nodes:[],rawText:"",durationMs:A,error:K instanceof Error?K.message:String(K)}}finally{if(j!==void 0&&Q!==void 0)try{let K=J$(j,Y);await Y.execute(`SET search_path TO ${K}`,void 0,Q)}catch{}}};if(!X&&W)return i(Y,U);return U(X)}async executeSingle($,Z,B,G,X,W){let Y=performance.now(),V=G===0?null:this.createTimeout(G),U=W===void 0?Symbol():void 0;X.poolQueryKey=U;try{let Q=W!==void 0?$.execute(Z,B,W):$.execute(Z,B,void 0,U),j=V?await Promise.race([Q,V.promise]):await Q;if(X.cancelled)return w$(performance.now()-Y);return{...j,durationMs:Math.round(performance.now()-Y)}}catch(Q){let j=Math.round(performance.now()-Y);if(V?.fired)try{if(W!==void 0)await $.cancel(W);else await $.cancel(void 0,U)}catch{}if(X.cancelled)return w$(j);if(V?.fired){let J=Z.trim().toUpperCase();if(/^(COMMIT|END)\b/.test(J))return{columns:[],rows:[],rowCount:0,durationMs:j,errorCode:"COMMIT_UNCERTAIN",error:"Connection lost or timed out during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying."};if(/^(INSERT|UPDATE|DELETE|MERGE)\b/.test(J))return{columns:[],rows:[],rowCount:0,durationMs:j,errorCode:"STATEMENT_UNCERTAIN",error:"Statement timed out but may have been executed by the server. Verify your data before retrying."}}let K=j$(Q,Z),A=Q instanceof _?Q.code:void 0;return{columns:[],rows:[],rowCount:0,durationMs:j,error:Q instanceof Error?Q.message:String(Q),errorCode:A,errorPosition:K}}finally{V?.cancel()}}createTimeout($){let Z,B=!1;return{promise:new Promise((X,W)=>{Z=setTimeout(()=>{B=!0,W(Error(`Query timed out after ${$}ms`))},$)}),cancel:()=>clearTimeout(Z),get fired(){return B}}}logHistory($,Z,B,G,X){let W=B.some((U)=>U.error),Y=B.reduce((U,Q)=>U+(Q.durationMs??0),0),H=B.reduce((U,Q)=>U+(Q.affectedRows??Q.rowCount),0),V=B.find((U)=>U.error)?.error;if(this.sessionLog.add($,Z,W?"error":"success",Math.round(Y),H,V,G,X),!this.appDb)return;try{this.appDb.addHistory({connectionId:$,database:G,sql:Z,status:W?"error":"success",durationMs:Math.round(Y),rowCount:H,errorMessage:V})}catch(U){console.debug("History logging failed:",U instanceof Error?U.message:U)}}}function w$($=0){return{columns:[],rows:[],rowCount:0,durationMs:Math.round($),error:"Query was cancelled"}}function J$($,Z){return $.split(",").map((B)=>{let G=B.trim();if(G.startsWith('"')&&G.endsWith('"'))G=G.slice(1,-1).replace(/""/g,'"');return Z.quoteIdentifier(G)}).join(", ")}function y0($){let Z=$.Plans??[],{"Node Type":B,"Relation Name":G,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)=>y0(Y))}}function r5($){let Z=new Map,B=new Map;for(let G of $){let X=Number(G.id??G.selectid??0),W=Number(G.parent??0),Y=String(G.detail??""),H={operation:Y,children:[]},V=Y.match(/^(SCAN|SEARCH|USE TEMP B-TREE)\s+(.*)/i);if(V){H.operation=V[1];let Q=V[2].match(/^(\S+)/);if(Q)H.relation=Q[1]}if(Z.set(X,H),!B.has(W))B.set(W,[]);B.get(W).push(H)}for(let[G,X]of Z)X.children=B.get(G)??[];return B.get(0)??[...Z.values()].filter((G,X)=>{let W=$[X],Y=Number(W?.parent??0);return!Z.has(Y)})}var b$=x(()=>{q();X$()});function m($){switch($.type){case"postgresql":return $.database;case"sqlite":return $.path;case"mysql":return $.database}}function v($){return y[$.type].hasHost}var y;var v$=x(()=>{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 a5,createDecipheriv as s5,hkdfSync as _9,randomBytes as e5}from"crypto";class u${keyPromise;constructor($){this.keyPromise=Z7($)}async encrypt($){let Z=await this.keyPromise,B=crypto.getRandomValues(new Uint8Array(g$)),G=new TextEncoder().encode($),X=await crypto.subtle.encrypt({name:f$,iv:B},Z,G),W=new Uint8Array(B.length+X.byteLength);return W.set(B,0),W.set(new Uint8Array(X),B.length),Buffer.from(W).toString("base64")}async decrypt($){let Z=await this.keyPromise,B=new Uint8Array(Buffer.from($,"base64")),G=B.slice(0,g$),X=B.slice(g$),W=await crypto.subtle.decrypt({name:f$,iv:G},Z,X);return new TextDecoder().decode(W)}}async function Z7($){let Z=new TextEncoder().encode($),B=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")},B,{name:f$,length:$7},!1,["encrypt","decrypt"])}function g($,Z){let B=new Uint8Array(e5(o)),G=a5("aes-256-gcm",Z,B),X=G.update($,"utf8"),W=G.final(),Y=new Uint8Array(G.getAuthTag()),H=new Uint8Array(X.length+W.length);H.set(X,0),H.set(W,X.length);let V=new Uint8Array(B.length+Y.length+H.length);return V.set(B,0),V.set(Y,B.length),V.set(H,B.length+Y.length),z$+Buffer.from(V).toString("base64")}function K$($,Z){if(!$.startsWith(z$))return $;let B=new Uint8Array(Buffer.from($.slice(z$.length),"base64")),G=B.subarray(0,o),X=B.subarray(o,o+h0),W=B.subarray(o+h0),Y=s5("aes-256-gcm",Z,G);return Y.setAuthTag(X),Y.update(W).toString("utf8")+Y.final("utf8")}function f($){return $.startsWith(z$)}var f$="AES-GCM",g$=12,$7=256,z$="enc:v1:",o=12,h0=16;var I$=()=>{};function G7($){$.run(`
|
|
39
39
|
CREATE TABLE IF NOT EXISTS schema_version (
|
|
40
40
|
version INTEGER PRIMARY KEY,
|
|
41
41
|
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
42
42
|
)
|
|
43
|
-
`)}function
|
|
43
|
+
`)}function X7($){return $.prepare("SELECT MAX(version) as version FROM schema_version").get()?.version??0}function w0($){G7($);let Z=X7($),B=B7.filter((G)=>G.version>Z);for(let G of B){if(G.disableForeignKeys)$.run("PRAGMA foreign_keys = OFF");$.run("BEGIN");try{G.up($),$.run("INSERT INTO schema_version (version) VALUES (?)",[G.version]),$.run("COMMIT")}catch(X){throw $.run("ROLLBACK"),X}if(G.disableForeignKeys)$.run("PRAGMA foreign_keys = ON")}return B.length}var B7;var b0=x(()=>{B7=[{version:1,description:"Create connections, query_history, saved_views, settings tables",up:($)=>{$.run(`
|
|
44
44
|
CREATE TABLE connections (
|
|
45
45
|
id TEXT PRIMARY KEY,
|
|
46
46
|
name TEXT NOT NULL,
|
|
47
|
-
type TEXT NOT NULL
|
|
47
|
+
type TEXT NOT NULL,
|
|
48
48
|
config TEXT NOT NULL,
|
|
49
49
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
50
50
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
@@ -95,8 +95,24 @@ ${H.join(`,
|
|
|
95
95
|
data TEXT NOT NULL,
|
|
96
96
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
97
97
|
)
|
|
98
|
-
`)}},{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 X7 from"bun:sqlite";class a{db;localKey=null;constructor($){this.db=new X7($,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),h0(this.db)}static getInstance($){if(!l){let Z=$??W7();l=new a(Z)}return l}static create($){return new a($)}close(){this.db.close()}transaction($){return this.db.transaction($)()}static resetInstance(){if(l)l.db.close(),l=null}setLocalKey($){this.localKey=$,this.migratePasswords()}encryptConfigJson($){if(this.localKey&&g($)){let Z={...$,password:f($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let B={...$.sshTunnel};if(B.password)B.password=f(B.password,this.localKey);if(B.keyPassphrase)B.keyPassphrase=f(B.keyPassphrase,this.localKey);Z={...Z,sshTunnel:B}}return JSON.stringify(Z)}return JSON.stringify($)}decryptConfig($){if(this.localKey&&g($)&&u($.password)){let Z={...$,password:K$($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let B={...$.sshTunnel};if(B.password&&u(B.password))B.password=K$(B.password,this.localKey);if(B.keyPassphrase&&u(B.keyPassphrase))B.keyPassphrase=K$(B.keyPassphrase,this.localKey);Z={...Z,sshTunnel:B}}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 B of $)try{let G=JSON.parse(B.config);if(g(G)){let X=!1,W={...G};if(!u(G.password))W={...W,password:f(G.password,this.localKey)},X=!0;if(G.type==="postgresql"&&G.sshTunnel){let Y={...G.sshTunnel};if(Y.password&&!u(Y.password))Y.password=f(Y.password,this.localKey),X=!0;if(Y.keyPassphrase&&!u(Y.keyPassphrase))Y.keyPassphrase=f(Y.keyPassphrase,this.localKey),X=!0;if(X)W={...W,sshTunnel:Y}}if(X)Z.run(JSON.stringify(W),B.id)}}catch{}})}toConnectionInfo($){let Z=g0($.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 B=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,B,B),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 B=this.getConnectionById($.id);if(!B)throw Error(`Connection not found: ${$.id}`);return B}setConnectionGroup($,Z){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(Z,$);let B=this.getConnectionById($);if(!B)throw Error(`Connection not found: ${$}`);return B}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 B=this.getConnectionById($);if(!B)throw Error(`Connection not found: ${$}`);return B}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($)??r[$]??null;if(Z===null)return null;let B=Number(Z);return Number.isFinite(B)?B:null}getBooleanSetting($){let Z=this.getSetting($)??r[$]??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 B of $)Z[B.key]=B.value;return Z}listSavedViews($,Z,B){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all($,Z,B).map(m$)}createSavedView($){let Z=crypto.randomUUID(),B=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),B,B),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 B=this.getSavedViewById($.id);if(!B)throw Error(`Saved view not found: ${$.id}`);return B}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(m$)}getSavedViewById($){let Z=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get($);return Z?m$(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(),w0(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,B=$.offset??0,G=[],X=[];if($.connectionId)G.push("connection_id = ?"),X.push($.connectionId);if($.search)G.push("sql LIKE ?"),X.push(`%${$.search}%`);if($.startDate)G.push("executed_at >= ?"),X.push($.startDate+" 00:00:00");if($.endDate){let V=new Date($.endDate+"T00:00:00Z");V.setUTCDate(V.getUTCDate()+1);let U=V.getUTCFullYear(),Q=String(V.getUTCMonth()+1).padStart(2,"0"),j=String(V.getUTCDate()).padStart(2,"0");G.push("executed_at < ?"),X.push(`${U}-${Q}-${j} 00:00:00`)}let Y=`SELECT * FROM query_history ${G.length>0?`WHERE ${G.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return X.push(Z,B),this.db.prepare(Y).all(...X).map(w0)}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(p$);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all($).map(p$)}createBookmark($){let Z=crypto.randomUUID(),B=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,B,B),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 B=this.getBookmarkById($.id);if(!B)throw Error(`Bookmark not found: ${$.id}`);return B}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?p$(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 g0($,Z){try{return JSON.parse($)}catch{throw Error(`Corrupted JSON in ${Z}: ${$.slice(0,100)}`)}}function m$($){return{id:$.id,connectionId:$.connection_id,schemaName:$.schema_name,tableName:$.table_name,name:$.name,config:g0($.config,`saved view "${$.name}"`),createdAt:$.created_at,updatedAt:$.updated_at}}function p$($){return{id:$.id,connectionId:$.connection_id,database:$.database??void 0,name:$.name,description:$.description,sql:$.sql,createdAt:$.created_at,updatedAt:$.updated_at}}function w0($){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(!v0)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return v0()}var r,l=null,v0;var l$=x(()=>{v$();I$();b0();r={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5",idleTransactionTimeoutMs:"300000","console.queryResponseTimeout":"300000"}});class d${cm;appDb;sessions=new Map;labelCounters=new Map;pendingRestore=new Map;txFirstSeen=new Map;idleCheckTimer=null;idleCheckRunning=!1;onTransactionRollback;constructor($,Z,B){this.cm=$,this.appDb=Z,this.onTransactionRollback=B,this.startIdleTransactionCheck()}dispose(){this.stopIdleTransactionCheck()}async createSession($,Z){let B=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(r.maxSessionsPerConnection),X=this.sessions.get($)?.size??0;if(B!==null&&X>=B)throw Error(`Maximum sessions per connection (${B}) reached. Destroy an existing session first.`);let W=crypto.randomUUID();await this.cm.getDriver($,Z).reserveSession(W);let H=(this.labelCounters.get($)??0)+1;this.labelCounters.set($,H);let V={sessionId:W,connectionId:$,database:Z,label:`Session ${H}`,inTransaction:!1,txAborted:!1,createdAt:Date.now()};if(!this.sessions.has($))this.sessions.set($,new Map);return this.sessions.get($).set(W,V),V}async destroySession($){let Z=this.findSession($);if(!Z)throw Error(`Session not found: ${$}`);let B=this.cm.getDriver(Z.connectionId,Z.database);try{await B.cancel($)}catch{}await B.releaseSession($),this.txFirstSeen.delete($);let G=this.sessions.get(Z.connectionId);if(G){if(G.delete($),G.size===0)this.sessions.delete(Z.connectionId)}}async destroySessionsForDatabase($,Z){let B=this.sessions.get($);if(!B)return;for(let[G,X]of B)if(X.database===Z){try{let W=this.cm.getDriver(X.connectionId,X.database);try{await W.cancel(G)}catch{}await W.releaseSession(G)}catch{}this.txFirstSeen.delete(G),B.delete(G)}if(B.size===0)this.sessions.delete($)}listSessions($){let Z=this.sessions.get($);if(!Z)return[];let B=[];for(let G of Z.values()){try{let X=this.cm.getDriver(G.connectionId,G.database);G.inTransaction=X.inTransaction(G.sessionId),G.txAborted=X.isTxAborted(G.sessionId)}catch{}B.push({...G})}return B}getSession($){let Z=this.findSession($);if(!Z)return;try{let B=this.cm.getDriver(Z.connectionId,Z.database);Z.inTransaction=B.inTransaction(Z.sessionId),Z.txAborted=B.isTxAborted(Z.sessionId)}catch{}return{...Z}}handleSessionDead($){let Z=this.findSession($);if(!Z)return;this.txFirstSeen.delete($);let B=this.sessions.get(Z.connectionId);if(B){if(B.delete($),B.size===0)this.sessions.delete(Z.connectionId)}}handleConnectionLost($){let Z=this.sessions.get($);if(Z){for(let G of Z.keys())this.txFirstSeen.delete(G);if(Z.size>0)this.pendingRestore.set($,Array.from(Z.values()).map((G)=>({database:G.database,label:G.label})))}let B=`${f0}:${$}:`;for(let G of this.txFirstSeen.keys())if(G.startsWith(B))this.txFirstSeen.delete(G);this.sessions.delete($)}async handleConnectionRestored($){let Z=this.pendingRestore.get($);if(this.pendingRestore.delete($),!Z||Z.length===0)return[];let B=[];for(let X of Z){let W=!1,Y,H;try{H=this.cm.getDriver($,X.database),Y=crypto.randomUUID(),await H.reserveSession(Y),W=!0;let V={sessionId:Y,connectionId:$,database:X.database,label:X.label,inTransaction:!1,txAborted:!1,createdAt:Date.now()};if(!this.sessions.has($))this.sessions.set($,new Map);this.sessions.get($).set(Y,V),B.push(V)}catch{if(W&&H&&Y)try{await H.releaseSession(Y)}catch{}}}let G=this.labelCounters.get($)??0;for(let X of B){let W=X.label.match(/^Session (\d+)$/);if(W)G=Math.max(G,Number(W[1]))}return this.labelCounters.set($,G),B}startIdleTransactionCheck(){this.idleCheckTimer=setInterval(()=>{this.checkIdleTransactions()},Y7)}stopIdleTransactionCheck(){if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null}async checkIdleTransactions(){if(this.idleCheckRunning)return;this.idleCheckRunning=!0;try{let $=this.appDb.getNumberSetting("idleTransactionTimeoutMs")??Number(r.idleTransactionTimeoutMs);if(!$||$<=0)return;let Z=Date.now();for(let[,B]of this.sessions)for(let[G,X]of B){let W=!1,Y=!1;try{let H=this.cm.getDriver(X.connectionId,X.database);W=H.inTransaction(G),Y=H.isIterating(G)}catch{this.txFirstSeen.delete(G);continue}if(Y)continue;if(W){if(!this.txFirstSeen.has(G))this.txFirstSeen.set(G,Z);else if(Z-this.txFirstSeen.get(G)>=$){try{await this.cm.getDriver(X.connectionId,X.database).rollback(G)}catch{}try{this.onTransactionRollback?.(X.connectionId,X.database,G)}catch{}this.txFirstSeen.delete(G)}}else this.txFirstSeen.delete(G)}for(let B of this.cm.listConnections()){if(B.state!=="connected")continue;let G=this.cm.getActiveDatabases(B.id);for(let X of G){let W=`${f0}:${B.id}:${X}`,Y=!1,H=!1;try{let V=this.cm.getDriver(B.id,X);Y=V.inTransaction(),H=V.isIterating()}catch{this.txFirstSeen.delete(W);continue}if(H)continue;if(Y){if(!this.txFirstSeen.has(W))this.txFirstSeen.set(W,Z);else if(Z-this.txFirstSeen.get(W)>=$){try{await this.cm.getDriver(B.id,X).rollback()}catch{}try{this.onTransactionRollback?.(B.id,X)}catch{}this.txFirstSeen.delete(W)}}else this.txFirstSeen.delete(W)}}}finally{this.idleCheckRunning=!1}}findSession($){for(let Z of this.sessions.values()){let B=Z.get($);if(B)return B}return}}var Y7=30000,f0="__default_tx__";var u0=x(()=>{l$()});function U7($){return V7.includes($)}function I0($){let Z=(G)=>$[`${H7}${G}`],B=Z("provider");return{provider:U7(B)?B:A$.provider,apiKey:Z("apiKey")??A$.apiKey,model:Z("model")??A$.model,endpoint:Z("endpoint")??A$.endpoint}}var A$,H7="ai.",V7;var m0=x(()=>{A$={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},V7=["anthropic","openai","custom"]});function p0($,Z=50){let B=[],G=0;for(let[X,W]of Object.entries($.tables))for(let Y of W){if(G>=Z)break;G++;let H=$.columns[`${X}.${Y.name}`]??[],V=$.foreignKeys[`${X}.${Y.name}`]??[],U=H.map((j)=>{let K=[j.name,j.dataType];if(j.isPrimaryKey)K.push("PK");if(!j.nullable)K.push("NOT NULL");if(j.isAutoIncrement)K.push("AUTO_INCREMENT");return K.join(" ")}),Q=X==="main"||X==="public"?Y.name:`${X}.${Y.name}`;B.push(`TABLE ${Q} (${U.join(", ")})`);for(let j of V){let K=j.referencedSchema==="main"||j.referencedSchema==="public"?j.referencedTable:`${j.referencedSchema}.${j.referencedTable}`;B.push(` FK ${j.columns.join(",")} -> ${K}(${j.referencedColumns.join(",")})`)}}return B.join(`
|
|
99
|
-
|
|
98
|
+
`)}},{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")}},{version:9,description:"Remove connection type CHECK constraint",disableForeignKeys:!0,up:($)=>{$.run(`
|
|
99
|
+
CREATE TABLE connections_new (
|
|
100
|
+
id TEXT PRIMARY KEY,
|
|
101
|
+
name TEXT NOT NULL,
|
|
102
|
+
type TEXT NOT NULL,
|
|
103
|
+
config TEXT NOT NULL,
|
|
104
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
105
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
106
|
+
read_only INTEGER NOT NULL DEFAULT 0,
|
|
107
|
+
color TEXT DEFAULT NULL,
|
|
108
|
+
group_name TEXT DEFAULT NULL
|
|
109
|
+
)
|
|
110
|
+
`),$.run(`
|
|
111
|
+
INSERT INTO connections_new (id, name, type, config, created_at, updated_at, read_only, color, group_name)
|
|
112
|
+
SELECT id, name, type, config, created_at, updated_at, read_only, color, group_name
|
|
113
|
+
FROM connections
|
|
114
|
+
`),$.run("DROP TABLE connections"),$.run("ALTER TABLE connections_new RENAME TO connections")}}]});import W7 from"bun:sqlite";class a{db;localKey=null;constructor($){this.db=new W7($,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),w0(this.db)}static getInstance($){if(!p){let Z=$??Y7();p=new a(Z)}return p}static create($){return new a($)}close(){this.db.close()}transaction($){return this.db.transaction($)()}static resetInstance(){if(p)p.db.close(),p=null}setLocalKey($){this.localKey=$,this.migratePasswords()}encryptConfigJson($){if(this.localKey&&v($)){let Z={...$,password:g($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let B={...$.sshTunnel};if(B.password)B.password=g(B.password,this.localKey);if(B.keyPassphrase)B.keyPassphrase=g(B.keyPassphrase,this.localKey);Z={...Z,sshTunnel:B}}return JSON.stringify(Z)}return JSON.stringify($)}decryptConfig($){if(this.localKey&&v($)&&f($.password)){let Z={...$,password:K$($.password,this.localKey)};if($.type==="postgresql"&&$.sshTunnel){let B={...$.sshTunnel};if(B.password&&f(B.password))B.password=K$(B.password,this.localKey);if(B.keyPassphrase&&f(B.keyPassphrase))B.keyPassphrase=K$(B.keyPassphrase,this.localKey);Z={...Z,sshTunnel:B}}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 B of $)try{let G=JSON.parse(B.config);if(v(G)){let X=!1,W={...G};if(!f(G.password))W={...W,password:g(G.password,this.localKey)},X=!0;if(G.type==="postgresql"&&G.sshTunnel){let Y={...G.sshTunnel};if(Y.password&&!f(Y.password))Y.password=g(Y.password,this.localKey),X=!0;if(Y.keyPassphrase&&!f(Y.keyPassphrase))Y.keyPassphrase=g(Y.keyPassphrase,this.localKey),X=!0;if(X)W={...W,sshTunnel:Y}}if(X)Z.run(JSON.stringify(W),B.id)}}catch{}})}toConnectionInfo($){let Z=f0($.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 B=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,B,B),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 B=this.getConnectionById($.id);if(!B)throw Error(`Connection not found: ${$.id}`);return B}setConnectionGroup($,Z){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(Z,$);let B=this.getConnectionById($);if(!B)throw Error(`Connection not found: ${$}`);return B}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 B=this.getConnectionById($);if(!B)throw Error(`Connection not found: ${$}`);return B}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($)??r[$]??null;if(Z===null)return null;let B=Number(Z);return Number.isFinite(B)?B:null}getBooleanSetting($){let Z=this.getSetting($)??r[$]??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 B of $)Z[B.key]=B.value;return Z}listSavedViews($,Z,B){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all($,Z,B).map(m$)}createSavedView($){let Z=crypto.randomUUID(),B=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),B,B),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 B=this.getSavedViewById($.id);if(!B)throw Error(`Saved view not found: ${$.id}`);return B}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(m$)}getSavedViewById($){let Z=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get($);return Z?m$(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(),v0(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,B=$.offset??0,G=[],X=[];if($.connectionId)G.push("connection_id = ?"),X.push($.connectionId);if($.search)G.push("sql LIKE ?"),X.push(`%${$.search}%`);if($.startDate)G.push("executed_at >= ?"),X.push($.startDate+" 00:00:00");if($.endDate){let V=new Date($.endDate+"T00:00:00Z");V.setUTCDate(V.getUTCDate()+1);let U=V.getUTCFullYear(),Q=String(V.getUTCMonth()+1).padStart(2,"0"),j=String(V.getUTCDate()).padStart(2,"0");G.push("executed_at < ?"),X.push(`${U}-${Q}-${j} 00:00:00`)}let Y=`SELECT * FROM query_history ${G.length>0?`WHERE ${G.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return X.push(Z,B),this.db.prepare(Y).all(...X).map(v0)}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(p$);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all($).map(p$)}createBookmark($){let Z=crypto.randomUUID(),B=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,B,B),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 B=this.getBookmarkById($.id);if(!B)throw Error(`Bookmark not found: ${$.id}`);return B}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?p$(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 f0($,Z){try{return JSON.parse($)}catch{throw Error(`Corrupted JSON in ${Z}: ${$.slice(0,100)}`)}}function m$($){return{id:$.id,connectionId:$.connection_id,schemaName:$.schema_name,tableName:$.table_name,name:$.name,config:f0($.config,`saved view "${$.name}"`),createdAt:$.created_at,updatedAt:$.updated_at}}function p$($){return{id:$.id,connectionId:$.connection_id,database:$.database??void 0,name:$.name,description:$.description,sql:$.sql,createdAt:$.created_at,updatedAt:$.updated_at}}function v0($){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 Y7(){if(!g0)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return g0()}var r,p=null,g0;var l$=x(()=>{v$();I$();b0();r={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5",idleTransactionTimeoutMs:"300000","console.queryResponseTimeout":"300000"}});class d${cm;appDb;sessions=new Map;labelCounters=new Map;pendingRestore=new Map;txFirstSeen=new Map;idleCheckTimer=null;idleCheckRunning=!1;onTransactionRollback;constructor($,Z,B){this.cm=$,this.appDb=Z,this.onTransactionRollback=B,this.startIdleTransactionCheck()}dispose(){this.stopIdleTransactionCheck()}async createSession($,Z){let B=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(r.maxSessionsPerConnection),X=this.sessions.get($)?.size??0;if(B!==null&&X>=B)throw Error(`Maximum sessions per connection (${B}) reached. Destroy an existing session first.`);let W=crypto.randomUUID();await this.cm.getDriver($,Z).reserveSession(W);let H=(this.labelCounters.get($)??0)+1;this.labelCounters.set($,H);let V={sessionId:W,connectionId:$,database:Z,label:`Session ${H}`,inTransaction:!1,txAborted:!1,createdAt:Date.now()};if(!this.sessions.has($))this.sessions.set($,new Map);return this.sessions.get($).set(W,V),V}async destroySession($){let Z=this.findSession($);if(!Z)throw Error(`Session not found: ${$}`);let B=this.cm.getDriver(Z.connectionId,Z.database);try{await B.cancel($)}catch{}await B.releaseSession($),this.txFirstSeen.delete($);let G=this.sessions.get(Z.connectionId);if(G){if(G.delete($),G.size===0)this.sessions.delete(Z.connectionId)}}async destroySessionsForDatabase($,Z){let B=this.sessions.get($);if(!B)return;for(let[G,X]of B)if(X.database===Z){try{let W=this.cm.getDriver(X.connectionId,X.database);try{await W.cancel(G)}catch{}await W.releaseSession(G)}catch{}this.txFirstSeen.delete(G),B.delete(G)}if(B.size===0)this.sessions.delete($)}listSessions($){let Z=this.sessions.get($);if(!Z)return[];let B=[];for(let G of Z.values()){try{let X=this.cm.getDriver(G.connectionId,G.database);G.inTransaction=X.inTransaction(G.sessionId),G.txAborted=X.isTxAborted(G.sessionId)}catch{}B.push({...G})}return B}getSession($){let Z=this.findSession($);if(!Z)return;try{let B=this.cm.getDriver(Z.connectionId,Z.database);Z.inTransaction=B.inTransaction(Z.sessionId),Z.txAborted=B.isTxAborted(Z.sessionId)}catch{}return{...Z}}handleSessionDead($){let Z=this.findSession($);if(!Z)return;this.txFirstSeen.delete($);let B=this.sessions.get(Z.connectionId);if(B){if(B.delete($),B.size===0)this.sessions.delete(Z.connectionId)}}handleConnectionLost($){let Z=this.sessions.get($);if(Z){for(let G of Z.keys())this.txFirstSeen.delete(G);if(Z.size>0)this.pendingRestore.set($,Array.from(Z.values()).map((G)=>({database:G.database,label:G.label})))}let B=`${u0}:${$}:`;for(let G of this.txFirstSeen.keys())if(G.startsWith(B))this.txFirstSeen.delete(G);this.sessions.delete($)}async handleConnectionRestored($){let Z=this.pendingRestore.get($);if(this.pendingRestore.delete($),!Z||Z.length===0)return[];let B=[];for(let X of Z){let W=!1,Y,H;try{H=this.cm.getDriver($,X.database),Y=crypto.randomUUID(),await H.reserveSession(Y),W=!0;let V={sessionId:Y,connectionId:$,database:X.database,label:X.label,inTransaction:!1,txAborted:!1,createdAt:Date.now()};if(!this.sessions.has($))this.sessions.set($,new Map);this.sessions.get($).set(Y,V),B.push(V)}catch{if(W&&H&&Y)try{await H.releaseSession(Y)}catch{}}}let G=this.labelCounters.get($)??0;for(let X of B){let W=X.label.match(/^Session (\d+)$/);if(W)G=Math.max(G,Number(W[1]))}return this.labelCounters.set($,G),B}startIdleTransactionCheck(){this.idleCheckTimer=setInterval(()=>{this.checkIdleTransactions()},H7)}stopIdleTransactionCheck(){if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null}async checkIdleTransactions(){if(this.idleCheckRunning)return;this.idleCheckRunning=!0;try{let $=this.appDb.getNumberSetting("idleTransactionTimeoutMs")??Number(r.idleTransactionTimeoutMs);if(!$||$<=0)return;let Z=Date.now();for(let[,B]of this.sessions)for(let[G,X]of B){let W=!1,Y=!1;try{let H=this.cm.getDriver(X.connectionId,X.database);W=H.inTransaction(G),Y=H.isIterating(G)}catch{this.txFirstSeen.delete(G);continue}if(Y)continue;if(W){if(!this.txFirstSeen.has(G))this.txFirstSeen.set(G,Z);else if(Z-this.txFirstSeen.get(G)>=$){try{await this.cm.getDriver(X.connectionId,X.database).rollback(G)}catch{}try{this.onTransactionRollback?.(X.connectionId,X.database,G)}catch{}this.txFirstSeen.delete(G)}}else this.txFirstSeen.delete(G)}for(let B of this.cm.listConnections()){if(B.state!=="connected")continue;let G=this.cm.getActiveDatabases(B.id);for(let X of G){let W=`${u0}:${B.id}:${X}`,Y=!1,H=!1;try{let V=this.cm.getDriver(B.id,X);Y=V.inTransaction(),H=V.isIterating()}catch{this.txFirstSeen.delete(W);continue}if(H)continue;if(Y){if(!this.txFirstSeen.has(W))this.txFirstSeen.set(W,Z);else if(Z-this.txFirstSeen.get(W)>=$){try{await this.cm.getDriver(B.id,X).rollback()}catch{}try{this.onTransactionRollback?.(B.id,X)}catch{}this.txFirstSeen.delete(W)}}else this.txFirstSeen.delete(W)}}}finally{this.idleCheckRunning=!1}}findSession($){for(let Z of this.sessions.values()){let B=Z.get($);if(B)return B}return}}var H7=30000,u0="__default_tx__";var I0=x(()=>{l$()});function Q7($){return U7.includes($)}function m0($){let Z=(G)=>$[`${V7}${G}`],B=Z("provider");return{provider:Q7(B)?B:A$.provider,apiKey:Z("apiKey")??A$.apiKey,model:Z("model")??A$.model,endpoint:Z("endpoint")??A$.endpoint}}var A$,V7="ai.",U7;var p0=x(()=>{A$={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},U7=["anthropic","openai","custom"]});function l0($,Z=50){let B=[],G=0;for(let[X,W]of Object.entries($.tables))for(let Y of W){if(G>=Z)break;G++;let H=$.columns[`${X}.${Y.name}`]??[],V=$.foreignKeys[`${X}.${Y.name}`]??[],U=H.map((j)=>{let K=[j.name,j.dataType];if(j.isPrimaryKey)K.push("PK");if(!j.nullable)K.push("NOT NULL");if(j.isAutoIncrement)K.push("AUTO_INCREMENT");return K.join(" ")}),Q=X==="main"||X==="public"?Y.name:`${X}.${Y.name}`;B.push(`TABLE ${Q} (${U.join(", ")})`);for(let j of V){let K=j.referencedSchema==="main"||j.referencedSchema==="public"?j.referencedTable:`${j.referencedSchema}.${j.referencedTable}`;B.push(` FK ${j.columns.join(",")} -> ${K}(${j.referencedColumns.join(",")})`)}}return B.join(`
|
|
115
|
+
`)}async function j7($,Z){let G=`${$.endpoint||"https://api.anthropic.com"}/v1/messages`,X=await fetch(G,{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.
|
|
100
116
|
|
|
101
117
|
Rules:
|
|
102
118
|
- Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
|
|
@@ -110,7 +126,7 @@ Rules:
|
|
|
110
126
|
Database schema:
|
|
111
127
|
${Z.schemaContext}
|
|
112
128
|
|
|
113
|
-
Request: ${Z.prompt}`}]})});if(!X.ok){let H=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}): ${H.slice(0,200)}`)}let Y=(await X.json()).content?.find((H)=>H.type==="text");return
|
|
129
|
+
Request: ${Z.prompt}`}]})});if(!X.ok){let H=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}): ${H.slice(0,200)}`)}let Y=(await X.json()).content?.find((H)=>H.type==="text");return c0(Y?.text??"")}async function d0($,Z){let G=`${$.endpoint||"https://api.openai.com"}/v1/chat/completions`,X=await fetch(G,{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.
|
|
114
130
|
|
|
115
131
|
Rules:
|
|
116
132
|
- Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
|
|
@@ -124,8 +140,8 @@ Rules:
|
|
|
124
140
|
Database schema:
|
|
125
141
|
${Z.schemaContext}
|
|
126
142
|
|
|
127
|
-
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
|
|
128
|
-
`)}var n0,o0,z7,K7;var a0=x(()=>{n0=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],o0=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],z7=["ON","AND","OR"],K7=["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 c${cm;constructor($){this.cm=$}async begin($,Z,B){let G=this.cm.getDriver($,Z);if(G.inTransaction(B))throw Error("Transaction already active on this connection");await G.beginTransaction(B)}async commit($,Z,B){let G=this.cm.getDriver($,Z);if(!G.inTransaction(B))throw Error("No active transaction to commit");await G.commit(B)}async rollback($,Z,B){let G=this.cm.getDriver($,Z);if(!G.inTransaction(B))throw Error("No active transaction to rollback");await G.rollback(B)}isActive($,Z,B){try{return this.cm.getDriver($,Z).inTransaction(B)}catch{return!1}}async rollbackIfActive($,Z,B){if(this.isActive($,Z,B))await this.rollback($,Z,B)}}class t${cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;constructor($,Z,B,G){this.cm=$;this.queryExecutor=Z;this.appDb=B;this.txManager=new c$($),this.encryption=G?.encryption,this.Utils=G?.Utils,this.emitMessage=G?.emitMessage,this.sessionManager=G?.sessionManager,this.demoDbSourcePath=G?.demoDbSourcePath,this.demoDbTargetPath=G?.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,B,G){if(B&&this.encryption){let X=await this.encryption.decrypt(B),W=JSON.parse(X),Y=this.appDb.getConnectionById($);if(!Y)this.appDb.createConnectionWithId($,{name:G??$,config:W});else this.appDb.updateConnection({id:$,name:G??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 B=await this.sessionManager.createSession($,Z);return this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)}),B}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){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase($,Z),this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)});await this.cm.deactivateDatabase($,Z)}async executeQuery($,Z,B,G,X,W,Y){return this.queryExecutor.executeQuery($,Z,B,void 0,G,X,W,Y)}async executeStatements($,Z,B,G){let X=this.cm.getDriver($,B),W=async(Y)=>{let H=X.inTransaction(Y);try{if(!H)await X.beginTransaction(Y);let V=[];for(let U of Z){let Q=performance.now();try{let j=await X.execute(U.sql,U.params,Y),K=Math.round(performance.now()-Q);V.push({...j,durationMs:K}),this.queryExecutor.sessionLog.add($,U.sql,j.error?"error":"success",K,j.affectedRows??j.rowCount,j.error,B,Y)}catch(j){let K=Math.round(performance.now()-Q);throw this.queryExecutor.sessionLog.add($,U.sql,"error",K,0,j instanceof Error?j.message:String(j),B,Y),j}}if(!H)await X.commit(Y);return V}catch(V){if(!H)try{await X.rollback(Y)}catch(U){console.debug("Rollback after error failed:",U instanceof Error?U.message:U)}throw V}};if(G)return W(G);return i(X,W)}submitQuery($,Z,B,G,X,W,Y){let H=performance.now();this.queryExecutor.executeQuery($,Z,B,0,G,X,W,Y).then((V)=>{this.emitMessage?.("query.completed",{queryId:G,results:V,durationMs:Math.round(performance.now()-H)})}).catch((V)=>{let U=V?.code;this.emitMessage?.("query.completed",{queryId:G,error:V instanceof Error?V.message:String(V),errorCode:U,durationMs:Math.round(performance.now()-H)})})}submitExplain($,Z,B,G,X,W,Y){let H=performance.now();this.queryExecutor.explainQuery($,Z,B,X,W,Y).then((V)=>{this.emitMessage?.("query.completed",{queryId:G,explainResult:V,durationMs:Math.round(performance.now()-H)})}).catch((V)=>{this.emitMessage?.("query.completed",{queryId:G,error:V instanceof Error?V.message:String(V),durationMs:Math.round(performance.now()-H)})})}async cancelQuery($){await this.queryExecutor.cancelQuery($)}async beginTransaction($,Z,B){await this.txManager.begin($,Z,B),this.queryExecutor.sessionLog.resetPendingCount($,Z,B)}async commitTransaction($,Z,B){await this.txManager.commit($,Z,B),this.queryExecutor.sessionLog.resetPendingCount($,Z,B)}async rollbackTransaction($,Z,B){await this.txManager.rollback($,Z,B),this.queryExecutor.sessionLog.resetPendingCount($,Z,B)}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 B=this.txManager.isActive($.connectionId,$.database,$.sessionId),G=B?this.queryExecutor.sessionLog.getPendingCount($.connectionId,$.database,$.sessionId):0;return{entries:Z,pendingStatementCount:G,inTransaction:B}}clearTransactionLog($,Z,B){this.queryExecutor.sessionLog.clear($,Z)}listHistory($){return this.appDb.listHistory($)}clearHistory($){this.appDb.clearHistory($)}listSavedViews($,Z,B){return this.appDb.listSavedViews($,Z,B)}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 t0(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 B=this.emitMessage?(X)=>this.emitMessage("export.progress",{rowCount:X}):void 0;return{...await M0(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,B),filePath:$.filePath}}async exportPreview($){let Z=this.cm.getDriver($.connectionId,$.database);return F0(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:B,params:G}=W$({schema:$.schema,table:$.table,format:"csv",columns:$.columns,filters:$.filters,sort:$.sort,autoJoins:$.autoJoins},Z),X=G.length+1,W=`${B} LIMIT ${Z.placeholder(X)}`,H=(await Z.execute(W,[...G,$.limit])).rows,V=H.length>0?Object.keys(H[0]):$.columns??[];return{rows:H,columns:V}}async importData($){let Z=this.cm.getDriver($.connectionId,$.database),B=this.resolveImportStream($.filePath,$.fileContent),G=this.emitMessage?(X)=>this.emitMessage("import.progress",{rowCount:X}):void 0;return H$(Z,B,{schema:$.schema,table:$.table,format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,mappings:$.mappings,batchSize:$.batchSize},void 0,G)}async importPreview($){let Z=this.resolveImportPreviewStream($.filePath,$.fileContent),B=await D0(Z,{format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,limit:$.limit});if($.filePath)try{let G=Bun.file($.filePath);B.fileSizeBytes=G.size}catch{}return B}resolveImportStream($,Z){if($)return Bun.file($).stream();if(Z!==void 0)return new ReadableStream({start(B){B.enqueue(new TextEncoder().encode(Z)),B.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(H){let{done:V,value:U}=await X.read();if(V){H.close();return}if(Y+=U.byteLength,Y>=65536){H.enqueue(U),H.close(),X.releaseLock();return}H.enqueue(U)},cancel(){X.releaseLock()}})}if(Z!==void 0)return new ReadableStream({start(B){B.enqueue(new TextEncoder().encode(Z)),B.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 B=$&&$.length>0?$.flatMap((W)=>W.extensions.map((Y)=>`*.${Y}`)).join(","):"*",X=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:B,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 B=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!B||B==="")return{path:null,cancelled:!0};return{path:$?`${B}/${$}`:B,cancelled:!1}}formatSql($){return r0($)}async generateSql($){let Z=this.cm.getDriver($.connectionId,$.database),B=await Z.loadSchema(),G=p0(B),X=I0(this.appDb.getAllSettings());return{sql:await c0(X,{prompt:$.prompt,schemaContext:G,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},B=this.appDb.createConnection({name:"Bookstore (Demo)",config:Z});return await this.cm.connect(B.id),B}getSessionManager(){return this.sessionManager}}var s0=x(()=>{m0();S$();y$();i0();a0()});function e0($){return{"connections.list":()=>{return $.listConnections()},"connections.create":({name:Z,config:B,readOnly:G,color:X,groupName:W})=>{return $.createConnection({name:Z,config:B,readOnly:G,color:X,groupName:W})},"connections.update":({id:Z,name:B,config:G,readOnly:X,color:W,groupName:Y})=>{return $.updateConnection({id:Z,name:B,config:G,readOnly:X,color:W,groupName:Y})},"connections.setReadOnly":({id:Z,readOnly:B})=>{return $.setConnectionReadOnly(Z,B)},"connections.setGroup":({id:Z,groupName:B})=>{return $.setConnectionGroup(Z,B)},"connections.listGroups":()=>{return $.listConnectionGroups()},"connections.renameGroup":({oldName:Z,newName:B})=>{$.renameConnectionGroup(Z,B)},"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:B,encryptedConfig:G,name:X})=>{await $.connect(Z,B,G,X)},"connections.disconnect":async({connectionId:Z})=>{await $.disconnect(Z)},"session.create":async({connectionId:Z,database:B})=>{return $.createSession(Z,B)},"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:B})=>{await $.activateDatabase(Z,B)},"databases.deactivate":async({connectionId:Z,database:B})=>{await $.deactivateDatabase(Z,B)},"schema.load":async({connectionId:Z,database:B,sessionId:G})=>{return $.getDriver(Z,B).loadSchema(G)},"query.execute":async({connectionId:Z,sql:B,queryId:G,params:X,database:W,statements:Y,sessionId:H,searchPath:V})=>{if(Y&&Y.length>0)return $.executeStatements(Z,Y,W,H);return $.executeQuery(Z,B,X,G,W,H,V)},"query.submit":({connectionId:Z,sql:B,queryId:G,params:X,database:W,sessionId:Y,searchPath:H})=>{return $.submitQuery(Z,B,X,G,W,Y,H),{queryId:G}},"query.submitExplain":({connectionId:Z,sql:B,analyze:G,queryId:X,database:W,sessionId:Y,searchPath:H})=>{return $.submitExplain(Z,B,G??!1,X,W,Y,H),{queryId:X}},"query.cancel":async({queryId:Z})=>{await $.cancelQuery(Z)},"query.format":({sql:Z})=>{return{sql:$.formatSql(Z)}},"tx.begin":async({connectionId:Z,database:B,sessionId:G})=>{await $.beginTransaction(Z,B,G)},"tx.commit":async({connectionId:Z,database:B,sessionId:G})=>{await $.commitTransaction(Z,B,G)},"tx.rollback":async({connectionId:Z,database:B,sessionId:G})=>{await $.rollbackTransaction(Z,B,G)},"transaction.getLog":(Z)=>{return $.getTransactionLog(Z)},"transaction.clearLog":({connectionId:Z,database:B,sessionId:G})=>{$.clearTransactionLog(Z,B,G)},"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:B,tableName:G,name:X,config:W})=>{if(!X||!X.trim())throw Error("View name is required");if(!Z)throw Error("connectionId is required");if(!G)throw Error("tableName is required");if($.listSavedViews(Z,B,G).some((H)=>H.name===X.trim()))throw Error(`A view named "${X.trim()}" already exists for this table`);return $.createSavedView({connectionId:Z,schemaName:B,tableName:G,name:X.trim(),config:W})},"views.update":({id:Z,name:B,config:G})=>{if(!Z)throw Error("View id is required");if(!B||!B.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===B.trim()))throw Error(`A view named "${B.trim()}" already exists for this table`);return $.updateSavedView({id:Z,name:B.trim(),config:G})},"views.delete":({id:Z})=>{$.deleteSavedView(Z)},"views.listByConnection":({connectionId:Z})=>{return $.listSavedViewsByConnection(Z)},"bookmarks.list":({connectionId:Z,search:B})=>{return $.listBookmarks(Z,B)},"bookmarks.create":({connectionId:Z,database:B,name:G,description:X,sql:W})=>{if(!G||!G.trim())throw Error("Bookmark name is required");return $.createBookmark({connectionId:Z,database:B,name:G.trim(),description:X,sql:W})},"bookmarks.update":({id:Z,name:B,description:G,sql:X})=>{if(!Z)throw Error("Bookmark id is required");if(!B||!B.trim())throw Error("Bookmark name is required");return $.updateBookmark({id:Z,name:B.trim(),description:G,sql:X})},"bookmarks.delete":({id:Z})=>{$.deleteBookmark(Z)},"settings.getAll":()=>{return $.getAllSettings()},"settings.set":({key:Z,value:B})=>{$.setSetting(Z,B)},"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 R7($){if(!$)throw Error("AppDatabase is required");return $}function $5($,Z,B,G,X){let W=R7(B),Y=Z??new n($,void 0,W),H=new d$($,W,(U,Q,j)=>{Y.sessionLog.resetPendingCount(U,Q,j)}),V=new t$($,Y,W,{encryption:X?.encryption,Utils:G,emitMessage:X?.emitMessage,sessionManager:H,demoDbSourcePath:X?.demoDbSourcePath,demoDbTargetPath:X?.demoDbTargetPath});return{handlers:e0(V),sessionManager:H,adapter:V}}var Z5=x(()=>{w$();u0();s0()});class i${inner;constructor($){this.inner=$}log($,Z,B,G){let X=$.replace(/\s+/g," ").trim(),W=Z&&Z.length>0;if(G)console.debug(`[SQL ERROR] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""} (${B}ms)`,G);else if(B!==void 0)console.debug(`[SQL] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""} (${B}ms)`);else console.debug(`[SQL] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""}`)}async execute($,Z,B){let G=performance.now();try{let X=await this.inner.execute($,Z,B);return this.log($,Z,Math.round(performance.now()-G)),X}catch(X){throw this.log($,Z,Math.round(performance.now()-G),X),X}}async*iterate($,Z,B,G,X){this.log($,Z),yield*this.inner.iterate($,Z,B,G,X)}async importBatch($,Z,B,G){let X=`INSERT INTO ${$} (${Z.join(", ")}) VALUES ... [${B.length} rows]`,W=performance.now();try{let Y=await this.inner.importBatch($,Z,B,G);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($)}ping(){return this.inner.ping()}async loadSchema($){console.debug("[SQL] loadSchema started"+($?` (session: ${$})`:""));let Z=performance.now();try{let B=await this.inner.loadSchema($),G=Object.values(B.tables).reduce((X,W)=>X+W.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${B.schemas.length} schemas, ${G} tables (${Math.round(performance.now()-Z)}ms)`),B}catch(B){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-Z)}ms)`,B),B}}beginTransaction($){return this.inner.beginTransaction($)}commit($){return this.inner.commit($)}rollback($){return this.inner.rollback($)}inTransaction($){return this.inner.inTransaction($)}isTxAborted($){return this.inner.isTxAborted($)}isIterating($){return this.inner.isIterating($)}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 n$($){let Z=$ instanceof Error?$.message:String($),B=$?.errno??$?.code;if(/ECONNREFUSED|connection refused/i.test(Z))return new D("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new D("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new D("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections|connection limit/i.test(Z))return new D("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new D("SSL_ERROR",Z,{cause:$});if(B?.startsWith("28")||/authentication failed|password authentication/i.test(Z))return new V$(Z,{cause:$});if(B==="3D000"||/database .* does not exist/i.test(Z))return new D("DATABASE_NOT_FOUND",Z,{cause:$});if(B==="23505"||/violates unique constraint|duplicate key/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(B==="23503"||/violates foreign key constraint/i.test(Z))return new C("CONSTRAINT_FK",Z,{cause:$});if(B==="23514"||/violates check constraint/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(B==="23502"||/violates not-null constraint/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(B==="42601"||/syntax error/i.test(Z))return new N("QUERY_SYNTAX",Z,{cause:$});if(B==="42P01"||/relation .* does not exist/i.test(Z))return new N("TABLE_NOT_FOUND",Z,{cause:$});if(B==="42703"||/column .* does not exist/i.test(Z))return new N("COLUMN_NOT_FOUND",Z,{cause:$});if(B==="42501"||/permission denied/i.test(Z))return new L("PERMISSION_DENIED",Z,{cause:$});if(B==="40001")return new N("SERIALIZATION_FAILURE",Z,{cause:$});if(B==="40P01")return new N("DEADLOCK_DETECTED",Z,{cause:$});if(B==="25P02")return new N("TRANSACTION_ABORTED",Z,{cause:$});if(B?.startsWith("42")||B?.startsWith("22"))return new N("QUERY_EXECUTION",Z,{cause:$});return new L("UNKNOWN",Z,{cause:$})}function o$($){let Z=$ instanceof Error?$.message:String($);if(/unable to open database|cannot open/i.test(Z))return new D("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 N("TABLE_NOT_FOUND",Z,{cause:$});if(/no such column/i.test(Z))return new N("COLUMN_NOT_FOUND",Z,{cause:$});if(/syntax error|near /i.test(Z))return new N("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 r$($){let Z=$ instanceof Error?$.message:String($),B=$?.errno;if(/ECONNREFUSED|connection refused/i.test(Z)||B===2003)return new D("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new D("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new D("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections/i.test(Z)||B===1040)return new D("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new D("SSL_ERROR",Z,{cause:$});if(B===1045||/access denied/i.test(Z))return new V$(Z,{cause:$});if(B===1049||/unknown database/i.test(Z))return new D("DATABASE_NOT_FOUND",Z,{cause:$});if(B===1062||/duplicate entry/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(B===1451||B===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(B===3819||/check constraint/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(B===1048||/cannot be null/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(B===1213||/deadlock found/i.test(Z))return new N("DEADLOCK_DETECTED",Z,{cause:$});if(B===1205||/lock wait timeout exceeded/i.test(Z))return new N("SERIALIZATION_FAILURE",Z,{cause:$});if(B===1064||/syntax error|you have an error in your sql syntax/i.test(Z))return new N("QUERY_SYNTAX",Z,{cause:$});if(B===1146||/table .* doesn't exist/i.test(Z))return new N("TABLE_NOT_FOUND",Z,{cause:$});if(B===1054||/unknown column/i.test(Z))return new N("COLUMN_NOT_FOUND",Z,{cause:$});if(B===1142||B===1143||/command denied|access denied/i.test(Z))return new L("PERMISSION_DENIED",Z,{cause:$});return new L("UNKNOWN",Z,{cause:$})}var O$=x(()=>{y()});function d($){let Z=$;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;return 0}var B5=x(()=>{X$()});function R$($,Z){let B=h$(Z).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(B)){if($.txActive=!0,"txAborted"in $)$.txAborted=!1}else if(/^(COMMIT|END)\b/.test(B)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}else if(/^ROLLBACK\b/.test(B)&&!/^ROLLBACK\s+TO\b/.test(B)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}}function I($){let Z=$?.code;if(typeof Z==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(Z))return!0;let B=$ instanceof Error?$.message:String($);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(B)}async function E($,Z,B){if(B?.rollback)try{await $.unsafe("ROLLBACK")}catch{}try{await Z($);try{$.release()}catch{}}catch{try{$.close({timeout:0})}catch{}}}var a$=x(()=>{B5()});var{SQL:_7}=globalThis.Bun;function L7($){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 s${db=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;defaultIsolationLevel="REPEATABLE READ";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 _7({url:Z});try{await this.db`SELECT 1`;let G=[...await this.db.unsafe("SELECT @@GLOBAL.transaction_isolation AS level")][0]?.level;if(G)this.defaultIsolationLevel=G.replace(/-/g," ")}catch(B){throw this.db=null,B instanceof L?B:r$(B)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,$]of this.sessions)await E($.conn,(Z)=>this.resetConnection(Z),{rollback:$.txActive});if(this.sessions.clear(),this.db)await this.db.close(),this.db=null}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,iterating:!1,activeQueries:new Set})}async releaseSession($){let Z=this.sessions.get($);if(!Z)return;await E(Z.conn,(B)=>this.resetConnection(B),{rollback:!0}),this.sessions.delete($)}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==q)}async execute($,Z,B,G){this.ensureConnected();let X=this.resolveSession(B),W=X?X.conn:this.db,Y=performance.now(),H=W.unsafe($,Z??[]),V=X?void 0:G??Symbol();if(X)X.activeQueries.add(H);else this.poolActiveQueries.set(V,H);try{let U=await H,Q=Math.round(performance.now()-Y),j=[...U];if(X)R$(X,$);return{columns:j.length>0?Object.keys(j[0]).map((A)=>({name:A,dataType:"unknown"})):[],rows:j,rowCount:j.length,affectedRows:d(U),durationMs:Q}}catch(U){throw U instanceof L?U:r$(U)}finally{if(X)X.activeQueries.delete(H);else this.poolActiveQueries.delete(V)}}async cancel($,Z){if($){let B=this.sessions.get($);if(B){for(let G of B.activeQueries)G.cancel();B.activeQueries.clear()}}else if(Z){let B=this.poolActiveQueries.get(Z);if(B)B.cancel(),this.poolActiveQueries.delete(Z)}else{for(let B of this.poolActiveQueries.values())B.cancel();this.poolActiveQueries.clear()}}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),B=Z?Z.conn:this.db,G=await this.getSchemas(B),X=G.map((J)=>J.name),W={};for(let J of G)W[J.name]=await this.getTables(B,J.name);let[Y,H,V,U]=await Promise.all([B.unsafe(`SELECT
|
|
143
|
+
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 c0(W.choices?.[0]?.message?.content??"")}async function J7($,Z){if(!$.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return d0($,Z)}function c0($){let Z=$.trim(),B=Z.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(B)Z=B[1].trim();return Z}async function t0($,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 j7($,Z);case"openai":return d0($,Z);case"custom":return J7($,Z);default:throw Error(`Unknown AI provider: ${$.provider}`)}}function z7($){return $.dataType!=="binary"}async function i0($,Z,B,G){let X=performance.now(),W=await $.loadSchema(),Y=[];for(let[K,A]of Object.entries(W.tables)){if(Z.scope==="schema"&&Z.schemaName&&K!==Z.schemaName)continue;for(let J of A){if(J.type!=="table")continue;if(Z.scope==="tables"&&Z.tableNames){if(!Z.tableNames.includes(J.name))continue}Y.push(J)}}let H=[],V=0,U=0,Q=$.getDriverType()==="postgresql",j=Q?"ILIKE":"LIKE";for(let K of Y){if(G())return{matches:H,searchedTables:U,totalMatches:V,cancelled:!0,elapsedMs:Math.round(performance.now()-X)};B(K.name,U,Y.length);let A=`${K.schema}.${K.name}`,R=(W.columns[A]??[]).filter(z7);if(R.length===0){U++;continue}let z=[],O=[],L=0;for(let k of R){L++;let h=$.quoteIdentifier(k.name);z.push(`CAST(${h} AS TEXT) ${j} ${$.placeholder(L)}`),O.push(`%${Z.searchTerm}%`)}let P=$.qualifyTable(K.schema,K.name);L++;let T=$.placeholder(L),F=`SELECT * FROM ${P} WHERE ${z.join(" OR ")} LIMIT ${T}`;O.push(Z.resultsPerTable);try{let k=await $.execute(F,O);for(let h of k.rows){let $$=h;for(let w of R){let Q0=$$[w.name];if(Q0==null)continue;let j0=String(Q0);if(Q?j0.toLowerCase().includes(Z.searchTerm.toLowerCase()):j0.toLowerCase().includes(Z.searchTerm.toLowerCase())){H.push({schema:K.schema,table:K.name,column:w.name,row:$$}),V++;break}}}}catch(k){console.debug(`Search: skipped ${K.schema}.${K.name}:`,k instanceof Error?k.message:k)}U++}return{matches:H,searchedTables:U,totalMatches:V,cancelled:!1,elapsedMs:Math.round(performance.now()-X)}}var n0=x(()=>{I()});function R7($){let Z=[],B=0;while(B<$.length){let G=$[B];if(G==="'"||G==='"'){let X=G,W=G;B++;while(B<$.length)if($[B]===X)if(W+=$[B],B++,B<$.length&&$[B]===X)W+=$[B],B++;else break;else W+=$[B],B++;Z.push({type:"string",value:W,upper:W});continue}if(/\s/.test(G)){let X="";while(B<$.length&&/\s/.test($[B]))X+=$[B],B++;Z.push({type:"whitespace",value:X,upper:X});continue}if(/[a-zA-Z_]/.test(G)){let X="";while(B<$.length&&/[a-zA-Z0-9_]/.test($[B]))X+=$[B],B++;Z.push({type:"word",value:X,upper:X.toUpperCase()});continue}Z.push({type:"symbol",value:G,upper:G}),B++}return Z}function O7($,Z,B){let G=B.split(" "),X=Z,W=0;while(W<G.length&&X<$.length){if($[X].type==="whitespace"){X++;continue}if($[X].upper!==G[W])return 0;W++,X++}return W===G.length?X-Z:0}function a0($){let Z=$.trim();if(!Z)return"";let B=R7(Z);for(let V of B)if(V.type==="word"){if(A7.includes(V.upper))V.value=V.upper}let G=[],X="",W=0,Y=0;while(W<B.length){let V=B[W];if(V.type==="symbol"&&V.value==="("){Y++,X+=V.value,W++;continue}if(V.type==="symbol"&&V.value===")"){if(Y>0)Y--;X+=V.value,W++;continue}if(Y>0){X+=V.value,W++;continue}if(V.type==="word"){let U=!1,Q=[...o0,...r0].sort((j,K)=>K.split(" ").length-j.split(" ").length);for(let j of Q){let K=O7(B,W,j);if(K>0){let A=[];for(let O=W;O<W+K;O++)A.push(B[O].value);let J=A.filter((O)=>O.trim()).join(" "),R=r0.includes(j);if(o0.includes(j)||R){let O=X.trimEnd();if(O)G.push(O);X=J}else X+=J;W+=K,U=!0;break}}if(U)continue;if(K7.includes(V.upper)){let j=X.trimEnd();if(j)G.push(j);X=" "+V.value,W++;continue}}if(V.type==="whitespace"){if(X.trimEnd())X+=" "}else X+=V.value;W++}let H=X.trimEnd();if(H)G.push(H);return G.join(`
|
|
144
|
+
`)}var o0,r0,K7,A7;var s0=x(()=>{o0=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],r0=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],K7=["ON","AND","OR"],A7=["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 c${cm;constructor($){this.cm=$}async begin($,Z,B){let G=this.cm.getDriver($,Z);if(G.inTransaction(B))throw Error("Transaction already active on this connection");await G.beginTransaction(B)}async commit($,Z,B){let G=this.cm.getDriver($,Z);if(!G.inTransaction(B))throw Error("No active transaction to commit");await G.commit(B)}async rollback($,Z,B){let G=this.cm.getDriver($,Z);if(!G.inTransaction(B))throw Error("No active transaction to rollback");await G.rollback(B)}isActive($,Z,B){try{return this.cm.getDriver($,Z).inTransaction(B)}catch{return!1}}async rollbackIfActive($,Z,B){if(this.isActive($,Z,B))await this.rollback($,Z,B)}}class t${cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;constructor($,Z,B,G){this.cm=$;this.queryExecutor=Z;this.appDb=B;this.txManager=new c$($),this.encryption=G?.encryption,this.Utils=G?.Utils,this.emitMessage=G?.emitMessage,this.sessionManager=G?.sessionManager,this.demoDbSourcePath=G?.demoDbSourcePath,this.demoDbTargetPath=G?.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,B,G){if(B&&this.encryption){let X=await this.encryption.decrypt(B),W=JSON.parse(X),Y=this.appDb.getConnectionById($);if(!Y)this.appDb.createConnectionWithId($,{name:G??$,config:W});else this.appDb.updateConnection({id:$,name:G??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 B=await this.sessionManager.createSession($,Z);return this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)}),B}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){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase($,Z),this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)});await this.cm.deactivateDatabase($,Z)}async executeQuery($,Z,B,G,X,W,Y){return this.queryExecutor.executeQuery($,Z,B,void 0,G,X,W,Y)}async executeStatements($,Z,B,G){let X=this.cm.getDriver($,B),W=async(Y)=>{let H=X.inTransaction(Y);try{if(!H)await X.beginTransaction(Y);let V=[];for(let U of Z){let Q=performance.now();try{let j=await X.execute(U.sql,U.params,Y),K=Math.round(performance.now()-Q);V.push({...j,durationMs:K}),this.queryExecutor.sessionLog.add($,U.sql,j.error?"error":"success",K,j.affectedRows??j.rowCount,j.error,B,Y)}catch(j){let K=Math.round(performance.now()-Q);throw this.queryExecutor.sessionLog.add($,U.sql,"error",K,0,j instanceof Error?j.message:String(j),B,Y),j}}if(!H)await X.commit(Y);return V}catch(V){if(!H)try{await X.rollback(Y)}catch(U){console.debug("Rollback after error failed:",U instanceof Error?U.message:U)}throw V}};if(G)return W(G);return i(X,W)}submitQuery($,Z,B,G,X,W,Y){let H=performance.now();this.queryExecutor.executeQuery($,Z,B,0,G,X,W,Y).then((V)=>{this.emitMessage?.("query.completed",{queryId:G,results:V,durationMs:Math.round(performance.now()-H)})}).catch((V)=>{let U=V?.code;this.emitMessage?.("query.completed",{queryId:G,error:V instanceof Error?V.message:String(V),errorCode:U,durationMs:Math.round(performance.now()-H)})})}submitExplain($,Z,B,G,X,W,Y){let H=performance.now();this.queryExecutor.explainQuery($,Z,B,X,W,Y).then((V)=>{this.emitMessage?.("query.completed",{queryId:G,explainResult:V,durationMs:Math.round(performance.now()-H)})}).catch((V)=>{this.emitMessage?.("query.completed",{queryId:G,error:V instanceof Error?V.message:String(V),durationMs:Math.round(performance.now()-H)})})}async cancelQuery($){await this.queryExecutor.cancelQuery($)}async beginTransaction($,Z,B){await this.txManager.begin($,Z,B),this.queryExecutor.sessionLog.resetPendingCount($,Z,B)}async commitTransaction($,Z,B){await this.txManager.commit($,Z,B),this.queryExecutor.sessionLog.resetPendingCount($,Z,B)}async rollbackTransaction($,Z,B){await this.txManager.rollback($,Z,B),this.queryExecutor.sessionLog.resetPendingCount($,Z,B)}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 B=this.txManager.isActive($.connectionId,$.database,$.sessionId),G=B?this.queryExecutor.sessionLog.getPendingCount($.connectionId,$.database,$.sessionId):0;return{entries:Z,pendingStatementCount:G,inTransaction:B}}clearTransactionLog($,Z,B){this.queryExecutor.sessionLog.clear($,Z)}listHistory($){return this.appDb.listHistory($)}clearHistory($){this.appDb.clearHistory($)}listSavedViews($,Z,B){return this.appDb.listSavedViews($,Z,B)}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 i0(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 B=this.emitMessage?(X)=>this.emitMessage("export.progress",{rowCount:X}):void 0;return{...await M0(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,B),filePath:$.filePath}}async exportPreview($){let Z=this.cm.getDriver($.connectionId,$.database);return N0(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:B,params:G}=W$({schema:$.schema,table:$.table,format:"csv",columns:$.columns,filters:$.filters,sort:$.sort,autoJoins:$.autoJoins},Z),X=G.length+1,W=`${B} LIMIT ${Z.placeholder(X)}`,H=(await Z.execute(W,[...G,$.limit])).rows,V=H.length>0?Object.keys(H[0]):$.columns??[];return{rows:H,columns:V}}async importData($){let Z=this.cm.getDriver($.connectionId,$.database),B=this.resolveImportStream($.filePath,$.fileContent),G=this.emitMessage?(X)=>this.emitMessage("import.progress",{rowCount:X}):void 0;return H$(Z,B,{schema:$.schema,table:$.table,format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,mappings:$.mappings,batchSize:$.batchSize},void 0,G)}async importPreview($){let Z=this.resolveImportPreviewStream($.filePath,$.fileContent),B=await C0(Z,{format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,limit:$.limit});if($.filePath)try{let G=Bun.file($.filePath);B.fileSizeBytes=G.size}catch{}return B}resolveImportStream($,Z){if($)return Bun.file($).stream();if(Z!==void 0)return new ReadableStream({start(B){B.enqueue(new TextEncoder().encode(Z)),B.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(H){let{done:V,value:U}=await X.read();if(V){H.close();return}if(Y+=U.byteLength,Y>=65536){H.enqueue(U),H.close(),X.releaseLock();return}H.enqueue(U)},cancel(){X.releaseLock()}})}if(Z!==void 0)return new ReadableStream({start(B){B.enqueue(new TextEncoder().encode(Z)),B.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 B=$&&$.length>0?$.flatMap((W)=>W.extensions.map((Y)=>`*.${Y}`)).join(","):"*",X=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:B,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 B=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!B||B==="")return{path:null,cancelled:!0};return{path:$?`${B}/${$}`:B,cancelled:!1}}formatSql($){return a0($)}async generateSql($){let Z=this.cm.getDriver($.connectionId,$.database),B=await Z.loadSchema(),G=l0(B),X=m0(this.appDb.getAllSettings());return{sql:await t0(X,{prompt:$.prompt,schemaContext:G,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},B=this.appDb.createConnection({name:"Bookstore (Demo)",config:Z});return await this.cm.connect(B.id),B}getSessionManager(){return this.sessionManager}}var e0=x(()=>{p0();S$();y$();n0();s0()});function $5($){return{"connections.list":()=>{return $.listConnections()},"connections.create":({name:Z,config:B,readOnly:G,color:X,groupName:W})=>{return $.createConnection({name:Z,config:B,readOnly:G,color:X,groupName:W})},"connections.update":({id:Z,name:B,config:G,readOnly:X,color:W,groupName:Y})=>{return $.updateConnection({id:Z,name:B,config:G,readOnly:X,color:W,groupName:Y})},"connections.setReadOnly":({id:Z,readOnly:B})=>{return $.setConnectionReadOnly(Z,B)},"connections.setGroup":({id:Z,groupName:B})=>{return $.setConnectionGroup(Z,B)},"connections.listGroups":()=>{return $.listConnectionGroups()},"connections.renameGroup":({oldName:Z,newName:B})=>{$.renameConnectionGroup(Z,B)},"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:B,encryptedConfig:G,name:X})=>{await $.connect(Z,B,G,X)},"connections.disconnect":async({connectionId:Z})=>{await $.disconnect(Z)},"session.create":async({connectionId:Z,database:B})=>{return $.createSession(Z,B)},"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:B})=>{await $.activateDatabase(Z,B)},"databases.deactivate":async({connectionId:Z,database:B})=>{await $.deactivateDatabase(Z,B)},"schema.load":async({connectionId:Z,database:B,sessionId:G})=>{return $.getDriver(Z,B).loadSchema(G)},"query.execute":async({connectionId:Z,sql:B,queryId:G,params:X,database:W,statements:Y,sessionId:H,searchPath:V})=>{if(Y&&Y.length>0)return $.executeStatements(Z,Y,W,H);return $.executeQuery(Z,B,X,G,W,H,V)},"query.submit":({connectionId:Z,sql:B,queryId:G,params:X,database:W,sessionId:Y,searchPath:H})=>{return $.submitQuery(Z,B,X,G,W,Y,H),{queryId:G}},"query.submitExplain":({connectionId:Z,sql:B,analyze:G,queryId:X,database:W,sessionId:Y,searchPath:H})=>{return $.submitExplain(Z,B,G??!1,X,W,Y,H),{queryId:X}},"query.cancel":async({queryId:Z})=>{await $.cancelQuery(Z)},"query.format":({sql:Z})=>{return{sql:$.formatSql(Z)}},"tx.begin":async({connectionId:Z,database:B,sessionId:G})=>{await $.beginTransaction(Z,B,G)},"tx.commit":async({connectionId:Z,database:B,sessionId:G})=>{await $.commitTransaction(Z,B,G)},"tx.rollback":async({connectionId:Z,database:B,sessionId:G})=>{await $.rollbackTransaction(Z,B,G)},"transaction.getLog":(Z)=>{return $.getTransactionLog(Z)},"transaction.clearLog":({connectionId:Z,database:B,sessionId:G})=>{$.clearTransactionLog(Z,B,G)},"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:B,tableName:G,name:X,config:W})=>{if(!X||!X.trim())throw Error("View name is required");if(!Z)throw Error("connectionId is required");if(!G)throw Error("tableName is required");if($.listSavedViews(Z,B,G).some((H)=>H.name===X.trim()))throw Error(`A view named "${X.trim()}" already exists for this table`);return $.createSavedView({connectionId:Z,schemaName:B,tableName:G,name:X.trim(),config:W})},"views.update":({id:Z,name:B,config:G})=>{if(!Z)throw Error("View id is required");if(!B||!B.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===B.trim()))throw Error(`A view named "${B.trim()}" already exists for this table`);return $.updateSavedView({id:Z,name:B.trim(),config:G})},"views.delete":({id:Z})=>{$.deleteSavedView(Z)},"views.listByConnection":({connectionId:Z})=>{return $.listSavedViewsByConnection(Z)},"bookmarks.list":({connectionId:Z,search:B})=>{return $.listBookmarks(Z,B)},"bookmarks.create":({connectionId:Z,database:B,name:G,description:X,sql:W})=>{if(!G||!G.trim())throw Error("Bookmark name is required");return $.createBookmark({connectionId:Z,database:B,name:G.trim(),description:X,sql:W})},"bookmarks.update":({id:Z,name:B,description:G,sql:X})=>{if(!Z)throw Error("Bookmark id is required");if(!B||!B.trim())throw Error("Bookmark name is required");return $.updateBookmark({id:Z,name:B.trim(),description:G,sql:X})},"bookmarks.delete":({id:Z})=>{$.deleteBookmark(Z)},"settings.getAll":()=>{return $.getAllSettings()},"settings.set":({key:Z,value:B})=>{$.setSetting(Z,B)},"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 L7($){if(!$)throw Error("AppDatabase is required");return $}function Z5($,Z,B,G,X){let W=L7(B),Y=Z??new n($,void 0,W),H=new d$($,W,(U,Q,j)=>{Y.sessionLog.resetPendingCount(U,Q,j)}),V=new t$($,Y,W,{encryption:X?.encryption,Utils:G,emitMessage:X?.emitMessage,sessionManager:H,demoDbSourcePath:X?.demoDbSourcePath,demoDbTargetPath:X?.demoDbTargetPath});return{handlers:$5(V),sessionManager:H,adapter:V}}var B5=x(()=>{b$();I0();e0()});class i${inner;constructor($){this.inner=$}log($,Z,B,G){let X=$.replace(/\s+/g," ").trim(),W=Z&&Z.length>0;if(G)console.debug(`[SQL ERROR] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""} (${B}ms)`,G);else if(B!==void 0)console.debug(`[SQL] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""} (${B}ms)`);else console.debug(`[SQL] ${X}${W?` -- params: ${JSON.stringify(Z)}`:""}`)}async execute($,Z,B){let G=performance.now();try{let X=await this.inner.execute($,Z,B);return this.log($,Z,Math.round(performance.now()-G)),X}catch(X){throw this.log($,Z,Math.round(performance.now()-G),X),X}}async*iterate($,Z,B,G,X){this.log($,Z),yield*this.inner.iterate($,Z,B,G,X)}async importBatch($,Z,B,G){let X=`INSERT INTO ${$} (${Z.join(", ")}) VALUES ... [${B.length} rows]`,W=performance.now();try{let Y=await this.inner.importBatch($,Z,B,G);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($)}ping(){return this.inner.ping()}async loadSchema($){console.debug("[SQL] loadSchema started"+($?` (session: ${$})`:""));let Z=performance.now();try{let B=await this.inner.loadSchema($),G=Object.values(B.tables).reduce((X,W)=>X+W.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${B.schemas.length} schemas, ${G} tables (${Math.round(performance.now()-Z)}ms)`),B}catch(B){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-Z)}ms)`,B),B}}beginTransaction($){return this.inner.beginTransaction($)}commit($){return this.inner.commit($)}rollback($){return this.inner.rollback($)}inTransaction($){return this.inner.inTransaction($)}isTxAborted($){return this.inner.isTxAborted($)}isIterating($){return this.inner.isIterating($)}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($)}}var{SQL:_7}=globalThis.Bun;class s{url;resetFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;constructor($,Z){this.url=$;this.resetFn=Z}async connect(){this.systemConn=this.createSql(),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1")}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.systemConn}createConnection(){let $=this.createSql();return this.connections.add($),$}acquireConnection(){if(this.idleConn){let $=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),$}return this.createConnection()}async releaseConnection($){if(!this.idleConn){if(this.resetFn)try{await this.resetFn($)}catch{await this.destroyConnection($);return}this.idleConn=$,this.scheduleIdleTimeout()}else await this.destroyConnection($)}async destroyConnection($){if(this.idleConn===$)this.idleConn=null,this.clearIdleTimer();this.connections.delete($);try{await $.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn){this.connections.delete(this.systemConn);try{await this.systemConn.close()}catch{}}this.systemConn=this.createSql(),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1")}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let $=[...this.connections];this.connections.clear(),this.systemConn=null,await Promise.allSettled($.map((Z)=>Z.close()))}createSql(){return new _7({url:this.url,max:1})}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},x7)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var x7=30000;var n$=()=>{};function o$($){let Z=$ instanceof Error?$.message:String($),B=$?.errno??$?.code;if(/ECONNREFUSED|connection refused/i.test(Z))return new D("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new D("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new D("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections|connection limit/i.test(Z))return new D("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new D("SSL_ERROR",Z,{cause:$});if(B?.startsWith("28")||/authentication failed|password authentication/i.test(Z))return new V$(Z,{cause:$});if(B==="3D000"||/database .* does not exist/i.test(Z))return new D("DATABASE_NOT_FOUND",Z,{cause:$});if(B==="23505"||/violates unique constraint|duplicate key/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(B==="23503"||/violates foreign key constraint/i.test(Z))return new C("CONSTRAINT_FK",Z,{cause:$});if(B==="23514"||/violates check constraint/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(B==="23502"||/violates not-null constraint/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(B==="42601"||/syntax error/i.test(Z))return new N("QUERY_SYNTAX",Z,{cause:$});if(B==="42P01"||/relation .* does not exist/i.test(Z))return new N("TABLE_NOT_FOUND",Z,{cause:$});if(B==="42703"||/column .* does not exist/i.test(Z))return new N("COLUMN_NOT_FOUND",Z,{cause:$});if(B==="42501"||/permission denied/i.test(Z))return new _("PERMISSION_DENIED",Z,{cause:$});if(B==="40001")return new N("SERIALIZATION_FAILURE",Z,{cause:$});if(B==="40P01")return new N("DEADLOCK_DETECTED",Z,{cause:$});if(B==="25P02")return new N("TRANSACTION_ABORTED",Z,{cause:$});if(B?.startsWith("42")||B?.startsWith("22"))return new N("QUERY_EXECUTION",Z,{cause:$});return new _("UNKNOWN",Z,{cause:$})}function r$($){let Z=$ instanceof Error?$.message:String($);if(/unable to open database|cannot open/i.test(Z))return new D("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 N("TABLE_NOT_FOUND",Z,{cause:$});if(/no such column/i.test(Z))return new N("COLUMN_NOT_FOUND",Z,{cause:$});if(/syntax error|near /i.test(Z))return new N("QUERY_SYNTAX",Z,{cause:$});if(/authorization denied|not authorized/i.test(Z))return new _("PERMISSION_DENIED",Z,{cause:$});return new _("UNKNOWN",Z,{cause:$})}function a$($){let Z=$ instanceof Error?$.message:String($),B=$?.errno;if(/ECONNREFUSED|connection refused/i.test(Z)||B===2003)return new D("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new D("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new D("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections/i.test(Z)||B===1040)return new D("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new D("SSL_ERROR",Z,{cause:$});if(B===1045||/access denied/i.test(Z))return new V$(Z,{cause:$});if(B===1049||/unknown database/i.test(Z))return new D("DATABASE_NOT_FOUND",Z,{cause:$});if(B===1062||/duplicate entry/i.test(Z))return new C("CONSTRAINT_UNIQUE",Z,{cause:$});if(B===1451||B===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(B===3819||/check constraint/i.test(Z))return new C("CONSTRAINT_CHECK",Z,{cause:$});if(B===1048||/cannot be null/i.test(Z))return new C("CONSTRAINT_NOT_NULL",Z,{cause:$});if(B===1213||/deadlock found/i.test(Z))return new N("DEADLOCK_DETECTED",Z,{cause:$});if(B===1205||/lock wait timeout exceeded/i.test(Z))return new N("SERIALIZATION_FAILURE",Z,{cause:$});if(B===1064||/syntax error|you have an error in your sql syntax/i.test(Z))return new N("QUERY_SYNTAX",Z,{cause:$});if(B===1146||/table .* doesn't exist/i.test(Z))return new N("TABLE_NOT_FOUND",Z,{cause:$});if(B===1054||/unknown column/i.test(Z))return new N("COLUMN_NOT_FOUND",Z,{cause:$});if(B===1142||B===1143||/command denied|access denied/i.test(Z))return new _("PERMISSION_DENIED",Z,{cause:$});return new _("UNKNOWN",Z,{cause:$})}var R$=x(()=>{q()});function l($){let Z=$;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;return 0}var G5=x(()=>{X$()});function O$($,Z){let B=h$(Z).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(B)){if($.txActive=!0,"txAborted"in $)$.txAborted=!1}else if(/^(COMMIT|END)\b/.test(B)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}else if(/^ROLLBACK\b/.test(B)&&!/^ROLLBACK\s+TO\b/.test(B)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}}function u($){let Z=$?.code;if(typeof Z==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(Z))return!0;let B=$ instanceof Error?$.message:String($);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(B)}async function d($,Z){if(Z?.rollback)try{await $.unsafe("ROLLBACK")}catch{}try{await $.close()}catch{}}var s$=x(()=>{G5()});function F7($){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 e${pool=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;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.pool=new s(Z,(B)=>B.unsafe("RESET CONNECTION"));try{await this.pool.connect()}catch(B){throw this.pool=null,B instanceof _?B:a$(B)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,$]of this.sessions)await d($.conn,{rollback:$.txActive});if(this.sessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=this.pool.createConnection();this.sessions.set($,{conn:Z,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession($){let Z=this.sessions.get($);if(!Z)return;this.sessions.delete($),await d(Z.conn,{rollback:!0})}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==S)}async execute($,Z,B,G){this.ensureConnected();let X=this.resolveSession(B),W=X?X.conn:this.pool.getSystemConnection(),Y=performance.now(),H=W.unsafe($,Z??[]),V=X?void 0:G??Symbol();if(X)X.activeQueries.add(H);else this.poolActiveQueries.set(V,H);try{let U=await H,Q=Math.round(performance.now()-Y),j=[...U];if(X)O$(X,$);return{columns:j.length>0?Object.keys(j[0]).map((A)=>({name:A,dataType:"unknown"})):[],rows:j,rowCount:j.length,affectedRows:l(U),durationMs:Q}}catch(U){throw U instanceof _?U:a$(U)}finally{if(X)X.activeQueries.delete(H);else this.poolActiveQueries.delete(V)}}async cancel($,Z){if($){let B=this.sessions.get($);if(B){for(let G of B.activeQueries)G.cancel();B.activeQueries.clear()}}else if(Z){let B=this.poolActiveQueries.get(Z);if(B)B.cancel(),this.poolActiveQueries.delete(Z)}else{for(let B of this.poolActiveQueries.values())B.cancel();this.poolActiveQueries.clear()}}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),B=Z?Z.conn:this.pool.getSystemConnection(),G=await this.getSchemas(B),X=G.map((J)=>J.name),W={};for(let J of G)W[J.name]=await this.getTables(B,J.name);let[Y,H,V,U]=await Promise.all([B.unsafe(`SELECT
|
|
129
145
|
c.TABLE_SCHEMA AS table_schema,
|
|
130
146
|
c.TABLE_NAME AS table_name,
|
|
131
147
|
c.COLUMN_NAME AS column_name,
|
|
@@ -179,10 +195,10 @@ Request: ${Z.prompt}`}]})});if(!X.ok){let Y=await X.text().catch(()=>"");if(X.st
|
|
|
179
195
|
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
|
|
180
196
|
GROUP BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME,
|
|
181
197
|
kcu.CONSTRAINT_NAME, kcu.TABLE_SCHEMA, kcu.TABLE_NAME
|
|
182
|
-
ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,X)]),Q={};for(let J of Y){let
|
|
198
|
+
ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,X)]),Q={};for(let J of Y){let R=`${J.table_schema}.${J.table_name}`;if(!Q[R])Q[R]=[];Q[R].push({name:J.column_name,dataType:F7(J.data_type),nullable:J.is_nullable==="YES",defaultValue:J.column_default,isPrimaryKey:J.column_key==="PRI",isAutoIncrement:(J.extra??"").includes("auto_increment"),maxLength:J.character_maximum_length??void 0})}let j={};for(let J of H){let R=`${J.table_schema}.${J.table_name}`;if(!j[R])j[R]=[];j[R].push({name:J.index_name,columns:typeof J.columns==="string"?J.columns.split(","):[J.columns],isUnique:J.non_unique===0||J.non_unique==="0",isPrimary:J.index_name==="PRIMARY"})}let K={};for(let J of V){let R=`${J.table_schema}.${J.table_name}`;if(!K[R])K[R]=[];K[R].push({name:J.constraint_name,columns:typeof J.columns==="string"?J.columns.split(","):[J.columns],referencedSchema:J.referenced_schema,referencedTable:J.referenced_table,referencedColumns:typeof J.referenced_columns==="string"?J.referenced_columns.split(","):[J.referenced_columns],onUpdate:J.on_update,onDelete:J.on_delete})}let A={};for(let J of U){let R=`${J.referenced_schema}.${J.referenced_table}`;if(!A[R])A[R]=[];A[R].push({constraintName:J.constraint_name,referencingSchema:J.referencing_schema,referencingTable:J.referencing_table,referencingColumns:typeof J.referencing_columns==="string"?J.referencing_columns.split(","):[J.referencing_columns],referencedColumns:typeof J.referenced_columns==="string"?J.referenced_columns.split(","):[J.referenced_columns]})}for(let J of G)for(let R of W[J.name]){let z=`${J.name}.${R.name}`;if(!Q[z])Q[z]=[];if(!j[z])j[z]=[];if(!K[z])K[z]=[];if(!A[z])A[z]=[]}return{schemas:G,tables:W,columns:Q,indexes:j,foreignKeys:K,referencingForeignKeys:A}}async getSchemas($){return this.ensureConnected(),[...await $.unsafe("SELECT DATABASE() AS name")]}async getTables($,Z){return this.ensureConnected(),[...await $.unsafe(`SELECT table_name AS name, table_type
|
|
183
199
|
FROM information_schema.tables
|
|
184
200
|
WHERE table_schema = ?
|
|
185
|
-
ORDER BY table_name`,[Z])].map((G)=>({schema:Z,name:G.name,type:G.table_type==="VIEW"?"view":"table"}))}async ping(){this.ensureConnected()
|
|
201
|
+
ORDER BY table_name`,[Z])].map((G)=>({schema:Z,name:G.name,type:G.table_type==="VIEW"?"view":"table"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async*iterate($,Z,B=1000,G,X){this.ensureConnected();let W=this.resolveSession(X);if(W?.txActive)throw Error("Cannot iterate on a session with an active transaction");let Y=W?W.conn:this.pool.acquireConnection(),H=!W;if(W)W.txActive=!0,W.iterating=!0;try{await Y.unsafe("START TRANSACTION WITH CONSISTENT SNAPSHOT");let V=0;while(!0){if(G?.aborted)throw new DOMException("Aborted","AbortError");let U=`${$} LIMIT ? OFFSET ?`,j=[...await Y.unsafe(U,[...Z??[],B,V])];if(j.length===0)break;if(yield j,j.length<B)break;V+=B}await Y.unsafe("COMMIT")}catch(V){try{await Y.unsafe("ROLLBACK")}catch{}throw V}finally{if(W)W.txActive=!1,W.iterating=!1;if(H)await this.pool.releaseConnection(Y)}}async importBatch($,Z,B,G){if(this.ensureConnected(),B.length===0)return 0;let X=Z.map((U)=>this.quoteIdentifier(U)).join(", "),W=[],Y=[];for(let U=0;U<B.length;U++){let Q=[];for(let j=0;j<Z.length;j++)W.push(B[U][Z[j]]),Q.push(this.placeholder(W.length));Y.push(`(${Q.join(", ")})`)}let H=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(H,W,G)).affectedRows??B.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{if(this.sessions.has(S)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let Z=this.pool.acquireConnection();try{await Z.unsafe("START TRANSACTION")}catch(B){throw await this.pool.releaseConnection(Z),B}this.sessions.set(S,{conn:Z,txActive:!0,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit($){this.ensureConnected();let Z=$??S,B=this.sessions.get(Z);if(!B)throw Error("No active transaction");if(B.iterating)throw Error("Cannot commit during active iteration");try{await B.conn.unsafe("COMMIT"),B.txActive=!1}catch(G){if(u(G))throw B.txActive=!1,new _("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:G});try{await B.conn.unsafe("ROLLBACK"),B.txActive=!1}catch{}throw G}finally{if(Z===S)this.sessions.delete(S),await this.pool.releaseConnection(B.conn)}}async rollback($){this.ensureConnected();let Z=$??S,B=this.sessions.get(Z);if(!B)throw Error("No active transaction");if(B.iterating)throw Error("Cannot rollback during active iteration");try{await B.conn.unsafe("ROLLBACK"),B.txActive=!1}catch(G){if(u(G))B.txActive=!1;throw G}finally{if(Z===S)this.sessions.delete(S),await this.pool.releaseConnection(B.conn)}}inTransaction($){let Z=$??S;return this.sessions.get(Z)?.txActive??!1}isTxAborted($){return!1}isIterating($){let Z=$??S;return this.sessions.get(Z)?.iterating??!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.pool||!this.connected)throw Error("Not connected. Call connect() first.")}resolveSession($){if(!$)return;let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);return Z}}var S="__default__";var X5=x(()=>{I();q();n$();R$();s$()});function M7($){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 $0{pool=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect($){if($.type!=="postgresql")throw Error("PostgresDriver requires a postgresql connection config");let Z=new URLSearchParams;if($.ssl)Z.set("sslmode",$.ssl);Z.set("application_name","dotaz");let B=`postgres://${encodeURIComponent($.user)}:${encodeURIComponent($.password)}@${$.host}:${$.port}/${encodeURIComponent($.database)}?${Z}`;this.pool=new s(B,(G)=>G.unsafe("DISCARD ALL"));try{await this.pool.connect()}catch(G){throw this.pool=null,G instanceof _?G:o$(G)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,$]of this.sessions)await d($.conn,{rollback:!0});if(this.sessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=this.pool.createConnection();this.sessions.set($,{conn:Z,txActive:!1,txAborted:!1,iterating:!1,activeQueries:new Set})}async releaseSession($){let Z=this.sessions.get($);if(!Z)return;this.sessions.delete($),await d(Z.conn,{rollback:!0})}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==E)}async execute($,Z,B,G){this.ensureConnected();let X=this.resolveSession(B),W=X?X.conn:this.pool.getSystemConnection(),Y=performance.now(),H=W.unsafe($,Z??[]),V=X?void 0:G??Symbol();if(X)X.activeQueries.add(H);else this.poolActiveQueries.set(V,H);try{let U=await H,Q=Math.round(performance.now()-Y),j=[...U];if(X)O$(X,$);return{columns:j.length>0?Object.keys(j[0]).map((A)=>({name:A,dataType:"unknown"})):[],rows:j,rowCount:j.length,affectedRows:l(U),durationMs:Q}}catch(U){if(X?.txActive&&!u(U))X.txAborted=!0;throw U instanceof _?U:o$(U)}finally{if(X)X.activeQueries.delete(H);else this.poolActiveQueries.delete(V)}}async cancel($,Z){if($){let B=this.sessions.get($);if(B){for(let G of B.activeQueries)G.cancel();B.activeQueries.clear()}}else if(Z){let B=this.poolActiveQueries.get(Z);if(B)B.cancel(),this.poolActiveQueries.delete(Z)}else{for(let B of this.poolActiveQueries.values())B.cancel();this.poolActiveQueries.clear()}}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),B=Z?Z.conn:this.pool.getSystemConnection(),G=await this.getSchemas(B),W=`{${G.map((z)=>z.name).join(",")}}`,Y={};for(let z of G){let O=await this.getTables(B,z.name),L=await this.getMaterializedViews(B,z.name);Y[z.name]=[...O,...L]}let H=new Map;for(let z of G){let O=Y[z.name].filter((L)=>L.type==="materialized-view");if(O.length>0)H.set(z.name,O.map((L)=>L.name))}let[V,U,Q,j]=await Promise.all([B.unsafe(`SELECT
|
|
186
202
|
c.table_schema,
|
|
187
203
|
c.table_name,
|
|
188
204
|
c.column_name,
|
|
@@ -282,7 +298,7 @@ Request: ${Z.prompt}`}]})});if(!X.ok){let Y=await X.text().catch(()=>"");if(X.st
|
|
|
282
298
|
AND nsp_ref.nspname = ANY($1)
|
|
283
299
|
GROUP BY nsp_ref.nspname, cl_ref.relname, con.conname,
|
|
284
300
|
nsp_src.nspname, cl_src.relname
|
|
285
|
-
ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[W])]);for(let[z,
|
|
301
|
+
ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[W])]);for(let[z,O]of H){let L=await B.unsafe(`SELECT
|
|
286
302
|
n.nspname AS schema_name,
|
|
287
303
|
c.relname AS table_name,
|
|
288
304
|
a.attname AS column_name,
|
|
@@ -300,7 +316,7 @@ Request: ${Z.prompt}`}]})});if(!X.ok){let Y=await X.text().catch(()=>"");if(X.st
|
|
|
300
316
|
AND c.relname = ANY($2)
|
|
301
317
|
AND a.attnum > 0
|
|
302
318
|
AND NOT a.attisdropped
|
|
303
|
-
ORDER BY n.nspname, c.relname, a.attnum`,[z,`{${
|
|
319
|
+
ORDER BY n.nspname, c.relname, a.attnum`,[z,`{${O.join(",")}}`]);for(let P of L)V.push({table_schema:P.schema_name,table_name:P.table_name,column_name:P.column_name,data_type:P.data_type,udt_name:P.udt_name,is_nullable:P.is_nullable,column_default:P.column_default,character_maximum_length:null,is_primary_key:!1})}let K={};for(let z of V){let O=`${z.table_schema}.${z.table_name}`;if(!K[O])K[O]=[];K[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 U){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 J={};for(let z of Q){let O=`${z.table_schema}.${z.table_name}`;if(!J[O])J[O]=[];J[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 G)for(let O of Y[z.name]){let L=`${z.name}.${O.name}`;if(!K[L])K[L]=[];if(!A[L])A[L]=[];if(!J[L])J[L]=[];if(!R[L])R[L]=[]}return{schemas:G,tables:Y,columns:K,indexes:A,foreignKeys:J,referencingForeignKeys:R}}async getSchemas($){return this.ensureConnected(),[...await $.unsafe(`SELECT schema_name AS name
|
|
304
320
|
FROM information_schema.schemata
|
|
305
321
|
WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
|
|
306
322
|
ORDER BY schema_name`)]}async getTables($,Z){return this.ensureConnected(),[...await $.unsafe(`SELECT table_name AS name, table_type
|
|
@@ -309,12 +325,12 @@ Request: ${Z.prompt}`}]})});if(!X.ok){let Y=await X.text().catch(()=>"");if(X.st
|
|
|
309
325
|
ORDER BY table_name`,[Z])].map((G)=>({schema:Z,name:G.name,type:G.table_type==="VIEW"?"view":"table"}))}async getMaterializedViews($,Z){return this.ensureConnected(),[...await $.unsafe(`SELECT matviewname
|
|
310
326
|
FROM pg_matviews
|
|
311
327
|
WHERE schemaname = $1
|
|
312
|
-
ORDER BY matviewname`,[Z])].map((G)=>({schema:Z,name:G.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected(),await this.db.unsafe("SELECT 1")}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,Z.txAborted=!1}else{if(this.sessions.has(T)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let Z=await this.db.reserve();try{await Z.unsafe("BEGIN")}catch(B){throw Z.release(),B}this.sessions.set(T,{conn:Z,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit($){this.ensureConnected();let Z=$??T,B=this.sessions.get(Z);if(!B)throw Error("No active transaction");if(B.iterating)throw Error("Cannot commit during active iteration");try{await B.conn.unsafe("COMMIT"),B.txActive=!1,B.txAborted=!1}catch(G){if(I(G))throw B.txActive=!1,B.txAborted=!1,new L("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:G});try{await B.conn.unsafe("ROLLBACK"),B.txActive=!1,B.txAborted=!1}catch{}throw G}finally{if(Z===T)await E(B.conn,s),this.sessions.delete(T)}}async rollback($){this.ensureConnected();let Z=$??T,B=this.sessions.get(Z);if(!B)throw Error("No active transaction");if(B.iterating)throw Error("Cannot rollback during active iteration");try{await B.conn.unsafe("ROLLBACK"),B.txActive=!1,B.txAborted=!1}catch(G){if(I(G))B.txActive=!1,B.txAborted=!1;throw G}finally{if(Z===T)await E(B.conn,s),this.sessions.delete(T)}}inTransaction($){let Z=$??T;return this.sessions.get(Z)?.txActive??!1}isTxAborted($){let Z=$??T;return this.sessions.get(Z)?.txAborted??!1}isIterating($){let Z=$??T;return this.sessions.get(Z)?.iterating??!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,B=1000,G,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`);if(Y?.txActive)throw Error("Cannot iterate on a session with an active transaction");let H=Y?Y.conn:await this.db.reserve(),V=!Y;if(Y)Y.txActive=!0,Y.iterating=!0;let U=!1;try{await H.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await H.unsafe(`DECLARE ${W} NO SCROLL CURSOR FOR ${$}`,Z??[]);try{while(!0){if(G?.aborted)throw new DOMException("Aborted","AbortError");let j=[...await H.unsafe(`FETCH FORWARD ${B} FROM ${W}`)];if(j.length===0)break;if(yield j,j.length<B)break}}finally{try{await H.unsafe(`CLOSE ${W}`)}catch{}}await H.unsafe("COMMIT")}catch(Q){U=!0;try{await H.unsafe("ROLLBACK")}catch{}throw Q}finally{if(Y)Y.txActive=!1,Y.iterating=!1;if(V)await E(H,s,{rollback:!U});else if(Y&&!U)try{await H.unsafe("ROLLBACK")}catch{}}}async importBatch($,Z,B,G){if(this.ensureConnected(),B.length===0)return 0;let X=Z.map((U)=>this.quoteIdentifier(U)).join(", "),W=[],Y=[];for(let U=0;U<B.length;U++){let Q=[];for(let j=0;j<Z.length;j++)W.push(B[U][Z[j]]),Q.push(this.placeholder(W.length));Y.push(`(${Q.join(", ")})`)}let H=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(H,W,G)).affectedRows??B.length}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}resolveSession($){if(!$)return;let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);return Z}mapDataType($,Z){if($==="ARRAY")return"array";if($==="USER-DEFINED"){let B=Z.toLowerCase();if(B==="json"||B==="jsonb")return"json";return"enum"}return M7($)}}var T="__default__";var X5=x(()=>{m();y();O$();a$()});var{SQL:W5}=globalThis.Bun;function F7($){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 $0{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;iterating=!1;iterateDb=null;async connect($){if($.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");try{this.db=new W5(`sqlite:${$.path}`),this.dbPath=$.path,await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON")}catch(Z){throw this.db=null,this.dbPath=null,Z instanceof L?Z:o$(Z)}this.connected=!0}async disconnect(){if(this.connected=!1,this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession($){this.sessionIds.add($)}async releaseSession($){if(this.txActive&&this.txOwnerSession===$){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete($)}getSessionIds(){return[...this.sessionIds]}async execute($,Z,B){this.ensureConnected(),this.ensureSessionCanExecute(B);let G=performance.now();try{let X=await this.db.unsafe($,Z??[]),W=Math.round(performance.now()-G),Y=[...X],H=$.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(H))this.txActive=!0,this.txOwnerSession=B??null;else if(/^(COMMIT|END)\b/.test(H))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(H)&&!/^ROLLBACK\s+TO\b/.test(H))this.txActive=!1,this.txOwnerSession=null;return{columns:Y.length>0?Object.keys(Y[0]).map((U)=>({name:U,dataType:"unknown"})):[],rows:Y,rowCount:Y.length,affectedRows:d(X),durationMs:W}}catch(X){throw X instanceof L?X:o$(X)}}async cancel($,Z){}async loadSchema($){this.ensureConnected();let Z=await this.getSchemas(),B=Z[0].name,G=await this.getTables(B),X={[B]:G},W={},Y={},H={},V={},U=new Map;for(let Q of G){let j=`${B}.${Q.name}`;W[j]=await this.getColumns(B,Q.name),Y[j]=await this.getIndexes(B,Q.name);let K=await this.getForeignKeys(B,Q.name);H[j]=K;for(let A of K){let J=`${A.referencedSchema}.${A.referencedTable}`;if(!U.has(J))U.set(J,[]);U.get(J).push({constraintName:A.name,referencingSchema:B,referencingTable:Q.name,referencingColumns:A.columns,referencedColumns:A.referencedColumns})}}for(let Q of G){let j=`${B}.${Q.name}`;V[j]=U.get(j)??[]}return{schemas:Z,tables:X,columns:W,indexes:Y,foreignKeys:H,referencingForeignKeys:V}}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((B)=>({schema:$,name:B.name,type:B.type}))}async getColumns($,Z){this.ensureConnected();let B=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(Z)})`)],G=B.filter((X)=>X.pk>0).length;return B.map((X)=>({name:X.name,dataType:F7(X.type||"BLOB"),nullable:X.notnull===0&&X.pk===0,defaultValue:X.dflt_value,isPrimaryKey:X.pk>0,isAutoIncrement:X.pk>0&&G===1&&X.type?.toUpperCase()==="INTEGER"}))}async getIndexes($,Z){this.ensureConnected();let B=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(Z)})`)],G=[];for(let X of B){let W=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(X.name)})`)];G.push({name:X.name,columns:W.map((Y)=>Y.name),isUnique:X.unique===1,isPrimary:X.origin==="pk"})}return G}async getForeignKeys($,Z){this.ensureConnected();let B=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(Z)})`)],G=new Map;for(let X of B){let W=G.get(X.id);if(W)W.columns.push(X.from),W.referencedColumns.push(X.to);else G.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(G.values())}async ping(){this.ensureConnected(),await this.db.unsafe("SELECT 1")}async*iterate($,Z,B=1000,G,X){this.ensureConnected();let W=this.dbPath===":memory:",Y=W?this.db:this.getIterateDb();if(W){if(this.ensureSessionCanExecute(X),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=X??null,this.iterating=!0}await Y.unsafe("BEGIN");let H=!1;try{let V=0;while(!0){if(G?.aborted)throw new DOMException("Aborted","AbortError");let U=`${$} LIMIT ? OFFSET ?`,j=[...await Y.unsafe(U,[...Z??[],B,V])];if(j.length===0)break;if(yield j,j.length<B)break;V+=B}await Y.unsafe("COMMIT"),H=!0}catch(V){try{await Y.unsafe("ROLLBACK")}catch{}throw V}finally{if(!H)try{await Y.unsafe("ROLLBACK")}catch{}if(W)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null}}getIterateDb(){if(!this.iterateDb)this.iterateDb=new W5(`sqlite:${this.dbPath}`);return this.iterateDb}async importBatch($,Z,B,G){if(this.ensureConnected(),B.length===0)return 0;let X=Z.map((U)=>this.quoteIdentifier(U)).join(", "),W=[],Y=[];for(let U=0;U<B.length;U++){let Q=[];for(let j=0;j<Z.length;j++)W.push(B[U][Z[j]]),Q.push(this.placeholder(W.length));Y.push(`(${Q.join(", ")})`)}let H=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(H,W,G)).affectedRows??B.length}async beginTransaction($){if(this.ensureConnected(),this.txActive)throw Error($&&this.txOwnerSession!==$?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=$??null}async commit($){if(this.ensureConnected(),this.ensureSessionOwnsTx($),this.iterating)throw Error("Cannot commit during active iteration");await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback($){if(this.ensureConnected(),this.ensureSessionOwnsTx($),this.iterating)throw Error("Cannot rollback during active iteration");try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction($){if($!==void 0)return this.txActive&&this.txOwnerSession===$;return this.txActive&&this.txOwnerSession===null}isTxAborted($){return!1}isIterating($){return this.iterating}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`$${$}`}ensureSessionCanExecute($){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if($!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if($===void 0||$!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx($){if(!this.txActive)throw Error("No active transaction");if(!($===void 0?this.txOwnerSession===null:this.txOwnerSession===$))throw Error(`Cannot modify transaction owned by ${this.txOwnerSession===null?"sessionless caller":`session "${this.txOwnerSession}"`}`)}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}}var Y5=x(()=>{m();y();O$()});import{chmodSync as N7,unlinkSync as P7,writeFileSync as k7}from"fs";import{tmpdir as D7}from"os";import{join as C7}from"path";async function S7(){return new Promise(($,Z)=>{let B=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),G=B.port;if(B.stop(!0),G>0)$(G);else Z(Error("Could not find a free port"))})}async function q7($,Z,B){let G=Date.now()+Z;while(Date.now()<G){if(B&&B.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(T7)}}throw Error(`SSH tunnel port ${$} did not become available within ${Z/1000}s`)}async function Z0($,Z,B){let G=$.localPort||await S7(),X=null,W=null;try{let Y=["ssh","-N","-L",`${G}:${Z}:${B}`,"-p",String($.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],H={...process.env};if($.authMethod==="key"&&$.keyPath)Y.push("-i",$.keyPath),Y.push("-o","BatchMode=yes");else if($.password)X=C7(D7(),`dotaz-askpass-${process.pid}-${Date.now()}`),k7(X,`#!/bin/sh
|
|
313
|
-
echo '${$.password.replace(/'/g,"'\\''")}'`),
|
|
314
|
-
`);for(let B of Z){let G=B.toLowerCase();if(G.includes("permission denied")||G.includes("authentication"))return`SSH authentication failed: ${B.trim()}`;if(G.includes("connection refused"))return`SSH host unreachable: ${B.trim()}`;if(G.includes("timed out")||G.includes("timeout"))return`SSH connection timed out: ${B.trim()}`;if(G.includes("no such file")||G.includes("no such identity"))return`SSH key file not found: ${B.trim()}`;if(G.includes("could not resolve"))return`SSH host unreachable: ${B.trim()}`}return Z[Z.length-1]?.trim()||null}function b7($){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 E7=15000,T7=100;var V5=()=>{};class B0{drivers=new Map;passwords=new Map;states=new Map;listeners=[];sessionDeadListeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;healthCheckRunning=new Set;connectAttempt=new Map;constructor($,Z){this.appDb=$,this.opts={...w7,...Z}}async connect($,Z){let B=this.appDb.getConnectionById($);if(!B)throw Error(`Connection not found: ${$}`);this.cancelAutoReconnect($);let G=(this.connectAttempt.get($)??0)+1;if(this.connectAttempt.set($,G),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),await this.setConnectionState($,"connecting");try{let X=Z?{...B.config,...Z}:B.config;if(L$(X),g(X))this.passwords.set($,X.password);X=await this.setupSshTunnel($,X);let W=p(X),Y=_$(X);if(await Y.connect(X),this.connectAttempt.get($)!==G){await Y.disconnect().catch(()=>{});return}let H=new Map;if(H.set(W,Y),this.drivers.set($,H),h[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)}await this.setConnectionState($,"connected"),this.startHealthCheck($)}catch(X){if(this.connectAttempt.get($)!==G)return;await this.closeTunnel($);let W=X instanceof Error?X.message:"Unknown connection error",Y=X instanceof L?X.code:void 0;throw await 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($),await this.setConnectionState($,"disconnected")}async reconnect($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.gracefulDisconnect($);await this.connect($)}getDriver($,Z){let B=this.drivers.get($);if(!B)throw Error(`No active connection for id: ${$}`);let G=Z??this.getDefaultDatabaseName($),X=B.get(G);if(!X)throw Error(`No active driver for database "${G}" on connection ${$}`);return X}getConnectionState($){return this.states.get($)?.state??"disconnected"}async listDatabases($){let Z=this.appDb.getConnectionById($);if(!Z||!h[Z.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let B=p(Z.config),X=await this.getDriver($,B).execute("SELECT datname FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname"),W=this.drivers.get($),Y=W?[...W.keys()]:[B];return X.rows.map((H)=>({name:H.datname,isDefault:H.datname===B,isActive:Y.includes(H.datname)}))}async activateDatabase($,Z){let B=this.appDb.getConnectionById($);if(!B||!h[B.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let G=B.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($)??G.password,H={...G,database:Z,password:Y};await this.connectDatabase($,H,Z);let V=[...new Set([...G.activeDatabases??[],Z])];this.appDb.updateConnection({id:$,name:B.name,config:{...G,activeDatabases:V}})}async deactivateDatabase($,Z){let B=this.appDb.getConnectionById($);if(!B||!h[B.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let G=B.config;if(Z===p(G))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=(G.activeDatabases??[]).filter((Y)=>Y!==Z);this.appDb.updateConnection({id:$,name:B.name,config:{...G,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 L$($.config,Z),this.appDb.createConnection($)}updateConnection($){return L$($.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($){L$($);let Z=null,B=$;try{if($.type==="postgresql"&&$.sshTunnel?.enabled)Z=await Z0($.sshTunnel,$.host,$.port),B={...$,host:"127.0.0.1",port:Z.localPort};let G=_$(B);return await G.connect(B),await G.disconnect(),{success:!0}}catch(G){return{success:!1,error:G instanceof Error?G.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)}}onSessionDead($){return this.sessionDeadListeners.push($),()=>{let Z=this.sessionDeadListeners.indexOf($);if(Z>=0)this.sessionDeadListeners.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($){if(this.healthCheckRunning.has($))return;this.healthCheckRunning.add($);try{let Z=this.drivers.get($);if(!Z)return;for(let B of Z.values()){try{await Promise.race([B.ping(),new Promise((G,X)=>setTimeout(()=>X(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let G=!1;for(let X of Z.values()){if(X.inTransaction()){G=!0;break}for(let W of X.getSessionIds())if(X.inTransaction(W)){G=!0;break}if(G)break}this.stopHealthCheck($);try{await this.disconnectAllDrivers($)}catch{}await this.setConnectionState($,"disconnected","Connection lost"),this.startAutoReconnect($,G);return}for(let G of B.getSessionIds())try{await B.execute("SELECT 1",void 0,G)}catch{try{await B.releaseSession(G)}catch{}for(let X of this.sessionDeadListeners)try{await X({connectionId:$,sessionId:G})}catch{}}}}finally{this.healthCheckRunning.delete($)}}startAutoReconnect($,Z=!1){this.cancelAutoReconnect($);let B={attempt:0,timer:null,cancelled:!1,hadTransaction:Z};this.reconnectStates.set($,B),this.scheduleReconnectAttempt($,B)}cancelAutoReconnect($){let Z=this.reconnectStates.get($);if(Z){if(Z.cancelled=!0,Z.timer)clearTimeout(Z.timer);this.reconnectStates.delete($)}}async scheduleReconnectAttempt($,Z){if(Z.cancelled)return;if(Z.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete($),await this.setConnectionState($,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let B=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,Z.attempt),this.opts.reconnectMaxDelayMs);Z.timer=setTimeout(()=>{if(Z.cancelled)return;this.attemptReconnect($,Z).catch(()=>{})},B)}async attemptReconnect($,Z){if(Z.cancelled)return;let B=this.appDb.getConnectionById($);if(!B){this.cancelAutoReconnect($);return}Z.attempt++,await this.setConnectionState($,"reconnecting");try{await this.closeTunnel($);let G=this.passwords.get($),X=G?{...B.config,password:G}:B.config;X=await this.setupSshTunnel($,X);let W=p(X),Y=_$(X);if(await Y.connect(X),Z.cancelled){await Y.disconnect(),await this.closeTunnel($);return}let H=new Map;if(H.set(W,Y),this.drivers.set($,H),h[X.type].supportsMultiDatabase&&"activeDatabases"in X&&X.activeDatabases){let U=X.activeDatabases.filter((Q)=>Q!==X.database).map((Q)=>this.connectDatabase($,X,Q));await Promise.allSettled(U)}let V=Z.hadTransaction;this.reconnectStates.delete($),await this.setConnectionState($,"connected",void 0,void 0,V),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[B,G]of Z)try{for(let X of G.getSessionIds()){try{await G.cancel(X)}catch{}if(G.inTransaction(X))try{await G.rollback(X)}catch{}}if(G.inTransaction())try{await G.rollback()}catch{}try{await G.cancel()}catch{}}finally{try{await G.disconnect()}finally{Z.delete(B)}}this.drivers.delete($)}async disconnectAllDrivers($){let Z=this.drivers.get($);if(!Z)return;for(let[B,G]of Z)try{await G.disconnect()}finally{Z.delete(B)}this.drivers.delete($)}async connectDatabase($,Z,B){let G=this.drivers.get($);if(!G)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:B},H=_$(Y);await H.connect(Y),G.set(B,H)}async setupSshTunnel($,Z){if(Z.type!=="postgresql"||!Z.sshTunnel?.enabled)return Z;let B=await Z0(Z.sshTunnel,Z.host,Z.port);return this.tunnels.set($,B),{...Z,host:"127.0.0.1",port:B.localPort}}async closeTunnel($){let Z=this.tunnels.get($);if(Z)await Z.close(),this.tunnels.delete($)}getActiveDatabases($){let Z=this.drivers.get($);if(!Z)return[];return[...Z.keys()]}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 p(Z.config)}async setConnectionState($,Z,B,G,X){this.states.set($,{state:Z,error:B});let W=this.listeners.map((Y)=>Y({connectionId:$,state:Z,error:B,errorCode:G,transactionLost:X||void 0}));await Promise.allSettled(W)}}function _$($){let Z;switch($.type){case"postgresql":Z=new e$;break;case"sqlite":Z=new $0;break;case"mysql":Z=new s$;break;default:throw Error(`Unsupported connection type: ${$.type}`)}if(process.env.DEBUG_SQL)Z=new i$(Z);return Z}function L$($,Z=!1){if(!$||!$.type)throw Error("Connection config must have a type");let B=h[$.type];if(!B)throw Error(`Unsupported connection type: ${$.type}`);if(B.hasHost&&g($)){let G=B.label;if(!$.host)throw Error(`${G} host is required`);if(!$.port)throw Error(`${G} port is required`);if(!$.database)throw Error(`${G} database is required`);if(!$.user)throw Error(`${G} user is required`);if(!Z&&($.password===void 0||$.password===null))throw Error(`${G} password is required`)}else if($.type==="sqlite"){if(!$.path)throw Error("SQLite path is required")}}var w7;var U5=x(()=>{v$();y();G5();X5();Y5();V5();w7={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5,maxActiveDatabases:10}});function Q5(){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 B=Z.protocol.replace(/:$/,"");if(B==="postgresql"||B==="postgres"){let G=Z.hostname||"localhost",X=Z.port?Number(Z.port):5432,W=Z.pathname.replace(/^\//,"")||"postgres",Y=decodeURIComponent(Z.username||"postgres"),H=decodeURIComponent(Z.password||"");return{name:`${G}/${W}`,config:{type:"postgresql",host:G,port:X,database:W,user:Y,password:H}}}if(B==="mysql"){let G=Z.hostname||"localhost",X=Z.port?Number(Z.port):3306,W=Z.pathname.replace(/^\//,"")||"mysql",Y=decodeURIComponent(Z.username||"root"),H=decodeURIComponent(Z.password||"");return{name:`${G}/${W}`,config:{type:"mysql",host:G,port:X,database:W,user:Y,password:H}}}return console.warn(`DATABASE_URL: unsupported scheme "${B}", ignoring`),null}var x$="env-default";function X0(){return F$}function J5($,Z){let B=crypto.randomUUID(),G=a.create(":memory:"),X=new B0(G),W=new n(X,void 0,G),Y=new u$(Z),H=(J,O)=>{if(A.ws)A.ws.send(JSON.stringify({type:"message",channel:J,payload:O}))},{handlers:V,sessionManager:U}=$5(X,W,G,void 0,{encryption:Y,emitMessage:H}),Q=new Set;if(M$){G.createConnectionWithId(x$,{name:M$.name,config:M$.config}),Q.add(x$);let J=V["connections.list"];V["connections.list"]=()=>{return J().map((z)=>Q.has(z.id)?{...z,serverManaged:!0}:z)}}let j=X.onSessionDead((J)=>{if(U.handleSessionDead(J.sessionId),A.ws)A.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:U.listSessions(J.connectionId)}}))}),K=X.onStatusChanged(async(J)=>{if(A.ws)A.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(U.handleConnectionLost(J.connectionId),A.ws)A.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:[]}}))}if(J.state==="connected")try{let O=await U.handleConnectionRestored(J.connectionId);if(O.length>0&&A.ws)A.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:O}}))}catch(O){console.warn("Session restoration failed:",O instanceof Error?O.message:O)}}),A={id:B,appDb:G,connectionManager:X,queryExecutor:W,handlers:V,sessionManager:U,serverManagedIds:Q,unsubscribe:()=>{j(),K()},ws:$,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(F$.set(B,A),M$)X.connect(x$).catch((J)=>{console.warn("DATABASE_URL auto-connect failed:",J?.message??J)});return A}async function e($){if(F$.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 z5($){if($.ws=null,$.disconnectedAt=Date.now(),$.activeStreams===0)await e($);else $.ttlTimer=setTimeout(async()=>{if(F$.has($.id))await e($)},G0)}async function W0($){if($.activeStreams--,$.ws===null&&$.activeStreams===0)await e($)}function Y0($,Z,B,G,X){let W=crypto.randomUUID();return c.set(W,{session:$,connectionId:B,database:G,params:X,type:Z,createdAt:Date.now()}),W}function H0($,Z){let B=c.get($);if(!B)return null;if(B.type!==Z)return null;if(Date.now()-B.createdAt>j5)return c.delete($),null;return c.delete($),B}function K5(){let $=Date.now();for(let[Z,B]of c)if($-B.createdAt>j5)c.delete(Z)}var G0=300000,j5=300000,M$,F$,c;var A5=x(()=>{Z5();U5();I$();w$();l$();M$=Q5(),F$=new Map;c=new Map});var l7={};import{resolve as V0}from"path";async function I7($,Z){let B=H0(Z,"export");if(!B)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:G,connectionId:X,database:W,params:Y}=B,H=Y,V;try{V=G.connectionManager.getDriver(X,W)}catch(J){return new Response(JSON.stringify({error:J?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}G.activeStreams++;let U=f7[H.format]??"application/octet-stream",Q=u7[H.format]??"dat",j=`${H.table}.${Q}`,K=new AbortController;$.signal.addEventListener("abort",()=>K.abort());let A=new ReadableStream({async start(J){let O={write(z){if(typeof z==="string")J.enqueue(new TextEncoder().encode(z));else J.enqueue(z)},async end(){}};try{let z=await T$(V,H,O,K.signal,(R)=>{if(G.ws)G.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:R}}))});if(G.ws)G.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:z.rowCount}}));J.close()}catch(z){if(K.signal.aborted)try{J.close()}catch{}else J.error(z)}finally{await W0(G)}}});return new Response(A,{headers:{"Content-Type":U,"Content-Disposition":`attachment; filename="${j}"`}})}async function m7($,Z){let B=H0(Z,"import");if(!B)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:G,connectionId:X,database:W,params:Y}=B,H=Y,V;try{V=G.connectionManager.getDriver(X,W)}catch(Q){return new Response(JSON.stringify({error:Q?.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"}});G.activeStreams++;let U=new AbortController;$.signal.addEventListener("abort",()=>U.abort());try{let Q=await H$(V,$.body,H,U.signal,(j)=>{if(G.ws)G.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:j}}))});return new Response(JSON.stringify({rowCount:Q.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(Q){return new Response(JSON.stringify({error:Q?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await W0(G)}}var v7,R5,O5,_5,g7=60000,f7,u7,p7;var L5=x(()=>{S$();y$();y();A5();v7=Number(process.env.DOTAZ_PORT)||6401,R5=process.env.DOTAZ_HOST||"localhost",O5=process.env.DOTAZ_DIST_DIR||V0(import.meta.dir,"../../dist"),_5=process.env.DOTAZ_ENCRYPTION_KEY;if(!_5)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{K5()},60000);setInterval(async()=>{let $=Date.now();for(let[,Z]of X0())if(Z.disconnectedAt!==null&&$-Z.disconnectedAt>G0)await e(Z)},g7);f7={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},u7={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};p7=Bun.serve({port:v7,hostname:R5,async fetch($,Z){let B=new URL($.url);if(B.pathname==="/rpc"){if(Z.upgrade($,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let G=B.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(G&&$.method==="GET")return I7($,G[1]);let X=B.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(X&&$.method==="POST")return m7($,X[1]);if(B.pathname==="/api/menu-action"&&$.method==="POST")try{let V=(await $.json())?.action;if(!V)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,U]of X0())if(U.ws)U.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:V}}));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=V0(O5,B.pathname.slice(1)),Y=Bun.file(W);if(await Y.exists())return new Response(Y);if(W=V0(O5,"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=J5($,_5);Object.assign($.data,Z)},async close($){await z5($.data)},async message($,Z){let B;try{B=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(B.type==="request"){if(B.method==="stream.createExportToken"){let{connectionId:X,database:W,...Y}=B.params,H=Y0($.data,"export",X,W,Y);$.send(JSON.stringify({type:"response",id:B.id,success:!0,payload:{token:H}}));return}if(B.method==="stream.createImportToken"){let{connectionId:X,database:W,...Y}=B.params,H=Y0($.data,"import",X,W,Y);$.send(JSON.stringify({type:"response",id:B.id,success:!0,payload:{token:H}}));return}let G=$.data.handlers[B.method];if(!G){$.send(JSON.stringify({type:"response",id:B.id,success:!1,error:`Unknown method: ${B.method}`}));return}try{let X=await G(B.params);$.send(JSON.stringify({type:"response",id:B.id,success:!0,payload:X}))}catch(X){$.send(JSON.stringify({type:"response",id:B.id,success:!1,error:X?.message??String(X),errorCode:X instanceof L?X.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${R5}:${p7.port}`)});var{secrets:x5}=globalThis.Bun;import{randomBytes as d7}from"crypto";import{resolve as c7}from"path";var M5="dev.dotaz.server",F5="encryption-key",t=process.argv.slice(2),N5=Number(process.env.DOTAZ_PORT)||6401,P5=process.env.DOTAZ_HOST||"localhost";for(let $=0;$<t.length;$++){let Z=t[$];if((Z==="--port"||Z==="-p")&&t[$+1])N5=Number(t[$+1]),$++;else if((Z==="--host"||Z==="-H")&&t[$+1])P5=t[$+1],$++;else if(Z==="--help")console.log(`Usage: dotaz [options]
|
|
328
|
+
ORDER BY matviewname`,[Z])].map((G)=>({schema:Z,name:G.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}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,Z.txAborted=!1}else{if(this.sessions.has(E)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let Z=this.pool.acquireConnection();try{await Z.unsafe("BEGIN")}catch(B){throw await this.pool.releaseConnection(Z),B}this.sessions.set(E,{conn:Z,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit($){this.ensureConnected();let Z=$??E,B=this.sessions.get(Z);if(!B)throw Error("No active transaction");if(B.iterating)throw Error("Cannot commit during active iteration");try{await B.conn.unsafe("COMMIT"),B.txActive=!1,B.txAborted=!1}catch(G){if(u(G))throw B.txActive=!1,B.txAborted=!1,new _("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:G});try{await B.conn.unsafe("ROLLBACK"),B.txActive=!1,B.txAborted=!1}catch{}throw G}finally{if(Z===E)this.sessions.delete(E),await this.pool.releaseConnection(B.conn)}}async rollback($){this.ensureConnected();let Z=$??E,B=this.sessions.get(Z);if(!B)throw Error("No active transaction");if(B.iterating)throw Error("Cannot rollback during active iteration");try{await B.conn.unsafe("ROLLBACK"),B.txActive=!1,B.txAborted=!1}catch(G){if(u(G))B.txActive=!1,B.txAborted=!1;throw G}finally{if(Z===E)this.sessions.delete(E),await this.pool.releaseConnection(B.conn)}}inTransaction($){let Z=$??E;return this.sessions.get(Z)?.txActive??!1}isTxAborted($){let Z=$??E;return this.sessions.get(Z)?.txAborted??!1}isIterating($){let Z=$??E;return this.sessions.get(Z)?.iterating??!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,B=1000,G,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`);if(Y?.txActive)throw Error("Cannot iterate on a session with an active transaction");let H=Y?Y.conn:this.pool.acquireConnection(),V=!Y;if(Y)Y.txActive=!0,Y.iterating=!0;let U=!1;try{await H.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await H.unsafe(`DECLARE ${W} NO SCROLL CURSOR FOR ${$}`,Z??[]);try{while(!0){if(G?.aborted)throw new DOMException("Aborted","AbortError");let j=[...await H.unsafe(`FETCH FORWARD ${B} FROM ${W}`)];if(j.length===0)break;if(yield j,j.length<B)break}}finally{try{await H.unsafe(`CLOSE ${W}`)}catch{}}await H.unsafe("COMMIT")}catch(Q){U=!0;try{await H.unsafe("ROLLBACK")}catch{}throw Q}finally{if(Y)Y.txActive=!1,Y.iterating=!1;if(V)await this.pool.releaseConnection(H);else if(Y&&!U)try{await H.unsafe("ROLLBACK")}catch{}}}async importBatch($,Z,B,G){if(this.ensureConnected(),B.length===0)return 0;let X=Z.map((U)=>this.quoteIdentifier(U)).join(", "),W=[],Y=[];for(let U=0;U<B.length;U++){let Q=[];for(let j=0;j<Z.length;j++)W.push(B[U][Z[j]]),Q.push(this.placeholder(W.length));Y.push(`(${Q.join(", ")})`)}let H=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(H,W,G)).affectedRows??B.length}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}resolveSession($){if(!$)return;let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);return Z}mapDataType($,Z){if($==="ARRAY")return"array";if($==="USER-DEFINED"){let B=Z.toLowerCase();if(B==="json"||B==="jsonb")return"json";return"enum"}return M7($)}}var E="__default__";var W5=x(()=>{I();q();n$();R$();s$()});var{SQL:Y5}=globalThis.Bun;function N7($){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 Z0{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;iterating=!1;iterateDb=null;async connect($){if($.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");try{this.db=new Y5(`sqlite:${$.path}`),this.dbPath=$.path,await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON")}catch(Z){throw this.db=null,this.dbPath=null,Z instanceof _?Z:r$(Z)}this.connected=!0}async disconnect(){if(this.connected=!1,this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession($){this.sessionIds.add($)}async releaseSession($){if(this.txActive&&this.txOwnerSession===$){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete($)}getSessionIds(){return[...this.sessionIds]}async execute($,Z,B){this.ensureConnected(),this.ensureSessionCanExecute(B);let G=performance.now();try{let X=await this.db.unsafe($,Z??[]),W=Math.round(performance.now()-G),Y=[...X],H=$.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(H))this.txActive=!0,this.txOwnerSession=B??null;else if(/^(COMMIT|END)\b/.test(H))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(H)&&!/^ROLLBACK\s+TO\b/.test(H))this.txActive=!1,this.txOwnerSession=null;return{columns:Y.length>0?Object.keys(Y[0]).map((U)=>({name:U,dataType:"unknown"})):[],rows:Y,rowCount:Y.length,affectedRows:l(X),durationMs:W}}catch(X){throw X instanceof _?X:r$(X)}}async cancel($,Z){}async loadSchema($){this.ensureConnected();let Z=await this.getSchemas(),B=Z[0].name,G=await this.getTables(B),X={[B]:G},W={},Y={},H={},V={},U=new Map;for(let Q of G){let j=`${B}.${Q.name}`;W[j]=await this.getColumns(B,Q.name),Y[j]=await this.getIndexes(B,Q.name);let K=await this.getForeignKeys(B,Q.name);H[j]=K;for(let A of K){let J=`${A.referencedSchema}.${A.referencedTable}`;if(!U.has(J))U.set(J,[]);U.get(J).push({constraintName:A.name,referencingSchema:B,referencingTable:Q.name,referencingColumns:A.columns,referencedColumns:A.referencedColumns})}}for(let Q of G){let j=`${B}.${Q.name}`;V[j]=U.get(j)??[]}return{schemas:Z,tables:X,columns:W,indexes:Y,foreignKeys:H,referencingForeignKeys:V}}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((B)=>({schema:$,name:B.name,type:B.type}))}async getColumns($,Z){this.ensureConnected();let B=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(Z)})`)],G=B.filter((X)=>X.pk>0).length;return B.map((X)=>({name:X.name,dataType:N7(X.type||"BLOB"),nullable:X.notnull===0&&X.pk===0,defaultValue:X.dflt_value,isPrimaryKey:X.pk>0,isAutoIncrement:X.pk>0&&G===1&&X.type?.toUpperCase()==="INTEGER"}))}async getIndexes($,Z){this.ensureConnected();let B=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(Z)})`)],G=[];for(let X of B){let W=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(X.name)})`)];G.push({name:X.name,columns:W.map((Y)=>Y.name),isUnique:X.unique===1,isPrimary:X.origin==="pk"})}return G}async getForeignKeys($,Z){this.ensureConnected();let B=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(Z)})`)],G=new Map;for(let X of B){let W=G.get(X.id);if(W)W.columns.push(X.from),W.referencedColumns.push(X.to);else G.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(G.values())}async ping(){this.ensureConnected(),await this.db.unsafe("SELECT 1")}async*iterate($,Z,B=1000,G,X){this.ensureConnected();let W=this.dbPath===":memory:",Y=W?this.db:this.getIterateDb();if(W){if(this.ensureSessionCanExecute(X),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=X??null,this.iterating=!0}await Y.unsafe("BEGIN");let H=!1;try{let V=0;while(!0){if(G?.aborted)throw new DOMException("Aborted","AbortError");let U=`${$} LIMIT ? OFFSET ?`,j=[...await Y.unsafe(U,[...Z??[],B,V])];if(j.length===0)break;if(yield j,j.length<B)break;V+=B}await Y.unsafe("COMMIT"),H=!0}catch(V){try{await Y.unsafe("ROLLBACK")}catch{}throw V}finally{if(!H)try{await Y.unsafe("ROLLBACK")}catch{}if(W)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null}}getIterateDb(){if(!this.iterateDb)this.iterateDb=new Y5(`sqlite:${this.dbPath}`);return this.iterateDb}async importBatch($,Z,B,G){if(this.ensureConnected(),B.length===0)return 0;let X=Z.map((U)=>this.quoteIdentifier(U)).join(", "),W=[],Y=[];for(let U=0;U<B.length;U++){let Q=[];for(let j=0;j<Z.length;j++)W.push(B[U][Z[j]]),Q.push(this.placeholder(W.length));Y.push(`(${Q.join(", ")})`)}let H=`INSERT INTO ${$} (${X}) VALUES ${Y.join(", ")}`;return(await this.execute(H,W,G)).affectedRows??B.length}async beginTransaction($){if(this.ensureConnected(),this.txActive)throw Error($&&this.txOwnerSession!==$?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=$??null}async commit($){if(this.ensureConnected(),this.ensureSessionOwnsTx($),this.iterating)throw Error("Cannot commit during active iteration");await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback($){if(this.ensureConnected(),this.ensureSessionOwnsTx($),this.iterating)throw Error("Cannot rollback during active iteration");try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction($){if($!==void 0)return this.txActive&&this.txOwnerSession===$;return this.txActive&&this.txOwnerSession===null}isTxAborted($){return!1}isIterating($){return this.iterating}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`$${$}`}ensureSessionCanExecute($){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if($!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if($===void 0||$!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx($){if(!this.txActive)throw Error("No active transaction");if(!($===void 0?this.txOwnerSession===null:this.txOwnerSession===$))throw Error(`Cannot modify transaction owned by ${this.txOwnerSession===null?"sessionless caller":`session "${this.txOwnerSession}"`}`)}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}}var H5=x(()=>{I();q();R$()});import{chmodSync as P7,unlinkSync as k7,writeFileSync as D7}from"fs";import{tmpdir as C7}from"os";import{join as E7}from"path";async function q7(){return new Promise(($,Z)=>{let B=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),G=B.port;if(B.stop(!0),G>0)$(G);else Z(Error("Could not find a free port"))})}async function y7($,Z,B){let G=Date.now()+Z;while(Date.now()<G){if(B&&B.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(S7)}}throw Error(`SSH tunnel port ${$} did not become available within ${Z/1000}s`)}async function B0($,Z,B){let G=$.localPort||await q7(),X=null,W=null;try{let Y=["ssh","-N","-L",`${G}:${Z}:${B}`,"-p",String($.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],H={...process.env};if($.authMethod==="key"&&$.keyPath)Y.push("-i",$.keyPath),Y.push("-o","BatchMode=yes");else if($.password)X=E7(C7(),`dotaz-askpass-${process.pid}-${Date.now()}`),D7(X,`#!/bin/sh
|
|
329
|
+
echo '${$.password.replace(/'/g,"'\\''")}'`),P7(X,448),H.SSH_ASKPASS=X,H.SSH_ASKPASS_REQUIRE="force",H.DISPLAY=H.DISPLAY||":0";if(Y.push(`${$.username}@${$.host}`),W=Bun.spawn(Y,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:H}),W.stdin&&typeof W.stdin!=="number")W.stdin.end();let V=W.stderr&&typeof W.stderr!=="number"?W.stderr:null,U=y7(G,T7,W),Q=W.exited.then(async(K)=>{if(K!==0){let A=await h7(V),J=w7(A)||`SSH process exited with code ${K}`;throw Error(J)}});return await Promise.race([U,Q]),{localPort:G,close:async()=>{if(W)W.kill(),W=null;V5(X)}}}catch(Y){if(W)W.kill();if(V5(X),Y instanceof Error)throw b7(Y);throw Error(`SSH tunnel error: ${String(Y)}`)}}function V5($){if($)try{k7($)}catch{}}async function h7($){if(!$)return"";try{let Z=$.getReader(),B=[];while(!0){let{done:G,value:X}=await Z.read();if(G)break;B.push(X)}return Buffer.concat(B).toString("utf-8")}catch{return""}}function w7($){if(!$.trim())return null;let Z=$.trim().split(`
|
|
330
|
+
`);for(let B of Z){let G=B.toLowerCase();if(G.includes("permission denied")||G.includes("authentication"))return`SSH authentication failed: ${B.trim()}`;if(G.includes("connection refused"))return`SSH host unreachable: ${B.trim()}`;if(G.includes("timed out")||G.includes("timeout"))return`SSH connection timed out: ${B.trim()}`;if(G.includes("no such file")||G.includes("no such identity"))return`SSH key file not found: ${B.trim()}`;if(G.includes("could not resolve"))return`SSH host unreachable: ${B.trim()}`}return Z[Z.length-1]?.trim()||null}function b7($){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 T7=15000,S7=100;var U5=()=>{};class G0{drivers=new Map;passwords=new Map;states=new Map;listeners=[];sessionDeadListeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;healthCheckRunning=new Set;connectAttempt=new Map;constructor($,Z){this.appDb=$,this.opts={...v7,...Z}}async connect($,Z){let B=this.appDb.getConnectionById($);if(!B)throw Error(`Connection not found: ${$}`);this.cancelAutoReconnect($);let G=(this.connectAttempt.get($)??0)+1;if(this.connectAttempt.set($,G),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),await this.setConnectionState($,"connecting");try{let X=Z?{...B.config,...Z}:B.config;if(_$(X),v(X))this.passwords.set($,X.password);X=await this.setupSshTunnel($,X);let W=m(X),Y=L$(X);if(await Y.connect(X),this.connectAttempt.get($)!==G){await Y.disconnect().catch(()=>{});return}let H=new Map;if(H.set(W,Y),this.drivers.set($,H),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)}await this.setConnectionState($,"connected"),this.startHealthCheck($)}catch(X){if(this.connectAttempt.get($)!==G)return;await this.closeTunnel($);let W=X instanceof Error?X.message:"Unknown connection error",Y=X instanceof _?X.code:void 0;throw await 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($),await this.setConnectionState($,"disconnected")}async reconnect($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.gracefulDisconnect($);await this.connect($)}getDriver($,Z){let B=this.drivers.get($);if(!B)throw Error(`No active connection for id: ${$}`);let G=Z??this.getDefaultDatabaseName($),X=B.get(G);if(!X)throw Error(`No active driver for database "${G}" 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 B=m(Z.config),X=await this.getDriver($,B).execute("SELECT datname FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname"),W=this.drivers.get($),Y=W?[...W.keys()]:[B];return X.rows.map((H)=>({name:H.datname,isDefault:H.datname===B,isActive:Y.includes(H.datname)}))}async activateDatabase($,Z){let B=this.appDb.getConnectionById($);if(!B||!y[B.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let G=B.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($)??G.password,H={...G,database:Z,password:Y};await this.connectDatabase($,H,Z);let V=[...new Set([...G.activeDatabases??[],Z])];this.appDb.updateConnection({id:$,name:B.name,config:{...G,activeDatabases:V}})}async deactivateDatabase($,Z){let B=this.appDb.getConnectionById($);if(!B||!y[B.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let G=B.config;if(Z===m(G))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=(G.activeDatabases??[]).filter((Y)=>Y!==Z);this.appDb.updateConnection({id:$,name:B.name,config:{...G,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 _$($.config,Z),this.appDb.createConnection($)}updateConnection($){return _$($.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($){_$($);let Z=null,B=$;try{if($.type==="postgresql"&&$.sshTunnel?.enabled)Z=await B0($.sshTunnel,$.host,$.port),B={...$,host:"127.0.0.1",port:Z.localPort};let G=L$(B);return await G.connect(B),await G.disconnect(),{success:!0}}catch(G){return{success:!1,error:G instanceof Error?G.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)}}onSessionDead($){return this.sessionDeadListeners.push($),()=>{let Z=this.sessionDeadListeners.indexOf($);if(Z>=0)this.sessionDeadListeners.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($){if(this.healthCheckRunning.has($))return;this.healthCheckRunning.add($);try{let Z=this.drivers.get($);if(!Z)return;for(let B of Z.values()){try{await Promise.race([B.ping(),new Promise((G,X)=>setTimeout(()=>X(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let G=!1;for(let X of Z.values()){if(X.inTransaction()){G=!0;break}for(let W of X.getSessionIds())if(X.inTransaction(W)){G=!0;break}if(G)break}this.stopHealthCheck($);try{await this.disconnectAllDrivers($)}catch{}await this.setConnectionState($,"disconnected","Connection lost"),this.startAutoReconnect($,G);return}for(let G of B.getSessionIds())try{await B.execute("SELECT 1",void 0,G)}catch{try{await B.releaseSession(G)}catch{}for(let X of this.sessionDeadListeners)try{await X({connectionId:$,sessionId:G})}catch{}}}}finally{this.healthCheckRunning.delete($)}}startAutoReconnect($,Z=!1){this.cancelAutoReconnect($);let B={attempt:0,timer:null,cancelled:!1,hadTransaction:Z};this.reconnectStates.set($,B),this.scheduleReconnectAttempt($,B)}cancelAutoReconnect($){let Z=this.reconnectStates.get($);if(Z){if(Z.cancelled=!0,Z.timer)clearTimeout(Z.timer);this.reconnectStates.delete($)}}async scheduleReconnectAttempt($,Z){if(Z.cancelled)return;if(Z.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete($),await this.setConnectionState($,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let B=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,Z.attempt),this.opts.reconnectMaxDelayMs);Z.timer=setTimeout(()=>{if(Z.cancelled)return;this.attemptReconnect($,Z).catch(()=>{})},B)}async attemptReconnect($,Z){if(Z.cancelled)return;let B=this.appDb.getConnectionById($);if(!B){this.cancelAutoReconnect($);return}Z.attempt++,await this.setConnectionState($,"reconnecting");try{await this.closeTunnel($);let G=this.passwords.get($),X=G?{...B.config,password:G}:B.config;X=await this.setupSshTunnel($,X);let W=m(X),Y=L$(X);if(await Y.connect(X),Z.cancelled){await Y.disconnect(),await this.closeTunnel($);return}let H=new Map;if(H.set(W,Y),this.drivers.set($,H),y[X.type].supportsMultiDatabase&&"activeDatabases"in X&&X.activeDatabases){let U=X.activeDatabases.filter((Q)=>Q!==X.database).map((Q)=>this.connectDatabase($,X,Q));await Promise.allSettled(U)}let V=Z.hadTransaction;this.reconnectStates.delete($),await this.setConnectionState($,"connected",void 0,void 0,V),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[B,G]of Z)try{for(let X of G.getSessionIds()){try{await G.cancel(X)}catch{}if(G.inTransaction(X))try{await G.rollback(X)}catch{}}if(G.inTransaction())try{await G.rollback()}catch{}try{await G.cancel()}catch{}}finally{try{await G.disconnect()}finally{Z.delete(B)}}this.drivers.delete($)}async disconnectAllDrivers($){let Z=this.drivers.get($);if(!Z)return;for(let[B,G]of Z)try{await G.disconnect()}finally{Z.delete(B)}this.drivers.delete($)}async connectDatabase($,Z,B){let G=this.drivers.get($);if(!G)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:B},H=L$(Y);await H.connect(Y),G.set(B,H)}async setupSshTunnel($,Z){if(Z.type!=="postgresql"||!Z.sshTunnel?.enabled)return Z;let B=await B0(Z.sshTunnel,Z.host,Z.port);return this.tunnels.set($,B),{...Z,host:"127.0.0.1",port:B.localPort}}async closeTunnel($){let Z=this.tunnels.get($);if(Z)await Z.close(),this.tunnels.delete($)}getActiveDatabases($){let Z=this.drivers.get($);if(!Z)return[];return[...Z.keys()]}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 m(Z.config)}async setConnectionState($,Z,B,G,X){this.states.set($,{state:Z,error:B});let W=this.listeners.map((Y)=>Y({connectionId:$,state:Z,error:B,errorCode:G,transactionLost:X||void 0}));await Promise.allSettled(W)}}function L$($){let Z;switch($.type){case"postgresql":Z=new $0;break;case"sqlite":Z=new Z0;break;case"mysql":Z=new e$;break;default:throw Error(`Unsupported connection type: ${$.type}`)}if(process.env.DEBUG_SQL)Z=new i$(Z);return Z}function _$($,Z=!1){if(!$||!$.type)throw Error("Connection config must have a type");let B=y[$.type];if(!B)throw Error(`Unsupported connection type: ${$.type}`);if(B.hasHost&&v($)){let G=B.label;if(!$.host)throw Error(`${G} host is required`);if(!$.port)throw Error(`${G} port is required`);if(!$.database)throw Error(`${G} database is required`);if(!$.user)throw Error(`${G} user is required`);if(!Z&&($.password===void 0||$.password===null))throw Error(`${G} password is required`)}else if($.type==="sqlite"){if(!$.path)throw Error("SQLite path is required")}}var v7;var Q5=x(()=>{v$();q();X5();W5();H5();U5();v7={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5,maxActiveDatabases:10}});function j5(){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 B=Z.protocol.replace(/:$/,"");if(B==="postgresql"||B==="postgres"){let G=Z.hostname||"localhost",X=Z.port?Number(Z.port):5432,W=Z.pathname.replace(/^\//,"")||"postgres",Y=decodeURIComponent(Z.username||"postgres"),H=decodeURIComponent(Z.password||"");return{name:`${G}/${W}`,config:{type:"postgresql",host:G,port:X,database:W,user:Y,password:H}}}if(B==="mysql"){let G=Z.hostname||"localhost",X=Z.port?Number(Z.port):3306,W=Z.pathname.replace(/^\//,"")||"mysql",Y=decodeURIComponent(Z.username||"root"),H=decodeURIComponent(Z.password||"");return{name:`${G}/${W}`,config:{type:"mysql",host:G,port:X,database:W,user:Y,password:H}}}return console.warn(`DATABASE_URL: unsupported scheme "${B}", ignoring`),null}var x$="env-default";function W0(){return M$}function z5($,Z){let B=crypto.randomUUID(),G=a.create(":memory:"),X=new G0(G),W=new n(X,void 0,G),Y=new u$(Z),H=(J,R)=>{if(A.ws)A.ws.send(JSON.stringify({type:"message",channel:J,payload:R}))},{handlers:V,sessionManager:U}=Z5(X,W,G,void 0,{encryption:Y,emitMessage:H}),Q=new Set;if(F$){G.createConnectionWithId(x$,{name:F$.name,config:F$.config}),Q.add(x$);let J=V["connections.list"];V["connections.list"]=()=>{return J().map((z)=>Q.has(z.id)?{...z,serverManaged:!0}:z)}}let j=X.onSessionDead((J)=>{if(U.handleSessionDead(J.sessionId),A.ws)A.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:U.listSessions(J.connectionId)}}))}),K=X.onStatusChanged(async(J)=>{if(A.ws)A.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(U.handleConnectionLost(J.connectionId),A.ws)A.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:[]}}))}if(J.state==="connected")try{let R=await U.handleConnectionRestored(J.connectionId);if(R.length>0&&A.ws)A.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:R}}))}catch(R){console.warn("Session restoration failed:",R instanceof Error?R.message:R)}}),A={id:B,appDb:G,connectionManager:X,queryExecutor:W,handlers:V,sessionManager:U,serverManagedIds:Q,unsubscribe:()=>{j(),K()},ws:$,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(M$.set(B,A),F$)X.connect(x$).catch((J)=>{console.warn("DATABASE_URL auto-connect failed:",J?.message??J)});return A}async function e($){if(M$.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 K5($){if($.ws=null,$.disconnectedAt=Date.now(),$.activeStreams===0)await e($);else $.ttlTimer=setTimeout(async()=>{if(M$.has($.id))await e($)},X0)}async function Y0($){if($.activeStreams--,$.ws===null&&$.activeStreams===0)await e($)}function H0($,Z,B,G,X){let W=crypto.randomUUID();return c.set(W,{session:$,connectionId:B,database:G,params:X,type:Z,createdAt:Date.now()}),W}function V0($,Z){let B=c.get($);if(!B)return null;if(B.type!==Z)return null;if(Date.now()-B.createdAt>J5)return c.delete($),null;return c.delete($),B}function A5(){let $=Date.now();for(let[Z,B]of c)if($-B.createdAt>J5)c.delete(Z)}var X0=300000,J5=300000,F$,M$,c;var R5=x(()=>{B5();Q5();I$();b$();l$();F$=j5(),M$=new Map;c=new Map});var d7={};import{resolve as U0}from"path";async function m7($,Z){let B=V0(Z,"export");if(!B)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:G,connectionId:X,database:W,params:Y}=B,H=Y,V;try{V=G.connectionManager.getDriver(X,W)}catch(J){return new Response(JSON.stringify({error:J?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}G.activeStreams++;let U=u7[H.format]??"application/octet-stream",Q=I7[H.format]??"dat",j=`${H.table}.${Q}`,K=new AbortController;$.signal.addEventListener("abort",()=>K.abort());let A=new ReadableStream({async start(J){let R={write(z){if(typeof z==="string")J.enqueue(new TextEncoder().encode(z));else J.enqueue(z)},async end(){}};try{let z=await T$(V,H,R,K.signal,(O)=>{if(G.ws)G.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:O}}))});if(G.ws)G.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:z.rowCount}}));J.close()}catch(z){if(K.signal.aborted)try{J.close()}catch{}else J.error(z)}finally{await Y0(G)}}});return new Response(A,{headers:{"Content-Type":U,"Content-Disposition":`attachment; filename="${j}"`}})}async function p7($,Z){let B=V0(Z,"import");if(!B)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:G,connectionId:X,database:W,params:Y}=B,H=Y,V;try{V=G.connectionManager.getDriver(X,W)}catch(Q){return new Response(JSON.stringify({error:Q?.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"}});G.activeStreams++;let U=new AbortController;$.signal.addEventListener("abort",()=>U.abort());try{let Q=await H$(V,$.body,H,U.signal,(j)=>{if(G.ws)G.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:j}}))});return new Response(JSON.stringify({rowCount:Q.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(Q){return new Response(JSON.stringify({error:Q?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await Y0(G)}}var g7,L5,O5,_5,f7=60000,u7,I7,l7;var x5=x(()=>{S$();y$();q();R5();g7=Number(process.env.DOTAZ_PORT)||6401,L5=process.env.DOTAZ_HOST||"localhost",O5=process.env.DOTAZ_DIST_DIR||U0(import.meta.dir,"../../dist"),_5=process.env.DOTAZ_ENCRYPTION_KEY;if(!_5)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{A5()},60000);setInterval(async()=>{let $=Date.now();for(let[,Z]of W0())if(Z.disconnectedAt!==null&&$-Z.disconnectedAt>X0)await e(Z)},f7);u7={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},I7={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};l7=Bun.serve({port:g7,hostname:L5,async fetch($,Z){let B=new URL($.url);if(B.pathname==="/rpc"){if(Z.upgrade($,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let G=B.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(G&&$.method==="GET")return m7($,G[1]);let X=B.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(X&&$.method==="POST")return p7($,X[1]);if(B.pathname==="/api/menu-action"&&$.method==="POST")try{let V=(await $.json())?.action;if(!V)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,U]of W0())if(U.ws)U.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:V}}));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=U0(O5,B.pathname.slice(1)),Y=Bun.file(W);if(await Y.exists())return new Response(Y);if(W=U0(O5,"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($,_5);Object.assign($.data,Z)},async close($){await K5($.data)},async message($,Z){let B;try{B=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(B.type==="request"){if(B.method==="stream.createExportToken"){let{connectionId:X,database:W,...Y}=B.params,H=H0($.data,"export",X,W,Y);$.send(JSON.stringify({type:"response",id:B.id,success:!0,payload:{token:H}}));return}if(B.method==="stream.createImportToken"){let{connectionId:X,database:W,...Y}=B.params,H=H0($.data,"import",X,W,Y);$.send(JSON.stringify({type:"response",id:B.id,success:!0,payload:{token:H}}));return}let G=$.data.handlers[B.method];if(!G){$.send(JSON.stringify({type:"response",id:B.id,success:!1,error:`Unknown method: ${B.method}`}));return}try{let X=await G(B.params);$.send(JSON.stringify({type:"response",id:B.id,success:!0,payload:X}))}catch(X){$.send(JSON.stringify({type:"response",id:B.id,success:!1,error:X?.message??String(X),errorCode:X instanceof _?X.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${L5}:${l7.port}`)});var{secrets:F5}=globalThis.Bun;import{randomBytes as c7}from"crypto";import{resolve as t7}from"path";var M5="dev.dotaz.server",N5="encryption-key",t=process.argv.slice(2),P5=Number(process.env.DOTAZ_PORT)||6401,k5=process.env.DOTAZ_HOST||"localhost";for(let $=0;$<t.length;$++){let Z=t[$];if((Z==="--port"||Z==="-p")&&t[$+1])P5=Number(t[$+1]),$++;else if((Z==="--host"||Z==="-H")&&t[$+1])k5=t[$+1],$++;else if(Z==="--help")console.log(`Usage: dotaz [options]
|
|
315
331
|
|
|
316
332
|
Options:
|
|
317
333
|
-p, --port <port> Port to listen on (default: 6401)
|
|
318
334
|
-H, --host <host> Host to bind to (default: localhost)
|
|
319
335
|
--help Show this help message
|
|
320
|
-
`),process.exit(0)}if(!process.env.DOTAZ_ENCRYPTION_KEY){let $=await
|
|
336
|
+
`),process.exit(0)}if(!process.env.DOTAZ_ENCRYPTION_KEY){let $=await F5.get({service:M5,name:N5});if(!$){$=c7(32).toString("hex");try{await F5.set({service:M5,name:N5,value:$})}catch{}}process.env.DOTAZ_ENCRYPTION_KEY=$}process.env.DOTAZ_PORT=String(P5);process.env.DOTAZ_HOST=k5;process.env.DOTAZ_DIST_DIR=t7(import.meta.dir,"../dist");await Promise.resolve().then(() => (x5(),d7));
|