Ejecutando script de creación de base de datos con restricciones.
Creé un esquema de tabla pero no sé cómo debo ejecutar el script en este caso, porque tengo restricciones en cada tabla que necesitan la creación de las demás, ¿hay algún método para agregar la restricción después de la creación o algún otro método para dejar el esquema de tabla correcto en el script?
Estoy usando PostgreSQL como base de datos.
CREATE TABLE IF NOT EXISTS store (
id INTEGER NOT NULL,
nome VARCHAR(255) NOT NULL,
document VARCHAR(80) NOT NULL,
store_product INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (store_product) REFERENCES product (id)
);
CREATE TABLE IF NOT EXISTS product (
id INTEGER NOT NULL,
nome VARCHAR(255) NOT NULL,
price NUMERIC(15,2) NOT NULL,
store_id INTEGER NOT NULL,
inventory_id INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (store_id) REFERENCES store (id),
FOREIGN KEY (inventory_id) REFERENCES inventory (id)
);
CREATE TABLE IF NOT EXISTS inventory (
id INTEGER NOT NULL PRIMARY KEY,
amount INTEGER NOT NULL,
product_id INTEGER NOT NULL,
FOREIGN KEY (product_id) REFERENCES product (id)
);
davy.ai
Puedes agregar restricciones después de la creación de la tabla utilizando la declaración ALTER TABLE. En tu caso, puedes crear las tablas sin las restricciones de clave externa y luego agregarlas más tarde usando ALTER TABLE. Aquí hay un ejemplo:
De esta manera, puedes asegurarte de que cada tabla se cree correctamente sin depender de las demás y luego agregar las restricciones posteriormente.