0

This seems like a very easy thing to do but could you tell me where I am going wrong.

I want to execute some SQL files on Postgres db start up to create a database and tables.

I use docker-compose to create a Postgres version 16.2 database I copy 3 SQL files ( named so they execute sequentially) into docker-entrypoint-initdb.d where they are executed, this works! I want the tables to belong in the created database, but I cannot get that working

Here are the files.

aa.sql

CREATE USER user1 WITH PASSWORD 'password';
CREATE DATABASE products;
GRANT ALL PRIVILEGES ON DATABASE products TO user1;

bb.sql (runs after aa.sql):

CREATE TABLE brands (
    brand_id INTEGER PRIMARY KEY,
    brand_name VARCHAR(255) NOT NULL
);

cc.sql (runs after bb.sql)

CREATE TABLE products (
    product_id SERIAL PRIMARY KEY,
    product_name VARCHAR(255) NOT NULL,
    brand_id INTEGER NOT NULL,
            FOREIGN KEY (brand_id)
            REFERENCES products.brands (brand_id)
            ON UPDATE CASCADE ON DELETE CASCADE
)

If I run my docker-compose I see the tables are created in the postgres database not products

If I use CREATE_TABLE databasename.tablename , no tables are created

If I use USE products; I get

psql:/docker-entrypoint-initdb.d/bb.sql:1: ERROR:  syntax error at or near "USE"

Can someone please tell me what I am doing wrong

4
  • PostgreSQL does provide error messages, when something goes wrong, like for example when a table does not get created. When you do not see any errors, you might need to use the CONNECT statement, see: postgresql.org/docs/current/ecpg-sql-connect.html Commented Feb 27, 2024 at 12:54
  • You could create the database and user with the POSTGRES_DB and POSTGRES_USER (and others) environment variables instead. Commented Feb 27, 2024 at 13:09
  • What is error due to table is not created? Is bb.sql really executed afater aa.sql - there is FK, so this can be problem. Commented Feb 27, 2024 at 13:09
  • PostgreSQL does not have USE, it has search_path: stackoverflow.com/questions/10335561/… Commented Feb 27, 2024 at 13:12

1 Answer 1

0

Thanks for all the comments.

I found this resolves the problem (connect to the right db first using the code below)

\connect products

CREATE TABLE products (
    product_id SERIAL PRIMARY KEY,
    product_name VARCHAR(255) NOT NULL,
    brand_id INTEGER NOT NULL,
            FOREIGN KEY (brand_id)
            REFERENCES brands (brand_id)
            ON UPDATE CASCADE ON DELETE CASCADE
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.