dbcube
Version:
268 lines (263 loc) • 8.66 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
Database: () => import_query_builder2.Database,
Table: () => import_query_builder2.Table,
dbcube: () => dbcube
});
module.exports = __toCommonJS(index_exports);
// src/lib/Dbcube.ts
var import_core = require("@dbcube/core");
var import_query_builder = require("@dbcube/query-builder");
// src/lib/FileUtils.ts
var fs = __toESM(require("fs"));
var path = __toESM(require("path"));
var FileUtils = class {
/**
* Verifica si un archivo existe (asincrónico).
* @param filePath - Ruta del archivo.
* @returns Promise que resuelve true si el archivo existe, false si no.
*/
static async fileExists(filePath) {
return new Promise((resolve2) => {
fs.access(path.resolve(filePath), fs.constants.F_OK, (err) => {
resolve2(!err);
});
});
}
/**
* Verifica si un archivo existe (sincrónico).
* @param filePath - Ruta del archivo.
* @returns True si el archivo existe, false si no.
*/
static fileExistsSync(filePath) {
try {
fs.accessSync(path.resolve(filePath), fs.constants.F_OK);
return true;
} catch {
return false;
}
}
/**
* Extrae el nombre de la base de datos de un string con formato @database().
* @param input - String de entrada que contiene la referencia a la base de datos.
* @returns El nombre de la base de datos o null si no se encuentra.
*/
static extractDatabaseName(input) {
const match = input.match(/@database\(["']?([\w-]+)["']?\)/);
return match ? match[1] : null;
}
/**
* Lee recursivamente archivos que terminan en un sufijo dado y los ordena numéricamente.
* @param dir - Directorio base (relativo o absoluto).
* @param suffix - Sufijo de archivo (como 'table.cube').
* @returns Rutas absolutas de los archivos encontrados y ordenados.
*/
static getCubeFilesRecursively(dir, suffix) {
const baseDir = path.resolve(dir);
const cubeFiles = [];
function recurse(currentDir) {
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
recurse(fullPath);
} else if (entry.isFile() && (entry.name.endsWith(suffix) || entry.name.includes(suffix))) {
cubeFiles.push(fullPath);
}
}
}
recurse(baseDir);
cubeFiles.sort((a, b) => {
const aNum = parseInt(path.basename(a));
const bNum = parseInt(path.basename(b));
return (isNaN(aNum) ? 0 : aNum) - (isNaN(bNum) ? 0 : bNum);
});
return cubeFiles;
}
};
var FileUtils_default = FileUtils;
// src/lib/Dbcube.ts
var import_path = __toESM(require("path"));
var import_module = require("module");
var Dbcube = class _Dbcube {
static instance;
configPath;
config;
databases;
/**
* Creates a new Dbcube instance (Singleton pattern)
*
* @constructor
* @example
* ```typescript
* const dbcube = new Dbcube();
* ```
*/
constructor() {
if (_Dbcube.instance) {
return _Dbcube.instance;
}
this.configPath = import_path.default.join(process.cwd(), "dbcube.config.js");
this.config = new import_core.Config();
this.databases = {};
_Dbcube.instance = this;
}
/**
* Loads configuration from dbcube.config.js file
*
* @private
* @returns {Promise<void>}
* @throws {Error} If config file doesn't exist
*/
async loadConfig() {
const exists = await FileUtils_default.fileExists(this.configPath);
exists ?? console.log("\u274C Dont exists config file, please create a dbcube.config.js file");
}
/**
* Initializes the Dbcube ORM with database configurations
*
* @param {Object} configCreate - Optional configuration for creating new database
* @param {string} [configCreate.databaseName] - Name of the database to create
* @param {string} [configCreate.motor] - Database engine (mysql, postgres, sqlite, mongodb)
* @param {any} [configCreate.configAnswers] - Additional configuration answers
* @returns {Promise<void>}
*
* @example
* ```typescript
* // Initialize with existing config
* await dbcube.init();
*
* // Initialize with new database creation
* await dbcube.init({
* databaseName: 'myapp',
* motor: 'mysql'
* });
* ```
*/
init(configCreate = {}) {
let config;
try {
const requireUrl = typeof __filename !== "undefined" ? __filename : process.cwd();
const require2 = (0, import_module.createRequire)(requireUrl);
delete require2.cache[require2.resolve(this.configPath)];
const configModule = require2(this.configPath);
config = configModule.default || configModule;
} catch (error) {
console.log("\u274C Config load error:", error);
if (error.code === "MODULE_NOT_FOUND") {
console.log("\u274C Config file not found, please create a dbcube.config.js file");
return;
}
throw error;
}
config(this.config);
const databases = Object.keys(this.config.getAllDatabases());
for (const database of databases) {
this.databases[database] = new import_query_builder.Database(database);
}
if (configCreate.databaseName) {
this.databases[configCreate.databaseName] = new import_query_builder.Database(configCreate.databaseName);
}
}
/**
* Gets a database connection instance for query building
*
* @param {string} databaseName - Name of the database configuration
* @returns {Database} Database instance with query builder capabilities
*
* @example
* ```typescript
* // Get database connection
* const db = dbcube.database('myapp');
*
* // Use query builder methods
* const users = await db.table('users')
* .select(['id', 'name', 'email'])
* .where('status', 'active')
* .orderBy('created_at', 'desc')
* .limit(10)
* .get();
*
* // Insert data
* await db.table('users').insert({
* name: 'John Doe',
* email: 'john@example.com'
* });
*
* // Update data
* await db.table('users')
* .where('id', 1)
* .update({ status: 'inactive' });
*
* // Delete data
* await db.table('users').where('id', 1).delete();
* ```
*/
database(databaseName) {
return this.databases[databaseName];
}
};
// src/index.ts
var import_query_builder2 = require("@dbcube/query-builder");
var dbcube = new Dbcube();
dbcube.init();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Database,
Table,
dbcube
});
/**
* Dbcube ORM - Main class for database management
*
* A lightweight, flexible ORM that supports multiple database engines including
* MySQL, PostgreSQL, SQLite, and MongoDB with a fluent query builder interface.
*
* @example
* ```typescript
* import { Dbcube } from 'dbcube';
*
* const dbcube = new Dbcube();
* await dbcube.init();
*
* // Get a database connection
* const db = dbcube.database('myDatabase');
*
* // Use query builder
* const users = await db.table('users').select().where('active', true).get();
* ```
*
* @class
* @author Albert Araya
* @license MIT
*/
//# sourceMappingURL=index.cjs.map