es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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)
);
Tags:  , , , ,

Answer

  1. Avatar for 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:

    CREATE TABLE IF NOT EXISTS store (
        id INTEGER NOT NULL,
        nome VARCHAR(255) NOT NULL,
        documento VARCHAR(80) NOT NULL,
        store_product INTEGER NOT NULL,
        PRIMARY KEY (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)
    );
    
    CREATE TABLE IF NOT EXISTS inventory (
        id INTEGER NOT NULL PRIMARY KEY,
        amount INTEGER NOT NULL,
        product_id INTEGER NOT NULL
    );
    
    -- Agregar restricciones de clave externa después de la creación de la tabla
    ALTER TABLE store ADD FOREIGN KEY (store_product) REFERENCES product (id);
    ALTER TABLE product ADD FOREIGN KEY (store_id) REFERENCES store (id);
    ALTER TABLE product ADD FOREIGN KEY (inventory_id) REFERENCES inventory (id);
    ALTER TABLE inventory ADD FOREIGN KEY (product_id) REFERENCES product (id);
    

    De esta manera, puedes asegurarte de que cada tabla se cree correctamente sin depender de las demás y luego agregar las restricciones posteriormente.

Comments are closed.