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

View File

@@ -27,3 +27,5 @@ jobs:
run: npm run lint run: npm run lint
- name: Run vite build - name: Run vite build
run: npm run build run: npm run build
- name: Run tests
run: npm run test

3
babel.config.cjs Normal file
View File

@@ -0,0 +1,3 @@
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

9
jest.config.cjs Normal file
View File

@@ -0,0 +1,9 @@
module.exports = {
transform: {
'^.+\\.[t|j]sx?$': 'babel-jest',
},
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
testEnvironment: 'node'
};

4557
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,8 @@
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview" "preview": "vite preview",
"test": "jest"
}, },
"dependencies": { "dependencies": {
"@codemirror/lang-json": "^6.0.1", "@codemirror/lang-json": "^6.0.1",
@@ -42,10 +43,13 @@
"usehooks-ts": "^3.1.0" "usehooks-ts": "^3.1.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.24.0",
"@babel/preset-env": "^7.24.0",
"@types/react": "^18.2.43", "@types/react": "^18.2.43",
"@types/react-dom": "^18.2.17", "@types/react-dom": "^18.2.17",
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.16", "autoprefixer": "^10.4.16",
"babel-jest": "^29.7.0",
"eslint": "^8.55.0", "eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-plugin-react": "^7.33.2", "eslint-plugin-react": "^7.33.2",
@@ -54,7 +58,8 @@
"postcss": "^8.4.32", "postcss": "^8.4.32",
"prettier": "3.2.5", "prettier": "3.2.5",
"tailwindcss": "^3.3.6", "tailwindcss": "^3.3.6",
"vite": "^5.4.1" "vite": "^5.4.1",
"jest": "^29.7.0"
}, },
"overrides": { "overrides": {
"follow-redirects": "^1.15.4" "follow-redirects": "^1.15.4"

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, jsonToSQLite,
jsonToMariaDB, jsonToMariaDB,
jsonToSQLServer, jsonToSQLServer,
jsonToOracle,
} from "../../utils/exportSQL/generic"; } from "../../utils/exportSQL/generic";
import { import {
ObjectType, ObjectType,
@@ -824,6 +825,12 @@ export default function ControlPanel({
setImportDb(DB.MSSQL); setImportDb(DB.MSSQL);
}, },
}, },
{
Oracle: () => {
setModal(MODAL.IMPORT_SRC);
setImportDb(DB.ORACLE);
},
},
], ],
}), }),
function: () => { 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: () => { function: () => {

View File

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

View File

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

View File

@@ -7,6 +7,16 @@ const binaryRegex = /^[01]+$/;
/* eslint-disable no-unused-vars */ /* eslint-disable no-unused-vars */
const defaultTypesBase = { const defaultTypesBase = {
NUMBER: {
type: "NUMBER",
checkDefault: (field) => {
return intRegex.test(field.default);
},
hasCheck: true,
isSized: false,
hasPrecision: true,
canIncrement: true,
},
INT: { INT: {
type: "INT", type: "INT",
checkDefault: (field) => { checkDefault: (field) => {
@@ -263,12 +273,193 @@ const defaultTypesBase = {
hasPrecision: false, hasPrecision: false,
noDefault: true, 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, { export const defaultTypes = new Proxy(defaultTypesBase, {
get: (target, prop) => (prop in target ? target[prop] : false), 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 = { const mysqlTypesBase = {
TINYINT: { TINYINT: {
type: "TINYINT", type: "TINYINT",
@@ -1754,6 +1945,7 @@ const dbToTypesBase = {
[DB.SQLITE]: sqliteTypes, [DB.SQLITE]: sqliteTypes,
[DB.MSSQL]: mssqlTypes, [DB.MSSQL]: mssqlTypes,
[DB.MARIADB]: mysqlTypes, [DB.MARIADB]: mysqlTypes,
[DB.ORACLE]: oracleTypes,
}; };
export const dbToTypes = new Proxy(dbToTypesBase, { 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) { export function jsonToMySQL(obj) {
return `${obj.tables return `${obj.tables
.map( .map(

View File

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

View File

@@ -0,0 +1,54 @@
/* eslint-env jest */
import { toOracle } from "../src/utils/exportSQL/oracle.js";
import { DB } from "../src/data/constants.js";
describe("toOracle", () => {
test("test for unique index creation", () => {
const diagram = {
database: DB.ORACLE,
tables: [
{
name: "mochila",
fields: [
{
name: "mochila_id",
type: "NUMBER",
size: "10,0",
notNull: true,
primary: true,
default: "",
},
{
name: "capacidad_kg",
type: "NUMBER",
size: "2,0",
notNull: true,
default: "",
},
],
indices: [
{
name: "mochila_index_0",
fields: ["mochila_id"],
unique: true,
}
],
},
],
references: [],
};
const expectedSQL = `CREATE TABLE mochila (
\t"mochila_id" NUMBER(10,0) NOT NULL,
\t"capacidad_kg" NUMBER(2,0) NOT NULL,
\tCONSTRAINT mochila_pk PRIMARY KEY("mochila_id")
);
CREATE UNIQUE INDEX "mochila_index_0" ON mochila ("mochila_id");
`;
const result = toOracle(diagram);
expect(result.trim()).toBe(expectedSQL.trim());
});
});

62
test/oracle_c_idx.test.js Normal file
View File

@@ -0,0 +1,62 @@
/* eslint-env jest */
import { toOracle } from "../src/utils/exportSQL/oracle.js";
import { DB } from "../src/data/constants.js";
describe("toOracle", () => {
test("test for unique index creation", () => {
const diagram = {
database: DB.ORACLE,
tables: [
{
name: "mochila",
fields: [
{
name: "mochila_id",
type: "NUMBER",
size: "10,0",
notNull: true,
primary: true,
default: "",
},
{
name: "capacidad_kg",
type: "NUMBER",
size: "2,0",
notNull: true,
default: "",
},
{
name: "compartimentos",
type: "NUMBER",
size: "2,0",
notNull: true,
default: "",
},
],
indices: [
{
name: "mochila_index_0",
fields: ["capacidad_kg", "compartimentos"],
unique: true,
}
],
},
],
references: [],
};
const expectedSQL = `CREATE TABLE mochila (
\t"mochila_id" NUMBER(10,0) NOT NULL,
\t"capacidad_kg" NUMBER(2,0) NOT NULL,
\t"compartimentos" NUMBER(2,0) NOT NULL,
\tCONSTRAINT mochila_pk PRIMARY KEY("mochila_id")
);
CREATE UNIQUE INDEX "mochila_index_0" ON mochila ("capacidad_kg", "compartimentos");
`;
const result = toOracle(diagram);
expect(result.trim()).toBe(expectedSQL.trim());
});
});

46
test/oracle_chk.test.js Normal file
View File

@@ -0,0 +1,46 @@
/* eslint-env jest */
import { toOracle } from "../src/utils/exportSQL/oracle.js";
import { DB } from "../src/data/constants.js";
describe("toOracle", () => {
test("test for check constraint in any field of a table", () => {
const diagram = {
database: DB.ORACLE,
tables: [
{
name: "salon",
fields: [
{
name: "salon_id",
type: "NUMBER",
size: "10,0",
notNull: true,
primary: true,
default: "",
},
{
name: "capacidad",
type: "NUMBER",
size: "10,0",
notNull: true,
default: "",
check: "> 0",
},
],
indices: [],
},
],
references: [],
};
const expectedSQL = `CREATE TABLE salon (
\t"salon_id" NUMBER(10,0) NOT NULL,
\t"capacidad" NUMBER(10,0) NOT NULL,
\tCONSTRAINT salon_capacidad_chk CHECK("capacidad" > 0),
\tCONSTRAINT salon_pk PRIMARY KEY("salon_id")
);`;
const result = toOracle(diagram);
expect(result.trim()).toBe(expectedSQL.trim());
});
});

View File

@@ -0,0 +1,75 @@
/* eslint-env jest */
import { toOracle } from "../src/utils/exportSQL/oracle.js";
import { DB } from "../src/data/constants.js";
describe("toOracle", () => {
test("should generate correct Oracle SQL for tables with relationships", () => {
const diagram = {
database: DB.ORACLE,
tables: [
{
name: "casa",
fields: [
{
name: "id",
type: "NUMBER",
size: "10,0",
notNull: true,
unique: true,
primary: true,
default: ""
},
{
name: "xd",
type: "VARCHAR",
size: "255",
notNull: true,
default: ""
}
],
indices: []
},
{
name: "cuarto",
fields: [
{
name: "id",
type: "NUMBER",
unique: true,
primary: true,
default: ""
}
],
indices: []
}
],
references: [
{
startTableId: 0,
startFieldId: 0,
endTableId: 1,
endFieldId: 0
}
]
};
const expectedSQL = `CREATE TABLE casa (
\t"id" NUMBER(10,0) NOT NULL,
\t"xd" VARCHAR(255) NOT NULL,
\tCONSTRAINT casa_pk PRIMARY KEY("id")
);
CREATE TABLE cuarto (
\t"id" NUMBER,
\tCONSTRAINT cuarto_pk PRIMARY KEY("id")
);
ALTER TABLE casa ADD CONSTRAINT casa_id_fk
FOREIGN KEY("id") REFERENCES cuarto("id");`;
const result = toOracle(diagram);
expect(result.trim()).toBe(expectedSQL.trim());
});
});

75
test/oracle_pk_fk.test.js Normal file
View File

@@ -0,0 +1,75 @@
/* eslint-env jest */
import { toOracle } from "../src/utils/exportSQL/oracle.js";
import { DB } from "../src/data/constants.js";
describe("toOracle", () => {
test("should generate correct Oracle SQL for tables with relationships", () => {
const diagram = {
database: DB.ORACLE,
tables: [
{
name: "casa",
fields: [
{
name: "id",
type: "NUMBER",
size: "10,0",
notNull: true,
unique: true,
primary: true,
default: ""
},
{
name: "xd",
type: "VARCHAR",
size: "255",
notNull: true,
default: ""
}
],
indices: []
},
{
name: "cuarto",
fields: [
{
name: "id",
type: "NUMBER",
unique: true,
primary: true,
default: ""
}
],
indices: []
}
],
references: [
{
startTableId: 0,
startFieldId: 0,
endTableId: 1,
endFieldId: 0
}
]
};
const expectedSQL = `CREATE TABLE casa (
\t"id" NUMBER(10,0) NOT NULL,
\t"xd" VARCHAR(255) NOT NULL,
\tCONSTRAINT casa_pk PRIMARY KEY("id")
);
CREATE TABLE cuarto (
\t"id" NUMBER,
\tCONSTRAINT cuarto_pk PRIMARY KEY("id")
);
ALTER TABLE casa ADD CONSTRAINT casa_id_fk
FOREIGN KEY("id") REFERENCES cuarto("id");`;
const result = toOracle(diagram);
expect(result.trim()).toBe(expectedSQL.trim());
});
});

View File

@@ -0,0 +1,46 @@
/* eslint-env jest */
import { toOracle } from "../src/utils/exportSQL/oracle.js";
import { DB } from "../src/data/constants.js";
describe("toOracle", () => {
test("test for unique constraints", () => {
const diagram = {
database: DB.ORACLE,
tables: [
{
name: "computador",
fields: [
{
name: "computador_id",
type: "NUMBER",
size: "10,0",
notNull: true,
primary: true,
default: "",
},
{
name: "num_serie",
type: "VARCHAR2",
size: 40,
notNull: true,
unique: true,
default: "",
},
],
indices: [],
},
],
references: [],
};
const expectedSQL = `CREATE TABLE computador (
\t"computador_id" NUMBER(10,0) NOT NULL,
\t"num_serie" VARCHAR2(40) NOT NULL,
\tCONSTRAINT computador_num_serie_uk UNIQUE("num_serie"),
\tCONSTRAINT computador_pk PRIMARY KEY("computador_id")
);`;
const result = toOracle(diagram);
expect(result.trim()).toBe(expectedSQL.trim());
});
});