seveibar/pgstrap(opens in a new tab)
Language: TypeScript
Bootstrapping utilities for Typescript/Postgres projects
- stars
- 42
- watchers
- 1
- forks
- 103
- open issues
- 87
- Last updated
- 06/17/2025
Language: TypeScript
Bootstrapping utilities for Typescript/Postgres projects
pgstrap allows you to easily run typescript migrations or generate a directory that represents your database schemas with table.sql files. Run pgstrap generate to generate a directory with the structure of your postgres database schemas!
[src]/db/migrations[src]/db/zapatos (compatible with Zapatos and Kysely)table.sql structure dumps in [src]/db/structurenpm install pgstrap --save-dev
Initialize pgstrap in your project:
npx pgstrap init
This will set up the necessary configuration and scripts in your package.json.
Create your first migration:
npm run db:create-migration my-first-migration
Edit the migration file in src/db/migrations/.
Run the migration:
npm run db:migrate
Generate types and structure:
npm run db:generate
npm run db:migrate - Run pending migrationsnpm run db:reset - Drop and recreate the database, then run all migrationsnpm run db:generate - Generate types and structure dumps. Use pgstrap generate --pglite to run migrations against an in-memory PGlite instance.npm run db:create-migration - Create a new migration fileAfter running pgstrap init, you'll find a pgstrap.config.js file in your project root. Customize it as needed:
module.exports = { defaultDatabase: "mydb", schemas: ["public"], dbDir: "./src/db", // optional, defaults to "./src/db" }
Migrations in pgstrap are written using node-pg-migrate, which provides a powerful and flexible way to define database changes.
To create a new migration:
npm run db:create-migration my-migration-name
This will create a new file in src/db/migrations/ with a timestamp prefix.
A typical migration file looks like this:
import { MigrationBuilder, ColumnDefinitions } from "node-pg-migrate" export const shorthands: ColumnDefinitions | undefined = undefined export async function up(pgm: MigrationBuilder): Promise<void> { // Your migration code here } export async function down(pgm: MigrationBuilder): Promise<void> { // Code to revert your migration (optional) }
Here's an example of a migration that creates a new table:
export async function up(pgm: MigrationBuilder): Promise<void> { pgm.createTable("users", { id: "id", username: { type: "text", notNull: true }, email: { type: "text", notNull: true, unique: true }, created_at: { type: "timestamptz", notNull: true, default: pgm.func("current_timestamp"), }, }) pgm.createIndex("users", "username") } export async function down(pgm: MigrationBuilder): Promise<void> { pgm.dropTable("users") }
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions, please file an issue on the GitHub repository.
Happy coding with pgstrap! 🚀