diff --git a/drift/lib/src/runtime/query_builder/schema/column_impl.dart b/drift/lib/src/runtime/query_builder/schema/column_impl.dart index afd5cd85..d6e9e4a4 100644 --- a/drift/lib/src/runtime/query_builder/schema/column_impl.dart +++ b/drift/lib/src/runtime/query_builder/schema/column_impl.dart @@ -246,6 +246,34 @@ class GeneratedColumn extends Column { return const VerificationResult.success(); }; } + + /// A helper method to make creating [defaultConstraints] simpler. Used when + /// the constraint does not depend on the dialect. + /// + /// Used by generated code. + static Function(GenerationContext) constraintIsAlways(String constraint) => + (context) => context.buffer + ..write(' ') + ..write(constraint); + + /// A helper method to make creating [defaultConstraints] simpler. Used when + /// the constraint depends on the dialect. + /// + /// Used by generated code. + static Function(GenerationContext) constraintsDependsOnDialect( + Map constraints, + ) => + (context) { + final constraint = constraints[context.dialect]; + + if (constraint == null || constraint.isEmpty) { + return; + } + + context.buffer + ..write(' ') + ..write(constraint); + }; } /// A [GeneratedColumn] with a type converter attached to it. diff --git a/drift_dev/lib/src/writer/tables/table_writer.dart b/drift_dev/lib/src/writer/tables/table_writer.dart index 674df90c..70d60ee7 100644 --- a/drift_dev/lib/src/writer/tables/table_writer.dart +++ b/drift_dev/lib/src/writer/tables/table_writer.dart @@ -53,23 +53,28 @@ abstract class TableOrViewWriter { } else if (constraints.values.any((constraint) => constraint.isNotEmpty)) { // Use the default constraints supported by drift - final literalEntries = [ - for (final entry in constraints.entries) - 'SqlDialect.${entry.key.name}: ${asDartLiteral(entry.value)},', - ]; + if (constraints.values.any( + (value) => value != constraints.values.first, + )) { + // One or more constraints are different depending on dialect, generate + // per-dialect constraints - additionalParams['defaultConstraints'] = '''(context) { - const dialectConstraints = { - ${literalEntries.join('\n')} - }; + final literalEntries = [ + for (final entry in constraints.entries) + 'SqlDialect.${entry.key.name}: ${asDartLiteral(entry.value)},', + ]; - final constraints = dialectConstraints[context.dialect]!; - if (constraints.isEmpty) { - return; - } + additionalParams['defaultConstraints'] = + 'GeneratedColumn.constraintsDependsOnDialect({${literalEntries.join('\n')}})'; + } else { + // Constraints are the same regardless of dialect, only generate one set + // of them - context.buffer..write(' ')..write(constraints); - }'''; + final constraint = asDartLiteral(constraints.values.first); + + additionalParams['defaultConstraints'] = + 'GeneratedColumn.constraintIsAlways($constraint)'; + } } if (column.defaultArgument != null) {