r/PostgreSQL • • Oct 16 '26

Community Postgres Conference 2027 CFP is open (San Jose, April 21-23)

Post image
31 Upvotes

Mod hat off for a moment:

I'm one of the organizers of Postgres Conference, and the Call for Proposals for 2027 is now open.

Next year is the conference's 20th, so we want the program to reflect what the community has actually learned running Postgres in the real world.

When/where: April 21-23, 2027, San Jose Marriott, San Jose, CA

This year’s program brings back our core technical tracks: Essentials, Dev, Ops, and Extensions, now joined by a new AI track.

We’re also continuing Professional Development & Wellness and Life & Fun. These newer tracks have been so well received that they’ve become an essential part of the conference experience.

We're especially interested in talks from people running Postgres in production, such as:

- Lessons from production incidents: what broke, how you found it, and what you changed afterward
- Autovacuum and bloat tuning on large or high-churn tables
- HA and replication setups, including failovers that didn't go to plan
- Building extensions, or running them at scale
- Benchmarks with methodology you're willing to share and defend

You don't need to be a known speaker. A clear story about a real problem is exactly what we're looking for, and first-time speakers are welcome.

CFP and details: https://postgresconf.org/conferences/2027

Happy to answer any questions about submitting here. 

What's a Postgres problem you wish someone would give a talk about?


r/PostgreSQL • • 15h ago

Projects How to check whether anyone on the internet can read your Supabase tables

Thumbnail reddit.com
0 Upvotes

r/PostgreSQL • • 16h ago

Projects plx: The Excellent Transpiler 3.1.0 releasd

1 Upvotes

plx is a PostgreSQL extension. When you run CREATE FUNCTION ... LANGUAGE plx*, plx transpiles the body to plpgsql and stores that plpgsql in pg_proc.prosrc. At run time the function is executed by PostgreSQL's own plpgsql interpreter. There is no separate language runtime loaded into the backend, the generated plpgsql is visible in the catalog, and every plpgsql construct is reachable from every dialect.

[3.1.0] - 2026-11-21

3.1.0 adds two dialects, plxlua and plxcsharp. Nothing that 3.0.0 does changes: functions in the other dialects transpile as before.

Added

  • plxlua, a Lua dialect (LANGUAGE plxlua). Lua's keyword-end blocks, local declarations with type inference and --:: annotations, <const>, if/elseif, while, repeat ... until, the numeric for (any step) and for ... in query(...) / ipairs(...), the goto continue idiom, and return into OUT parameters. Errors are raised with error(...), error{message = ..., sqlstate = ...}, assert and print, and handled with pcall(function() ... end), whose err carries err.sqlstate and the other diagnostics fields. In expressions: .., ~=, nil, #, table constructors as arrays, //, and the x or d, c and a or b and c and v or d idioms, with a subset of the string, math and table libraries. Locals keep Lua's block scope, and s = s .. e uses the string builder. See doc/plxlua.md.
  • plxcsharp, a C# dialect (LANGUAGE plxcsharp). Declarations put the type first and C# types map to PostgreSQL types (int to integer, string to text, decimal to numeric, DateTime to timestamp, T[] to arrays); var takes the type of its value. Regular, verbatim (@"..."), raw ("""...""") and interpolated ($"...") strings work, and an interpolated string passed to query, execute and the other SQL intrinsics is a SQL template whose values are bound. + is string concatenation when an operand is known to be a string. Statements: if, while, do/while, for, foreach over a query, an array or a string, switch and switch expressions, try/catch/finally with exception classes and when (e.SqlState == ...) filters, throw, yield return for set-returning functions, Console.WriteLine as RAISE NOTICE, and StringBuilder and s += x on the string builder, with a set of mapped .NET members (string, Math, Convert, DateTime, Guid, ...). See doc/plxcsharp.md.
  • make oraclecheck runs plxlua and plxcsharp programs and compares their results with what real Lua and C# print for the same programs.

r/PostgreSQL • • 1d ago

Tools Feedback wanted: Airflow style database orchestration written 100% in SQL (just use postgres!)

Thumbnail github.com
8 Upvotes

r/PostgreSQL • • 21h ago

Commercial Running 19 integration & concurrency checks against a real PostgreSQL 18 DB instead of mocking SQL

0 Upvotes

Mocked queries in unit tests are fast, but they miss real lock contention, transaction ordering, and constraint behavior when multiple requests hit the database at once.

