drixio 1.1.3 → 1.1.4

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/dist/cli.js CHANGED
@@ -9,7 +9,7 @@ var Jt=Object.defineProperty;var E=(s,a)=>()=>(s&&(a=s(s=0)),a);var L=(s,a)=>{fo
9
9
  `)+aa(` \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
10
10
  `)+oa(" \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D")))}function se(s,a){let r="\u2550".repeat(72);console.log(N.cyan(`
11
11
  \u2554${r}\u2557`));let o=72-s.length,e=Math.max(0,Math.floor(o/2)),n=Math.max(0,o-e),c=" ".repeat(e)+N.bold(N.white(s))+" ".repeat(n);console.log(N.cyan("\u2551")+c+N.cyan("\u2551")),console.log(N.cyan(`\u2560${"\u2550".repeat(72)}\u2563`));let i=(l,m)=>{let p=l.padEnd(12),u=` ${N.bold(p)}: ${m}`,d=` ${p}: `+m.replace(/\x1b\[[0-9;]*m/g,""),f=" ".repeat(Math.max(0,72-d.length));console.log(N.cyan("\u2551")+u+f+N.cyan("\u2551"))};for(let l of a)i(l.label,l.value);console.log(N.cyan(`\u255A${"\u2550".repeat(72)}\u255D`)),console.log(N.dim(` Use arrow keys to navigate \u2022 Enter to select \u2022 Ctrl+C to exit
12
- `))}function Fe(s){let a=" Lightweight Interactive TUI Database Client \u2022 v1.1.3 ",t="None",r="-",o="None";s.type==="unknown"?o=N.dim("No configuration found. Please run check to configure."):(t=s.type.toUpperCase(),r=s.targetUrl,o=s.source===".env"?"Loaded from project .env file":s.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config"),se(a,[{label:"Database",value:t},{label:"Target",value:r.length>45?"..."+r.slice(-42):r},{label:"Source",value:o},{label:"Working Dir",value:process.cwd().length>45?"..."+process.cwd().slice(-42):process.cwd()}])}var J,Xt,Zt,ea,ta,aa,oa,Se=E(()=>{"use strict";J=(s,a,t)=>r=>`\x1B[38;2;${s};${a};${t}m${r}\x1B[39m`,Xt=J(0,255,255),Zt=J(0,230,245),ea=J(0,210,235),ta=J(0,188,220),aa=J(0,168,205),oa=J(0,148,188)});var $e,We=E(()=>{"use strict";$e=class{dbPath;db=null;constructor(a){this.dbPath=a}async getDb(){if(!this.db){if(!(await import("fs")).existsSync(this.dbPath))throw new Error(`Failed to found database file at: ${this.dbPath}`);let t=await import("sqlite");this.db=new t.DatabaseSync(this.dbPath)}return this.db}quoteIdentifier(a){return`"${a.replace(/"/g,'""')}"`}async getTables(){return(await this.getDb()).prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name;").all().map(r=>r.name)}async getSchema(a){let t=await this.getDb(),r=this.quoteIdentifier(a),e=t.prepare(`PRAGMA table_info(${r})`).all(),c=t.prepare(`PRAGMA foreign_key_list(${r})`).all();return e.map(i=>{let l=c.find(m=>m.from===i.name);return{name:i.name,type:i.type,isPk:i.pk>0,nullable:i.notnull===0,defaultValue:i.dflt_value!=null?String(i.dflt_value):void 0,fkTarget:l?{table:l.table,column:l.to}:void 0}})}async getIndexes(a){let t=await this.getDb(),r=this.quoteIdentifier(a),e=t.prepare(`PRAGMA index_list(${r})`).all(),n=[];for(let c of e){if(c.origin==="pk")continue;let l=t.prepare(`PRAGMA index_info(${this.quoteIdentifier(c.name)})`).all();n.push({name:c.name,columns:l.map(m=>m.name),isUnique:c.unique>0})}return n}async getData(a,t=50,r=0,o,e){let n=await this.getDb(),i=(await this.getSchema(a)).map(u=>u.name),l=`SELECT * FROM ${this.quoteIdentifier(a)}`;o&&(l+=` WHERE ${o}`),e&&(l+=` ORDER BY ${this.quoteIdentifier(e.col)} ${e.asc?"ASC":"DESC"}`),l+=` LIMIT ${t} OFFSET ${r}`;let p=n.prepare(l).all();return{columns:i,rows:p}}async query(a){let t=await this.getDb(),r=a.trim().toUpperCase();if(r.startsWith("SELECT")||r.startsWith("PRAGMA")||r.startsWith("EXPLAIN")||r.startsWith("WITH")){let n=t.prepare(a).all(),c=[];return n.length>0&&(c=Object.keys(n[0])),{columns:c,rows:n}}else return t.prepare(a).run(),{columns:["Result"],rows:[{Result:"Success"}]}}async executeSql(a){(await this.getDb()).exec(a)}async close(){this.db&&(this.db.close(),this.db=null)}async insert(a,t){if(t.length===0)return;let r=await this.getDb(),o=Object.keys(t[0]),e=o.map(l=>this.quoteIdentifier(l)).join(", "),n=o.map(()=>"?").join(", "),c=`INSERT INTO ${this.quoteIdentifier(a)} (${e}) VALUES (${n})`,i=r.prepare(c);for(let l of t){let m=o.map(p=>l[p]);i.run(...m)}}}});import na from"pg";var xe,je=E(()=>{"use strict";xe=class{client;connected=!1;constructor(a){this.client=new na.Client({connectionString:a})}async connectIfNecessary(){this.connected||(await this.client.connect(),this.connected=!0)}quoteIdentifier(a){return`"${a.replace(/"/g,'""')}"`}async getTables(){return await this.connectIfNecessary(),(await this.client.query(`
12
+ `))}function Ue(s){let a=" Lightweight Interactive TUI Database Client \u2022 v1.1.4 ",t="None",r="-",o="None";s.type==="unknown"?o=N.dim("No configuration found. Please run check to configure."):(t=s.type.toUpperCase(),r=s.targetUrl,o=s.source===".env"?"Loaded from project .env file":s.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config"),se(a,[{label:"Database",value:t},{label:"Target",value:r.length>45?"..."+r.slice(-42):r},{label:"Source",value:o},{label:"Working Dir",value:process.cwd().length>45?"..."+process.cwd().slice(-42):process.cwd()}])}var J,Xt,Zt,ea,ta,aa,oa,Se=E(()=>{"use strict";J=(s,a,t)=>r=>`\x1B[38;2;${s};${a};${t}m${r}\x1B[39m`,Xt=J(0,255,255),Zt=J(0,230,245),ea=J(0,210,235),ta=J(0,188,220),aa=J(0,168,205),oa=J(0,148,188)});var $e,We=E(()=>{"use strict";$e=class{dbPath;db=null;constructor(a){this.dbPath=a}async getDb(){if(!this.db){if(!(await import("fs")).existsSync(this.dbPath))throw new Error(`Failed to found database file at: ${this.dbPath}`);let t=await import("sqlite");this.db=new t.DatabaseSync(this.dbPath)}return this.db}quoteIdentifier(a){return`"${a.replace(/"/g,'""')}"`}async getTables(){return(await this.getDb()).prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name;").all().map(r=>r.name)}async getSchema(a){let t=await this.getDb(),r=this.quoteIdentifier(a),e=t.prepare(`PRAGMA table_info(${r})`).all(),c=t.prepare(`PRAGMA foreign_key_list(${r})`).all();return e.map(i=>{let l=c.find(m=>m.from===i.name);return{name:i.name,type:i.type,isPk:i.pk>0,nullable:i.notnull===0,defaultValue:i.dflt_value!=null?String(i.dflt_value):void 0,fkTarget:l?{table:l.table,column:l.to}:void 0}})}async getIndexes(a){let t=await this.getDb(),r=this.quoteIdentifier(a),e=t.prepare(`PRAGMA index_list(${r})`).all(),n=[];for(let c of e){if(c.origin==="pk")continue;let l=t.prepare(`PRAGMA index_info(${this.quoteIdentifier(c.name)})`).all();n.push({name:c.name,columns:l.map(m=>m.name),isUnique:c.unique>0})}return n}async getData(a,t=50,r=0,o,e){let n=await this.getDb(),i=(await this.getSchema(a)).map(u=>u.name),l=`SELECT * FROM ${this.quoteIdentifier(a)}`;o&&(l+=` WHERE ${o}`),e&&(l+=` ORDER BY ${this.quoteIdentifier(e.col)} ${e.asc?"ASC":"DESC"}`),l+=` LIMIT ${t} OFFSET ${r}`;let p=n.prepare(l).all();return{columns:i,rows:p}}async query(a){let t=await this.getDb(),r=a.trim().toUpperCase();if(r.startsWith("SELECT")||r.startsWith("PRAGMA")||r.startsWith("EXPLAIN")||r.startsWith("WITH")){let n=t.prepare(a).all(),c=[];return n.length>0&&(c=Object.keys(n[0])),{columns:c,rows:n}}else return t.prepare(a).run(),{columns:["Result"],rows:[{Result:"Success"}]}}async executeSql(a){(await this.getDb()).exec(a)}async close(){this.db&&(this.db.close(),this.db=null)}async insert(a,t){if(t.length===0)return;let r=await this.getDb(),o=Object.keys(t[0]),e=o.map(l=>this.quoteIdentifier(l)).join(", "),n=o.map(()=>"?").join(", "),c=`INSERT INTO ${this.quoteIdentifier(a)} (${e}) VALUES (${n})`,i=r.prepare(c);for(let l of t){let m=o.map(p=>l[p]);i.run(...m)}}}});import na from"pg";var xe,je=E(()=>{"use strict";xe=class{client;connected=!1;constructor(a){this.client=new na.Client({connectionString:a})}async connectIfNecessary(){this.connected||(await this.client.connect(),this.connected=!0)}quoteIdentifier(a){return`"${a.replace(/"/g,'""')}"`}async getTables(){return await this.connectIfNecessary(),(await this.client.query(`
13
13
  SELECT tablename
14
14
  FROM pg_catalog.pg_tables
15
15
  WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'
@@ -55,7 +55,7 @@ var Jt=Object.defineProperty;var E=(s,a)=>()=>(s&&(a=s(s=0)),a);var L=(s,a)=>{fo
55
55
  AND t.relname = $1
56
56
  ORDER BY
57
57
  i.relname, a.attnum;
58
- `,[a])).rows,e=new Map;for(let n of o){if(n.is_primary)continue;let c=n.index_name;e.has(c)||e.set(c,{name:c,columns:[],isUnique:n.is_unique}),e.get(c).columns.push(n.column_name)}return Array.from(e.values())}async getData(a,t=50,r=0,o,e){await this.connectIfNecessary();let c=(await this.getSchema(a)).map(m=>m.name),i=`SELECT * FROM ${this.quoteIdentifier(a)}`;o&&(i+=` WHERE ${o}`),e&&(i+=` ORDER BY ${this.quoteIdentifier(e.col)} ${e.asc?"ASC":"DESC"}`),i+=" LIMIT $1 OFFSET $2";let l=await this.client.query(i,[t,r]);return{columns:c,rows:l.rows}}async query(a){await this.connectIfNecessary();let t=await this.client.query(a),r=[];return t.fields&&(r=t.fields.map(o=>o.name)),{columns:r,rows:t.rows||[]}}async executeSql(a){await this.connectIfNecessary(),await this.client.query(a)}async close(){this.connected&&(await this.client.end(),this.connected=!1)}async insert(a,t){if(t.length===0)return;await this.connectIfNecessary();let r=Object.keys(t[0]),o=r.map(e=>this.quoteIdentifier(e)).join(", ");for(let e of t){let n=r.map((l,m)=>`$${m+1}`).join(", "),c=`INSERT INTO ${this.quoteIdentifier(a)} (${o}) VALUES (${n})`,i=r.map(l=>e[l]);await this.client.query(c,i)}}}});import sa from"mysql2/promise";var Te,Qe=E(()=>{"use strict";Te=class{connection;pool=null;constructor(a){this.connection=a}async getPool(){return this.pool||(this.pool=sa.createPool(this.connection)),this.pool}quoteIdentifier(a){return`\`${a.replace(/`/g,"``")}\``}async getTables(){let a=await this.getPool(),[t]=await a.query("SHOW TABLES;");return t.map(r=>Object.values(r)[0])}async getSchema(a){let t=await this.getPool(),[r]=await t.query(`SHOW COLUMNS FROM ${this.quoteIdentifier(a)}`),o=r,[e]=await t.query(`
58
+ `,[a])).rows,e=new Map;for(let n of o){if(n.is_primary)continue;let c=n.index_name;e.has(c)||e.set(c,{name:c,columns:[],isUnique:n.is_unique}),e.get(c).columns.push(n.column_name)}return Array.from(e.values())}async getData(a,t=50,r=0,o,e){await this.connectIfNecessary();let c=(await this.getSchema(a)).map(m=>m.name),i=`SELECT * FROM ${this.quoteIdentifier(a)}`;o&&(i+=` WHERE ${o}`),e&&(i+=` ORDER BY ${this.quoteIdentifier(e.col)} ${e.asc?"ASC":"DESC"}`),i+=" LIMIT $1 OFFSET $2";let l=await this.client.query(i,[t,r]);return{columns:c,rows:l.rows}}async query(a){await this.connectIfNecessary();let t=await this.client.query(a),r=[];return t.fields&&(r=t.fields.map(o=>o.name)),{columns:r,rows:t.rows||[]}}async executeSql(a){await this.connectIfNecessary(),await this.client.query(a)}async close(){this.connected&&(await this.client.end(),this.connected=!1)}async insert(a,t){if(t.length===0)return;await this.connectIfNecessary();let r=Object.keys(t[0]),o=r.map(e=>this.quoteIdentifier(e)).join(", ");for(let e of t){let n=r.map((l,m)=>`$${m+1}`).join(", "),c=`INSERT INTO ${this.quoteIdentifier(a)} (${o}) VALUES (${n})`,i=r.map(l=>e[l]);await this.client.query(c,i)}}}});import sa from"mysql2/promise";var Te,Qe=E(()=>{"use strict";Te=class{connection;pool=null;constructor(a){this.connection=a}async getPool(){return this.pool||(this.pool=sa.createPool(this.connection),this.pool.on("connection",a=>{a.query("SET SESSION sql_mode = 'ANSI_QUOTES'")})),this.pool}quoteIdentifier(a){return`\`${a.replace(/`/g,"``")}\``}async getTables(){let a=await this.getPool(),[t]=await a.query("SHOW TABLES;");return t.map(r=>Object.values(r)[0])}async getSchema(a){let t=await this.getPool(),[r]=await t.query(`SHOW COLUMNS FROM ${this.quoteIdentifier(a)}`),o=r,[e]=await t.query(`
59
59
  SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
60
60
  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
61
61
  WHERE TABLE_SCHEMA = DATABASE()
@@ -74,12 +74,12 @@ ${r.join(`,
74
74
  \u2554${d}\u2557`)),r){let f=m-2-r.length,y=Math.max(0,Math.floor(f/2)),b=Math.max(0,f-y),x=" ".repeat(y)+$.bold($.white(r))+" ".repeat(b);console.log($.cyan("\u2551")+x+$.cyan("\u2551")),console.log($.cyan(`\u2560${d}\u2563`))}if(s.length>0){let f=s.map(y=>$.bold($.white(u(y,n[y]).padEnd(n[y])))).join($.cyan(" \u2551 "));console.log($.cyan("\u2551 ")+f+$.cyan(" \u2551")),console.log($.cyan(`\u2560${d}\u2563`))}if(a.length===0){let f=m-4-o.length,y=Math.max(0,Math.floor(f/2)),b=Math.max(0,f-y);console.log($.cyan("\u2551 ")+" ".repeat(y)+$.yellow(o)+" ".repeat(b)+$.cyan(" \u2551"))}else for(let f of a){let y=s.map(b=>$.white(u(String(f[b]??""),n[b]).padEnd(n[b]))).join($.cyan(" \u2551 "));console.log($.cyan("\u2551 ")+y+$.cyan(" \u2551"))}console.log($.cyan(`\u255A${d}\u255D`))}var Ce=E(()=>{"use strict"});var at={};L(at,{runQueryCommand:()=>ga});import ce from"picocolors";async function ga(s,a){s.type==="unknown"&&(console.log(ce.red("Error: No database connection found. Cannot run query.")),process.exit(1));let t=h(s),r=a[0];if(!r){let{input:o}=await import("@inquirer/prompts");r=await o({message:"Enter your SQL query:"})}(!r||r.trim()==="")&&(console.log(ce.yellow("No query provided. Exiting.")),process.exit(0));try{let o=await t.query(r);o.columns.length===0&&(console.log(ce.yellow("Query executed successfully. (No output)")),process.exit(0)),ee(o.columns,o.rows,{title:"Query Result",maxColWidth:50}),console.log(ce.dim(`
75
75
  (${o.rows.length} rows)`)),await t.close(),process.exit(0)}catch(o){console.log(ce.red(`
76
76
  Query Error: ${o.message}
77
- `)),process.exit(1)}}var ot=E(()=>{"use strict";A();Ce()});var nt={};L(nt,{runExportCommand:()=>fa});import U from"picocolors";import me from"fs/promises";import ue from"path";async function fa(s,a,t){s.type==="unknown"&&(console.log(U.red("Error: No database connection found. Cannot run export.")),process.exit(1));let r=h(s),o=a[0],e=t.format,n=t["schema-only"],{select:c}=await import("@inquirer/prompts");if(!o){let m=await r.getTables();m.length===0&&(console.log(U.yellow("No tables found in the database.")),process.exit(0));let p=[{name:"All Tables (*)",value:"*"},...m.map(u=>({name:u,value:u}))];o=await c({message:"Which table do you want to export?",choices:p})}e||(e=await c({message:"Which format do you want to export?",choices:[{name:"CSV",value:"csv"},{name:"JSON",value:"json"}]}));let i=ue.join(process.cwd(),"drixio_exports");await me.mkdir(i,{recursive:!0});let l=o==="*"?await r.getTables():[o];console.log(U.cyan(`
78
- Starting export to ${i}...`));for(let m of l)try{if(n){let p=await r.getSchema(m);if(e==="json"){let u=ue.join(i,`${m}_schema.json`);await me.writeFile(u,JSON.stringify(p,null,2),"utf-8"),console.log(U.green(`\u2714 Exported Schema (JSON): ${m}`))}else{let u=ue.join(i,`${m}_schema.csv`),d=`Name,Type,IsPrimaryKey,Nullable
77
+ `)),process.exit(1)}}var ot=E(()=>{"use strict";A();Ce()});var nt={};L(nt,{runExportCommand:()=>fa});import F from"picocolors";import me from"fs/promises";import ue from"path";async function fa(s,a,t){s.type==="unknown"&&(console.log(F.red("Error: No database connection found. Cannot run export.")),process.exit(1));let r=h(s),o=a[0],e=t.format,n=t["schema-only"],{select:c}=await import("@inquirer/prompts");if(!o){let m=await r.getTables();m.length===0&&(console.log(F.yellow("No tables found in the database.")),process.exit(0));let p=[{name:"All Tables (*)",value:"*"},...m.map(u=>({name:u,value:u}))];o=await c({message:"Which table do you want to export?",choices:p})}e||(e=await c({message:"Which format do you want to export?",choices:[{name:"CSV",value:"csv"},{name:"JSON",value:"json"}]}));let i=ue.join(process.cwd(),"drixio_exports");await me.mkdir(i,{recursive:!0});let l=o==="*"?await r.getTables():[o];console.log(F.cyan(`
78
+ Starting export to ${i}...`));for(let m of l)try{if(n){let p=await r.getSchema(m);if(e==="json"){let u=ue.join(i,`${m}_schema.json`);await me.writeFile(u,JSON.stringify(p,null,2),"utf-8"),console.log(F.green(`\u2714 Exported Schema (JSON): ${m}`))}else{let u=ue.join(i,`${m}_schema.csv`),d=`Name,Type,IsPrimaryKey,Nullable
79
79
  `,f=p.map(y=>`"${y.name}","${y.type}","${y.isPk}","${y.nullable}"`).join(`
80
- `);await me.writeFile(u,d+f,"utf-8"),console.log(U.green(`\u2714 Exported Schema (CSV): ${m}`))}}else{let p=await r.getData(m,9999999,0);if(e==="json"){let u=ue.join(i,`${m}_data.json`);await me.writeFile(u,JSON.stringify(p.rows,null,2),"utf-8"),console.log(U.green(`\u2714 Exported Data (JSON): ${m} (${p.rows.length} rows)`))}else{let u=ue.join(i,`${m}_data.csv`),d="";if(p.columns.length>0){let f=p.columns.join(",")+`
80
+ `);await me.writeFile(u,d+f,"utf-8"),console.log(F.green(`\u2714 Exported Schema (CSV): ${m}`))}}else{let p=await r.getData(m,9999999,0);if(e==="json"){let u=ue.join(i,`${m}_data.json`);await me.writeFile(u,JSON.stringify(p.rows,null,2),"utf-8"),console.log(F.green(`\u2714 Exported Data (JSON): ${m} (${p.rows.length} rows)`))}else{let u=ue.join(i,`${m}_data.csv`),d="";if(p.columns.length>0){let f=p.columns.join(",")+`
81
81
  `,y=p.rows.map(b=>p.columns.map(x=>`"${String(b[x]??"").replace(/"/g,'""')}"`).join(",")).join(`
82
- `);d=f+y}await me.writeFile(u,d,"utf-8"),console.log(U.green(`\u2714 Exported Data (CSV): ${m} (${p.rows.length} rows)`))}}}catch(p){console.log(U.red(`\u2718 Failed to export table ${m}: ${p.message}`))}await r.close(),console.log(U.cyan("Export complete.")),process.exit(0)}var st=E(()=>{"use strict";A()});import{Hono as ya}from"hono";function rt(s,a){let t=new ya,r=h(a);t.get("/tables",async o=>{try{let e=await r.getTables();return o.json({success:!0,data:e})}catch(e){return o.json({success:!1,error:e.message},500)}}),t.get("/tables/stats",async o=>{try{let e=await r.getTables(),n={};for(let c of e)try{let i=await r.query(`SELECT COUNT(*) as c FROM ${r.quoteIdentifier(c)}`);if(i&&i.rows&&i.rows.length>0){let l=i.rows[0],m=Object.values(l)[0];n[c]=parseInt(String(m),10)||0}else n[c]=0}catch{n[c]=0}return o.json({success:!0,data:n})}catch(e){return o.json({success:!1,error:e.message},500)}}),t.get("/tables/:name/schema",async o=>{let e=o.req.param("name");try{let n=await r.getSchema(e);return o.json({success:!0,data:n})}catch(n){return o.json({success:!1,error:n.message},500)}}),t.get("/tables/:name/indexes",async o=>{let e=o.req.param("name");try{let n=await r.getIndexes(e);return o.json({success:!0,data:n})}catch(n){return o.json({success:!1,error:n.message},500)}}),t.get("/tables/:name/data",async o=>{let e=o.req.param("name"),n=parseInt(o.req.query("limit")||"50",10),c=parseInt(o.req.query("offset")||"0",10),i=o.req.query("where")||"",l=o.req.query("orderCol"),m=o.req.query("orderAsc"),p;l&&(p={col:l,asc:m!=="false"});try{let u=await r.getData(e,n,c,i,p);return o.json({success:!0,data:u})}catch(u){return o.json({success:!1,error:u.message},500)}}),t.post("/query",async o=>{try{let{sql:e}=await o.req.json(),n=await r.query(e);return o.json({success:!0,data:n})}catch(e){return o.json({success:!1,error:e.message},500)}}),s.route("/api",t)}var it=E(()=>{"use strict";A()});var ct={};L(ct,{runStudio:()=>xa});import{serve as ha}from"@hono/node-server";import{Hono as wa}from"hono";import{serveStatic as ba}from"@hono/node-server/serve-static";import Ea from"open";import pe from"path";import lt from"picocolors";import{fileURLToPath as Sa}from"url";async function xa(s){let a=new wa;rt(a,s);let r=qe.includes("src")||qe.includes("server")?pe.resolve(qe,"../../dist/studio"):pe.resolve(qe,"./studio"),o=await import("fs/promises");a.use("/*",ba({root:pe.relative(process.cwd(),r)})),a.get("*",async c=>{let i=pe.join(r,"index.html");try{let l=await o.readFile(i,"utf-8");return c.html(l)}catch{return c.text("Drixio Studio static files not found. Did you run build?",404)}});let e=process.env.PORT?parseInt(process.env.PORT,10):51213,n=await Ta(e);console.log(lt.cyan(`
82
+ `);d=f+y}await me.writeFile(u,d,"utf-8"),console.log(F.green(`\u2714 Exported Data (CSV): ${m} (${p.rows.length} rows)`))}}}catch(p){console.log(F.red(`\u2718 Failed to export table ${m}: ${p.message}`))}await r.close(),console.log(F.cyan("Export complete.")),process.exit(0)}var st=E(()=>{"use strict";A()});import{Hono as ya}from"hono";function rt(s,a){let t=new ya,r=h(a);t.get("/tables",async o=>{try{let e=await r.getTables();return o.json({success:!0,data:e})}catch(e){return o.json({success:!1,error:e.message},500)}}),t.get("/config",o=>o.json({success:!0,data:{dbType:a.type}})),t.get("/tables/stats",async o=>{try{let e=await r.getTables(),n={};for(let c of e)try{let i=await r.query(`SELECT COUNT(*) as c FROM ${r.quoteIdentifier(c)}`);if(i&&i.rows&&i.rows.length>0){let l=i.rows[0],m=Object.values(l)[0];n[c]=parseInt(String(m),10)||0}else n[c]=0}catch{n[c]=0}return o.json({success:!0,data:n})}catch(e){return o.json({success:!1,error:e.message},500)}}),t.get("/tables/:name/schema",async o=>{let e=o.req.param("name");try{let n=await r.getSchema(e);return o.json({success:!0,data:n})}catch(n){return o.json({success:!1,error:n.message},500)}}),t.get("/tables/:name/indexes",async o=>{let e=o.req.param("name");try{let n=await r.getIndexes(e);return o.json({success:!0,data:n})}catch(n){return o.json({success:!1,error:n.message},500)}}),t.get("/tables/:name/data",async o=>{let e=o.req.param("name"),n=parseInt(o.req.query("limit")||"50",10),c=parseInt(o.req.query("offset")||"0",10),i=o.req.query("where")||"",l=o.req.query("orderCol"),m=o.req.query("orderAsc"),p;l&&(p={col:l,asc:m!=="false"});try{let u=await r.getData(e,n,c,i,p);return o.json({success:!0,data:u})}catch(u){return o.json({success:!1,error:u.message},500)}}),t.post("/query",async o=>{try{let{sql:e}=await o.req.json(),n=await r.query(e);return o.json({success:!0,data:n})}catch(e){return o.json({success:!1,error:e.message},500)}}),s.route("/api",t)}var it=E(()=>{"use strict";A()});var ct={};L(ct,{runStudio:()=>xa});import{serve as ha}from"@hono/node-server";import{Hono as wa}from"hono";import{serveStatic as ba}from"@hono/node-server/serve-static";import Ea from"open";import pe from"path";import lt from"picocolors";import{fileURLToPath as Sa}from"url";async function xa(s){let a=new wa;rt(a,s);let r=qe.includes("src")||qe.includes("server")?pe.resolve(qe,"../../dist/studio"):pe.resolve(qe,"./studio"),o=await import("fs/promises");a.use("/*",ba({root:pe.relative(process.cwd(),r)})),a.get("*",async c=>{let i=pe.join(r,"index.html");try{let l=await o.readFile(i,"utf-8");return c.html(l)}catch{return c.text("Drixio Studio static files not found. Did you run build?",404)}});let e=process.env.PORT?parseInt(process.env.PORT,10):51213,n=await Ta(e);console.log(lt.cyan(`
83
83
  Starting Drixio Studio on http://localhost:${n}...`)),console.log(lt.dim(`Press Ctrl+C to stop the server.
84
84
  `)),ha({fetch:a.fetch,port:n}),await Ea(`http://localhost:${n}`)}async function Ta(s){let a=await import("net"),t=s;for(;;){if(await new Promise(o=>{let e=a.createServer();e.unref(),e.on("error",()=>o(!1)),e.listen(t,()=>{e.close(()=>o(!0))})}))return t;t++}}var $a,qe,mt=E(()=>{"use strict";it();$a=Sa(import.meta.url),qe=pe.dirname($a)});var ut={};L(ut,{runBackupCommand:()=>Da});import I from"picocolors";import Ie from"fs/promises";import ve from"path";async function Da(s){s.type==="unknown"&&(console.log(I.red("Error: No database connection found. Cannot run backup.")),process.exit(1));let a=new Date().toISOString().replace(/[:.]/g,"-"),t=ve.join(process.cwd(),`drixio_backup_${a}`);if(console.log(I.cyan(`
85
85
  Starting database backup...`)),console.log(I.dim(`Database: ${s.type}`)),console.log(I.dim(`Target: ${s.targetUrl}`)),console.log(I.dim(`Backup Directory: ${t}
@@ -109,7 +109,7 @@ ${r}
109
109
  `,e=Ia.resolve(process.cwd(),"drixio_schema.md");await Na.writeFile(e,o.trim(),"utf-8"),console.log(Q.green(`
110
110
  \u2714 Diagram generated successfully!`)),console.log(Q.white(`Output saved to: ${Q.bold(e)}`)),console.log(Q.dim("Tip: Open this file in VSCode with a Markdown viewer or paste it into Draw.io."))}catch(t){console.log(Q.red(`
111
111
  \u2718 Failed to generate diagram: ${t.message}`))}finally{await a.close()}process.exit(0)}var bt=E(()=>{"use strict";A()});var St={};L(St,{runExecCommand:()=>Ba});import oe from"picocolors";import Et from"fs/promises";import Pa from"path";async function Ba(s,a){s.type==="unknown"&&(console.log(oe.red("Error: No database connection found. Cannot run exec.")),process.exit(1));let t=a[0],{input:r}=await import("@inquirer/prompts");t||(t=await r({message:"Enter the path to your .sql file:"}));let o=Pa.resolve(process.cwd(),t);try{await Et.access(o)}catch{console.log(oe.red(`Error: File not found at ${o}`)),process.exit(1)}let e=await Et.readFile(o,"utf-8");e.trim()||(console.log(oe.yellow("File is empty.")),process.exit(0));let n=h(s);console.log(oe.cyan(`
112
- Executing SQL script from ${t}...`));try{await n.executeSql(e),console.log(oe.green("\u2714 Script executed successfully!"))}catch(c){console.log(oe.red(`\u2718 Execution failed: ${c.message}`))}finally{await n.close()}process.exit(0)}var $t=E(()=>{"use strict";A()});var xt={};L(xt,{runGenerateTypesCommand:()=>Fa});import Y from"picocolors";import Ma from"fs/promises";import _a from"path";function Oa(s){let a=s.toLowerCase();return a.includes("int")||a.includes("num")||a.includes("float")||a.includes("double")||a.includes("real")?"number":a.includes("bool")||a==="tinyint(1)"?"boolean":a.includes("char")||a.includes("text")||a.includes("uuid")||a.includes("string")?"string":a.includes("date")||a.includes("time")?"Date":a.includes("json")?"any":"string"}async function Fa(s){s.type==="unknown"&&(console.log(Y.red("Error: No database connection found. Cannot generate types.")),process.exit(1));let a=h(s);console.log(Y.cyan(`
112
+ Executing SQL script from ${t}...`));try{await n.executeSql(e),console.log(oe.green("\u2714 Script executed successfully!"))}catch(c){console.log(oe.red(`\u2718 Execution failed: ${c.message}`))}finally{await n.close()}process.exit(0)}var $t=E(()=>{"use strict";A()});var xt={};L(xt,{runGenerateTypesCommand:()=>Ua});import Y from"picocolors";import Ma from"fs/promises";import _a from"path";function Oa(s){let a=s.toLowerCase();return a.includes("int")||a.includes("num")||a.includes("float")||a.includes("double")||a.includes("real")?"number":a.includes("bool")||a==="tinyint(1)"?"boolean":a.includes("char")||a.includes("text")||a.includes("uuid")||a.includes("string")?"string":a.includes("date")||a.includes("time")?"Date":a.includes("json")?"any":"string"}async function Ua(s){s.type==="unknown"&&(console.log(Y.red("Error: No database connection found. Cannot generate types.")),process.exit(1));let a=h(s);console.log(Y.cyan(`
113
113
  Scanning database to generate TypeScript interfaces...`));try{let t=await a.getTables();t.length===0&&(console.log(Y.yellow("No tables found in the database.")),process.exit(0));let r=`// Generated by Drixio CLI
114
114
  // Database: ${s.type.toUpperCase()}
115
115
 
@@ -119,7 +119,7 @@ Scanning database to generate TypeScript interfaces...`));try{let t=await a.getT
119
119
 
120
120
  `}let o=_a.resolve(process.cwd(),"drixio-types.d.ts");await Ma.writeFile(o,r.trim()+`
121
121
  `,"utf-8"),console.log(Y.green("\u2714 TypeScript interfaces generated successfully!")),console.log(Y.white(`Output saved to: ${Y.bold(o)}`))}catch(t){console.log(Y.red(`
122
- \u2718 Failed to generate types: ${t.message}`))}finally{await a.close()}process.exit(0)}var Tt=E(()=>{"use strict";A()});var At={};L(At,{runInitCommand:()=>Ua});import S from"picocolors";import Re from"fs/promises";import Dt from"path";async function Ua(s){let{select:a,input:t,password:r}=await import("@inquirer/prompts"),o=s[0];(!o||!["sqlite","mysql","postgres"].includes(o.toLowerCase()))&&(o=await a({message:"Which database do you want to initialize locally?",choices:[{name:"SQLite (Local File)",value:"sqlite"},{name:"MySQL (Local Server)",value:"mysql"},{name:"PostgreSQL (Local Server)",value:"postgres"}]})),o=o.toLowerCase(),console.log(S.cyan(`
122
+ \u2718 Failed to generate types: ${t.message}`))}finally{await a.close()}process.exit(0)}var Tt=E(()=>{"use strict";A()});var At={};L(At,{runInitCommand:()=>Fa});import S from"picocolors";import Re from"fs/promises";import Dt from"path";async function Fa(s){let{select:a,input:t,password:r}=await import("@inquirer/prompts"),o=s[0];(!o||!["sqlite","mysql","postgres"].includes(o.toLowerCase()))&&(o=await a({message:"Which database do you want to initialize locally?",choices:[{name:"SQLite (Local File)",value:"sqlite"},{name:"MySQL (Local Server)",value:"mysql"},{name:"PostgreSQL (Local Server)",value:"postgres"}]})),o=o.toLowerCase(),console.log(S.cyan(`
123
123
  Initializing a local ${o} database...`));let e="";if(o==="sqlite"){let i=s[1]||"database.sqlite";!i.endsWith(".sqlite")&&!i.endsWith(".db")&&(i+=".sqlite");let l=Dt.resolve(process.cwd(),i);try{await Re.access(l),console.log(S.yellow(`File ${i} already exists.`))}catch{await Re.writeFile(l,""),console.log(S.green(`\u2714 Created local database file: ${i}`))}e=`file:${i}`}else{console.log(S.dim("Please provide credentials for your local server (e.g. running via XAMPP, Homebrew, etc.)"));let i=await t({message:"Server Host:",default:"localhost"}),l=await t({message:"Server Port:",default:o==="mysql"?"3306":"5432"}),m=await t({message:"Username:",default:o==="mysql"?"root":"postgres"}),p=await r({message:"Password (leave empty if none):"}),u=s[1];u||(u=await t({message:"New Database Name (e.g. my_project):"})),(!u||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u))&&(console.log(S.red("Invalid database name. Please use only letters, numbers, and underscores.")),process.exit(1)),console.log(S.cyan(`
124
124
  Connecting to local server to create database '${u}'...`));try{if(o==="mysql"){let b=await(await import("mysql2/promise")).createConnection({host:i,port:parseInt(l),user:m,password:p});await b.query(`CREATE DATABASE IF NOT EXISTS \`${u}\``),await b.end()}else if(o==="postgres"){let y=await import("pg"),b=new y.Client({host:i,port:parseInt(l),user:m,password:p,database:"postgres"});await b.connect(),(await b.query("SELECT 1 FROM pg_database WHERE datname = $1",[u])).rowCount===0&&await b.query(`CREATE DATABASE "${u}"`),await b.end()}console.log(S.green(`\u2714 Created local database: ${u}`))}catch(y){console.log(S.red(`\u2718 Failed to create database on server: ${y.message}`)),console.log(S.dim(`
125
125
  Could not connect to the local ${o} server on ${i}:${l}.`)),(y.code==="ECONNREFUSED"||y.message.includes("ECONNREFUSED")||y.message.includes("connect"))&&(console.log(S.yellow(`
@@ -144,10 +144,10 @@ x Failed to read file: ${e.message}`));return}let o=r;if(t.toLowerCase().endsWit
144
144
  \u2713 SQL executed successfully!`))}finally{await e.close()}}else console.log(K.yellow(`
145
145
  \u26A0\uFE0F No SQL found in the file. Aborted.`))}else console.log(K.yellow(`
146
146
  No file path entered. Aborted.`))}catch(a){console.log(K.red(`
147
- Error executing SQL: ${a.message}`))}}var _t=E(()=>{"use strict";A()});import{select as ye,confirm as Ot,input as Xa}from"@inquirer/prompts";import C from"picocolors";async function Ft(s){let a=h(s);try{let t=await a.getTables();if(t.length===0){console.log(C.yellow("No tables found in the database."));return}let r=await ye({message:"Select a table to drop:",choices:t.map(e=>({name:e,value:e}))});if(await Ot({message:`Are you sure you want to DROP TABLE '${r}'? This will delete all its data!`,default:!1})){let e=`DROP TABLE ${r}`;s.type==="sqlite"||s.type==="postgres"?e=`DROP TABLE "${r}"`:s.type==="mysql"&&(e=`DROP TABLE \`${r}\``),await a.executeSql(e),console.log(C.green(`\u2713 Table '${r}' dropped successfully.`))}}catch(t){console.log(C.red(`Error: ${t.message}`))}finally{await a.close()}}async function he(s,a){let t=h(s),r=j(s.type);try{let o=await t.getTables();if(o.length===0){console.log(C.yellow("No tables found in the database."));return}let e=await ye({message:"Select a table to modify:",choices:o.map(c=>({name:c,value:c}))}),n=await t.getSchema(e);if(a==="add"){let c=n.some(m=>m.isPk),i=n.map(m=>m.name),{col:l}=await fe(t,c,i);if(l){let m=r.buildCreateTable("tmp",[l]).split(`
147
+ Error executing SQL: ${a.message}`))}}var _t=E(()=>{"use strict";A()});import{select as ye,confirm as Ot,input as Xa}from"@inquirer/prompts";import C from"picocolors";async function Ut(s){let a=h(s);try{let t=await a.getTables();if(t.length===0){console.log(C.yellow("No tables found in the database."));return}let r=await ye({message:"Select a table to drop:",choices:t.map(e=>({name:e,value:e}))});if(await Ot({message:`Are you sure you want to DROP TABLE '${r}'? This will delete all its data!`,default:!1})){let e=`DROP TABLE ${r}`;s.type==="sqlite"||s.type==="postgres"?e=`DROP TABLE "${r}"`:s.type==="mysql"&&(e=`DROP TABLE \`${r}\``),await a.executeSql(e),console.log(C.green(`\u2713 Table '${r}' dropped successfully.`))}}catch(t){console.log(C.red(`Error: ${t.message}`))}finally{await a.close()}}async function he(s,a){let t=h(s),r=j(s.type);try{let o=await t.getTables();if(o.length===0){console.log(C.yellow("No tables found in the database."));return}let e=await ye({message:"Select a table to modify:",choices:o.map(c=>({name:c,value:c}))}),n=await t.getSchema(e);if(a==="add"){let c=n.some(m=>m.isPk),i=n.map(m=>m.name),{col:l}=await fe(t,c,i);if(l){let m=r.buildCreateTable("tmp",[l]).split(`
148
148
  `)[1].trim().replace(/,$/,""),p=`ALTER TABLE ${e} ADD COLUMN ${m}`;s.type==="sqlite"||s.type==="postgres"?p=`ALTER TABLE "${e}" ADD COLUMN ${m}`:s.type==="mysql"&&(p=`ALTER TABLE \`${e}\` ADD COLUMN ${m}`),await t.executeSql(p),console.log(C.green(`\u2713 Column '${l.name}' added successfully.`))}}else if(a==="rename"){if(n.length===0)return console.log(C.yellow("Table has no columns."));let c=await ye({message:"Select a column to rename:",choices:n.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))}),i=await Xa({message:`New name for '${c}':`});if(i&&i!==c){let l=`ALTER TABLE ${e} RENAME COLUMN ${c} TO ${i}`;s.type==="sqlite"||s.type==="postgres"?l=`ALTER TABLE "${e}" RENAME COLUMN "${c}" TO "${i}"`:s.type==="mysql"&&(l=`ALTER TABLE \`${e}\` RENAME COLUMN \`${c}\` TO \`${i}\``),await t.executeSql(l),console.log(C.green(`\u2713 Column renamed to '${i}' successfully.`))}}else if(a==="modify"){if(n.length===0)return console.log(C.yellow("Table has no columns."));if(s.type==="sqlite"){console.log(C.yellow("SQLite does not support altering column types directly. Please recreate the table."));return}let c=await ye({message:"Select a column to modify:",choices:n.map(p=>({name:`${p.name} (${p.type})`,value:p.name}))}),i=n.some(p=>p.isPk&&p.name!==c),l=n.map(p=>p.name).filter(p=>p!==c),{col:m}=await fe(t,i,l,c);if(m){let p=r.buildCreateTable("tmp",[m]).split(`
149
- `)[1].trim().replace(/,$/,""),u="";s.type==="postgres"?(console.log(C.yellow("Note: Complex constraint modifications might require raw SQL in Postgres.")),u=`ALTER TABLE "${e}" ALTER COLUMN ${p.replace(m.name,`"${m.name}" TYPE`)}`):s.type==="mysql"&&(u=`ALTER TABLE \`${e}\` MODIFY COLUMN ${p}`);try{await t.executeSql(u),console.log(C.green(`\u2713 Column '${c}' modified successfully.`))}catch(d){console.log(C.red("x Could not modify column automatically. Try using Raw SQL.")),console.log(C.dim(d.message))}}}else if(a==="delete"){if(n.length===0)return console.log(C.yellow("Table has no columns."));let c=await ye({message:"Select a column to delete:",choices:n.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))});if(await Ot({message:`Are you sure you want to delete column '${c}'? Data will be lost!`,default:!1})){let l=`ALTER TABLE ${e} DROP COLUMN ${c}`;s.type==="sqlite"||s.type==="postgres"?l=`ALTER TABLE "${e}" DROP COLUMN "${c}"`:s.type==="mysql"&&(l=`ALTER TABLE \`${e}\` DROP COLUMN \`${c}\``);try{await t.executeSql(l),console.log(C.green(`\u2713 Column '${c}' deleted successfully.`))}catch(m){console.log(C.red(`x Error deleting column: ${m.message}`))}}}}catch(o){console.log(C.red(`Error: ${o.message}`))}finally{await t.close()}}var Ut=E(()=>{"use strict";A();Ae();Pe()});var jt={};L(jt,{runTableManagerFlow:()=>eo});import W from"picocolors";import{select as Wt,Separator as Za}from"@inquirer/prompts";async function eo(s){if(s.type==="unknown"){console.log(W.yellow(`
150
- No database connection found. Please setup first.`)),await Be();return}let a=await Promise.resolve().then(()=>(A(),Ve)).then(r=>r.createDBAdapter(s)),t=!0;for(;t;){console.clear();let r="Scanning...";try{r=`${(await a.getTables()).length} tables detected`}catch(n){r=W.red(n.message)}let o=s.targetUrl;switch(se(` Table Builder & Manager \u2022 [${s.type.toUpperCase()}]`,[{label:"Database",value:s.type.toUpperCase()},{label:"Target",value:o.length>45?"..."+o.slice(-42):o},{label:"Tables",value:r}]),await Rt()){case"create":let n=await Wt({message:"How do you want to create the table?",theme:{prefix:W.cyan("\u2713 "),icon:{cursor:W.cyan("\u203A ")},style:{message:c=>W.bold(W.white(c)),highlight:c=>{let i=c.replace(/\x1b\[[0-9;]*m/g,"");return i.includes("Cancel")?W.red(i):W.cyan(i)}}},choices:[{name:" Interactive Wizard (Beginner Friendly)",value:"wizard",description:"Follow the step-by-step guide to build your table."},{name:" Raw SQL (Experts)",value:"sql",description:"Write / Import your own CREATE TABLE statement."},new Za,{name:W.dim(" Cancel"),value:"cancel",description:"Back to Table Manager"}]});n==="wizard"?await Pt(s):n==="sql"&&await Mt(s);break;case"modify":await to(s);break;case"drop":await Ft(s),await Be();break;case"back":t=!1;break}}await a.close()}async function to(s){let a=await Wt({message:"Modify Table Actions:",choices:[{name:"Add Column",value:"add_col"},{name:"Rename Column",value:"rename_col"},{name:"Modify Column Settings (MySQL/Postgres)",value:"mod_col",disabled:s.type==="sqlite"},{name:"Delete Column",value:"del_col"},{name:" Back",value:"back"}]});if(a!=="back"){switch(a){case"add_col":await he(s,"add");break;case"rename_col":await he(s,"rename");break;case"mod_col":await he(s,"modify");break;case"del_col":await he(s,"delete");break}await Be()}}async function Be(){let{input:s}=await import("@inquirer/prompts");await s({message:"Press Enter to continue..."})}var Qt=E(()=>{"use strict";Lt();Bt();_t();Ut();Se()});Se();import D from"picocolors";import re from"fs/promises";import X from"path";async function q(s){let a=process.cwd();if(s){let e="sqlite";return s.startsWith("postgres://")||s.startsWith("postgresql://")?e="postgres":s.startsWith("mysql://")?e="mysql":e="sqlite",{type:e,targetUrl:s.replace("file:",""),source:"manual"}}let t=[".","prisma","db","database","src/db","src/database"];for(let e of t)try{let n=X.join(a,e),i=(await re.readdir(n)).find(l=>l.endsWith(".db")||l.endsWith(".sqlite")||l.endsWith(".sqlite3"));if(i)return{type:"sqlite",targetUrl:X.join(n,i),source:"auto-detected"}}catch{}let r=X.join(a,"prisma","schema.prisma");try{let e=await re.readFile(r,"utf-8"),n=e.match(/provider\s*=\s*["']([^"']+)["']/),c=e.match(/url\s*=\s*(?:env\(["']([^"']+)["']\)|["']([^"']+)["'])/);if(n){let i=n[1];i==="postgresql"&&(i="postgres");let l="";if(c&&c[2]&&(l=c[2],l.startsWith("file:")&&(l=X.join(a,"prisma",l.replace("file:","")))),l&&(i==="sqlite"||i==="postgres"||i==="mysql"))return{type:i,targetUrl:l,source:".env"}}}catch{}let o=X.join(a,".env");try{let e=await re.readFile(o,"utf-8"),n=["DATABASE_URL","DB_URL","POSTGRES_URL","POSTGRES_PRISMA_URL","MYSQL_URL"];for(let c of n){let i=new RegExp(`${c}\\s*=\\s*["']?([^"'\\r\\n]+)["']?`),l=e.match(i);if(l){let m=l[1];if(m.startsWith("file:")||m.endsWith(".db")||m.includes(".sqlite"))return{type:"sqlite",targetUrl:m.replace("file:",""),source:".env"};if(m.startsWith("postgres://")||m.startsWith("postgresql://"))return{type:"postgres",targetUrl:m,source:".env"};if(m.startsWith("mysql://"))return{type:"mysql",targetUrl:m,source:".env"}}}}catch{}return{type:"unknown",targetUrl:"",source:"manual"}}async function Ue(s){let a=X.join(process.cwd(),".env"),t="";try{t=await re.readFile(a,"utf-8")}catch{}let r=/DATABASE_URL\s*=\s*["']?([^"'\r\n]+)["']?/;r.test(t)?t=t.replace(r,`DATABASE_URL="${s}"`):(t&&!t.endsWith(`
149
+ `)[1].trim().replace(/,$/,""),u="";s.type==="postgres"?(console.log(C.yellow("Note: Complex constraint modifications might require raw SQL in Postgres.")),u=`ALTER TABLE "${e}" ALTER COLUMN ${p.replace(m.name,`"${m.name}" TYPE`)}`):s.type==="mysql"&&(u=`ALTER TABLE \`${e}\` MODIFY COLUMN ${p}`);try{await t.executeSql(u),console.log(C.green(`\u2713 Column '${c}' modified successfully.`))}catch(d){console.log(C.red("x Could not modify column automatically. Try using Raw SQL.")),console.log(C.dim(d.message))}}}else if(a==="delete"){if(n.length===0)return console.log(C.yellow("Table has no columns."));let c=await ye({message:"Select a column to delete:",choices:n.map(l=>({name:`${l.name} (${l.type})`,value:l.name}))});if(await Ot({message:`Are you sure you want to delete column '${c}'? Data will be lost!`,default:!1})){let l=`ALTER TABLE ${e} DROP COLUMN ${c}`;s.type==="sqlite"||s.type==="postgres"?l=`ALTER TABLE "${e}" DROP COLUMN "${c}"`:s.type==="mysql"&&(l=`ALTER TABLE \`${e}\` DROP COLUMN \`${c}\``);try{await t.executeSql(l),console.log(C.green(`\u2713 Column '${c}' deleted successfully.`))}catch(m){console.log(C.red(`x Error deleting column: ${m.message}`))}}}}catch(o){console.log(C.red(`Error: ${o.message}`))}finally{await t.close()}}var Ft=E(()=>{"use strict";A();Ae();Pe()});var jt={};L(jt,{runTableManagerFlow:()=>eo});import W from"picocolors";import{select as Wt,Separator as Za}from"@inquirer/prompts";async function eo(s){if(s.type==="unknown"){console.log(W.yellow(`
150
+ No database connection found. Please setup first.`)),await Be();return}let a=await Promise.resolve().then(()=>(A(),Ve)).then(r=>r.createDBAdapter(s)),t=!0;for(;t;){console.clear();let r="Scanning...";try{r=`${(await a.getTables()).length} tables detected`}catch(n){r=W.red(n.message)}let o=s.targetUrl;switch(se(` Table Builder & Manager \u2022 [${s.type.toUpperCase()}]`,[{label:"Database",value:s.type.toUpperCase()},{label:"Target",value:o.length>45?"..."+o.slice(-42):o},{label:"Tables",value:r}]),await Rt()){case"create":let n=await Wt({message:"How do you want to create the table?",theme:{prefix:W.cyan("\u2713 "),icon:{cursor:W.cyan("\u203A ")},style:{message:c=>W.bold(W.white(c)),highlight:c=>{let i=c.replace(/\x1b\[[0-9;]*m/g,"");return i.includes("Cancel")?W.red(i):W.cyan(i)}}},choices:[{name:" Interactive Wizard (Beginner Friendly)",value:"wizard",description:"Follow the step-by-step guide to build your table."},{name:" Raw SQL (Experts)",value:"sql",description:"Write / Import your own CREATE TABLE statement."},new Za,{name:W.dim(" Cancel"),value:"cancel",description:"Back to Table Manager"}]});n==="wizard"?await Pt(s):n==="sql"&&await Mt(s);break;case"modify":await to(s);break;case"drop":await Ut(s),await Be();break;case"back":t=!1;break}}await a.close()}async function to(s){let a=await Wt({message:"Modify Table Actions:",choices:[{name:"Add Column",value:"add_col"},{name:"Rename Column",value:"rename_col"},{name:"Modify Column Settings (MySQL/Postgres)",value:"mod_col",disabled:s.type==="sqlite"},{name:"Delete Column",value:"del_col"},{name:" Back",value:"back"}]});if(a!=="back"){switch(a){case"add_col":await he(s,"add");break;case"rename_col":await he(s,"rename");break;case"mod_col":await he(s,"modify");break;case"del_col":await he(s,"delete");break}await Be()}}async function Be(){let{input:s}=await import("@inquirer/prompts");await s({message:"Press Enter to continue..."})}var Qt=E(()=>{"use strict";Lt();Bt();_t();Ft();Se()});Se();import D from"picocolors";import re from"fs/promises";import X from"path";async function q(s){let a=process.cwd();if(s){let e="sqlite";return s.startsWith("postgres://")||s.startsWith("postgresql://")?e="postgres":s.startsWith("mysql://")?e="mysql":e="sqlite",{type:e,targetUrl:s.replace("file:",""),source:"manual"}}let t=[".","prisma","db","database","src/db","src/database"];for(let e of t)try{let n=X.join(a,e),i=(await re.readdir(n)).find(l=>l.endsWith(".db")||l.endsWith(".sqlite")||l.endsWith(".sqlite3"));if(i)return{type:"sqlite",targetUrl:X.join(n,i),source:"auto-detected"}}catch{}let r=X.join(a,"prisma","schema.prisma");try{let e=await re.readFile(r,"utf-8"),n=e.match(/provider\s*=\s*["']([^"']+)["']/),c=e.match(/url\s*=\s*(?:env\(["']([^"']+)["']\)|["']([^"']+)["'])/);if(n){let i=n[1];i==="postgresql"&&(i="postgres");let l="";if(c&&c[2]&&(l=c[2],l.startsWith("file:")&&(l=X.join(a,"prisma",l.replace("file:","")))),l&&(i==="sqlite"||i==="postgres"||i==="mysql"))return{type:i,targetUrl:l,source:".env"}}}catch{}let o=X.join(a,".env");try{let e=await re.readFile(o,"utf-8"),n=["DATABASE_URL","DB_URL","POSTGRES_URL","POSTGRES_PRISMA_URL","MYSQL_URL"];for(let c of n){let i=new RegExp(`${c}\\s*=\\s*["']?([^"'\\r\\n]+)["']?`),l=e.match(i);if(l){let m=l[1];if(m.startsWith("file:")||m.endsWith(".db")||m.includes(".sqlite"))return{type:"sqlite",targetUrl:m.replace("file:",""),source:".env"};if(m.startsWith("postgres://")||m.startsWith("postgresql://"))return{type:"postgres",targetUrl:m,source:".env"};if(m.startsWith("mysql://"))return{type:"mysql",targetUrl:m,source:".env"}}}}catch{}return{type:"unknown",targetUrl:"",source:"manual"}}async function Fe(s){let a=X.join(process.cwd(),".env"),t="";try{t=await re.readFile(a,"utf-8")}catch{}let r=/DATABASE_URL\s*=\s*["']?([^"'\r\n]+)["']?/;r.test(t)?t=t.replace(r,`DATABASE_URL="${s}"`):(t&&!t.endsWith(`
151
151
  `)&&(t+=`
152
152
  `),t+=`DATABASE_URL="${s}"
153
153
  `),await re.writeFile(a,t,"utf-8")}A();import{select as Je,Separator as le}from"@inquirer/prompts";import T from"picocolors";import{select as ra}from"@inquirer/prompts";import Z from"picocolors";var Ke=async s=>await ra({message:"Select a table to edit data:",theme:{prefix:Z.cyan("\u2713 "),icon:{cursor:Z.cyan("\u203A ")},style:{message:a=>Z.bold(Z.white(a)),highlight:a=>{let t=a.replace(/\x1b\[[0-9;]*m/g,"");return t.includes(" Back")?Z.red(t):Z.cyan(t)}}},choices:s});Ae();import{input as ie,select as ia}from"@inquirer/prompts";import w from"picocolors";import la from"fs/promises";import ca from"path";async function He(s,a,t,r){let o=j(a);console.log(w.cyan(`
@@ -168,17 +168,17 @@ x Error executing SQL: ${e.message}`))}}else console.log(w.yellow(`
168
168
  No file path entered. Aborted.`))}catch(a){console.log(w.red(`
169
169
  Error: ${a.message}`))}}Ce();Se();async function Xe(s){let a=h(s),t=!0;for(;t;){console.clear();let r=[],o=0,e="Scanning...";try{r=await a.getTables();for(let i of r)try{let l=s.type==="mysql"?"`":'"',m=await a.query(`SELECT COUNT(*) as count FROM ${l}${i}${l}`);m.rows.length>0&&m.rows[0].count!=null&&(o+=Number(m.rows[0].count))}catch{}e=`${o.toLocaleString()} rows across ${r.length} tables`}catch(i){e=T.red(i.message)}let n=s.targetUrl,c=s.source===".env"?"Loaded from project .env file":s.source==="auto-detected"?"Auto-detected local SQLite file":"Manual connection config";se(` Data Browser & Editor \u2022 [${s.type.toUpperCase()}]`,[{label:"Database",value:s.type.toUpperCase()},{label:"Target",value:n.length>45?"..."+n.slice(-42):n},{label:"Source",value:c},{label:"Total Data",value:e}]);try{if(r.length===0){console.log(T.yellow("No tables found in this database.")),await te(),await a.close();return}let i=[...r.map(f=>({name:f,value:f})),new le,{name:T.dim(" Back"),value:"BACK"}],l=await Ke(i);if(l==="BACK"){t=!1;continue}let m=!0,p=1,u="",d=50;for(;m;){console.clear();let f=(p-1)*d,y=await a.getSchema(l),b=y.map(P=>P.name),x;try{x=await a.getData(l,d,f,u)}catch(P){console.log(T.red(`
170
170
  Error fetching data: ${P.message}
171
- `)),u="";let{input:R}=await import("@inquirer/prompts");await R({message:"Click Enter to continue..."});continue}let k=x.rows,Kt=` ${l} (Page ${p}) `;ee(b,k,{title:Kt,maxColWidth:30});let Ht=k.length===d,Yt=p>1,we=[{name:"Add Data",value:"add"},{name:"Edit Data",value:"edit"},{name:"Delete Data",value:"delete"},new le,{name:"Search Data",value:"search"},{name:u?"Clear Search":T.dim("Clear Search (disabled)"),value:u?"clear_search":"noop"},new le,{name:"Export to CSV",value:"exportCsv"},{name:"Export to JSON",value:"exportJson"},new le];Yt&&we.push({name:"Previous Page",value:"prev"}),Ht&&we.push({name:"Next Page",value:"next"}),we.push({name:T.dim(" Back"),value:"BACK"});let v=await Je({message:"Select an action for this table:",theme:{prefix:T.cyan("\u2713 "),icon:{cursor:T.cyan("\u203A ")},style:{message:P=>T.bold(T.white(P)),highlight:P=>{let R=P.replace(/\x1b\[[0-9;]*m/g,"");return R.includes(" Back")?T.red(R):T.cyan(R)}}},choices:we});if(v==="prev"){p--;continue}if(v==="next"){p++;continue}if(v==="noop")continue;if(v==="BACK"){m=!1;continue}if(v==="clear_search"){u="",p=1;continue}if(v==="search"){let{input:P}=await import("@inquirer/prompts"),O=(await P({message:"Enter Search (e.g. `age > 18` or `John` for fuzzy search):"})).trim();if(O){if(/[=<>]|LIKE|IN|AND|OR/i.test(O))u=O;else{let z=y.filter(F=>F.type.toLowerCase().includes("char")||F.type.toLowerCase().includes("text"));if(z.length>0){let F=s.type==="postgres"?"ILIKE":"LIKE";u=z.map(Ee=>`"${Ee.name}" ${F} '%${O.replace(/'/g,"''")}%'`).join(" OR ")}else u=`"${y[0].name}" = '${O}'`}p=1}continue}if(v==="exportCsv"||v==="exportJson"){try{console.log(T.yellow(`
172
- Exporting data...`));let R=await a.getData(l,9999999,0,u),O=await import("fs/promises"),be=await import("path"),z=be.join(process.cwd(),"drixio_exports");if(await O.mkdir(z,{recursive:!0}),v==="exportCsv"){let F=R.columns.join(",")+`
171
+ `)),u="";let{input:R}=await import("@inquirer/prompts");await R({message:"Click Enter to continue..."});continue}let k=x.rows,Kt=` ${l} (Page ${p}) `;ee(b,k,{title:Kt,maxColWidth:30});let Ht=k.length===d,Yt=p>1,we=[{name:"Add Data",value:"add"},{name:"Edit Data",value:"edit"},{name:"Delete Data",value:"delete"},new le,{name:"Search Data",value:"search"},{name:u?"Clear Search":T.dim("Clear Search (disabled)"),value:u?"clear_search":"noop"},new le,{name:"Export to CSV",value:"exportCsv"},{name:"Export to JSON",value:"exportJson"},new le];Yt&&we.push({name:"Previous Page",value:"prev"}),Ht&&we.push({name:"Next Page",value:"next"}),we.push({name:T.dim(" Back"),value:"BACK"});let v=await Je({message:"Select an action for this table:",theme:{prefix:T.cyan("\u2713 "),icon:{cursor:T.cyan("\u203A ")},style:{message:P=>T.bold(T.white(P)),highlight:P=>{let R=P.replace(/\x1b\[[0-9;]*m/g,"");return R.includes(" Back")?T.red(R):T.cyan(R)}}},choices:we});if(v==="prev"){p--;continue}if(v==="next"){p++;continue}if(v==="noop")continue;if(v==="BACK"){m=!1;continue}if(v==="clear_search"){u="",p=1;continue}if(v==="search"){let{input:P}=await import("@inquirer/prompts"),O=(await P({message:"Enter Search (e.g. `age > 18` or `John` for fuzzy search):"})).trim();if(O){if(/[=<>]|LIKE|IN|AND|OR/i.test(O))u=O;else{let z=y.filter(U=>U.type.toLowerCase().includes("char")||U.type.toLowerCase().includes("text"));if(z.length>0){let U=s.type==="postgres"?"ILIKE":"LIKE";u=z.map(Ee=>`"${Ee.name}" ${U} '%${O.replace(/'/g,"''")}%'`).join(" OR ")}else u=`"${y[0].name}" = '${O}'`}p=1}continue}if(v==="exportCsv"||v==="exportJson"){try{console.log(T.yellow(`
172
+ Exporting data...`));let R=await a.getData(l,9999999,0,u),O=await import("fs/promises"),be=await import("path"),z=be.join(process.cwd(),"drixio_exports");if(await O.mkdir(z,{recursive:!0}),v==="exportCsv"){let U=R.columns.join(",")+`
173
173
  `,_e=R.rows.map(Gt=>R.columns.map(zt=>`"${String(Gt[zt]??"").replace(/"/g,'""')}"`).join(",")).join(`
174
- `),Ee=be.join(z,`${l}.csv`);await O.writeFile(Ee,F+_e,"utf-8"),console.log(T.green(`
175
- Exported to ${Ee}`))}else{let F=be.join(z,`${l}.json`);await O.writeFile(F,JSON.stringify(R.rows,null,2),"utf-8"),console.log(T.green(`
176
- Exported to ${F}`))}}catch(R){console.log(T.red(`
174
+ `),Ee=be.join(z,`${l}.csv`);await O.writeFile(Ee,U+_e,"utf-8"),console.log(T.green(`
175
+ Exported to ${Ee}`))}else{let U=be.join(z,`${l}.json`);await O.writeFile(U,JSON.stringify(R.rows,null,2),"utf-8"),console.log(T.green(`
176
+ Exported to ${U}`))}}catch(R){console.log(T.red(`
177
177
  Export Error: ${R.message}`))}let{input:P}=await import("@inquirer/prompts");await P({message:"Click Enter to continue..."});continue}let Me=await Je({message:`Select mode for ${v} data:`,choices:[{name:"Beginner (Interactive Step-by-Step)",value:"beginner"},{name:"Expert (Load SQL from .sql or .md file)",value:"expert"},new le,{name:T.dim("Cancel"),value:"cancel"}]});if(Me!=="cancel"){if(Me==="expert"){await ze(a),await te();continue}v==="add"?(await He(a,s.type,l,y),await te()):v==="edit"?(await Ye(a,s.type,l,y),await te()):v==="delete"&&(await Ge(a,s.type,l,y),await te())}}}catch(i){console.log(T.red(`
178
178
  x Error: ${i.message}`)),await te(),t=!1}}await a.close()}async function te(){let{input:s}=await import("@inquirer/prompts");await s({message:"Press Enter to continue..."})}import{select as ma,input as ua}from"@inquirer/prompts";import ae from"picocolors";A();async function Ze(s){let a=await ma({message:"What method you want to use to setup database connection?",choices:[{name:" Auto-Config",value:"auto",description:"Automatically detect and setup database connection (May fail for some cases)."},{name:" Manual Config",value:"manual",description:"Manually setup database connection by entering parameters step by step."}]}),t=s;switch(a){case"auto":let r=await q();r.type!=="unknown"?(t=r,console.log(ae.green(`
179
179
  Database connection setup successfully.`))):console.log(ae.red(`
180
180
  Failed to auto-detect database connection. Please try manual configuration.`));break;case"manual":let o=await ua({message:"Enter the database connection URL: "});if(o){let e=await q(o);console.log(ae.dim(`
181
- Testing connection...`));try{let n=h(e);await n.getTables(),await n.close(),t=e,await Ue(o),console.log(ae.green("\u2713 Database connection setup successfully and saved to .env!"))}catch(n){console.log(ae.red(`
181
+ Testing connection...`));try{let n=h(e);await n.getTables(),await n.close(),t=e,await Fe(o),console.log(ae.green("\u2713 Database connection setup successfully and saved to .env!"))}catch(n){console.log(ae.red(`
182
182
  x Connection failed: ${n.message}
183
183
  Please enter a valid database URL or check your database status.`))}}else console.log(ae.red(`
184
184
  Failed to detect database connection. Please enter valid database URL.`));break}return t}import{select as pa,Separator as da}from"@inquirer/prompts";import H from"picocolors";var et=async s=>await pa({message:"Select an action:",theme:{prefix:H.cyan("\u2713 "),icon:{cursor:H.cyan("\u203A ")},style:{message:a=>H.bold(H.white(a)),highlight:a=>{let t=a.replace(/\x1b\[[0-9;]*m/g,"");return t.includes("Exit")?H.red(t):H.cyan(t)}}},choices:[{name:" Data Browser & Editor",value:"editor",description:"View, insert, update, and delete row data in your tables.",disabled:s.type==="unknown"},{name:" Run Raw SQL (REPL)",value:"repl",description:"Execute arbitrary SQL queries interactively.",disabled:s.type==="unknown"},{name:" Table Builder & Manager",value:"table",description:"Create new tables, or modify/drop existing tables.",disabled:s.type==="unknown"},new da,{name:s.type==="unknown"?" Setup Connection":" Connection Settings",value:s.type==="unknown"?"setup":"re-configure",description:s.type==="unknown"?"Setup the database connection manually.":"Re-configure the database connection."},{name:H.dim(" Exit"),value:"exit",description:"Exit the Drixio CLI application."}]});A();Ce();import B from"picocolors";async function tt(s){if(s.type==="unknown")return;let a=h(s),t=!0,{input:r}=await import("@inquirer/prompts");for(console.clear(),console.log(B.cyan(`
@@ -191,7 +191,7 @@ Drixio CLI - Modern Database Manager
191
191
  `)),console.log(`${D.bold("Usage:")} npx drixio [command] [options]
192
192
  `),console.log(`${D.bold("Commands:")}`),console.log(` ${D.green("query")} "<sql>" Run a quick SQL query`),console.log(` ${D.green("exec")} <file.sql> Execute a SQL script file`),console.log(` ${D.green("export")} [table] Export table(s) to CSV/JSON`),console.log(` ${D.green("import")} [file] Import JSON/CSV into a table`),console.log(` ${D.green("seed")} [table] [count] Generate fake data for a table`),console.log(` ${D.green("diagram")} Generate a Mermaid ER diagram`),console.log(` ${D.green("generate-types")} Generate TypeScript interfaces`),console.log(` ${D.green("backup")} Backup the entire database`),console.log(` ${D.green("studio")} Launch the Web UI Studio`),console.log(` ${D.green("init")} [db_type] Initialize a local database & .env`),console.log(` ${D.green("drop-db")} [db_type] Drop a local database`),console.log(`
193
193
  ${D.bold("Options:")}`),console.log(" --help Show this help message"),console.log(" --format <type> Specify export format (csv|json)"),console.log(" --schema-only Export schema without data"),console.log(" --table <name> Specify table for import"),console.log(`
194
- If you don't provide a command, Drixio will launch the Interactive UI!`),process.exit(0));let o=a?void 0:t[0];if(o==="query"){let{runQueryCommand:i}=await Promise.resolve().then(()=>(ot(),at)),l=await q();await i(l,t.slice(1));return}if(o==="export"){let{runExportCommand:i}=await Promise.resolve().then(()=>(st(),nt)),l=await q();await i(l,t.slice(1),r);return}if(o==="studio"){let{runStudio:i}=await Promise.resolve().then(()=>(mt(),ct)),l=await q();await i(l);return}if(o==="backup"){let{runBackupCommand:i}=await Promise.resolve().then(()=>(pt(),ut)),l=await q();await i(l);return}if(o==="import"){let{runImportCommand:i}=await Promise.resolve().then(()=>(ft(),gt)),l=await q();await i(l,t.slice(1),r);return}if(o==="seed"){let{runSeedCommand:i}=await Promise.resolve().then(()=>(ht(),yt)),l=await q();await i(l,t.slice(1));return}if(o==="diagram"){let{runDiagramCommand:i}=await Promise.resolve().then(()=>(bt(),wt)),l=await q();await i(l);return}if(o==="exec"){let{runExecCommand:i}=await Promise.resolve().then(()=>($t(),St)),l=await q();await i(l,t.slice(1));return}if(o==="generate-types"){let{runGenerateTypesCommand:i}=await Promise.resolve().then(()=>(Tt(),xt)),l=await q();await i(l);return}if(o==="init"){let{runInitCommand:i}=await Promise.resolve().then(()=>(Ct(),At));await i(t.slice(1));return}if(o==="drop-db"){let{runDropDbCommand:i}=await Promise.resolve().then(()=>(vt(),qt));await i(t.slice(1));return}let e=!0,n=await q(a);for(;e;)switch(console.clear(),Oe(),Fe(n),await et(n)){case"editor":n.type==="unknown"?(console.log(D.yellow(`
194
+ If you don't provide a command, Drixio will launch the Interactive UI!`),process.exit(0));let o=a?void 0:t[0];if(o==="query"){let{runQueryCommand:i}=await Promise.resolve().then(()=>(ot(),at)),l=await q();await i(l,t.slice(1));return}if(o==="export"){let{runExportCommand:i}=await Promise.resolve().then(()=>(st(),nt)),l=await q();await i(l,t.slice(1),r);return}if(o==="studio"){let{runStudio:i}=await Promise.resolve().then(()=>(mt(),ct)),l=await q();await i(l);return}if(o==="backup"){let{runBackupCommand:i}=await Promise.resolve().then(()=>(pt(),ut)),l=await q();await i(l);return}if(o==="import"){let{runImportCommand:i}=await Promise.resolve().then(()=>(ft(),gt)),l=await q();await i(l,t.slice(1),r);return}if(o==="seed"){let{runSeedCommand:i}=await Promise.resolve().then(()=>(ht(),yt)),l=await q();await i(l,t.slice(1));return}if(o==="diagram"){let{runDiagramCommand:i}=await Promise.resolve().then(()=>(bt(),wt)),l=await q();await i(l);return}if(o==="exec"){let{runExecCommand:i}=await Promise.resolve().then(()=>($t(),St)),l=await q();await i(l,t.slice(1));return}if(o==="generate-types"){let{runGenerateTypesCommand:i}=await Promise.resolve().then(()=>(Tt(),xt)),l=await q();await i(l);return}if(o==="init"){let{runInitCommand:i}=await Promise.resolve().then(()=>(Ct(),At));await i(t.slice(1));return}if(o==="drop-db"){let{runDropDbCommand:i}=await Promise.resolve().then(()=>(vt(),qt));await i(t.slice(1));return}let e=!0,n=await q(a);for(;e;)switch(console.clear(),Oe(),Ue(n),await et(n)){case"editor":n.type==="unknown"?(console.log(D.yellow(`
195
195
  No database connection found. Please run ${D.bold("drixio check")} first.`)),await c()):await Xe(n);break;case"table":let{runTableManagerFlow:l}=await Promise.resolve().then(()=>(Qt(),jt));await l(n);break;case"repl":await tt(n);break;case"setup":case"re-configure":n=await Ze(n),await c();break;case"exit":e=!1,console.log(D.dim(`
196
196
  Thanks for using Drixio. Goodbye!`));break}async function c(){let{input:i}=await import("@inquirer/prompts");await i({message:"Click Enter to continue..."})}}Vt().catch(s=>{s.name==="ExitPromptError"&&(console.log(`
197
197
  Exit Drixio.`),process.exit(0)),console.error(`
@@ -82,20 +82,20 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
82
82
  SQL Console
83
83
  </button>
84
84
  </nav>
85
- `,a=t({executeRawQuery:()=>d,fetchTableIndexes:()=>u,fetchTableSchema:()=>l,fetchTableStats:()=>s,fetchTableWithName:()=>c,fetchTables:()=>o});async function o(){return await(await fetch(`/api/tables`)).json()}async function s(){return await(await fetch(`/api/tables/stats`)).json()}async function c(e,t={}){let{where:n=``,limit:r=50,offset:i=0,orderCol:a,orderAsc:o}=t,s=new URLSearchParams;n&&s.append(`where`,n),s.append(`limit`,r.toString()),s.append(`offset`,i.toString()),a&&(s.append(`orderCol`,a),s.append(`orderAsc`,o===!1?`false`:`true`));let c=`/api/tables/${e}/data?${s.toString()}`;return await(await fetch(c)).json()}async function l(e){return await(await fetch(`/api/tables/${e}/schema`)).json()}async function u(e){return await(await fetch(`/api/tables/${e}/indexes`)).json()}async function d(e){return await(await fetch(`/api/query`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sql:e})})).json()}async function f(){try{let e=await o(),t=document.getElementById(`table-nav`),n=document.getElementById(`not-found-msg`);n&&n.remove(),e.success&&e.data&&e.data.length>0?(e.data.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`table-btn`,n.innerHTML=`<span>${e}</span><span class="table-btn-badge" id="badge-${e}" style="display:none;"></span>`,n.onclick=()=>{window.AppState.currentTable=e,window.AppState.currentTableBtnElement=n,window.AppState.currentTab===`erd-btn`||window.AppState.currentTab===`sql-btn`||window.AppState.currentTab===`status-btn`?window.handleSwitchTab(`data-btn`):window.renderCurrentView()},t.appendChild(n)}),window.handleSwitchTab(`data-btn`),s().then(e=>{e.success&&e.data&&Object.entries(e.data).forEach(([e,t])=>{let n=document.getElementById(`badge-${e}`);n&&(n.textContent=Number(t).toLocaleString(),n.style.display=`inline-flex`)})}).catch(e=>console.error(`Failed to load table stats:`,e))):(t.innerHTML=`<div id="not-found-msg">No Tables Found.</div>`,window.handleSwitchTab(`data-btn`))}catch(e){console.error(`Failed to fetch tables:`,e)}}var p=t({bindCellSelection:()=>h,bindColumnResizer:()=>_,renderSelection:()=>m});function m(e,t){document.querySelectorAll(`#${e} .cell-in-range, #${e} .cell-selected, #${e} .range-top, #${e} .range-bottom, #${e} .range-left, #${e} .range-right, #${e} .row-header-selected`).forEach(e=>{e.classList.remove(`cell-in-range`,`cell-selected`,`range-top`,`range-bottom`,`range-left`,`range-right`,`row-header-selected`)});let n=t.selection;if(n.startRow===-1)return;let r=Math.min(n.startRow,n.endRow),i=Math.max(n.startRow,n.endRow),a=Math.min(n.startCol,n.endCol),o=Math.max(n.startCol,n.endCol);document.querySelectorAll(`#${e} td.data-cell`).forEach(e=>{let s=parseInt(e.dataset.rowIdx),c=parseInt(e.dataset.colIdx);s>=r&&s<=i&&c>=a&&c<=o&&(e.classList.add(`cell-in-range`),s===r&&e.classList.add(`range-top`),s===i&&e.classList.add(`range-bottom`),c===a&&e.classList.add(`range-left`),c===o&&e.classList.add(`range-right`),s===n.startRow&&c===n.startCol&&(e.classList.add(`cell-selected`),t.selectedCell=e))}),n.isDraggingRow&&document.querySelectorAll(`#${e} td.row-header`).forEach(e=>{let t=parseInt(e.dataset.rowIdx);t>=r&&t<=i&&e.classList.add(`row-header-selected`)})}function h(e,t,n,r){e.addEventListener(`mousedown`,e=>{if(e.target.tagName===`INPUT`||e.target.tagName===`SELECT`)return;let i=e.target.closest(`td.row-header`);if(i&&e.button!==2){let e=parseInt(i.dataset.rowIdx);n.selection={isDragging:!1,isDraggingRow:!0,startRow:e,endRow:e,startCol:0,endCol:r-1},m(t,n);return}let a=e.target.closest(`td.data-cell`);if(!a)return;let o=parseInt(a.dataset.rowIdx),s=parseInt(a.dataset.colIdx);n.selection={isDragging:!0,startRow:o,startCol:s,endRow:o,endCol:s},m(t,n)}),e.addEventListener(`mouseover`,e=>{if(n.selection.isDraggingRow){let r=e.target.closest(`td.row-header`);if(!r)return;n.selection.endRow=parseInt(r.dataset.rowIdx),m(t,n);return}if(!n.selection.isDragging)return;let r=e.target.closest(`td.data-cell`);r&&(n.selection.endRow=parseInt(r.dataset.rowIdx),n.selection.endCol=parseInt(r.dataset.colIdx),m(t,n))}),e.addEventListener(`mouseup`,()=>{n.selection&&(n.selection.isDragging=!1,n.selection.isDraggingRow=!1)}),e.addEventListener(`contextmenu`,e=>{let r=e.target.closest(`td.row-header`);if(!r)return;let i=parseInt(r.dataset.rowIdx),a=n.selection,o=Math.min(a.startRow,a.endRow),s=Math.max(a.startRow,a.endRow);a.startRow!==-1&&i>=o&&i<=s&&(e.preventDefault(),g(e.pageX,e.pageY,n,t))})}function g(e,t,n,r){let i=document.getElementById(`grid-context-menu`);i||(i=document.createElement(`div`),i.id=`grid-context-menu`,i.className=`context-menu`,document.body.appendChild(i),document.addEventListener(`click`,()=>{i.style.display=`none`}));let a=n.selection,o=Math.min(a.startRow,a.endRow),s=Math.max(a.startRow,a.endRow),c=s-o+1;i.innerHTML=`
85
+ `,a=t({executeRawQuery:()=>f,fetchConfig:()=>s,fetchTableIndexes:()=>d,fetchTableSchema:()=>u,fetchTableStats:()=>c,fetchTableWithName:()=>l,fetchTables:()=>o});async function o(){return await(await fetch(`/api/tables`)).json()}async function s(){return await(await fetch(`/api/config`)).json()}async function c(){return await(await fetch(`/api/tables/stats`)).json()}async function l(e,t={}){let{where:n=``,limit:r=50,offset:i=0,orderCol:a,orderAsc:o}=t,s=new URLSearchParams;n&&s.append(`where`,n),s.append(`limit`,r.toString()),s.append(`offset`,i.toString()),a&&(s.append(`orderCol`,a),s.append(`orderAsc`,o===!1?`false`:`true`));let c=`/api/tables/${e}/data?${s.toString()}`;return await(await fetch(c)).json()}async function u(e){return await(await fetch(`/api/tables/${e}/schema`)).json()}async function d(e){return await(await fetch(`/api/tables/${e}/indexes`)).json()}async function f(e){return await(await fetch(`/api/query`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sql:e})})).json()}async function p(){try{let e=await o(),t=document.getElementById(`table-nav`),n=document.getElementById(`not-found-msg`);n&&n.remove(),e.success&&e.data&&e.data.length>0?(e.data.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`table-btn`,n.innerHTML=`<span>${e}</span><span class="table-btn-badge" id="badge-${e}" style="display:none;"></span>`,n.onclick=()=>{window.AppState.currentTable=e,window.AppState.currentTableBtnElement=n,window.AppState.currentTab===`erd-btn`||window.AppState.currentTab===`sql-btn`||window.AppState.currentTab===`status-btn`?window.handleSwitchTab(`data-btn`):window.renderCurrentView()},t.appendChild(n)}),window.handleSwitchTab(`data-btn`),c().then(e=>{e.success&&e.data&&Object.entries(e.data).forEach(([e,t])=>{let n=document.getElementById(`badge-${e}`);n&&(n.textContent=Number(t).toLocaleString(),n.style.display=`inline-flex`)})}).catch(e=>console.error(`Failed to load table stats:`,e))):(t.innerHTML=`<div id="not-found-msg">No Tables Found.</div>`,window.handleSwitchTab(`data-btn`))}catch(e){console.error(`Failed to fetch tables:`,e)}}var m=t({bindCellSelection:()=>g,bindColumnResizer:()=>v,renderSelection:()=>h});function h(e,t){document.querySelectorAll(`#${e} .cell-in-range, #${e} .cell-selected, #${e} .range-top, #${e} .range-bottom, #${e} .range-left, #${e} .range-right, #${e} .row-header-selected`).forEach(e=>{e.classList.remove(`cell-in-range`,`cell-selected`,`range-top`,`range-bottom`,`range-left`,`range-right`,`row-header-selected`)});let n=t.selection;if(n.startRow===-1)return;let r=Math.min(n.startRow,n.endRow),i=Math.max(n.startRow,n.endRow),a=Math.min(n.startCol,n.endCol),o=Math.max(n.startCol,n.endCol);document.querySelectorAll(`#${e} td.data-cell`).forEach(e=>{let s=parseInt(e.dataset.rowIdx),c=parseInt(e.dataset.colIdx);s>=r&&s<=i&&c>=a&&c<=o&&(e.classList.add(`cell-in-range`),s===r&&e.classList.add(`range-top`),s===i&&e.classList.add(`range-bottom`),c===a&&e.classList.add(`range-left`),c===o&&e.classList.add(`range-right`),s===n.startRow&&c===n.startCol&&(e.classList.add(`cell-selected`),t.selectedCell=e))}),n.isDraggingRow&&document.querySelectorAll(`#${e} td.row-header`).forEach(e=>{let t=parseInt(e.dataset.rowIdx);t>=r&&t<=i&&e.classList.add(`row-header-selected`)})}function g(e,t,n,r){e.addEventListener(`mousedown`,e=>{if(e.target.tagName===`INPUT`||e.target.tagName===`SELECT`)return;let i=e.target.closest(`td.row-header`);if(i&&e.button!==2){let e=parseInt(i.dataset.rowIdx);n.selection={isDragging:!1,isDraggingRow:!0,startRow:e,endRow:e,startCol:0,endCol:r-1},h(t,n);return}let a=e.target.closest(`td.data-cell`);if(!a)return;let o=parseInt(a.dataset.rowIdx),s=parseInt(a.dataset.colIdx);n.selection={isDragging:!0,startRow:o,startCol:s,endRow:o,endCol:s},h(t,n)}),e.addEventListener(`mouseover`,e=>{if(n.selection.isDraggingRow){let r=e.target.closest(`td.row-header`);if(!r)return;n.selection.endRow=parseInt(r.dataset.rowIdx),h(t,n);return}if(!n.selection.isDragging)return;let r=e.target.closest(`td.data-cell`);r&&(n.selection.endRow=parseInt(r.dataset.rowIdx),n.selection.endCol=parseInt(r.dataset.colIdx),h(t,n))}),e.addEventListener(`mouseup`,()=>{n.selection&&(n.selection.isDragging=!1,n.selection.isDraggingRow=!1)}),e.addEventListener(`contextmenu`,e=>{let r=e.target.closest(`td.row-header`);if(!r)return;let i=parseInt(r.dataset.rowIdx),a=n.selection,o=Math.min(a.startRow,a.endRow),s=Math.max(a.startRow,a.endRow);a.startRow!==-1&&i>=o&&i<=s&&(e.preventDefault(),_(e.pageX,e.pageY,n,t))})}function _(e,t,n,r){let i=document.getElementById(`grid-context-menu`);i||(i=document.createElement(`div`),i.id=`grid-context-menu`,i.className=`context-menu`,document.body.appendChild(i),document.addEventListener(`click`,()=>{i.style.display=`none`}));let a=n.selection,o=Math.min(a.startRow,a.endRow),s=Math.max(a.startRow,a.endRow),c=s-o+1;i.innerHTML=`
86
86
  <div class="menu-item delete-action">
87
87
  <span class="material-symbols-outlined">delete</span>
88
88
  Delete ${c} Row${c>1?`s`:``}
89
89
  </div>
90
- `,i.style.left=`${e}px`,i.style.top=`${t}px`,i.style.display=`block`,i.querySelector(`.delete-action`).onclick=e=>{e.stopPropagation(),i.style.display=`none`;let t=document.querySelectorAll(`#${r} tbody tr:not(.ghost-row-tr)`);for(let e=o;e<=s;e++){let r=t[e];if(!r)continue;let i=r.querySelector(`td.data-cell`);if(i){let e=i.dataset.pk;e!==`undefined`&&e!=null&&(n.pendingDeletes||=new Set,n.pendingDeletes.add(e),r.classList.add(`row-deleted`))}}let a=document.getElementById(`btn-save-changes`);a&&a.classList.add(`has-changes`)}}function _(e,t){let n=document.createElement(`div`);n.className=`resizer`,e.appendChild(n),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,n=>{n.preventDefault(),n.stopPropagation();let r=n.pageX,i=e.offsetWidth,a=!1,o=n=>{a=!0,t&&(t.isResizing=!0);let o=i+(n.pageX-r);e.style.width=o+`px`,e.style.minWidth=o+`px`,e.style.maxWidth=o+`px`},s=()=>{document.removeEventListener(`mousemove`,o),document.removeEventListener(`mouseup`,s),document.body.style.cursor=``,a&&setTimeout(()=>{t&&(t.isResizing=!1)},100)};document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,o),document.addEventListener(`mouseup`,s)})}var v=t({duplicateDataRows:()=>C,markRowDeleted:()=>x,saveDataGridEdits:()=>y,unmarkRowDeleted:()=>S,updateCell:()=>b});async function y(){if(!window.DataGrid)return;let{pendingEdits:e,pendingInserts:t,pkColumn:n}=window.DataGrid,r=window.AppState.currentTable;if(!r||!n){alert(`Cannot save: No Primary Key detected for this table.`);return}let i=[];for(let[t,a]of Object.entries(e)){if(Object.keys(a).length===0)continue;let e=Object.entries(a).map(([e,t])=>t===``?`"${e}" = NULL`:`"${e}" = '${t.replace(/'/g,`''`)}'`).join(`, `);i.push(`UPDATE "${r}" SET ${e} WHERE "${n}" = '${t.replace(/'/g,`''`)}';`)}for(let e=0;e<t.length;e++){let n=t[e];if(Object.keys(n).length===0||!Object.values(n).some(e=>e!==``))continue;let a=Object.keys(n),o=a.map(e=>{let t=n[e];return t===``?`NULL`:`'${t.replace(/'/g,`''`)}'`});i.push(`INSERT INTO "${r}" ("${a.join(`", "`)}") VALUES (${o.join(`, `)});`)}if(window.DataGrid.pendingDeletes)for(let e of window.DataGrid.pendingDeletes)i.push(`DELETE FROM "${r}" WHERE "${n}" = '${e.replace(/'/g,`''`)}';`);if(i.length===0)return;let a=!0,o=``;for(let e of i)try{let t=await d(e);if(!t.success){a=!1,o=t.error;break}}catch(e){a=!1,o=e.message;break}a?(window.renderCurrentView(),window.showToast&&window.showToast(`Data saved successfully!`)):(window.showToast?window.showToast(`Save failed: `+o,`error`):alert(`Save failed:
91
- `+o),document.querySelectorAll(`.cell-edited`).forEach(e=>{e.classList.remove(`cell-edited`),e.classList.add(`cell-error`)})),window.updateSidebarDirtyState?.()}function b(e,t,n,r=!0){if(r&&window.DataGrid.currentTransaction){let n=e.textContent;(n===`null`||e.classList.contains(`ghost-row`))&&(n=``),n!==t&&window.DataGrid.currentTransaction.push({td:e,oldVal:n,newVal:t})}let i=e.dataset.col;if(e.innerHTML=t||(e.dataset.insertIndex===void 0?`<em>null</em>`:`+ New`),e.dataset.insertIndex!==void 0){let r=parseInt(e.dataset.insertIndex);if(window.DataGrid.pendingInserts[r]||(window.DataGrid.pendingInserts[r]={}),t&&(window.DataGrid.pendingInserts[r][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`ghost-row`),r===window.DataGrid.pendingInserts.length-1)){e.closest(`tr`).classList.remove(`ghost-row-tr`),window.DataGrid.pendingInserts.push({});let t=document.querySelector(`#data-grid-table-${window.AppState.currentTable} tbody`),i=document.createElement(`tr`);i.className=`ghost-row-tr`;let a=parseInt(e.dataset.rowIdx)+1;i.innerHTML+=`<td class="row-header" data-row-idx="${a}">*</td>`,n.forEach((e,t)=>{i.innerHTML+=`<td class="data-cell ghost-row" data-row-idx="${a}" data-col-idx="${t}" data-insert-index="${r+1}" data-col="${e}">+ New</td>`}),t.appendChild(i)}}else{let n=e.dataset.pk;t===e.dataset.original?(e.classList.remove(`cell-edited`),e.classList.remove(`cell-error`),window.DataGrid.pendingEdits[n]&&delete window.DataGrid.pendingEdits[n][i]):(window.DataGrid.pendingEdits[n]||(window.DataGrid.pendingEdits[n]={}),window.DataGrid.pendingEdits[n][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`cell-error`))}window.updateSidebarDirtyState?.()}function x(e,t=!0){let n=document.querySelector(`td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!n||n.classList.contains(`ghost-row-tr`)||n.classList.contains(`row-deleted`))return;let r=n.querySelector(`td.data-cell`)?.dataset.pk;r!==void 0&&(t&&window.DataGrid.currentTransaction&&window.DataGrid.currentTransaction.push({type:`delete`,rowIdx:e,pk:r}),window.DataGrid.pendingDeletes.add(r),n.classList.add(`row-deleted`)),window.updateSidebarDirtyState?.()}function S(e,t){let n=document.querySelector(`td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);n&&n.classList.remove(`row-deleted`),window.DataGrid.pendingDeletes.delete(t),window.updateSidebarDirtyState?.()}function C(e,t){e.forEach(e=>{let n=window.AppState.currentTable,r=document.querySelector(`#data-grid-table-${n} td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!r||r.classList.contains(`ghost-row-tr`))return;let i=document.querySelector(`#data-grid-table-${n} .ghost-row-tr`);i&&t.forEach((e,n)=>{let a=r.querySelector(`td.data-cell[data-col-idx="${n}"]`),o=i.querySelector(`td.data-cell[data-col-idx="${n}"]`);if(a&&o){let n=a.dataset.insertIndex===void 0?a.classList.contains(`cell-edited`)?window.DataGrid.pendingEdits[a.dataset.pk]?.[e]:a.dataset.original:window.DataGrid.pendingInserts[a.dataset.insertIndex][e];n!=null&&n!==`null`&&b(o,n,t,!0)}})})}var w=`modulepreload`,T=function(e,t){return new URL(e,t).href},E={},D=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=T(t,n),t=s(t),t in E)return;E[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:w,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};function O(e,t,n){e.addEventListener(`dblclick`,e=>{let r=e.target.closest(`td.data-cell`);if(!r||r.querySelector(`input, select`))return;let i=r.dataset.col,o=t.find(e=>e.name===i),s=o?.type?.toUpperCase()||``,c=s.includes(`ENUM`),l=s===`DATE`,u=s.includes(`DATETIME`)||s.includes(`TIMESTAMP`),d=s.includes(`BOOL`)||s===`TINYINT(1)`,f=r.textContent===`null`||r.textContent===`+ New`?``:r.textContent,p;if(o&&o.fkTarget){p=document.createElement(`select`);let e=document.createElement(`option`);e.value=f,e.textContent=`Loading...`,p.appendChild(e),D(async()=>{let{executeRawQuery:e}=await Promise.resolve().then(()=>a);return{executeRawQuery:e}},void 0,import.meta.url).then(({executeRawQuery:t})=>{let{table:n,column:r}=o.fkTarget;t(`SELECT * FROM "${n}" LIMIT 100`).then(e=>{if(e.success&&e.data&&e.data.rows){if(p.innerHTML=``,o.nullable){let e=document.createElement(`option`);e.value=``,e.textContent=`-- None --`,p.appendChild(e)}let t=r;if(e.data.columns){let n=[`name`,`title`,`label`,`description`],r=e.data.columns.find(e=>n.includes(e.toLowerCase()));r&&(t=r)}if(e.data.rows.forEach(e=>{let n=String(e[r]),i=t===r?n:`${n} - ${e[t]}`,a=document.createElement(`option`);a.value=n,a.textContent=i,n===f&&(a.selected=!0),p.appendChild(a)}),f&&!e.data.rows.find(e=>String(e[r])===f)){let e=document.createElement(`option`);e.value=f,e.textContent=`${f} (Not in limit)`,e.selected=!0,p.appendChild(e)}}}).catch(t=>{e.textContent=`Error loading options`})})}else if(c){let e=o.type.match(/enum\((.*?)\)/i),t=[];e&&(t=e[1].split(`,`).map(e=>e.trim().replace(/^'|'$/g,``))),p=document.createElement(`select`),t.forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,e===f&&(t.selected=!0),p.appendChild(t)})}else if(l)p=document.createElement(`input`),p.type=`date`,p.value=f;else if(u){p=document.createElement(`input`),p.type=`datetime-local`;let e=f.replace(` `,`T`).slice(0,16);p.value=e}else d?(p=document.createElement(`input`),p.type=`checkbox`,p.checked=f===`1`||f.toLowerCase()===`true`):(p=document.createElement(`input`),p.type=`text`,p.value=f);let m=!1,h=()=>{m=!0;let e=document.getElementById(`modal-editor-overlay`),t=document.getElementById(`modal-textarea`),n=document.getElementById(`modal-cancel-btn`),r=document.getElementById(`modal-save-btn`),a=document.getElementById(`modal-title`);a.textContent=`Edit ${i}`,t.value=p.value,e.style.display=`flex`,t.focus();let o=()=>{e.style.display=`none`,r.onclick=null,n.onclick=null,m=!1,p.focus()};n.onclick=o,r.onclick=()=>{p.value=t.value,o(),g()}};if(r.innerHTML=``,r.appendChild(p),s===``||!c&&!l&&!u&&!d&&!(o&&o.fkTarget)){let e=document.createElement(`span`);e.className=`material-symbols-outlined cell-expand-btn`,e.textContent=`open_in_full`,e.onmousedown=e=>e.preventDefault(),e.onclick=()=>h(),r.appendChild(e),p.style.width=`100%`,p.style.paddingRight=`32px`,p.addEventListener(`keydown`,e=>{e.key===`Enter`&&e.shiftKey?(e.preventDefault(),h()):e.key===`Enter`&&p.blur()})}else p.addEventListener(`keydown`,e=>{e.key===`Enter`&&p.blur()});p.focus();let g=()=>{if(m)return;let e=d?p.checked?`1`:`0`:p.value;u&&e&&(e=e.replace(`T`,` `)+`:00`),window.DataGrid.currentTransaction=[],b(r,e,n),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null};p.addEventListener(`blur`,()=>{setTimeout(()=>{m||g()},100)})})}function k(){let e=window.AppState?.currentTable;if(!e)return``;let t=document.getElementById(`filter-val-${e}`)?.value.trim(),n=document.getElementById(`filter-op-${e}`)?.value,r=document.getElementById(`filter-col-${e}`)?.value,i=``;if(t||n===`IS NULL`){let e=t;e&&!e.startsWith(`'`)&&!e.endsWith(`'`)&&isNaN(Number(e))&&(e.toUpperCase().includes(` AND `)||e.toUpperCase().includes(` OR `)||(e=`'${e.replace(/'/g,`''`)}'`)),i=`"${r}" ${n} ${e}`}return i}function A(e,t,n,r){let i=`<td class="row-header" data-row-idx="${t}">${t+1}</td>`,a=n?e[n]:t;return r.forEach((n,r)=>{let o=e[n]===null?`null`:String(e[n]),s=o.replace(/"/g,`&quot;`),c=o===`null`?`<em>null</em>`:o.replace(/</g,`&lt;`);i+=`<td class="data-cell" data-row-idx="${t}" data-col-idx="${r}" data-pk="${a}" data-col="${n}" data-original="${s}">${c}</td>`}),i}async function j(e,t,n=``,r=!1,i=null){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let a=document.getElementById(`table-name`);a&&(a.textContent=e);let o=i||document.getElementById(`main-content`);r||(o.innerHTML=`<div style='padding:24px;'>Loading...</div>`);try{let i=await l(e);if(!i.success)throw Error(i.error);let a=i.data,s=a.find(e=>e.isPk)?.name;(!r||!window.DataGrid)&&(window.DataGrid={schema:a,pkColumn:s,pendingEdits:{},pendingInserts:[{}],pendingDeletes:new Set,selectedCell:null,history:[],currentTransaction:null,sortState:{col:s||a[0].name,asc:!0},pagination:{limit:50,offset:0,isLoading:!1,hasMore:!0},selection:{isDragging:!1,isDraggingRow:!1,startRow:-1,startCol:-1,endRow:-1,endCol:-1}}),window.TableStates&&window.TableStates[e]&&(window.TableStates[e].dataGrid=window.DataGrid);let u=await c(e,{where:n,limit:window.DataGrid.pagination.limit,offset:window.DataGrid.pagination.offset,orderCol:window.DataGrid.sortState.col,orderAsc:window.DataGrid.sortState.asc});if(u.success&&u.data){let n=u.data.rows,i=u.data.columns;window.DataGrid.pagination.hasMore=n.length===window.DataGrid.pagination.limit;let l=i.map(e=>`<option value="${e}">${e}</option>`).join(``);r||(o.innerHTML=`
90
+ `,i.style.left=`${e}px`,i.style.top=`${t}px`,i.style.display=`block`,i.querySelector(`.delete-action`).onclick=e=>{e.stopPropagation(),i.style.display=`none`;let t=document.querySelectorAll(`#${r} tbody tr:not(.ghost-row-tr)`);for(let e=o;e<=s;e++){let r=t[e];if(!r)continue;let i=r.querySelector(`td.data-cell`);if(i){let e=i.dataset.pk;e!==`undefined`&&e!=null&&(n.pendingDeletes||=new Set,n.pendingDeletes.add(e),r.classList.add(`row-deleted`))}}let a=document.getElementById(`btn-save-changes`);a&&a.classList.add(`has-changes`)}}function v(e,t){let n=document.createElement(`div`);n.className=`resizer`,e.appendChild(n),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,n=>{n.preventDefault(),n.stopPropagation();let r=n.pageX,i=e.offsetWidth,a=!1,o=n=>{a=!0,t&&(t.isResizing=!0);let o=i+(n.pageX-r);e.style.width=o+`px`,e.style.minWidth=o+`px`,e.style.maxWidth=o+`px`},s=()=>{document.removeEventListener(`mousemove`,o),document.removeEventListener(`mouseup`,s),document.body.style.cursor=``,a&&setTimeout(()=>{t&&(t.isResizing=!1)},100)};document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,o),document.addEventListener(`mouseup`,s)})}var y=t({duplicateDataRows:()=>w,markRowDeleted:()=>S,saveDataGridEdits:()=>b,unmarkRowDeleted:()=>C,updateCell:()=>x});async function b(){if(!window.DataGrid)return;let{pendingEdits:e,pendingInserts:t,pkColumn:n}=window.DataGrid,r=window.AppState.currentTable;if(!r||!n){alert(`Cannot save: No Primary Key detected for this table.`);return}let i=[];for(let[t,a]of Object.entries(e)){if(Object.keys(a).length===0)continue;let e=Object.entries(a).map(([e,t])=>t===``?`"${e}" = NULL`:`"${e}" = '${t.replace(/'/g,`''`)}'`).join(`, `);i.push(`UPDATE "${r}" SET ${e} WHERE "${n}" = '${t.replace(/'/g,`''`)}';`)}for(let e=0;e<t.length;e++){let n=t[e];if(Object.keys(n).length===0||!Object.values(n).some(e=>e!==``))continue;let a=Object.keys(n),o=a.map(e=>{let t=n[e];return t===``?`NULL`:`'${t.replace(/'/g,`''`)}'`});i.push(`INSERT INTO "${r}" ("${a.join(`", "`)}") VALUES (${o.join(`, `)});`)}if(window.DataGrid.pendingDeletes)for(let e of window.DataGrid.pendingDeletes)i.push(`DELETE FROM "${r}" WHERE "${n}" = '${e.replace(/'/g,`''`)}';`);if(i.length===0)return;let a=!0,o=``;for(let e of i)try{let t=await f(e);if(!t.success){a=!1,o=t.error;break}}catch(e){a=!1,o=e.message;break}a?(window.renderCurrentView(),window.showToast&&window.showToast(`Data saved successfully!`)):(window.showToast?window.showToast(`Save failed: `+o,`error`):alert(`Save failed:
91
+ `+o),document.querySelectorAll(`.cell-edited`).forEach(e=>{e.classList.remove(`cell-edited`),e.classList.add(`cell-error`)})),window.updateSidebarDirtyState?.()}function x(e,t,n,r=!0){if(r&&window.DataGrid.currentTransaction){let n=e.textContent;(n===`null`||e.classList.contains(`ghost-row`))&&(n=``),n!==t&&window.DataGrid.currentTransaction.push({td:e,oldVal:n,newVal:t})}let i=e.dataset.col;if(e.innerHTML=t||(e.dataset.insertIndex===void 0?`<em>null</em>`:`+ New`),e.dataset.insertIndex!==void 0){let r=parseInt(e.dataset.insertIndex);if(window.DataGrid.pendingInserts[r]||(window.DataGrid.pendingInserts[r]={}),t&&(window.DataGrid.pendingInserts[r][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`ghost-row`),r===window.DataGrid.pendingInserts.length-1)){e.closest(`tr`).classList.remove(`ghost-row-tr`),window.DataGrid.pendingInserts.push({});let t=document.querySelector(`#data-grid-table-${window.AppState.currentTable} tbody`),i=document.createElement(`tr`);i.className=`ghost-row-tr`;let a=parseInt(e.dataset.rowIdx)+1;i.innerHTML+=`<td class="row-header" data-row-idx="${a}">*</td>`,n.forEach((e,t)=>{i.innerHTML+=`<td class="data-cell ghost-row" data-row-idx="${a}" data-col-idx="${t}" data-insert-index="${r+1}" data-col="${e}">+ New</td>`}),t.appendChild(i)}}else{let n=e.dataset.pk;t===e.dataset.original?(e.classList.remove(`cell-edited`),e.classList.remove(`cell-error`),window.DataGrid.pendingEdits[n]&&delete window.DataGrid.pendingEdits[n][i]):(window.DataGrid.pendingEdits[n]||(window.DataGrid.pendingEdits[n]={}),window.DataGrid.pendingEdits[n][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`cell-error`))}window.updateSidebarDirtyState?.()}function S(e,t=!0){let n=document.querySelector(`td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!n||n.classList.contains(`ghost-row-tr`)||n.classList.contains(`row-deleted`))return;let r=n.querySelector(`td.data-cell`)?.dataset.pk;r!==void 0&&(t&&window.DataGrid.currentTransaction&&window.DataGrid.currentTransaction.push({type:`delete`,rowIdx:e,pk:r}),window.DataGrid.pendingDeletes.add(r),n.classList.add(`row-deleted`)),window.updateSidebarDirtyState?.()}function C(e,t){let n=document.querySelector(`td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);n&&n.classList.remove(`row-deleted`),window.DataGrid.pendingDeletes.delete(t),window.updateSidebarDirtyState?.()}function w(e,t){e.forEach(e=>{let n=window.AppState.currentTable,r=document.querySelector(`#data-grid-table-${n} td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!r||r.classList.contains(`ghost-row-tr`))return;let i=document.querySelector(`#data-grid-table-${n} .ghost-row-tr`);i&&t.forEach((e,n)=>{let a=r.querySelector(`td.data-cell[data-col-idx="${n}"]`),o=i.querySelector(`td.data-cell[data-col-idx="${n}"]`);if(a&&o){let n=a.dataset.insertIndex===void 0?a.classList.contains(`cell-edited`)?window.DataGrid.pendingEdits[a.dataset.pk]?.[e]:a.dataset.original:window.DataGrid.pendingInserts[a.dataset.insertIndex][e];n!=null&&n!==`null`&&x(o,n,t,!0)}})})}var T=`modulepreload`,E=function(e,t){return new URL(e,t).href},D={},O=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=E(t,n),t=s(t),t in D)return;D[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:T,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};function k(e,t,n){e.addEventListener(`dblclick`,e=>{let r=e.target.closest(`td.data-cell`);if(!r||r.querySelector(`input, select`))return;let i=r.dataset.col,o=t.find(e=>e.name===i),s=o?.type?.toUpperCase()||``,c=s.includes(`ENUM`),l=s===`DATE`,u=s.includes(`DATETIME`)||s.includes(`TIMESTAMP`),d=s.includes(`BOOL`)||s===`TINYINT(1)`,f=r.textContent===`null`||r.textContent===`+ New`?``:r.textContent,p;if(o&&o.fkTarget){p=document.createElement(`select`);let e=document.createElement(`option`);e.value=f,e.textContent=`Loading...`,p.appendChild(e),O(async()=>{let{executeRawQuery:e}=await Promise.resolve().then(()=>a);return{executeRawQuery:e}},void 0,import.meta.url).then(({executeRawQuery:t})=>{let{table:n,column:r}=o.fkTarget;t(`SELECT * FROM "${n}" LIMIT 100`).then(e=>{if(e.success&&e.data&&e.data.rows){if(p.innerHTML=``,o.nullable){let e=document.createElement(`option`);e.value=``,e.textContent=`-- None --`,p.appendChild(e)}let t=r;if(e.data.columns){let n=[`name`,`title`,`label`,`description`],r=e.data.columns.find(e=>n.includes(e.toLowerCase()));r&&(t=r)}if(e.data.rows.forEach(e=>{let n=String(e[r]),i=t===r?n:`${n} - ${e[t]}`,a=document.createElement(`option`);a.value=n,a.textContent=i,n===f&&(a.selected=!0),p.appendChild(a)}),f&&!e.data.rows.find(e=>String(e[r])===f)){let e=document.createElement(`option`);e.value=f,e.textContent=`${f} (Not in limit)`,e.selected=!0,p.appendChild(e)}}}).catch(t=>{e.textContent=`Error loading options`})})}else if(c){let e=o.type.match(/enum\((.*?)\)/i),t=[];e&&(t=e[1].split(`,`).map(e=>e.trim().replace(/^'|'$/g,``))),p=document.createElement(`select`),t.forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,e===f&&(t.selected=!0),p.appendChild(t)})}else if(l)p=document.createElement(`input`),p.type=`date`,p.value=f;else if(u){p=document.createElement(`input`),p.type=`datetime-local`;let e=f.replace(` `,`T`).slice(0,16);p.value=e}else d?(p=document.createElement(`input`),p.type=`checkbox`,p.checked=f===`1`||f.toLowerCase()===`true`):(p=document.createElement(`input`),p.type=`text`,p.value=f);let m=!1,h=()=>{m=!0;let e=document.getElementById(`modal-editor-overlay`),t=document.getElementById(`modal-textarea`),n=document.getElementById(`modal-cancel-btn`),r=document.getElementById(`modal-save-btn`),a=document.getElementById(`modal-title`);a.textContent=`Edit ${i}`,t.value=p.value,e.style.display=`flex`,t.focus();let o=()=>{e.style.display=`none`,r.onclick=null,n.onclick=null,m=!1,p.focus()};n.onclick=o,r.onclick=()=>{p.value=t.value,o(),g()}};if(r.innerHTML=``,r.appendChild(p),s===``||!c&&!l&&!u&&!d&&!(o&&o.fkTarget)){let e=document.createElement(`span`);e.className=`material-symbols-outlined cell-expand-btn`,e.textContent=`open_in_full`,e.onmousedown=e=>e.preventDefault(),e.onclick=()=>h(),r.appendChild(e),p.style.width=`100%`,p.style.paddingRight=`32px`,p.addEventListener(`keydown`,e=>{e.key===`Enter`&&e.shiftKey?(e.preventDefault(),h()):e.key===`Enter`&&p.blur()})}else p.addEventListener(`keydown`,e=>{e.key===`Enter`&&p.blur()});p.focus();let g=()=>{if(m)return;let e=d?p.checked?`1`:`0`:p.value;u&&e&&(e=e.replace(`T`,` `)+`:00`),window.DataGrid.currentTransaction=[],x(r,e,n),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null};p.addEventListener(`blur`,()=>{setTimeout(()=>{m||g()},100)})})}function A(){let e=window.AppState?.currentTable;if(!e)return``;let t=document.getElementById(`filter-val-${e}`)?.value.trim(),n=document.getElementById(`filter-op-${e}`)?.value,r=document.getElementById(`filter-col-${e}`)?.value,i=``;if(t||n===`IS NULL`){let e=t;e&&!e.startsWith(`'`)&&!e.endsWith(`'`)&&isNaN(Number(e))&&(e.toUpperCase().includes(` AND `)||e.toUpperCase().includes(` OR `)||(e=`'${e.replace(/'/g,`''`)}'`)),i=`"${r}" ${n} ${e}`}return i}function j(e,t,n,r){let i=`<td class="row-header" data-row-idx="${t}">${t+1}</td>`,a=n?e[n]:t;return r.forEach((n,r)=>{let o=e[n]===null?`null`:String(e[n]),s=o.replace(/"/g,`&quot;`),c=o===`null`?`<em>null</em>`:o.replace(/</g,`&lt;`);i+=`<td class="data-cell" data-row-idx="${t}" data-col-idx="${r}" data-pk="${a}" data-col="${n}" data-original="${s}">${c}</td>`}),i}async function M(e,t,n=``,r=!1,i=null){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let a=document.getElementById(`table-name`);a&&(a.textContent=e);let o=i||document.getElementById(`main-content`);r||(o.innerHTML=`<div style='padding:24px;'>Loading...</div>`);try{let i=await u(e);if(!i.success)throw Error(i.error);let a=i.data,s=a.find(e=>e.isPk)?.name;(!r||!window.DataGrid)&&(window.DataGrid={schema:a,pkColumn:s,pendingEdits:{},pendingInserts:[{}],pendingDeletes:new Set,selectedCell:null,history:[],currentTransaction:null,sortState:{col:s||a[0].name,asc:!0},pagination:{limit:50,offset:0,isLoading:!1,hasMore:!0},selection:{isDragging:!1,isDraggingRow:!1,startRow:-1,startCol:-1,endRow:-1,endCol:-1}}),window.TableStates&&window.TableStates[e]&&(window.TableStates[e].dataGrid=window.DataGrid);let c=await l(e,{where:n,limit:window.DataGrid.pagination.limit,offset:window.DataGrid.pagination.offset,orderCol:window.DataGrid.sortState.col,orderAsc:window.DataGrid.sortState.asc});if(c.success&&c.data){let n=c.data.rows,i=c.data.columns;window.DataGrid.pagination.hasMore=n.length===window.DataGrid.pagination.limit;let u=i.map(e=>`<option value="${e}">${e}</option>`).join(``);r||(o.innerHTML=`
92
92
  <div class="toolbar">
93
93
  <div class="filter-group">
94
94
  <div class="filter-icon-container">
95
95
  <span class="material-symbols-outlined" id="filter-icon">filter_list</span>
96
96
  <span>Filter</span>
97
97
  </div>
98
- <select id="filter-col-${e}" class="filter-select">${l}</select>
98
+ <select id="filter-col-${e}" class="filter-select">${u}</select>
99
99
  <select id="filter-op-${e}" class="filter-select">
100
100
  <option value="=">=</option>
101
101
  <option value=">">></option>
@@ -116,8 +116,8 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
116
116
  <div>${e}${n}${r}</div>
117
117
  <div class="sort-arrow" style="font-size:10px; opacity:0.8; margin-left: 8px; width: 12px; text-align: right;">${i}</div>
118
118
  </div>
119
- </th>`}),d+=`</tr></thead><tbody>`,n&&n.length>0&&n.forEach((e,t)=>{d+=`<tr>${A(e,t,s,i)}</tr>`}),d+=`<tr class="ghost-row-tr">`;let f=n?n.length:0;d+=`<td class="row-header" data-row-idx="${f}">*</td>`,i.forEach((e,t)=>{d+=`<td class="data-cell ghost-row" data-row-idx="${f}" data-col-idx="${t}" data-insert-index="0" data-col="${e}">+ New</td>`}),d+=`</tr></tbody></table>`;let p=document.getElementById(`data-grid-container-${e}`);if(!p)return;if(p.innerHTML=d,document.querySelectorAll(`th.sortable`).forEach(n=>{n.onclick=r=>{if(window.DataGrid&&window.DataGrid.isResizing)return;if(Object.keys(window.DataGrid.pendingEdits).length>0||window.DataGrid.pendingInserts.length>1||window.DataGrid.pendingDeletes.size>0){alert(`You have unsaved changes. Please save changes before sorting.`);return}let i=n.dataset.col;window.DataGrid.sortState.col===i?window.DataGrid.sortState.asc=!window.DataGrid.sortState.asc:(window.DataGrid.sortState.col=i,window.DataGrid.sortState.asc=!0),window.DataGrid.pagination.offset=0,j(e,t,k(),!0)},_(n,window.DataGrid)}),h(p,`data-grid-table-${e}`,window.DataGrid,i.length),O(p,a,i),!r){let n=document.getElementById(`filter-val-${e}`),r=(n=!0)=>{n&&window.DataGrid&&(window.DataGrid.pagination.offset=0),j(e,t,k(),!0)},a;n&&n.addEventListener(`input`,()=>{clearTimeout(a),a=setTimeout(()=>r(!0),400)});let o=document.getElementById(`filter-col-${e}`),l=document.getElementById(`filter-op-${e}`);o&&o.addEventListener(`change`,()=>r(!0)),l&&l.addEventListener(`change`,()=>r(!0));let u=()=>{(Object.keys(window.DataGrid.pendingEdits).length>0||window.DataGrid.pendingInserts.length>1||window.DataGrid.pendingDeletes.size>0)&&!confirm(`You have unsaved changes. Are you sure you want to refresh and discard them?`)||(window.DataGrid.pendingEdits={},window.DataGrid.pendingInserts=[{}],window.DataGrid.pendingDeletes=new Set,window.DataGrid.history=[],window.DataGrid.currentTransaction=null,window.updateSidebarDirtyState?.(),r(!1))},d=document.getElementById(`btn-refresh-data-${e}`);d&&(d.onclick=u),window.DataGrid.refreshData=u;let f=async()=>{if(window.DataGrid.pagination.isLoading||!window.DataGrid.pagination.hasMore)return;window.DataGrid.pagination.isLoading=!0,window.DataGrid.pagination.offset+=window.DataGrid.pagination.limit;let t={where:k(),limit:window.DataGrid.pagination.limit,offset:window.DataGrid.pagination.offset,orderCol:window.DataGrid.sortState.col,orderAsc:window.DataGrid.sortState.asc};try{let n=await c(e,t);if(window.DataGrid.pagination.isLoading=!1,n.success&&n.data){let t=n.data.rows;window.DataGrid.pagination.hasMore=t.length===window.DataGrid.pagination.limit;let r=document.querySelector(`#data-grid-table-${e} tbody`);if(!r)return;let a=r.querySelector(`.ghost-row-tr`);a&&r.removeChild(a);let o=window.DataGrid.pagination.offset;if(t.forEach((e,t)=>{let n=document.createElement(`tr`);n.innerHTML=A(e,o+t,s,i),r.appendChild(n)}),a){let e=o+t.length,n=a.querySelector(`.row-header`);n&&(n.dataset.rowIdx=e),a.querySelectorAll(`.ghost-row`).forEach(t=>{t.dataset.rowIdx=e}),r.appendChild(a)}}}catch{window.DataGrid.pagination.isLoading=!1}};setTimeout(()=>{let t=document.getElementById(`data-grid-container-${e}`);t&&t.addEventListener(`scroll`,e=>{let{scrollTop:t,scrollHeight:n,clientHeight:r}=e.target;t+r>=n-50&&f()})},50)}}else o.innerHTML=`<div style="padding:24px; color:red;">Error: ${u.error}</div>`}catch(e){o.innerHTML=`<div style="padding:24px; color:red;">Failed to load data: ${e.message}</div>`}}var M=t({duplicateSchemaRows:()=>L,markSchemaRowDeleted:()=>F,saveSchemaEdits:()=>N,unmarkSchemaRowDeleted:()=>I,updateSchemaCell:()=>P});async function N(){if(!window.SchemaGrid)return;let{pendingEdits:e,pendingInserts:t,pendingDeletes:n}=window.SchemaGrid,r=window.AppState.currentTable;if(!r)return;let i=[];if(n)for(let e of n)i.push(`ALTER TABLE "${r}" DROP COLUMN "${e}";`);for(let[t,n]of Object.entries(e)){let e=t;if(n.name&&n.name!==t&&(i.push(`ALTER TABLE "${r}" RENAME COLUMN "${t}" TO "${n.name}";`),e=n.name),Object.keys(n).filter(e=>e!==`name`).length>0){let a=window.SchemaGrid.schema?.find(e=>e.name===t)||{},o=n.type===void 0?a.type:n.type,s=[],c=n.isPk===void 0?a.isPk:n.isPk,l=String(c).toUpperCase();if((l===`1`||l===`TRUE`||l===`YES`||l.includes(`PK`)||l===`KEY`)&&s.push(`PRIMARY KEY`),l.includes(`FK:`)){let e=l.match(/FK:\s*([^\s,]+)/i);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&s.push(`REFERENCES "${t[0]}"("${t[1]}")`)}}let u=n.nullable===void 0?a.nullable:n.nullable;(u===`0`||u===`No`||u===!1)&&s.push(`NOT NULL`);let d=n.defaultValue===void 0?a.defaultValue:n.defaultValue;d&&s.push(`DEFAULT '${String(d).replace(/'/g,`''`)}'`),i.push(`ALTER TABLE "${r}" MODIFY COLUMN "${e}" ${o} ${s.join(` `)};`)}}for(let e=0;e<t.length;e++){let n=t[e];if(Object.keys(n).length===0||!n.name||n.name.trim()===``)continue;let a=n.name.trim(),o=n.type||`TEXT`,s=[],c=String(n.isPk||``).toUpperCase();if((c===`1`||c===`TRUE`||c===`YES`||c.includes(`PK`)||c===`KEY`)&&s.push(`PRIMARY KEY`),c.includes(`FK:`)){let e=c.match(/FK:\s*([^\s,]+)/i);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&s.push(`REFERENCES "${t[0]}"("${t[1]}")`)}}(n.nullable===`0`||n.nullable===`false`||n.nullable===`No`)&&s.push(`NOT NULL`),n.defaultValue&&s.push(`DEFAULT '${n.defaultValue.replace(/'/g,`''`)}'`),i.push(`ALTER TABLE "${r}" ADD COLUMN "${a}" ${o} ${s.join(` `)};`)}if(window.SchemaGrid.pendingIndexEdits){for(let e of window.SchemaGrid.pendingIndexEdits.dropped)e&&e.trim()!==``&&i.push(`DROP INDEX "${e}";`);for(let e of window.SchemaGrid.pendingIndexEdits.added){let t=``;t=e.name&&e.name.trim()!==``?`"${e.name}"`:`"idx_${r}_${e.columns.join(`_`)}_${Date.now()}"`;let n=e.isUnique?`UNIQUE`:``,a=e.columns.map(e=>`"${e}"`).join(`, `);i.push(`CREATE ${n} INDEX IF NOT EXISTS ${t} ON "${r}" (${a});`)}}if(i.length===0)return;let a=!0,o=``;for(let e of i)try{let t=await d(e);if(!t.success){a=!1,o=t.error;break}}catch(e){a=!1,o=e.message;break}a?(window.renderCurrentView(),window.showToast&&window.showToast(`Schema saved successfully!`)):(o.includes(`near "MODIFY": syntax error`)?o=`SQLite: Currently does not support modifying existing column types or constraints directly. You can only Rename columns or Add new columns.`:o.includes(`syntax error`)&&(o=`SQLite: `+o),window.showToast?window.showToast(`Save failed: `+o,`error`):alert(`Save failed:
120
- `+o),document.querySelectorAll(`.cell-edited`).forEach(e=>{e.classList.remove(`cell-edited`),e.classList.add(`cell-error`)})),window.updateSidebarDirtyState?.()}function P(e,t,n,r=!0){if(r&&window.SchemaGrid.currentTransaction){let n=e.textContent;(n===`null`||e.classList.contains(`ghost-row`))&&(n=``),n!==t&&window.SchemaGrid.currentTransaction.push({td:e,oldVal:n,newVal:t})}let i=e.dataset.colKey;if(e.innerHTML=t||(e.dataset.insertIndex===void 0?`<span style="color:var(--color-text-soft)">-</span>`:`+ New`),e.dataset.insertIndex!==void 0){let r=parseInt(e.dataset.insertIndex);if(window.SchemaGrid.pendingInserts[r]||(window.SchemaGrid.pendingInserts[r]={}),t&&(window.SchemaGrid.pendingInserts[r][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`ghost-row`),r===window.SchemaGrid.pendingInserts.length-1)){e.closest(`tr`).classList.remove(`ghost-row-tr`),window.SchemaGrid.pendingInserts.push({});let t=document.querySelector(`#schema-grid-table-${window.AppState.currentTable} tbody`),i=document.createElement(`tr`);i.className=`ghost-row-tr`;let a=parseInt(e.dataset.rowIdx)+1;i.innerHTML+=`<td class="row-header" data-row-idx="${a}">*</td>`,n.forEach((e,t)=>{i.innerHTML+=`<td class="data-cell ghost-row" data-row-idx="${a}" data-col-idx="${t}" data-insert-index="${r+1}" data-col-key="${e}">+ New</td>`}),t.appendChild(i)}}else{let n=e.dataset.pk,r=e.dataset.original;r===`-`&&(r=``),t===r?(e.classList.remove(`cell-edited`),e.classList.remove(`cell-error`),window.SchemaGrid.pendingEdits[n]&&delete window.SchemaGrid.pendingEdits[n][i]):(window.SchemaGrid.pendingEdits[n]||(window.SchemaGrid.pendingEdits[n]={}),window.SchemaGrid.pendingEdits[n][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`cell-error`))}window.updateSidebarDirtyState?.()}function F(e,t=!0){let n=document.querySelector(`#schema-grid-table td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!n||n.classList.contains(`ghost-row-tr`)||n.classList.contains(`row-deleted`))return;let r=n.querySelector(`td.data-cell`)?.dataset.pk;r!==void 0&&(t&&window.SchemaGrid.currentTransaction&&window.SchemaGrid.currentTransaction.push({type:`delete`,rowIdx:e,pk:r}),window.SchemaGrid.pendingDeletes.add(r),n.classList.add(`row-deleted`)),window.updateSidebarDirtyState?.()}function I(e,t){let n=document.querySelector(`#schema-grid-table td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);n&&n.classList.remove(`row-deleted`),window.SchemaGrid.pendingDeletes.delete(t),window.updateSidebarDirtyState?.()}function L(e,t){e.forEach(e=>{let n=window.AppState.currentTable,r=document.querySelector(`#schema-grid-table-${n} td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!r||r.classList.contains(`ghost-row-tr`))return;let i=document.querySelector(`#schema-grid-table-${n} .ghost-row-tr`);i&&t.forEach((e,n)=>{let a=r.querySelector(`td.data-cell[data-col-idx="${n}"]`),o=i.querySelector(`td.data-cell[data-col-idx="${n}"]`);if(a&&o){let n=a.dataset.insertIndex===void 0?a.classList.contains(`cell-edited`)?window.SchemaGrid.pendingEdits[a.dataset.pk]?.[e]:a.dataset.original:window.SchemaGrid.pendingInserts[a.dataset.insertIndex][e];n!=null&&n!==`null`&&(e===`name`&&(n+=`_copy`),P(o,n,t,!0))}})})}function R(){let e=window.SchemaGrid;if(!e)return;let t=document.getElementById(`index-modal`);t&&t.remove();let n=[...e.indexes],r=[...e.pendingIndexEdits.added],i=new Set(e.pendingIndexEdits.dropped),a=n.filter(e=>!i.has(e.name)).concat(r),o=e.schema.map(e=>e.name);e.pendingInserts.forEach(e=>{e.name&&e.name.trim()!==``&&o.push(e.name.trim())});let s=o.map(e=>`<option value="${e}">${e}</option>`).join(``);t=document.createElement(`div`),t.id=`index-modal`,t.style.cssText=`
119
+ </th>`}),d+=`</tr></thead><tbody>`,n&&n.length>0&&n.forEach((e,t)=>{d+=`<tr>${j(e,t,s,i)}</tr>`}),d+=`<tr class="ghost-row-tr">`;let f=n?n.length:0;d+=`<td class="row-header" data-row-idx="${f}">*</td>`,i.forEach((e,t)=>{d+=`<td class="data-cell ghost-row" data-row-idx="${f}" data-col-idx="${t}" data-insert-index="0" data-col="${e}">+ New</td>`}),d+=`</tr></tbody></table>`;let p=document.getElementById(`data-grid-container-${e}`);if(!p)return;if(p.innerHTML=d,document.querySelectorAll(`th.sortable`).forEach(n=>{n.onclick=r=>{if(window.DataGrid&&window.DataGrid.isResizing)return;if(Object.keys(window.DataGrid.pendingEdits).length>0||window.DataGrid.pendingInserts.length>1||window.DataGrid.pendingDeletes.size>0){alert(`You have unsaved changes. Please save changes before sorting.`);return}let i=n.dataset.col;window.DataGrid.sortState.col===i?window.DataGrid.sortState.asc=!window.DataGrid.sortState.asc:(window.DataGrid.sortState.col=i,window.DataGrid.sortState.asc=!0),window.DataGrid.pagination.offset=0,M(e,t,A(),!0)},v(n,window.DataGrid)}),g(p,`data-grid-table-${e}`,window.DataGrid,i.length),k(p,a,i),!r){let n=document.getElementById(`filter-val-${e}`),r=(n=!0)=>{n&&window.DataGrid&&(window.DataGrid.pagination.offset=0),M(e,t,A(),!0)},a;n&&n.addEventListener(`input`,()=>{clearTimeout(a),a=setTimeout(()=>r(!0),400)});let o=document.getElementById(`filter-col-${e}`),c=document.getElementById(`filter-op-${e}`);o&&o.addEventListener(`change`,()=>r(!0)),c&&c.addEventListener(`change`,()=>r(!0));let u=()=>{(Object.keys(window.DataGrid.pendingEdits).length>0||window.DataGrid.pendingInserts.length>1||window.DataGrid.pendingDeletes.size>0)&&!confirm(`You have unsaved changes. Are you sure you want to refresh and discard them?`)||(window.DataGrid.pendingEdits={},window.DataGrid.pendingInserts=[{}],window.DataGrid.pendingDeletes=new Set,window.DataGrid.history=[],window.DataGrid.currentTransaction=null,window.updateSidebarDirtyState?.(),r(!1))},d=document.getElementById(`btn-refresh-data-${e}`);d&&(d.onclick=u),window.DataGrid.refreshData=u;let f=async()=>{if(window.DataGrid.pagination.isLoading||!window.DataGrid.pagination.hasMore)return;window.DataGrid.pagination.isLoading=!0,window.DataGrid.pagination.offset+=window.DataGrid.pagination.limit;let t={where:A(),limit:window.DataGrid.pagination.limit,offset:window.DataGrid.pagination.offset,orderCol:window.DataGrid.sortState.col,orderAsc:window.DataGrid.sortState.asc};try{let n=await l(e,t);if(window.DataGrid.pagination.isLoading=!1,n.success&&n.data){let t=n.data.rows;window.DataGrid.pagination.hasMore=t.length===window.DataGrid.pagination.limit;let r=document.querySelector(`#data-grid-table-${e} tbody`);if(!r)return;let a=r.querySelector(`.ghost-row-tr`);a&&r.removeChild(a);let o=window.DataGrid.pagination.offset;if(t.forEach((e,t)=>{let n=document.createElement(`tr`);n.innerHTML=j(e,o+t,s,i),r.appendChild(n)}),a){let e=o+t.length,n=a.querySelector(`.row-header`);n&&(n.dataset.rowIdx=e),a.querySelectorAll(`.ghost-row`).forEach(t=>{t.dataset.rowIdx=e}),r.appendChild(a)}}}catch{window.DataGrid.pagination.isLoading=!1}};setTimeout(()=>{let t=document.getElementById(`data-grid-container-${e}`);t&&t.addEventListener(`scroll`,e=>{let{scrollTop:t,scrollHeight:n,clientHeight:r}=e.target;t+r>=n-50&&f()})},50)}}else o.innerHTML=`<div style="padding:24px; color:red;">Error: ${c.error}</div>`}catch(e){o.innerHTML=`<div style="padding:24px; color:red;">Failed to load data: ${e.message}</div>`}}var N=t({duplicateSchemaRows:()=>R,markSchemaRowDeleted:()=>I,saveSchemaEdits:()=>P,unmarkSchemaRowDeleted:()=>L,updateSchemaCell:()=>F});async function P(){if(!window.SchemaGrid)return;let{pendingEdits:e,pendingInserts:t,pendingDeletes:n}=window.SchemaGrid,r=window.AppState.currentTable;if(!r)return;let i=[];if(n)for(let e of n)i.push(`ALTER TABLE "${r}" DROP COLUMN "${e}";`);for(let[t,n]of Object.entries(e)){let e=t;if(n.name&&n.name!==t&&(i.push(`ALTER TABLE "${r}" RENAME COLUMN "${t}" TO "${n.name}";`),e=n.name),Object.keys(n).filter(e=>e!==`name`).length>0){let a=window.SchemaGrid.schema?.find(e=>e.name===t)||{},o=n.type===void 0?a.type:n.type,s=[],c=n.isPk===void 0?a.isPk:n.isPk,l=String(c).toUpperCase();if((l===`1`||l===`TRUE`||l===`YES`||l.includes(`PK`)||l===`KEY`)&&s.push(`PRIMARY KEY`),l.includes(`FK:`)){let e=l.match(/FK:\s*([^\s,]+)/i);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&s.push(`REFERENCES "${t[0]}"("${t[1]}")`)}}let u=n.nullable===void 0?a.nullable:n.nullable;(u===`0`||u===`No`||u===!1)&&s.push(`NOT NULL`);let d=n.defaultValue===void 0?a.defaultValue:n.defaultValue;if(d&&s.push(`DEFAULT '${String(d).replace(/'/g,`''`)}'`),window.AppState.dbType===`sqlite`){alert(`SQLite does not support altering column types directly. Please recreate the table or use Raw SQL.`);return}else window.AppState.dbType===`postgres`?(i.push(`ALTER TABLE "${r}" ALTER COLUMN "${e}" TYPE ${o};`),s.includes(`NOT NULL`)&&i.push(`ALTER TABLE "${r}" ALTER COLUMN "${e}" SET NOT NULL;`),d&&i.push(`ALTER TABLE "${r}" ALTER COLUMN "${e}" SET DEFAULT '${String(d).replace(/'/g,`''`)}';`)):i.push(`ALTER TABLE "${r}" MODIFY COLUMN "${e}" ${o} ${s.join(` `)};`)}}for(let e=0;e<t.length;e++){let n=t[e];if(Object.keys(n).length===0||!n.name||n.name.trim()===``)continue;let a=n.name.trim(),o=n.type||`TEXT`,s=[],c=String(n.isPk||``).toUpperCase();if((c===`1`||c===`TRUE`||c===`YES`||c.includes(`PK`)||c===`KEY`)&&s.push(`PRIMARY KEY`),c.includes(`FK:`)){let e=c.match(/FK:\s*([^\s,]+)/i);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&s.push(`REFERENCES "${t[0]}"("${t[1]}")`)}}(n.nullable===`0`||n.nullable===`false`||n.nullable===`No`)&&s.push(`NOT NULL`),n.defaultValue&&s.push(`DEFAULT '${n.defaultValue.replace(/'/g,`''`)}'`),i.push(`ALTER TABLE "${r}" ADD COLUMN "${a}" ${o} ${s.join(` `)};`)}if(window.SchemaGrid.pendingIndexEdits){for(let e of window.SchemaGrid.pendingIndexEdits.dropped)e&&e.trim()!==``&&i.push(`DROP INDEX "${e}";`);for(let e of window.SchemaGrid.pendingIndexEdits.added){let t=``;t=e.name&&e.name.trim()!==``?`"${e.name}"`:`"idx_${r}_${e.columns.join(`_`)}_${Date.now()}"`;let n=e.isUnique?`UNIQUE`:``,a=e.columns.map(e=>`"${e}"`).join(`, `);i.push(`CREATE ${n} INDEX IF NOT EXISTS ${t} ON "${r}" (${a});`)}}if(i.length===0)return;let a=!0,o=``;for(let e of i)try{let t=await f(e);if(!t.success){a=!1,o=t.error;break}}catch(e){a=!1,o=e.message;break}a?(window.renderCurrentView(),window.showToast&&window.showToast(`Schema saved successfully!`)):(o.includes(`near "MODIFY": syntax error`)?o=`SQLite: Currently does not support modifying existing column types or constraints directly. You can only Rename columns or Add new columns.`:o.includes(`syntax error`)&&(o=`SQLite: `+o),window.showToast?window.showToast(`Save failed: `+o,`error`):alert(`Save failed:
120
+ `+o),document.querySelectorAll(`.cell-edited`).forEach(e=>{e.classList.remove(`cell-edited`),e.classList.add(`cell-error`)})),window.updateSidebarDirtyState?.()}function F(e,t,n,r=!0){if(r&&window.SchemaGrid.currentTransaction){let n=e.textContent;(n===`null`||e.classList.contains(`ghost-row`))&&(n=``),n!==t&&window.SchemaGrid.currentTransaction.push({td:e,oldVal:n,newVal:t})}let i=e.dataset.colKey;if(e.innerHTML=t||(e.dataset.insertIndex===void 0?`<span style="color:var(--color-text-soft)">-</span>`:`+ New`),e.dataset.insertIndex!==void 0){let r=parseInt(e.dataset.insertIndex);if(window.SchemaGrid.pendingInserts[r]||(window.SchemaGrid.pendingInserts[r]={}),t&&(window.SchemaGrid.pendingInserts[r][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`ghost-row`),r===window.SchemaGrid.pendingInserts.length-1)){e.closest(`tr`).classList.remove(`ghost-row-tr`),window.SchemaGrid.pendingInserts.push({});let t=document.querySelector(`#schema-grid-table-${window.AppState.currentTable} tbody`),i=document.createElement(`tr`);i.className=`ghost-row-tr`;let a=parseInt(e.dataset.rowIdx)+1;i.innerHTML+=`<td class="row-header" data-row-idx="${a}">*</td>`,n.forEach((e,t)=>{i.innerHTML+=`<td class="data-cell ghost-row" data-row-idx="${a}" data-col-idx="${t}" data-insert-index="${r+1}" data-col-key="${e}">+ New</td>`}),t.appendChild(i)}}else{let n=e.dataset.pk,r=e.dataset.original;r===`-`&&(r=``),t===r?(e.classList.remove(`cell-edited`),e.classList.remove(`cell-error`),window.SchemaGrid.pendingEdits[n]&&delete window.SchemaGrid.pendingEdits[n][i]):(window.SchemaGrid.pendingEdits[n]||(window.SchemaGrid.pendingEdits[n]={}),window.SchemaGrid.pendingEdits[n][i]=t,e.classList.add(`cell-edited`),e.classList.remove(`cell-error`))}window.updateSidebarDirtyState?.()}function I(e,t=!0){let n=document.querySelector(`#schema-grid-table td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!n||n.classList.contains(`ghost-row-tr`)||n.classList.contains(`row-deleted`))return;let r=n.querySelector(`td.data-cell`)?.dataset.pk;r!==void 0&&(t&&window.SchemaGrid.currentTransaction&&window.SchemaGrid.currentTransaction.push({type:`delete`,rowIdx:e,pk:r}),window.SchemaGrid.pendingDeletes.add(r),n.classList.add(`row-deleted`)),window.updateSidebarDirtyState?.()}function L(e,t){let n=document.querySelector(`#schema-grid-table td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);n&&n.classList.remove(`row-deleted`),window.SchemaGrid.pendingDeletes.delete(t),window.updateSidebarDirtyState?.()}function R(e,t){e.forEach(e=>{let n=window.AppState.currentTable,r=document.querySelector(`#schema-grid-table-${n} td.data-cell[data-row-idx="${e}"]`)?.closest(`tr`);if(!r||r.classList.contains(`ghost-row-tr`))return;let i=document.querySelector(`#schema-grid-table-${n} .ghost-row-tr`);i&&t.forEach((e,n)=>{let a=r.querySelector(`td.data-cell[data-col-idx="${n}"]`),o=i.querySelector(`td.data-cell[data-col-idx="${n}"]`);if(a&&o){let n=a.dataset.insertIndex===void 0?a.classList.contains(`cell-edited`)?window.SchemaGrid.pendingEdits[a.dataset.pk]?.[e]:a.dataset.original:window.SchemaGrid.pendingInserts[a.dataset.insertIndex][e];n!=null&&n!==`null`&&(e===`name`&&(n+=`_copy`),F(o,n,t,!0))}})})}function z(){let e=window.SchemaGrid;if(!e)return;let t=document.getElementById(`index-modal`);t&&t.remove();let n=[...e.indexes],r=[...e.pendingIndexEdits.added],i=new Set(e.pendingIndexEdits.dropped),a=n.filter(e=>!i.has(e.name)).concat(r),o=e.schema.map(e=>e.name);e.pendingInserts.forEach(e=>{e.name&&e.name.trim()!==``&&o.push(e.name.trim())});let s=o.map(e=>`<option value="${e}">${e}</option>`).join(``);t=document.createElement(`div`),t.id=`index-modal`,t.style.cssText=`
121
121
  position: fixed; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.5);
122
122
  display:flex; justify-content:center; align-items:center; z-index:9999;
123
123
  `,t.innerHTML=`
@@ -154,7 +154,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
154
154
  <div style="width:60px; font-size:12px; text-align:center;">${e.isUnique?`UNIQUE`:``}</div>
155
155
  <button class="icon-btn delete-idx-btn" data-idx="${t}" style="color:var(--color-error); border:none; background:none; cursor:pointer;"><span class="material-symbols-outlined" style="font-size:18px;">delete</span></button>
156
156
  </div>
157
- `).join(``);a.length===0&&(e=`<div style="padding:16px; text-align:center; color:var(--color-text-secondary);">No indexes yet.</div>`),document.getElementById(`idx-list-container`).innerHTML=e,document.querySelectorAll(`.delete-idx-btn`).forEach(e=>{e.onclick=e=>{let t=parseInt(e.currentTarget.dataset.idx,10);a.splice(t,1),l()}})};l(),document.getElementById(`add-idx-btn`).onclick=()=>{let e=document.getElementById(`new-idx-name`).value.trim(),t=document.getElementById(`new-idx-cols`),n=Array.from(t.selectedOptions).map(e=>e.value),r=document.getElementById(`new-idx-unique`).checked;if(n.length===0){alert(`Please select at least one column for the index.`);return}a.push({name:e,columns:n,isUnique:r}),document.getElementById(`new-idx-name`).value=``,document.getElementById(`new-idx-unique`).checked=!1,t.selectedIndex=-1,l()},document.getElementById(`save-idx-btn`).onclick=()=>{let t=[],r=new Set;n.forEach(e=>{a.find(t=>t.name===e.name&&JSON.stringify(t.columns)===JSON.stringify(e.columns))||r.add(e.name)}),a.forEach(e=>{n.find(t=>t.name===e.name&&JSON.stringify(t.columns)===JSON.stringify(e.columns))||t.push(e)}),e.pendingIndexEdits.added=t,e.pendingIndexEdits.dropped=Array.from(r),window.updateSidebarDirtyState?.(),window.renderSchemaGrid(),c()}}async function z(e,t){if(!window.SchemaGrid)return;let n=document.getElementById(`pkfk-modal`);n&&n.remove();let r=e.dataset.insertIndex!==void 0,i=t.includes(`PK`),a=t.includes(`FK`),o=``,s=``;if(a){let e=t.match(/FK \((.*?)\)/);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&(o=t[0],s=t[1])}else{let e=t.match(/FK:\s*([^\s,]+)/i);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&(o=t[0],s=t[1])}}}n=document.createElement(`div`),n.id=`pkfk-modal`,n.style.cssText=`
157
+ `).join(``);a.length===0&&(e=`<div style="padding:16px; text-align:center; color:var(--color-text-secondary);">No indexes yet.</div>`),document.getElementById(`idx-list-container`).innerHTML=e,document.querySelectorAll(`.delete-idx-btn`).forEach(e=>{e.onclick=e=>{let t=parseInt(e.currentTarget.dataset.idx,10);a.splice(t,1),l()}})};l(),document.getElementById(`add-idx-btn`).onclick=()=>{let e=document.getElementById(`new-idx-name`).value.trim(),t=document.getElementById(`new-idx-cols`),n=Array.from(t.selectedOptions).map(e=>e.value),r=document.getElementById(`new-idx-unique`).checked;if(n.length===0){alert(`Please select at least one column for the index.`);return}a.push({name:e,columns:n,isUnique:r}),document.getElementById(`new-idx-name`).value=``,document.getElementById(`new-idx-unique`).checked=!1,t.selectedIndex=-1,l()},document.getElementById(`save-idx-btn`).onclick=()=>{let t=[],r=new Set;n.forEach(e=>{a.find(t=>t.name===e.name&&JSON.stringify(t.columns)===JSON.stringify(e.columns))||r.add(e.name)}),a.forEach(e=>{n.find(t=>t.name===e.name&&JSON.stringify(t.columns)===JSON.stringify(e.columns))||t.push(e)}),e.pendingIndexEdits.added=t,e.pendingIndexEdits.dropped=Array.from(r),window.updateSidebarDirtyState?.(),window.renderSchemaGrid(),c()}}async function B(e,t){if(!window.SchemaGrid)return;let n=document.getElementById(`pkfk-modal`);n&&n.remove();let r=e.dataset.insertIndex!==void 0,i=t.includes(`PK`),a=t.includes(`FK`),o=``,s=``;if(a){let e=t.match(/FK \((.*?)\)/);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&(o=t[0],s=t[1])}else{let e=t.match(/FK:\s*([^\s,]+)/i);if(e&&e[1]){let t=e[1].split(`.`);t.length===2&&(o=t[0],s=t[1])}}}n=document.createElement(`div`),n.id=`pkfk-modal`,n.style.cssText=`
158
158
  position: fixed; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.5);
159
159
  display:flex; justify-content:center; align-items:center; z-index:9999;
160
160
  `,n.innerHTML=`
@@ -198,7 +198,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
198
198
  <button id="save-pkfk-btn" class="primary" style="padding:6px 16px; border-radius:4px; border:none; cursor:pointer;">Save</button>
199
199
  </div>
200
200
  </div>
201
- `,document.body.appendChild(n);let c=()=>n.remove();document.getElementById(`close-pkfk-modal`).onclick=c,document.getElementById(`cancel-pkfk-btn`).onclick=c;let l=document.getElementById(`modal-is-fk`),u=document.getElementById(`fk-settings-container`),d=document.getElementById(`modal-fk-table`),f=document.getElementById(`modal-fk-col`);l.addEventListener(`change`,e=>{u.style.display=e.target.checked?`flex`:`none`});try{let e=await(await fetch(`/api/tables`)).json();e.success&&e.data&&(d.innerHTML=`<option value="">-- Select Table --</option>`+e.data.map(e=>`<option value="${e}" ${e===o?`selected`:``}>${e}</option>`).join(``),o&&p(o,s))}catch{d.innerHTML=`<option value="">Error loading tables</option>`}async function p(e,t=``){f.disabled=!0,f.innerHTML=`<option value="">Loading columns...</option>`;try{let n=await(await fetch(`/api/tables/${e}/schema`)).json();n.success&&n.data&&(f.innerHTML=`<option value="">-- Select Column --</option>`+n.data.map(e=>`<option value="${e.name}" ${e.name===t?`selected`:``}>${e.name}</option>`).join(``),f.disabled=!1)}catch{f.innerHTML=`<option value="">Error loading columns</option>`}}d.addEventListener(`change`,e=>{let t=e.target.value;t?p(t):(f.innerHTML=`<option value="">Select a table first</option>`,f.disabled=!0)}),document.getElementById(`save-pkfk-btn`).onclick=()=>{let t=document.getElementById(`modal-is-pk`).checked,n=document.getElementById(`modal-is-fk`).checked,r=d.value,l=f.value;if(t===i&&n===a&&r===o&&l===s){c();return}let u=``;if(t&&n){if(!r||!l){alert(`Please select both Target Table and Target Column for the Foreign Key.`);return}u=`PK, FK: ${r}.${l}`}else if(t)u=`PK`;else if(n){if(!r||!l){alert(`Please select both Target Table and Target Column for the Foreign Key.`);return}u=`FK: ${r}.${l}`}window.SchemaGrid.currentTransaction=[];let p=[`name`,`type`,`isPk`,`nullable`,`defaultValue`,`indexing`];D(async()=>{let{updateSchemaCell:e}=await Promise.resolve().then(()=>M);return{updateSchemaCell:e}},void 0,import.meta.url).then(({updateSchemaCell:t})=>{t(e,u,p),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null}),c()}}function B(e,t){e.addEventListener(`click`,e=>{e.target.closest(`.manage-indexes-cell`)&&R()}),e.addEventListener(`dblclick`,e=>{let n=e.target.closest(`td.data-cell`);if(!n||n.querySelector(`input, select`))return;let r=n.dataset.colKey;n.dataset.insertIndex;let i=n.textContent===`-`||n.textContent===`+ New`||n.textContent===`No`||n.textContent===`null`?``:n.textContent===`Yes`?`1`:n.textContent,a;if(r===`isPk`){z(n,n.textContent);return}else if(r===`nullable`)a=document.createElement(`select`),[`No`,`Yes`].forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,(e===`Yes`&&i===`1`||e===`No`&&i===``)&&(t.selected=!0),a.appendChild(t)});else if(r===`type`){a=document.createElement(`select`);let e=[`INTEGER`,`TEXT`,`REAL`,`BLOB`,`NUMERIC`,`BOOLEAN`,`DATE`,`DATETIME`,`JSON`,`VARCHAR(255)`,`DECIMAL(10,2)`,`UUID`];i&&!e.some(e=>e.toUpperCase()===i.toUpperCase())&&e.unshift(i),e.forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,e.toUpperCase()===i.toUpperCase()&&(t.selected=!0),a.appendChild(t)})}else a=document.createElement(`input`),a.type=`text`,a.value=i;n.innerHTML=``,n.appendChild(a),a.style.width=`100%`,a.addEventListener(`keydown`,e=>{e.key===`Enter`&&a.blur()}),a.focus();let o=()=>{let e=a.value;window.SchemaGrid.currentTransaction=[],P(n,e,t),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null};a.addEventListener(`blur`,()=>{o()})})}async function V(e,t,n=null){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let r=document.getElementById(`table-name`);r&&(r.textContent=e+` (Schema)`);let i=n||document.getElementById(`main-content`);i.innerHTML=`<div style='padding:24px;'>Loading Schema...</div>`;try{let[n,r]=await Promise.all([l(e),u(e)]);if(n.success&&n.data){let a=n.data,o=r.success&&r.data?r.data:[];window.SchemaGrid={schema:a,indexes:o,pendingEdits:{},pendingIndexEdits:{added:[],dropped:[]},pendingInserts:[{}],pendingDeletes:new Set,selectedCell:null,history:[],currentTransaction:null,sortState:{colKey:null,asc:!0},filterText:``,isResizing:!1,selection:{startRow:-1,startCol:-1,endRow:-1,endCol:-1,isDragging:!1}},window.TableStates&&window.TableStates[e]&&(window.TableStates[e].schemaGrid=window.SchemaGrid),i.innerHTML=`
201
+ `,document.body.appendChild(n);let c=()=>n.remove();document.getElementById(`close-pkfk-modal`).onclick=c,document.getElementById(`cancel-pkfk-btn`).onclick=c;let l=document.getElementById(`modal-is-fk`),u=document.getElementById(`fk-settings-container`),d=document.getElementById(`modal-fk-table`),f=document.getElementById(`modal-fk-col`);l.addEventListener(`change`,e=>{u.style.display=e.target.checked?`flex`:`none`});try{let e=await(await fetch(`/api/tables`)).json();e.success&&e.data&&(d.innerHTML=`<option value="">-- Select Table --</option>`+e.data.map(e=>`<option value="${e}" ${e===o?`selected`:``}>${e}</option>`).join(``),o&&p(o,s))}catch{d.innerHTML=`<option value="">Error loading tables</option>`}async function p(e,t=``){f.disabled=!0,f.innerHTML=`<option value="">Loading columns...</option>`;try{let n=await(await fetch(`/api/tables/${e}/schema`)).json();n.success&&n.data&&(f.innerHTML=`<option value="">-- Select Column --</option>`+n.data.map(e=>`<option value="${e.name}" ${e.name===t?`selected`:``}>${e.name}</option>`).join(``),f.disabled=!1)}catch{f.innerHTML=`<option value="">Error loading columns</option>`}}d.addEventListener(`change`,e=>{let t=e.target.value;t?p(t):(f.innerHTML=`<option value="">Select a table first</option>`,f.disabled=!0)}),document.getElementById(`save-pkfk-btn`).onclick=()=>{let t=document.getElementById(`modal-is-pk`).checked,n=document.getElementById(`modal-is-fk`).checked,r=d.value,l=f.value;if(t===i&&n===a&&r===o&&l===s){c();return}let u=``;if(t&&n){if(!r||!l){alert(`Please select both Target Table and Target Column for the Foreign Key.`);return}u=`PK, FK: ${r}.${l}`}else if(t)u=`PK`;else if(n){if(!r||!l){alert(`Please select both Target Table and Target Column for the Foreign Key.`);return}u=`FK: ${r}.${l}`}window.SchemaGrid.currentTransaction=[];let p=[`name`,`type`,`isPk`,`nullable`,`defaultValue`,`indexing`];O(async()=>{let{updateSchemaCell:e}=await Promise.resolve().then(()=>N);return{updateSchemaCell:e}},void 0,import.meta.url).then(({updateSchemaCell:t})=>{t(e,u,p),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null}),c()}}function V(e,t){e.addEventListener(`click`,e=>{e.target.closest(`.manage-indexes-cell`)&&z()}),e.addEventListener(`dblclick`,e=>{let n=e.target.closest(`td.data-cell`);if(!n||n.querySelector(`input, select`))return;let r=n.dataset.colKey;n.dataset.insertIndex;let i=n.textContent===`-`||n.textContent===`+ New`||n.textContent===`No`||n.textContent===`null`?``:n.textContent===`Yes`?`1`:n.textContent,a;if(r===`isPk`){B(n,n.textContent);return}else if(r===`nullable`)a=document.createElement(`select`),[`No`,`Yes`].forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,(e===`Yes`&&i===`1`||e===`No`&&i===``)&&(t.selected=!0),a.appendChild(t)});else if(r===`type`){a=document.createElement(`select`);let e=[`INTEGER`,`TEXT`,`REAL`,`BLOB`,`NUMERIC`,`BOOLEAN`,`DATE`,`DATETIME`,`JSON`,`VARCHAR(255)`,`DECIMAL(10,2)`,`UUID`];i&&!e.some(e=>e.toUpperCase()===i.toUpperCase())&&e.unshift(i),e.forEach(e=>{let t=document.createElement(`option`);t.value=e,t.textContent=e,e.toUpperCase()===i.toUpperCase()&&(t.selected=!0),a.appendChild(t)})}else a=document.createElement(`input`),a.type=`text`,a.value=i;n.innerHTML=``,n.appendChild(a),a.style.width=`100%`,a.addEventListener(`keydown`,e=>{e.key===`Enter`&&a.blur()}),a.focus();let o=()=>{let e=a.value;window.SchemaGrid.currentTransaction=[],F(n,e,t),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null};a.addEventListener(`blur`,()=>{o()})})}async function H(e,t,n=null){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let r=document.getElementById(`table-name`);r&&(r.textContent=e+` (Schema)`);let i=n||document.getElementById(`main-content`);i.innerHTML=`<div style='padding:24px;'>Loading Schema...</div>`;try{let[n,r]=await Promise.all([u(e),d(e)]);if(n.success&&n.data){let a=n.data,o=r.success&&r.data?r.data:[];window.SchemaGrid={schema:a,indexes:o,pendingEdits:{},pendingIndexEdits:{added:[],dropped:[]},pendingInserts:[{}],pendingDeletes:new Set,selectedCell:null,history:[],currentTransaction:null,sortState:{colKey:null,asc:!0},filterText:``,isResizing:!1,selection:{startRow:-1,startCol:-1,endRow:-1,endCol:-1,isDragging:!1}},window.TableStates&&window.TableStates[e]&&(window.TableStates[e].schemaGrid=window.SchemaGrid),i.innerHTML=`
202
202
  <div class="toolbar">
203
203
  <div class="filter-group">
204
204
  <div class="filter-icon-container">
@@ -218,7 +218,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
218
218
  </div>
219
219
  </th>`}),a+=`</tr></thead><tbody>`,n&&n.length>0&&n.forEach((e,t)=>{a+=`<tr><td class="row-header" data-row-idx="${t}">${t+1}</td>`,r.forEach((r,i)=>{if(r===`indexing`){if(t===0){let e=(n?n.length:0)+1,t=window.SchemaGrid.indexes.length,r=window.SchemaGrid.pendingIndexEdits.added.length,i=window.SchemaGrid.pendingIndexEdits.dropped.length,o=t+r-i;a+=`<td class="data-cell manage-indexes-cell" rowspan="${e}" style="text-align:center; vertical-align:middle; cursor:pointer; color:var(--color-brand-500); font-weight:500; border-left: 1px solid var(--color-border);">
220
220
  Manage Indexes (${o})
221
- </td>`}return}let o=e[r];if(r===`isPk`){let t=o,n=!!e.fkTarget;o=t&&n?`PK, FK (${e.fkTarget.table}.${e.fkTarget.column})`:t?`PK`:n?`FK (${e.fkTarget.table}.${e.fkTarget.column})`:`-`}else r===`nullable`?o=o?`Yes`:`No`:o??=``;let s=String(o).replace(/"/g,`&quot;`),c=o===``?`<span style="color:var(--color-text-soft)">-</span>`:String(o).replace(/</g,`&lt;`);a+=`<td class="data-cell" data-row-idx="${t}" data-col-idx="${i}" data-pk="${e.name}" data-col-key="${r}" data-original="${s}">${c}</td>`}),a+=`</tr>`}),a+=`<tr class="ghost-row-tr">`;let o=n?n.length:0;a+=`<td class="row-header" data-row-idx="${o}">*</td>`,r.forEach((e,t)=>{e!==`indexing`&&(a+=`<td class="data-cell ghost-row" data-row-idx="${o}" data-col-idx="${t}" data-insert-index="0" data-col-key="${e}">+ New</td>`)}),a+=`</tr></tbody></table>`,t.innerHTML=a,document.querySelectorAll(`#schema-grid-table-${e} th.sortable`).forEach(e=>{e.onclick=t=>{if(window.SchemaGrid.isResizing)return;if(Object.keys(window.SchemaGrid.pendingEdits).length>0||window.SchemaGrid.pendingInserts.length>1||window.SchemaGrid.pendingDeletes.size>0||window.SchemaGrid.pendingIndexEdits.added.length>0||window.SchemaGrid.pendingIndexEdits.dropped.length>0){alert(`You have unsaved changes! Please press Ctrl+S to save them before sorting.`);return}let n=e.dataset.colKey;window.SchemaGrid.sortState.colKey===n?window.SchemaGrid.sortState.asc=!window.SchemaGrid.sortState.asc:(window.SchemaGrid.sortState.colKey=n,window.SchemaGrid.sortState.asc=!0),window.SchemaGrid.selection={startRow:-1,startCol:-1,endRow:-1,endCol:-1,isDragging:!1},window.renderSchemaGrid()},_(e,window.SchemaGrid)}),h(t,`schema-grid-table-${e}`,window.SchemaGrid,r.length),B(t,r)},window.renderSchemaGrid();let s=document.getElementById(`schema-search-val-${e}`);s&&s.addEventListener(`input`,e=>{window.SchemaGrid.filterText=e.target.value,window.SchemaGrid.selection={startRow:-1,startCol:-1,endRow:-1,endCol:-1,isDragging:!1},window.renderSchemaGrid()});let c=document.getElementById(`btn-refresh-schema-${e}`);c&&(c.onclick=()=>{(Object.keys(window.SchemaGrid.pendingEdits).length>0||window.SchemaGrid.pendingInserts.length>1||window.SchemaGrid.pendingDeletes.size>0||window.SchemaGrid.pendingIndexEdits.added.length>0||window.SchemaGrid.pendingIndexEdits.dropped.length>0)&&!confirm(`You have unsaved changes. Are you sure you want to refresh and discard them?`)||(window.SchemaGrid.pendingEdits={},window.SchemaGrid.pendingInserts=[{}],window.SchemaGrid.pendingDeletes.clear(),window.SchemaGrid.pendingIndexEdits={added:[],dropped:[]},window.SchemaGrid.history=[],window.SchemaGrid.currentTransaction=null,window.updateSidebarDirtyState?.(),V(e,t,document.getElementById(`view-schema-btn-${e}`)))})}else i.innerHTML=`<div style="padding:24px; color:red;">Error: ${n.error}</div>`}catch(e){i.innerHTML=`<div style="padding:24px; color:red;">Failed to load schema: ${e.message}</div>`}}function H(e,t){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let n=document.getElementById(`table-name`);n&&(n.textContent=`SQL Console`);let r=document.getElementById(`main-content`);r.innerHTML=`
221
+ </td>`}return}let o=e[r];if(r===`isPk`){let t=o,n=!!e.fkTarget;o=t&&n?`PK, FK (${e.fkTarget.table}.${e.fkTarget.column})`:t?`PK`:n?`FK (${e.fkTarget.table}.${e.fkTarget.column})`:`-`}else r===`nullable`?o=o?`Yes`:`No`:o??=``;let s=String(o).replace(/"/g,`&quot;`),c=o===``?`<span style="color:var(--color-text-soft)">-</span>`:String(o).replace(/</g,`&lt;`);a+=`<td class="data-cell" data-row-idx="${t}" data-col-idx="${i}" data-pk="${e.name}" data-col-key="${r}" data-original="${s}">${c}</td>`}),a+=`</tr>`}),a+=`<tr class="ghost-row-tr">`;let o=n?n.length:0;a+=`<td class="row-header" data-row-idx="${o}">*</td>`,r.forEach((e,t)=>{e!==`indexing`&&(a+=`<td class="data-cell ghost-row" data-row-idx="${o}" data-col-idx="${t}" data-insert-index="0" data-col-key="${e}">+ New</td>`)}),a+=`</tr></tbody></table>`,t.innerHTML=a,document.querySelectorAll(`#schema-grid-table-${e} th.sortable`).forEach(e=>{e.onclick=t=>{if(window.SchemaGrid.isResizing)return;if(Object.keys(window.SchemaGrid.pendingEdits).length>0||window.SchemaGrid.pendingInserts.length>1||window.SchemaGrid.pendingDeletes.size>0||window.SchemaGrid.pendingIndexEdits.added.length>0||window.SchemaGrid.pendingIndexEdits.dropped.length>0){alert(`You have unsaved changes! Please press Ctrl+S to save them before sorting.`);return}let n=e.dataset.colKey;window.SchemaGrid.sortState.colKey===n?window.SchemaGrid.sortState.asc=!window.SchemaGrid.sortState.asc:(window.SchemaGrid.sortState.colKey=n,window.SchemaGrid.sortState.asc=!0),window.SchemaGrid.selection={startRow:-1,startCol:-1,endRow:-1,endCol:-1,isDragging:!1},window.renderSchemaGrid()},v(e,window.SchemaGrid)}),g(t,`schema-grid-table-${e}`,window.SchemaGrid,r.length),V(t,r)},window.renderSchemaGrid();let s=document.getElementById(`schema-search-val-${e}`);s&&s.addEventListener(`input`,e=>{window.SchemaGrid.filterText=e.target.value,window.SchemaGrid.selection={startRow:-1,startCol:-1,endRow:-1,endCol:-1,isDragging:!1},window.renderSchemaGrid()});let c=document.getElementById(`btn-refresh-schema-${e}`);c&&(c.onclick=()=>{(Object.keys(window.SchemaGrid.pendingEdits).length>0||window.SchemaGrid.pendingInserts.length>1||window.SchemaGrid.pendingDeletes.size>0||window.SchemaGrid.pendingIndexEdits.added.length>0||window.SchemaGrid.pendingIndexEdits.dropped.length>0)&&!confirm(`You have unsaved changes. Are you sure you want to refresh and discard them?`)||(window.SchemaGrid.pendingEdits={},window.SchemaGrid.pendingInserts=[{}],window.SchemaGrid.pendingDeletes.clear(),window.SchemaGrid.pendingIndexEdits={added:[],dropped:[]},window.SchemaGrid.history=[],window.SchemaGrid.currentTransaction=null,window.updateSidebarDirtyState?.(),H(e,t,document.getElementById(`view-schema-btn-${e}`)))})}else i.innerHTML=`<div style="padding:24px; color:red;">Error: ${n.error}</div>`}catch(e){i.innerHTML=`<div style="padding:24px; color:red;">Failed to load schema: ${e.message}</div>`}}function U(e,t){document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),t&&t.classList.add(`active`);let n=document.getElementById(`table-name`);n&&(n.textContent=`SQL Console`);let r=document.getElementById(`main-content`);r.innerHTML=`
222
222
  <div id="console-container" style="display: flex; flex-direction: column; flex: 1; height: 100%; min-width: 0;">
223
223
  <div id="console-editor-pane" style="flex: 1; display: flex; flex-direction: column; border-bottom: 1px solid var(--color-border); position: relative; min-height: 200px;">
224
224
  <div id="sql-editor" style="flex: 1; font-size: 14px;"></div>
@@ -235,7 +235,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
235
235
  </div>
236
236
  `;let i=window.ace.edit(`sql-editor`);i.setTheme(`ace/theme/chrome`),i.session.setMode(`ace/mode/sql`),i.setOptions({showPrintMargin:!1,fontSize:`14px`,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,highlightActiveLine:!0}),window.AppState.lastQuery?i.setValue(window.AppState.lastQuery,1):i.setValue(`-- Enter your SQL query here
237
237
  SELECT * FROM sqlite_master;
238
- `,1),i.focus();let a=async()=>{let e=i.getValue().trim();if(!e)return;window.AppState.lastQuery=e;let t=document.getElementById(`console-table-container`),n=document.getElementById(`console-results-header`);n.textContent=`EXECUTING...`,n.style.color=`var(--color-primary)`,t.innerHTML=`<div style="padding: 24px; text-align: center; color: var(--color-text-soft);">Executing query...</div>`;try{let r=await d(e);if(!r.success){n.textContent=`ERROR`,n.style.color=`red`,t.innerHTML=`<div style="padding: 24px; color: red; font-family: monospace; white-space: pre-wrap;">${r.error}</div>`;return}let i=r.data.rows||[];if(n.textContent=`SUCCESS - ${i.length} rows returned`,n.style.color=`green`,i.length===0){t.innerHTML=`<div style="padding: 24px; text-align: center; color: var(--color-text-soft);">0 rows returned.</div>`;return}let a=Object.keys(i[0]),o=document.createElement(`table`);o.className=`data-table`;let s=document.createElement(`thead`),c=document.createElement(`tr`),l=document.createElement(`th`);l.className=`row-header`,l.textContent=`#`,c.appendChild(l),a.forEach(e=>{let t=document.createElement(`th`);t.textContent=e;let n=document.createElement(`div`);n.className=`resizer`,t.appendChild(n),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>{e.preventDefault(),e.stopPropagation();let n=e.pageX,r=t.offsetWidth,i=e=>{let i=r+(e.pageX-n);t.style.width=i+`px`,t.style.minWidth=i+`px`,t.style.maxWidth=i+`px`},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),document.body.style.cursor=``};document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}),c.appendChild(t)}),s.appendChild(c),o.appendChild(s);let u=document.createElement(`tbody`);i.forEach((e,t)=>{let n=document.createElement(`tr`),r=document.createElement(`td`);r.className=`row-header`,r.textContent=t+1,n.appendChild(r),a.forEach(t=>{let r=document.createElement(`td`),i=e[t];if(i===null){let e=document.createElement(`span`);e.textContent=`NULL`,e.style.color=`var(--color-text-soft)`,e.style.fontStyle=`italic`,r.appendChild(e)}else r.textContent=String(i);n.appendChild(r)}),u.appendChild(n)}),o.appendChild(u),t.innerHTML=``,t.appendChild(o)}catch(e){n.textContent=`ERROR`,n.style.color=`red`,t.innerHTML=`<div style="padding: 24px; color: red; font-family: monospace; white-space: pre-wrap;">${e.message}</div>`}};document.getElementById(`run-sql-btn`).onclick=a,i.commands.addCommand({name:`run`,bindKey:{win:`Ctrl-Enter`,mac:`Command-Enter`},exec:function(){a()}})}var U=document.getElementById(`header-container`),W=document.getElementById(`sidebar-container`),G=document.getElementById(`tab-container`);U.innerHTML=n,W.innerHTML=r,G.innerHTML=i,window.AppState={currentTable:null,currentTab:`data-btn`,currentTableBtnElement:null},window.TableStates={},window.ViewCache={},window.updateSidebarDirtyState=function(){document.querySelectorAll(`.table-btn`).forEach(e=>{let t=e.dataset.table,n=e.querySelector(`span`).textContent,r=t||n.replace(/\s*\*$/,``),i=window.TableStates[r],a=!1;if(i){if(i.dataGrid){let e=i.dataGrid;(Object.keys(e.pendingEdits||{}).length>0||e.pendingInserts&&e.pendingInserts.length>1||e.pendingDeletes&&e.pendingDeletes.size>0)&&(a=!0)}if(i.schemaGrid){let e=i.schemaGrid,t=e.pendingIndexEdits&&(e.pendingIndexEdits.added.length>0||e.pendingIndexEdits.dropped.length>0);(Object.keys(e.pendingEdits||{}).length>0||e.pendingInserts&&e.pendingInserts.length>1||e.pendingDeletes&&e.pendingDeletes.size>0||t)&&(a=!0)}}let o=e.querySelector(`span`),s=o.textContent.replace(/\s*\*$/,``);a?(o.textContent=s+` *`,o.style.fontWeight=`bold`):(o.textContent=s,o.style.fontWeight=`normal`)})},window.handleSwitchTab=function(e){document.querySelectorAll(`.tab-btn`).forEach(e=>e.classList.remove(`isCurrentTab`));let t=document.getElementById(e);if(t&&t.classList.add(`isCurrentTab`),window.AppState.currentTab=e,e===`erd-btn`||e===`sql-btn`||e===`status-btn`)window.AppState.currentTable=null,window.AppState.currentTableBtnElement=null,document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`));else if((e===`data-btn`||e===`schema-btn`)&&!window.AppState.currentTable){let e=document.querySelector(`.table-btn`);e&&(window.AppState.currentTable=e.querySelector(`span`).textContent,window.AppState.currentTableBtnElement=e,e.classList.add(`active`))}window.renderCurrentView()},window.renderEmptyState=function(e){e.innerHTML=`
238
+ `,1),i.focus();let a=async()=>{let e=i.getValue().trim();if(!e)return;window.AppState.lastQuery=e;let t=document.getElementById(`console-table-container`),n=document.getElementById(`console-results-header`);n.textContent=`EXECUTING...`,n.style.color=`var(--color-primary)`,t.innerHTML=`<div style="padding: 24px; text-align: center; color: var(--color-text-soft);">Executing query...</div>`;try{let r=await f(e);if(!r.success){n.textContent=`ERROR`,n.style.color=`red`,t.innerHTML=`<div style="padding: 24px; color: red; font-family: monospace; white-space: pre-wrap;">${r.error}</div>`;return}let i=r.data.rows||[];if(n.textContent=`SUCCESS - ${i.length} rows returned`,n.style.color=`green`,i.length===0){t.innerHTML=`<div style="padding: 24px; text-align: center; color: var(--color-text-soft);">0 rows returned.</div>`;return}let a=Object.keys(i[0]),o=document.createElement(`table`);o.className=`data-table`;let s=document.createElement(`thead`),c=document.createElement(`tr`),l=document.createElement(`th`);l.className=`row-header`,l.textContent=`#`,c.appendChild(l),a.forEach(e=>{let t=document.createElement(`th`);t.textContent=e;let n=document.createElement(`div`);n.className=`resizer`,t.appendChild(n),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>{e.preventDefault(),e.stopPropagation();let n=e.pageX,r=t.offsetWidth,i=e=>{let i=r+(e.pageX-n);t.style.width=i+`px`,t.style.minWidth=i+`px`,t.style.maxWidth=i+`px`},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),document.body.style.cursor=``};document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}),c.appendChild(t)}),s.appendChild(c),o.appendChild(s);let u=document.createElement(`tbody`);i.forEach((e,t)=>{let n=document.createElement(`tr`),r=document.createElement(`td`);r.className=`row-header`,r.textContent=t+1,n.appendChild(r),a.forEach(t=>{let r=document.createElement(`td`),i=e[t];if(i===null){let e=document.createElement(`span`);e.textContent=`NULL`,e.style.color=`var(--color-text-soft)`,e.style.fontStyle=`italic`,r.appendChild(e)}else r.textContent=String(i);n.appendChild(r)}),u.appendChild(n)}),o.appendChild(u),t.innerHTML=``,t.appendChild(o)}catch(e){n.textContent=`ERROR`,n.style.color=`red`,t.innerHTML=`<div style="padding: 24px; color: red; font-family: monospace; white-space: pre-wrap;">${e.message}</div>`}};document.getElementById(`run-sql-btn`).onclick=a,i.commands.addCommand({name:`run`,bindKey:{win:`Ctrl-Enter`,mac:`Command-Enter`},exec:function(){a()}})}var W=document.getElementById(`header-container`),G=document.getElementById(`sidebar-container`),K=document.getElementById(`tab-container`);W.innerHTML=n,G.innerHTML=r,K.innerHTML=i,window.AppState={currentTable:null,currentTab:`data-btn`,currentTableBtnElement:null,dbType:null},s().then(e=>{e&&e.success&&e.data&&(window.AppState.dbType=e.data.dbType)}),window.TableStates={},window.ViewCache={},window.updateSidebarDirtyState=function(){document.querySelectorAll(`.table-btn`).forEach(e=>{let t=e.dataset.table,n=e.querySelector(`span`).textContent,r=t||n.replace(/\s*\*$/,``),i=window.TableStates[r],a=!1;if(i){if(i.dataGrid){let e=i.dataGrid;(Object.keys(e.pendingEdits||{}).length>0||e.pendingInserts&&e.pendingInserts.length>1||e.pendingDeletes&&e.pendingDeletes.size>0)&&(a=!0)}if(i.schemaGrid){let e=i.schemaGrid,t=e.pendingIndexEdits&&(e.pendingIndexEdits.added.length>0||e.pendingIndexEdits.dropped.length>0);(Object.keys(e.pendingEdits||{}).length>0||e.pendingInserts&&e.pendingInserts.length>1||e.pendingDeletes&&e.pendingDeletes.size>0||t)&&(a=!0)}}let o=e.querySelector(`span`),s=o.textContent.replace(/\s*\*$/,``);a?(o.textContent=s+` *`,o.style.fontWeight=`bold`):(o.textContent=s,o.style.fontWeight=`normal`)})},window.handleSwitchTab=function(e){document.querySelectorAll(`.tab-btn`).forEach(e=>e.classList.remove(`isCurrentTab`));let t=document.getElementById(e);if(t&&t.classList.add(`isCurrentTab`),window.AppState.currentTab=e,e===`erd-btn`||e===`sql-btn`||e===`status-btn`)window.AppState.currentTable=null,window.AppState.currentTableBtnElement=null,document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`));else if((e===`data-btn`||e===`schema-btn`)&&!window.AppState.currentTable){let e=document.querySelector(`.table-btn`);e&&(window.AppState.currentTable=e.querySelector(`span`).textContent,window.AppState.currentTableBtnElement=e,e.classList.add(`active`))}window.renderCurrentView()},window.renderEmptyState=function(e){e.innerHTML=`
239
239
  <div class="empty-state">
240
240
  <div class="icon-container">
241
241
  <span class="material-symbols-outlined">database</span>
@@ -243,12 +243,12 @@ SELECT * FROM sqlite_master;
243
243
  <h2>No Table Selected</h2>
244
244
  <p>Select a table from the sidebar to view its data, schema, or run SQL queries.</p>
245
245
  </div>
246
- `},window.renderCurrentView=function(e=``,t=!1){let n=[`erd-btn`,`sql-btn`,`status-btn`].includes(window.AppState.currentTab),r=document.getElementById(`main-content`);document.querySelectorAll(`.view-container`).forEach(e=>e.style.display=`none`);let i=n?`view-${window.AppState.currentTab}`:`view-${window.AppState.currentTab}-${window.AppState.currentTable}`,a=document.getElementById(i);if(a||(a=document.createElement(`div`),a.id=i,a.className=`view-container`,a.style.width=`100%`,a.style.flex=`1`,a.style.display=`flex`,a.style.flexDirection=`column`,a.style.overflow=`hidden`,r.appendChild(a)),a.style.display=`flex`,!window.AppState.currentTable&&!n){window.renderEmptyState(a);return}let o=window.AppState.currentTable;o&&!window.TableStates[o]&&(window.TableStates[o]={dataGrid:null,schemaGrid:null}),window.AppState.currentTab===`data-btn`?(window.TableStates[o].dataGrid&&(window.DataGrid=window.TableStates[o].dataGrid),(!window.TableStates[o].dataGrid||!a.hasChildNodes())&&j(o,window.AppState.currentTableBtnElement,e,t,a)):window.AppState.currentTab===`schema-btn`?(window.TableStates[o].schemaGrid&&(window.SchemaGrid=window.TableStates[o].schemaGrid),(!window.TableStates[o].schemaGrid||!a.hasChildNodes())&&V(o,window.AppState.currentTableBtnElement,a)):window.AppState.currentTab===`console-btn`?a.hasChildNodes()||H(o,window.AppState.currentTableBtnElement,a):window.AppState.currentTab===`erd-btn`?a.hasChildNodes()||(a.innerHTML=`<div style='padding:24px; color: var(--color-text-soft);'>ERD Visualization coming soon!</div>`):window.AppState.currentTab===`status-btn`&&(a.hasChildNodes()||(a.innerHTML=`<div style='padding:24px; color: var(--color-text-soft);'>Database Status Dashboard coming soon!</div>`)),document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),window.AppState.currentTableBtnElement&&window.AppState.currentTableBtnElement.classList.add(`active`)},window.saveDataGridEdits=y,window.saveSchemaEdits=N,document.addEventListener(`DOMContentLoaded`,()=>{f();let e=localStorage.getItem(`drixio-theme`),t=window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches;if(e===`dark`||!e&&t){document.documentElement.setAttribute(`data-theme`,`dark`);let e=document.getElementById(`theme-icon`);e&&(e.textContent=`light_mode`)}let n=document.getElementById(`theme-toggle`);n&&n.addEventListener(`click`,()=>{let e=document.documentElement.getAttribute(`data-theme`)===`dark`,t=e?`light`:`dark`;document.documentElement.setAttribute(`data-theme`,t),localStorage.setItem(`drixio-theme`,t),document.getElementById(`theme-icon`).textContent=e?`dark_mode`:`light_mode`}),window.showToast=function(e,t=`success`){let n=document.getElementById(`toast-container`);if(!n)return;let r=document.createElement(`div`);r.className=`toast ${t}`,r.innerHTML=`<span class="material-symbols-outlined">${t===`success`?`check_circle`:`error`}</span> <span>${e}</span>`,n.appendChild(r),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},3e3)},document.addEventListener(`mouseup`,()=>{window.DataGrid&&window.DataGrid.selection&&(window.DataGrid.selection.isDragging=!1),window.SchemaGrid&&window.SchemaGrid.selection&&(window.SchemaGrid.selection.isDragging=!1)}),document.addEventListener(`contextmenu`,e=>{let t=window.AppState?.currentTab===`data-btn`,n=window.AppState?.currentTab===`schema-btn`;if(!t&&!n||t&&!window.DataGrid||n&&!window.SchemaGrid)return;let r=e.target.closest(`td.row-header`);if(!r)return;e.preventDefault();let i=parseInt(r.dataset.rowIdx);document.getElementById(`custom-context-menu`)?.remove();let a=document.createElement(`div`);a.id=`custom-context-menu`,a.className=`context-menu`,a.style.top=`${e.clientY}px`,a.style.left=`${e.clientX}px`,a.innerHTML=`
246
+ `},window.renderCurrentView=function(e=``,t=!1){let n=[`erd-btn`,`sql-btn`,`status-btn`].includes(window.AppState.currentTab),r=document.getElementById(`main-content`);document.querySelectorAll(`.view-container`).forEach(e=>e.style.display=`none`);let i=n?`view-${window.AppState.currentTab}`:`view-${window.AppState.currentTab}-${window.AppState.currentTable}`,a=document.getElementById(i);if(a||(a=document.createElement(`div`),a.id=i,a.className=`view-container`,a.style.width=`100%`,a.style.flex=`1`,a.style.display=`flex`,a.style.flexDirection=`column`,a.style.overflow=`hidden`,r.appendChild(a)),a.style.display=`flex`,!window.AppState.currentTable&&!n){window.renderEmptyState(a);return}let o=window.AppState.currentTable;o&&!window.TableStates[o]&&(window.TableStates[o]={dataGrid:null,schemaGrid:null}),window.AppState.currentTab===`data-btn`?(window.TableStates[o].dataGrid&&(window.DataGrid=window.TableStates[o].dataGrid),(!window.TableStates[o].dataGrid||!a.hasChildNodes())&&M(o,window.AppState.currentTableBtnElement,e,t,a)):window.AppState.currentTab===`schema-btn`?(window.TableStates[o].schemaGrid&&(window.SchemaGrid=window.TableStates[o].schemaGrid),(!window.TableStates[o].schemaGrid||!a.hasChildNodes())&&H(o,window.AppState.currentTableBtnElement,a)):window.AppState.currentTab===`console-btn`?a.hasChildNodes()||U(o,window.AppState.currentTableBtnElement,a):window.AppState.currentTab===`erd-btn`?a.hasChildNodes()||(a.innerHTML=`<div style='padding:24px; color: var(--color-text-soft);'>ERD Visualization coming soon!</div>`):window.AppState.currentTab===`status-btn`&&(a.hasChildNodes()||(a.innerHTML=`<div style='padding:24px; color: var(--color-text-soft);'>Database Status Dashboard coming soon!</div>`)),document.querySelectorAll(`.table-btn`).forEach(e=>e.classList.remove(`active`)),window.AppState.currentTableBtnElement&&window.AppState.currentTableBtnElement.classList.add(`active`)},window.saveDataGridEdits=b,window.saveSchemaEdits=P,document.addEventListener(`DOMContentLoaded`,()=>{p();let e=localStorage.getItem(`drixio-theme`),t=window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches;if(e===`dark`||!e&&t){document.documentElement.setAttribute(`data-theme`,`dark`);let e=document.getElementById(`theme-icon`);e&&(e.textContent=`light_mode`)}let n=document.getElementById(`theme-toggle`);n&&n.addEventListener(`click`,()=>{let e=document.documentElement.getAttribute(`data-theme`)===`dark`,t=e?`light`:`dark`;document.documentElement.setAttribute(`data-theme`,t),localStorage.setItem(`drixio-theme`,t),document.getElementById(`theme-icon`).textContent=e?`dark_mode`:`light_mode`}),window.showToast=function(e,t=`success`){let n=document.getElementById(`toast-container`);if(!n)return;let r=document.createElement(`div`);r.className=`toast ${t}`,r.innerHTML=`<span class="material-symbols-outlined">${t===`success`?`check_circle`:`error`}</span> <span>${e}</span>`,n.appendChild(r),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},3e3)},document.addEventListener(`mouseup`,()=>{window.DataGrid&&window.DataGrid.selection&&(window.DataGrid.selection.isDragging=!1),window.SchemaGrid&&window.SchemaGrid.selection&&(window.SchemaGrid.selection.isDragging=!1)}),document.addEventListener(`contextmenu`,e=>{let t=window.AppState?.currentTab===`data-btn`,n=window.AppState?.currentTab===`schema-btn`;if(!t&&!n||t&&!window.DataGrid||n&&!window.SchemaGrid)return;let r=e.target.closest(`td.row-header`);if(!r)return;e.preventDefault();let i=parseInt(r.dataset.rowIdx);document.getElementById(`custom-context-menu`)?.remove();let a=document.createElement(`div`);a.id=`custom-context-menu`,a.className=`context-menu`,a.style.top=`${e.clientY}px`,a.style.left=`${e.clientX}px`,a.innerHTML=`
247
247
  <div class="context-menu-item" id="cmenu-duplicate">
248
248
  <span class="material-symbols-outlined" style="font-size:16px;">content_copy</span> Duplicate Row(s)
249
249
  </div>
250
250
  <div class="context-menu-item danger" id="cmenu-delete">
251
251
  <span class="material-symbols-outlined" style="font-size:16px;">delete</span> Delete Row(s)
252
252
  </div>
253
- `,document.body.appendChild(a);let o=e=>{let r=[i],o=t?window.DataGrid:window.SchemaGrid;if(o&&o.selection&&o.selection.startRow!==-1){let e=o.selection,t=Math.min(e.startRow,e.endRow),n=Math.max(e.startRow,e.endRow);if(i>=t&&i<=n){r=[];for(let e=t;e<=n;e++)r.push(e)}}t?D(()=>Promise.resolve().then(()=>v).then(t=>{window.DataGrid.currentTransaction=[],e===`delete`?r.forEach(e=>t.markRowDeleted(e)):e===`duplicate`&&(t.duplicateDataRows(r,window.DataGrid.schema.map(e=>e.name)),setTimeout(()=>{let e=document.getElementById(`data-grid-container-${window.AppState.currentTable}`);e&&(e.scrollTop=e.scrollHeight)},50)),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null}),void 0,import.meta.url):n&&D(()=>Promise.resolve().then(()=>M).then(t=>{window.SchemaGrid.currentTransaction=[],e===`delete`?r.forEach(e=>t.markSchemaRowDeleted(e)):e===`duplicate`&&(t.duplicateSchemaRows(r,[`name`,`type`,`isPk`,`nullable`,`defaultValue`,`Index`]),setTimeout(()=>{let e=document.getElementById(`schema-grid-container-${window.AppState.currentTable}`);e&&(e.scrollTop=e.scrollHeight)},50)),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null}),void 0,import.meta.url),a.remove()};document.getElementById(`cmenu-duplicate`).onclick=()=>o(`duplicate`),document.getElementById(`cmenu-delete`).onclick=()=>o(`delete`);let s=e=>{a.contains(e.target)||(a.remove(),document.removeEventListener(`click`,s))};setTimeout(()=>document.addEventListener(`click`,s),0)}),document.addEventListener(`keydown`,e=>{let t=window.AppState?.currentTab===`data-btn`,n=window.AppState?.currentTab===`schema-btn`;if(e.key===`F5`){t&&window.DataGrid?.refreshData?(e.preventDefault(),window.DataGrid.refreshData()):n&&document.getElementById(`btn-refresh-schema`)&&(e.preventDefault(),document.getElementById(`btn-refresh-schema`).click());return}if(!(!t&&!n)&&!(e.target.tagName===`INPUT`||e.target.tagName===`SELECT`||e.target.tagName===`TEXTAREA`)){if([`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`].includes(e.key)){let n=t?window.DataGrid:window.SchemaGrid;if(!n||!n.selection)return;e.preventDefault();let r=n.selection;if(r.startRow===-1)return;let i=t?n.schema.length:5,a=window.AppState?.currentTable,o=document.querySelectorAll(t?`#data-grid-table-${a} tbody tr`:`#schema-grid-table-${a} tbody tr`),s=o.length>0?o.length-1:0,c=e.shiftKey?r.endRow:r.startRow,l=e.shiftKey?r.endCol:r.startCol;e.key===`ArrowUp`&&(c=Math.max(0,c-1)),e.key===`ArrowDown`&&(c=Math.min(s,c+1)),e.key===`ArrowLeft`&&(l=Math.max(0,l-1)),e.key===`ArrowRight`&&(l=Math.min(i-1,l+1)),e.shiftKey?(r.endRow=c,r.endCol=l):(r.startRow=c,r.endRow=c,r.startCol=l,r.endCol=l);let u=t?`data-grid-table-${a}`:`schema-grid-table-${a}`;D(()=>Promise.resolve().then(()=>p).then(e=>e.renderSelection(u,n)),void 0,import.meta.url),setTimeout(()=>{let e=document.querySelector(t?`#data-grid-table-${a} td.data-cell[data-row-idx="${c}"][data-col-idx="${l}"]`:`#schema-grid-table-${a} td.data-cell[data-row-idx="${c}"][data-col-idx="${l}"]`);if(e){let n=document.getElementById(t?`data-grid-container`:`schema-grid-container`);if(n){let t=e.getBoundingClientRect(),r=n.getBoundingClientRect();t.bottom>r.bottom?n.scrollTop+=t.bottom-r.bottom+5:t.top<r.top+30&&(n.scrollTop-=r.top+30-t.top),t.right>r.right?n.scrollLeft+=t.right-r.right+5:t.left<r.left+50&&(n.scrollLeft-=r.left+50-t.left)}}},5);return}if((e.key===`Delete`||e.key===`Backspace`)&&(t?D(()=>Promise.resolve().then(()=>v).then(e=>{window.DataGrid.currentTransaction=[],document.querySelectorAll(`#data-grid-table-${window.AppState.currentTable} .cell-in-range`).forEach(t=>e.updateCell(t,``,window.DataGrid.schema.map(e=>e.name))),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null}),void 0,import.meta.url):n&&D(()=>Promise.resolve().then(()=>M).then(e=>{window.SchemaGrid.currentTransaction=[];let t=[`name`,`type`,`isPk`,`nullable`,`defaultValue`];document.querySelectorAll(`#schema-grid-table-${window.AppState.currentTable} .cell-in-range`).forEach(n=>{(n.dataset.insertIndex!==void 0||n.dataset.colKey===`name`)&&e.updateSchemaCell(n,``,t)}),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null}),void 0,import.meta.url)),e.key.toLowerCase()===`s`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),t&&window.saveDataGridEdits(),n&&window.saveSchemaEdits()),e.key.toLowerCase()===`c`&&(e.ctrlKey||e.metaKey)){let e=(t?window.DataGrid:window.SchemaGrid).selection;if(e.startRow===-1)return;let n=Math.min(e.startRow,e.endRow),r=Math.max(e.startRow,e.endRow),i=Math.min(e.startCol,e.endCol),a=Math.max(e.startCol,e.endCol),o=``;for(let e=n;e<=r;e++){let n=[];for(let r=i;r<=a;r++){let i=document.querySelector(t?`#data-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${e}"][data-col-idx="${r}"]`:`#schema-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${e}"][data-col-idx="${r}"]`);if(i){let e=i.textContent.replace(/^null$|^\+ New$/,``);n.push(e)}}o+=n.join(` `)+`
254
- `}navigator.clipboard.writeText(o.trimEnd()),document.querySelectorAll(`.cell-in-range`).forEach(e=>{e.style.backgroundColor=`#bfdbfe`,setTimeout(()=>e.style.backgroundColor=``,150)})}if(e.key===`-`&&(e.ctrlKey||e.metaKey)){e.preventDefault();let r=t?window.DataGrid:window.SchemaGrid,i=r.selection;if(i.startRow===-1)return;let a=Math.min(i.startRow,i.endRow),o=Math.max(i.startRow,i.endRow);t?D(()=>Promise.resolve().then(()=>v).then(e=>{r.currentTransaction=[];for(let t=a;t<=o;t++)e.markRowDeleted(t);r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url):n&&D(()=>Promise.resolve().then(()=>M).then(e=>{r.currentTransaction=[];for(let t=a;t<=o;t++)e.markSchemaRowDeleted(t);r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url)}if(e.key.toLowerCase()===`z`&&(e.ctrlKey||e.metaKey)){if(e.preventDefault(),t){let e=window.DataGrid.history?.pop();e&&D(()=>Promise.resolve().then(()=>v).then(t=>{let n=window.DataGrid.schema.map(e=>e.name);for(let r=e.length-1;r>=0;r--){let i=e[r];i.type===`delete`?t.unmarkRowDeleted(i.rowIdx,i.pk):t.updateCell(i.td,i.oldVal,n,!1)}}),void 0,import.meta.url)}else if(n){let e=window.SchemaGrid.history?.pop();e&&D(()=>Promise.resolve().then(()=>M).then(t=>{let n=[`name`,`type`,`isPk`,`nullable`,`defaultValue`];for(let r=e.length-1;r>=0;r--){let i=e[r];i.type===`delete`?t.unmarkSchemaRowDeleted(i.rowIdx,i.pk):t.updateSchemaCell(i.td,i.oldVal,n,!1)}}),void 0,import.meta.url)}}}}),document.addEventListener(`paste`,e=>{let t=window.AppState?.currentTab===`data-btn`,n=window.AppState?.currentTab===`schema-btn`;if(!t&&!n)return;let r=t?window.DataGrid:window.SchemaGrid;if(!r||e.target.tagName===`INPUT`||e.target.tagName===`SELECT`||e.target.tagName===`TEXTAREA`)return;let i=r.selection;if(i.startRow===-1)return;let a=e.clipboardData.getData(`text`);if(!a)return;e.preventDefault();let o=a.split(/\r?\n/).map(e=>e.split(` `)),s=Math.min(i.startRow,i.endRow),c=Math.min(i.startCol,i.endCol);r.currentTransaction=[],t?D(()=>Promise.resolve().then(()=>v).then(e=>{let t=r.schema.map(e=>e.name);o.forEach(n=>{n.forEach((n,r)=>{let i=c+r,a=document.querySelector(`#data-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${s}"][data-col-idx="${i}"]`);a&&e.updateCell(a,n,t)}),s++}),r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url):n&&D(()=>Promise.resolve().then(()=>M).then(e=>{let t=[`name`,`type`,`isPk`,`nullable`,`defaultValue`];o.forEach(n=>{n.forEach((n,r)=>{let i=c+r,a=document.querySelector(`#schema-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${s}"][data-col-idx="${i}"]`);a&&(a.dataset.insertIndex!==void 0||a.dataset.colKey===`name`)&&e.updateSchemaCell(a,n,t)}),s++}),r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url)})});
253
+ `,document.body.appendChild(a);let o=e=>{let r=[i],o=t?window.DataGrid:window.SchemaGrid;if(o&&o.selection&&o.selection.startRow!==-1){let e=o.selection,t=Math.min(e.startRow,e.endRow),n=Math.max(e.startRow,e.endRow);if(i>=t&&i<=n){r=[];for(let e=t;e<=n;e++)r.push(e)}}t?O(()=>Promise.resolve().then(()=>y).then(t=>{window.DataGrid.currentTransaction=[],e===`delete`?r.forEach(e=>t.markRowDeleted(e)):e===`duplicate`&&(t.duplicateDataRows(r,window.DataGrid.schema.map(e=>e.name)),setTimeout(()=>{let e=document.getElementById(`data-grid-container-${window.AppState.currentTable}`);e&&(e.scrollTop=e.scrollHeight)},50)),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null}),void 0,import.meta.url):n&&O(()=>Promise.resolve().then(()=>N).then(t=>{window.SchemaGrid.currentTransaction=[],e===`delete`?r.forEach(e=>t.markSchemaRowDeleted(e)):e===`duplicate`&&(t.duplicateSchemaRows(r,[`name`,`type`,`isPk`,`nullable`,`defaultValue`,`Index`]),setTimeout(()=>{let e=document.getElementById(`schema-grid-container-${window.AppState.currentTable}`);e&&(e.scrollTop=e.scrollHeight)},50)),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null}),void 0,import.meta.url),a.remove()};document.getElementById(`cmenu-duplicate`).onclick=()=>o(`duplicate`),document.getElementById(`cmenu-delete`).onclick=()=>o(`delete`);let s=e=>{a.contains(e.target)||(a.remove(),document.removeEventListener(`click`,s))};setTimeout(()=>document.addEventListener(`click`,s),0)}),document.addEventListener(`keydown`,e=>{let t=window.AppState?.currentTab===`data-btn`,n=window.AppState?.currentTab===`schema-btn`;if(e.key===`F5`){t&&window.DataGrid?.refreshData?(e.preventDefault(),window.DataGrid.refreshData()):n&&document.getElementById(`btn-refresh-schema`)&&(e.preventDefault(),document.getElementById(`btn-refresh-schema`).click());return}if(!(!t&&!n)&&!(e.target.tagName===`INPUT`||e.target.tagName===`SELECT`||e.target.tagName===`TEXTAREA`)){if([`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`].includes(e.key)){let n=t?window.DataGrid:window.SchemaGrid;if(!n||!n.selection)return;e.preventDefault();let r=n.selection;if(r.startRow===-1)return;let i=t?n.schema.length:5,a=window.AppState?.currentTable,o=document.querySelectorAll(t?`#data-grid-table-${a} tbody tr`:`#schema-grid-table-${a} tbody tr`),s=o.length>0?o.length-1:0,c=e.shiftKey?r.endRow:r.startRow,l=e.shiftKey?r.endCol:r.startCol;e.key===`ArrowUp`&&(c=Math.max(0,c-1)),e.key===`ArrowDown`&&(c=Math.min(s,c+1)),e.key===`ArrowLeft`&&(l=Math.max(0,l-1)),e.key===`ArrowRight`&&(l=Math.min(i-1,l+1)),e.shiftKey?(r.endRow=c,r.endCol=l):(r.startRow=c,r.endRow=c,r.startCol=l,r.endCol=l);let u=t?`data-grid-table-${a}`:`schema-grid-table-${a}`;O(()=>Promise.resolve().then(()=>m).then(e=>e.renderSelection(u,n)),void 0,import.meta.url),setTimeout(()=>{let e=document.querySelector(t?`#data-grid-table-${a} td.data-cell[data-row-idx="${c}"][data-col-idx="${l}"]`:`#schema-grid-table-${a} td.data-cell[data-row-idx="${c}"][data-col-idx="${l}"]`);if(e){let n=document.getElementById(t?`data-grid-container`:`schema-grid-container`);if(n){let t=e.getBoundingClientRect(),r=n.getBoundingClientRect();t.bottom>r.bottom?n.scrollTop+=t.bottom-r.bottom+5:t.top<r.top+30&&(n.scrollTop-=r.top+30-t.top),t.right>r.right?n.scrollLeft+=t.right-r.right+5:t.left<r.left+50&&(n.scrollLeft-=r.left+50-t.left)}}},5);return}if((e.key===`Delete`||e.key===`Backspace`)&&(t?O(()=>Promise.resolve().then(()=>y).then(e=>{window.DataGrid.currentTransaction=[],document.querySelectorAll(`#data-grid-table-${window.AppState.currentTable} .cell-in-range`).forEach(t=>e.updateCell(t,``,window.DataGrid.schema.map(e=>e.name))),window.DataGrid.currentTransaction.length>0&&window.DataGrid.history.push(window.DataGrid.currentTransaction),window.DataGrid.currentTransaction=null}),void 0,import.meta.url):n&&O(()=>Promise.resolve().then(()=>N).then(e=>{window.SchemaGrid.currentTransaction=[];let t=[`name`,`type`,`isPk`,`nullable`,`defaultValue`];document.querySelectorAll(`#schema-grid-table-${window.AppState.currentTable} .cell-in-range`).forEach(n=>{(n.dataset.insertIndex!==void 0||n.dataset.colKey===`name`)&&e.updateSchemaCell(n,``,t)}),window.SchemaGrid.currentTransaction.length>0&&window.SchemaGrid.history.push(window.SchemaGrid.currentTransaction),window.SchemaGrid.currentTransaction=null}),void 0,import.meta.url)),e.key.toLowerCase()===`s`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),t&&window.saveDataGridEdits(),n&&window.saveSchemaEdits()),e.key.toLowerCase()===`c`&&(e.ctrlKey||e.metaKey)){let e=(t?window.DataGrid:window.SchemaGrid).selection;if(e.startRow===-1)return;let n=Math.min(e.startRow,e.endRow),r=Math.max(e.startRow,e.endRow),i=Math.min(e.startCol,e.endCol),a=Math.max(e.startCol,e.endCol),o=``;for(let e=n;e<=r;e++){let n=[];for(let r=i;r<=a;r++){let i=document.querySelector(t?`#data-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${e}"][data-col-idx="${r}"]`:`#schema-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${e}"][data-col-idx="${r}"]`);if(i){let e=i.textContent.replace(/^null$|^\+ New$/,``);n.push(e)}}o+=n.join(` `)+`
254
+ `}navigator.clipboard.writeText(o.trimEnd()),document.querySelectorAll(`.cell-in-range`).forEach(e=>{e.style.backgroundColor=`#bfdbfe`,setTimeout(()=>e.style.backgroundColor=``,150)})}if(e.key===`-`&&(e.ctrlKey||e.metaKey)){e.preventDefault();let r=t?window.DataGrid:window.SchemaGrid,i=r.selection;if(i.startRow===-1)return;let a=Math.min(i.startRow,i.endRow),o=Math.max(i.startRow,i.endRow);t?O(()=>Promise.resolve().then(()=>y).then(e=>{r.currentTransaction=[];for(let t=a;t<=o;t++)e.markRowDeleted(t);r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url):n&&O(()=>Promise.resolve().then(()=>N).then(e=>{r.currentTransaction=[];for(let t=a;t<=o;t++)e.markSchemaRowDeleted(t);r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url)}if(e.key.toLowerCase()===`z`&&(e.ctrlKey||e.metaKey)){if(e.preventDefault(),t){let e=window.DataGrid.history?.pop();e&&O(()=>Promise.resolve().then(()=>y).then(t=>{let n=window.DataGrid.schema.map(e=>e.name);for(let r=e.length-1;r>=0;r--){let i=e[r];i.type===`delete`?t.unmarkRowDeleted(i.rowIdx,i.pk):t.updateCell(i.td,i.oldVal,n,!1)}}),void 0,import.meta.url)}else if(n){let e=window.SchemaGrid.history?.pop();e&&O(()=>Promise.resolve().then(()=>N).then(t=>{let n=[`name`,`type`,`isPk`,`nullable`,`defaultValue`];for(let r=e.length-1;r>=0;r--){let i=e[r];i.type===`delete`?t.unmarkSchemaRowDeleted(i.rowIdx,i.pk):t.updateSchemaCell(i.td,i.oldVal,n,!1)}}),void 0,import.meta.url)}}}}),document.addEventListener(`paste`,e=>{let t=window.AppState?.currentTab===`data-btn`,n=window.AppState?.currentTab===`schema-btn`;if(!t&&!n)return;let r=t?window.DataGrid:window.SchemaGrid;if(!r||e.target.tagName===`INPUT`||e.target.tagName===`SELECT`||e.target.tagName===`TEXTAREA`)return;let i=r.selection;if(i.startRow===-1)return;let a=e.clipboardData.getData(`text`);if(!a)return;e.preventDefault();let o=a.split(/\r?\n/).map(e=>e.split(` `)),s=Math.min(i.startRow,i.endRow),c=Math.min(i.startCol,i.endCol);r.currentTransaction=[],t?O(()=>Promise.resolve().then(()=>y).then(e=>{let t=r.schema.map(e=>e.name);o.forEach(n=>{n.forEach((n,r)=>{let i=c+r,a=document.querySelector(`#data-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${s}"][data-col-idx="${i}"]`);a&&e.updateCell(a,n,t)}),s++}),r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url):n&&O(()=>Promise.resolve().then(()=>N).then(e=>{let t=[`name`,`type`,`isPk`,`nullable`,`defaultValue`];o.forEach(n=>{n.forEach((n,r)=>{let i=c+r,a=document.querySelector(`#schema-grid-table-${window.AppState.currentTable} td.data-cell[data-row-idx="${s}"][data-col-idx="${i}"]`);a&&(a.dataset.insertIndex!==void 0||a.dataset.colKey===`name`)&&e.updateSchemaCell(a,n,t)}),s++}),r.currentTransaction.length>0&&r.history.push(r.currentTransaction),r.currentTransaction=null}),void 0,import.meta.url)})});
@@ -16,7 +16,7 @@
16
16
  crossorigin="anonymous"
17
17
  referrerpolicy="no-referrer"
18
18
  ></script>
19
- <script type="module" crossorigin src="./assets/index-B2SFgnu7.js"></script>
19
+ <script type="module" crossorigin src="./assets/index-DrR5jotT.js"></script>
20
20
  <link rel="stylesheet" crossorigin href="./assets/index-CCy0fVAv.css">
21
21
  </head>
22
22
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drixio",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "A lightweight interactive TUI database client",
5
5
  "bin": {
6
6
  "drixio": "dist/cli.js"