createForeignKeys method

Future<SqlDatabaseResult?> createForeignKeys(
  1. DatabaseDriver conn
)

Creates foreign key constraints for the table. Generates and executes ALTER TABLE statements to add foreign key constraints defined in the table's foreign keys collection. Each constraint is given a unique name using the current timestamp. Parameters:

  • conn - The active MySQL database connection Returns a MySqlResult if foreign keys exist and are created, or null if no foreign keys are defined. Example:
var result = await table.createForeignKeys(conn);
if (result?.success == true) {
  print('Foreign keys created successfully');
}

Implementation

Future<SqlDatabaseResult?> createForeignKeys(DatabaseDriver conn) async {
  if (foreignKeys.isEmpty) {
    return null;
  }
  String sql = 'ALTER TABLE `$name`\n';
  for (var i = 1; i <= foreignKeys.length; i++) {
    var fk = foreignKeys[i - 1];
    sql +=
        'ADD CONSTRAINT fk_${name}_${fk.name}_${DateTime.now().microsecondsSinceEpoch} ${fk.toSQL()}${i == foreignKeys.length ? ';\n' : ',\n'}';
  }
  return conn.executeString(sql);
}