93 lines
2.6 KiB
TypeScript
93 lines
2.6 KiB
TypeScript
import varDatabaseDbHandler from "./varDatabaseDbHandler";
|
|
import generateColumnDescription from "./generateColumnDescription";
|
|
import supplementTable from "./supplementTable";
|
|
import { DSQL_FieldSchemaType, DSQL_TableSchemaType } from "../../types";
|
|
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
|
|
import handleTableForeignKey from "./handle-table-foreign-key";
|
|
import createTableHandleTableRecord from "./create-table-handle-table-record";
|
|
|
|
type Param = {
|
|
dbFullName: string;
|
|
tableName: string;
|
|
tableInfoArray: DSQL_FieldSchemaType[];
|
|
tableSchema?: DSQL_TableSchemaType;
|
|
recordedDbEntry?: DSQL_DATASQUIREL_USER_DATABASES;
|
|
isMain?: boolean;
|
|
};
|
|
|
|
/**
|
|
* # Create Table Functions
|
|
*/
|
|
export default async function createTable({
|
|
dbFullName,
|
|
tableName,
|
|
tableInfoArray,
|
|
tableSchema,
|
|
recordedDbEntry,
|
|
isMain,
|
|
}: Param) {
|
|
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
|
|
|
|
let tableId = await createTableHandleTableRecord({
|
|
recordedDbEntry,
|
|
tableSchema,
|
|
isMain,
|
|
});
|
|
|
|
if (!tableId && !isMain) throw new Error(`Couldn't grab table ID`);
|
|
|
|
const createTableQueryArray = [];
|
|
|
|
createTableQueryArray.push(
|
|
`CREATE TABLE IF NOT EXISTS \`${dbFullName}\`.\`${tableName}\` (`
|
|
);
|
|
|
|
let primaryKeySet = false;
|
|
|
|
for (let i = 0; i < finalTable.length; i++) {
|
|
const column = finalTable[i];
|
|
|
|
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({
|
|
columnData: column,
|
|
primaryKeySet: primaryKeySet,
|
|
});
|
|
|
|
primaryKeySet = newPrimaryKeySet;
|
|
|
|
const comma = (() => {
|
|
if (i === finalTable.length - 1) return "";
|
|
return ",";
|
|
})();
|
|
|
|
createTableQueryArray.push(" " + fieldEntryText + comma);
|
|
}
|
|
|
|
createTableQueryArray.push(
|
|
`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`
|
|
);
|
|
|
|
const createTableQuery = createTableQueryArray.join("\n");
|
|
|
|
const newTable = await varDatabaseDbHandler({
|
|
queryString: createTableQuery,
|
|
});
|
|
|
|
for (let i = 0; i < finalTable.length; i++) {
|
|
const column = finalTable[i];
|
|
const { foreignKey, fieldName } = column;
|
|
|
|
if (!fieldName) continue;
|
|
|
|
if (foreignKey) {
|
|
await handleTableForeignKey({
|
|
dbFullName,
|
|
foreignKey,
|
|
tableName,
|
|
fieldName,
|
|
});
|
|
}
|
|
}
|
|
|
|
return tableId;
|
|
}
|