PgBuilder is a Ruby gem for building PostgreSQL schema deployments from many small SQL files.
It turns your src/ tree into Rake tasks, resolves declared dependencies, and produces a final merged build/schema.sql.
- Keep database objects in small, reviewable SQL files.
- Control creation order with explicit dependencies.
- Build a single deployable script from source files.
- Generate Cucumber features for tables/functions to validate your schema.
- Ruby
>= 3.0 - PostgreSQL (for running generated SQL and tests)
- Docker (for running the Cucumber integration tests)
gem install pg_builderOr in your project Gemfile:
gem "pg_builder"Create a Rakefile in your database project root:
require "pg_builder"
spec = Gem::Specification.find_by_name("pg_builder")
load "#{spec.gem_dir}/lib/pg_builder/Rakefile"
# Optional: provide this task if your project grants permissions.
task :permissions do
# load/run permission SQL here
endrake uses this task graph:
default->completecomplete->init,schemas:all,permissions,schema.sqlinit->clean,tmp/,roles:all
If you do not need permissions, define an empty task :permissions.
project_root/
src/
roles/
app_reader.sql
app_writer.sql
schemas/
accounting.sql
accounting/
types/
invoice_status.sql
sequences/
invoice_id_seq.sql
tables/
invoice.sql
invoice_line.sql
functions/
calculate_invoice_total.sql
trigger_functions/
set_updated_at.sql
The first line can declare dependencies:
-- depends_on: ["::schemas:accounting:types:invoice_status", "invoice_line"]Rules:
- Use
:as path separator. - Use
::prefix for absolute paths fromsrc/. - Relative paths are resolved from the current SQL file directory.
- Do not include
.sqlin dependency names.
PgBuilder also auto-adds the parent schema as a dependency for objects under schemas/<name>/... (except public).
rakeThis creates build/schema.sql from the ordered SQL sources.
Create a new schema skeleton:
rake generate:schema[schema_name]This creates:
src/schemas/schema_name.sqlsrc/schemas/schema_name/functions/src/schemas/schema_name/sequences/src/schemas/schema_name/tables/src/schemas/schema_name/trigger_functions/src/schemas/schema_name/types/
Run:
bundle exec rake cucumberDuring tests PgBuilder:
- spins up a PostgreSQL Docker container,
- generates feature files under
features/schemas/generated, - applies SQL from
tmp/*.sql, - runs Cucumber scenarios for supported object types (
tables,functions).
Optional env var:
PG_BUILDER_EXTENSION_SCHEMA: creates this schema before tests (useful for extension-related testing).
Detailed guide: docs/integration-testing.md
- Missing dependency file -> build fails with
Cannot find dependency ... - Missing
permissionstask in your projectRakefile->Don't know how to build task 'permissions' - Invalid dependency format -> make sure it is valid JSON in the first line after
-- depends_on:
Issues and pull requests are welcome at github.com/brunoenten/pg_builder.
MIT - see LICENSE.txt.