Code generated value

I'm using SQLite. How can I create a custom type with an auto-generated value which is generated in code and not the database? I managed to get it to work, but I have to pass a blank value for the field whenever creating records otherwise I get a type error, and I'm having trouble finding the right combination of options.
import {customType, sqliteTable } from "drizzle-orm/sqlite-core";
import { createId } from "@paralleldrive/cuid2";

const cuid2 = customType<{ data: string; notNull: true }>({
dataType() { return "text"; },
toDriver(): string { return createId(); },
});

const users = sqliteTable("users",
{ id: cuid2("id").primaryKey() }
);

db.insert(users).values({id: ""}).run();
import {customType, sqliteTable } from "drizzle-orm/sqlite-core";
import { createId } from "@paralleldrive/cuid2";

const cuid2 = customType<{ data: string; notNull: true }>({
dataType() { return "text"; },
toDriver(): string { return createId(); },
});

const users = sqliteTable("users",
{ id: cuid2("id").primaryKey() }
);

db.insert(users).values({id: ""}).run();
If {id: ""} is left out of values, TypeScript complains: "property id is missing. On the other hand, setting a default or using default: true as configuration resolves the TypeScript error, but inserting records fails with a runtime error: UNIQUE constraint failed: users.id. Is there a better way that allows omitting the field on insert, does not result in a type error, and safely and reliably generates an value?
2 Replies
Andrii Sherman
Andrii Sherman15mo ago
I see you have notNull: true in types for customType
tacomanator
tacomanator15mo ago
@Andrii Sherman because I want the generated database column to be not null