API for clojure.java.jdbc - JDBC-based SQL Interface 0.3.0 (in development)

by Stephen C. Gilardi, Sean Corfield

Full namespace name: clojure.java.jdbc

Overview

A Clojure interface to SQL databases via JDBC

clojure.java.jdbc provides a simple abstraction for CRUD (create, read,
update, delete) operations on a SQL database, along with basic transaction
support. Basic DDL operations are also supported (create table, drop table,
access to table metadata).

Maps are used to represent records, making it easy to store and retrieve
data. Results can be processed using any standard sequence operations.

For most operations, Java's PreparedStatement is used so your SQL and
parameters can be represented as simple vectors where the first element
is the SQL string, with ? for each parameter, and the remaining elements
are the parameter values to be substituted. In general, operations return
the number of rows affected, except for a single record insert where any
generated keys are returned (as a map).

As of release 0.3.0, the API has undergone a major overhaul and most of the
original API has been deprecated in favor of a more idiomatic API, and a
minimal DSL for generating SQL has been added as an option. The original
API is still supported but will be deprecated before a 1.0.0 release is
made at some future date.

Related documentation:
Manipulating Data with SQL

Manipulating Tables with DDL

Mapping Keywords to/from Entity Names

Connection Pooling

Protocols



IResultSetReadColumn

Protocol
Protocol for reading objects from the java.sql.ResultSet. Default
implementations (for Object and nil) return the argument, but it can
be extended to provide custom behavior for special types.
Known implementations: nil, Object

result-set-read-column

function
Usage: (result-set-read-column val rsmeta idx)
Function for transforming values after reading them
from the database
Source

Public Variables and Functions



connection

function
Usage: (connection)
Returns the current database connection (or throws if there is none)
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


create-table

function
Usage: (create-table name & specs)
Creates a table on the open database connection given a table name and
specs. Each spec is either a column spec: a vector containing a column
name and optionally a type and other constraints, or a table-level
constraint: a vector containing words that express the constraint. An
optional suffix to the CREATE TABLE DDL describing table attributes may
by provided as :table-spec {table-attributes-string}. All words used to
describe the table may be supplied as strings or keywords.
Source


create-table-ddl

function
Usage: (create-table-ddl name & specs)
Given a table name and column specs with an optional table-spec
return the DDL string for creating a table based on that.
Source


db-connection

function
Usage: (db-connection db)
Returns the current database connection (or throws if there is none)
Source


db-do-commands

function
Usage: (db-do-commands db transaction? & commands)
Executes SQL commands on the specified database connection. Wraps the commands
in a transaction if transaction? is true.
Source


db-do-prepared

function
Usage: (db-do-prepared db transaction? sql & param-groups)
Executes an (optionally parameterized) SQL prepared statement on the
open database connection. Each param-group is a seq of values for all of
the parameters.
Return a seq of update counts (one count for each param-group).
Source


db-do-prepared-return-keys

function
Usage: (db-do-prepared-return-keys db transaction? sql param-group)
Executes an (optionally parameterized) SQL prepared statement on the
open database connection. The param-group is a seq of values for all of
the parameters.
Return the generated keys for the (single) update/insert.
Source


db-find-connection

function
Usage: (db-find-connection db)
Returns the current database connection (or nil if there is none)
Source


db-is-rollback-only

function
Usage: (db-is-rollback-only db)
Returns true if the outermost transaction will rollback rather than
commit when complete
Source


db-set-rollback-only!

function
Usage: (db-set-rollback-only! db)
Marks the outermost transaction such that it will rollback rather than
commit when complete
Source


db-transaction

macro
Usage: (db-transaction binding & body)
Evaluates body in the context of a transaction on the specified database connection.
The binding provides the database connection for the transaction and the name to which
that is bound for evaluation of the body.
See db-transaction* for more details.
Source


db-transaction*

function
Usage: (db-transaction* db func)
Evaluates func as a transaction on the open database connection. Any
nested transactions are absorbed into the outermost transaction. By
default, all database updates are committed together as a group after
evaluating the outermost body, or rolled back on any uncaught
exception. If rollback is set within scope of the outermost transaction,
the entire transaction will be rolled back rather than committed when
complete.
Source


db-unset-rollback-only!

function
Usage: (db-unset-rollback-only! db)
Marks the outermost transaction such that it will not rollback when complete
Source


