簡體   English   中英

用戶定義的函數在 better-sqlite3 中不起作用

[英]User defined functions is not working in better-sqlite3

我有一個連接和初始化sqlite數據庫的node.js服務器。 我正在使用better-sqlite3庫。

但是服務器永遠不會啟動。 它給出以下錯誤:

在此處輸入圖像描述

表架構:

CREATE TABLE IF NOT EXISTS users (

    user_id       text        NOT NULL DEFAULT gen_random_uuid() ,
    email         text UNIQUE NOT NULL                           ,
    full_name     text        NOT NULL                           ,
    profile_photo text                 DEFAULT ''                ,    
    passhash      text        NOT NULL                           ,
    created_time  int         NOT NULL DEFAULT now()             ,
    settings      text        NOT NULL DEFAULT '{}'              ,       

    CHECK ( length ( user_id ) = 36 ) ,
    CHECK ( length ( email     ) >= 3  AND length ( email     ) <= 100 ) ,
    CHECK ( length ( full_name ) >= 1  AND length ( full_name ) <= 100 ) ,
    CHECK ( length ( passhash  ) >= 8  AND length ( passhash  ) <= 100 ) ,
    CHECK ( length ( profile_photo  ) >= 0  AND length ( profile_photo  ) <= 1000 ) , 

    PRIMARY KEY ( user_id )

) STRICT;

node.js服務器代碼的一部分:

function setup (config) {
    db = new Database('colube.db', { verbose: console.log }); 
    db.pragma('journal_mode = WAL');

    if (!isTablesCreated(db)) {
        addFns(db);

        let path      = getPath('db/migrations/V0001__sqlite3_initial_version.sql');
        let migration = fs.readFileSync(path, 'utf8');

        db.exec(migration);
    }
}

我的user-defined functions

function addFns (db) {

    db.function('gen_random_uuid', () => {
        return v4();
    }); 
    
    db.function('now', () => {
        return Date.now();
    }); 
}   

執行sqlite遷移文件時拋出錯誤。 移除gen_random_uuidnow (用戶定義的函數)的使用時,遷移工作正常。

由於better-sqlite3的文檔明確表示支持user-defined functions ,不知道怎么解決這個問題。

Better-sqlite3 文檔:用戶定義函數

我在 github 上收到了來自better-sqlite3社區的回復,解決了我的問題,回復的鏈接: Help: syntax error 以下為回復內容:

問題是您使用了無效的語法。 正確的語法描述為:

顯式 DEFAULT 子句可以指定默認值為 NULL、字符串常量、blob 常量、有符號數或括號中的任何常量表達式。 默認值也可以是與特殊情況無關的關鍵字 CURRENT_TIME、CURRENT_DATE 或 CURRENT_TIMESTAMP 之一。

換句話說,您必須將 gen_random_uuid() 括在括號中,例如 (gen_random_uuid())。 now() -> (now()) 也必須這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM