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

[BUG]: Column with custom type not working with `default()`

Open b0o opened this issue 3 years ago โ€ข 6 comments

What version of drizzle-orm are you using?

v0.27.0

What version of drizzle-kit are you using?

v0.19.2

Describe the Bug

With the following schema:

import { customType, mysqlTable, serial, varchar } from 'drizzle-orm/mysql-core'

interface Semver {
  major: number
  minor: number
  patch: number
}

const semver = customType<{
  data: Semver
  driverData: string
  config: { length: number }
  configRequired: true
}>({
  dataType(config) {
    return `varchar(${config.length})`
  },
  fromDriver(value: string): Semver {
    const [major, minor, patch] = value.split('.')
    if (!major || !minor || !patch) {
      throw new Error(`Invalid semver: ${value}`)
    }
    return {
      major: parseInt(major),
      minor: parseInt(minor),
      patch: parseInt(patch),
    }
  },
  toDriver(value: Semver): string {
    return `${value.major}.${value.minor}.${value.patch}`
  },
})

export const releases = mysqlTable(
  'releases',
  {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 255 }).notNull(),
    version: semver('version', { length: 16 }).notNull().default({
      major: 1,
      minor: 0,
      patch: 0,
    }),
  },
)

I get this error on running drizzle-kit push:mysql:

> drizzle-kit push:mysql

drizzle-kit: v0.19.2
drizzle-orm: v0.27.0

No config path provided, using default 'drizzle.config.ts'
Reading config file 'drizzle.config.ts'
Reading schema files:
schemas/releases.ts


 Warning  You are about to execute current statements:

CREATE TABLE `releases` (
        `id` serial AUTO_INCREMENT PRIMARY KEY NOT NULL,
        `name` varchar(255) NOT NULL,
        `version` varchar(16) NOT NULL DEFAULT [object Object]);

  No, abort
โฏ Yes, I want to execute all statements

Error: extra characters encountered after end of DDL: 'object'
    at PromiseConnection.query (node_modules/drizzle-kit/index.cjs:34122:26)
    at Command.<anonymous> (node_modules/drizzle-kit/index.cjs:51859:33)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ER_UNKNOWN_ERROR',
  errno: 1105,
  sql: 'CREATE TABLE `releases` (\n' +
    '\t`id` serial AUTO_INCREMENT PRIMARY KEY NOT NULL,\n' +
    '\t`name` varchar(255) NOT NULL,\n' +
    '\t`version` varchar(16) NOT NULL DEFAULT [object Object]);\n',
  sqlState: 'HY000',
  sqlMessage: "extra characters encountered after end of DDL: 'object'"
}

It seems the value passed to default is being converted to a string instead of using the customType's toDriver() function.

I know the customType code works, because if I remove the .default({ major: 1, minor: 0, patch: 0 }), I can push the schema and I can successfully insert rows using:

await db
  .insert(releases)
  .values({
    name: "Test",
    version: { major: 1, minor: 2, patch: 3 },
  })
  .execute()

Also, the TypeScript type for foo in semver('version', { length: 16 }).notNull().default(foo) is Semver, and trying to pass e.g. a string is a type error, implying that my usage is correct.

Expected behavior

I'd expect .default({ major: 1, minor: 2, patch: 3 }) to behave the same as db.insert(table).values({ version: { major: 1, minor: 2, patch: 3 } }), by calling .toDriver() to serialize the data.

Workaround

In the mean time, using raw sql works around the issue:

import { sql } from 'drizzle-orm'

export const releases = mysqlTable(
  'releases',
  {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 255 }).notNull(),
    version: semver('version', { length: 16 }).notNull().default(sql`'0.0.0'`),
  },
)

b0o avatar Jun 27 '23 04:06 b0o

I think I have the same problem, but I couldn't find a workaround for my case. Trying to add an unsigned bigint:

const unsignedBigInt = customType<{
  data: number;
  // I also tried this โ†“ https://orm.drizzle.team/docs/custom-types#examples
  // notNull: true;
  // default: true;
}>({
  dataType() {
    return "bigint UNSIGNED";
  },
});

export const myTable = mysqlTable("MyTable", {
  id: varchar("id", { length: 191 }).primaryKey().notNull(),
  //...
  // โ†“ this was added โ†“
  usage: unsignedBigInt("usage").default(0).notNull(),
});
ยท You're about to add not-null usage column without default value, which contains 3 items

I decided to say Yes to the warning to see what happens. The drizzle-kit truncated the table, but the table seems to have the correct default value.

mysql> describe MyTable;
+-----------+-----------------+------+-----+----------------------+-------------------+
| Field     | Type            | Null | Key | Default              | Extra             |
+-----------+-----------------+------+-----+----------------------+-------------------+
| id        | varchar(191)    | NO   | PRI | NULL                 |                   |
-- ...
| usage     | bigint unsigned | NO   |     | 0                    |                   |
+-----------+-----------------+------+-----+----------------------+-------------------+

Now if I add some data and run db push again (without doing any changes), it thinks the data is serial and it wants to truncate it again.

 Warning  Found data-loss statements:
ยท You're about to change usage column type from serial to bigint UNSIGNED with 3 items

THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED

for now I think I'll just give up the unsigned on this column.. I think it should be fine.

raviships avatar Jul 12 '23 08:07 raviships

.autoincrement() also doesn't appear to work when using custom types.

Sparticuz avatar Sep 28 '23 14:09 Sparticuz

Perhaps I have a related issue.

I have a custom type:

export const publicId = customType<{
  data: string
  driverData: number
  notNull: true
  default: true
}>({
  dataType() {
    return 'integer'
  },
  fromDriver(value) {
    return encodeId(value)
  },
  toDriver(value) {
    return decodeId(value)
  },
})

But I can't use autoincrement

id: publicId().primaryKey(),

Image

It makes the stuff incompatible with Better Auth: https://www.better-auth.com/docs/reference/options#advanced Image

Because I have to enable useNumberId but disabled generateId. But when I do with without supported auto-incremented ID for custom type, I'm getting NaN for such fields where I have id or references to the id. Image

@AndriiSherman Do you have any updates on this?

serhii-chernenko avatar Jun 10 '25 18:06 serhii-chernenko

I'm confused, I've a similar error with integer via the code approuve: integer({ mode: 'boolean' }).default(0).notNull(),:

[โœ“] Pulling schema from database...

 Warning  You are about to execute current statements:

delete from subventions;
ALTER TABLE `subventions` ADD `approuve` integer DEFAULT 0 NOT NULL;

 Warning  Found data-loss statements:
ยท You're about to add not-null approuve column without default value, which contains 2 items

THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED

Do you still want to push changes?
  No, abort
โฏ Yes, I want to truncate 1 table

tobiasBora avatar Jul 29 '25 16:07 tobiasBora

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

This issue has been fixed in the beta tag, which serves as the release candidate for Drizzle v1 It's available under drizzle-orm@beta and drizzle-kit@beta version.

For more info please check: https://orm.drizzle.team/docs/upgrade-v1

AndriiSherman avatar Jan 03 '26 19:01 AndriiSherman