delete!

function
Usage: (delete! db table where-clause & {:keys [entities transaction?], :or {entities as-is, transaction? true}})
Given a database connection, a table name and a where clause of columns to match,
perform a delete. The optional keyword arguments specify how to transform
column names in the map (default 'as-is') and whether to run the delete in
a transaction (default true).
Example:
  (delete! db :person (where {:zip 94546}))
is equivalent to:
  (execute! db ["DELETE FROM person WHERE zip = ?" 94546])
Source


delete-rows

function
Usage: (delete-rows table where-params)
Deletes rows from a table. where-params is a vector containing a string
providing the (optionally parameterized) selection criteria followed by
values for any parameters.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


do-commands

function
Usage: (do-commands & commands)
Executes SQL commands on the open database connection.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


do-prepared

function
Usage: (do-prepared sql & param-groups)
Executes an (optionally parameterized) SQL prepared statement on the
open database connection. Each param-group is a seq of values for all of
the parameters.
Return a seq of update counts (one count for each param-group).
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


do-prepared-return-keys

function
Usage: (do-prepared-return-keys sql param-group)
Executes an (optionally parameterized) SQL prepared statement on the
open database connection. The param-group is a seq of values for all of
the parameters.
Return the generated keys for the (single) update/insert.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


drop-table

function
Usage: (drop-table name)
Drops a table on the open database connection given its name, a string
or keyword
Source


execute!

function
Usage: (execute! db sql-params & {:keys [transaction? multi?], :or {transaction? true, multi? false}})
Given a database connection and a vector containing SQL and optional parameters,
perform a general (non-select) SQL operation. The optional keyword argument specifies
whether to run the operation in a transaction or not (default true).
Source


find-connection

function
Usage: (find-connection)
Returns the current database connection (or nil if there is none)
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


get-connection

function
Usage: (get-connection {:keys [connection factory connection-uri classname subprotocol subname datasource username password name environment], :as db-spec})
Creates a connection to a database. db-spec is a map containing connection
parameters. db-spec is a map containing values for one of the following
parameter sets:

Existing Connection:
  :connection  (required) an existing open connection that can be used
               but cannot be closed (only the parent connection can be closed)

Factory:
  :factory     (required) a function of one argument, a map of params
  (others)     (optional) passed to the factory function in a map

DriverManager:
  :subprotocol (required) a String, the jdbc subprotocol
  :subname     (required) a String, the jdbc subname
  :classname   (optional) a String, the jdbc driver class name
  (others)     (optional) passed to the driver as properties.

DataSource:
  :datasource  (required) a javax.sql.DataSource
  :username    (optional) a String
  :password    (optional) a String, required if :username is supplied

JNDI:
  :name        (required) a String or javax.naming.Name
  :environment (optional) a java.util.Map

Raw:
  :connection-uri (required) a String
               Passed directly to DriverManager/getConnection

URI:
  Parsed JDBC connection string - see below

String:
  subprotocol://user:password@host:post/subname
               An optional prefix of jdbc: is allowed.
Source


insert!

function
Usage: (insert! db table & options)
Given a database connection, a table name and either maps representing rows or
a list of column names followed by lists of column values, perform an insert.
Use :transaction? argument to specify whether to run in a transaction or not.
The default is true (use a transaction).
Source


insert-record

function
Usage: (insert-record table record)
Inserts a single record into a table. A record is a map from strings or
keywords (identifying columns) to values.
Returns a map of the generated keys.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


insert-records

function
Usage: (insert-records table & records)
Inserts records into a table. records are maps from strings or keywords
(identifying columns) to values. Inserts the records one at a time.
Returns a sequence of maps containing the generated keys for each record.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


insert-values

function
Usage: (insert-values table column-names & value-groups)
Inserts rows into a table with values for specified columns only.
column-names is a vector of strings or keywords identifying columns. Each
value-group is a vector containing a values for each column in
order. When inserting complete rows (all columns), consider using
insert-rows instead.
If a single set of values is inserted, returns a map of the generated keys.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


is-rollback-only

function
Usage: (is-rollback-only)
Returns true if the outermost transaction will rollback rather than
commit when complete
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


prepare-statement

