simolus3 / drift

Drift is an easy to use, reactive, typesafe persistence library for Dart & Flutter.
https://drift.simonbinder.eu/
MIT License
2.67k stars 372 forks source link

Fix column references in versioned schema code #3259

Closed simolus3 closed 1 month ago

simolus3 commented 1 month ago

When a column is defined like this:

  DateTimeColumn get creationTime => dateTime()
    .check(creationTime.isBiggerThan(Constant(DateTime(2020))))
    .withDefault(Constant(DateTime(2024, 1, 1)))();

Our generated code relies on the fact that creationTime as a getter is in scope for the copied check code (it is because we're generating columns in table classes). With versioned schemas however, we have an optimization that tries to not re-generate column code if it hasn't changed between different schema versions. With this generation mode, columns are no longer in scope for check constraints.

This fix relies on detecting columns in Dart code (so we see that the creationTime reference in check references a column) and then rewriting these expressions with a CustomExpression when generating code:

i1.GeneratedColumn<DateTime> _column_18(String aliasedName) =>
    i1.GeneratedColumn<DateTime>('birthday', aliasedName, true,
        check: () =>
            i2.ComparableExpr((i0.VersionedTable.col<DateTime>('birthday')))
                .isBiggerThan(i2.Constant(DateTime(1900))),
        type: i1.DriftSqlType.dateTime);

Closes https://github.com/simolus3/drift/issues/3219

github-actions[bot] commented 1 month ago

🚀 Deployed on https://deploy-preview-3259--moor.netlify.app