@dotaz/server 0.0.20 → 0.0.22

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