datasquirel/package-shared/shell/utils/createTable.js

214 lines
7.3 KiB
JavaScript
Raw Normal View History

2023-09-21 14:00:04 +00:00
// @ts-check
2024-12-06 10:31:24 +00:00
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
2023-09-21 14:00:04 +00:00
const generateColumnDescription = require("./generateColumnDescription");
const supplementTable = require("./supplementTable");
2024-12-06 10:31:24 +00:00
const dbHandler = require("./dbHandler");
2023-09-21 14:00:04 +00:00
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
2024-10-14 06:49:01 +00:00
/**
*
2024-12-06 10:31:24 +00:00
* @param {object} params
* @param {string} params.dbFullName
* @param {string} params.tableName
* @param {any[]} params.tableInfoArray
* @param {import("../../types").DSQL_DatabaseSchemaType[]} [params.dbSchema]
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema]
* @param {any} [params.recordedDbEntry]
* @param {boolean} [params.clone] - Is this a newly cloned table?
2024-10-14 06:49:01 +00:00
* @returns
*/
module.exports = async function createTable({
dbFullName,
tableName,
tableInfoArray,
dbSchema,
2024-12-06 10:31:24 +00:00
clone,
tableSchema,
recordedDbEntry,
2024-10-14 06:49:01 +00:00
}) {
2023-09-21 14:00:04 +00:00
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
/**
* Grab Schema
*
* @description Grab Schema
*/
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
2024-12-06 10:31:24 +00:00
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
try {
if (!recordedDbEntry) {
throw new Error("Recorded Db entry not found!");
}
const existingTable = await varDatabaseDbHandler({
database: "datasquirel",
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
queryValuesArray: [recordedDbEntry.id, tableSchema?.tableName],
});
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
const table = existingTable?.[0];
if (!table?.id) {
const newTableEntry = await dbHandler({
query: `INSERT INTO user_database_tables SET ?`,
values: {
user_id: recordedDbEntry.user_id,
db_id: recordedDbEntry.id,
db_slug: recordedDbEntry.db_slug,
table_name: tableSchema?.tableFullName,
table_slug: tableSchema?.tableName,
child_table: tableSchema?.childTable ? "1" : null,
child_table_parent_database:
tableSchema?.childTableDbFullName || null,
child_table_parent_table:
tableSchema?.childTableName || null,
date_created: Date(),
date_created_code: Date.now(),
date_updated: Date(),
date_updated_code: Date.now(),
},
database: "datasquirel",
});
}
} catch (error) {}
////////////////////////////////////////
////////////////////////////////////////
2023-09-21 14:00:04 +00:00
////////////////////////////////////////
let primaryKeySet = false;
2024-12-08 08:58:57 +00:00
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
2023-09-21 14:00:04 +00:00
let foreignKeys = [];
////////////////////////////////////////
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
2024-12-06 10:31:24 +00:00
const {
fieldName,
dataType,
nullValue,
primaryKey,
autoIncrement,
defaultValue,
defaultValueLiteral,
foreignKey,
updatedField,
onUpdate,
onUpdateLiteral,
onDelete,
onDeleteLiteral,
defaultField,
encrypted,
json,
newTempField,
notNullValue,
originName,
plainText,
pattern,
patternFlags,
richText,
} = column;
2023-09-21 14:00:04 +00:00
if (foreignKey) {
foreignKeys.push({
2024-12-08 08:58:57 +00:00
...column,
2023-09-21 14:00:04 +00:00
});
}
2024-10-14 06:49:01 +00:00
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({
columnData: column,
primaryKeySet: primaryKeySet,
});
2023-09-21 14:00:04 +00:00
primaryKeySet = newPrimaryKeySet;
////////////////////////////////////////
const comma = (() => {
if (foreignKeys[0]) return ",";
if (i === finalTable.length - 1) return "";
return ",";
})();
createTableQueryArray.push(" " + fieldEntryText + comma);
////////////////////////////////////////
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (foreignKeys[0]) {
foreignKeys.forEach((foreighKey, index, array) => {
2024-12-08 08:58:57 +00:00
const fieldName = foreighKey.fieldName;
const destinationTableName =
foreighKey.foreignKey?.destinationTableName;
const destinationTableColumnName =
foreighKey.foreignKey?.destinationTableColumnName;
const cascadeDelete = foreighKey.foreignKey?.cascadeDelete;
const cascadeUpdate = foreighKey.foreignKey?.cascadeUpdate;
const foreignKeyName = foreighKey.foreignKey?.foreignKeyName;
2023-09-21 14:00:04 +00:00
const comma = (() => {
if (index === foreignKeys.length - 1) return "";
return ",";
})();
2024-10-14 06:49:01 +00:00
createTableQueryArray.push(
` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${
cascadeDelete ? " ON DELETE CASCADE" : ""
}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`
);
2023-09-21 14:00:04 +00:00
});
}
////////////////////////////////////////
2024-10-14 06:49:01 +00:00
createTableQueryArray.push(
`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`
);
2023-09-21 14:00:04 +00:00
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = await varDatabaseDbHandler({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */