@dbcube/core 1.0.12 → 1.0.14

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.js CHANGED
@@ -261,7 +261,7 @@ var Engine = class {
261
261
  return this.config;
262
262
  }
263
263
  async run(binary, args) {
264
- return new Promise((resolve2, reject) => {
264
+ return new Promise((resolve3, reject) => {
265
265
  const child = spawn(this.binary[binary], [...this.arguments, ...args]);
266
266
  let stdoutBuffer = "";
267
267
  let stderrBuffer = "";
@@ -277,7 +277,7 @@ var Engine = class {
277
277
  if (!isResolved) {
278
278
  isResolved = true;
279
279
  clearTimeout(timeoutId);
280
- resolve2(response);
280
+ resolve3(response);
281
281
  }
282
282
  };
283
283
  child.stdout.on("data", (data) => {
@@ -345,93 +345,248 @@ var Engine = class {
345
345
  }
346
346
  };
347
347
 
348
- // src/lib/DbConfig.ts
349
- import Database from "better-sqlite3";
348
+ // src/lib/SqliteExecutor.ts
349
+ import { exec } from "child_process";
350
350
  import * as path2 from "path";
351
+ import { promisify } from "util";
352
+ var execAsync = promisify(exec);
353
+ var SqliteExecutor = class {
354
+ binaryPath;
355
+ dbPath;
356
+ constructor(dbPath) {
357
+ this.dbPath = dbPath;
358
+ this.binaryPath = this.getBinaryPath();
359
+ }
360
+ getBinaryPath() {
361
+ const binDir = path2.resolve(__dirname, "..", "bin");
362
+ const platform2 = process.platform;
363
+ const extension = platform2 === "win32" ? ".exe" : "";
364
+ const binaryName = `sqlite-engine${extension}`;
365
+ return path2.join(binDir, binaryName);
366
+ }
367
+ async executeBinary(args) {
368
+ const command = `"${this.binaryPath}" ${args.map((arg) => `"${arg}"`).join(" ")}`;
369
+ try {
370
+ const { stdout, stderr } = await execAsync(command, {
371
+ maxBuffer: 10 * 1024 * 1024,
372
+ // 10MB buffer
373
+ timeout: 3e4
374
+ // 30s timeout
375
+ });
376
+ if (stderr && stderr.trim()) {
377
+ console.warn("SQLite Engine Warning:", stderr);
378
+ }
379
+ const result = JSON.parse(stdout.trim());
380
+ return result;
381
+ } catch (error) {
382
+ if (error.stdout) {
383
+ try {
384
+ const result = JSON.parse(error.stdout.trim());
385
+ return result;
386
+ } catch (parseError) {
387
+ }
388
+ }
389
+ throw new Error(`SQLite execution failed: ${error.message}`);
390
+ }
391
+ }
392
+ async connect() {
393
+ try {
394
+ const result = await this.executeBinary([
395
+ "--action",
396
+ "connect",
397
+ "--database",
398
+ this.dbPath
399
+ ]);
400
+ return result.status === "success";
401
+ } catch (error) {
402
+ return false;
403
+ }
404
+ }
405
+ async exists() {
406
+ try {
407
+ const result = await this.executeBinary([
408
+ "--action",
409
+ "exists",
410
+ "--database",
411
+ this.dbPath
412
+ ]);
413
+ return result.status === "success" && result.data === true;
414
+ } catch (error) {
415
+ return false;
416
+ }
417
+ }
418
+ async query(sql, params) {
419
+ const args = [
420
+ "--action",
421
+ "query",
422
+ "--database",
423
+ this.dbPath,
424
+ "--query",
425
+ sql
426
+ ];
427
+ if (params && params.length > 0) {
428
+ args.push("--params", JSON.stringify(params));
429
+ }
430
+ return this.executeBinary(args);
431
+ }
432
+ // Método para múltiples queries (como lo hace better-sqlite3)
433
+ async queryMultiple(sql) {
434
+ return this.query(sql);
435
+ }
436
+ // Método prepare que simula prepared statements
437
+ prepare(sql) {
438
+ return {
439
+ all: async (...params) => {
440
+ const result = await this.query(sql, params);
441
+ if (result.status === "error") {
442
+ throw new Error(result.message);
443
+ }
444
+ return Array.isArray(result.data) ? result.data : [];
445
+ },
446
+ run: async (...params) => {
447
+ const result = await this.query(sql, params);
448
+ if (result.status === "error") {
449
+ throw new Error(result.message);
450
+ }
451
+ if (typeof result.data === "object" && result.data.hasOwnProperty("changes") && result.data.hasOwnProperty("lastID")) {
452
+ return result.data;
453
+ }
454
+ return { changes: 0, lastID: 0 };
455
+ }
456
+ };
457
+ }
458
+ // Para compatibilidad con better-sqlite3 API sincrona usando deasync si es necesario
459
+ prepareSync(sql) {
460
+ const deasync = __require("deasync");
461
+ return {
462
+ all: (...params) => {
463
+ let result;
464
+ let done = false;
465
+ let error;
466
+ this.query(sql, params).then((res) => {
467
+ if (res.status === "error") {
468
+ error = new Error(res.message);
469
+ } else {
470
+ result = Array.isArray(res.data) ? res.data : [];
471
+ }
472
+ done = true;
473
+ }).catch((err) => {
474
+ error = err;
475
+ done = true;
476
+ });
477
+ deasync.loopWhile(() => !done);
478
+ if (error) throw error;
479
+ return result;
480
+ },
481
+ run: (...params) => {
482
+ let result;
483
+ let done = false;
484
+ let error;
485
+ this.query(sql, params).then((res) => {
486
+ if (res.status === "error") {
487
+ error = new Error(res.message);
488
+ } else if (typeof res.data === "object" && res.data.hasOwnProperty("changes") && res.data.hasOwnProperty("lastID")) {
489
+ result = res.data;
490
+ } else {
491
+ result = { changes: 0, lastID: 0 };
492
+ }
493
+ done = true;
494
+ }).catch((err) => {
495
+ error = err;
496
+ done = true;
497
+ });
498
+ deasync.loopWhile(() => !done);
499
+ if (error) throw error;
500
+ return result;
501
+ }
502
+ };
503
+ }
504
+ };
505
+
506
+ // src/lib/DbConfig.ts
507
+ import * as path3 from "path";
351
508
  import fs from "fs";
352
- var rootPath = path2.resolve(process.cwd(), ".dbcube");
509
+ var rootPath = path3.resolve(process.cwd(), ".dbcube");
353
510
  var SQLite = class {
354
- db = null;
511
+ executor = null;
355
512
  database;
356
513
  constructor(config) {
357
514
  this.database = config.DATABASE;
358
515
  }
359
- ifExist() {
516
+ async ifExist() {
360
517
  if (this.database) {
361
518
  const dbPath = this.database || ":memory:";
362
- const configPath = path2.join(rootPath, dbPath + ".db");
519
+ const configPath = path3.join(rootPath, dbPath + ".db");
363
520
  if (!fs.existsSync(rootPath)) {
364
521
  fs.mkdirSync(rootPath, { recursive: true });
365
522
  }
366
523
  if (fs.existsSync(configPath)) {
367
524
  return true;
368
525
  }
526
+ if (!this.executor) {
527
+ this.executor = new SqliteExecutor(configPath);
528
+ }
529
+ return await this.executor.exists();
369
530
  }
370
531
  return false;
371
532
  }
372
533
  async connect() {
373
- return new Promise((resolve2, reject) => {
534
+ return new Promise(async (resolve3, reject) => {
374
535
  try {
375
- if (!this.db) {
536
+ if (!this.executor) {
376
537
  const dbPath = this.database || ":memory:";
377
- const configPath = path2.join(rootPath, dbPath + ".db");
538
+ const configPath = path3.join(rootPath, dbPath + ".db");
378
539
  if (!fs.existsSync(rootPath)) {
379
540
  fs.mkdirSync(rootPath, { recursive: true });
380
541
  }
381
- this.db = new Database(configPath);
542
+ this.executor = new SqliteExecutor(configPath);
543
+ const connected = await this.executor.connect();
544
+ if (!connected) {
545
+ throw new Error("Failed to connect to SQLite database");
546
+ }
382
547
  }
383
- resolve2(this.db);
548
+ resolve3(this.executor);
384
549
  } catch (error) {
385
550
  reject(error);
386
551
  }
387
552
  });
388
553
  }
389
554
  async disconnect() {
390
- return new Promise((resolve2) => {
391
- if (this.db) {
392
- this.db.close();
393
- this.db = null;
555
+ return new Promise((resolve3) => {
556
+ if (this.executor) {
557
+ this.executor = null;
394
558
  }
395
- resolve2();
559
+ resolve3();
396
560
  });
397
561
  }
398
562
  async query(sqlQuery) {
399
- return new Promise(async (resolve2) => {
563
+ return new Promise(async (resolve3) => {
400
564
  try {
401
565
  if (typeof sqlQuery !== "string") {
402
566
  throw new Error("The SQL query must be a string.");
403
567
  }
404
- if (!this.db) {
568
+ if (!this.executor) {
405
569
  await this.connect();
406
570
  }
407
- if (!this.db) {
571
+ if (!this.executor) {
408
572
  throw new Error("Database connection is not available.");
409
573
  }
410
- const sqlCommands = sqlQuery.split(";").filter((cmd) => cmd.trim().length > 0);
411
- const results = [];
412
- for (const command of sqlCommands) {
413
- const query = `${command};`;
414
- const isSelect = query.trim().toLowerCase().startsWith("select");
415
- if (isSelect) {
416
- const stmt = this.db.prepare(query);
417
- const rows = stmt.all();
418
- results.push(rows);
419
- } else {
420
- const stmt = this.db.prepare(query);
421
- const result = stmt.run();
422
- results.push({
423
- changes: result.changes,
424
- lastID: result.lastInsertRowid
425
- });
426
- }
574
+ const result = await this.executor.queryMultiple(sqlQuery);
575
+ if (result.status === "error") {
576
+ resolve3({
577
+ status: "error",
578
+ message: result.message,
579
+ data: null
580
+ });
581
+ } else {
582
+ resolve3({
583
+ status: "success",
584
+ message: "Query executed successfully",
585
+ data: result.data
586
+ });
427
587
  }
428
- resolve2({
429
- status: "success",
430
- message: "Query executed successfully",
431
- data: results.length === 1 ? results[0] : results
432
- });
433
588
  } catch (error) {
434
- resolve2({
589
+ resolve3({
435
590
  status: "error",
436
591
  message: error.message || "An error occurred while executing the query.",
437
592
  data: null
@@ -440,7 +595,7 @@ var SQLite = class {
440
595
  });
441
596
  }
442
597
  async queryWithParameters(sqlQuery, params = []) {
443
- return new Promise(async (resolve2) => {
598
+ return new Promise(async (resolve3) => {
444
599
  try {
445
600
  if (typeof sqlQuery !== "string") {
446
601
  throw new Error("The SQL query must be a string.");
@@ -448,35 +603,29 @@ var SQLite = class {
448
603
  if (!Array.isArray(params)) {
449
604
  throw new Error("Parameters must be an array.");
450
605
  }
451
- if (!this.db) {
606
+ if (!this.executor) {
452
607
  await this.connect();
453
608
  }
454
- if (!this.db) {
609
+ if (!this.executor) {
455
610
  throw new Error("Database connection is not available.");
456
611
  }
457
- const isSelect = sqlQuery.trim().toLowerCase().startsWith("select");
458
- const stmt = this.db.prepare(sqlQuery);
459
- if (isSelect) {
460
- const rows = stmt.all(...params);
461
- resolve2({
462
- status: "success",
463
- message: "Query executed successfully",
464
- data: rows
612
+ const result = await this.executor.query(sqlQuery, params);
613
+ if (result.status === "error") {
614
+ resolve3({
615
+ status: "error",
616
+ message: result.message,
617
+ data: null
465
618
  });
466
619
  } else {
467
- const result = stmt.run(...params);
468
- resolve2({
620
+ resolve3({
469
621
  status: "success",
470
622
  message: "Query executed successfully",
471
- data: {
472
- changes: result.changes,
473
- lastID: result.lastInsertRowid
474
- }
623
+ data: result.data
475
624
  });
476
625
  }
477
626
  } catch (error) {
478
627
  console.log(error);
479
- resolve2({
628
+ resolve3({
480
629
  status: "error",
481
630
  message: error.message || "An error occurred while executing the query.",
482
631
  data: null
@@ -571,7 +720,7 @@ var DbConfig_default = DbConfig;
571
720
 
572
721
  // src/lib/FileLogger.ts
573
722
  import * as fs2 from "fs";
574
- import * as path3 from "path";
723
+ import * as path4 from "path";
575
724
  import { EventEmitter } from "events";
576
725
  var FileLogger = class _FileLogger extends EventEmitter {
577
726
  static watchers = /* @__PURE__ */ new Map();
@@ -586,7 +735,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
586
735
  */
587
736
  static async write(filePath, message, level = "INFO", append = true) {
588
737
  try {
589
- const dir = path3.dirname(filePath);
738
+ const dir = path4.dirname(filePath);
590
739
  if (!fs2.existsSync(dir)) {
591
740
  fs2.mkdirSync(dir, { recursive: true });
592
741
  }
@@ -625,7 +774,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
625
774
  const buffer = _FileLogger.buffers.get(filePath);
626
775
  if (buffer && buffer.length > 0) {
627
776
  try {
628
- const dir = path3.dirname(filePath);
777
+ const dir = path4.dirname(filePath);
629
778
  if (!fs2.existsSync(dir)) {
630
779
  fs2.mkdirSync(dir, { recursive: true });
631
780
  }
@@ -946,7 +1095,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
946
1095
  var ComputedFieldProcessor = class {
947
1096
  static async getComputedFields(name) {
948
1097
  let computedFields = [];
949
- if (DbConfig_default.ifExist()) {
1098
+ if (await DbConfig_default.ifExist()) {
950
1099
  await DbConfig_default.connect();
951
1100
  try {
952
1101
  const tableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='dbcube_computes_config'`;
@@ -1245,7 +1394,7 @@ var TableProcessor = class {
1245
1394
  }
1246
1395
  return true;
1247
1396
  }
1248
- if (DbConfig_default.ifExist()) {
1397
+ if (await DbConfig_default.ifExist()) {
1249
1398
  await DbConfig_default.connect();
1250
1399
  try {
1251
1400
  const tableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='dbcube_computes_config'`;
@@ -1287,7 +1436,7 @@ var TableProcessor = class {
1287
1436
  }
1288
1437
  }
1289
1438
  static async saveQuery(table_ref, database_ref, struct) {
1290
- if (DbConfig_default.ifExist()) {
1439
+ if (await DbConfig_default.ifExist()) {
1291
1440
  await DbConfig_default.connect();
1292
1441
  try {
1293
1442
  await DbConfig_default.query(`DELETE FROM dbcube_schemas_config WHERE table_ref='${table_ref}' AND database_ref='${database_ref}'`);
@@ -1303,7 +1452,7 @@ var TableProcessor = class {
1303
1452
  var TriggerProcessor = class {
1304
1453
  static async getTriggers(name) {
1305
1454
  let triggers = [];
1306
- if (DbConfig_default.ifExist()) {
1455
+ if (await DbConfig_default.ifExist()) {
1307
1456
  await DbConfig_default.connect();
1308
1457
  try {
1309
1458
  const tableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='dbcube_triggers_config'`;