Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ npm install pgstrap --save-dev
- `npm run db:reset` - Drop and recreate the database, then run all migrations
- `npm run db:generate` - Generate types and structure dumps
- `npm run db:create-migration` - Create a new migration file
- `pgstrap generate --pglite` - Run migrations and generate schema using an in-memory PGlite instance

### Configuration

Expand Down
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"license": "MIT",
"dependencies": {
"@electric-sql/pglite": "^0.2.10",
"pg-gateway": "^0.3.0-beta.4",
"pg-schema-dump": "^2.0.2",
"yargs": "^17.7.2"
},
Expand Down
26 changes: 22 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
#!/usr/bin/env node
import yargs from "yargs"
import { migrate, reset, generate, createMigration, initPgstrap } from "./"
import {
migrate,
reset,
generate,
createMigration,
initPgstrap,
generateWithPglite,
} from "./"
import { getProjectContext } from "./get-project-context"
;(yargs as any)
.command("init", "initialize pgstrap", {}, async () => {
Expand Down Expand Up @@ -34,9 +41,20 @@ import { getProjectContext } from "./get-project-context"
.command(
"generate",
"generate types and sql documentation from database",
{},
async () => {
generate(await getProjectContext())
(yargs) => {
yargs.option("pglite", {
type: "boolean",
describe: "use pglite instead of connecting to Postgres",
default: false,
})
},
async (argv) => {
const ctx = await getProjectContext()
if (argv.pglite) {
await generateWithPglite(ctx)
} else {
await generate(ctx)
}
},
)
.parse()
67 changes: 63 additions & 4 deletions src/generate.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as zg from "zapatos/generate"
import {
getConnectionStringFromEnv,
getPgConnectionFromEnv,
} from "pg-connection-from-env"
import { getConnectionStringFromEnv } from "pg-connection-from-env"
import { Context } from "./get-project-context"
import { dumpTree } from "pg-schema-dump"
import path from "path"
import { PGlite } from "@electric-sql/pglite"
import net from "net"
import { fromNodeSocket } from "pg-gateway/node"
import { migrate } from "./migrate"

export const generate = async ({
schemas,
Expand Down Expand Up @@ -40,3 +41,61 @@ export const generate = async ({
schemas,
})
}

export const generateWithPglite = async (
ctx: Context & { migrationsDir?: string },
) => {
const db = new PGlite()

const migrationsDir =
ctx.migrationsDir ?? path.join(ctx.dbDir ?? "./src/db", "migrations")

await migrate({
...ctx,
migrationsDir,
client: db as any,
})

const server = net.createServer(async (socket) => {
const connection = await fromNodeSocket(socket as any, {
auth: { method: "trust" },
async onStartup() {
await db.waitReady
return false
},
async onMessage(data: any, { isAuthenticated }: any) {
if (!isAuthenticated) return false

try {
const [[_, responseData]] = (await db.execProtocol(
data as any,
)) as any
connection.sendData(responseData)
} catch (err) {
connection.sendError(err as Error)
connection.sendReadyForQuery()
}
return true
},
})

socket.on("end", () => {
// connection cleanup if needed
})
})

await new Promise<void>((resolve) => server.listen(0, () => resolve()))
server.unref()
const port = (server.address() as net.AddressInfo).port
const prevUrl = process.env.DATABASE_URL
process.env.DATABASE_URL = `postgres://localhost:${port}`

try {
await generate(ctx)
} finally {
if (prevUrl === undefined) delete process.env.DATABASE_URL
else process.env.DATABASE_URL = prevUrl
await new Promise<void>((resolve) => server.close(() => resolve()))
await db.close()
}
}
38 changes: 38 additions & 0 deletions tests/generate-pglite.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import test from "ava"
import fs from "fs"
import path from "path"
import { generateWithPglite } from "../src/generate"

const migrationContent = `
exports.up = async (pgm) => {
pgm.createTable('foo', {
id: 'id'
})
}
exports.down = async (pgm) => {
pgm.dropTable('foo')
}
`

test("generateWithPglite creates structure", async (t) => {
const cwd = fs.mkdtempSync(path.join(__dirname, "temp_proj"))
const migrationsDir = path.join(cwd, "migrations")
fs.mkdirSync(migrationsDir, { recursive: true })
fs.writeFileSync(
path.join(migrationsDir, "001_create_foo.cjs"),
migrationContent,
)

await generateWithPglite({
schemas: ["public"],
defaultDatabase: "test_db",
dbDir: path.join(cwd, "db"),
migrationsDir,
cwd,
})

const expected = path.join(cwd, "db/structure/public/tables/foo/table.sql")
t.true(fs.existsSync(expected))

fs.rmSync(cwd, { recursive: true, force: true })
})
2 changes: 1 addition & 1 deletion tests/pglite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ test("migration of a pglite db works", async (t) => {
}
`
fs.writeFileSync(
path.join(migrationsDir, "001_create_test_table.js"),
path.join(migrationsDir, "001_create_test_table.cjs"),
migrationContent,
)

Expand Down
Loading