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

[BUG]: drizzle-kit pull fails on MSSQL with "Cannot read properties of null (reading 'replace')"

Open david-sfernandes opened this issue 10 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?

1.0.0-beta.8-734e789

What version of drizzle-kit are you using?

1.0.0-beta.8-734e789

Other packages

No response

Describe the Bug

Description

I'm trying to use drizzle-kit pull to introspect an existing SQL Server (MSSQL) database, but the command fails with a runtime error during the introspection phase.

The connection itself works, but the process crashes after attempting to fetch database metadata.

Environment

Database: Microsoft SQL Server Azure Node.js: 24.4.1 Package manager: pnpm OS: Linux

Message example:

pnpm drizzle-kit pull --init
No config path provided, using default 'drizzle.config.ts'
Reading config file '/home/MYUSER/projects/MY-PROJECT/apps/api/drizzle.config.ts'
[[email protected]] injecting env (0) from .env -- tip: ⚙️  write to custom object with { processEnv: myObject }
[⣽] 0 tables fetching
[⣽] 0 columns fetching
[⣽] 0 enums fetching
[⣽] 0 indexes fetching
[⣽] 0 foreign keys fetching
[⣽] 0 policies fetching
[⣽] 0 check constraints fetching
[⣽] 0 views fetching
 Error  Cannot read properties of null (reading 'replace')

My drizzle.config.ts:

import * as dotenv from "dotenv"
import { defineConfig } from "drizzle-kit"

dotenv.config({ path: ".env" })

if (
  !process.env.DB_HOST ||
  !process.env.DB_NAME ||
  !process.env.DB_USER ||
  !process.env.DB_PASSWORD ||
  !process.env.DATABASE_URL
) {
  throw new Error("DATABASE_URL is not set")
}

export default defineConfig({
  out: "./drizzle",
  schema: "./src/db/schema.ts",
  dialect: "mssql",
  verbose: true,
  dbCredentials: {
    server: process.env.DB_HOST,
    database: process.env.DB_NAME,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    port: 1433,
    // OBS: I try to use only DATABASE_URL, but it leads to another error:
    // The "config.server" property is required and must be of type string.
    // url: process.env.DATABASE_URL
    options: {
      encrypt: true,
      trustServerCertificate: true,
    },
  },
});

Steps to reproduce (following the get started tutorial)

  1. Install the dependecies
  2. set env vars
  3. create drizzle folder and src/db/index.ts
  4. create drizzle.config.ts
  5. run pnpm drizzle-kit pull --init

david-sfernandes avatar Jan 06 '26 01:01 david-sfernandes

Hi @david-sfernandes. Have you tried running this against an empty database? If not, could you please share the SQL statements (DDL) you used to create your tables and any other entities (e.g., schemas, enums, views)? That would help us reproduce the issue.

OleksiiKH0240 avatar Jan 12 '26 18:01 OleksiiKH0240

I tried to reproduce your issue, but wasn't able to. I ran the following DDL statement against the database:

CREATE TABLE [users] (
 [id] int,
 [name] varchar(255) NOT NULL,
 [age] int NOT NULL,
 [email] varchar(255) NOT NULL,
 CONSTRAINT [users_pkey] PRIMARY KEY([id]),
 CONSTRAINT [users_email_key] UNIQUE([email])
);

Then I ran pnpm drizzle-kit pull --init and got the following schema:

import { mssqlTable, int, varchar, unique, primaryKey } from "drizzle-orm/mssql-core"
import { sql } from "drizzle-orm"


export const users = mssqlTable("users", {
	id: int(),
	name: varchar({ length: 255 }).notNull(),
	age: int().notNull(),
	email: varchar({ length: 255 }).notNull(),
}, (table) => [
	primaryKey({ columns: [table.id], name: "users_pkey"}),
	unique("users_email_key").on(table.email)
]);

Environment / versions:

drizzle.config.ts

import { defineConfig } from "drizzle-kit";

export default defineConfig({
  dialect: "mssql",
  schema: "./schema.ts",
  out: "./drizzle",
  dbCredentials: {
    // this works as well
    // url: 'mssql://SA:drizzle123PASSWORD!@localhost:1433?encrypt=true&trustServerCertificate=true',
    server: 'localhost',
    port: 1433,
    user: 'SA',
    password: 'drizzle123PASSWORD!',
    database: 'master',
    options: {
      encrypt: true,
      trustServerCertificate: true
    }
  },
	verbose: true,
	strict: true,
});

