Chris
Chris

Reputation: 55

How to initialize multiple sql files with postgreSQL

I am new to web dev and taking a run at a full-stack node, react, express, postgreSQL app. All of the tutorials I had done and documentation I have found thus far, talk about using a single .sql file. However I imagine you would use multiple in a large app?

For example, in a small version of a Facebook clone, I would think you would have a separate .sql for users, posts, groups, etc... It would seem an awful mess to lump everything into one file, lol.

If multiple files is the way to go I am wondering how to initiate those files. Do you still use one database name but use multiple sql files? The closest I have found is something like the following:

// Initiate your database in a bash script
database="appdb"

dropdb -U node_user appdb
createdb -U node_user appdb

// Initiate sql files, something like this?
psql -U node_user "BEGIN;" \i file1.sql \i file2.sql "COMMIT;"

// Or iterate through the .sql files?
for file in dir/*.sql
    do sudo -u postgres psql $DATABASE_NAME -f $file
done

Wondering if either of those is correct and if there is a standard way of doing this. Any thoughts and/or further reading material is appreciated.

Thanks much

Upvotes: 2

Views: 1668

Answers (1)

Laurenz Albe
Laurenz Albe

Reputation: 246818

If you want to run several scripts in a single transaction, use

psql -U node_user -d "$database" --single-transaction -f file1.sql -f file2.sql

Upvotes: 6

Related Questions