There is a certain logical sense in saving everything that is connected with a table in one file - column definitions, keys, indexes, triggers, etc. If you never have to rebuild a very large database from SQL, this will work fine for almost time. This doesn’t work well several times, probably it’s not worth changing the process of storing all related things in one file.
But if you need to rebuild a very large database or if you need to move the database to another server for testing, or if you just want to mess with things, it makes sense to split things up. In PostgreSQL, we break that down. All of these files are under version control.
- All CREATE DOMAIN statements in one file.
- Each CREATE TABLE statement in a separate file. This file contains all restrictions except the FOREIGN KEY restrictions expressed in ALTER TABLE expressions. (More on this a bit.)
- Each FOREIGN KEY constraint table in a separate file.
- Each table indexes non-key columns in a separate file.
- Each table is launched in a separate file. (If there are three triggers in the table, all three go to the same file.)
- Each data table in a separate file. (Only for tables uploaded before bringing the database to the network.)
- Each table is managed in a separate file.
- Each function in a separate file. (PostgreSQL functions are equivalent to stored procedures.)
Without foreign key restrictions, we can load tables in any order. After loading the tables, we can run one script to rebuild all the foreign keys. The Makefile takes care of combining the right individual files together. (Since they are separate files, we can run them individually if we want.)
Tables load faster if they have no restrictions. I said that we put each CREATE TABLE statement in a separate file. The file contains all the restrictions except the FOREIGN KEY constraints expressed in ALTER TABLE expressions. You can use sed stream editor to split these files into two parts. One part has column definitions; the other part has all the ALTER TABLE ADD CONSTRAINT instructions. The Makefile takes care of splitting the source files and combining them - all table definitions in one SQL file and all ALTER TABLE statements in another. Then we can run one script to create all the tables, load the tables, and then run one script to rebuild all the restrictions.
make is your friend.
Mike Sherrill 'Cat Recall'
source share