Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove explicit values from seeders incrementing column #9

Closed
wants to merge 1 commit into from

Conversation

bobbyiliev
Copy link
Collaborator

Fixes the following error:

[2021-05-27 18:25:07] local.ERROR: SQLSTATE[23505]: **Unique violation: 7 ERROR:  duplicate key value violates unique constraint "menus_pkey"**
DETAIL:  Key (id)=(3) already exists. (SQL: insert into "menus" ("name", "updated_at", "created_at") values (sidebar, 2021-05-27 18:25:07, 2021-05-27 18:25:07) returning "id") {"userId":1,"exception":"[object] (Illuminate\\Database\\QueryException(code: 23505): SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"menus_pkey\"

Only affecting PostgreSQL.

Seems like when you explicitly assign a value to the incrementing column PostgreSQL does not register this in the next sequence causing the duplicate key value violates unique constraint error. By leaving it out, everything works properly.

@bobbyiliev bobbyiliev requested a review from tnylea May 27, 2021 20:12
@7Skiez
Copy link

7Skiez commented May 28, 2021

You could just run this instead and it would fix the sequence, No need to edit the seeders.

if (config('database.default') === 'pgsql') {
   $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);
      }
   }
}

Check out 49421bc I put the code in a method inside global helper and called it at the end of database seeder.
Could even address the primary key instead of 'id' to automatically fix all tables, Though I'm not sure if that's necessary here.

@bobbyiliev
Copy link
Collaborator Author

Hi @7Skiez,

Ah yes very good point. I like your fix better! Will close this PR then!

@bobbyiliev bobbyiliev closed this May 28, 2021
@bobbyiliev bobbyiliev deleted the bugfix/seedersViolateUiqueConstraint branch January 27, 2023 10:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants