例如,这是 PostgreSQL 中的产品表,状态为枚举:
create type product_status as enum ('InStock', 'OutOfStock');
create table product (
pid int primary key default nextval('product_pid_seq'),
sku text not null unique,
name text not null,
description text not null,
quantity int not null,
cost numeric(10,2) not null,
price numeric(10,2) not null,
weight numeric(10,2),
status product_status not null
);
插入产品的典型 Clojure 代码是:
(def prod-12345 {:sku "12345"
:name "My Product"
:description "yada yada yada"
:quantity 100
:cost 42.00
:price 59.00
:weight 0.3
:status "InStock"})
(sql/with-connection db-spec
(sql/insert-record :product prod-12345))
然而,
status
是一个枚举,因此您不能将其作为普通字符串插入而不将其转换为枚举:'InStock'::product_status
我知道您可以使用准备好的语句来做到这一点,例如:
INSERT INTO product (name, status) VALUES (?, ?::product_status)
但是有没有办法在不使用准备好的语句的情况下做到这一点?
最佳答案
我今天使用 stringtype=unspecified
完成了这项工作黑客解决方法。
您可以将此参数添加到您的 db-spec
如下:
(def db-spec {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//myserver:5432/mydatabase"
:user "myuser"
:password "mypassword"
:stringtype "unspecified"}) ; HACK to support enums
然后只需使用
insert!
照常。最好有一个不会削弱类型安全性的解决方案。
关于sql - 如何使用 Clojure JDBC 插入 Postgres 枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14719207/