sqitchcraft

Functions and views

A table changes through migrations, because its rows have to survive. A function or a view has no rows: you can replace it whole. That makes them the easiest objects to keep in one file, and the place where that file pays off most.

The same example project, later the same day: Ana and Ben add a function, change it three times, and rename a column it depends on. Every output below was captured from those runs.

1. Add a function

Support wants to know what a customer still owes. Ana starts from a template:

$ create-migration function general --schema billing --function-name outstanding_for
Created database/deploy/billing/function/outstanding_for.sql
Created database/revert/billing/function/outstanding_for.sql
Created database/verify/billing/function/outstanding_for.sql
Added "billing/function/outstanding_for" to database/sqitch.plan

The template is a placeholder PL/pgSQL function to fill in. She replaces it with what she means, and makes the verify script call the function, so a deploy fails if the function cannot run:

deploy/billing/function/outstanding_for.sql

begin;

    create or replace function billing.outstanding_for(email text)
        returns numeric(12,2)
        language sql
        stable
    as $$
        select coalesce(sum(amount), 0)
        from billing.invoice
        where customer_email = email
          and paid_at is null;
    $$;

    comment on function billing.outstanding_for(text) is
      'What a customer still owes across all their unpaid invoices.';

commit;

verify/billing/function/outstanding_for.sql

begin;

    select billing.outstanding_for('nobody@example.com');

rollback;

The revert the template wrote is drop function if exists billing.outstanding_for;, which is right for a function that did not exist before.

$ sqitch deploy
Deploying changes to db:pg:shop
  + billing/function/outstanding_for .. ok
$ psql -Atc "select billing.outstanding_for('ana@example.com')"
200.50

Ana has two unpaid invoices: 120.50, issued three days ago, and 80.00, dated two days from now.

2. Change its body

Support notices the 80.00: an invoice dated next week is not owed yet. Ben needs one more condition. The function is deployed, so its script is history; he reworks it, and sqitch wants a tag to mark where the old version ends:

$ sqitch rework billing/function/outstanding_for -n "Leave out invoices issued in the future"
Cannot rework "billing/function/outstanding_for" without an intervening tag.
Use "sqitch tag" to create a tag and try again

$ sqitch tag @2026-11-25_outstanding -n "before outstanding_for skips future invoices"
Tagged "billing/function/outstanding_for" with @2026-11-25_outstanding in database/sqitch.plan

$ sqitch rework billing/function/outstanding_for -n "Leave out invoices issued in the future"
Added "billing/function/outstanding_for [billing/function/outstanding_for@2026-11-25_outstanding]" to database/sqitch.plan.
Modify these files as appropriate:
  * database/deploy/billing/function/outstanding_for.sql
  * database/revert/billing/function/outstanding_for.sql
  * database/verify/billing/function/outstanding_for.sql

sqitch has copied the deploy script to outstanding_for@2026-11-25_outstanding.sql and made the old deploy script the new revert script. Ben edits the function where it is. Here is his pull request next to the same change in a numbered-migrations project:

A rework

git diff, deploy/billing/function/outstanding_for.sql

@@ -10,10 +10,11 @@ begin;
         select coalesce(sum(amount), 0)
         from billing.invoice
         where customer_email = email
-          and paid_at is null;
+          and paid_at is null
+          and issued_on <= current_date;
     $$;

     comment on function billing.outstanding_for(text) is
-      'What a customer still owes across all their unpaid invoices.';
+      'What a customer still owes across all their unpaid invoices issued so far.';

The reviewer sees the one condition that changed, in the context of the function.

A new migration

The same change, as numbered migrations would have it

+create or replace function billing.outstanding_for(email text)
+    returns numeric(12,2)
+    language sql
+    stable
+as $$
+    select coalesce(sum(amount), 0)
+    from billing.invoice
+    where customer_email = email
+      and paid_at is null
+      and issued_on <= current_date;
+$$;

The whole function, copied into a new file. Spot the change. Now imagine it is 200 lines of PL/pgSQL.

git sees the snapshots for what they are:

$ git diff --cached --stat -C
 database/deploy/billing/function/outstanding_for.sql     |  5 +++--
 ...or.sql => outstanding_for@2026-11-25_outstanding.sql} |  0
 database/revert/billing/function/outstanding_for.sql     | 16 ++++++++++++++--
 ...or.sql => outstanding_for@2026-11-25_outstanding.sql} |  0
 database/sqitch.plan                                     |  2 ++
 .../function/outstanding_for@2026-11-25_outstanding.sql  |  7 +++++++
 6 files changed, 26 insertions(+), 4 deletions(-)

Deploying replaces the function; reverting puts the previous one back. Both are checked here against the same data:

$ sqitch deploy
  + billing/function/outstanding_for .. ok
$ psql -Atc "select billing.outstanding_for('ana@example.com')"
120.50
$ sqitch revert -y --to @2026-11-25_outstanding
  - billing/function/outstanding_for .. ok
