How do you typecast and insert a Postgres enum value using Clojure JDBC?

2,460 views
Skip to first unread message

James Thornton

unread,
Feb 6, 2013, 3:59:14 AM2/6/13
to clo...@googlegroups.com

For example, here is a product table in PostgreSQL with status as an enum:

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
);

Typical Clojure code to insert a product would be:

(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 product-12345))

However, status is an enum so you can't insert it as a normal string without casting it to an enum:

'InStock'::product_status

I know you can do it with a prepared statement, such as:

INSERT INTO product (name, status) VALUES (?, ?::product_status)

But is there a way to do it without using a prepared statement?

From StackOverflow: 
http://stackoverflow.com/questions/14719207/how-do-you-insert-a-postgres-enum-value-using-clojure-jdbc

- James

Ryan Neufeld

unread,
Aug 18, 2014, 2:16:14 PM8/18/14
to clo...@googlegroups.com
For posterity, you should create a PGobject object. See instructions how in http://naiquevin.github.io/using-postgresqls-enum-types-with-korma.html
Reply all
Reply to author
Forward
0 new messages