Drizzle Columns Schema JSON 将我的 JSON 作为文本存储在 PostgreSQL 中

问题描述 投票:0回答:2

我使用 Drizzle 作为 Typescript 后端,为一些 API 端点提供服务。我的数据库是 Postgresql,有一个 JSON 列。

export const transactions = pgTable("transactions", {
    id: serial("id").primaryKey(),
    my_json: json('my_json')
});

我如果尝试从supabase表编辑器存储

{"hello":"world"}
,这就是我得到的:

如果我尝试使用 TS/Drizzle 插入我的 {"hello":"world"},这就是我得到的:

不知怎的,我找不到设置或方法让 drizzle 将其存储为真正的 JSON 对象而不是它的字符串版本。

json typescript postgresql orm drizzle
2个回答
6
投票

目前(2023 年 6 月)由于错误而无法实现:https://github.com/drizzle-team/drizzle-orm/issues/724

您需要执行原始 DML 查询:

db.execute(sql`INSERT INTO table(foo_id, foo_json)...VALUES(123,${yourObject})`)

例如,这对我有用。

const statement = sql`
        INSERT INTO wikidata_article (wikidata_id, category, grade, en_raw_length, en_url_title, labels, sitelinks)
        VALUES (${articleDetails.wikiDataId}, ${articleDetails.category}, ${articleDetails.grade}, ${articleDetails.enBytes}, ${articleDetails.enUrlTitle}, ${articleDetails.labels}, ${articleDetails.sitelinks})
        ON CONFLICT (wikidata_id) DO UPDATE
        SET 
            category = ${articleDetails.category},
            grade = ${articleDetails.grade},    
            en_raw_length = ${articleDetails.enBytes},
            en_url_title = ${articleDetails.enUrlTitle},
            labels = ${articleDetails.labels},
            sitelinks = ${articleDetails.sitelinks}
        `;
        await db.execute(statement);

0
投票

创建一个 lil sqlJSON 帮助器来解决这个问题......:

import type { SQL } from 'drizzle-orm';
import type { PgColumn } from 'drizzle-orm/pg-core';

export const sqlJSON = <TC extends PgColumn, TD = Exclude<TC['default'], SQL<unknown>>>(column: TC, data: TD) => {
  return sql`${JSON.stringify(data)}::json`;
};


// usage:

const MyTable = pgTable('my_table', {
  jsonData: json('json_data').$type<{ data: string; }>
})

sqlJSON(MyTable.jsonData, { data: 'to make JSON' })

© www.soinside.com 2019 - 2024. All rights reserved.