function
Usage: (prepare-statement con sql & {:keys [return-keys result-type concurrency cursors fetch-size max-rows]})
Create a prepared statement from a connection, a SQL string and an
optional list of parameters:
  :return-keys true | false - default false
  :result-type :forward-only | :scroll-insensitive | :scroll-sensitive
  :concurrency :read-only | :updatable
  :cursors
  :fetch-size n
  :max-rows n
Source


print-sql-exception

function
Usage: (print-sql-exception exception)
Prints the contents of an SQLException to *out*
Source


print-sql-exception-chain

function
Usage: (print-sql-exception-chain exception)
Prints a chain of SQLExceptions to *out*
Source


print-update-counts

function
Usage: (print-update-counts exception)
Prints the update counts from a BatchUpdateException to *out*
Source


query

function
Usage: (query db sql-params & {:keys [result-set-fn row-fn identifiers as-arrays?], :or {result-set-fn doall, row-fn identity, identifiers lower-case}})
Given a database connection and a vector containing SQL and optional parameters,
perform a simple database query. The optional keyword arguments specify how to
construct the result set:
  :result-set-fn - applied to the entire result set, default doall
  :row-fn - applied to each row as the result set is constructed, default identity
  :identifiers - applied to each column name in the result set, default lower-case
  :as-arrays? - return the results as a set of arrays, default false.
Source


result-set-seq

function
Usage: (result-set-seq rs & {:keys [identifiers as-arrays?], :or {identifiers lower-case}})
Creates and returns a lazy sequence of maps corresponding to the rows in the
java.sql.ResultSet rs. Loosely based on clojure.core/resultset-seq but it
respects the specified naming strategy. Duplicate column names are made unique
by appending _N before applying the naming strategy (where N is a unique integer).
Source


set-rollback-only

function
Usage: (set-rollback-only)
Marks the outermost transaction such that it will rollback rather than
commit when complete
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


transaction

macro
Usage: (transaction & body)
Evaluates body as a transaction on the open database connection. Any
nested transactions are absorbed into the outermost transaction. By
default, all database updates are committed together as a group after
evaluating the outermost body, or rolled back on any uncaught
exception. If set-rollback-only is called within scope of the outermost
transaction, the entire transaction will be rolled back rather than
committed when complete.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


update!

function
Usage: (update! db table set-map where-clause & {:keys [entities transaction?], :or {entities as-is, transaction? true}})
Given a database connection, a table name, a map of column values to set and a
where clause of columns to match, perform an update. The optional keyword arguments
specify how column names (in the set / match maps) should be transformed (default
'as-is') and whether to run the update in a transaction (default true).
Example:
  (update! db :person {:zip 94540} (where {:zip 94546}))
is equivalent to:
  (execute! db ["UPDATE person SET zip = ? WHERE zip = ?" 94540 94546])
Source


update-or-insert-values

function
Usage: (update-or-insert-values table where-params record)
Updates values on selected rows in a table, or inserts a new row when no
existing row matches the selection criteria. where-params is a vector
containing a string providing the (optionally parameterized) selection
criteria followed by values for any parameters. record is a map from
strings or keywords (identifying columns) to updated values.
Source


update-values

function
Usage: (update-values table where-params record)
Updates values on selected rows in a table. where-params is a vector
containing a string providing the (optionally parameterized) selection
criteria followed by values for any parameters. record is a map from
strings or keywords (identifying columns) to updated values.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


with-connection

macro
Usage: (with-connection db-spec & body)
Evaluates body in the context of a new connection to a database then
closes the connection.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


with-connection*

function
Usage: (with-connection* db-spec func)
Evaluates func in the context of a new connection to a database then
closes the connection.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


with-query-results

macro
Usage: (with-query-results results sql-params & body)
Executes a query, then evaluates body with results bound to a seq of the
results. sql-params is a vector containing either:
  [sql & params] - a SQL query, followed by any parameters it needs
  [stmt & params] - a PreparedStatement, followed by any parameters it needs
                    (the PreparedStatement already contains the SQL query)
  [options sql & params] - options and a SQL query for creating a
                    PreparedStatement, followed by any parameters it needs
See prepare-statement for supported options.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source


with-query-results*

