postgresql - Korma 和 Postgresql 的默认 ID?

标签 postgresql clojure compojure korma

我有以下架构:

CREATE TABLE IF NOT EXISTS art_pieces
(
  -- Art Data
  ID SERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  description TEXT,
  price INT NULL,

  -- Relations
  artists_id INT NULL

);

--;;

CREATE TABLE IF NOT EXISTS artists
(
  -- Art Data
  ID SERIAL PRIMARY KEY,
  name TEXT NOT NULL
);

这是相应的艺术作品实体:

(defentity art-pieces
  (table :art_pieces)
  (entity-fields
    :id
    :title
    :description
    :price
    :artists_id)
  (belongs-to artists))

我想知道为什么以下返回 PSQLException ERROR: null value in column "id"violates not-null constraint:

(create-piece {:title "The Silence of the Lambda" 
               :description "Something something java beans and a nice chianti" 
               :price 5000})

ID SERIAL PRIMARY KEY 字段不应该自动填充吗?这与 Korma 与 PSQL 的交互有关吗?

最佳答案

INSERT INTO "art_pieces" ("description", "id", "price", "title") VALUES (?, NULL, ?, ?)

这里的问题是您尝试将 NULL 值插入到 id 列中。仅当您省略该列或使用 DEFAULT 关键字(而不是 NULL)时才会插入默认值。

To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value. This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word

PostgreSQL Serial Types

因此您必须将查询更改为:

INSERT INTO "art_pieces" ("description", "id", "price", "title") VALUES (?, DEFAULT, ?, ?)
-- or
INSERT INTO "art_pieces" ("description", "price", "title") VALUES (?, ?, ?)

另一种解决方法(如果您没有更改查询的权限)是添加一个 trigger 函数来替换 id 中的 NULL 列自动:

CREATE OR REPLACE FUNCTION tf_art_pieces_bi() RETURNS trigger AS
$BODY$
BEGIN
    -- if insert NULL value into "id" column
    IF TG_OP = 'INSERT' AND new.id IS NULL THEN
        -- set "id" to the next sequence value
        new.id = nextval('art_pieces_id_seq');
    END IF;
    RETURN new; 
END;
$BODY$
LANGUAGE plpgsql;

CREATE TRIGGER art_pieces_bi
BEFORE INSERT
ON art_pieces
FOR EACH ROW EXECUTE PROCEDURE tf_art_pieces_bi();

关于postgresql - Korma 和 Postgresql 的默认 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35904208/

相关文章:

r - 如何在 plr(PostgreSQL R 扩展)中从 R_LIBS_USER 加载 R 库

clojure - 编辑无限循环运行的程序

clojure - 响铃响应下载index.html而不是渲染它

java - 将 Clojure WAR Web 应用程序部署到 Tomcat 后提取的结果应该是什么?

clojure - Compojure 路由问题

postgresql - Postgresql 查询代码覆盖率

python - Django ConnectionAbortedError : [WinError 10053] An established connection was aborted by the software in your host machine

ruby-on-rails - rails : Return only objects where all associations meet a condition

list - Clojure 函数抛出空指针异常

clojure - 如何将值应用于 Clojure 中的多个函数?