createImplicitManyToManyTableStatement method
Returns a join-table creation statement for storage.
Implementation
String createImplicitManyToManyTableStatement(
ImplicitManyToManyStorageDefinition storage,
) {
final sourceKeyFields = storage.sourceKeyFields
.map((fieldName) => storage.sourceModel.findField(fieldName))
.toList(growable: false);
final targetKeyFields = storage.targetKeyFields
.map((fieldName) => storage.targetModel.findField(fieldName))
.toList(growable: false);
if (sourceKeyFields.any((field) => field == null) ||
targetKeyFields.any((field) => field == null)) {
throw StateError(
'Unable to resolve key fields for implicit many-to-many table ${storage.tableName}.',
);
}
final sourceColumns = <String>[];
for (var index = 0; index < sourceKeyFields.length; index++) {
sourceColumns.add(
'${_quoteIdentifier(storage.sourceJoinColumns[index])} ${postgresTypeForField(sourceKeyFields[index]!)}',
);
}
final targetColumns = <String>[];
for (var index = 0; index < targetKeyFields.length; index++) {
targetColumns.add(
'${_quoteIdentifier(storage.targetJoinColumns[index])} ${postgresTypeForField(targetKeyFields[index]!)}',
);
}
final primaryKeyColumns = [
...storage.sourceJoinColumns,
...storage.targetJoinColumns,
].map(_quoteIdentifier).join(', ');
final sourceJoinColumns = storage.sourceJoinColumns
.map(_quoteIdentifier)
.join(', ');
final sourceTargetColumns = sourceKeyFields
.map((field) => _quoteIdentifier(field!.databaseName))
.join(', ');
final targetJoinColumns = storage.targetJoinColumns
.map(_quoteIdentifier)
.join(', ');
final targetTargetColumns = targetKeyFields
.map((field) => _quoteIdentifier(field!.databaseName))
.join(', ');
return 'CREATE TABLE IF NOT EXISTS ${_quoteIdentifier(storage.tableName)} ('
'${[...sourceColumns, ...targetColumns].join(', ')}, '
'PRIMARY KEY ($primaryKeyColumns), '
'CONSTRAINT ${_quoteIdentifier('${storage.tableName}_source_fkey')} '
'FOREIGN KEY ($sourceJoinColumns) '
'REFERENCES ${_quoteIdentifier(storage.sourceModel.databaseName)} ($sourceTargetColumns) '
'ON DELETE CASCADE ON UPDATE CASCADE, '
'CONSTRAINT ${_quoteIdentifier('${storage.tableName}_target_fkey')} '
'FOREIGN KEY ($targetJoinColumns) '
'REFERENCES ${_quoteIdentifier(storage.targetModel.databaseName)} ($targetTargetColumns) '
'ON DELETE CASCADE ON UPDATE CASCADE'
')';
}