drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.81k stars 658 forks source link

[BUG]: Column name conversion not working when using `sql.js` #3642

Open rockmagma02 opened 3 days ago

rockmagma02 commented 3 days ago

Report hasn't been filed before.

What version of drizzle-orm are you using?

0.36.4

What version of drizzle-kit are you using?

0.28.1

Other packages

No response

Describe the Bug

Column name conversion not working when using sql.js

Description

Here is a simple example can show this bug:

import initSqlJs from "sql.js";
import fs from "node:fs";
import { drizzle } from "drizzle-orm/sql-js";
import { numeric, sqliteTable, text } from "drizzle-orm/sqlite-core";

const testTable = sqliteTable("test", {
    id: numeric().primaryKey().notNull(),
    testSnakeName: text("test_snake_name").notNull(),
});

async function main() {
    const SQL = await initSqlJs();
        // // this a simple sqlite database, which is used to demonstrate this bug
    const dbFile = fs.readFileSync("./test.sqlite");
    const dbOrigin = new SQL.Database(dbFile);
    const db = drizzle(dbOrigin, {
        schema: { testTable },
        logger: true,
    });
    const result = await db.query.testTable.findFirst();
    console.log("result:", result);
    console.log("property:", result?.testSnakeName);
}

await main();

As you can observe, the table contains a column named test_snake_name. We utilize the testSnakeName to refer to this column in the Drizzle schema. However, there is an issue:

Query: select "id", "test_snake_name" from "test" "testTable" limit ? -- params: [1]
result: { id: 1, test_snake_name: 'test' }
property: undefined

The query was successfully executed, and the result was retrieved. However, the retrieved data was not converted to the appropriate object type suitable for use in TypeScript or JavaScript code. Instead, it retains the name stored in the database.

Other info

I discovered similar (or identical) issues in #2189, which was opened on April 22, 2024. However, due to the high volume of issues, it appears that your team may have overlooked this matter. Therefore, I am re-reporting it here for your attention.

rockmagma02 commented 3 days ago

Incidentally, I believe I have identified the source of the issue.

https://github.com/drizzle-team/drizzle-orm/blob/599da5ef7a037904989069596c8879690f9c5322/drizzle-orm/src/sql-js/session.ts#L42-L70

It is evident that the prepareQuery method does not accept a customResultMapper, which is essential for converting column names.

I am passionate to open a new Pull Request to fix this issue.