Beginner's question on enumerated types
Gitsis Christos
cgitsis at gmail.com
Thu Mar 20 04:18:45 UTC 2014
Hello,
I have recently started using postmodern in a project. I need to store enum
values (of many different types) in a class. I have declared a LISP type
(deftype season-type () '(member winter spring summer autumn))
and I have functions that convert the above symbols to the numbers 0..3 and
vice-versa, if needed.
-- I have tried to emulate enum types with
(defclass my-type ()
((id :initarg :id :col-type bigint)
(season :initarg :season :col-type smallint))
(:metaclass dao-class)
(:keys id))
CREATE TABLE valid_seasons (
id SERIAL PRIMARY KEY NOT NULL,
season TEXT
);
INSERT INTO valid_seasons (seasons) VALUES
("WINTER"), ("SPRING"), ("SUMMER"), ("AUTUMN");
and then like
(deftable season
(!dao-def)
(!foreign 'valid-seasons 'id 'season))
I would like the class my-type to have the symbols of the seasons (winter,
spring, etc) stored in its slot when I am in the land of lisp and not to be
forced to store integer numbers, which should only be used in the land of
the database. What is the normal way to achieve that in postmodern?
-- PostgreSQL offers an enum type, so I tried using it in postmodern
(:create-enum 'seasondbtype (list "WINTER" "SPRING" "SUMMER" "AUTUMN"))
(defclass my-type ()
((id :initarg :id :col-type bigint)
(season :initarg :season :col-type seasondbtype))
(:metaclass dao-class)
(:keys id))
But then again I have to store strings inside my-type.season, not symbols.
I have added something like
(defmethod initialize-instance :after ((object my-type) &key)
(dolist (slot-name '(season))
(setf (slot-value object slot-name) (symbol-name (slot-value object
slot-name))))),
so that I can call make-instance with a symbol of season-type as an
argument. But this is only for storing objects to the database, I have not
gotten around to retrieving yet, and I think initialize-instance will be
called there as well, so I will have to fix it.
-- CL-SQL offers two slot options called :db-reader :db-writer where you
can specify functions which "take one argument, the value from the
database, and return the value that should be put into the slot" and "take
one argument, the value of the slot, and return the value that should be
put into the database" respectively. Is there something similar in
postmodern? Does the macro with-column-writers or the parameter
*custom-column-writers* have anything to do with that? If yes, can I have
an example of usage? I think that might solve my problem.
In short, in what way do postmodern's users deal with enumerated types, and
in particular how do they manage to store symbols in CLOS instances and the
corresponding strings (or even numbers) in PostgreSQL?
Regards,
Christos Gitsis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/postmodern-devel/attachments/20140320/9d3a5173/attachment.html>
More information about the postmodern-devel
mailing list