findFieldsReferencedTablesImpl method

  1. @override
Future<Map<String, TableFieldReference>> findFieldsReferencedTablesImpl(
  1. PostgreSQLConnectionWrapper connection,
  2. String table
)
override

Finds the foreign keys of table, with connection: the referenced table (and field) of each referencing field, by the field name.

Implemented by the adapters that introspect their schema (see listTablesNamesImpl). Default: throws UnsupportedError.

Implementation

@override
Future<Map<String, TableFieldReference>> findFieldsReferencedTablesImpl(
  PostgreSQLConnectionWrapper connection,
  String table,
) async {
  var sql = findFieldsReferencedTablesSQL(table);

  var referenceFields = await connection.mappedResultsQuery(sql);

  var map = Map<String, TableFieldReference>.fromEntries(
    referenceFields.map((e) {
      var sourceTable = e['source_table'] as String?;
      var sourceField = e['source_column'] as String?;
      var sourceFieldDataType = e['source_column_type'] as String?;
      var targetTable = e['target_table'] as String?;
      var targetField = e['target_column'] as String?;
      var targetFieldDataType = e['target_column_type'] as String?;
      var fkIndexName = e['fk_index_name'] as String?;

      if (sourceTable == null ||
          sourceField == null ||
          targetTable == null ||
          targetField == null) {
        return null;
      }

      if (fkIndexName != null && fkIndexName.isEmpty) {
        fkIndexName = null;
      }

      var sourceFieldType = sourceFieldDataType != null
          ? _toFieldType(sourceFieldDataType)
          : String;

      var targetFieldType = targetFieldDataType != null
          ? _toFieldType(targetFieldDataType)
          : String;

      var reference = TableFieldReference(
        sourceTable,
        sourceField,
        sourceFieldType,
        targetTable,
        targetField,
        targetFieldType,
        indexName: fkIndexName,
      );

      return MapEntry<String, TableFieldReference>(sourceField, reference);
    }).nonNulls,
  );

  return map;
}