3 A Common Lisp PostgreSQL programming interface
9 Postmodern is a Common Lisp library for interacting with [PostgreSQL](http://www.postgresql.org) databases. It is under active development. Features are:
11 - Efficient communication with the database server without need for foreign libraries.
12 - Support for UTF-8 on Unicode-aware Lisp implementations
13 - A syntax for mixing SQL and Lisp code
14 - Convenient support for prepared statements and stored procedures
15 - A metaclass for simple database-access objects
17 The biggest differences between this library and CLSQL/CommonSQL or cl-dbi are that Postmodern has no intention of being portable across different SQL implementations (it embraces non-standard PostgreSQL features), and approaches extensions like lispy SQL and database access objects in a quite different way. This library was written because the CLSQL approach did not really work for me. Your mileage may vary.
23 - [Reference](#reference)
24 - [Dependencies](#dependencies)
25 - [License](#dependencies)
26 - [Download and installation](#download-and-installation)
27 - [Quickstart](#quickstart)
28 - [Authentication](#authentication)
29 - [Reference](#reference)
30 - [Data types](#data-types)
31 - [Portability](#portability)
32 - [Reserved Words](#reserved-words)
33 - [Feature Requests](#feature-requests)
34 - [Resources](#resources)
35 - [Running tests](#running-tests)
36 - [Caveats and to-dos](#caveats-and-to-dos)
37 - [Resources](#resources)
43 The reference manuals for the different components of Postmodern are kept in separate files. For using the library in the most straightforward way, you only really need to read the Postmodern reference and glance over the S-SQL reference. The simple-date reference explains the time-related data types included in Postmodern, and the CL-postgres reference might be useful if you just want a low-level library for talking to a PostgreSQL server.
45 - [Postmodern - Index Page](https://marijnhaverbeke.nl/postmodern/index.html)
46 - [Postmodern](https://marijnhaverbeke.nl/postmodern/postmodern.html)
47 - [S-SQL](https://marijnhaverbeke.nl/postmodern/s-sql.html)
48 - [Simple-date](https://marijnhaverbeke.nl/postmodern/simple-date.html)
49 - [CL-postgres](https://marijnhaverbeke.nl/postmodern/cl-postgres.html)
51 Some specific topics in more detail:
53 - [Array Notes](https://marijnhaverbeke.nl/postmodern/array-notes.html)
54 - [Creating Tables](https://marijnhaverbeke.nl/postmodern/create-tables.html)
55 - [Dao Classes](https://marijnhaverbeke.nl/postmodern/dao-classes.html)
56 - [Dynamic Queries](https://marijnhaverbeke.nl/postmodern/dynamic-queries.html)
57 - [Interval Notes](https://marijnhaverbeke.nl/postmodern/interval-notes.html)
58 - [Isolation Notes](https://marijnhaverbeke.nl/postmodern/isolation-notes.html)
59 - [S-SQL Examples](https://marijnhaverbeke.nl/postmodern/s-sql-examples.html)
65 The library depends on usocket (except on SBCL and ACL, where the built-in socket library is used), md5, closer-mop, bordeaux-threads if you want thread-safe connection pools, and CL+SSL when SSL connections are needed. As of version 1.3 it also depends on ironclad, base64 and uax-15 because of the requirement to support scram-sha-256 authentication.
67 Postmodern itself is split into four different packages, some of which can be used independently.
69 Simple-date is a very basic implementation of date and time objects, used to support storing and retrieving time-related SQL types. It is not loaded by default and you can use local-time (which has support for timezones) instead.
71 CL-postgres is the low-level library used for interfacing with a PostgreSQL server over a socket.
73 S-SQL is used to compile s-expressions to strings of SQL code, escaping any Lisp values inside, and doing as much as possible of the work at compile time.
75 Finally, Postmodern itself is a wrapper around these packages and provides higher level functions, a very simple data access object that can be mapped directly to database tables and some convient utilities. It then tries to put all these things together into a convenient programming interface.
81 Postmodern is released under a zlib-style license. Which approximately means you can use the code in whatever way you like, except for passing it off as your own or releasing a modified version without indication that it is not the original.
83 The functions execute-file.lisp were ported from [pgloader](https://github.com/dimitri/pgloader) with grateful thanks to Dimitri Fontaine and are released under a BSD-3 license.
85 ## Download and installation
89 We suggest using [quicklisp](https://www.quicklisp.org/beta/) for installation.
91 A git repository with the most recent changes can be viewed or checked out at <https://github.com/marijnh/Postmodern>
97 This quickstart is intended to give you a feel of the way coding with Postmodern works. Further details about the workings of the library can be found in the reference manual.
99 Assuming you have already installed it, first load and use the system:
102 (ql:quickload :postmodern)
103 (use-package :postmodern)
106 If you have a PostgreSQL server running on localhost, with a database called 'testdb' on it, which is accessible for user 'foucault' with password 'surveiller', there are two basic ways to connect
107 to a database. If your role/application/database(s) looks like a 1:1 relationship and you are not using threads, you can connect like this:
110 (connect-toplevel "testdb" "foucault" "surveiller" "localhost")
113 Which will establish a connection to be used by all code, except for that wrapped in a with-connection form, which takes the same arguments but only establishes the connection within
116 Connect-toplevel will maintain a single connection for the life of the session.
118 If the Postgresql server is running on a port other than 5432, you would also pass the appropriate keyword port parameter. E.g.:
121 (connect-toplevel "testdb" "foucault" "surveiller" "localhost" :port 5434)
124 Ssl connections would similarly use the keyword parameter :use-ssl and pass :yes, :no, :try, :require or :full
127 - :try means if the server supports it
128 - :require means use provided ssl certificate with no verification
129 - :yes means verify that the server cert is issued by a trusted CA, but does not verify the server hostname
130 - :full means expect a CA-signed cert for the supplied hostname and verify the server hostname
132 When using ssl, you can set the cl-postgres exported variables \*ssl-certificate-file\*, \*ssl-key-file\* and \*ssl-root-ca-file\* to provide client key, certificate files
133 and root ca files. They can be either NIL, for no file, or a pathname.
135 If you have multiple roles connecting to one or more databases, i.e. 1:many or
136 many:1, (in other words, changing connections) or you are using threads (each thread will need to have its own connection) then with-connection form which establishes a connection with a lexical scope is more appropriate.
139 (with-connection '("testdb" "foucault" "surveiller" "localhost")
143 If you are creating a database, you need to have established a connection
144 to a currently existing database (typically "postgres"). Assuming the foucault role
145 is a superuser and you want to stay in a development connection with your new database
146 afterwards, you would first use with-connection to connect to postgres, create the
147 database and then switch to connect-toplevel for development ease.
150 (with-connection '("postgres" "foucault" "surveiller" "localhost")
151 (create-database 'testdb :limit-public-access t
152 :comment "This database is for testing silly theories"))
154 (connect-toplevel "testdb" "foucault" "surveiller" "localhost")
157 Note: (create-database) functionality is new to postmodern v. 1.32. Setting the
158 :limit-public-access parameter to t will block connections to that database from
159 anyone who you have not explicitly given permission (except other superusers).
161 A word about Postgresql connections. Postgresql connections are not lightweight
162 threads. They actually consume about 10 MB of memory per connection. In
163 addition, any connections which require security (ssl or scram authentication)
164 will take additiona time and create more overhead.
166 Postgresql can be tuned to limit the number of connections allowed at any one time. It defaults to 100. The parameter is set in the postgresql.conf file. Depending on the size of your server and what you are doing, the sweet spot generally seems to be between 200-400 connections before you need to bring in connection pooling.
168 If your application is threaded, each thread should use its own connection. Connections are stateful and attempts to use the same connection for multiple threads will likely have problems.
170 If you have an application like a web app which will make many connections, you also
171 generally do not want to create and drop connections for every query. The usual solution
172 is to use connection pools so that the application is grabbing an already existing connection
173 and returning it to the pool when finished, saving connection time and memory.
175 To use postmodern's simple connection pooler, the with-connection call would look like:
178 (with-connection '("testdb" "foucault" "surveiller" "localhost" :pooled-p t)
182 The maximum number of connections in the pool is set in the special variable
183 \*max-pool-size\*, which defaults to nil (no maximum).
185 Now for a basic sanity test which does not need a database connection at all:
188 (query "select 22, 'Folie et déraison', 4.5")
189 ;; => ((22 "Folie et déraison" 9/2))
192 That should work. query is the basic way to send queries to the database. The same query can be expressed like this:
195 (query (:select 22 "Folie et déraison" 4.5))
196 ;; => ((22 "Folie et déraison" 9/2))
199 In many contexts, query strings and lists starting with keywords can be used interchangeably. The lists will be compiled to SQL. The S-SQL manual describes the syntax used by these expressions. Lisp values occurring in them are automatically escaped. In the above query, only constant values are used, but it is possible to transparently use run-time values as well:
202 (defun database-powered-addition (a b)
203 (query (:select (:+ a b)) :single))
204 (database-powered-addition 1030 204)
208 That last argument, :single, indicates that we want the result not as a list of lists (for the result rows), but as a single value, since we know that we are only selecting one value. Some other options are :rows, :row, :column, :alists, and :none. Their precise effect is documented in the reference manual.
210 You do not have to pull in the whole result of a query at once, you can also iterate over it with the doquery macro:
213 (doquery (:select 'x 'y :from 'some-imaginary-table) (x y)
214 (format t "On this row, x = ~A and y = ~A.~%" x y))
217 You can work directly with the database or you can use a simple [database-access-class](https://marijnhaverbeke.nl/postmodern/dao-classes.html) (aka dao) which would cover all the columns in a row. This is what a database-access class looks like:
221 ((name :col-type string :initarg :name
222 :reader country-name)
223 (inhabitants :col-type integer :initarg :inhabitants
224 :accessor country-inhabitants)
225 (sovereign :col-type (or db-null string) :initarg :sovereign
226 :accessor country-sovereign))
227 (:metaclass dao-class)
231 The above defines a class that can be used to handle records in a table with three columns: name, inhabitants and sovereign. The :keys parameter specifies which column(s) are used for the primary key. Once you have created the class, you can return an instance of the country class by calling
234 (get-dao 'country "Croatia")
237 You can also define classes that use multiple columns in the primary key:
241 ((x :col-type integer :initarg :x
243 (y :col-type integer :initarg :y
245 (value :col-type integer :initarg :value
247 (:metaclass dao-class)
251 In this case, retrieving a points record would look like the following where 12 and 34 would be the values you are looking to find in the x column and y column respectively.:
254 (get-dao 'points 12 34)
257 Consider a slightly more complicated version of country:
261 ((id :col-type integer :col-identity t :accessor id)
262 (name :col-type string :col-unique t :check (:<> 'name "")
263 :initarg :name :reader country-name)
264 (inhabitants :col-type integer :initarg :inhabitants
265 :accessor country-inhabitants)
266 (sovereign :col-type (or db-null string) :initarg :sovereign
267 :accessor country-sovereign)
268 (region-id :col-type integer :col-references ((regions id))
269 :initarg :region-id :accessor region-id))
270 (:metaclass dao-class)
271 (:table-name countries))
274 In this example we have an id column which is specified to be an identity column.
275 Postgresql will automatically generate a sequence of of integers and this will
278 We have a name column which is specified as unique and is not null and the
279 check will ensure that the database refuses to accept an empty string as the name.
281 We have a region-id column which references the id column in the regions table.
282 This is a foreign key constraint and Postgresql will not accept inserting a country
283 into the database unless there is an existing region with an id that matches this
284 number. Postgresql will also not allow deleting a region if there are countries
285 that reference that region's id. If we wanted Postgresql to delete countries when
286 regions are deleted, that column would be specified as:
289 (region-id :col-type integer :col-references ((regions id) :cascade)
290 :initarg :region-id :accessor region-id)
293 Now you can see why the double parens.
295 We also specify that the table name is not "country" but "countries". (Some style guides
296 recommend that table names be plural and references to rows be singular.)
300 You can create tables directly without the need to define a class, and in more
301 complicated cases, you may need to use the s-sql :create-table operator or plain
302 vanilla sql. Staying with examples that will match our slightly more complicated
303 dao-class above (but ignoring the fact that the references parameter would
304 actually require us to create the regions table first) and using s-sql rather
305 than plain vanilla sql would be the following:
308 (query (:create-table 'countries
309 ((id :type integer :primary-key t :identity-always t)
310 (name :type string :unique t :check (:<> 'name ""))
311 (inhabitants :type integer)
312 (sovereign :type (or db-null string))
313 (region-id :type integer :references ((regions id))))))
316 Restated using vanilla sql:
319 (query "CREATE TABLE countries (
320 id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
321 name TEXT NOT NULL UNIQUE CHECK (NAME <> E''),
322 inhabitants INTEGER NOT NULL,
324 region_id INTEGER NOT NULL REFERENCES regions(id)
325 MATCH SIMPLE ON DELETE RESTRICT ON UPDATE RESTRICT)")
328 Let's look at a slightly different example:
331 (query (:create-table so-items
332 ((item-id :type integer)
333 (so-id :type (or integer db-null) :references ((so-headers id)))
334 (product-id :type (or integer db-null))
335 (qty :type (or integer db-null))
336 (net-price :type (or numeric db-null)))
337 (:primary-key item-id so-id)))
340 Restated using plain sql:
343 (query "CREATE TABLE so_items (
344 item_id INTEGER NOT NULL,
345 so_id INTEGER REFERENCES so_headers(id)
346 MATCH SIMPLE ON DELETE RESTRICT ON UPDATE RESTRICT,
350 PRIMARY KEY (item_id, so_id)
355 In the above case, the new table's name will be so_items because sql does not allow hyphens and plain vanilla sql will require that. Postmodern will generally allow you to use the quoted symbol 'so-items. This is also true for all the column names. The column item-id is an integer and cannot be null. The column so-id is also an integer, but is allowed to be null and is a foreign key to the id field in the so-headers table so-headers. The primary key is actually a composite of item-id and so-id. (If we wanted the primary key to be just item-id, we could have specified that in the form defining item-id.)
357 You can also use a previously defined dao to create a table as well using the dao-table-definition function which generates the plain vanilla sql for creating plain vanilla sql for creating a table
358 described above. Using the slightly more complicated version of the country dao above:
361 (dao-table-definition 'country)
363 ;; => "CREATE TABLE countries (
364 ;; id INTEGER NOT NULL PRIMARY KEY generated always as identity,
365 ;; name TEXT NOT NULL UNIQUE,
366 ;; inhabitants INTEGER NOT NULL,
367 ;; sovereign TEXT DEFAULT NULL,
368 ;; region_id INTEGER NOT NULL REFERENCES regions(id)
369 ;; MATCH SIMPLE ON DELETE RESTRICT ON UPDATE RESTRICT)
371 (execute (dao-table-definition 'country))
374 This defines our table in the database. execute works like query, but does not expect any results back.
376 See [Introduction to Multi-table dao class objects](doc/dao-classes.html#multi-table-dao-class-object) in the postmodern.org or postmodern.html manual for a further discussion of multi-table use of daos.
380 Similarly to table creation, you can insert data using the s-sql wrapper, plain
381 vanilla sql or daos. Because we have not created a regions table, we are just
382 going to use the simple version of country without the region-id.
384 The s-sql approach would be:
387 (query (:insert-into 'country :set 'name "The Netherlands"
388 'inhabitants 16800000
389 'sovereign "Willem-Alexander"))
391 (query (:insert-into 'country :set 'name "Croatia"
392 'inhabitants 4400000))
395 You could also insert multiple rows at a time but that requires the same columns for each row:
398 (query (:insert-rows-into 'country :columns 'name 'inhabitants 'sovereign
399 :values '(("The Netherlands" 16800000 "Willem-Alexander")
400 ("Croatia" 4400000 :null))))
403 The sql approach would be:
406 (query "insert into country (name, inhabitants, sovereign)
407 values ('The Netherlands', 16800000, 'Willem-Alexander')")
409 (query "insert into country (name, inhabitants)
410 values ('Croatia', 4400000)")
413 The multiple row sql approach would be:
416 (query "insert into country (name, inhabitants, sovereign)
418 ('The Netherlands', 16800000, 'Willem-Alexander'),
419 ('Croatia', 4400000, NULL)")
422 Using dao classes would look like:
425 (insert-dao (make-instance 'country :name "The Netherlands"
426 :inhabitants 16800000
427 :sovereign "Willem-Alexander"))
428 (insert-dao (make-instance 'country :name "Croatia"
429 :inhabitants 4400000))
432 Postmodern does not yet have an insert-daos (plural) function.
434 Staying with the dao class approach, to update Croatia's population, we could do this:
437 (let ((croatia (get-dao 'country "Croatia")))
438 (setf (country-inhabitants croatia) 4500000)
439 (update-dao croatia))
440 (query (:select '* :from 'country))
441 ;; => (("The Netherlands" 16800000 "Willem-Alexander")
442 ;; ("Croatia" 4500000 :NULL))
445 Next, to demonstrate a bit more of the S-SQL syntax, here is the query the utility function list-tables uses to get a list of the tables in a database:
448 (sql (:select 'relname :from 'pg-catalog.pg-class
449 :inner-join 'pg-catalog.pg-namespace :on (:= 'relnamespace 'pg-namespace.oid)
450 :where (:and (:= 'relkind "r")
451 (:not-in 'nspname (:set "pg_catalog" "pg_toast"))
452 (:pg-catalog.pg-table-is-visible 'pg-class.oid))))
454 ;; => "(SELECT relname FROM pg_catalog.pg_class
455 ;; INNER JOIN pg_catalog.pg_namespace ON (relnamespace = pg_namespace.oid)
456 ;; WHERE ((relkind = 'r') and (nspname NOT IN ('pg_catalog', 'pg_toast'))
457 ;; and pg_catalog.pg_table_is_visible(pg_class.oid)))"
460 sql is a macro that will simply compile a query, it can be useful for seeing how your queries are expanded or if you want to do something unexpected with them.
462 As you can see, lists starting with keywords are used to express SQL commands and operators (lists starting with something else will be evaluated and then inserted into the query). Quoted symbols name columns or tables (keywords can also be used but might introduce ambiguities). The syntax supports subqueries, multiple joins, stored procedures, etc. See the S-SQL reference manual for a complete treatment and the S-SQL Example pages.
464 Finally, here is an example of the use of prepared statements:
467 (defprepared sovereign-of
468 (:select 'sovereign :from 'country :where (:= 'name '$1))
470 (sovereign-of "The Netherlands")
471 ;; => "Willem-Alexander"
474 The defprepared macro creates a function that takes the same amount of arguments as there are $X placeholders in the given query. The query will only be parsed and planned once (per database connection), which can be faster, especially for complex queries.
477 (disconnect-toplevel)
482 Postmodern can use either md5 or scram-sha-256 authentication. Scram-sha-256 authentication is obviously more secure, but slower than md5, so take that into account if you are planning on opening and closing many connections without using a connection pooling setup..
484 Other authentication methods have not been tested. Please let us know if there is a authentication method that you believe should be considered.
490 For a short comparison of lisp and Postgresql data types (date and time datatypes are described in the next section)
492 | Lisp type | SQL type | Description |
493 | ------------- | ---------------- | ---------------------------------------------------------- |
494 | integer | smallint | -32,768 to +32,768 2-byte storage |
495 | integer | integer | -2147483648 to +2147483647 integer, 4-byte storage |
496 | integer | bigint | -9223372036854775808 to 9223372036854775807 8-byte storage |
497 | (numeric X Y) | numeric(X, Y) | user specified. See below |
498 | float, real | real | float, 6 decimal digit precision 4-byte storage |
499 | double-float | double-precision | double float 15 decimal digit precision 8-byte storage |
500 | string, text | text | variable length string, no limit specified |
501 | string | char(X) | char(length), blank-padded string, fixed storage length |
502 | string | varchar(X) | varchar(length), non-blank-padded string, variable storage |
503 | boolean | boolean | boolean, 'true'/'false', 1 byte |
504 | bytea | bytea | binary strings allowing non-printable octets |
505 | date | date | date range: 4713 BC to 5874897 AD |
506 | interval | interval | time intervals |
507 | array | array | See discussion at [Array-Notes.html](doc/array-notes.html)|
509 Numeric and decimal are variable storage size numbers with user specified precision.
510 Up to 131072 digits before the decimal point; up to 16383 digits after the decimal point.
511 The syntax is numeric(precision, scale). Numeric columns with a specified scale will coerce input
512 values to that scale. For more detail, see <https://www.postgresql.org/docs/current/datatype-numeric.html>
514 | PG Type | Sample Postmodern Return Value | Lisp Type (per sbcl) |
515 | --------------- | --------------------------------------------------------------------------- | ------------------------------------ |
516 | boolean | T | BOOLEAN |
517 | boolean | NIL (Note: within Postgresql this will show 'f') | BOOLEAN |
518 | int2 | 273 | (INTEGER 0 4611686018427387903) |
519 | int4 | 2 | (INTEGER 0 4611686018427387903) |
520 | char | A | (VECTOR CHARACTER 64) |
521 | varchar | id&wl;19 | (VECTOR CHARACTER 64) |
522 | numeric | 78239/100 | RATIO |
523 | json | { "customer": "John Doe", "items": {"product": "Beer","qty": 6}} | (VECTOR CHARACTER 64) |
524 | jsonb | {"title": "Sleeping Beauties", "genres": ["Fiction", "Thriller", "Horror"]} | (VECTOR CHARACTER 128) |
525 | float | 782.31 | SINGLE-FLOAT |
526 | point | (0.0d0 0.0d0) | CONS |
527 | lseg | ((-1.0d0 0.0d0) (2.0d0 4.0d0)) | CONS |
528 | path | ((1,0),(2,4)) | (VECTOR CHARACTER 64) |
529 | box | ((1.0d0 1.0d0) (0.0d0 0.0d0)) | CONS |
530 | polygon | ((21,0),(2,4)) | (VECTOR CHARACTER 64) |
531 | line | {2,-1,0} | (VECTOR CHARACTER 64) |
532 | double\_precision | 2.38921379231d8 | DOUBLE-FLOAT |
533 | double\_float | 2.3892137923231d8 | DOUBLE-FLOAT |
534 | circle | <(0,0),2> | (VECTOR CHARACTER 64) |
535 | cidr | 100.24.10.0/24 | (VECTOR CHARACTER 64) |
536 | inet | 100.24.10.0/24 | (VECTOR CHARACTER 64) |
537 | interval | #<INTERVAL P1Y3H20m> | INTERVAL |
538 | bit | #*1 | (SIMPLE-BIT-VECTOR 1) |
539 | int4range | [11,24) | (VECTOR CHARACTER 64) |
540 | uuid | 40e6215d-b5c6-4896-987c-f30f3678f608 | (VECTOR CHARACTER 64) |
541 | text\_array | #(text one text two text three) | (SIMPLE-VECTOR 3) |
542 | integer\_array | #(3 5 7 8) | (SIMPLE-VECTOR 4) |
543 | bytea | #(222 173 190 239) | (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (4)) |
544 | text | Lorem ipsum dolor sit amet, consectetur adipiscing elit | (VECTOR CHARACTER 64) |
545 | enum\_mood | happy (Note: enum_mood was defined as 'sad','ok' or 'happy') | (VECTOR CHARACTER 64) |
549 ### Passing Parameters as Text or Binary
551 See [index.html#passing-binary-parameters](https://marijnhaverbeke.nl/postmodern/index.html#passing-binary-parameters)
557 See [array-notes.html](https://marijnhaverbeke.nl/postmodern/array-notes.html)
563 It is important to understand how postgresql (not postmodern) handles timestamps and timestamps with time zones. Postgresql keeps everything in UTC, it does not store a timezone even in a timezone aware column. If you use a timestamp with timezone column, postgresql will calculate the UTC time and will normalize the timestamp data to UTC. When you later select the record, postgresql will look at the timezone for the postgresql session, retrieve the data and then provide the data recalculated from UTC to the timezone for that postgresql session. There is a good writeup of timezones at [http://blog.untrod.com/2016/08/actually-understanding-timezones-in-postgresql.html](http://blog.untrod.com/2016/08/actually-understanding-timezones-in-postgresql.html) and [http://phili.pe/posts/timestamps-and-time-zones-in-postgresql/](http://phili.pe/posts/timestamps-and-time-zones-in-postgresql/).
565 Without simple-date or local-time properly loaded, sample date and time data
566 from postgresql will look like:
568 | PG Type | Return Value | Lisp Type |
569 | ----------------------------- | -------------------------------- | -------------------- |
570 | date | #<DATE 16-05-2020> | DATE |
571 | time\_without\_timezone | #<TIME-OF-DAY 09:47:09.926531> | TIME-OF-DAY |
572 | time\_with\_timezone | 09:47:16.510459-04 | (VECTOR CHARACTER 64) |
573 | timestamp\_without\_timezone | #<TIMESTAMP 16-05-2020T09:47:33,315> | TIMESTAMP |
574 | timestamp\_with\_timezone | #<TIMESTAMP 16-05-2020T13:47:27,855> | TIMESTAMP |
576 The Simple-date add-on library (not enabled by default)
577 provides types (CLOS classes) for dates, timestamps, and intervals
578 similar to the ones SQL databases use, in order to be able to store and read
579 these to and from a database in a straighforward way. A few obvious operations
580 are defined on these types.
582 To use simple-date with cl-postgres or postmodern,
583 load simple-date-cl-postgres-glue and register suitable SQL
584 readers and writers for the associated database types.
587 (ql:quickload :simple-date/postgres-glue)
589 (setf cl-postgres:*sql-readtable*
590 (cl-postgres:copy-sql-readtable
591 simple-date-cl-postgres-glue:*simple-date-sql-readtable*))
594 With simple date loaded, the same data will look like this:
596 | PG Type | Return Value | Lisp Type |
597 | -------------------------- | -------------------------------- | -------------------- |
598 | date | #<DATE 16-05-2020> | DATE |
599 | time\_without\_timezone | #<TIME-OF-DAY 09:47:09.926531> | TIME-OF-DAY |
600 | time\_with\_timezone | 09:47:16.510459-04 | (VECTOR CHARACTER 64) |
601 | timestamp\_without\_timezone | #<TIMESTAMP 16-05-2020T09:47:33,315> | TIMESTAMP |
602 | timestamp\_with\_timezone | #<TIMESTAMP 16-05-2020T13:47:27,855> | TIMESTAMP |
604 To get back to the default cl-postgres reader:
607 (setf cl-postgres:*sql-readtable*
608 (cl-postgres:copy-sql-readtable
609 cl-postgres::*default-sql-readtable*))
612 However [Simple-date](http://marijnhaverbeke.nl/postmodern/simple-date.html) has no concept of time zones. Many users use another library, [local-time](https://github.com/dlowe-net/local-time), which solves the same problem as simple-date, but does understand time zones.
614 For those who want to use local-time, to enable the local-time reader:
617 (ql:quickload :cl-postgres+local-time)
618 (local-time:set-local-time-cl-postgres-readers)
621 With that set postgresql time datatype returns look like:
622 With local-time loaded and local-time:set-local-time-cl-postgres-readers run,
623 the same sample data looks like:
625 | PG Type | Return Value | Lisp Type |
626 | ---------------------------- | -------------------------------- | -------------------- |
627 | date | 2020-05-15T20:00:00.000000-04:00 | TIMESTAMP |
628 | time\_without\_timezone | 2000-03-01T04:47:09.926531-05:00 | TIMESTAMP |
629 | time\_with\_timezone | 09:47:16.510459-04 | (VECTOR CHARACTER 64) |
630 | timestamp\_without\_timezone | 2020-05-16T05:47:33.315622-04:00 | TIMESTAMP |
631 | timestamp\_with\_timezone | 2020-05-16T09:47:27.855146-04:00 | TIMESTAMP |
635 The Lisp code in Postmodern is theoretically portable across implementations,
636 and seems to work on all major ones as well as some minor ones such as Genera.
637 It is regularly tested on ccl, sbcl, ecl, abcl and cmucl.
639 ABCL version 1.8.0 broke the dao class inheritance. See [https://abcl.org/trac/ticket/479](https://abcl.org/trac/ticket/479). Everything other than dao-classes works.
641 Clisp currently has issues with executing a file of sql statements (Postmodern's execute-file function).
643 Please let us know if it does not work on the implementation that you normally use. Implementations that do not have meta-object protocol support will not have DAOs, but all other parts of the library should work (all widely used implementations do support this).
645 The library is not likely to work for PostgreSQL versions older than 8.4. Other features only work in newer Postgresql versions as the features were only introduced in those newer versions.
649 It is highly suggested that you do not use words that are reserved by Postgresql as identifiers (e.g. table names, columns). The reserved words are:
651 "all" "analyse" "analyze" "and" "any" "array" "as" "asc" "asymmetric"
652 "authorization" "between" "binary" "both" "case" "cast" "check" "collate"
653 "column" "concurrently" "constraint" "create" "cross" "current-catalog"
654 "current-date" "current-role" "current-schema" "current-time"
655 "current-timestamp" "current-user" "default" "deferrable" "desc" "distinct" "do"
656 "else" "end" "except" "false" "fetch" "filter" "for" "foreign" "freeze" "from"
657 "full" "grant" "group" "having" "ilike" "in" "initially" "inner" "intersect"
658 "into" "is" "isnull" "join" "lateral" "leading" "left" "like" "limit"
659 "localtime" "localtimestamp" "natural" "new" "not" "notnull" "nowait" "null"
660 "off" "offset" "old" "on" "only" "or" "order" "outer" "overlaps" "placing"
661 "primary" "references" "returning" "right" "select" "session-user" "share"
662 "similar" "some" "symmetric" "table" "then" "to" "trailing" "true" "union"
663 "unique" "user" "using" "variadic" "verbose" "when" "where" "window" "with"
668 Postmodern is under periodic development so issues and feature requests should
669 be flagged on [Postmodern's site on github](https://github.com/marijnh/Postmodern).
675 - [Mailing List](https://mailman.common-lisp.net/listinfo/postmodern-devel)
676 - [A collection of Postmodern examples](https://sites.google.com/site/sabraonthehill/postmodern-examples)
677 - [The PostgreSQL manuals](http://www.postgresql.org/docs/current/static/index.html)
678 - [The wire protocol Postmodern uses](http://www.postgresql.org/docs/current/static/protocol.html)
679 - [Common Lisp Postgis library](https://github.com/filonenko-mikhail/cl-ewkb)
680 - [Local-time](http://common-lisp.net/project/local-time/)
686 Postmodern uses [FiveAM](https://github.com/sionescu/fiveam) for
687 testing. The different component systems of Postmodern have tests
688 defined in corresponding test systems, each defining a test suite.
689 The test systems and corresponding top-level test suites are:
691 - `:postmodern` in `postmodern/tests`,
692 - `:cl-postgres` in `cl-postgres/tests`,
693 - `:s-sql` in `s-sql/tests`, and
694 - `:simple-date` in `simple-date/tests`.
696 Before running the tests make sure PostgreSQL is running and a test
697 database is created. By default tests use the following connection
698 parameters to run the tests:
700 - Database name: test
703 - Hostname: localhost
707 If connection with these parameters fails then you will be asked to
708 provide the connection parameters interactively. The parameters will
709 be stored in `cl-postgres-tests:*test-connection*` variable and
710 automatically used on successive test runs. This variable can also be
711 set manually before running the tests.
713 To test a particular component one would first load the corresponding
714 test system, and then run the test suite. For example, to test the
715 `postmodern` system in the REPL one would do the following:
718 (ql:quickload "postmodern/tests")
719 (5am:run! :postmodern)
720 ;; ... test output ...
723 It is also possible to test multiple components at once by first
724 loading test systems and then running all tests:
727 (ql:quickload '("cl-postgres/tests" "s-sql/tests"))
729 ;; ... test output ...
732 To run the tests from command-line specify the same forms using your
733 implementation's command-line syntax. For instance, to test all
734 Postmodern components on SBCL, use the following command:
737 env DB_USER=$USER sbcl --noinform \
738 --eval '(ql:quickload "postmodern/tests")' \
739 --eval '(ql:quickload "cl-postgres/tests")' \
740 --eval '(ql:quickload "s-sql/tests")' \
741 --eval '(ql:quickload "simple-date/tests")' \
742 --eval '(progn (setq 5am:*print-names* nil) (5am:run-all-tests))' \
743 --eval '(sb-ext:exit)'
746 As you can see from above, database connection parameters can be
747 provided using environment variables:
749 - `DB_NAME`: database name,
751 - `DB_PASS`: password,
752 - `DB_HOST`: hostname.