# Adding a column (a table step)

This is what you used to do by adding a block to `upgradedb.sql`. Now it is a **step file** in `~/dev/improvize/lesage/sql/steps/`.

## 1. Pick the version

Look at `lesage/sql/version` and `lesage/released.json`:

- **The current version is in `released.json`** (e.g. `version` = 1 and `"1"` is released): bump `version` to `2`. Your new steps are `0002-*.sql`.
- **The current version is not released yet** (you already bumped it): keep it and add your step under that number.

Several files per version are fine. They run in byte-wise filename order, so use a suffix to order them: `0002-1-…`, `0002-2-…`. Lint refuses a step numbered above `version`.

<p class="callout warning">Never add a block to a step that belongs to a released version (e.g. `0001-1-upgradedb.sql`). The databases that already have version 1 would never run it, and lint fails because the released checksum no longer matches.</p>

## 2. Write the step

```sql
-- steps/0002-1-oeu-isdeposited.sql
-- Why: (ticket / one sentence). Converges on every replay: addcolumn skips an existing column.
DO $step$
BEGIN
	IF tableexists('oeu') THEN
		PERFORM addcolumn('oeu', 'IsDeposited', 'BOOLEAN NOT NULL DEFAULT FALSE',
			'The work has been deposited with the society');
	END IF;
END
$step$;
```

Same idea as in `upgradedb.sql`, with three differences:

- it is a `DO` block (or plain DDL), not the body of a function;
- it runs **as the owner role** (`SET LOCAL ROLE` is done by the engine), inside the engine's transaction;
- it may be run **again** at any time on a database that already has the column (reinstall), so it must be a no-op then.

### Backfill only when the column is new

`addcolumn` returns `TRUE` when it created the column, so a backfill runs once and a replay skips it:

```sql
DO $step$
BEGIN
	IF addcolumn('oeu', 'IsDeposited', 'BOOLEAN NOT NULL DEFAULT FALSE') THEN
		UPDATE oeu SET IsDeposited = TRUE WHERE datedepotsacem IS NOT NULL;
	END IF;
END
$step$;
```

### Other guarded changes

```sql
DO $step$
BEGIN
	-- new table
	CREATE TABLE IF NOT EXISTS public.depots (iddepot SERIAL PRIMARY KEY, idoeu INTEGER NOT NULL, datedepot DATE);

	-- index
	IF NOT indexexists('ix_depots_idoeu') THEN
		CREATE INDEX ix_depots_idoeu ON public.depots (idoeu);
	END IF;

	-- foreign key (helper checks constraintexists itself)
	PERFORM addconstraintforeignkey('fk_depots_oeu', 'depots', 'idoeu', 'oeu', 'idoeu', 'ON DELETE CASCADE');

	-- other constraint
	IF NOT constraintexists('depots', 'ck_depots_date') THEN
		ALTER TABLE public.depots ADD CONSTRAINT ck_depots_date CHECK (datedepot >= '1900-01-01');
	END IF;

	-- remove a column / widen a VARCHAR
	PERFORM dropcolumn('oeu', 'oldfield');
	PERFORM resizefield('oeu', 'soustitre', 100);
END
$step$;
```

<p class="callout danger">`addconstraintforeignkey` cleans orphans before adding the key: it sets them to NULL when the column is nullable and **deletes the rows** otherwise. Check the data first.</p>

## Helpers available in steps (from `common`)

<table id="bkmrk-helperreturns-addcol"><thead><tr><th>Helper</th><th>Returns</th></tr></thead><tbody><tr><td>`addcolumn(table, column, type [, comment])`</td><td>`TRUE` if it created the column</td></tr><tr><td>`dropcolumn(table, column)`</td><td>boolean</td></tr><tr><td>`resizefield(table, column, newsize)`</td><td>boolean</td></tr><tr><td>`addconstraintforeignkey(name, table, column, othertable, othercolumn, options)`</td><td>void, no-op if the constraint exists</td></tr><tr><td>`tableexists`, `columnexists`, `indexexists`, `constraintexists`, `triggerexists`, `columnisnullable`, `columntype`, `hasdefault`</td><td>tests for guards</td></tr><tr><td>`dropconstraint`, `addcreatorcreated(table)`, `fixsequence(table)`</td><td></td></tr></tbody></table>

Table names without a schema resolve to the bundle's schema (`search_path` file, `public` for Le Sage).

## What "idempotent" means here

- Guard every object on its existence (`IF NOT EXISTS`, `indexexists`, `constraintexists`…). Never rely on "this step already ran".
- A replay converges to the target but **does not fix an object with a wrong definition**: changing an existing column or constraint takes a new step that detects the old shape (`columntype`, `constraintexists`) and changes it.
- Table DDL (`CREATE/ALTER/DROP TABLE`, `CREATE INDEX`, `VALIDATE CONSTRAINT`) is allowed **only in `steps/`**.

## Forbidden in every bundle file (lint refuses)

`BEGIN` / `COMMIT` / `ROLLBACK` / `SAVEPOINT`, `SET ROLE` / `RESET ROLE` / `setrole()`, plain session `SET` (`SET LOCAL` is fine), `CONCURRENTLY`, `VACUUM`, `COPY`, `CREATE/ALTER/DROP EXTENSION`, psql `\` commands, `udf_dropfunction`. Files are UTF-8 without BOM, LF line endings.

## Then

Run the checks and try it on your test database: see *Testing locally without releasing*.