drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[BUG]: drizzle seed breaks serial sequence sync with Postgres serial type

Open kmate19 opened this issue 11 months ago â€ĸ 6 comments

Report hasn't been filed before.

  • [x] I have verified that the bug I'm about to report hasn't been filed before.

What version of drizzle-orm are you using?

0.38.3

What version of drizzle-kit are you using?

0.30.1

Other packages

[email protected]

Describe the Bug

bug: currently, inserting data to a column with the serial type, drizzle seed doesn't seem to actually sync the sequence properly, causing data that's inserted after the seed to have a duplicate key issue.

reproduce: simply seed a table with a serial primary key with some data, then try and insert some more data after the seed.

desired result: drizzle seed should keep the serial sequence in sync.

kmate19 avatar Jan 07 '25 19:01 kmate19

I'm also having this issue! Using Supabase

danilarb avatar Jan 16 '25 08:01 danilarb

Having same issue

RiznykLeo avatar Jan 22 '25 01:01 RiznykLeo

same issue on drizzle-seed 0.3.1

If someone comes across this, here is a query to update the sequence. Execute it after seeding your database, and replace 51 with the id from which you want postgres to start:

DO $$ 
DECLARE
    seq_record record;
BEGIN
    FOR seq_record IN 
        SELECT schemaname, sequencename 
        FROM pg_sequences 
        WHERE schemaname = 'public'  -- adjust schema if needed
    LOOP
        EXECUTE format('SELECT setval(%L, 51',  
            seq_record.schemaname || '.' || seq_record.sequencename);
    END LOOP;
END $$;

younes101020 avatar Feb 02 '25 10:02 younes101020

We will think about the best solution for it and take into account @younes101020 comment

OleksiiKH0240 avatar Mar 05 '25 10:03 OleksiiKH0240

Another workaround: As @younes101020 pointed out, you need to update the sequence. I rewrote as javascript that you can co-locate with your seed file:

await db.execute(
    sql`SELECT setval(pg_get_serial_sequence('YOUR_TABLE_NAME', 'id'), coalesce(max(id), 0) + 1, false) FROM YOUR_TABLE_NAME`
  );

cassiozen avatar Mar 28 '25 18:03 cassiozen

Another workaround: As @younes101020 pointed out, you need to update the sequence. I rewrote as javascript that you can co-locate with your seed file:

await db.execute( sqlSELECT setval(pg_get_serial_sequence('YOUR_TABLE_NAME', 'id'), coalesce(max(id), 0) + 1, false) FROM YOUR_TABLE_NAME );

I wrote a function to help automate this process. I hope it helps you.

import * as schema from './schema';
import type * as relations from './relations';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

// Define schema type
type AppSchema = typeof schema & typeof relations;


async function serialSequenceReset(
	db: NodePgDatabase<AppSchema>,
): Promise<boolean> {
	// [BUG]: drizzle seed breaks serial sequence sync with Postgres serial type #3915
	console.log(
		'â„šī¸ Resetting serial sequences... Refer to https://github.com/drizzle-team/drizzle-orm/issues/3915',
	);

	const tables = Object.entries(schema)
		.filter(([_, value]) => value instanceof Table)
		.map(([key]) => camelToKebab(key));
	const schemaName = Object.entries(schema).find(
		([_, value]) => value instanceof PgSchema,
	)?.[0];

	for (const table of tables) {
		const tableName = schemaName ? `${schemaName}.${table}` : table;
		const cmd = `SELECT setval(pg_get_serial_sequence('${tableName}', 'id'), coalesce(max(id), 0) + 1, false) FROM ${tableName}`;
		try {
			await db.execute(sql.raw(cmd));
		} catch (error) {
			console.log(sql.raw(cmd));
			console.warn(
				`âš ī¸ Error Reset Serial Sequence for '${table}': ${error instanceof Error ? error.message : String(error)}`,
			);
			throw error;
		}
	}
	return true;
}

Dilettante258 avatar Apr 23 '25 07:04 Dilettante258

Another workaround: As @younes101020 pointed out, you need to update the sequence. I rewrote as javascript that you can co-locate with your seed file:

await db.execute( sqlSELECT setval(pg_get_serial_sequence('YOUR_TABLE_NAME', 'id'), coalesce(max(id), 0) + 1, false) FROM YOUR_TABLE_NAME );

can confirm this fixed it. thank you for this

Milopadma avatar May 13 '25 11:05 Milopadma

Can also confirm this is still a problem with

    "drizzle-orm": "^0.44.2",
    "drizzle-seed": "^0.3.1",

defaultdigital1 avatar Jul 01 '25 10:07 defaultdigital1

correct, it is still a problem

Jaime5Alvarez avatar Aug 01 '25 18:08 Jaime5Alvarez

Im having the same issue. https://github.com/drizzle-team/drizzle-orm/blob/33f0374e29014677c29f4b1f1dd1ab8fb68ac516/drizzle-seed/src/services/Generators.ts#L444-L462

Here its the code of intPrimaryKey, its not doing the seq_id update

Lautarotetamusa avatar Aug 22 '25 13:08 Lautarotetamusa

Hey everyone!

I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.

I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!

We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.


First branch is drizzle-kit rewrite

All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439

As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.

What's left here:

  • We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the srid issue here as well).
  • We are finishing commutative migrations for all dialects.
  • We are finishing up the command, so the migration flow will be as simple as drizzle-kit up for you.

Where it brings us:

  • We are getting drizzle-kit into a new good shape where we can call it [email protected]!

Timeline:

  • We need ~2 weeks to finish all of the above and send this branch to beta for testing.

Second big branch is a complex one with several HUGE updates

  • Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)

TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k

You can read more about it here.

What's left here:

Where it brings us:

  • We are getting drizzle-orm into a new good shape where we can call it [email protected]!

Breaking changes:

  • We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.

Third branch is adding support for CockroachDB and MSSQL dialects

Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.

Summary

All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.

We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).

We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.

Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!

Timelines

We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!

AndriiSherman avatar Aug 30 '25 18:08 AndriiSherman