UNPKG

simplifield-sql

Version:

A simplifield sql package that makes your work more easier, simpler and smarter!.

98 lines 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @description This function is used to create a new table * @returns Promise * @example * await db.createTable("users", [ * { * name: "id", * dataType: "INT", * primaryKey: true, * autoIncrement: true, * }, * { * name: "username", * dataType: "VARCHAR", * dataLength: 255, * characterSet: "utf8mb4", * collation: "utf8mb4_general_ci", * allowNull: false, * unique: true, * }, * ]); * // output: { * // table: "users", * // rows: [ * // { * // name: "id", * // dataType: "INT", * // primaryKey: true, * // autoIncrement: true, * // }, * // { * // name: "username", * // dataType: "VARCHAR(255)", * // characterSet: "utf8mb4", * // collation: "utf8mb4_general_ci", * // allowNull: false, * // unique: true, * // } * // ] * } */ async function default_1(table, rows) { const Class = this; return new Promise((resolve, reject) => { if (!table) reject('"table" param is required.'); if (typeof table !== "string") reject('"table" type should be string.'); if (!rows) reject('"rows" param is required.'); if (typeof rows !== "object") reject('"rows" type should be Row[] type.'); const rowDefinitions = rows .map((row) => { let rowDefinition = `\`${row.name}\` ${row.dataType}(${row.dataLength || 11})`; if (row.characterSet) { rowDefinition += ` CHARACTER SET ${row.characterSet}`; } if (row.collation) { rowDefinition += ` COLLATE ${row.collation}`; } if (!row.allowNull) { rowDefinition += " NOT NULL"; } if (row.defaultValue !== undefined) { if (row.defaultValue === null) { rowDefinition += " DEFAULT NULL"; } else { rowDefinition += ` DEFAULT '${row.defaultValue}'`; } } if (row.primaryKey) { rowDefinition += " PRIMARY KEY"; } if (row.autoIncrement) { rowDefinition += " AUTO_INCREMENT"; } if (row.unique) { rowDefinition += " UNIQUE"; } return rowDefinition; }) .join(", "); Class.db?.query(`CREATE TABLE \`${table}\` (${rowDefinitions});`, (err, result) => { if (err) reject(err); else { resolve({ table, rows }); Class.emit("createTable", table); } }); }); } exports.default = default_1; //# sourceMappingURL=createTable.js.map