The issue you're experiencing is because, when you rename a table in PostgreSQL using Laravel’s Schema::rename(), the table name itself is changed, but underlying dependencies like sequences (used for SERIAL/BIGSERIAL or identity-like columns) do not get renamed automatically. As a result, your new table (now stored_events) still references the original sequence: stored_events_migrated_id_seq.
Why?
Postgres sequences are independent database objects. When you create a table with an auto-incrementing primary key, Postgres creates a sequence e.g., stored_events_migrated_id_seq for stored_events_migrated, and the default value for the column references this sequence. Renaming the table does not rename its associated sequence or update the column's default.
Solution Steps
- Rename the Sequence
- Update the Table’s Default Reference
Example Migration
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
class RenameStoredEventsMigration extends Migration
{
public function up()
{
// 1. Rename tables
Schema::rename('stored_events', 'stored_events_bak');
Schema::rename('stored_events_migrated', 'stored_events');
// 2. Rename the sequence
DB::statement('ALTER SEQUENCE stored_events_migrated_id_seq RENAME TO stored_events_id_seq');
// 3. Update the default of the id column to use the new sequence
DB::statement("ALTER TABLE stored_events ALTER COLUMN id SET DEFAULT nextval('stored_events_id_seq')");
}
public function down()
{
// To reverse (example; adjust as needed)
DB::statement("ALTER TABLE stored_events ALTER COLUMN id SET DEFAULT nextval('stored_events_migrated_id_seq')");
DB::statement('ALTER SEQUENCE stored_events_id_seq RENAME TO stored_events_migrated_id_seq');
Schema::rename('stored_events', 'stored_events_migrated');
Schema::rename('stored_events_bak', 'stored_events');
}
}
Key Points:
- Renaming tables does not affect sequence names or column default values.
- Always manually handle sequence renames/references when renaming tables in PostgreSQL.
References:
Let me know if you need further clarification or help with this migration!