$ psql -Atc "select billing.outstanding_for('ana@example.com')"
200.50

3. Change its signature

Finance wants to ask what a customer owed at the end of last month. Ana adds a date argument, defaulting to today so existing callers keep working. The obvious edit is to add the argument and keep create or replace. PostgreSQL accepts it, and that is the problem:

=# create or replace function billing.outstanding_for(email text, as_of date default current_date) …
CREATE FUNCTION
=# \df billing.outstanding_for
 Schema  |      Name       | Result data type |             Argument data types
---------+-----------------+------------------+---------------------------------------------
 billing | outstanding_for | numeric          | email text
 billing | outstanding_for | numeric          | email text, as_of date DEFAULT CURRENT_DATE
=# select billing.outstanding_for('ana@example.com');
ERROR:  function billing.outstanding_for(unknown) is not unique
HINT:  Could not choose a best candidate function. You might need to add explicit type casts.

A function is identified by its name and argument types, so a new argument makes a new function. The old one stays, and every existing one-argument call now matches both. Two other signature changes are refused outright:

-- returns bigint instead of numeric
ERROR:  cannot change return type of existing function
HINT:  Use DROP FUNCTION billing.outstanding_for(text) first.

-- the parameter called customer_email instead of email
ERROR:  cannot change name of input parameter "email"
HINT:  Use DROP FUNCTION billing.outstanding_for(text) first.

So the definition drops the old signature and creates the new one, in one transaction so no caller sees neither. Both statements are safe to run again, which a definition must be:

@@ -2,7 +2,11 @@

 begin;

-    create or replace function billing.outstanding_for(email text)
+    -- A new argument is a new function: drop the old one, or both would exist
+    -- and every one-argument call would become ambiguous.
+    drop function if exists billing.outstanding_for(text);
+
+    create or replace function billing.outstanding_for(email text, as_of date default current_date)
         returns numeric(12,2)
         language sql
         stable
@@ -11,10 +15,10 @@ begin;
         from billing.invoice
         where customer_email = email
           and paid_at is null
-          and issued_on <= current_date;
+          and issued_on <= as_of;
     $$;
$ psql -Atc "select billing.outstanding_for('ana@example.com'), billing.outstanding_for('ana@example.com', current_date + 5)"
120.50|200.50

Old calls still work through the default. Two more things to know about the drop. It takes the function's grants and comment with it, so the definition has to add them again; this one restates its comment, and a function with grants would restate those too. And it fails if a view or another object depends on the function; then those have to be dropped and created around it.

The revert needs the same care. sqitch made the previous deploy script the revert script, and that script only creates the one-argument function. Ana tried it before editing it:

$ sqitch revert -y --to @2026-11-25_as_of
  - billing/function/outstanding_for .. ok
$ psql -c "select billing.outstanding_for('ana@example.com')"
ERROR:  function billing.outstanding_for(unknown) is not unique

The revert has to drop the new signature first:

  begin;

+     drop function if exists billing.outstanding_for(text, date);
+
      create or replace function billing.outstanding_for(email text)

4. When a table change breaks it

Refunds settle invoices too, so Ben renames paid_at to settled_at in the table's file. The function reads paid_at. A SQL function's body is checked when it is created, not when the tables it reads change, so PostgreSQL will happily rename the column and leave the function broken until someone calls it.

sqiff notices the name first. It also asks, as it always does when a column disappears and another of the same type appears:

$ sqiff table database/deploy/billing/table/invoice.sql
-- billing.invoice.paid_at
--   named in
--     billing.outstanding_for
-- paid_at is dropped and settled_at added with the same type; pass --rename paid_at:settled_at if it is a rename, or --drop-and-add if it is not
…
$ sqiff table database/deploy/billing/table/invoice.sql --rename paid_at:settled_at
-- billing.invoice.paid_at
--   named in
--     billing.outstanding_for

-- table column billing.invoice.settled_at
-- hazard: breaks running code that still uses the old name
alter table billing.invoice rename column paid_at to settled_at;

sqiff found the name in the function's body. With the plpgsql_check extension installed it also follows dependencies into PL/pgSQL. Then sqint's dynamic pass deploys the change into a scratch database and settles it:

