DEV Community

George Pamfilis
George Pamfilis

Posted on

Reset IDs postgresql database - snippet

I created a copy of a database so i can mutate the data and try things out. I was getting an error on insert.

sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely)
(psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "customers_pkey"
DETAIL: Key (id)=(14) already exists.

[SQL: INSERT INTO customers (user_id, first_name, last_name, email, phone_number) VALUES (%(user_id)s, %(first_name)s, %(last_name)s, %(email)s, %(phone_number)s) RETURNING customers.id]
[parameters: {'user_id': 1, 'first_name': 'myname', 'last_name': '', 'email': 'myemail', 'phone_number': ''}]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
Enter fullscreen mode Exit fullscreen mode

Here is a snippet that helped me out.

DO $$
DECLARE
    l_table RECORD;
    column_exists BOOLEAN;
BEGIN
    FOR l_table IN SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name != 'alembic_version'
    LOOP
        -- Check if 'id' column exists in the table
        SELECT EXISTS (
            SELECT FROM information_schema.columns 
            WHERE table_schema = 'public' 
            AND table_name = l_table.table_name 
            AND column_name = 'id'
        ) INTO column_exists;

        -- Log the table name and whether the 'id' column exists
        RAISE NOTICE 'Processing table: %, ID column exists: %', l_table.table_name, column_exists;

        -- If 'id' column exists, set the sequence value and log the action
        IF column_exists THEN
            EXECUTE FORMAT('SELECT setval(pg_catalog.quote_ident(''%s_id_seq''), COALESCE(MAX(id), 1)) FROM %I', l_table.table_name, l_table.table_name);
            RAISE NOTICE 'Sequence set for table: %', l_table.table_name;
        ELSE
            RAISE NOTICE 'No ID column for table: %', l_table.table_name;
        END IF;
    END LOOP;
END;
$$;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)