initializeForeignKeys method

Future<bool> initializeForeignKeys()

CHECK FOREIGN KEYS

Implementation

Future<bool> initializeForeignKeys() async {
  // {id: 0, seq: 0, table: Employee, from: SupportRepId, to: EmployeeId, on_update: NO ACTION, on_delete: NO ACTION, match: NONE}
  // ALTER TABLE child ADD CONSTRAINT fk_child_parent FOREIGN KEY (parent_id) REFERENCES parent(id);
  // FOREIGN KEY(column_name) REFERENCES parent_table_name(reference_to)
  final alterTableQuery = <String>[];
  for (final table in databaseTables!) {
    final rfields =
        table.fields!.whereType<SqfEntityFieldRelationshipBase>().toList();
    if (rfields.isNotEmpty) {
      final fKeys =
          await SqfEntityProvider(this).getForeignKeys(table.tableName!);
      for (final rfield in rfields) {
        final fkeyExist = fKeys.isEmpty
            ? null
            : fKeys.singleWhere((f) => f['from'] == rfield.fieldName);
        if (fkeyExist == null) {
          final String? tableName = rfield.table == null
              ? table.tableName
              : rfield.table!.tableName;
          final String? primaryKey = rfield.table == null
              ? table.primaryKeyName
              : rfield.table!.primaryKeyName;
          alterTableQuery.add(
              'ALTER TABLE ${table.tableName} ADD CONSTRAINT fk_${table.tableName}_${rfield.fieldName} FOREIGN KEY (${rfield.fieldName}) REFERENCES $tableName($primaryKey) ON DELETE ${rfield.deleteRule.toString().replaceAll('_VALUE', '').replaceAll('_', ' ').replaceAll('DeleteRule.', '')}');
        }
      }
    }
  }
  if (alterTableQuery.isNotEmpty) {
    print('SQFENTITIY: alterTableIndexesQuery => $alterTableQuery');
    await SqfEntityProvider(this).execSQLList(alterTableQuery);
  }
  return true;
}