OleksiiKH0240 avatar Jan 15 '26 18:01 OleksiiKH0240

I've got the same issue, some tables can be pulled alright, but some others can't.

Here's a table that can't be pulled.

CREATE TABLE [dbo].[Groups] (
    [ID] int NOT NULL IDENTITY,
    [AccountID] int NOT NULL,
    [Name] varchar(140) NOT NULL,
    PRIMARY KEY ([ID])
);

CREATE TABLE [dbo].[ApplePodcastCategories] (
    [Id] int NOT NULL IDENTITY,
    [ParentId] int NOT NULL,
    [Name] varchar(50),
    [IsActive] bit NOT NULL,
    [DateFrom] date NOT NULL,
    [DateTo] date NOT NULL,
    [IABId] int NOT NULL,
    PRIMARY KEY ([Id]),
    CONSTRAINT IX_ApplePodcastCategories UNIQUE NONCLUSTERED (ParentId, Name)
);

The Groups can be pulled, but the ApplePodcastCategories can't.

I didn't create the databases so I don't have the initial creation snippet and I can't modify them. Though I recreated the SQL statements from the tables structure.

Using:

  • Microsoft SQL Server 2019 (RTM-CU27-GDR) (KB5040948) - 15.0.4382.1 (X64) via RDS
  • drizzle-orm@^1.0.0-beta.15-859cf75
  • drizzle-kit@^1.0.0-beta.15-859cf75

I tried to reproduce in an other database that I created with admin roles, and there it works, so maybe there is some permission concern? Or should I test with all the tables from the DB?

I'm testing this using tablesFilter option to only pull those two tables.

Is there any way to debug this on my end like logging every SQL queries made?

depsimon avatar Feb 09 '26 12:02 depsimon

@OleksiiKH0240 After lots of logging into the drizzle-kit bin file, I found where my issue was.

In my case value was null here: https://github.com/drizzle-team/drizzle-orm/blob/859cf755d66c07aa4c5af072c5185a710f975e01/drizzle-kit/src/dialects/mssql/grammar.ts#L221

I've had the issue with some Datetime columns as well.

I fixed it by modifying it like this: const tmp = (value$1 || "").replace(".))", "))");

My guess is it throws an error because the column is non-nullable but the default is set to NULL by default.

Image

Here's the table info from my Table Plus:

CREATE TABLE [dbo].[ApplePodcastCategories] (
    [Id] int IDENTITY,
    [ParentId] int,
    [Name] varchar(50),
    [IsActive] bit,
    [DateFrom] date,
    [DateTo] date,
    [IABId] int,
    PRIMARY KEY ([Id])
);

I also see those default constraints in the DB:

name schema_id parent_table_id parent_column_id definition is_system_named
DF__ApplePodc__Paren__3C34F16F 1 994102582 2 1
DF__ApplePodc__IsAct__3D2915A8 1 994102582 4 1
DF__ApplePodc__DateF__3E1D39E1 1 994102582 5 1
DF__ApplePodc__DateT__3F115E1A 1 994102582 6 1
DF__ApplePodc__IABId__40058253 1 994102582 7 1

I also got the following error on two occasions:

 Error  Cannot read properties of undefined (reading 'schema_id')
error: "drizzle-kit" exited with code 1
  1. When I include a table that has a FK to another table which is not included in the tableFilters
  2. When I have a FK that points to another schema for which I don't have permissions to read the tables.

This one was easier to spot though.

Let me know if I can provide more info to help.

depsimon avatar Feb 09 '26 15:02 depsimon

Hello @david-sfernandes and @depsimon

Upon investigation we were able to reproduce the issue It occurs because the user does not have sufficient permissions You should grant the GRANT VIEW DEFINITION TO <user> This will allow access to the table metadata, enabling introspection to work correctly

You can read about VIEW DEFINITION here - https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175808(v=sql.105)

If you continue to experience any problems, please, feel free to reopen this issue

AleksandrSherman avatar Mar 06 '26 12:03 AleksandrSherman

@AleksandrSherman Tried this morning with the permission and it works, thanks!

depsimon avatar Mar 09 '26 08:03 depsimon