Extract generated code to method

This commit is contained in:
Abitofevrything 2022-11-05 20:34:55 +01:00
parent 897f8c10ad
commit cb1389f272
2 changed files with 47 additions and 14 deletions

View File

@ -246,6 +246,34 @@ class GeneratedColumn<T extends Object> extends Column<T> {
return const VerificationResult.success(); 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<SqlDialect, String> 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. /// A [GeneratedColumn] with a type converter attached to it.

View File

@ -53,23 +53,28 @@ abstract class TableOrViewWriter {
} else if (constraints.values.any((constraint) => constraint.isNotEmpty)) { } else if (constraints.values.any((constraint) => constraint.isNotEmpty)) {
// Use the default constraints supported by drift // Use the default constraints supported by drift
if (constraints.values.any(
(value) => value != constraints.values.first,
)) {
// One or more constraints are different depending on dialect, generate
// per-dialect constraints
final literalEntries = [ final literalEntries = [
for (final entry in constraints.entries) for (final entry in constraints.entries)
'SqlDialect.${entry.key.name}: ${asDartLiteral(entry.value)},', 'SqlDialect.${entry.key.name}: ${asDartLiteral(entry.value)},',
]; ];
additionalParams['defaultConstraints'] = '''(context) { additionalParams['defaultConstraints'] =
const dialectConstraints = { 'GeneratedColumn.constraintsDependsOnDialect({${literalEntries.join('\n')}})';
${literalEntries.join('\n')} } else {
}; // Constraints are the same regardless of dialect, only generate one set
// of them
final constraints = dialectConstraints[context.dialect]!; final constraint = asDartLiteral(constraints.values.first);
if (constraints.isEmpty) {
return; additionalParams['defaultConstraints'] =
'GeneratedColumn.constraintIsAlways($constraint)';
} }
context.buffer..write(' ')..write(constraints);
}''';
} }
if (column.defaultArgument != null) { if (column.defaultArgument != null) {