Skip to content

Commit

Permalink
Add numeric type check for 'id' column in PostgreSQL sequence fix
Browse files Browse the repository at this point in the history
  • Loading branch information
almontasser authored Nov 13, 2024
1 parent 393935c commit e17363c
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions database/seeders/DatabaseSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,15 @@ function fixPostgresSequence()
$tables = \DB::select('SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\' ORDER BY table_name;');
foreach ($tables as $table) {
if (\Schema::hasColumn($table->table_name, 'id')) {
$seq = \DB::table($table->table_name)->max('id') + 1;
\DB::select('SELECT setval(pg_get_serial_sequence(\'' . $table->table_name . '\', \'id\'), coalesce(' . $seq . ',1), false) FROM ' . $table->table_name);
$columnType = \DB::select("SELECT data_type FROM information_schema.columns WHERE table_name = '{$table->table_name}' AND column_name = 'id'")[0]->data_type;
// Only proceed if the 'id' column is numeric
if (in_array($columnType, ['integer', 'bigint', 'smallint', 'smallserial', 'serial', 'bigserial'])) {
$seq = \DB::table($table->table_name)->max('id') + 1;
\DB::select('SELECT setval(pg_get_serial_sequence(\'' . $table->table_name . '\', \'id\'), coalesce(' . $seq . ',1), false) FROM ' . $table->table_name);
}
}
}
}
}
}

0 comments on commit e17363c

Please sign in to comment.