@dbcube/core 1.0.12 → 1.0.13

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/index.cjs CHANGED
@@ -298,7 +298,7 @@ var Engine = class {
298
298
  return this.config;
299
299
  }
300
300
  async run(binary, args) {
301
- return new Promise((resolve2, reject) => {
301
+ return new Promise((resolve3, reject) => {
302
302
  const child = (0, import_child_process.spawn)(this.binary[binary], [...this.arguments, ...args]);
303
303
  let stdoutBuffer = "";
304
304
  let stderrBuffer = "";
@@ -314,7 +314,7 @@ var Engine = class {
314
314
  if (!isResolved) {
315
315
  isResolved = true;
316
316
  clearTimeout(timeoutId);
317
- resolve2(response);
317
+ resolve3(response);
318
318
  }
319
319
  };
320
320
  child.stdout.on("data", (data) => {
@@ -382,93 +382,248 @@ var Engine = class {
382
382
  }
383
383
  };
384
384
 
385
- // src/lib/DbConfig.ts
386
- var import_better_sqlite3 = __toESM(require("better-sqlite3"));
385
+ // src/lib/SqliteExecutor.ts
386
+ var import_child_process2 = require("child_process");
387
387
  var path2 = __toESM(require("path"));
388
+ var import_util = require("util");
389
+ var execAsync = (0, import_util.promisify)(import_child_process2.exec);
390
+ var SqliteExecutor = class {
391
+ binaryPath;
392
+ dbPath;
393
+ constructor(dbPath) {
394
+ this.dbPath = dbPath;
395
+ this.binaryPath = this.getBinaryPath();
396
+ }
397
+ getBinaryPath() {
398
+ const binDir = path2.resolve(__dirname, "..", "bin");
399
+ const platform2 = process.platform;
400
+ const extension = platform2 === "win32" ? ".exe" : "";
401
+ const binaryName = `sqlite-engine${extension}`;
402
+ return path2.join(binDir, binaryName);
403
+ }
404
+ async executeBinary(args) {
405
+ const command = `"${this.binaryPath}" ${args.map((arg) => `"${arg}"`).join(" ")}`;
406
+ try {
407
+ const { stdout, stderr } = await execAsync(command, {
408
+ maxBuffer: 10 * 1024 * 1024,
409
+ // 10MB buffer
410
+ timeout: 3e4
411
+ // 30s timeout
412
+ });
413
+ if (stderr && stderr.trim()) {
414
+ console.warn("SQLite Engine Warning:", stderr);
415
+ }
416
+ const result = JSON.parse(stdout.trim());
417
+ return result;
418
+ } catch (error) {
419
+ if (error.stdout) {
420
+ try {
421
+ const result = JSON.parse(error.stdout.trim());
422
+ return result;
423
+ } catch (parseError) {
424
+ }
425
+ }
426
+ throw new Error(`SQLite execution failed: ${error.message}`);
427
+ }
428
+ }
429
+ async connect() {
430
+ try {
431
+ const result = await this.executeBinary([
432
+ "--action",
433
+ "connect",
434
+ "--database",
435
+ this.dbPath
436
+ ]);
437
+ return result.status === "success";
438
+ } catch (error) {
439
+ return false;
440
+ }
441
+ }
442
+ async exists() {
443
+ try {
444
+ const result = await this.executeBinary([
445
+ "--action",
446
+ "exists",
447
+ "--database",
448
+ this.dbPath
449
+ ]);
450
+ return result.status === "success" && result.data === true;
451
+ } catch (error) {
452
+ return false;
453
+ }
454
+ }
455
+ async query(sql, params) {
456
+ const args = [
457
+ "--action",
458
+ "query",
459
+ "--database",
460
+ this.dbPath,
461
+ "--query",
462
+ sql
463
+ ];
464
+ if (params && params.length > 0) {
465
+ args.push("--params", JSON.stringify(params));
466
+ }
467
+ return this.executeBinary(args);
468
+ }
469
+ // Método para múltiples queries (como lo hace better-sqlite3)
470
+ async queryMultiple(sql) {
471
+ return this.query(sql);
472
+ }
473
+ // Método prepare que simula prepared statements
474
+ prepare(sql) {
475
+ return {
476
+ all: async (...params) => {
477
+ const result = await this.query(sql, params);
478
+ if (result.status === "error") {
479
+ throw new Error(result.message);
480
+ }
481
+ return Array.isArray(result.data) ? result.data : [];
482
+ },
483
+ run: async (...params) => {
484
+ const result = await this.query(sql, params);
485
+ if (result.status === "error") {
486
+ throw new Error(result.message);
487
+ }
488
+ if (typeof result.data === "object" && result.data.hasOwnProperty("changes") && result.data.hasOwnProperty("lastID")) {
489
+ return result.data;
490
+ }
491
+ return { changes: 0, lastID: 0 };
492
+ }
493
+ };
494
+ }
495
+ // Para compatibilidad con better-sqlite3 API sincrona usando deasync si es necesario
496
+ prepareSync(sql) {
497
+ const deasync = require("deasync");
498
+ return {
499
+ all: (...params) => {
500
+ let result;
501
+ let done = false;
502
+ let error;
503
+ this.query(sql, params).then((res) => {
504
+ if (res.status === "error") {
505
+ error = new Error(res.message);
506
+ } else {
507
+ result = Array.isArray(res.data) ? res.data : [];
508
+ }
509
+ done = true;
510
+ }).catch((err) => {
511
+ error = err;
512
+ done = true;
513
+ });
514
+ deasync.loopWhile(() => !done);
515
+ if (error) throw error;
516
+ return result;
517
+ },
518
+ run: (...params) => {
519
+ let result;
520
+ let done = false;
521
+ let error;
522
+ this.query(sql, params).then((res) => {
523
+ if (res.status === "error") {
524
+ error = new Error(res.message);
525
+ } else if (typeof res.data === "object" && res.data.hasOwnProperty("changes") && res.data.hasOwnProperty("lastID")) {
526
+ result = res.data;
527
+ } else {
528
+ result = { changes: 0, lastID: 0 };
529
+ }
530
+ done = true;
531
+ }).catch((err) => {
532
+ error = err;
533
+ done = true;
534
+ });
535
+ deasync.loopWhile(() => !done);
536
+ if (error) throw error;
537
+ return result;
538
+ }
539
+ };
540
+ }
541
+ };
542
+
543
+ // src/lib/DbConfig.ts
544
+ var path3 = __toESM(require("path"));
388
545
  var import_fs = __toESM(require("fs"));
389
- var rootPath = path2.resolve(process.cwd(), ".dbcube");
546
+ var rootPath = path3.resolve(process.cwd(), ".dbcube");
390
547
  var SQLite = class {
391
- db = null;
548
+ executor = null;
392
549
  database;
393
550
  constructor(config) {
394
551
  this.database = config.DATABASE;
395
552
  }
396
- ifExist() {
553
+ async ifExist() {
397
554
  if (this.database) {
398
555
  const dbPath = this.database || ":memory:";
399
- const configPath = path2.join(rootPath, dbPath + ".db");
556
+ const configPath = path3.join(rootPath, dbPath + ".db");
400
557
  if (!import_fs.default.existsSync(rootPath)) {
401
558
  import_fs.default.mkdirSync(rootPath, { recursive: true });
402
559
  }
403
560
  if (import_fs.default.existsSync(configPath)) {
404
561
  return true;
405
562
  }
563
+ if (!this.executor) {
564
+ this.executor = new SqliteExecutor(configPath);
565
+ }
566
+ return await this.executor.exists();
406
567
  }
407
568
  return false;
408
569
  }
409
570
  async connect() {
410
- return new Promise((resolve2, reject) => {
571
+ return new Promise(async (resolve3, reject) => {
411
572
  try {
412
- if (!this.db) {
573
+ if (!this.executor) {
413
574
  const dbPath = this.database || ":memory:";
414
- const configPath = path2.join(rootPath, dbPath + ".db");
575
+ const configPath = path3.join(rootPath, dbPath + ".db");
415
576
  if (!import_fs.default.existsSync(rootPath)) {
416
577
  import_fs.default.mkdirSync(rootPath, { recursive: true });
417
578
  }
418
- this.db = new import_better_sqlite3.default(configPath);
579
+ this.executor = new SqliteExecutor(configPath);
580
+ const connected = await this.executor.connect();
581
+ if (!connected) {
582
+ throw new Error("Failed to connect to SQLite database");
583
+ }
419
584
  }
420
- resolve2(this.db);
585
+ resolve3(this.executor);
421
586
  } catch (error) {
422
587
  reject(error);
423
588
  }
424
589
  });
425
590
  }
426
591
  async disconnect() {
427
- return new Promise((resolve2) => {
428
- if (this.db) {
429
- this.db.close();
430
- this.db = null;
592
+ return new Promise((resolve3) => {
593
+ if (this.executor) {
594
+ this.executor = null;
431
595
  }
432
- resolve2();
596
+ resolve3();
433
597
  });
434
598
  }
435
599
  async query(sqlQuery) {
436
- return new Promise(async (resolve2) => {
600
+ return new Promise(async (resolve3) => {
437
601
  try {
438
602
  if (typeof sqlQuery !== "string") {
439
603
  throw new Error("The SQL query must be a string.");
440
604
  }
441
- if (!this.db) {
605
+ if (!this.executor) {
442
606
  await this.connect();
443
607
  }
444
- if (!this.db) {
608
+ if (!this.executor) {
445
609
  throw new Error("Database connection is not available.");
446
610
  }
447
- const sqlCommands = sqlQuery.split(";").filter((cmd) => cmd.trim().length > 0);
448
- const results = [];
449
- for (const command of sqlCommands) {
450
- const query = `${command};`;
451
- const isSelect = query.trim().toLowerCase().startsWith("select");
452
- if (isSelect) {
453
- const stmt = this.db.prepare(query);
454
- const rows = stmt.all();
455
- results.push(rows);
456
- } else {
457
- const stmt = this.db.prepare(query);
458
- const result = stmt.run();
459
- results.push({
460
- changes: result.changes,
461
- lastID: result.lastInsertRowid
462
- });
463
- }
611
+ const result = await this.executor.queryMultiple(sqlQuery);
612
+ if (result.status === "error") {
613
+ resolve3({
614
+ status: "error",
615
+ message: result.message,
616
+ data: null
617
+ });
618
+ } else {
619
+ resolve3({
620
+ status: "success",
621
+ message: "Query executed successfully",
622
+ data: result.data
623
+ });
464
624
  }
465
- resolve2({
466
- status: "success",
467
- message: "Query executed successfully",
468
- data: results.length === 1 ? results[0] : results
469
- });
470
625
  } catch (error) {
471
- resolve2({
626
+ resolve3({
472
627
  status: "error",
473
628
  message: error.message || "An error occurred while executing the query.",
474
629
  data: null
@@ -477,7 +632,7 @@ var SQLite = class {
477
632
  });
478
633
  }
479
634
  async queryWithParameters(sqlQuery, params = []) {
480
- return new Promise(async (resolve2) => {
635
+ return new Promise(async (resolve3) => {
481
636
  try {
482
637
  if (typeof sqlQuery !== "string") {
483
638
  throw new Error("The SQL query must be a string.");
@@ -485,35 +640,29 @@ var SQLite = class {
485
640
  if (!Array.isArray(params)) {
486
641
  throw new Error("Parameters must be an array.");
487
642
  }
488
- if (!this.db) {
643
+ if (!this.executor) {
489
644
  await this.connect();
490
645
  }
491
- if (!this.db) {
646
+ if (!this.executor) {
492
647
  throw new Error("Database connection is not available.");
493
648
  }
494
- const isSelect = sqlQuery.trim().toLowerCase().startsWith("select");
495
- const stmt = this.db.prepare(sqlQuery);
496
- if (isSelect) {
497
- const rows = stmt.all(...params);
498
- resolve2({
499
- status: "success",
500
- message: "Query executed successfully",
501
- data: rows
649
+ const result = await this.executor.query(sqlQuery, params);
650
+ if (result.status === "error") {
651
+ resolve3({
652
+ status: "error",
653
+ message: result.message,
654
+ data: null
502
655
  });
503
656
  } else {
504
- const result = stmt.run(...params);
505
- resolve2({
657
+ resolve3({
506
658
  status: "success",
507
659
  message: "Query executed successfully",
508
- data: {
509
- changes: result.changes,
510
- lastID: result.lastInsertRowid
511
- }
660
+ data: result.data
512
661
  });
513
662
  }
514
663
  } catch (error) {
515
664
  console.log(error);
516
- resolve2({
665
+ resolve3({
517
666
  status: "error",
518
667
  message: error.message || "An error occurred while executing the query.",
519
668
  data: null
@@ -608,7 +757,7 @@ var DbConfig_default = DbConfig;
608
757
 
609
758
  // src/lib/FileLogger.ts
610
759
  var fs2 = __toESM(require("fs"));
611
- var path3 = __toESM(require("path"));
760
+ var path4 = __toESM(require("path"));
612
761
  var import_events = require("events");
613
762
  var FileLogger = class _FileLogger extends import_events.EventEmitter {
614
763
  static watchers = /* @__PURE__ */ new Map();
@@ -623,7 +772,7 @@ var FileLogger = class _FileLogger extends import_events.EventEmitter {
623
772
  */
624
773
  static async write(filePath, message, level = "INFO", append = true) {
625
774
  try {
626
- const dir = path3.dirname(filePath);
775
+ const dir = path4.dirname(filePath);
627
776
  if (!fs2.existsSync(dir)) {
628
777
  fs2.mkdirSync(dir, { recursive: true });
629
778
  }
@@ -662,7 +811,7 @@ var FileLogger = class _FileLogger extends import_events.EventEmitter {
662
811
  const buffer = _FileLogger.buffers.get(filePath);
663
812
  if (buffer && buffer.length > 0) {
664
813
  try {
665
- const dir = path3.dirname(filePath);
814
+ const dir = path4.dirname(filePath);
666
815
  if (!fs2.existsSync(dir)) {
667
816
  fs2.mkdirSync(dir, { recursive: true });
668
817
  }
@@ -983,7 +1132,7 @@ var FileLogger = class _FileLogger extends import_events.EventEmitter {
983
1132
  var ComputedFieldProcessor = class {
984
1133
  static async getComputedFields(name) {
985
1134
  let computedFields = [];
986
- if (DbConfig_default.ifExist()) {
1135
+ if (await DbConfig_default.ifExist()) {
987
1136
  await DbConfig_default.connect();
988
1137
  try {
989
1138
  const tableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='dbcube_computes_config'`;
@@ -1282,7 +1431,7 @@ var TableProcessor = class {
1282
1431
  }
1283
1432
  return true;
1284
1433
  }
1285
- if (DbConfig_default.ifExist()) {
1434
+ if (await DbConfig_default.ifExist()) {
1286
1435
  await DbConfig_default.connect();
1287
1436
  try {
1288
1437
  const tableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='dbcube_computes_config'`;
@@ -1324,7 +1473,7 @@ var TableProcessor = class {
1324
1473
  }
1325
1474
  }
1326
1475
  static async saveQuery(table_ref, database_ref, struct) {
1327
- if (DbConfig_default.ifExist()) {
1476
+ if (await DbConfig_default.ifExist()) {
1328
1477
  await DbConfig_default.connect();
1329
1478
  try {
1330
1479
  await DbConfig_default.query(`DELETE FROM dbcube_schemas_config WHERE table_ref='${table_ref}' AND database_ref='${database_ref}'`);
@@ -1340,7 +1489,7 @@ var TableProcessor = class {
1340
1489
  var TriggerProcessor = class {
1341
1490
  static async getTriggers(name) {
1342
1491
  let triggers = [];
1343
- if (DbConfig_default.ifExist()) {
1492
+ if (await DbConfig_default.ifExist()) {
1344
1493
  await DbConfig_default.connect();
1345
1494
  try {
1346
1495
  const tableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='dbcube_triggers_config'`;