function
Usage: (with-query-results* sql-params func)
Executes a query, then evaluates func passing in a seq of the results as
an argument. The first argument is a vector containing either:
  [sql & params] - a SQL query, followed by any parameters it needs
  [stmt & params] - a PreparedStatement, followed by any parameters it needs
                   (the PreparedStatement already contains the SQL query)
  [options sql & params] - options and a SQL query for creating a
                   PreparedStatement, followed by any parameters it needs
See prepare-statement for supported options.
Deprecated since JDBC-based SQL Interface version 0.3.0
Source

clojure.java.jdbc.sql

An optional DSL for generating SQL.

Intended to be used with clojure.java.jdbc, this provides a simple DSL -
Domain Specific Language - that generates raw SQL strings. Any other DSL
can be used instead. This DSL is entirely optional and is deliberately
not very sophisticated. It is sufficient to support the delete!, insert!
and update! high-level operations within clojure.java.jdbc directly.

Public Variables and Functions



as-quoted-str

function
Usage: (as-quoted-str q)
       (as-quoted-str q x)
Given a quoting pattern - either a single character or a vector pair of
characters - and a string, return the quoted string:
  (as-quoted-str X foo) will return XfooX
  (as-quoted-str [A B] foo) will return AfooB
Source


as-str

function
Usage: (as-str f)
       (as-str f x)
Given a naming strategy and a keyword, return the keyword as a
string per that naming strategy. Given (a naming strategy and)
a string, return it as-is.
A keyword of the form :x.y is treated as keywords :x and :y,
both are turned into strings via the naming strategy and then
joined back together so :x.y might become `x`.`y` if the naming
strategy quotes identifiers with `.
Source


delete

function
Usage: (delete table [where & params] & {:keys [entities], :or {entities as-is}})
Given a table name, a where class and its parameters and an optional entities spec,
return a vector of the SQL for that delete operation followed by its parameters. The
entities spec (default 'as-is') specifies how to transform column names.
Source


entities

macro
Usage: (entities entities sql)
Given an entities function and a SQL-generating DSL form, transform the DSL form
to inject an :entities keyword argument with the function at the end of each appropriate
form.
Source


identifiers

macro
Usage: (identifiers identifiers sql)
Given an identifiers function and a SQL-generating DSL form, transform the DSL form
to inject an :identifiers keyword argument with the function at the end of each
appropriate form.
Source


insert

function
Usage: (insert table & clauses)
Given a table name and either column names and values or maps representing rows, retun
return a vector of the SQL for that insert operation followed by its parameters. An
optional entities spec (default 'as-is') specifies how to transform column names.
Source


join

function
Usage: (join table on-map & {:keys [entities], :or {entities as-is}})
Given a table name and a map of how to join it (to the existing SQL fragment),
retun the SQL string for the JOIN clause. The optional entities spec (default 'as-is')
specifies how to transform column names.
Source


order-by

function
Usage: (order-by cols & {:keys [entities], :or {entities as-is}})
Given a sequence of column order specs, and an optional entities spec, return the
SQL string for the ORDER BY clause. A column order spec may be a column name or a
map of the column name to the desired order.
Source


select

function
Usage: (select col-seq table & clauses)
Given a sequence of column names (or *) and a table name, followed by optional SQL
clauses, return a vector for the SQL followed by its parameters. The general form is:
  (select [columns] table joins [where params] order-by options)
where joins are optional strings, as is order-by, and the where clause is a vector
of a where SQL clause followed by its parameters. The options may may include an
entities spec to specify how column names should be transformed.
The intent is that the joins, where clause and order by clause are generated by
other parts of the DSL:
  (select * {:person :p}
          (join {:address :a} {:p.addressId :a.id})
          (where {:a.zip 94546})
          (order-by :p.name))
Source


update

function
Usage: (update table set-map & where-etc)
Given a table name and a map of columns to set, and optional map of columns to
match (and an optional entities spec), return a vector of the SQL for that update
followed by its parameters. Example:
  (update :person {:zip 94540} (where {:zip 94546}))
returns:
  ["UPDATE person SET zip = ? WHERE zip = ?" 94540 94546]
Source


where

function
Usage: (where param-map & {:keys [entities], :or {entities as-is}})
Given a map of columns and values, return a vector containing the where clause SQL
followed by its parameters. Example:
  (where {:a 42 :b nil})
returns:
  ["a = ? AND b IS NULL" 42]
Source
Logo & site design by Tom Hickey.
Clojure auto-documentation system by Tom Faulhaber.