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
final literalEntries = [ if (constraints.values.any(
for (final entry in constraints.entries) (value) => value != constraints.values.first,
'SqlDialect.${entry.key.name}: ${asDartLiteral(entry.value)},', )) {
]; // One or more constraints are different depending on dialect, generate
// per-dialect constraints
additionalParams['defaultConstraints'] = '''(context) { final literalEntries = [
const dialectConstraints = { for (final entry in constraints.entries)
${literalEntries.join('\n')} 'SqlDialect.${entry.key.name}: ${asDartLiteral(entry.value)},',
}; ];
final constraints = dialectConstraints[context.dialect]!; additionalParams['defaultConstraints'] =
if (constraints.isEmpty) { 'GeneratedColumn.constraintsDependsOnDialect({${literalEntries.join('\n')}})';
return; } 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) { if (column.defaultArgument != null) {