Next: , Previous: Result Transforms, Up: Top


14 Single-Table Abstraction

Sometimes it is convenient to focus on a single table, adding rows to it or drawing queries from it exclusively of any other tables in the database. Likewise with a view, except that only queries are possible. This chapter describes Guile-PG facilities for this kind of use.

To get started, load the postgres-table module:

     (use-modules (database postgres-table))

Basically, the pgtable-manager procedure encapsulates specification, query and mutation (including create/delete) of a PostgreSQL table; and the pgtable-worker procedure encapsulates pgtable-manager.

[NOTE: docs missing for pgtable-manager]

[NOTE: docs missing for compile-outspec]

[NOTE: docs missing for pgtable-worker]

The other procedures are useful for succinctly codifying queries, and translating the result en mass to Scheme objects. [NOTE: These will definitely migrate to other modules at some point before 1.0 release.]

[NOTE: docs missing for sql-pre]

The rest of this chapter is an extended example showing some of the uses of pgtable-manager.

     (define m (pgtable-manager "ttn" "guile_pg_demo"
                                '((i          serial)
                                  (date       timestamp)
                                  (amount     float4)
                                  (catcode    text)
                                  (details    text[]))))
     
     ((m #:create))
     ⇒ #<PG-RESULT:COMMAND_OK:0:0>
     
     (define add (m #:insert-col-values))
     (define sel (m #:select))
     
     (add '(date amount) (current-time) 1.98)
     ⇒ #<PG-RESULT:COMMAND_OK:0:0>
     
     (add '(date amount) (current-time) 2.98)
     ⇒ #<PG-RESULT:COMMAND_OK:0:0>
     
     (define (under n)
       (sel '((integer #f (count *)))  ;; outspec
            #:where `(< amount ,n)))   ;; prefix-style expression
     
     (define result (under 2.00))
     
     result
     ⇒ #<PG-RESULT:TUPLES_OK:1:1>
     
     ((m #:tuples-result->object-alist) result)
     ⇒ ((count 1))
     
     ((m #:drop))
     ⇒ (#<PG-RESULT:COMMAND_OK:0:0> #<PG-RESULT:COMMAND_OK:0:0>)

Two things to note in this example: (1) Both #:create and #:drop invocations evaluate the operating thunk directly (double parentheses); and (2) The drop returns a list of result values to accommodate the possibility (shown here) of a serial column type, which requires an additional drop of the associated PostgreSQL sequence used to implement the expected serial behavior. (As of PostgreSQL 7.x, the sequence name is constructed like so: TABLENAME_COLNAME_seq. For more info, see the PostgreSQL User Guide, Chapter 3: Data Types.)