While hardening a multi-tenant backend (27 test files / 131 tests total, plus 19 integration and concurrency checks) against an isolated PostgreSQL 18 instance, testing against real Postgres caught edge cases around concurrent mutations, rate-limit counters, and webhook/state transitions that mocked unit tests never surfaced. The attached 26-second clip shows the test suite passing and moves straight into the live workspace.

For those running integration or concurrency tests against real Postgres: how do you isolate state between test runs (per-test transactions, fresh schema/DB, or reset scripts) while keeping execution times fast?


r/PostgreSQL • • 1d ago

How-To How to choose a Postgres read cache: Redis, Memcached, build your own, or proxy

Thumbnail pgcache.com
19 Upvotes

hey everyone - a couple months ago, I posted an overview of caching in Postgres. Seemed like it was helpful to a lot of people, and I've noticed there's not a lot of clear content on this topic out there. So I wrote this is the follow-up, for anyone who has decided to cache reads and is trying to figure out how to do it.

In addition to the main options, the article also covers some of the classic zingers that leave you serving stale data: invalidation, stampedes, tenants and RLS, read-your-own-writes, schema changes.

(disclaimer: I'm one of the founders of PgCache, which is one of the proxy options)

Did I miss anything?


r/PostgreSQL • • 1d ago Bravo

Projects The subtle trap with SQL functions when you drop or alter a column in a migration

15 Upvotes

I hit a Postgres behavior recently that surprised me, even after spending the last six months testing migration edge cases.

Say you have a simple helper function written the traditional way with a dollar-quoted body:

CREATE FUNCTION active_user_emails() RETURNS SETOF text
LANGUAGE sql AS $$ SELECT email FROM users WHERE active = true; $$;

Later on, somebody writes a migration that drops or renames users.email

If you run ALTER TABLE users DROP COLUMN email;, Postgres lets it through without a single warning. Even though check_function_bodies parsed the SQL when the function was created, Postgres stores a `$$` body as an opaque string literal and doesn't record pg_depend edges to the columns inside it. Your migration succeeds, CI is green, and the function only blows up in production the next time something calls it.

Now flip one line and write the exact same function using the SQL-standard body syntax (BEGIN ATOMIC, added in PG 14):

CREATE FUNCTION active_user_emails() RETURNS SETOF text
LANGUAGE sql
BEGIN ATOMIC
  SELECT email FROM users WHERE active = true;
END;

Because Postgres stores BEGIN ATOMIC as a parsed node tree in pg_proc.prosqlbody, it records hard dependency edges in pg_depend now that exact same ALTER TABLE users DROP COLUMN email; fails outright in the middle of your migration unless you pass CASCADE and if you do pass CASCADE, it silently drops the function along with the column.

And there is a third twist: if an earlier statement in your migration runs SET check_function_bodies = off; (which tools like pg_dump do all the time), a dollar-quoted LANGUAGE sql function won't even check whether the table exists at creation time, whereas BEGIN ATOMIC still parses and binds the objects immediately.

I've been building an open-source migration simulator (safe-migrate) that steps through migration files statement by statement against a snapshot of your catalog so it can catch things like this before deploy. Getting routine bodies, pg_depend edges, and check_function_bodies scoping (`SET`, `SET LOCAL`, `ROLLBACK TO SAVEPOINT`) to match real Postgres 14–18 took way more digging than I expected.

Have many of you switched your SQL functions over to `BEGIN ATOMIC` specifically so Postgres tracks the schema dependencies, or is almost everyone still on `$$` strings?


r/PostgreSQL • • 1d ago

Commercial Testing multi-tenant isolation, role privileges, and concurrency against real Postgres 18

6 Upvotes

When building multi-tenant systems on PostgreSQL 18, relying on application-layer checks or mocked queries leaves gaps around what the database itself enforces when things run concurrently or when a query misses a filter.

A few database-level patterns we focus on when verifying multi-tenant behavior against a live Postgres 18 instance:

  • Negative cross-tenant assertions on real tables: Verifying not just that a query returns expected rows for Tenant A, but that reads/writes scoped to another tenant's IDs or org context return zero rows or fail cleanly rather than leaking across boundaries.
  • Role separation and privilege boundaries: Keeping runtime application roles distinct from migration/admin roles—and tightening elevated or schema-creation privileges after initial setup—so an application flaw doesn't automatically carry superuser/DDL reach.
  • Concurrent state and session/connection edge cases: Testing overlapping requests against real Postgres state (such as concurrent updates, role/membership changes, and connection reuse) to catch race conditions and stale assumptions early.
  • Repeatable test runs against clean migrations: Applying migrations against an isolated test database so schema drift and constraint mismatches show up immediately during development and CI.

This setup is part of a multi-tenant foundation (B2B SaaS OS) I'm building—more details are at https://andrady.co , and I've attached a short clip showing the test/DB flow in action.

For those running PostgreSQL in multi-tenant setups: do you enforce isolation primarily via query scoping, Postgres RLS policies, or a combination of both—and where have you seen subtle edge cases creep in?


r/PostgreSQL • • 1d ago

Projects Audax Data Manager 1.6

1 Upvotes

Release Notes

  • Upgrade Notes:

    • rebranded the application as "Audax Data Manager": new logos, icons, splash screen and installer graphics throughout the app #886
    • the application data directory has been renamed from ~/.pgmanage to ~/.audaxdm (on Windows: %USERPROFILE%.pgmanage to %USERPROFILE%.audaxdm); existing data is migrated automatically on first launch #889
    • the database and log files have been renamed from pgmanage.db/pgmanage.log to audaxdm.db/audaxdm.log as part of the same automatic migration #889
    • the Windows uninstaller no longer removes application data by default
  • New features:

    • rewrote the Entity Relationship Diagram: intelligent relationship-edge routing, added snap-to-grid positioning, improved node/edge selection, add cardinality markers, viewport save/restore and a dedicated full-screen controls panel #885
    • rewrote the Database Console: make it behave like a real console, added command history navigation with the Up/Down keys and active database switching via the "\c" meta-command for Postgres #894
    • implemented visual feedback and keyboard navigation for moving focus between application panels #842
    • added support for SQLite3 database file paths containing a tilde (~)
    • implemented "rows affected" display on Query tab toolbar #701
  • UI/UX Improvements:

    • Database object icons and context menu icons/paddings now scale with the app font size setting #908
    • limited the minimum size of the application container and added scrollbars when the window is smaller than it, preventing UI breakage #726
    • the onboarding widget is now only shown on the Welcome screen #784
    • improved text truncation of recent connections subtitles to keep the most important part visible #804
    • improved Settings > Hotkeys tab layout: more rows fit on screen and columns are wide enough for larger key combinations like Ctrl+Shift+Space
    • implemented live resize of the built-in SSH terminal when font size or window size changes #897
    • improved desktop app startup time by switching the Linux build to PyInstaller's one-directory mode, avoiding double compression with AppImage #879
  • Bugs fixed:

    • fixed a remote code execution (RCE) vulnerability via psql meta-commands during plain-format server restore #899
    • fixed an XSS vulnerability in backup/restore preview alert messages #902
    • fixed database passwords being retained in the backup/restore process environment
    • fixed backup argument handling: missing --dbname option, invalid backup type validation, and pigz pipeline formatting in command previews
    • fixed pigz backup failing when file paths contain spaces #909
    • fixed ERD tab failing to generate relationship edges for foreign keys referencing quoted/uppercase table names #882
    • fixed DDL content being lost when toggling the Properties panel #907
    • fixed layout breakage when tabbing through DDL/Properties panel elements #906
    • closing a connection now also closes its open tabs #911
    • fixed Data Editor footer bar jumping when the tab regains focus
    • fixed light terminal theme rendering the cursor's character invisible
  • Other Changes

    • updated the docs link and wording of the onboarding wizard link on the Welcome screen #898
    • updated pev2 to 1.22
    • bumped nwjs from 0.77.0 to 0.114.0 to fix CSS rendering issues in ERD tab on Windows and macOS
    • bump cryptography from 45.0.5 to 46.0.7
    • bump django from 5.2.12 to 5.2.15
    • bump psycopg2 from 2.9.11 to 2.9.12
    • bump RestrictedPython from 8.0 to 8.3
    • bump oracledb from 3.4.2 to 4.0.1
    • bump pymysql from 1.1.2 to 1.1.3
    • bump django-vite from 3.0.4 to 3.0.6
    • bump prettytable from 3.16.0 to 3.17.0
    • bump ace-builds from 1.39.1 to 1.43.6
    • bump axios from 1.16.0 to 1.17.0
    • bump bootstrap from 5.3.3 to 5.3.8
    • bump fuse.js from 7.1.0 to 7.3.0
    • bump knex from 3.1.0 to 3.2.10
    • bump lodash from 4.17.21 to 4.18.1
    • bump pinia from 2.2.2 to 2.3.1
    • bump sql-formatter from 15.4.1 to 15.7.4
    • bump vue from 3.5.13 to 3.5.32
    • excluded django.contrib.admin and non-English locale/timezone data files from the PyInstaller bundle to reduce binary size #498

r/PostgreSQL • • 2d ago

Tools A Django migration linter that flags non-concurrent indexes, table rewrites and long locks

3 Upvotes

I maintain django-safe-migrations, a static linter for Django migrations. 0.8.0 came out today. I'm posting here because most of its rules are about what PostgreSQL actually does when Django runs a migration:

  • CREATE INDEX / DROP INDEX without CONCURRENTLY, and the reminder that concurrent operations need atomic = False
  • adding a foreign key or CHECK constraint without NOT VALID, which checks every existing row while holding a lock
  • unique constraints built without a concurrent index
  • shrinking a VARCHAR, which rewrites the table
  • ALTER TYPE ... ADD VALUE inside a transaction: the new enum value can't be used before commit
  • DDL in RunSQL without SET lock_timeout

It only reads the migration files, so it runs in CI without a database, and each finding comes with the safer pattern.

GitHub: https://github.com/YasserShkeir/django-safe-migrations

Which Postgres-side patterns would you want a linter like this to catch?


r/PostgreSQL • • 1d ago

Projects Run PL/SQL against PostgreSQL

0 Upvotes

I love Oracle's PL/SQL. I love PostgreSQL. Why not combine the two I thought. Here is the result: https://github.com/sqling-com/sqlingpl


r/PostgreSQL • • 2d ago

Tools Beta test of user account admin tool

Post image
0 Upvotes

This may be completely niche, so probably not of interest to EVERYONE... but I wish a tool like this existed for me. It didn't, as far as I could tell... so I wrote it :-)

In case there are any others who might benefit from it, I thought I'd share it as open source.

https://github.com/ppbrown/postgres-user-control

It's available both as a standalone app, or a container (build yourself, or use my helm chart to pull my image)

The problem:

While standard application creds are somewhat fixed and static, we had a situation where a semi-large group of people (20+) required different levels of access to different postgres instances.
Furthermore, we had a need to sometimes grant temporary access to certain people, at certain times. And then revoke it.

All while ensuring that these access changes got logged, and user actions get logged too.

Plus at the same time, I wanted to migrate humans over to using some kind of SSO type login to the database, rather than manually fed passwords.

---

In theory, I might have chosen some ansible or terraform approach, but thats not very readable at a glance. This is.

I welcome people's constructive comments. Even, "you could have just used [this other tool] instead"


r/PostgreSQL • • 2d ago

How-To Count-then-insert races in 4 popular Prisma apps, and how my first fix starved the pool

0 Upvotes

AI agents write this all the time:

const count = await prisma.item.count({ where: { accountId } })
if (count >= LIMIT) throw new Error("limit reached")
await prisma.item.create({ data })

Under read committed, two requests that land together both read the old count, both pass, and both insert. A free plan with a limit of 1 ends up with 2.

I ran the real handlers of a few open-source apps on a real Postgres and tried every order of two concurrent requests. Found the same shape in four of them:

  • formbricks: a survey quota of 1 that lets in two responses
  • documenso: the org member cap goes one over when two invites get accepted together
  • inbox-zero: the free knowledge base limit
  • papermark: the dataroom plan limit

cal.com came out clean, since they lock the booking row before counting.

What held for every order: SELECT ... FOR NO KEY UPDATE on the parent row (quota, team, org) before the count, in the same transaction. When there's no parent row, use pg_advisory_xact_lock per account.

The part I got wrong: my first inbox-zero fix used prisma.$transaction(async (tx) => ...) and called a premium check through the global client inside it. That needs a second pooled connection while the first one is held. With a pool of 10, ten creates at once can each wait on a connection that never frees. Three review bots caught it on the PR, and the repo's AGENTS.md bans that kind of transaction anyway. The new version uses an array transaction (lock, then a conditional insert), and the premium check runs outside it. 12 requests on a pool of 10 finish in under 0.6s.

Issues and PRs: documenso · formbricks · inbox-zero · papermark

I found these with VibeRaven, a tool I'm building. Happy to go deeper on the interleaving search if anyone's curious.AI agents write this all the time:

const count = await prisma.item.count({ where: { accountId } })
if (count >= LIMIT) throw new Error("limit reached")
await prisma.item.create({ data })

Under read committed, two requests that land together both read the old count, both pass, and both insert. A free plan with a limit of 1 ends up with 2.

I ran the real handlers of a few open-source apps on a real Postgres and tried every order of two concurrent requests. Found the same shape in four of them:

formbricks: a survey quota of 1 that lets in two responses
documenso: the org member cap goes one over when two invites get accepted together
inbox-zero: the free knowledge base limit
papermark: the dataroom plan limit

cal.com came out clean, since they lock the booking row before counting.

What held for every order: SELECT ... FOR NO KEY UPDATE on the parent row (quota, team, org) before the count, in the same transaction. When there's no parent row, use pg_advisory_xact_lock per account.The part I got wrong: my first inbox-zero fix used prisma.$transaction(async (tx) => ...) and called a premium check through the global client inside it. That needs a second pooled connection while the first one is held. With a pool of 10, ten creates at once can each wait on a connection that never frees. Three review bots caught it on the PR, and the repo's AGENTS.md bans that kind of transaction anyway. The new version uses an array transaction (lock, then a conditional insert), and the premium check runs outside it. 12 requests on a pool of 10 finish in under 0.6s.

Issues and PRs: documenso · formbricks · inbox-zero · papermark

I found these with VibeRaven, a tool I'm building. Happy to go deeper on the interleaving search if anyone's curious.


r/PostgreSQL • • 3d ago

Projects I measured how much smaller pgvector HNSW indexes get with halfvec and binary_quantize on real embeddings, and built a read-only tool to measure it on your own table

Thumbnail github.com
5 Upvotes

I've been testing pgvector's compression options on real embeddings: 171k TREC-COVID documents, Qwen3-Embedding-0.6B, 1024 dims. I built the real HNSW indexes and queried them, and the results surprised me enough to share.

indexsizesame top-10 as the current vector indexp50 query*
vector(1024) HNSW (today)1338 MB100%324 ms
halfvec expression index446 MB98.1%2.2 ms
binary_quantize + rerank ×1070 MB97.6%2.0 ms

*Docker, default shared_buffers = 128MB. The big index didn't fit in memory and the small ones did, so the latency gap is about memory, not CPU. On a box with enough RAM it will be much smaller.

Two things I didn't expect:

  • halfvec makes the HNSW index ~3× smaller, not 2×. A 4 KB vector(1024) row fills an 8 KB page on its own, while three halfvec rows fit in one page. A simple page-packing model (value + ~98 + 12·m bytes per row) predicts all five index sizes I built within 3%.
  • Measuring on a sample of the table overstates reranking. "Rerank the top 100 candidates" covers 2% of a 5k-row sample but 0.06% of the full table, so you have to compare against the full column.

How much quality you lose depends on your model and data. The docs, rightly, say to test it yourself. So I wrapped the method in a small CLI, pgshrink:

pip install pgshrink
pgshrink analyze "postgresql://user@host/db" --table documents --column embedding

What it does:

  • Uses ~200 random rows as queries and streams the whole column with COPY ... BINARY, so the exact top-k is the ground truth. It needs no labels or test queries.
  • Simulates each layout pgvector supports (halfvec, subvector truncation, binary_quantize with or without rerank) and reports how often it returns the same top-k as today, with a 95% CI.
  • Estimates each layout's HNSW index size and prints the CREATE INDEX CONCURRENTLY plus the rerank query for the smallest layout that keeps your results.
  • Runs read-only (default_transaction_read_only = on; there's a test for it). On the table above it took ~6 s.

The integration tests run every SQL statement it prints against a real pgvector and check that the neighbors match its prediction.

Caveats, so nobody is misled:

  • It measures "same results as today", not retrieval quality.
  • Real HNSW adds its own approximation: about −1 to −2 points in my test.
  • subvector truncation only makes sense for Matryoshka-trained models. The tool measures it anyway, so a big drop tells you yours isn't one.

Repo, with the full validation write-up: https://github.com/alessandroamormino/pgshrink

I'd love feedback from anyone running pgvector at scale. Do your numbers look like this? What does your index look like vs. your RAM? And which layouts or index types (IVFFlat? other m values?) would be worth adding?


r/PostgreSQL • • 3d ago

Tools Planflare compares two saved PostgreSQL EXPLAIN plans locally

0 Upvotes

I built Planflare to compare two saved EXPLAIN JSON plans while reviewing a query change. The display shows which operators changed and what each plan reported.

In the bundled fixture, the first plan has a sequential scan and a sort. The second uses an index scan. The saved execution times are 1,840.2 ms and 4.2 ms. The figures are fixture data so you can try the comparison without a database connection.

Try the bundled example on Node.js 24 or later with npx planflare@0.1.0 --demo. The comparison runs locally from the saved plans.

Source and demo

https://github.com/flipcyde101/planflare

When you review a plan diff, what do you check first? Operator changes, actual rows versus estimates, or buffer usage?


r/PostgreSQL • • 4d ago

Help Me! Is migrating from MongoDB to PostgreSQL worth it?

39 Upvotes

TL;DR: Running an EdTech platform with 600K+ users on MongoDB. Our data is heavily relational, and while regular API queries perform well, complex analytical queries are becoming painful to write and execute. Considering migrating to PostgreSQL and looking for advice on migration and production hosting.

Current setup:

- Node.js, MongoDB, and Mongoose.

- MongoDB Atlas (fully managed).

- 600K+ registered users and around 15K daily active users.

- An EdTech platform somewhat similar to Udemy or Coursera.

When the backend's foundations were laid, I was a junior working primarily on the frontend, so I wasn't involved in the database decision. It's been 1 year since we've been building this product.

Something that has been bothering me for a while is that we're essentially treating MongoDB like a relational database.

- Strict schemas and validations across collections.

- Heavily relational data with references between collections.

- Extensive use of aggregation pipelines and "$lookup".

- Very little reliance on MongoDB's schema flexibility.

To be fair, MongoDB has served us well. Our indexes are in place, most endpoints perform well, and we haven't faced any critical performance issues.

However, complex analytical queries for internal dashboards are a different story. Some involve joining up to 10 collections, take over 60 seconds, or occasionally time out despite optimization. Writing and maintaining these aggregation pipelines is also becoming increasingly painful.

I've experimented with MongoDB's transactions but didn't particularly enjoy the experience. I'd also like stronger database level relational integrity and better transaction management.

I feel PostgreSQL would have been a more natural fit for our data model from the beginning.

What I'd like advice on:

  1. Is migration justified? Given that MongoDB works well for most of our workloads, would migrating to PostgreSQL be worth the effort, or should I address the analytical workload separately?
  2. Migration strategy: If I proceed, how should I approach migrating a live production database at this scale? Any articles, case studies, or resources would be appreciated.
  3. PostgreSQL hosting: One thing I genuinely appreciate about MongoDB Atlas is how little I have to worry about infrastructure, backups, updates, and maintenance. What's the equivalent experience for PostgreSQL?
  4. Self-hosted vs. managed: How do you guys run PostgreSQL in production? Do you self-host it on a private EC2 instance or use something like AWS RDS, Neon, or another managed provider?

I've worked with relational databases on smaller projects, but never operated PostgreSQL in production at this scale.

I don't want to migrate just because I prefer PostgreSQL, but I also don't want to ignore what might be a fundamental architectural mismatch simply because things work today.

Would love to your thoughts and suggestions on this


r/PostgreSQL • • 4d ago

Projects Storing generated PDFs in Postgres vs object storage: where do you draw the line?

Thumbnail reddit.com
26 Upvotes

r/PostgreSQL • • 4d ago

Tools I needed a distributed DB solution, found Pigsty

0 Upvotes

(Unsure of which flair was accurate). So yeah had a project at work where I was replacing a multi-zone RDS with something on-prem. Looked at CockroachDB and Pigsty.io and after discovering breaking incompatibilities on the Cockroach side ended up choosing Pigsty.

In case anyone's interested the architecture is 5 Rocky vm's scattered across three geographically desperate offsite dcs. Two of this are in the US, the third (for quorum only really) is in the EU.

My god.. the amount of stuff the Pig folks packed into this application is astounding. Granted I do not have a prod DB in the platform just yet.. I'm seriously thinking of getting the boss to pay for some support because these folks made a fantastical distributed database application!

(posting in this sub because I will be rolling nothing but pgsql databases in this application)


r/PostgreSQL • • 7d ago

Feature PITR a 5 TB Postgres database in 5 seconds.

60 Upvotes

I'm Scott, the pgCraftsman and a Sr. Staff Engineer at Databricks. I've been operating some of the world's largest and most complex Postgres deployments for 22 years.

Ever need to do an emergency PITR at 2AM because an agent dropped a table?

Lakebase and Neon Postgres: PITR a 5TB DB in 5 seconds

https://pgcraftsman.io/posts/restoring-5-tb-of-postgres-in-5-seconds/


r/PostgreSQL • • 6d ago

Projects I built a free, read-only CLI that audits legacy Postgres/SQLite schemas before migration and compiles dbt staging + diagnostic SQL (zero PII in outputs)

2 Upvotes

Most legacy migration blowups happen in week one because nobody knew a source table lacked a primary key for AWS DMS CDC, had NUL bytes (`0x00`) that crash Postgres UTF-8 imports, carried CP1252 mojibake, or had free-text notes full of undeclared PII.

I open-sourced `crucible-audit` (MIT), a read-only Python CLI that profiles a source database locally with no outbound network calls. It outputs a static HTML audit page, a `profile.json` evidence file, dbt staging models, and read-only diagnostic SQL.

What it checks right now:

- AWS DMS CDC blockers: missing primary keys, wide LOB columns, NUL-byte poison, CP1252 encoding ghosts, and legacy proprietary types.

- Shadow FKs and orphan keys: infers undeclared foreign keys by column naming and key overlap, then reports both total orphaned rows and distinct orphan keys (`COUNT(*)` vs `COUNT(DISTINCT)`).

- UK shadow PII (Zero-PII output): detects UK NINOs, Modulus-11 validated NHS numbers, and legacy redaction markers inside free-text columns. Outputs record counts, rates, column metadata, and rule IDs only, so no raw cell values or partial masks ever land in JSON, HTML, or SQL files.

- PostgreSQL-valid diagnostic SQL: generated regex queries use POSIX word boundaries (`\y`) instead of PCRE `\b`, so the compiled `diagnostics/*.sql` files run directly in `psql`.

- External `rules.yaml`: toggle rule packs or add custom regex rules without editing Python.

Live sample audit (generated from a synthetic dirty UK council SQLite DB): https://schemafirst.parkanore.com

GitHub (MIT): https://github.com/oranmcclintock/schemafirst.git

Curious what migration failure modes you hit most often on legacy Postgres, SQL Server, or Oracle estates that a pre-flight profiler should catch.


r/PostgreSQL • • 7d ago

Community How do you find a particular record if you dont even know which table in a DB has it?

4 Upvotes

The chance of running into this situation is 0.00005% and you will actually have to want to get into this situation for you to actually be in this situation but lets say it happened. What will you do?


r/PostgreSQL • • 8d ago

Community How one connection kills a database

Thumbnail planetscale.com
16 Upvotes

r/PostgreSQL • • 8d ago

How-To A pg_stat_statements regression case: total calls rose while one row reset

4 Upvotes

I contributed a collector fix to pg-regression-radar; the project's maintainer merged it on November 12. Today I ran a separate test: reset one role's counters while another role keeps executing the same statement. The total can keep increasing, so checking for a decrease after grouping by queryid misses the reset.

On a disposable PostgreSQL 16.13 instance, I ran SELECT 1 under two roles. PostgreSQL assigned both rows the same queryid. These are the observed call counts:

SnapshotRole ARole BSum
Initial10212
Before reset12315
Reset B, then execute A ten times and B once22123

Subtracting the grouped totals gives 23 - 15 = 8. The fixture executed 11 calls after the second snapshot. Keeping the rows separate gives A's increment of 10 and B's one call after its known reset.

The reset happened immediately after the second snapshot. In a real scrape interval, you cannot recover calls that happened before a reset and disappeared before the next scrape. A per-row decrease can expose a reset; it cannot tell you how much history the reset discarded. It can also miss a reset if the new counter has already overtaken the previous value.

The original issue involved a collector treating independent rows as successive samples of the same counter. The merged fix derives intervals per (dbid, userid, queryid, toplevel) before rolling them up for detection.

For a collector regression test, I would include both a visible decrease in the aggregate and this increasing-total case. Also establish a fresh baseline when the set of sampled rows changes, so an entry appearing or dropping out of a top-N scrape does not look like query activity.

PostgreSQL's row definition and reset API · Public two-role integration test

The table is a new local synthetic test, separate from the linked integration test. I used AI assistance for the code and write-up.

To reproduce the table, save the complete script below as postgres_row_reset_repro.py. It uses PostgreSQL 16's initdb, pg_ctl and psql, with the pg_stat_statements extension installed. Run it as a regular user who can start a local PostgreSQL instance.

The script creates a new temporary cluster with TCP disabled and a private Unix socket. It creates the two fixture roles only in that cluster, resets only role B's statement, checks the counts, then stops and removes the entire temporary cluster. It clears inherited PG* connection settings. The default binary path is the Homebrew PostgreSQL 16 path used for this run; set POSTGRES_BIN if your PostgreSQL 16 binaries are elsewhere.

python3 postgres_row_reset_repro.py

Complete tested script:

"""Run only against a newly-created disposable local PostgreSQL 16 instance.

Uses installed official PostgreSQL tools; no downloaded project code executes.
Unix socket only. The temporary database shuts down and is removed in finally.
"""
from __future__ import annotations

import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile

BIN = Path(os.environ.get("POSTGRES_BIN", "/opt/homebrew/opt/postgresql@16/bin"))


def main():
    tmp = Path(tempfile.mkdtemp(prefix="pg-row-reset-"))
    data, socket = tmp / "data", tmp / "socket"
    socket.mkdir()
    started = False
    env = os.environ.copy()
    # Ignore any inherited connection setting from another task.
    for key in list(env):
        if key.startswith("PG"):
            del env[key]

    def command(args):
        return subprocess.run(args, env=env, text=True, capture_output=True, check=True).stdout.strip()

    def sql(statement):
        return command([str(BIN / "psql"), "-X", "-h", str(socket), "-p", "55443",
                        "-U", "postgres", "-d", "postgres", "-At", "-v", "ON_ERROR_STOP=1",
                        "-c", statement])

    def calls(role, count):
        sql(f"SET ROLE {role}; " + "SELECT 1; " * count)

    def snapshot():
        return json.loads(sql("""SELECT json_agg(x ORDER BY role) FROM (
            SELECT r.rolname AS role, s.dbid, s.userid, s.queryid, s.toplevel, s.calls
            FROM pg_stat_statements s JOIN pg_roles r ON r.oid=s.userid
            WHERE r.rolname IN ('case_role_a','case_role_b') AND s.query='SELECT $1'
        ) x"""))

    try:
        command([str(BIN / "initdb"), "-D", str(data), "-U", "postgres", "-A", "trust", "--no-locale"])
        with (data / "postgresql.conf").open("a") as stream:
            stream.write("\nlisten_addresses=''\nshared_preload_libraries='pg_stat_statements'\n")
            stream.write(f"unix_socket_directories='{socket}'\nport=55443\n")
        command([str(BIN / "pg_ctl"), "-D", str(data), "-l", str(tmp / "server.log"), "-w", "start"])
        started = True
        server_version = sql("SHOW server_version")
        sql("CREATE EXTENSION pg_stat_statements; CREATE ROLE case_role_a; CREATE ROLE case_role_b;")
        calls("case_role_a", 10)
        calls("case_role_b", 2)
        first = snapshot()
        calls("case_role_a", 2)
        calls("case_role_b", 1)
        second = snapshot()
        b = next(row for row in second if row["role"] == "case_role_b")
        sql(f"SELECT pg_stat_statements_reset({b['userid']}, {b['dbid']}, {b['queryid']})")
        calls("case_role_a", 10)
        calls("case_role_b", 1)
        third = snapshot()
        assert [r["calls"] for r in first] == [10, 2], first
        assert [r["calls"] for r in second] == [12, 3], second
        assert [r["calls"] for r in third] == [22, 1], third
        assert len({r["queryid"] for snap in [first, second, third] for r in snap}) == 1
        before = {r["role"]: r for r in second}
        observed_activity = sum(r["calls"] - before[r["role"]]["calls"]
                                if r["calls"] >= before[r["role"]]["calls"] else r["calls"]
                                for r in third)
        result = {"postgresql": server_version, "network": "private Unix socket; TCP disabled",
                  "snapshots": [first, second, third],
                  "aggregate_then_difference": sum(r["calls"] for r in third) - sum(r["calls"] for r in second),
                  "row_activity_with_known_b_reset": observed_activity,
                  "actual_fixture_calls_after_second_snapshot": 11,
                  "limitation": "Reset performed immediately after snapshot two; no hidden pre-reset activity. A real collector cannot recover activity discarded by an unobserved reset."}
        assert result["aggregate_then_difference"] == 8
        assert observed_activity == 11
    finally:
        if started:
            command([str(BIN / "pg_ctl"), "-D", str(data), "-m", "fast", "-w", "stop"])
        shutil.rmtree(tmp)
    result["temporary_database_stopped_and_removed"] = True
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()