BLOCK database/deploy/migrations/2026/11/2026-11-25-104309-rename-billing.invoice.settled_at.sql:3 [function/broken-body] `billing.outstanding_for(text,date)` is broken after deploying `migrations/2026/11/2026-11-25-104309-rename-billing.invoice.settled_at`
        Postgres rejects the current definition of `billing.outstanding_for(text,date)` once `migrations/2026/11/2026-11-25-104309-rename-billing.invoice.settled_at` is deployed: column "paid_at" does not exist. No later change in this PR fixes it, so it stays broken after the deploy. Sqitch commits each change on its own, so every call to the function fails for as long as it is broken. Redefine the function in the same change that breaks it (for a new column, inside the migration's transaction).

The advice is the important part: reworking the function in a later change would not be enough, because sqitch commits each change separately and the function would be broken in between. So Ben does two things.

Redefine it in the migration

deploy/migrations/2026/11/…-rename-billing.invoice.settled_at.sql

begin;

  -- Do not remove this line
  select set_config('lock_timeout', '50ms', false);

  -- hazard: breaks running code that still uses the old name
  alter table billing.invoice
      rename column paid_at to settled_at;

  -- billing.outstanding_for reads this column by name. Redefine it in the
  -- same transaction, so no call ever sees it broken.
  create or replace function billing.outstanding_for(email text, as_of date default current_date)
      returns numeric(12,2)
      language sql
      stable
  as $$
      select coalesce(sum(amount), 0)
      from billing.invoice
      where customer_email = email
        and settled_at is null
        and issued_on <= as_of;
  $$;

commit;

Rework the definition to match

deploy/billing/function/outstanding_for.sql

@@ -14,7 +14,7 @@ begin;
         select coalesce(sum(amount), 0)
         from billing.invoice
         where customer_email = email
-          and paid_at is null
+          and settled_at is null
           and issued_on <= as_of;
     $$;

The migration keeps production working; the rework keeps the file truthful, so the next reader sees settled_at. The migration comes first in the plan, so on deploy the rework finds the function already in this shape.

$ sqitch deploy
$ psql -Atc "select billing.outstanding_for('ana@example.com')"
120.50

And the way back

We first stopped there, and the plan deployed cleanly. Then the check script reverted the branch's changes, and failed:

$ scripts/check-database HEAD~1
…
== revert this branch's 3 changes and deploy them again
psql:database/revert/billing/function/outstanding_for.sql:19: ERROR:  column "paid_at" does not exist
not ok

Reverts run in reverse plan order, so the function rework is undone first. Its revert script, which sqitch made from the previous definition, recreated the function reading paid_at, while the migration that renamed the column was still in place. PostgreSQL checks a SQL function's body when it is created, and refused.

The fix mirrors the deploy. The migration owns the function's change in both directions, and the rework only keeps the file truthful:

The migration's revert

revert/migrations/2026/11/…-rename-billing.invoice.settled_at.sql

  alter table billing.invoice
      rename column settled_at to paid_at;

  -- The deploy redefined billing.outstanding_for for the new name; put back the
  -- definition that reads the old one, in the same transaction.
  create or replace function billing.outstanding_for(email text, as_of date default current_date)
      …
        and paid_at is null
      …

The rework's revert

revert/billing/function/outstanding_for.sql

    -- This rework only brought the definition in line with the rename migration,
    -- which changed the function itself. When this revert runs, that migration
    -- is still deployed and the column is still settled_at, so the function
    -- stays as it is; the migration's revert puts back the paid_at version.
    create or replace function billing.outstanding_for(email text, as_of date default current_date)
      …
          and settled_at is null
      …
$ scripts/check-database HEAD~1
…
== revert this branch's 3 changes and deploy them again
== database checks passed

A deploy that works says nothing about its revert. Check both, every time.

The rename itself is still a breaking change for application code that reads paid_at; sqiff's hazard says so. On a live system you would use the two-release rename instead, and redefine the function in its first step the same way.

5. Its history

Four commits touched the function. Each line of its file points at the one that last meant to change it:

$ git log --format='%h %an %s' -- database/deploy/billing/function/outstanding_for.sql
2c86364 Ben Okafor Call it settled_at: refunds settle invoices too
ee678f6 Ana Lima Ask what a customer owed on a given day
6f02996 Ben Okafor Leave invoices issued in the future out of what a customer owes
ef17119 Ana Lima Add what a customer still owes

$ git blame -s database/deploy/billing/function/outstanding_for.sql
ee678f69  7)     drop function if exists billing.outstanding_for(text);
ee678f69  8)
ee678f69  9)     create or replace function billing.outstanding_for(email text, as_of date default current_date)
ef171198 10)         returns numeric(12,2)
ef171198 11)         language sql
ef171198 12)         stable
ef171198 13)     as $$
ef171198 14)         select coalesce(sum(amount), 0)
ef171198 15)         from billing.invoice
ef171198 16)         where customer_email = email
2c863649 17)           and settled_at is null
ee678f69 18)           and issued_on <= as_of;
ef171198 19)     $$;

With each version copied into a new migration, blame on the newest copy would credit every line to whoever made the last copy.

6. Views

A view works like a function: one file under view/, changed with sqitch rework, replaced whole with create or replace view. PostgreSQL limits what a replacement may change, though. Tried on billing.daily_invoiced:

-- add a column at the end
CREATE VIEW

-- rename issued_on to day
ERROR:  cannot change name of view column "issued_on" to "day"
HINT:  Use ALTER VIEW ... RENAME COLUMN ... to change name of view column instead.

-- leave out the total column
ERROR:  cannot drop columns from view

The rules, in short