import{a as g,b}from"./chunk-74CEPOFO.js";import"./chunk-DXB73IDG.js";import{fileURLToPath as P}from"node:url";import{Worker as W}from"node:worker_threads";import E from"sql.js";function $(e,t,o){switch(o.mode){case"list":return x(e,t,o);case"csv":return q(e,t,o);case"json":return V(e,t);case"line":return k(e,t,o);case"column":return A(e,t,o);case"table":return O(e,t,o);case"markdown":return R(e,t,o);case"tabs":return N(e,t,o);case"box":return M(e,t,o);case"quote":return I(e,t,o);case"html":return U(e,t,o);case"ascii":return B(e,t,o)}}function f(e,t){return e==null?t:e instanceof Uint8Array||Buffer.isBuffer(e)?Buffer.from(e).toString("utf8"):typeof e=="number"&&!Number.isInteger(e)?e.toPrecision(17).replace(/\.?0+$/,""):String(e)}function x(e,t,o){let r=[];o.header&&e.length>0&&r.push(e.join(o.separator));for(let a of t)r.push(a.map(s=>f(s,o.nullValue)).join(o.separator));return r.length>0?`${r.join(o.newline)}${o.newline}`:""}function q(e,t,o){let r=[];o.header&&e.length>0&&r.push(e.map(w).join(","));for(let a of t)r.push(a.map(s=>w(f(s,o.nullValue))).join(","));return r.length>0?`${r.join(`
`)}
`:""}function w(e){return e.includes(",")||e.includes('"')||e.includes("'")||e.includes(`
`)?`"${e.replace(/"/g,'""')}"`:e}function j(e){return e.toPrecision(17).replace(/\.?0+$/,"")}function L(e){return e===null?"null":typeof e=="number"?Number.isInteger(e)?String(e):j(e):JSON.stringify(e)}function V(e,t){return t.length===0?"":`[${t.map(r=>`{${e.map((s,i)=>`${JSON.stringify(s)}:${L(r[i])}`).join(",")}}`).join(`,
`)}]
`}function k(e,t,o){if(e.length===0||t.length===0)return"";let r=Math.max(5,...e.map(s=>s.length)),a=[];for(let s of t)for(let i=0;i<e.length;i++){let n=e[i].padStart(r);a.push(`${n} = ${f(s[i],o.nullValue)}`)}return`${a.join(`
`)}
`}function A(e,t,o){if(e.length===0)return"";let r=e.map(s=>s.length);for(let s of t)for(let i=0;i<s.length;i++){let n=f(s[i],o.nullValue).length;n>r[i]&&(r[i]=n)}let a=[];o.header&&(a.push(e.map((s,i)=>s.padEnd(r[i])).join("  ")),a.push(r.map(s=>"-".repeat(s)).join("  ")));for(let s of t)a.push(s.map((i,n)=>f(i,o.nullValue).padEnd(r[n])).join("  "));return a.length>0?`${a.join(`
`)}
`:""}function O(e,t,o){if(e.length===0)return"";let r=e.map(i=>i.length);for(let i of t)for(let n=0;n<i.length;n++){let l=f(i[n],o.nullValue).length;l>r[n]&&(r[n]=l)}let a=[],s=`+${r.map(i=>"-".repeat(i+2)).join("+")}+`;a.push(s),o.header&&(a.push(`| ${e.map((i,n)=>i.padEnd(r[n])).join(" | ")} |`),a.push(s));for(let i of t)a.push(`| ${i.map((n,l)=>f(n,o.nullValue).padEnd(r[l])).join(" | ")} |`);return a.push(s),`${a.join(`
`)}
`}function R(e,t,o){if(e.length===0)return"";let r=[];o.header&&(r.push(`| ${e.join(" | ")} |`),r.push(`|${e.map(()=>"---").join("|")}|`));for(let a of t)r.push(`| ${a.map(s=>f(s,o.nullValue)).join(" | ")} |`);return r.length>0?`${r.join(`
`)}
`:""}function N(e,t,o){let r=[];o.header&&e.length>0&&r.push(e.join("	"));for(let a of t)r.push(a.map(s=>f(s,o.nullValue)).join("	"));return r.length>0?`${r.join(o.newline)}${o.newline}`:""}function M(e,t,o){if(e.length===0)return"";let r=e.map(s=>s.length);for(let s of t)for(let i=0;i<s.length;i++){let n=f(s[i],o.nullValue).length;n>r[i]&&(r[i]=n)}let a=[];a.push(`\u250C${r.map(s=>"\u2500".repeat(s+2)).join("\u252C")}\u2510`),a.push(`\u2502 ${e.map((s,i)=>s.padEnd(r[i])).join(" \u2502 ")} \u2502`),a.push(`\u251C${r.map(s=>"\u2500".repeat(s+2)).join("\u253C")}\u2524`);for(let s of t)a.push(`\u2502 ${s.map((i,n)=>f(i,o.nullValue).padEnd(r[n])).join(" \u2502 ")} \u2502`);return a.push(`\u2514${r.map(s=>"\u2500".repeat(s+2)).join("\u2534")}\u2518`),`${a.join(`
`)}
`}function I(e,t,o){let r=[];o.header&&e.length>0&&r.push(e.map(a=>`'${a}'`).join(","));for(let a of t)r.push(a.map(s=>s==null?"NULL":typeof s=="number"?Number.isInteger(s)?String(s):j(s):`'${String(s)}'`).join(","));return r.length>0?`${r.join(o.newline)}${o.newline}`:""}function U(e,t,o){let r=[];o.header&&e.length>0&&(r.push(`<TR>${e.map(a=>`<TH>${S(a)}</TH>`).join("")}`),r.push("</TR>"));for(let a of t)r.push(`<TR>${a.map(s=>`<TD>${S(f(s,o.nullValue))}</TD>`).join("")}`),r.push("</TR>");return r.length>0?`${r.join(`
`)}
`:""}function S(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function B(e,t,o){let s=[];o.header&&e.length>0&&s.push(e.join(""));for(let i of t)s.push(i.map(n=>f(n,o.nullValue)).join(""));return s.length>0?s.join("")+"":""}var D=5e3,Q={name:"sqlite3",summary:"SQLite database CLI",usage:"sqlite3 [OPTIONS] DATABASE [SQL]",options:["-list           output in list mode (default)","-csv            output in CSV mode","-json           output in JSON mode","-line           output in line mode","-column         output in column mode","-table          output as ASCII table","-markdown       output as markdown table","-tabs           output in tab-separated mode","-box            output in Unicode box mode","-quote          output in SQL quote mode","-html           output as HTML table","-ascii          output in ASCII mode (control chars)","-header         show column headers","-noheader       hide column headers","-separator SEP  field separator for list mode (default: |)","-newline SEP    row separator (default: \\n)","-nullvalue TEXT text for NULL values (default: empty)","-readonly       open database read-only (no writeback)","-bail           stop on first error","-echo           print SQL before execution","-cmd COMMAND    run SQL command before main SQL","-version        show SQLite version","--              end of options","--help          show this help"],examples:['sqlite3 :memory: "CREATE TABLE t(x); INSERT INTO t VALUES(1); SELECT * FROM t"','sqlite3 -json data.db "SELECT * FROM users"','sqlite3 -csv -header data.db "SELECT id, name FROM products"','sqlite3 -box data.db "SELECT * FROM users"']};function F(e){let t={mode:"list",header:!1,separator:"|",newline:`
`,nullValue:"",readonly:!1,bail:!1,echo:!1,cmd:null},o=null,r=null,a=!1,s=!1;for(let i=0;i<e.length;i++){let n=e[i];if(s){o===null?o=n:r===null&&(r=n);continue}if(n==="--")s=!0;else if(n==="-version")a=!0;else if(n==="-list")t.mode="list";else if(n==="-csv")t.mode="csv";else if(n==="-json")t.mode="json";else if(n==="-line")t.mode="line";else if(n==="-column")t.mode="column";else if(n==="-table")t.mode="table";else if(n==="-markdown")t.mode="markdown";else if(n==="-tabs")t.mode="tabs";else if(n==="-box")t.mode="box";else if(n==="-quote")t.mode="quote";else if(n==="-html")t.mode="html";else if(n==="-ascii")t.mode="ascii";else if(n==="-header")t.header=!0;else if(n==="-noheader")t.header=!1;else if(n==="-readonly")t.readonly=!0;else if(n==="-bail")t.bail=!0;else if(n==="-echo")t.echo=!0;else if(n==="-separator"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -separator
`,exitCode:1};t.separator=e[++i]}else if(n==="-newline"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -newline
`,exitCode:1};t.newline=e[++i]}else if(n==="-nullvalue"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -nullvalue
`,exitCode:1};t.nullValue=e[++i]}else if(n==="-cmd"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
`,exitCode:1};t.cmd=e[++i]}else{if(n.startsWith("-"))return{stdout:"",stderr:`sqlite3: Error: unknown option: ${n.startsWith("--")?n.slice(1):n}
Use -help for a list of options.
`,exitCode:1};o===null?o=n:r===null&&(r=n)}}return{options:t,database:o,sql:r,showVersion:a}}async function H(){let e=await E(),t=new e.Database;try{let o=t.exec("SELECT sqlite_version()");return o.length>0&&o[0].values.length>0?String(o[0].values[0][0]):"unknown"}finally{t.close()}}function J(e){let t=e.trim().toUpperCase();return t.startsWith("INSERT")||t.startsWith("UPDATE")||t.startsWith("DELETE")||t.startsWith("CREATE")||t.startsWith("DROP")||t.startsWith("ALTER")||t.startsWith("REPLACE")||t.startsWith("VACUUM")}function _(e){let t=[],o="",r=!1,a="";for(let i=0;i<e.length;i++){let n=e[i];if(r)o+=n,n===a&&(e[i+1]===a?o+=e[++i]:r=!1);else if(n==="'"||n==='"')o+=n,r=!0,a=n;else if(n===";"){let l=o.trim();l&&t.push(l),o=""}else o+=n}let s=o.trim();return s&&t.push(s),t}async function X(e){let t;try{let a=await E();e.dbBuffer?t=new a.Database(e.dbBuffer):t=new a.Database}catch(a){return{success:!1,error:a.message}}let o=[],r=!1;try{let a=_(e.sql);for(let i of a)try{if(J(i))t.run(i),r=!0,o.push({type:"data",columns:[],rows:[]});else{let n=t.prepare(i),l=n.getColumnNames(),d=[];for(;n.step();)d.push(n.get());n.free(),o.push({type:"data",columns:l,rows:d})}}catch(n){let l=n.message;if(o.push({type:"error",error:l}),e.options.bail)break}let s=null;return r&&(s=t.export()),t.close(),{success:!0,results:o,hasModifications:r,dbBuffer:s}}catch(a){return t.close(),{success:!1,error:a.message}}}async function Y(e,t){try{let o=P(new URL("./worker.js",import.meta.url));return await new Promise((r,a)=>{let s=new W(o,{workerData:e}),i=setTimeout(()=>{s.terminate(),r({success:!1,error:`Query timeout: execution exceeded ${t}ms limit`})},t);s.on("message",n=>{clearTimeout(i),r(n)}),s.on("error",n=>{clearTimeout(i),a(n)}),s.on("exit",n=>{clearTimeout(i),n!==0&&r({success:!1,error:`Worker exited with code ${n}`})})})}catch{return X(e)}}var te={name:"sqlite3",async execute(e,t){if(b(e)||e.includes("-help"))return g(Q);let o=F(e);if("exitCode"in o)return o;let{options:r,database:a,sql:s,showVersion:i}=o;if(i)return{stdout:`${await H()}
`,stderr:"",exitCode:0};if(!a)return{stdout:"",stderr:`sqlite3: missing database argument
`,exitCode:1};let n=s||t.stdin.trim();if(r.cmd&&(n=r.cmd+(n?`; ${n}`:"")),!n)return{stdout:"",stderr:`sqlite3: no SQL provided
`,exitCode:1};let l=a===":memory:",d="",m=null;try{l||(d=t.fs.resolvePath(t.cwd,a),await t.fs.exists(d)&&(m=await t.fs.readFileBuffer(d)))}catch(u){return{stdout:"",stderr:`sqlite3: unable to open database "${a}": ${u.message}
`,exitCode:1}}let C=t.limits?.maxSqliteTimeoutMs??D,T={dbBuffer:m,sql:n,options:{bail:r.bail,echo:r.echo}},c;try{c=await Y(T,C)}catch(u){return{stdout:"",stderr:`sqlite3: worker error: ${u.message}
`,exitCode:1}}if(!c.success)return{stdout:"",stderr:`sqlite3: ${c.error}
`,exitCode:1};let y={mode:r.mode,header:r.header,separator:r.separator,newline:r.newline,nullValue:r.nullValue},h="";r.echo&&(h+=`${n}
`);let p=!1;for(let u of c.results)if(u.type==="error"){if(r.bail)return{stdout:h,stderr:`Error: ${u.error}
`,exitCode:1};h+=`Error: ${u.error}
`,p=!0}else u.columns&&u.rows&&(u.rows.length>0||r.header)&&(h+=$(u.columns,u.rows,y));if(c.hasModifications&&!r.readonly&&!l&&d&&c.dbBuffer)try{await t.fs.writeFile(d,c.dbBuffer)}catch(u){return{stdout:h,stderr:`sqlite3: failed to write database: ${u.message}
`,exitCode:1}}return{stdout:h,stderr:"",exitCode:p&&r.bail?1:0}}};export{te as sqlite3Command};
