@dotaz/server 0.0.19 → 0.0.20

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