Suppose I have a file where I write my database schema, which is initialized upon:
CREATE TABLE users ( id PRIMARY KEY, name TEXT )
In the next day I decide to add a new table, so I edit that file:
CREATE TABLE users ( id PRIMARY KEY, name text ); CREATE TABLE actions ( user_id int REFERENCES users (id), name text );
If I run the tool, I should be able to get a diff with only the stuff required for bring a database created on the first day into the state it should be in the second day:
CREATE TABLE actions ( user_id int REFERENCES users (id), name text );
Now suppose on the third day I go back and make a bunch of changes:
CREATE TABLE users ( id PRIMARY KEY, name text NOT NULL, age int NOT NULL ); CREATE TABLE actions ( user_id int REFERENCES users (id), name text NOT NULL );
I should also get a migration from the changes above:
ALTER TABLE users ADD COLUMN age int NOT NULL; ALTER TABLE users ALTER TABLE name ADD CONSTRAINT NOT NULL; ALTER TABLE actions ALTER TABLE name ADD CONSTRAINT NOT NULL;
And so on and so forth (I don't know if the example above is correct).
This should work for the most common things, like adding and removing tables or columns, adding and removing constraints and indexes and foreign keys (what else? I can't remember). More complex stuff could have their migrations specified manually.
https://github.com/lelit/pglast gives you a parsed AST, so you could use that.
The only requirement is that this tool is written in a way that it is runnable without installing thousands of runtimes or dependencies or Docker stuff. Scala, Python and JavaScript are ok, Java, PHP and Ruby are not fine. Go, Rust and lower-level things are fine.
50,000 sats bounty
1: Install the necessary dependencies:
2: Create a new directory for your project and navigate to it:
3: Initialize the Alembic migration environment:
4: Update the alembic.ini file in the migrations directory to configure your database connection. Modify the [alembic] section as follows:
5: Create a new Python script in the project directory, for example diff_tool.py. Add the following code to the script:
6: Customize the script as needed, including the database URL in the create_engine function.
7: Run the diffing tool:
8: To apply the generated migrations to the database, run the diffing tool again: