Pull-request para export a Oracle (#4)

* Permito deployment en un subfolder

* Remove vercel/analytics

* Remove vercel/analytics

* Remove vercel/analytics

* Revert "Permito deployment en un subfolder"

This reverts commit e7aedc3ecf.

* Boton de oracle funciona pero no add table

* datatypes.js fixed

* export oracle funciona, falta formato adecuado

* Agregando convenciones a constraints

* Cambiando detalle de unique constraint

* Adding a test for diagram exports to oracle

* tests for constraints added

* Correccion de la funcion check

* vercel added and tests run with npm run lint

* little fixes, vercel added in datatypes and main.jsx

* Delete tatus file added by mistake

---------

Co-authored-by: Francisco-Galindo <paqui10718@gmail.com>
Co-authored-by: hansmarcus <hansmarcus14@gmail.com>
Co-authored-by: Pablo Estrada <pabloem@apache.org>
This commit is contained in:
lethalSopaper
2025-02-06 22:41:42 -06:00
committed by GitHub
parent aaf83b6f28
commit d95b86b7b5
20 changed files with 5173 additions and 345 deletions

BIN
src/assets/oracle-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

@@ -31,6 +31,7 @@ import {
jsonToSQLite,
jsonToMariaDB,
jsonToSQLServer,
jsonToOracle,
} from "../../utils/exportSQL/generic";
import {
ObjectType,
@@ -824,6 +825,12 @@ export default function ControlPanel({
setImportDb(DB.MSSQL);
},
},
{
Oracle: () => {
setModal(MODAL.IMPORT_SRC);
setImportDb(DB.ORACLE);
},
},
],
}),
function: () => {
@@ -915,6 +922,22 @@ export default function ControlPanel({
}));
},
},
{
Oracle: () => {
setModal(MODAL.CODE);
const src = jsonToOracle({
tables: tables,
references: relationships,
types: types,
database: database,
});
setExportData((prev) => ({
...prev,
data: src,
extension: "sql",
}));
}
},
],
}),
function: () => {

View File

@@ -113,5 +113,6 @@ export const DB = {
MSSQL: "transactsql",
SQLITE: "sqlite",
MARIADB: "mariadb",
ORACLE: "oracledb",
GENERIC: "generic",
};

View File

@@ -3,6 +3,7 @@ import postgresImage from "../assets/postgres-icon.png";
import sqliteImage from "../assets/sqlite-icon.png";
import mariadbImage from "../assets/mariadb-icon.png";
import mssqlImage from "../assets/mssql-icon.png";
import oracleImage from "../assets/oracle-icon.png";
import i18n from "../i18n/i18n";
import { DB } from "./constants";
@@ -42,6 +43,12 @@ export const databases = new Proxy(
image: mssqlImage,
hasTypes: false,
},
[DB.ORACLE]: {
name: "Oracle",
label: DB.ORACLE,
image: oracleImage,
hasTypes: true,
},
[DB.GENERIC]: {
name: i18n.t("generic"),
label: DB.GENERIC,

View File

@@ -7,6 +7,16 @@ const binaryRegex = /^[01]+$/;
/* eslint-disable no-unused-vars */
const defaultTypesBase = {
NUMBER: {
type: "NUMBER",
checkDefault: (field) => {
return intRegex.test(field.default);
},
hasCheck: true,
isSized: false,
hasPrecision: true,
canIncrement: true,
},
INT: {
type: "INT",
checkDefault: (field) => {
@@ -263,12 +273,193 @@ const defaultTypesBase = {
hasPrecision: false,
noDefault: true,
},
VARCHAR2: {
type: "VARCHAR2",
checkDefault: (field) => {
if (strHasQuotes(field.default)) {
return field.default.length - 2 <= field.size;
}
return field.default.length <= field.size;
},
hasCheck: true,
isSized: true,
hasPrecision: false,
defaultSize: 10,
},
};
export const defaultTypes = new Proxy(defaultTypesBase, {
get: (target, prop) => (prop in target ? target[prop] : false),
});
const oracleTypesBase = {
VARCHAR2: {
type: "VARCHAR2",
checkDefault: (field) => {
if (strHasQuotes(field.default)) {
return field.default.length - 2 <= field.size;
}
return field.default.length <= field.size;
},
hasCheck: true,
isSized: true,
hasPrecision: false,
defaultSize: 255,
hasQuotes: true,
},
NUMBER: {
type: "NUMBER",
checkDefault: (field) => {
return intRegex.test(field.default);
},
hasCheck: true,
isSized: false,
hasPrecision: true,
canIncrement: true,
},
FLOAT: {
type: "FLOAT",
checkDefault: (field) => {
return doubleRegex.test(field.default);
},
hasCheck: true,
isSized: false,
hasPrecision: true,
},
CHAR: {
type: "CHAR",
checkDefault: (field) => {
if (strHasQuotes(field.default)) {
return field.default.length - 2 <= field.size;
}
return field.default.length <= field.size;
},
hasCheck: true,
isSized: true,
hasPrecision: false,
defaultSize: 1,
hasQuotes: true,
},
VARCHAR: {
type: "VARCHAR",
checkDefault: (field) => {
if (strHasQuotes(field.default)) {
return field.default.length - 2 <= field.size;
}
return field.default.length <= field.size;
},
hasCheck: true,
isSized: true,
hasPrecision: false,
defaultSize: 255,
hasQuotes: true,
},
TEXT: {
type: "TEXT",
checkDefault: (field) => true,
hasCheck: false,
isSized: true,
hasPrecision: false,
defaultSize: 65535,
hasQuotes: true,
},
TIME: {
type: "TIME",
checkDefault: (field) => {
return /^(?:[01]?\d|2[0-3]):[0-5]?\d:[0-5]?\d$/.test(field.default);
},
hasCheck: false,
isSized: false,
hasPrecision: false,
hasQuotes: true,
},
TIMESTAMP: {
type: "TIMESTAMP",
checkDefault: (field) => {
if (field.default.toUpperCase() === "CURRENT_TIMESTAMP") {
return true;
}
if (!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(field.default)) {
return false;
}
const content = field.default.split(" ");
const date = content[0].split("-");
return parseInt(date[0]) >= 1970 && parseInt(date[0]) <= 2038;
},
hasCheck: false,
isSized: false,
hasPrecision: false,
hasQuotes: true,
},
DATE: {
type: "DATE",
checkDefault: (field) => {
return /^\d{4}-\d{2}-\d{2}$/.test(field.default);
},
hasCheck: false,
isSized: false,
hasPrecision: false,
hasQuotes: true,
},
DATETIME: {
type: "DATETIME",
checkDefault: (field) => {
if (field.default.toUpperCase() === "CURRENT_TIMESTAMP") {
return true;
}
if (!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(field.default)) {
return false;
}
const c = field.default.split(" ");
const d = c[0].split("-");
return parseInt(d[0]) >= 1000 && parseInt(d[0]) <= 9999;
},
hasCheck: false,
isSized: false,
hasPrecision: false,
hasQuotes: true,
},
BOOLEAN: {
type: "BOOLEAN",
checkDefault: (field) => {
return (
field.default.toLowerCase() === "false" ||
field.default.toLowerCase() === "true" ||
field.default === "0" ||
field.default === "1"
);
},
hasCheck: false,
isSized: false,
hasPrecision: false,
},
BINARY: {
type: "BINARY",
checkDefault: (field) => {
return (
field.default.length <= field.size && binaryRegex.test(field.default)
);
},
hasCheck: false,
isSized: true,
hasPrecision: false,
defaultSize: 1,
hasQuotes: true,
},
BLOB: {
type: "BLOB",
checkDefault: (field) => true,
isSized: false,
hasCheck: false,
hasPrecision: false,
noDefault: true,
},
};
export const oracleTypes = new Proxy(oracleTypesBase, {
get: (target, prop) => (prop in target ? target[prop] : false),
});
const mysqlTypesBase = {
TINYINT: {
type: "TINYINT",
@@ -1754,6 +1945,7 @@ const dbToTypesBase = {
[DB.SQLITE]: sqliteTypes,
[DB.MSSQL]: mssqlTypes,
[DB.MARIADB]: mysqlTypes,
[DB.ORACLE]: oracleTypes,
};
export const dbToTypes = new Proxy(dbToTypesBase, {

View File

@@ -137,6 +137,43 @@ export function getTypeString(
}
}
export function jsonToOracle(obj) {
return `${obj.tables
.map(
(table) =>
`CREATE TABLE "${table.name}" (\n${table.fields
.map(
(field) =>
`"${field.name}" ${getTypeString(field, obj.database, "oracle")}${
field.notNull ? " NOT NULL" : ""
}${field.unique ? " UNIQUE" : ""}${
field.default !== "" ? ` DEFAULT ${parseDefault(field, obj.database)}` : ""
}${field.check ? ` CHECK(${field.check})` : ""}`,
)
.join(",\n")}${
table.fields.filter((f) => f.primary).length > 0
? `,\nPRIMARY KEY(${table.fields
.filter((f) => f.primary)
.map((f) => `"${f.name}"`)
.join(", ")})`
: ""
}\n);\n${table.indices
.map(
(i) =>
`CREATE ${i.unique ? "UNIQUE " : ""}INDEX "${i.name}"\nON "${table.name}" (${i.fields
.map((f) => `"${f}"`)
.join(", ")});`,
)
.join("\n")}`,
)
.join("\n")}\n${obj.references
.map(
(r) =>
`ALTER TABLE "${obj.tables[r.startTableId].name}"\nADD FOREIGN KEY("${obj.tables[r.startTableId].fields[r.startFieldId].name}") REFERENCES "${obj.tables[r.endTableId].name}"("${obj.tables[r.endTableId].fields[r.endFieldId].name}")\nON UPDATE ${r.updateConstraint.toUpperCase()} ON DELETE ${r.deleteConstraint.toUpperCase()};`,
)
.join("\n")}`;
}
export function jsonToMySQL(obj) {
return `${obj.tables
.map(

View File

@@ -4,6 +4,7 @@ import { toMSSQL } from "./mssql";
import { toMySQL } from "./mysql";
import { toPostgres } from "./postgres";
import { toSqlite } from "./sqlite";
import { toOracle } from "./oracle";
export function exportSQL(diagram) {
switch (diagram.database) {
@@ -17,6 +18,8 @@ export function exportSQL(diagram) {
return toMariaDB(diagram);
case DB.MSSQL:
return toMSSQL(diagram);
case DB.ORACLE:
return toOracle(diagram);
default:
return "";
}

View File

@@ -0,0 +1,59 @@
import { parseDefault } from "./shared";
export function toOracle(diagram) {
return `${diagram.tables
.map(
(table) =>
`CREATE TABLE ${table.name} (\n${table.fields
.map(
(field) =>
`\t"${field.name}" ${field.type}${field.size ? `(${field.size})` : ""}${
field.default !== "" ? ` DEFAULT ${parseDefault(field, diagram.database)}` : ""
}${field.notNull ? " NOT NULL" : ""}`
)
.join(",\n")}${
table.fields.filter((f) => f.unique && !f.primary).length > 0
? `,\n\t${table.fields
.filter((f) => f.unique && !f.primary)
.map((f) => `CONSTRAINT ${table.name}_${f.name}_uk UNIQUE("${f.name}")`)
.join(",\n\t")}`
: ""
}${
table.fields.filter((f) => f.check).length > 0
? `,\n\t${table.fields
.filter((f) => f.check)
.map((f) => `CONSTRAINT ${table.name}_${f.name}_chk CHECK("${f.name}" ${f.check})`)
.join(",\n\t")}`
: ""
}${
table.fields.filter((f) => f.primary).length > 0
? `,\n\tCONSTRAINT ${table.name}_pk PRIMARY KEY(${table.fields
.filter((f) => f.primary)
.map((f) => `"${f.name}"`)
.join(", ")})`
: ""
}\n);\n${table.comment ? `COMMENT ON TABLE ${table.name} IS '${table.comment}';` : ""}${table.fields
.map(
(field) =>
field.comment ? `\nCOMMENT ON COLUMN "${table.name}"."${field.name}" IS '${field.comment}';` : ""
)
.join("")}\n${table.indices
.map(
(i) =>
`\nCREATE ${i.unique ? "UNIQUE " : ""}INDEX "${i.name}" ON ${table.name} (${i.fields
.map((f) => `"${f}"`)
.join(", ")});`
)
.join("")}`
)
.join("\n")}\n${diagram.references
.map(
(r) => {
const deleteConstraint = r.deleteConstraint && ['CASCADE', 'SET NULL'].includes(r.deleteConstraint.toUpperCase())
? ` ON DELETE ${r.deleteConstraint.toUpperCase()}`
: '';
return `ALTER TABLE ${diagram.tables[r.startTableId].name} ADD CONSTRAINT ${diagram.tables[r.startTableId].name}_${diagram.tables[r.startTableId].fields[r.startFieldId].name}_fk\nFOREIGN KEY("${diagram.tables[r.startTableId].fields[r.startFieldId].name}") REFERENCES ${diagram.tables[r.endTableId].name}("${diagram.tables[r.endTableId].fields[r.endFieldId].name}")${deleteConstraint};`
}
)
.join("\n")}`;
}

View File

@@ -0,0 +1,268 @@
// Import SQL files from Oracle database
import { Cardinality, DB } from "../../data/constants";
import { dbToTypes } from "../../data/datatypes";
import { buildSQLFromAST } from "./shared";
const affinity = {
[DB.MARIADB]: new Proxy(
{ INT: "INTEGER" },
{ get: (target, prop) => (prop in target ? target[prop] : "BLOB") },
),
[DB.GENERIC]: new Proxy(
{
INT: "INTEGER",
TINYINT: "SMALLINT",
MEDIUMINT: "INTEGER",
BIT: "BOOLEAN",
YEAR: "INTEGER",
},
{ get: (target, prop) => (prop in target ? target[prop] : "BLOB") },
),
};
export function fromOracle(ast, diagramDb = DB.GENERIC) {
const tables = [];
const relationships = [];
const parseSingleStatement = (e) => {
if (e.type === "create") {
if (e.keyword === "table") {
const table = {};
table.name = e.table[0].table;
table.comment = "";
table.color = "#175e7a";
table.fields = [];
table.indices = [];
table.id = tables.length;
e.create_definitions.forEach((d) => {
if (d.resource === "column") {
const field = {};
field.name = d.column.column;
let type = d.definition.dataType;
if (!dbToTypes[diagramDb][type]) {
type = affinity[diagramDb][type];
}
field.type = type;
if (d.definition.expr && d.definition.expr.type === "expr_list") {
field.values = d.definition.expr.value.map((v) => v.value);
}
field.comment = d.comment ? d.comment.value.value : "";
field.unique = false;
if (d.unique) field.unique = true;
field.increment = false;
if (d.auto_increment) field.increment = true;
field.notNull = false;
if (d.nullable) field.notNull = true;
field.primary = false;
if (d.primary_key) field.primary = true;
field.default = "";
if (d.default_val) {
let defaultValue = "";
if (d.default_val.value.type === "function") {
defaultValue = d.default_val.value.name.name[0].value;
if (d.default_val.value.args) {
defaultValue +=
"(" +
d.default_val.value.args.value
.map((v) => {
if (
v.type === "single_quote_string" ||
v.type === "double_quote_string"
)
return "'" + v.value + "'";
return v.value;
})
.join(", ") +
")";
}
} else if (d.default_val.value.type === "null") {
defaultValue = "NULL";
} else {
defaultValue = d.default_val.value.value.toString();
}
field.default = defaultValue;
}
if (d.definition["length"]) {
if (d.definition.scale) {
field.size = d.definition["length"] + "," + d.definition.scale;
} else {
field.size = d.definition["length"];
}
}
field.check = "";
if (d.check) {
field.check = buildSQLFromAST(d.check.definition[0], DB.MARIADB);
}
table.fields.push(field);
} else if (d.resource === "constraint") {
if (d.constraint_type === "primary key") {
d.definition.forEach((c) => {
table.fields.forEach((f) => {
if (f.name === c.column && !f.primary) {
f.primary = true;
}
});
});
} else if (d.constraint_type.toLowerCase() === "foreign key") {
const relationship = {};
const startTableId = table.id;
const startTable = e.table[0].table;
const startField = d.definition[0].column;
const endTable = d.reference_definition.table[0].table;
const endField = d.reference_definition.definition[0].column;
const endTableId = tables.findIndex((t) => t.name === endTable);
if (endTableId === -1) return;
const endFieldId = tables[endTableId].fields.findIndex(
(f) => f.name === endField,
);
if (endFieldId === -1) return;
const startFieldId = table.fields.findIndex(
(f) => f.name === startField,
);
if (startFieldId === -1) return;
relationship.name = startTable + "_" + startField + "_fk";
relationship.startTableId = startTableId;
relationship.endTableId = endTableId;
relationship.endFieldId = endFieldId;
relationship.startFieldId = startFieldId;
let updateConstraint = "No action";
let deleteConstraint = "No action";
d.reference_definition.on_action.forEach((c) => {
if (c.type === "on update") {
updateConstraint = c.value.value;
updateConstraint =
updateConstraint[0].toUpperCase() +
updateConstraint.substring(1);
} else if (c.type === "on delete") {
deleteConstraint = c.value.value;
deleteConstraint =
deleteConstraint[0].toUpperCase() +
deleteConstraint.substring(1);
}
});
relationship.updateConstraint = updateConstraint;
relationship.deleteConstraint = deleteConstraint;
if (table.fields[startFieldId].unique) {
relationship.cardinality = Cardinality.ONE_TO_ONE;
} else {
relationship.cardinality = Cardinality.MANY_TO_ONE;
}
relationships.push(relationship);
}
}
});
table.fields.forEach((f, j) => {
f.id = j;
});
tables.push(table);
} else if (e.keyword === "index") {
const index = {};
index.name = e.index;
index.unique = false;
if (e.index_type === "unique") index.unique = true;
index.fields = [];
e.index_columns.forEach((f) => index.fields.push(f.column));
let found = -1;
tables.forEach((t, i) => {
if (found !== -1) return;
if (t.name === e.table.table) {
t.indices.push(index);
found = i;
}
});
if (found !== -1) tables[found].indices.forEach((i, j) => (i.id = j));
}
} else if (e.type === "alter") {
e.expr.forEach((expr) => {
if (
expr.action === "add" &&
expr.create_definitions.constraint_type.toLowerCase() === "foreign key"
) {
const relationship = {};
const startTable = e.table[0].table;
const startField = expr.create_definitions.definition[0].column;
const endTable =
expr.create_definitions.reference_definition.table[0].table;
const endField =
expr.create_definitions.reference_definition.definition[0].column;
let updateConstraint = "No action";
let deleteConstraint = "No action";
expr.create_definitions.reference_definition.on_action.forEach(
(c) => {
if (c.type === "on update") {
updateConstraint = c.value.value;
updateConstraint =
updateConstraint[0].toUpperCase() +
updateConstraint.substring(1);
} else if (c.type === "on delete") {
deleteConstraint = c.value.value;
deleteConstraint =
deleteConstraint[0].toUpperCase() +
deleteConstraint.substring(1);
}
},
);
const startTableId = tables.findIndex((t) => t.name === startTable);
if (startTable === -1) return;
const endTableId = tables.findIndex((t) => t.name === endTable);
if (endTableId === -1) return;
const endFieldId = tables[endTableId].fields.findIndex(
(f) => f.name === endField,
);
if (endFieldId === -1) return;
const startFieldId = tables[startTableId].fields.findIndex(
(f) => f.name === startField,
);
if (startFieldId === -1) return;
relationship.name = startTable + "_" + startField + "_fk";
relationship.startTableId = startTableId;
relationship.startFieldId = startFieldId;
relationship.endTableId = endTableId;
relationship.endFieldId = endFieldId;
relationship.updateConstraint = updateConstraint;
relationship.deleteConstraint = deleteConstraint;
if (tables[startTableId].fields[startFieldId].unique) {
relationship.cardinality = Cardinality.ONE_TO_ONE;
} else {
relationship.cardinality = Cardinality.MANY_TO_ONE;
}
relationships.push(relationship);
relationships.forEach((r, i) => (r.id = i));
}
});
}
};
if (Array.isArray(ast)) {
ast.forEach((e) => parseSingleStatement(e));
} else {
parseSingleStatement(ast);
}
relationships.forEach((r, i) => (r.id = i));
return { tables, relationships };
}