Custom migrations
¶
Write a migration for a change that needs custom logic.
The change being applied determines which context the migration receives.
Migration contexts¶
- class lamindb_setup.evolve.MigrationContext(feature, desired_dtype, live_dtype, target_registry=None, cat_filters=None, report=<factory>)¶
What a
DataMigrationcallable receives when it runs.featureis the live LaminDBFeaturerecord, already flipped todesired_dtypeby the engine (the dtype write must precede any categorical value write; the stale scalar rows survive the flip and remain readable). The callable relocates / rewrites the feature’s stored values so they validate againstdesired_dtype, then returns; it runs inside the apply transaction, so raising rolls the whole apply back.target_registryandcat_filtersare the plan’s resolved target: the live registry class the new dtype points at (e.g.ln.Record,bt.CellType) and the filters narrowing it (e.g.{"type__uid": ...}). The engine resolves both from the plan feature’s declaredLaminDType, which is the only place they survive intact –desired_dtypeis a string, and no registry-name to class resolver exists. Both areNonefor a scalar target.reportcollects per-value outcomes for the plan preview (seeMigrationReport).-
target_registry:
Any= None¶
-
cat_filters:
dict[str,Any] |None= None¶
-
target_registry:
- class lamindb_setup.evolve.DeclarationTarget(kind, answers, by_key=False)¶
One kind of target a
DataMigrationcan be declared for.A plan object of
kind–"Feature","Schema","Sheet"or"Record"– or, withby_key, the natural key of one whose leaf is of that kind: the only way to address an object the plan no longer declares. A natural key may stand in for an object target too, since the engine looks every declaration up by key – that is how a schema no plan manages, one a deleted feature is detached from, is answered for.answerssays what a declaration attached there answers for, which is what an error naming a misplaced declaration explains.-
by_key:
bool= False¶
- describe()¶
a Schema (...)orthe natural key of a Feature (...).- Return type:
str
-
by_key:
- class lamindb_setup.evolve.MemberMigrationContext(schema, features, report=<factory>, accepted_nulls=<factory>, *, rows_omitting)¶
What a
DataMigrationattached to a schema receives.The counterpart of
MigrationContextfor the other narrowing a plan can declare a migration for: making an optional schema member required again. Nothing about a feature’s dtype changes; what has to be fixed up is the rows that omitted the member, since those are what the block exists to protect.schemais the live LaminDBSchema, its optional set already narrowed by the engine, andfeaturesare the live members it no longer marks optional. The callable annotates every row that lacks one of them –missing()enumerates exactly those – and returns; the engine then re-counts them and fails the apply if any is left, so a partial backfill rolls back rather than silently invalidating records.A row backfilled with null is the one exception. lamindb has no stored null –
add_valuesskips aNone, a categorical value is a foreign key, and both JSON stores areNOT NULLcolumns – so an un-annotated row is a null one, whatever the member’s dtype. A migration that filled a row with null says so withaccept_null(), which exempts that row from the re-count; a row merely left alone is not exempted and still fails the apply.reportcollects per-row outcomes for the plan preview (seeMigrationReport).rows_omittingis the engine’s query behindmissing(), supplied by whoever constructs the context.- accept_null(feature, row)¶
Declare that
rowdeliberately holds no value forfeature.Recorded per
(feature, row)rather than per feature, because a backfill may fill some rows with a real value and leave only the rest null; only the rows named here are exempted from the engine’s re-count.- Return type:
None
- missing(feature)¶
The rows validated by
schemathat carry no value forfeature.Spans every registry a schema validates rows of (
Record,Artifact,Collection) and every composite schema that embeds this one, matching what the engine counts when it checks the backfill succeeded.- Return type:
list[Any]
- class lamindb_setup.evolve.MemberRemovalContext(schema, features, report=<factory>, kept=<factory>, *, rows_carrying)¶
What a
DataMigrationattached to a schema losing a member receives.The third narrowing a plan can declare a migration for. Removing a member changes nothing about the rows themselves – it is the schema that stops declaring the feature – so what has to be answered for is the values already stored for it, which no longer belong to anything the schema describes.
schemais the live LaminDBSchema, the member already unlinked by the engine, andfeaturesare the live features it no longer declares. The callable clears the values those members hold on the rows the schema validates –carrying()enumerates exactly those – and returns; the engine then re-counts them and fails the apply if any is left.A migration that deliberately keeps the values (they stay on the rows as undeclared extra data) is exempt from that re-count; it says so with
DataMigration(keeps_values=True), whichkeep_member_values()sets.reportcollects per-row outcomes for the plan preview (seeMigrationReport).rows_carryingis the engine’s query behindcarrying(), supplied by whoever constructs the context.- keep(feature)¶
Declare that
feature’s stored values are deliberately left in place.Exempts it from the post-check that otherwise requires a removed member’s values to be gone. Stated per member rather than per migration because the declarations are not matched to members: a schema dropping two of them may keep one and delete the other.
- Return type:
None
- carrying(feature)¶
The rows validated by
schemathat hold a value forfeature.The exact complement of
MemberMigrationContext.missing(), over the same registries (Record,Artifact,Collection) and the same composite closure, and what the engine re-counts to check the drop succeeded.- Return type:
list[Any]
- class lamindb_setup.evolve.IndexChangeContext(schema, previous, index, report=<factory>)¶
What a
DataMigrationattached to a schema whose index changes receives.The fifth narrowing a plan can declare a migration for, and the only one with nothing to rewrite.
Schema.indexmarks which member identifies a row, so adding, changing or removing it changes how every dataset the schema already validated would be curated now – and that cannot be re-checked in place. The declaration is the plan author vouching that the data conforms (seeaccept_index_change()).schemais the live LaminDBSchema, its index already switched by the engine.previousandindexare the live index features before and after, either of which isNonewhen the schema had, respectively has, no index. It runs inside the apply transaction, like the member narrowings.reportcollects notes for the diff (seeMigrationReport).
- class lamindb_setup.evolve.FlexibleChangeContext(schema, previous, flexible, report=<factory>, *, recorded_nonmembers)¶
What a
DataMigrationattached to a schema turningflexibleoff receives.While
flexiblewas on, curating a dataset against the schema also validated and annotated every column whose name matched a registered feature: each such column is listed among the columns the artifact records for the slot, and a categorical one carries label links. Turning the flag off changes none of that. Undermaximal_set=Trueit is refused as well, since a dataset carrying such a column would no longer validate.Two declarations answer for it:
accept_flexible_change()keeps the annotations and, on amaximal_setschema, vouches for the data;drop_nonmember_annotations()removes them.schemais the live LaminDBSchema, its flag already switched;previousandflexibleare the values before and after.nonmember_columns()lists what is left to answer for. It runs inside the apply transaction, like the member narrowings.reportcollects notes for the diff (seeMigrationReport).recorded_nonmembersis the engine’s query behindnonmember_columns(), supplied by whoever constructs the context.- nonmember_columns()¶
Every artifact slot
schemacurated whose recorded columns it does not declare.One entry per artifact and slot –
columnsfor a dataframe the schema validated itself, else the composite’s slot – with theartifact, theslot, thelinkrow recording its columns, therecordedschema that row points at and the non-memberfeaturesit lists. Trashed artifacts are left out.- Return type:
list[Any]
- class lamindb_setup.evolve.FeatureRemovalContext(feature, report=<factory>)¶
What a
DataMigrationattached to a deleted feature receives.The plan has stopped declaring the feature altogether, so the removal pass is about to move it to the trash. Trashing detaches nothing: the values stay keyed to it, invisible to every query that goes through a live feature, while
get_values()still reports them by name – and a feature of the same name declared later is a different record, so the history splits in two.featureis the live LaminDBFeature, still on its branch: the migration runs before the deletion, so everything it reads is still there. Only the two attributesclear_values()needs, which is what letsdrop_values()serve this case unchanged.Declared by natural key, since there is no plan object left to name:
ctx.migrate("FeatureType:ft/Feature:retired", drop_values())
- class lamindb_setup.evolve.RecordTypeRemovalContext(record_type, report=<factory>, *, live_rows)¶
What a
DataMigrationattached to a deleted record type receives.The plan has stopped declaring a
RecordTypeorSheetthat still has records – a sheet’s rows, a vocabulary’s values – and lamindb’s trash cascades to every one of them. The removal is refused until the plan says what should become of them, declared by natural key like a deleted feature:ctx.migrate("Sheet:Experiments", drop_rows())
record_typeis the live record type, still on its branch: the migration runs before the deletion.rows()lists its records that are not in the trash, sub-types left out.- rows()¶
The records typed by
record_typethat are not in the trash.- Return type:
Any
- class lamindb_setup.evolve.SchemaRemovalContext(schema, report=<factory>)¶
What a
DataMigrationattached to a deleted schema receives.The plan has stopped declaring a schema that artifacts or collections were validated against. Trashing it leaves them pointing at a trashed schema, which no longer describes them for anyone querying live schemas, so the removal is refused until the plan vouches for that:
ctx.migrate("Schema:Legacy", keep_validated(reason="superseded by v2"))
schemais the live schema, still on its branch.
- class lamindb_setup.evolve.SheetExportContext(schema, exports, report=<factory>, written=<factory>, promotions=<factory>, branch_factory=None, _branch=None, *, reexport, current_branch)¶
Context for rewriting stale sheet exports after a schema migration.
The fourth narrowing a plan can declare a migration for, and the only one whose subject is not stored in the database. A sheet export is a CSV already written to storage. Renaming or retyping a member, or adding a required one, leaves the file describing the previous schema even though its
schemaforeign key points to the updated schema.schemais the live LaminDBSchema, already reconciled to the plan, andexportsthe snapshots the change invalidated – each naming its sheet, the artifact at the head of its version family, and why it no longer adheres.write()produces the new version.Two things set this context apart from the other three, and a hand-written migration has to respect both:
It runs after the apply transaction has committed. A file write cannot be rolled back with the database, so raising here does not undo the schema change – it leaves
branchunmerged and fails the command.Everything it creates lands on :attr:`branch`, a branch merged into the instance only once every declared migration succeeded. Write through
write()(or passbranch=self.branchyourself), or the new version becomes visible before the run that produced it is known to be good.
branchis created on first access rather than up front, so a migration that writes nothing –keep_stale_exports(), or a hand-written one that decides against it – leaves no empty branch behind (lamindb never deletes them).reportcollects per-export outcomes for the diff (seeMigrationReport).reexportandcurrent_branchare the engine operations behindwrite(), supplied by whoever constructs the context.-
branch_factory:
Callable[[],Any] |None= None¶
- property branch: Any¶
The branch new export versions are written onto, created on demand.
- write(export)¶
Write a new version of
exportfrom the sheet’s current rows.Returns the saved artifact, which is the existing one when the rows hash to the content already stored – lamindb deduplicates by hash, so an export that did not actually change gains no version, and nothing is recorded in
written. That is the property a declaration relies on to be safe to leave in a plan forever.The same deduplication has two failure modes, because its lookup is scoped by neither key, branch, nor
is_latest: :rtype:Anyit can resolve onto a version an earlier, failed run parked on another re-export branch – same content, stranded where the merge cannot reach it. That one is adopted onto this run’s branch.
it can resolve onto a superseded version of the family, when the rows happen to render exactly what some older export holds (a schema change and its revert, say). Nothing promotes that row, so the head would keep its stale content while this reported a re-export. The family already holds the right bytes, so the fix is to re-point it – recorded in
promotionsand applied after the merge, since it touches the instance’s own branch and must not become visible before the run succeeds.
An artifact already on the instance’s own branch is otherwise left alone. Moving it here would take a live artifact off the branch every query sees, to hand it back at the merge – and to hide it permanently if this run failed in between. A file write that cannot be rolled back must never be able to remove something that was already there.
- class lamindb_setup.evolve.RecordUpdateContext(record, values=<factory>, fields=<factory>, report=<factory>)¶
What a
DataMigrationattached to a seeded record receives.A plan seeds its records. To apply edits to an existing record, declare an update:
ctx.migrate(record, update_record())
recordis the live record.valuesmaps each liveFeaturewhose stored value differs from the one the plan declares to that declared value, andfieldseach descriptive attribute that differs to the plan’s. Only what the plan declares is compared: a feature it leaves out, or declares asNone, keeps its stored value.
- class lamindb_setup.evolve.RecordRemovalContext(record, relocate_to=None, report=<factory>, *, value_links)¶
What a
DataMigrationdeclared for a record the plan drops receives.A seeded record the plan stops declaring stays on the instance. Declaring its removal by natural key moves it to the trash, which is refused while other objects still hold it as a categorical value:
ctx.migrate("RecordType:Vocabulary/Record:obsolete", drop_record())
recordis the live record, still live: the migration runs before it is trashed.relocate_tois the live record its annotations move onto, orNone.links()lists the link rows that still namerecordas their value, one queryset per link table.-
relocate_to:
Any= None¶
- links()¶
The link rows naming
recordas their value, per link table.- Return type:
list[Any]
-
relocate_to:
Migration helpers¶
- lamindb_setup.evolve.backfill_members(context, /, value=DEFAULT, *, feature=None)¶
Annotate every row that omits one of the schema’s newly-required members.
valueis either the value to write for every such row, or a callable receiving(feature, row)and returning one – returningNoneleaves the row alone, which then fails the apply, since the engine requires the backfill to cover every row.Two sentinels stand for a value the feature defines rather than the declaration, and either may equally be returned from the callable, so a backfill can decide row by row: :rtype:
NoneDEFAULT(the default) fills the row with the member’sdefault_value, falling back to null when it declares none – the same order lamindb’s ownDataFrameCurator.standardize()fills a missing column in. One declaration therefore covers members of different dtypes.NULLfills the row with null.
Both are refused for a member that is not nullable and defines no default, since a null there would not validate. A null is not written: lamindb has no stored null –
add_valuesskips one, a categorical value is a foreign key, and the JSON stores areNOT NULL– so an un-annotated row is what a null member looks like, whatever its dtype. The row is instead declared settled withaccept_null(), which is what exempts it from the engine’s post-check; a row merely left alone (the callable returningNone) still fails the apply.featurenarrows this to the member of that name, so a schema narrowing several members can take one declaration per member (with a value of the right dtype for each) instead of one callable branching on the feature. A name that is not among the newly-required members is a no-op, which is what keeps such a declaration idempotent once its member has been settled.The write deliberately bypasses
add_values: that re-curates the whole row against its type’s schema, which a backfill by definition cannot satisfy yet – it is running precisely because the row does not, and a row missing two required members would have its first repair rejected for still missing the second. One annotation is one row in the feature’s value table, so it is written there directly.
- lamindb_setup.evolve.clear_values(context, /)¶
Delete every value stored for the feature, scalar and categorical alike.
The blunt instrument for a change no mapping can express: the feature keeps its identity and its new dtype but starts out unannotated. Serves the feature’s deletion too (see
FeatureRemovalContext), where the point is that nothing is left keyed to a record about to be trashed.- Return type:
None
- lamindb_setup.evolve.clear_member_values(context, /, *, feature=None)¶
Delete the values a schema’s removed members hold on the rows it validates.
featurenarrows this to the member of that name, so a schema dropping several members can take one declaration per member. A name that is not among the removed members is a no-op, which is what keeps such a declaration idempotent once its member is gone.Only the rows this schema validates are touched (see
carrying()). The same feature may hold values on rows some other schema validates, and those are that schema’s business – deleting them here would invalidate it.A value row annotating several objects at once (
JsonValue, shared across the artifacts and runs it is linked to) is only unlinked from the objects in scope; the row survives for the rest. Every other store holds one annotation per row, so there the row itself goes.- Return type:
None
- lamindb_setup.evolve.clear_nonmember_annotations(context, /)¶
Remove what the flexible match annotated on the artifacts a schema curated.
Brings every artifact
nonmember_columns()lists to what curating it against the schema withflexibleoff records: :rtype:Nonethe slot’s recorded columns are re-pointed to a schema of the member columns alone – the live one lamindb keeps for that content, or a new one, built as lamindb’s own
annotate_artifactbuilds it. A slot left with no column loses its record. The schema it recorded before is not edited, since other artifacts may record it too.the label links of the non-member features are deleted, unless the artifact still records the feature in another slot or a schema it is validated against declares it: that annotation is not the flexible match’s.
Scalar values are left alone: curation writes none for a slot’s columns, so any stored there were annotated some other way.
- lamindb_setup.evolve.relocate_to_records(context, /, *, mapping=None, transform=None, standardize=False, field=None, element_wise=False)¶
Relocate a feature’s scalar values onto existing records (
str->cat).Reads every stored scalar value (both stores), resolves each distinct one to a record of the plan’s target registry, then rewrites the annotations onto the categorical store. See the module docstring for the resolution chain and for why targets must already exist.
fieldoverrides the field records are matched on (defaulting to the registry’s name field);standardizeadditionally resolves synonyms before a value is considered unmatched.element_wisemaps each element of a stored list onto a record, for alist[cat[...]]target (list[str] -> list[cat[...]]); a single value is mapped as a list of one.mapping/transformmay answer withNULLorDEFAULTfor a nullable feature, which leaves the row un-annotated – lamindb’s way of spelling a null – rather than mapping it onto a record.- Return type:
None
- lamindb_setup.evolve.relocate_to_str(context, /, *, mapping=None, transform=None, field=None)¶
Relocate a feature’s categorical values to strings (
cat->str).Renders each linked label as text (its name field, or
field) and rewrites the annotation into the scalar store. Every label renders, so no value is ever unmatched:mappingandtransformare pure rewrites here, andNonestill drops the annotation, whileNULL/DEFAULTnull it out / substitute the feature’s default.- Return type:
None
- lamindb_setup.evolve.rewrite_values(context, /, *, mapping=None, transform=None, element_wise=False)¶
Rewrite a feature’s scalar values for a narrowed scalar dtype.
Each distinct value is coerced to the target dtype; one that will not coerce goes through
mapping/transformexactly as elsewhere, sotransform=lambda _: Nonedrops the offending values,transform=lambda _: 0replaces them, andtransform=lambda _: NULLnulls them out.element_wisecoerces each element of a list to alist[...]target’s element dtype instead (list[str] -> list[int]); a single value becomes a list of one, and an element answered withNoneis left out of its list.- Return type:
None