Change your schema safely
What you will do
You will change a collection that is already published. First you will make an additive change, which npx phibac deploy publishes as a new minor version. Then you will make a breaking change, see npx phibac deploy refuse it, and publish it as a new major version. Last, you will make your app handle the records written before the change.
A few words used on this page:
- An app is the web app you build. A user is the person who uses it and whose records it saves.
- A collection is one kind of data, such as notes, and each saved item in it is a record. The collection's schema describes its fields: their names, types and rules.
- A major version is a numbered version of a schema: the
versioninpb.config.ts. Within one major version, each published change gets a new minor version: 1.0, then 1.1, and so on. - Consent is the user's permission for another app to read your collection. Apps that have it read your records too, so a change to your schema can affect them.
Before you start
You need the notes app as Upload and show files leaves it: the local server running (npx phibac dev), the com.example.notes.note collection published at major version 1, and a few notes saved, some of them pinned.
The steps show pb.config.ts as that guide leaves it, with a photo field. If you skipped it, leave out the photo line and fileRef. If you added other fields in other guides, keep them, and change only the lines each step names.
Steps
1. Know which changes are additive and which are breaking
The server compares your new schema with the published one. An additive change keeps every record and every app that uses the collection working, so it is published in the same major version, as a new minor version. A breaking change could make existing records or apps wrong, so it needs the next major version.
| Change | Kind |
|---|---|
| Add an optional field | additive |
| Change the description of the collection or of a field | additive |
Add or remove indexed or sensitive |
additive |
Raise a field's maxLength, or remove it |
additive |
Lower a field's min, raise its max, or remove either |
additive |
Add a value to an enumOf list |
additive |
| Remove a field (renaming a field removes it) | breaking |
| Change a field's type | breaking |
| Make a field required, or no longer required | breaking |
| Add a required field | breaking |
Add a maxLength, or lower it |
breaking |
Add a min or max, raise the min or lower the max |
breaking |
Remove a value from an enumOf list |
breaking |
pb.config.ts reference gives the reason npx phibac deploy prints for each breaking change.
2. Make an additive change
Add an optional title field: in pb.config.ts, add the title line to the fields. The result is (keep your own app value):
import { defineApp, collection, string, boolean, fileRef } from "phibac";
export default defineApp({
app: "app_...",
collections: {
"com.example.notes.note": collection({
version: 1,
description: "A note written by the user",
fields: {
text: string({ description: "Note text", maxLength: 20000, required: true }),
pinned: boolean({ description: "Whether the note is pinned", indexed: true }),
photo: fileRef({ description: "A photo attached to the note" }),
title: string({ description: "A short title for the note", maxLength: 200 }),
},
}),
},
});
Publish it:
npx phibac deploy
You should see (your app ID differs, and the minor version depends on how many changes you published before):
Previewing 1 collection for app app_01M7E9YEJZZSYKAAB14AMBBJPR on http://localhost:8787
com.example.notes.note additive (will become version 1.2)
published com.example.notes.note version 1.2
Published 1 collection.
Then run npx phibac generate. src/pb-types.ts gains title?: string;, and SCHEMA_MAJORS still says 1. Your notes are unchanged: they simply have no title yet. Apps that read your collection with the user's consent see the new field too, because consent covers fields added later.
3. Read the preview before anything is published
npx phibac deploy never publishes straight away. For each collection in pb.config.ts it first asks the server for a dry run, a preview that publishes nothing, and prints one line per collection:
same (version 1.2, nothing to publish): the collection has not changed; it is skipped.additive (will become version 1.3): the change will be published as that version.breaking, followed by one line per reason: the change cannot be published in this major version.failed (<error code>), followed by the server's message and a hint: the collection has another problem, such as a missing description.
If any collection is breaking or failed, npx phibac deploy publishes nothing at all, for every collection, and exits with code 1. Only when every preview passes does it publish the collections that changed.
4. Try a breaking change
Rename pinned to starred: in pb.config.ts, replace the pinned line with a starred line. The file is now:
import { defineApp, collection, string, boolean, fileRef } from "phibac";
export default defineApp({
app: "app_...",
collections: {
"com.example.notes.note": collection({
version: 1,
description: "A note written by the user",
fields: {
text: string({ description: "Note text", maxLength: 20000, required: true }),
starred: boolean({ description: "Whether the user starred the note", indexed: true }),
photo: fileRef({ description: "A photo attached to the note" }),
title: string({ description: "A short title for the note", maxLength: 200 }),
},
}),
},
});
Run npx phibac deploy. It refuses:
Previewing 1 collection for app app_01M7E9YEJZZSYKAAB14AMBBJPR on http://localhost:8787
com.example.notes.note breaking
- field removed: pinned
Publish it as the next major version: set "version": 2 on this collection in pb.config.ts, or remove the changes listed above.
error: nothing was published: com.example.notes.note cannot be published (see above). Fix 1 collection and run phibac deploy again.
To the server a rename is a removed field plus a new one. Adding starred alone would be additive; removing pinned is what breaks, because existing notes have pinned, and code written for version 1, in your app or in another app that reads your notes, uses it. Nothing was published.
5. Publish the change as the next major version
In pb.config.ts, change version: 1 to version: 2, and nothing else. The whole file is now:
import { defineApp, collection, string, boolean, fileRef } from "phibac";
export default defineApp({
app: "app_...",
collections: {
"com.example.notes.note": collection({
version: 2,
description: "A note written by the user",
fields: {
text: string({ description: "Note text", maxLength: 20000, required: true }),
starred: boolean({ description: "Whether the user starred the note", indexed: true }),
photo: fileRef({ description: "A photo attached to the note" }),
title: string({ description: "A short title for the note", maxLength: 200 }),
},
}),
},
});
Publish it and generate the types:
npx phibac deploy
npx phibac generate
Previewing 1 collection for app app_01M7E9YEJZZSYKAAB14AMBBJPR on http://localhost:8787
com.example.notes.note additive (will become version 2.0)
published com.example.notes.note version 2.0
Published 1 collection.
Wrote src/pb-types.ts (1 collection: com.example.notes.note@2).
The preview says additive here too: it means the version can be published. A new major version starts at minor 0, and its fields can be anything. The rules for numbers: the first version of a collection is 1, and the next major version is always the latest plus one, never more.
src/pb-types.ts now describes version 2, under a new name:
// Generated from published collection schemas. Do not edit by hand.
/** A note written by the user */
export interface ComExampleNotesNoteV2 {
/** A photo attached to the note */
photo?: string;
/** Whether the user starred the note */
starred?: boolean;
/** Note text */
text: string;
/** A short title for the note */
title?: string;
}
export const SCHEMA_MAJORS = {
"com.example.notes.note": 2,
} as const;
Update src/main.ts to match: import ComExampleNotesNoteV2 as Note instead of ComExampleNotesNoteV1 as Note, and use starred wherever the code used pinned. In the file from Upload and show files, those are { text, pinned: notePinned.checked } in the form handler, which becomes { text, starred: notePinned.checked }, and where("pinned", "==", true), which becomes where("starred", "==", true). Keep passing SCHEMA_MAJORS to connect(): it makes your app write version 2 from now on.
6. Handle the records written with version 1
No published schema version is ever deleted: version 1 stays published, and a record keeps the major version it was written with until an update moves it to another. Publishing never deletes records either: npx phibac deploy changes schemas only. Your existing notes are still version 1 notes, with pinned and no starred. What that means for your app:
- A collection handle without
versionsreturns records of every major version.backend.collection<Note>("com.example.notes.note")gives you the old notes too, even thoughNoteis now the version 2 type. To get only version 2 records, open it withbackend.collection<Note>("com.example.notes.note", { versions: [2] }). - Updating an old record checks it against version 2. Because your app passes
SCHEMA_MAJORS, an update is checked against version 2 and moves the record to version 2. An old note still haspinned, which version 2 does not have, so an update that leaves it in place is refused withschema_violation(unknown field). Set the removed field tonullin the same update to remove it. - Other apps that read your collection list the major versions they understand, as in Read another app's data. An app that lists only version 1 keeps seeing the records that are still version 1, and no longer sees a record once you move it to version 2.
To move every old note to version 2, add this file next to src/main.ts and call await upgradeNotes(backend) once, after connect() has returned:
import type { Backend } from "@phibac/sdk";
import type { ComExampleNotesNoteV2 as Note } from "./pb-types";
// A note as version 1 stored it. phibac generate writes types only for the version in pb.config.ts.
interface NoteV1 {
text: string;
pinned?: boolean;
photo?: string;
title?: string;
}
// Far more notes than one user will ever have, so none is left out.
const ALL = 1_000_000;
// Moves every version 1 note to version 2: starred takes the value of pinned, and pinned is removed.
export async function upgradeNotes(backend: Backend): Promise<number> {
const old = await backend.collection<NoteV1>("com.example.notes.note", { versions: [1] }).orderBy("createdAt").limit(ALL).get();
const notes = backend.collection<Note>("com.example.notes.note");
for (const record of old) {
// null removes a field. The cast is needed because the generated type has no pinned field.
const patch: Record<string, unknown> = { pinned: null };
if (record.data.pinned !== undefined) patch.starred = record.data.pinned;
await notes.update(record.rkey, patch as Partial<Note>);
}
return old.length;
}
The updates are queued like any other write: each note moves to version 2 when the server has the change. The replaced version 1 of each note stays in the record's history for 30 days, where the user can restore it.
What you should see
- The additive change:
npx phibac deployprintsadditive (will become version 1.2)(or another minor number) and publishes. Run it again and it printssame (version 1.2, nothing to publish). - The rename in version 1:
npx phibac deployprintsbreakingwithfield removed: pinned, publishes nothing and exits with code 1. - With
version: 2:npx phibac deploypublishes version 2.0, andsrc/pb-types.tshasComExampleNotesNoteV2withstarred. - After
upgradeNotes(backend), a query withversions: [2]returns your old notes withstarredset wherepinnedwas, and nopinnedfield.
Common problems
npx phibac deployprintsbreaking(the server's code isschema_incompatible). The change needs the next major version. Undo the change, or raise that collection'sversionby one, asnpx phibac deploysuggests.invalid_requestsaying a version "skips ahead". The next major version must be the latest plus one. Setversionto the number the hint gives.invalid_requestsaying the collection "is new, so its version must be 1". This server has no version of the collection yet, for example after you reset your local data or on another server. Publish version 1 first.- An update fails with
schema_violationandunknown field(throughonConflict, if it was queued). The record was written with an older major version and still has a field the new one removed. Set that field tonullin the update. version_unsupported. A write, a query or aversionslist names a major version that was never published. Use one that is, and runnpx phibac generateafter everynpx phibac deploy.- TypeScript says
./pb-typeshas no exported memberComExampleNotesNoteV1.npx phibac generatenow writes the version 2 type. ImportComExampleNotesNoteV2instead. - You published a major version you did not want. It stays published: no published schema version is ever deleted. Set
versionback to the major version you want to keep using; your app writes the version inSCHEMA_MAJORS, and you can still publish additive changes to that version.
Next step
Put your app on the internet publishes these collections, both major versions, on the real server and puts the notes app online. For more about the local server you have used so far, see Develop on your own machine.