pax_global_header 0000666 0000000 0000000 00000000064 13132773030 0014511 g ustar 00root root 0000000 0000000 52 comment=7f24fdd6d16b13ed998ea3968ae6db5cde5f54a0
java.jdbc-java.jdbc-0.7.0/ 0000775 0000000 0000000 00000000000 13132773030 0015157 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/.gitignore 0000664 0000000 0000000 00000000275 13132773030 0017153 0 ustar 00root root 0000000 0000000 *.jar
.classpath
.project
.settings
/.lein-failures
/.lein-repl-history
/.nrepl-port
/clojure_test_*
bin
classes
derby.log
settings.xml
target
test-all.sh
/postgres-down.sh
/postgres-up.sh
java.jdbc-java.jdbc-0.7.0/CHANGES.md 0000664 0000000 0000000 00000072622 13132773030 0016562 0 ustar 00root root 0000000 0000000 Changes in 0.7.0
* `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL).
* Add better support for Oracle connections (default port to `1521`, support `:dbtype "oracle"` -- as `"oracle:thin"` -- and `:dbtype "oracle:oci"`, with `@` instead of `//` before host).
Changes in 0.7.0-beta5
* `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153).
* Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`.
Changes in 0.7.0-beta4
* `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`.
* Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there.
Changes in 0.7.0-beta3
* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152).
Changes in 0.7.0-beta2
* Support for Clojure 1.6.0 and earlier has been dropped -- breaking change.
* Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later!
* All public functions now have specs in the optional `clojure.java.jdbc.spec` namespace (requires `clojure.spec.alpha`).
* `reducible-query` and `reducible-result-set` use `IReduce` and correctly support the no-`init` arity of `reduce` by using the first row of the `ResultSet`, if present, as the (missing) `init` value, and only calling `f` with no arguments if the `ResultSet` is empty. The `init` arity of `reduce` only ever calls `f` with two arguments.
Changes in 0.7.0-beta1
* Support for Clojure 1.4.0 has been dropped -- breaking change.
* Optional spec support now uses `clojure.spec.alpha`.
* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99).
Changes in 0.7.0-alpha3
* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151).
* `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name.
Changes in 0.7.0-alpha2
* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150).
* `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149).
* Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://dev.clojure.org/jira/browse/JDBC-148).
* Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://dev.clojure.org/jira/browse/JDBC-145).
Changes in 0.7.0-alpha1 -- potentially breaking changes
* The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting).
* Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://dev.clojure.org/jira/browse/JDBC-147).
* All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://dev.clojure.org/jira/browse/JDBC-144).
* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141).
* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://dev.clojure.org/jira/browse/JDBC-137).
* Expanded optional `clojure.spec` coverage to almost the whole library API.
Changes in 0.6.2-alpha3
* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140).
* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139).
* Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138).
This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb).
Changes in 0.6.2-alpha2
* Updates to `clojure.spec` support to work properly with Clojure 1.9.0 Alpha 10.
Changes in 0.6.2-alpha1
* Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later).
* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136).
* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://dev.clojure.org/jira/browse/JDBC-135).
* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134).
* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133).
Changes in 0.6.1
* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values.
* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129).
Changes in 0.6.0
* `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126).
* `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause.
Changes in 0.6.0-rc2
* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125).
- Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell.
* `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence.
* `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`.
* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125).
* `find-by-keys` now accepts an `:order-by` option that specifies a sequence of orderings; an ordering is either a column (to sort ascending) or a map from column name to direct (`:asc` or `:desc`).
Changes in 0.6.0-rc1
* Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable).
* REMINDER: ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118).
- See alpha2 / alpha1 below for more details.
Changes in 0.6.0-alpha2
* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118).
- This removes deprecated functionality from db-do-commands and db-do-prepared* which should have been removed in Alpha 1.
* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124).
* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123).
Changes in 0.6.0-alpha1
* (ALMOST) ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118).
- See changes described in versions 0.5.5 through 0.5.8 for what was deprecated
- Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies!
- `db-transaction` (deprecated in version 0.3.0) has been removed
- The `java.jdbc.deprecated` namespace has been removed
Changes in 0.5.8
* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console.
* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console.
Changes in 0.5.7
* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/browse/JDBC-121).
Changes in 0.5.6
* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/browse/JDBC-120). If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console.
* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/browse/JDBC-119). If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console.
* NOTE: all deprecated functionality will go away in version 0.6.0!
Changes in 0.5.5
* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117). The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0.
Changes in 0.5.0
* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115).
* Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114).
* Drop Clojure 1.3 compatibility.
Changes in 0.4.2
* Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume.
* Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume.
* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107).
* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104).
* Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL.
Changes in 0.4.0 / 0.4.1
* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen.
* Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball.
* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109).
* Drop Clojure 1.2 compatibility.
Changes in 0.3.7
* Bump all driver versions in `project.clj` and re-test.
* Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver.
* Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106).
* Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker.
Changes in 0.3.6
* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102).
* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101).
* Add `:timeout` argument to `prepare-statement` [JDBC-100](http://dev.clojure.org/jira/browse/JDBC-100).
Changes in 0.3.5
* Reflection warnings on executeUpdate addressed.
* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://dev.clojure.org/jira/browse/JDBC-94).
* Add support for readonly transactions via :read-only? [JDBC-93](http://dev.clojure.org/jira/browse/JDBC-93).
Changes in 0.3.4
* execute! can now accept a PreparedStatement [JDBC-96](http://dev.clojure.org/jira/browse/JDBC-96).
* Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92).
* Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90).
Changes in 0.3.3
* Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89).
* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87).
* Support key/value configuration from URI (Phil Hagelberg).
Changes in 0.3.2
* Add nil protocol implementation to ISQLParameter.
Changes in 0.3.1 (broken)
* Improve docstrings and add :arglists for better auto-generated documentation.
* Make insert-sql private - technically a breaking change but it should never have been public: sorry folks!
* Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86).
* Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85).
* Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected.
Changes in 0.3.0
* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84).
* Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83).
* Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82).
* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://dev.clojure.org/jira/browse/JDBC-65).
Changes in 0.3.0-rc1
* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81).
* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80).
* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79).
* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77).
* Add support for :isolation in with-db-transaction [JDBC-75](http://dev.clojure.org/jira/browse/JDBC-75).
* Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74).
Changes in 0.3.0-beta2
* The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL).
* The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation.
Changes in 0.3.0-beta1
* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72).
* "h2" is recognized as a protocol shorthand for org.h2.Driver
* Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71).
* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69).
* New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63).
* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40).
Changes in 0.3.0-alpha5
* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53).
* Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/).
* Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html)
* Added Leiningen support for easier development/testing (Maven is still the primary build tool).
* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist
* Make transaction? boolean optional in various db-do-* functions
* Create clojure.java.jdbc.ddl namespace
* Add create-table, drop-table, create-index and drop-index
* Deprecate create-table, create-table-ddl and drop-table in main namespace
* Update README to clarify PostgreSQL instructions.
* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59)
* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57)
* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55)
* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53).
* Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/).
* Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html)
* Added Leiningen support for easier development/testing (Maven is still the primary build tool).
* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist
* Make transaction? boolean optional in various db-do-* functions
* It will ultimately change to a function argument I think when [JDBC-37](http://dev.clojure.org/jira/browser/JDBC-37) is dealt with
* Create clojure.java.jdbc.ddl namespace
* Add create-table and drop-table
* Deprecate create-table, create-table-ddl and drop-table in main namespace
* More DDL is coming soon
* Update README to clarify PostgreSQL instructions.
* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59)
* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57)
* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55)
Changes in 0.3.0-alpha4
* Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54)
* Allow order-by to accept empty sequence (and return empty string)
Changes in 0.3.0-alpha3
* Fix macro / import interaction by fully qualifying Connection type.
Changes in 0.3.0-alpha2
* Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection
* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46)
* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52)
* Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40))
* Rename :as-arrays to :as-arrays? since it is boolean
* Add curried version of clojure.java.jdbc.sql/as-quoted-str
* Officially deprecate resultset-seq
Changes in 0.3.0-alpha1
Major overhaul of the API and deprecation of most of the old API!
* Add insert!, query, update!, delete! and execute! high-level API
[JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20)
* Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20)
* Add db- prefixed versions of low-level API
* Add db-transaction macro:
```
(db-transaction [t-con db-spec]
(query t-con (select * :user (where {:id 42}))))
```
* Add result-set-seq as replacement for resultset-seq (which will be deprecated)
* Transaction now correctly rollback on non-Exception Throwables
[JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43)
* Rewrite old API functions in terms of new API, and deprecate old API
[JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43)
* Add :as-arrays to query / result-set-seq
[JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41)
* Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40)
and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18)
Note: JDBC-40 has been reverted in 0.3.0-alpha2 because it introduced regressions for PostgreSQL
* db-do-commands allows you to execute SQL without a transaction wrapping it
[JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38)
* Remove reflection warning from execute-batch
* Add notes to README about 3rd party database driver dependencies
* Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy
Changes in 0.2.3:
* as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b]
* Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34)
Changes in 0.2.2:
* Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33)
* Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32)
* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31)
Changes in 0.2.1:
* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29)
* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30)
Changes in 0.2.0:
* Merge internal namespace into main jdbc namespace and update symbol visibility / naming.
Changes in 0.1.4:
* Unwrap RTE for nested transaction exception (we already unwrapped top-level transaction RTEs).
* Remove reflection warning unwrapping RunTimeException (Alan Malloy)
Changes in 0.1.3:
* Fix JDBC-26 (fully) by adding transaction/generated keys support for SQLite3 (based on patch from Nelson Morris)
Changes in 0.1.2:
* Fix JDBC-23 by handling prepared statement params correctly (Ghadi Shayban)
* Fix JDBC-26 by adding support for SQLite3 (based on patch from Nelson Morris)
* Fix JDBC-27 by replacing replicate with repeat (Jonas Enlund)
* Ensure MS SQL Server passes tests with both Microsoft and jTDS drivers
* Build server now tests derby, hsqldb and sqlite by default
* Update README per Stuart Sierra's outline for contrib projects
Changes in 0.1.1:
* Fix JDBC-21 by adding support for db-spec as URI (Phil Hagelberg).
* Fix JDBC-22 by deducing driver class name from subprotocol (Phil Hagelberg).
* Add Postgres dependency so tests can be automcated (Phil Hagelberg).
* Add ability to specify test databases via TEST_DBS environment variable (Phil Hagelberg).
Changes in 0.1.0:
* Fix JDBC-15 by removing dependence on deprecated structmap.
Changes in 0.0.7:
* Fix JDBC-9 by renaming duplicate columns instead of throwing an exception.
- thanx to Peter Siewert!
* Fix JDBC-16 by ensuring do-prepared works with no param-groups provided.
* Fix JDBC-17 by adding type hints to remove more reflection warnings.
- thanx to Stuart Sierra!
Documentation:
* Address JDBC-4 by documenting how to do connection pooling.
Changes in 0.0.6:
* Move former tests to test-utilities namespace - these do not touch a database
* Convert old "test" examples into real tests against real databases
- tested locally against MySQL, Apache Derby, HSQLDB
- build system should run against Apache Derby, HSQLSB
- will add additional databases later
* Fix JDBC-12 by removing batch when doing a single update
* Remove wrapping of exceptions in transactions to make it easier to work with SQLExceptions
Changes in 0.0.5:
* Add prepare-statement function to ease creation of PreparedStatement with common options:
- see docstring for details
* with-query-results now allows the SQL/params vector to be:
- a PreparedStatement object, followed by any parameters the SQL needs
- a SQL query string, followed by any parameters it needs
- options (for prepareStatement), a SQL query string, followed by any parameters it needs
* Add support for databases that cannot return generated keys (e.g., HSQLDB)
- insert operations silently return the insert counts instead of generated keys
- it is the user's responsibility to handle this if you're using such a database!
Changes in 0.0.4:
* Fix JDBC-2 by allowing :table-spec {string} at the end of create-table arguments:
(sql/create-table :foo [:col1 "int"] ["col2" :int] :table-spec "ENGINE=MyISAM")
* Fix JDBC-8 by removing all reflection warnings
* Fix JDBC-11 by no longer committing the transaction when an Error occurs
* Clean up as-... functions to reduce use of (binding)
* Refactor do-prepared*, separating out return keys logic and parameter setting logic
- in preparation for exposing more hooks in PreparedStatement creation / manipulation
Changes in 0.0.3:
* Fix JDBC-10 by using .executeUpdate when generating keys (MS SQL Server, PostgreSQL compatibility issue)
Changes in 0.0.2:
* Fix JDBC-7 Clojure 1.2 compatibility (thanx to Aaron Bedra!)
Changes in 0.0.1 (compared to clojure.contrib.sql):
* Exposed print-... functions for exception printing; no longer writes exceptions to *out*
* Add clojure.java.jdbc/resultset-seq (to replace clojure.core/resultset-seq which should be deprecated)
* Add support for naming and quoting strategies - see http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/NameMapping.html
- The formatting is a bit borked, Tom F knows about this and is working on an enhancement to auto-doc to improve it
* Add ability to return generated keys from single insert operations, add insert-record function
* Clojure 1.3 compatibility
java.jdbc-java.jdbc-0.7.0/CONTRIBUTING.md 0000664 0000000 0000000 00000001220 13132773030 0017403 0 ustar 00root root 0000000 0000000 This is a [Clojure contrib] project.
Under the Clojure contrib [guidelines], this project cannot accept
pull requests. All patches must be submitted via [JIRA].
See [Contributing] and the [FAQ] on the Clojure development [wiki] for
more information on how to contribute.
[Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib
[Contributing]: http://dev.clojure.org/display/community/Contributing
[FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ
[JIRA]: http://dev.clojure.org/jira/browse/JDBC
[guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers
[wiki]: http://dev.clojure.org/
java.jdbc-java.jdbc-0.7.0/README.md 0000664 0000000 0000000 00000103642 13132773030 0016444 0 ustar 00root root 0000000 0000000 clojure.java.jdbc
========================================
A low-level Clojure wrapper for JDBC-based access to databases.
For DSLs that are compatible with this library, consider:
* [HoneySQL](https://github.com/jkk/honeysql)
* [SQLingvo](https://github.com/r0man/sqlingvo)
* [Korma](http://sqlkorma.com)
Formerly known as `clojure.contrib.sql`.
Additional documentation can be found in the [java.jdbc section of clojure-doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html) and there is a dedicated [java.jdbc mailing list](https://groups.google.com/forum/#!forum/clojure-java-jdbc)
Releases and Dependency Information
========================================
Latest stable release: 0.7.0 -- requires Clojure 1.7 or later!
* [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jdbc%22)
* [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~java.jdbc~~~)
[Leiningen](https://github.com/technomancy/leiningen) dependency information:
```clojure
[org.clojure/java.jdbc "0.7.0"]
```
[Maven](http://maven.apache.org/) dependency information:
```xml
org.clojure
java.jdbc
0.7.0
```
_Note: Earlier versions of Clojure are supported by older versions of `clojure.java.jdbc`: e.g., version 0.6.1 supports Clojure 1.4 and later._
You will also need to add dependencies for the JDBC driver you intend to use. Here are links (to Maven Central) for each of the common database drivers that clojure.java.jdbc is known to be used with:
* [Apache Derby](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.derby%22%20AND%20a%3A%22derby%22)
* [H2](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.h2database%22%20AND%20a%3A%22h2%22)
* [HSQLDB](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22hsqldb%22%20AND%20a%3A%22hsqldb%22)
* [Microsoft SQL Server jTDS](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.jtds%22%20AND%20a%3A%22jtds%22)
* [MySQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22mysql%22%20AND%20a%3A%22mysql-connector-java%22)
* [PostgreSQL](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.postgresql%22%20AND%20a%3A%22postgresql%22)
* [SQLite](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.xerial%22%20AND%20a%3A%22sqlite-jdbc%22)
Note: different versions of various database drivers have different Java/JVM version requirements. In particular, recent versions of Apache Derby require at least Java 8 and recent versions of H2 require at least Java 7. Clojure's Continuous Integration system uses older versions so tests can be run on Java 6 (see `pom.xml`); local testing is done with more recent versions on Java 8.
`clojure.java.jdbc` is also tested against Microsoft's own JDBC4 Driver 4.0 but that
has to be [downloaded manually](https://www.microsoft.com/en-us/download/details.aspx?id=11774) and placed in a Maven repository accessible to your system. For testing, it was installed locally as:
```clojure
;; Microsoft SQL Server JDBC4 Driver 4.0
[sqljdbc4/sqljdbc4 "4.0"]
```
Example Usage
========================================
```clojure
(require '[clojure.java.jdbc :as j])
;; there are many ways to write a db-spec but the easiest way is to
;; use :dbtype and then provide the :dbname and any of :user, :password,
;; :host, :port, and other options as needed:
(def mysql-db {:dbtype "mysql"
:dbname "clojure_test"
:user "clojure_test"
:password "clojure_test"})
(def pg-db {:dbtype "postgresql"
:dbname "mypgdatabase"
:host "mydb.server.com"
:user "myuser"
:password "secret"
:ssl true
:sslfactory "org.postgresql.ssl.NonValidatingFactory"})
;; if the dbtype is not known to clojure.java.jdbc, or you want to override the
;; default choice of JDBC driver class name, you can provide :classname and the
;; name of the class to use:
(def redshift42 {:dbtype "redshift"
:dbname "myredstore"
:classname "com.amazon.redshift.jdbc42.Driver"
...})
;; you can also specify a full connection string if you'd prefer:
(def pg-uri
{:connection-uri (str "postgresql://myuser:secret@mydb.server.com:5432/mypgdatabase"
"?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory")})
(j/insert-multi! mysql-db :fruit
[{:name "Apple" :appearance "rosy" :cost 24}
{:name "Orange" :appearance "round" :cost 49}])
;; ({:generated_key 1} {:generated_key 2})
(j/query mysql-db
["select * from fruit where appearance = ?" "rosy"]
{:row-fn :cost})
;; (24)
```
For more detail see the [generated documentation on github](http://clojure.github.com/java.jdbc/).
Developer Information
========================================
* [GitHub project](https://github.com/clojure/java.jdbc)
* [Bug Tracker](http://dev.clojure.org/jira/browse/JDBC)
* [Continuous Integration](http://build.clojure.org/job/java.jdbc/)
* [Compatibility Test Matrix](http://build.clojure.org/job/java.jdbc-test-matrix/)
* Testing:
* Currently by default tests run only against Derby and HSQLDB, the in-process databases.
* To test against PostgreSQL, first create the user and database:
$ sudo -u postgres createuser clojure_test -P clojure_test
$ sudo -u postgres createdb clojure_test -O clojure_test
* Or similarly with MySQL:
$ mysql -u root
mysql> create database clojure_test;
mysql> grant all on clojure_test.* to clojure_test identified by "clojure_test";
* Then run the tests with the TEST_DBS environment variable:
$ TEST_DBS=mysql,postgres mvn test
Change Log
====================
Release 0.7.0 on 2017-07-16
* `:conditional?` option for `create-table-ddl` and `drop-table-ddl` to provide for existence check (or a function to manipulate the generated DDL).
* Add better support for Oracle connections (default port to `1521`, support `:dbtype "oracle"` -- as `"oracle:thin"` -- and `:dbtype "oracle:oci"`, with `@` instead of `//` before host).
Release 0.7.0-beta5 on 2017-07-05
* `get-connection` now accepts an `opts` map with `:auto-commit?` and `:read-only?` options. If present, the appropriate methods will be called on the connection obtained. These options are valid in any function call that may call `get-connection` under the hood. This should allow for streaming results in a query for most databases [JDBC-153](https://dev.clojure.org/jira/browse/JDBC-153).
* Additional validation of options is performed in `prepared-statement` to avoid silently ignoring invalid combinations of `:concurrency`, `:cursors`, `:result-type`, and `:return-keys`.
Release 0.7.0-beta4 on 2017-07-04
* `opts` are now correctly passed from `reducible-query` to `db-query-with-resultset`.
* Updated the `::query-options` spec to make it clear that `::prepare-options` are also acceptable there.
Release 0.7.0-beta3 on 2017-07-04
* Reflection warnings removed in `reducible-result-set` [JDBC-152](https://dev.clojure.org/jira/browse/JDBC-152).
Release 0.7.0-beta2 on 2017-06-30 (a.k.a The Reducible Saga, Part 2)
* Support for Clojure 1.5 and 1.6 has been dropped -- breaking change.
* Or, put another way, `clojure.java.jdbc` now requires Clojure 1.7 or later!
* All public functions now have specs in the optional `clojure.java.jdbc.spec` namespace (requires `clojure.spec.alpha`).
* `reducible-query` and `reducible-result-set` use `IReduce` and correctly support the no-`init` arity of `reduce` by using the first row of the `ResultSet`, if present, as the (missing) `init` value, and only calling `f` with no arguments if the `ResultSet` is empty. The `init` arity of `reduce` only ever calls `f` with two arguments.
Release 0.7.0-beta1 on 2017-06-29
* Support for Clojure 1.4.0 has been dropped -- breaking change.
* Optional spec support now uses `clojure.spec.alpha`.
* `reducible-query` accepts a `db-spec` and a SQL/parameters vector and returns a reducible (`IReduce` on Clojure 1.7 or later; `CollReduce` on Clojure 1.5/1.6): when reduced, it runs the query, obtains a reducible result set, and then reduces that. A reducible query will run the query each time it is reduced. The helper function `reducible-result-set` is public: it accepts a `ResultSet` and produces a reducible that offers a single pass reduce over the rows. Both functions honor `reduced` values to short-circuit the process [JDBC-99](https://dev.clojure.org/jira/browse/JDBC-99).
Release 0.7.0-alpha3 on 2017-03-23
* `classname` is now accepted with `dbtype` / `dbname` so you can easily specify a JDBC driver class name for a database type that is not known [JDBC-151](http://dev.clojure.org/jira/browse/JDBC-151).
* `redshift` has been added as a `dbtype` with `com.amazon.redshift.jdbc.Driver` as the driver name.
* Release 0.7.0-alpha2 on 2017-03-01
* `pgsql` and the Impossibl PostgresSQL 'NG' driver are now supported (note that `:max-rows` does not work with this driver!); also, providing unknown `dbtype` or `subprotocol` in a `db-spec` should now throw a better exception [JDBC-150](http://dev.clojure.org/jira/browse/JDBC-150).
* `quoted` now accepts keywords for database / dialect (`:ansi` (including PostgresSQL), `:mysql`, `:oracle`, `:sqlserver` -- these match the keywords used in HoneySQL which is the recommended third party SQL DSL for java.jdbc) [JDBC-149](http://dev.clojure.org/jira/browse/JDBC-149).
* Reorder `get-connection` clauses to make it easier to combine keys in a `db-spec` [JDBC-148](http://dev.clojure.org/jira/browse/JDBC-148).
* Force load `DriverManager` before `classForName` call on drivers to avoid potential race condition on initialization [JDBC-145](http://dev.clojure.org/jira/browse/JDBC-145).
* Release 0.7.0-alpha1 on 2016-11-12 -- potentially breaking changes
* The signatures of `as-sql-name` and `quoted` have changed slightly: the former no longer has the curried (single argument) version, and the latter no longer has the two argument version. This change came out of a discussion on Slack which indicated curried functions are non-idiomatic. If you relied on the curried version of `as-sql-name`, you will not need to use `partial`. If you relied on the two argument version of `quoted`, you will need to add an extra `( )` for the one argument call. I'd be fairly surprised if anyone is using `as-sql-name` at all since it is really an implementation detail. I'd also be surprised if anyone was using the two argument version of `quoted` since the natural usage is `:entities (quoted [\[ \]])` to create a naming strategy (that provides SQL entity quoting).
* Clarified that `insert-multi!` with a sequence of row maps may be substantially slower than with a sequence of row value vectors (the former performs an insert for each row, the latter performs a single insert for all the data together) [JDBC-147](http://dev.clojure.org/jira/browse/JDBC-147).
* All options are passed through all function calls, expanding the range of options you can pass into high-level functions such as `insert!` and `update!` [JDBC-144](http://dev.clojure.org/jira/browse/JDBC-144).
* Added `get-isolation-level` to return the current transaction's isolation level, if any [JDBC-141](http://dev.clojure.org/jira/browse/JDBC-141).
* Added support for `read-columns` option to allow more flexible customization of reading column values from a result set (particularly in a multi-database application). Also expands `set-parameters` support to options (previously it was just part of the db-spec) [JDBC-137](http://dev.clojure.org/jira/browse/JDBC-137).
* Expanded optional `clojure.spec` coverage to almost the whole library API.
* Release 0.6.2-alpha3 on 2016-08-25
* Fixed bad interaction between `:qualifier` and existing `:identifiers` functionality [JDBC-140](http://dev.clojure.org/jira/browse/JDBC-140).
* Updated the README and docstrings to reflect that `:dbtype` is the easiest / preferred way to write `db-spec` maps [JDBC-139](http://dev.clojure.org/jira/browse/JDBC-139).
* Fixed postgres / postgresql alias support [JDBC-138](http://dev.clojure.org/jira/browse/JDBC-138).
This also adds aliases for mssql (sqlserver), jtds (jtds:sqlserver), oracle (oracle:thin), and hsql (hsqldb).
* Release 0.6.2-alpha2 on 2016-07-21
* Update `clojure.spec` support to work with Clojure 1.9.0 Alpha 10.
* Release 0.6.2-alpha1 on 2016-07-05
* Experimental support for `clojure.spec` via the new `clojure.java.jdbc.spec` namespace. Requires Clojure 1.9.0 Alpha 8 (or later).
* All options to all functions can now have defaults within the `db-spec` itself [JDBC-136](http://dev.clojure.org/jira/browse/JDBC-136).
* `query` (and by extension `find-by-keys` and `get-by-id`) now support `:explain?` and `:explain-fn` options to help support basic performance analysis [JDBC-135](http://dev.clojure.org/jira/browse/JDBC-135).
* `insert!` and `insert-multi!` now respect `:identifiers` and `:qualifier` because inserting rows on PostgreSQL returns full rows, not just the newly inserted keys [JDBC-134](http://dev.clojure.org/jira/browse/JDBC-134).
* In addition to the `:identifiers` option, you can now use `:qualifier` to specify a namespace qualifier (string) to be used when constructing keywords from SQL column names [JDBC-133](http://dev.clojure.org/jira/browse/JDBC-133).
* Release 0.6.1 on 2016-05-12 -- **IMPORTANT BUG FIX!**
* `insert!` and `insert-multi!` now default `:transaction?` to `true` (as they should have done in 0.6.0!) [JDBC-128](http://dev.clojure.org/jira/browse/JDBC-128). These two functions also have improved docstrings to clarify the difference in behavior between inserting rows as maps compared to inserting rows as a series of column values.
* PostgreSQL support has been improved: java.jdbc is now tested against PostgreSQL locally (as well as SQLite, Apache Derby, HSQLDB, H2, MySQL, MS SQL Server (both MS Type 4 driver and jTDS driver). [JDBC-127](http://dev.clojure.org/jira/browse/JDBC-127) and [JDBC-129](http://dev.clojure.org/jira/browse/JDBC-129).
* Release 0.6.0 on 2016-05-11 -- **BREAKING RELEASE! DEPRECATED FUNCTIONALITY REMOVED!**
* `find-by-keys` now correctly handles `nil` values [JDBC-126](http://dev.clojure.org/jira/browse/JDBC-126). 0.6.0 / 2016-05-11.
* `find-by-keys` calls `seq` on `:order-by` to treat `[]` as no `ORDER BY` clause. 0.6.0 / 2016-05-11.
* `db-query-with-resultset` now accepts an options map and passes it to `prepare-statement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07.
- Passing the `prepare-statement` options map as the first element of the `[sql & params]` vector is no longer supported and will throw an `IllegalArgumentException`. It was always very poorly documented and almost never used, as far as I can tell.
* `db-query-with-resultset` no longer requires the `sql-params` argument to be a vector: a sequence is acceptable. This is in line with other functions that accept a sequence. 0.6.0-rc2 / 2016-05-07.
* `db-query-with-resultset` now accepts a bare SQL string or `PreparedStatement` as the `sql-params` argument, when there are no parameters needed. This is in line with other functions that accept SQL or a `PreparedStatement`. 0.6.0-rc2 / 2016-05-07.
* `query`'s options map now is passed to `db-query-with-resultset` and thus can contain options to be used to construct the `PreparedStatement` [JDBC-125](http://dev.clojure.org/jira/browse/JDBC-125). 0.6.0-rc2 / 2016-05-07.
* Adds `get-by-id` and `find-by-keys` convenience functions (these were easy to add after the API changes in 0.6.0 and we rely very heavily on them at World Singles so putting them in the core for everyone seemed reasonable). 0.6.0-rc1 / 2016-05-04.
- `find-by-keys` accepts an `:order-by` option that expects a sequence of orderings; an ordering is a column name (keyword) or a map from column name (keyword) to direction (`:asc` or `:desc`). 0.6.0-rc2 / 2016-05-07.
* Ensures SQL / params are actually vectors prior to destructuring (this addresses an interop edge case from other languages) [JDBC-124](http://dev.clojure.org/jira/browse/JDBC-124). 0.6.0-alpha2 / 2016-04-18.
* Fix typo in `insert-multi!` argument validation exception [JDBC-123](http://dev.clojure.org/jira/browse/JDBC-123). 0.6.0-alpha2 / 2016-04-18.
* ALL DEPRECATED FUNCTIONALITY HAS BEEN REMOVED! [JDBC-118](http://dev.clojure.org/jira/browse/JDBC-118). 0.6.0-alpha1 / 2016-04-13
- See changes described in versions 0.5.5 through 0.5.8 for what was deprecated
- Use version 0.5.8 as a bridge to identify any deprecated API calls on which your code relies!
- `db-transaction` (deprecated in version 0.3.0) has been removed
- The `java.jdbc.deprecated` namespace has been removed
* Release 0.5.8 on 2016-04-12
* `db-do-commands` now expects multiple commands to be be wrapped in a vector [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). The single command form is unchanged (but may be wrapped in a vector). Calling `db-do-commands` with multiple commands (not wrapped in a single vector) will produce a "DEPRECATED" warning printed to the console.
* `db-do-prepared` and `db-do-prepared-return-keys` now expect to receive a `db-spec`, an optional `transaction?` boolean, a `sql-params` argument, and an optional options map. `sql-params` is a vector containing a SQL string or `PreparedStatement` followed by parameters -- like other APIs in this library. In addition, like the `:multi? true` version of `execute!`, `db-do-prepared` can accept a vector that has parameter groups: multiple vectors containing groups of parameter values [JDBC-122](http://dev.clojure.org/jira/browse/JDBC-123). Calling `db-do-prepared` with unrolled arguments -- the SQL string / statement followed by parameter groups -- is deprecated and will produce "DEPRECATED" warnings printed to the console.
* Release 0.5.7 on 2016-04-10
* `(insert! db table [:col] ["val"] {})` syntax, introduced in 0.5.6, threw an exception [JDBC-121](http://dev.clojure.org/jira/browse/JDBC-121).
* Release 0.5.6 on 2016-04-10
* `create-table-ddl` now expects the column specs to be wrapped in a single vector and no longer needs the `:options` delimiter to specify the options map [JDBC-120](http://dev.clojure.org/jira/browse/JDBC-120).
- If column specs are not wrapped in a vector, you will get a "DEPRECATED" warning printed to the console.
* `insert!` now supports only single row insertion; multi-row insertion is deprecated. `insert-multi!` has been added for multi-row insertion. `:options` is no longer needed as a delimiter for the options map [JDBC-119](http://dev.clojure.org/jira/browse/JDBC-119).
- If `insert!` is called with multiple rows, or `:options` is specified, you will get a "DEPRECATED" warning printed to the console.
* NOTE: all deprecated functionality will go away in version 0.6.0!
* Release 0.5.5 on 2016-04-09
* Allow options map in all calls that previously took optional keyword arguments [JDBC-117](http://dev.clojure.org/jira/browse/JDBC-117).
- The unrolled keyword argument forms of call are deprecated -- and print a "DEPRECATED" message to the console! -- and will go away in 0.6.0.
* Release 0.5.0 on 2016-03-27
* Allow PreparedStatement in db-do-prepared-return-keys [JDBC-115](http://dev.clojure.org/jira/browse/JDBC-115).
* Remove exception wrapping [JDBC-114](http://dev.clojure.org/jira/browse/JDBC-114).
* Drop Clojure 1.3 compatibility.
* Release 0.4.2 on 2015-09-15
* Remove redundant type hints [JDBC-113](http://dev.clojure.org/jira/browse/JDBC-113) - Michael Blume.
* Avoid reflection on `.prepareStatement` [JDBC-112](http://dev.clojure.org/jira/browse/JDBC-112) - Michael Blume.
* Add `metadata-query` macro to make metadata query / results easier to work with for [JDBC-107](http://dev.clojure.org/jira/browse/JDBC-107).
* `prepare-statement` `:return-keys` may now be a vector of (auto-generated) column names to return, in addition to just being truthy or falsey. This allows keys to be returned for more databases. [JDBC-104](http://dev.clojure.org/jira/browse/JDBC-104).
* Officially support H2 (and test against it) to support [JDBC-91](http://dev.clojure.org/jira/browse/JDBC-91) and clarify docstrings to improve debugging driver-specific restrictions on SQL.
* Release 0.4.0 / 0.4.1 on 2015-07-26
* `db-do-prepared` now allows `transaction?` to be omitted when a `PreparedStatement` is passed as the second argument [JDBC-111](http://dev.clojure.org/jira/browse/JDBC-111) - Stefan Kamphausen.
* Nested transaction checks isolation level is the same [JDBC-110](http://dev.clojure.org/jira/browse/JDBC-110) - Donald Ball.
* Default PostgreSQL port; Support more dbtype/dbname variants [JDBC-109](http://dev.clojure.org/jira/browse/JDBC-109).
* Drop Clojure 1.2 compatibility.
* Release 0.3.7 on 2015-05-18
* Bump all driver versions in `project.clj` and re-test.
* Remove duplicate `count` calls in `insert-sql` [JDBC-108](http://dev.clojure.org/jira/browse/JDBC-108) - Earl St Sauver.
* Remove driver versions from README and link to Maven Central [JDBC-106](http://dev.clojure.org/jira/browse/JDBC-106).
* Fix links in CHANGES and README [JDBC-103](http://dev.clojure.org/jira/browse/JDBC-103) - John Walker.
* Release 0.3.6 on 2014-10-28
* Arbitrary values allowed for `:cursors`, `:concurrency`, `:result-type` arguments to `prepare-statement` [JDBC-102](http://dev.clojure.org/jira/browse/JDBC-102).
* Allow `:as-arrays? :cols-as-is` to omit column name uniqueness when returning result sets as arrrays [JDBC-101](http://dev.clojure.org/jira/browse/JDBC-101).
* Add `:timeout` argument to `prepare-statement` [JDBC-100](http://dev.clojure.org/jira/browse/JDBC-100).
* Release 0.3.5 on 2014-08-01
* Reflection warnings on executeUpdate addressed.
* HSQLDB and SQLite in-memory strings are now accepted [JDBC-94](http://dev.clojure.org/jira/browse/JDBC-94).
* Add support for readonly transactions via :read-only? [JDBC-93](http://dev.clojure.org/jira/browse/JDBC-93).
* Release 0.3.4 on 2014-06-30
* execute! can now accept a PreparedStatement [JDBC-96](http://dev.clojure.org/jira/browse/JDBC-96).
* Support simpler db-spec with :dbtype and :dbname (and optional :host and :port etc) [JDBC-92](http://dev.clojure.org/jire/browse/JDBC-92).
* Support oracle:oci and oracle:thin subprotocols [JDBC-90](http://dev.clojure.org/jira/browse/JDBC-90).
* Release 0.3.3 on 2014-01-30
* Prevent exception/crash when query called with bare SQL string [JDBC-89](http://dev.clojure.org/jira/browse/JDBC-89).
* Add :row-fn and :result-set-fn to metadata-result function [JDBC-87](http://dev.clojure.org/jira/browse/JDBC-87).
* Support key/value configuration from URI (Phil Hagelberg).
* Release 0.3.2 on 2013-12-30
* Add nil protocol implementation to ISQLParameter
* Release 0.3.1 on 2013-12-29 (broken; use 0.3.2 instead)
* Improve docstrings and add :arglists for better auto-generated documentation.
* Make insert-sql private - technically a breaking change but it should never have been public: sorry folks!
* Provide better protocol for setting parameters in prepared statements [JDBC-86](http://dev.clojure.org/jira/browse/JDBC-86).
* Fix parens in two deprecated tests [JDBC-85](http://dev.clojure.org/jira/browse/JDBC-85).
* Made create-table-ddl less aggressive about applying as-sql-name so only first name in a column spec is affected.
* Release 0.3.0 on 2013-12-16
* Ensure canonical Boolean to workaround strange behavior in some JDBC drivers [JDBC-84](http://dev.clojure.org/jira/browse/JDBC-84).
* Rename recently introduced test to ensure unique names [JDBC-83](http://dev.clojure.org/jira/browse/JDBC-83).
* Rename unused arguments in protocol implementation to support Android [JDBC-82](http://dev.clojure.org/jira/browse/JDBC-82).
* Correctly handle empty param group sequence in execute! (which only seemed to affect SQLite) [JDBC-65](http://dev.clojure.org/jira/browse/JDBC-65).
* Release 0.3.0-rc1 on 2013-12-12
* Deprecate db-transaction (new in 0.3.0) in favor of with-db-transaction [JDBC-81](http://dev.clojure.org/jira/browse/JDBC-81).
* Add with-db-metadata macro and metadata-result function to make it easier to work with SQL metadata [JDBC-80](http://dev.clojure.org/jira/browse/JDBC-80).
* Add with-db-connection macro to make it easier to run groups of operations against a single open connection [JDBC-79](http://dev.clojure.org/jira/browse/JDBC-79).
* Add ISQLValue protocol to make it easier to support custom SQL types for parameters in SQL statements [JDBC-77](http://dev.clojure.org/jira/browse/JDBC-77).
* Add support for :isolation in with-db-transaction [JDBC-75](http://dev.clojure.org/jira/browse/JDBC-75).
* Add :user as an alias for :username for DataSource connections [JDBC-74](http://dev.clojure.org/jira/browse/JDBC-74).
* Release 0.3.0-beta2 on 2013-11-24
* **BREAKING CHANGES!**
* The DSL namespaces introduced in 0.3.0-alpha1 have been retired - see [java-jdbc/dsl](https://github.com/seancorfield/jsql) for a migration path if you wish to continue using the DSL (although it is recommended you switch to another, more expressive DSL).
* The older API (0.2.3) which was deprecated in earlier 0.3.0 builds has moved to `clojure.java.jdbc.deprecated` to help streamline the API for 0.3.0 and clean up the documentation.
* Release 0.3.0-beta1 on 2013-11-03
* query as-arrays? now allows you to leverage lazy result fetching [JDBC-72](http://dev.clojure.org/jira/browse/JDBC-72).
* "h2" is recognized as a protocol shorthand for org.h2.Driver
* Tests no longer use :1 literal [JDBC-71](http://dev.clojure.org/jira/browse/JDBC-71).
* Conditional use of javax.naming.InitialContext so it can be compiled on Android [JDBC-69](http://dev.clojure.org/jira/browse/JDBC-69).
* New db-query-with-resultset function replaces private db-with-query-results* and processes a raw ResultSet object [JDBC-63](http://dev.clojure.org/jira/browse/JDBC-63).
* Allow :set-parameters in db-spec to override set-parameters internal function to allow per-DB special handling of SQL parameters values (such as null for Teradata) [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40).
* Release 0.3.0-alpha5 on 2013-09-15
* DDL now supports entities naming strategy [JDBC-53](http://dev.clojure.org/jira/browse/JDBC-53).
* Attempt to address potential memory leaks due to closures - see [Christophe Grand's blog post on Macros, closures and unexpected object retention](http://clj-me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/).
* Documentation has moved to [Using java.jdbc on Clojure-Doc.org](http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html)
* Added Leiningen support for easier development/testing (Maven is still the primary build tool).
* Added create-index / drop-index DDL [JDBC-62](http://dev.clojure.org/jira/browse/JDBC-62) - moquist
* Make transaction? boolean optional in various db-do-* functions
* Create clojure.java.jdbc.ddl namespace
* Add create-table, drop-table, create-index and drop-index
* Deprecate create-table, create-table-ddl and drop-table in main namespace
* Update README to clarify PostgreSQL instructions.
* Fix test suite for PostgreSQL [JDBC-59](http://dev.clojure.org/jira/browser/JDBC-59)
* Improve hooks for Oracle data type handling [JDBC-57](http://dev.clojure.org/jira/browser/JDBC-57)
* Fix reflection warnings [JDBC-55](http://dev.clojure.org/jira/browser/JDBC-55)
* Release 0.3.0-alpha4 on 2013-05-11
* Fix connection leaks [JDBC-54](http://dev.clojure.org/jira/browser/JDBC-54)
* Allow order-by to accept empty sequence (and return empty string)
* Release 0.3.0-alpha3 on 2013-05-04
* Fix macro / import interaction by fully qualifying Connection type.
* Release 0.3.0-alpha2 on 2013-05-03
* Address [JDBC-51](http://dev.clojure.org/jira/browse/JDBC-51) by declaring get-connection returns java.sql.Connection
* Add IResultSetReadColumn protocol extension point for custom read conversions [JDBC-46](http://dev.clojure.org/jira/browse/JDBC-46)
* Add :multi? to execute! so it can be used for repeated operations [JDBC-52](http://dev.clojure.org/jira/browse/JDBC-52)
* Reverted specialized handling of NULL values (reopens [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40))
* Rename :as-arrays to :as-arrays? since it is boolean
* Add curried version of clojure.java.jdbc.sql/as-quoted-str
* Officially deprecate resultset-seq
* Release 0.3.0-alpha1 on 2013-04-07
* MAJOR API OVERHAUL!
* Most of the old 0.2.x API has been deprecated and a new, more idiomatic API introduced, along with a minimal DSL to generate basic SQL
* Specifics:
* Add insert!, query, update!, delete! and execute! high-level API [JDBC-20](http://dev.clojure.org/jira/browse/JDBC-20)
* Add optional SQL-generating DSL in clojure.java.jdbc.sql (implied by JDBC-20)
* Add db- prefixed versions of low-level API
* Add db-transaction macro
* Add result-set-seq as replacement for resultset-seq (which will be deprecated)
* Transaction now correctly rollback on non-Exception Throwables [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43)
* Rewrite old API functions in terms of new API, and deprecate old API [JDBC-43](http://dev.clojure.org/jira/browse/JDBC-43)
* Add :as-arrays to query / result-set-seq [JDBC-41](http://dev.clojure.org/jira/browse/JDBC-41)
* Better handling of NULL values [JDBC-40](http://dev.clojure.org/jira/browse/JDBC-40) and [JDBC-18](http://dev.clojure.org/jira/browse/JDBC-18)
Note: JDBC-40 is being reverted in 0.3.0-alpha2 because it introduces regressions in PostgreSQL
* db-do-commands allows you to execute SQL without a transaction wrapping it [JDBC-38](http://dev.clojure.org/jira/browse/JDBC-38)
* Remove reflection warning from execute-batch
* Add notes to README about 3rd party database driver dependencies
* Add optional :identifiers argument to resultset-seq so you can explicitly pass in the naming strategy
* Release 0.2.3 on 2012-06-18
* as-str now treats a.b as two identifiers separated by . so quoting produces [a].[b] instead of [a.b]
* Add :connection-uri option [JDBC-34](http://dev.clojure.org/jira/browse/JDBC-34)
* Release 0.2.2 on 2012-06-10
* Handle Oracle unknown row count affected [JDBC-33](http://dev.clojure.org/jira/browse/JDBC-33)
* Handle jdbc: prefix in string db-specs [JDBC-32](http://dev.clojure.org/jira/browse/JDBC-32)
* Handle empty columns in make column unique (Juergen Hoetzel) [JDBC-31](http://dev.clojure.org/jira/browse/JDBC-31)
* Release 0.2.1 on 2012-05-10
* Result set performance enhancement (Juergen Hoetzel) [JDBC-29](http://dev.clojure.org/jira/browse/JDBC-29)
* Make do-prepared-return-keys (for Korma team) [JDBC-30](http://dev.clojure.org/jira/browse/JDBC-30)
* Release 0.2.0 on 2012-04-23
* Merge internal namespace into main jdbc namespace [JDBC-19](http://dev.clojure.org/jira/browse/JDBC-19)
* Release 0.1.4 on 2012-04-15
* Unwrap RTE for nested transaction exceptions (we already
unwrapped top-level transaction RTEs).
* Remove reflection warning unwrapping RunTimeException (Alan Malloy)
* Release 0.1.3 on 2012-02-29
* Fix generated keys inside transactions for SQLite3 [JDBC-26](http://dev.clojure.org/jira/browse/JDBC-26)
* Release 0.1.2 on 2012-02-29
* Handle prepared statement params correctly [JDBC-23](http://dev.clojure.org/jira/browse/JDBC-23)
* Add support for SQLite3 [JDBC-26](http://dev.clojure.org/jira/browse/JDBC-26)
* Replace replicate (deprecated) with repeat [JDBC-27](http://dev.clojure.org/jira/browse/JDBC-27)
* Ensure MS SQL Server passes tests with both Microsoft and jTDS drivers
* Build server now tests derby, hsqldb and sqlite by default
* Update README per Stuart Sierra's outline for contrib projects
* Release 0.1.1 on 2011-11-02
* Accept string or URI in connection definition [JDBC-21](http://dev.clojure.org/jira/browse/JDBC-21)
* Allow driver, port and subprotocol to be deduced [JDBC-22](http://dev.clojure.org/jira/browse/JDBC-22)
* Release 0.1.0 on 2011-10-16
* Remove dependence on deprecated structmap [JDBC-15](http://dev.clojure.org/jira/browse/JDBC-15)
* Release 0.0.7 on 2011-10-11
* Rename duplicate columns [JDBC-9](http://dev.clojure.org/jira/browse/JDBC-9)
* Ensure do-preared traps invalid SQL [JDBC-16](http://dev.clojure.org/jira/browse/JDBC-16)
* Release 0.0.6 on 2011-08-04
* Improve exception handling (unwrap RTE)
* Don't use batch for update (causes exceptions on Apache Derby) [JDBC-12](http://dev.clojure.org/jire/JDBC-12)
* Add test suite
* Release 0.0.5 on 2011-07-18
* Expose prepare-statement API
* Allow with-query-results to accept a PreparedStatement or options for creating one, instead of SQL query string and parameters
* Support databases that cannot return generated keys
* Release 0.0.4 on 2011-07-17
* Allow :table-spec {string} in create-table [JDBC-4](http://dev.clojure.org/jire/JDBC-4)
* Remove reflection warnings [JDBC-8](http://dev.clojure.org/jire/JDBC-8)
* Ensure transactions are not committed when Error occurs [JDBC-11](http://dev.clojure.org/jire/JDBC-11)
* Release 0.0.3 on 2011-07-01
* Key generation compatibility with MS SQL Server, PostgreSQL [JDBC-10](http://dev.clojure.org/jira/browse/JDBC-10)
* Release 0.0.2 on 2011-06-07
* Clojure 1.2 compatibility [JDBC-7](http://dev.clojure.org/jira/browse/JDBC-7)
* Release 0.0.1 on 2011-05-07
* Initial release
* Changes from clojure.contrib.sql:
* Expose print-... functions; no longer write exceptions to **\*out\***
* Define resultset-seq to replace clojure.core/resultset-seq
* Add naming / quoting strategies (see [name mapping documentation](http://clojure.github.com/java.jdbc/doc/clojure/java/jdbc/NameMapping.html)
* Return generated keys from insert operations, where possible
* Add insert-record function
* Clojure 1.3 compatibility
Copyright and License
========================================
Copyright (c) Sean Corfield, Stephen Gilardi, 2011-2014. All rights reserved. The use and
distribution terms for this software are covered by the Eclipse Public
License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license. You must not remove this notice, or any
other, from this software.
java.jdbc-java.jdbc-0.7.0/epl.html 0000664 0000000 0000000 00000030536 13132773030 0016634 0 ustar 00root root 0000000 0000000
Eclipse Public License - Version 1.0
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial
code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that particular Contributor. A
Contribution 'originates' from a Contributor if it was added to the
Program by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include additions to the
Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii)
are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents" mean patent claims licensable by a
Contributor which are necessarily infringed by the use or sale of its
Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance
with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free copyright license to reproduce, prepare derivative works
of, publicly display, publicly perform, distribute and sublicense the
Contribution of such Contributor, if any, and such derivative works, in
source code and object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the Contribution of such
Contributor, if any, in source code and object code form. This patent
license shall apply to the combination of the Contribution and the
Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor
grants the licenses to its Contributions set forth herein, no assurances
are provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity. Each
Contributor disclaims any liability to Recipient for claims brought by
any other entity based on infringement of intellectual property rights
or otherwise. As a condition to exercising the rights and licenses
granted hereunder, each Recipient hereby assumes sole responsibility to
secure any other intellectual property rights needed, if any. For
example, if a third party patent license is required to allow Recipient
to distribute the Program, it is Recipient's responsibility to acquire
that license before distributing the Program.
d) Each Contributor represents that to its knowledge it
has sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code
form under its own license agreement, provided that:
a) it complies with the terms and conditions of this
Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors
all warranties and conditions, express and implied, including warranties
or conditions of title and non-infringement, and implied warranties or
conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors
all liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this
Agreement are offered by that Contributor alone and not by any other
party; and
iv) states that source code for the Program is available
from such Contributor, and informs licensees how to obtain it in a
reasonable manner on or through a medium customarily used for software
exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each
copy of the Program.
Contributors may not remove or alter any copyright notices contained
within the Program.
Each Contributor must identify itself as the originator of its
Contribution, if any, in a manner that reasonably allows subsequent
Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business partners and the
like. While this license is intended to facilitate the commercial use of
the Program, the Contributor who includes the Program in a commercial
product offering should do so in a manner which does not create
potential liability for other Contributors. Therefore, if a Contributor
includes the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and
indemnify every other Contributor ("Indemnified Contributor")
against any losses, damages and costs (collectively "Losses")
arising from claims, lawsuits and other legal actions brought by a third
party against the Indemnified Contributor to the extent caused by the
acts or omissions of such Commercial Contributor in connection with its
distribution of the Program in a commercial product offering. The
obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In
order to qualify, an Indemnified Contributor must: a) promptly notify
the Commercial Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the Commercial
Contributor in, the defense and any related settlement negotiations. The
Indemnified Contributor may participate in any such claim at its own
expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other
Contributor to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement , including but not limited to
the risks and costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and unavailability or
interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further action
by the parties hereto, such provision shall be reformed to the minimum
extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's patent(s), then such
Recipient's rights granted under Section 2(b) shall terminate as of the
date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of time
after becoming aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease use and
distribution of the Program as soon as reasonably practicable. However,
Recipient's obligations under this Agreement and any licenses granted by
Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this
Agreement, but in order to avoid inconsistency the Agreement is
copyrighted and may only be modified in the following manner. The
Agreement Steward reserves the right to publish new versions (including
revisions) of this Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement. The Eclipse
Foundation is the initial Agreement Steward. The Eclipse Foundation may
assign the responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the Agreement will be
given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version
of the Agreement is published, Contributor may elect to distribute the
Program (including its Contributions) under the new version. Except as
expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
rights or licenses to the intellectual property of any Contributor under
this Agreement, whether expressly, by implication, estoppel or
otherwise. All rights in the Program not expressly granted under this
Agreement are reserved.
This Agreement is governed by the laws of the State of New York and
the intellectual property laws of the United States of America. No party
to this Agreement will bring a legal action under this Agreement more
than one year after the cause of action arose. Each party waives its
rights to a jury trial in any resulting litigation.
java.jdbc-java.jdbc-0.7.0/pom.xml 0000664 0000000 0000000 00000006766 13132773030 0016513 0 ustar 00root root 0000000 0000000
4.0.0
java.jdbc
0.7.0
java.jdbc
org.clojure
pom.contrib
0.2.2
Stephen C. Gilardi
Sean Corfield
scm:git:git@github.com:clojure/java.jdbc.git
scm:git:git@github.com:clojure/java.jdbc.git
git@github.com:clojure/java.jdbc.git
java.jdbc-0.7.0
1.7.0
com.theoryinpractise
clojure-maven-plugin
1.7.1
true
${clojure.warnOnReflection}
true
clojure-compile
none
clojure-test
test
test
mysql
mysql-connector-java
5.1.41
test
org.apache.derby
derby
10.12.1.1
test
org.hsqldb
hsqldb
2.3.4
test
com.h2database
h2
1.4.191
test
org.postgresql
postgresql
9.4.1212.jre7
test
org.xerial
sqlite-jdbc
3.16.1
test
net.sourceforge.jtds
jtds
1.3.1
test
org.clojure
test.check
0.9.0
test
java.jdbc-java.jdbc-0.7.0/project.clj 0000664 0000000 0000000 00000004510 13132773030 0017317 0 ustar 00root root 0000000 0000000 ;; NOTE: This project.clj file exists purely to make it easier to
;; develop and test java.jdbc locally. The pom.xml file is the
;; "system of record" as far as the project version is concerned.
(defproject org.clojure/java.jdbc "0.7.0-SNAPSHOT"
:description "A low-level Clojure wrapper for JDBC-based access to databases."
:parent [org.clojure/pom.contrib "0.1.2"]
:url "https://github.com/clojure/java.jdbc"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:dependencies [[org.clojure/clojure "1.9.0-alpha17"]
;; These are just the versions most recently test against
;; for your own projects, use whatever version is most
;; appropriate for you. Again, note that this project.clj
;; file exists for convenience -- the pom.xml file is the
;; "system of record" as far as dependencies go!
;; Note: 1.12.1.1 is used in pom.xml for Java 6/7 compat
[org.apache.derby/derby "10.13.1.1"]
[org.hsqldb/hsqldb "2.3.4"]
;; Note: 1.4.191 is used in pom.xml for Java 6 compat
[com.h2database/h2 "1.4.193"]
[net.sourceforge.jtds/jtds "1.3.1"]
;; Tests fail with 6.0.2 driver:
[mysql/mysql-connector-java "5.1.41"]
[org.postgresql/postgresql "9.4.1212.jre7"]
[com.impossibl.pgjdbc-ng/pgjdbc-ng "0.7.1"]
[org.xerial/sqlite-jdbc "3.16.1"]
;; if you have the MS driver in your local repo
[sqljdbc4 "4.0"]]
:profiles {:1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0-master-SNAPSHOT"]]}
:dev {:dependencies [[org.clojure/test.check "0.9.0"]]}}
:repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"
"ws-archiva" "https://d259tvauhnips9.cloudfront.net/archiva/repository/internal/"}
;; include dev profile with 1.9 to pull in test.check
:aliases {"test-all" ["with-profile" "test,1.7:test,1.8:dev,test,1.9" "test"]}
:min-lein-version "2.0.0")
java.jdbc-java.jdbc-0.7.0/src/ 0000775 0000000 0000000 00000000000 13132773030 0015746 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/main/ 0000775 0000000 0000000 00000000000 13132773030 0016672 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/main/clojure/ 0000775 0000000 0000000 00000000000 13132773030 0020335 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/main/clojure/clojure/ 0000775 0000000 0000000 00000000000 13132773030 0022000 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/main/clojure/clojure/java/ 0000775 0000000 0000000 00000000000 13132773030 0022721 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/main/clojure/clojure/java/jdbc.clj 0000664 0000000 0000000 00000175145 13132773030 0024332 0 ustar 00root root 0000000 0000000 ;; Copyright (c) 2008-2017 Sean Corfield, Stephen C. Gilardi. All rights reserved.
;; The use and distribution terms for this software are covered by
;; the Eclipse Public License 1.0
;; (http://opensource.org/licenses/eclipse-1.0.php) which can be
;; found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be
;; bound by the terms of this license. You must not remove this
;; notice, or any other, from this software.
;;
;; jdbc.clj
;;
;; A Clojure interface to sql databases via jdbc
;;
;; scgilardi (gmail)
;; Created 2 April 2008
;;
;; seancorfield (gmail)
;; Migrated from clojure.contrib.sql 17 April 2011
(ns
^{:author "Stephen C. Gilardi, Sean Corfield",
:doc "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).
For more documentation, see:
http://clojure-doc.org/articles/ecosystem/java_jdbc/home.html"}
clojure.java.jdbc
(:require [clojure.set :as set]
[clojure.string :as str]
[clojure.walk :as walk])
(:import (java.net URI)
(java.sql BatchUpdateException DriverManager
PreparedStatement ResultSet ResultSetMetaData
SQLException Statement Types)
(java.util Hashtable Map Properties)
(javax.sql DataSource)))
(defn as-sql-name
"Given a naming strategy function and a keyword or string, return
a string per that naming strategy.
A name of the form x.y is treated as multiple names, x, y, etc,
and each 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 `."
[f x]
(let [n (name x)
i (.indexOf n (int \.))]
(if (= -1 i)
(f n)
(str/join "." (map f (.split n "\\."))))))
(defn quoted
"Given a (vector) pair of delimiters (characters or strings), return a naming
strategy function that will quote SQL entities with them.
Given a single delimiter, treat it as a (vector) pair of that delimiter.
((quoted [\\[ \\]]) \"foo\") will return \"[foo]\" -- for MS SQL Server
((quoted \\`') \"foo\") will return \"`foo`\" -- for MySQL
Intended to be used with :entities to provide a quoting (naming) strategy that
is appropriate for your database."
[q]
(cond (vector? q)
(fn [x]
(str (first q) x (last q)))
(keyword? q)
(case q
:ansi (quoted \")
:mysql (quoted \`)
:oracle (quoted \")
:sqlserver (quoted [\[ \]]))
:else
(quoted [q q])))
(defn- table-str
"Transform a table spec to an entity name for SQL. The table spec may be a
string, a keyword or a map with a single pair - table name and alias."
[table entities]
(let [entities (or entities identity)]
(if (map? table)
(let [[k v] (first table)]
(str (as-sql-name entities k) " " (as-sql-name entities v)))
(as-sql-name entities table))))
(defn- kv-sql
"Given a sequence of column name keys and a matching sequence of column
values, and an entities mapping function, return a sequence of SQL fragments
that can be joined for part of an UPDATE SET or a SELECT WHERE clause.
Note that we pass the appropriate operator for NULL since it is different
in each case."
[ks vs entities null-op]
(map (fn [k v]
(str (as-sql-name entities k)
(if (nil? v) null-op " = ?")))
ks vs))
(defn- ^Properties as-properties
"Convert any seq of pairs to a java.utils.Properties instance.
Uses as-sql-name to convert both keys and values into strings."
[m]
(let [p (Properties.)]
(doseq [[k v] m]
(.setProperty p (as-sql-name identity k)
(if (instance? clojure.lang.Named v)
(as-sql-name identity v)
(str v))))
p))
;; convenience for working with different forms of connections
(defprotocol Connectable
(add-connection [db connection])
(get-level [db]))
(defn- inc-level
"Increment the nesting level for a transacted database connection.
If we are at the top level, also add in a rollback state."
[db]
(let [nested-db (update-in db [:level] (fnil inc 0))]
(if (= 1 (:level nested-db))
(assoc nested-db :rollback (atom false))
nested-db)))
(extend-protocol Connectable
String
(add-connection [s connection] {:connection connection :level 0 :connection-string s})
(get-level [_] 0)
clojure.lang.Associative
(add-connection [m connection] (assoc m :connection connection))
(get-level [m] (or (:level m) 0))
nil
(add-connection [_ connection] {:connection connection :level 0 :legacy true})
(get-level [_] 0))
(def ^:private classnames
"Map of subprotocols to classnames. dbtype specifies one of these keys.
The subprotocols map below provides aliases for dbtype."
{"derby" "org.apache.derby.jdbc.EmbeddedDriver"
"h2" "org.h2.Driver"
"hsqldb" "org.hsqldb.jdbcDriver"
"jtds:sqlserver" "net.sourceforge.jtds.jdbc.Driver"
"mysql" "com.mysql.jdbc.Driver"
"oracle:oci" "oracle.jdbc.OracleDriver"
"oracle:thin" "oracle.jdbc.OracleDriver"
"postgresql" "org.postgresql.Driver"
"pgsql" "com.impossibl.postgres.jdbc.PGDriver"
"redshift" "com.amazon.redshift.jdbc.Driver"
"sqlite" "org.sqlite.JDBC"
"sqlserver" "com.microsoft.sqlserver.jdbc.SQLServerDriver"})
(def ^:private subprotocols
"Map of schemes to subprotocols. Used to provide aliases for dbtype."
{"hsql" "hsqldb"
"jtds" "jtds:sqlserver"
"mssql" "sqlserver"
"oracle" "oracle:thin"
"postgres" "postgresql"})
(def ^:private host-prefixes
"Map of subprotocols to non-standard host-prefixes.
Anything not listed is assumed to use //."
{"oracle:oci" "@"
"oracle:thin" "@"})
(defn- parse-properties-uri [^URI uri]
(let [host (.getHost uri)
port (if (pos? (.getPort uri)) (.getPort uri))
path (.getPath uri)
scheme (.getScheme uri)
subprotocol (subprotocols scheme scheme)
host-prefix (host-prefixes subprotocol "//")
^String query (.getQuery uri)
query-parts (and query (for [^String kvs (.split query "&")]
(vec (.split kvs "="))))]
(merge
{:subname (if host
(if port
(str host-prefix host ":" port path)
(str host-prefix host path))
(.getSchemeSpecificPart uri))
:subprotocol subprotocol}
(if-let [user-info (.getUserInfo uri)]
{:user (first (str/split user-info #":"))
:password (second (str/split user-info #":"))})
(walk/keywordize-keys (into {} query-parts)))))
(defn- strip-jdbc [^String spec]
(if (.startsWith spec "jdbc:")
(.substring spec 5)
spec))
;; feature testing macro, based on suggestion from Chas Emerick:
(defmacro when-available
[sym & body]
(try
(when (resolve sym)
(list* 'do body))
(catch ClassNotFoundException _#)))
(defn- modify-connection
"Given a database connection and a map of options, update the connection
as specified by the options."
^java.sql.Connection
[^java.sql.Connection connection opts]
(when (contains? opts :auto-commit?)
(.setAutoCommit connection (:auto-commit? opts)))
(when (contains? opts :read-only?)
(.setReadOnly connection (:read-only? opts)))
connection)
(defn get-connection
"Creates a connection to a database. db-spec is usually a map containing connection
parameters but can also be a URI or a String. The various possibilities are described
below:
DriverManager (preferred):
:dbtype (required) a String, the type of the database (the jdbc subprotocol)
:dbname (required) a String, the name of the database
:classname (optional) a String, the jdbc driver class name
:host (optional) a String, the host name/IP of the database
(defaults to 127.0.0.1)
:port (optional) a Long, the port of the database
(defaults to 3306 for mysql, 1433 for mssql/jtds, else nil)
(others) (optional) passed to the driver as properties.
Raw:
:connection-uri (required) a String
Passed directly to DriverManager/getConnection
Other formats accepted:
Existing Connection:
:connection (required) an existing open connection that can be used
but cannot be closed (only the parent connection can be closed)
DriverManager (alternative / legacy style):
: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.
Factory:
:factory (required) a function of one argument, a map of params
(others) (optional) passed to the factory function in a map
DataSource:
:datasource (required) a javax.sql.DataSource
:username (optional) a String
:user (optional) a String - an alternate alias for :username
(added after 0.3.0-beta2 for consistency JDBC-74)
:password (optional) a String, required if :username is supplied
JNDI:
:name (required) a String or javax.naming.Name
:environment (optional) a java.util.Map
java.net.URI:
Parsed JDBC connection string (see java.lang.String format next)
java.lang.String:
subprotocol://user:password@host:post/subname
An optional prefix of jdbc: is allowed."
(^java.sql.Connection [db-spec] (get-connection db-spec {}))
(^java.sql.Connection
[{:keys [connection
factory
connection-uri
classname subprotocol subname
dbtype dbname host port
datasource username password user
name environment]
:as db-spec}
opts]
(cond
(string? db-spec)
(get-connection (URI. (strip-jdbc db-spec)) opts)
(instance? URI db-spec)
(get-connection (parse-properties-uri db-spec) opts)
connection
connection ;; do not apply opts here
(or (and datasource username password)
(and datasource user password))
(-> (.getConnection ^DataSource datasource
^String (or username user)
^String password)
(modify-connection opts))
datasource
(-> (.getConnection ^DataSource datasource)
(modify-connection opts))
factory
(-> (factory (dissoc db-spec :factory))
(modify-connection opts))
connection-uri
(-> (DriverManager/getConnection connection-uri)
(modify-connection opts))
(and dbtype dbname)
(let [;; allow aliases for dbtype
subprotocol (subprotocols dbtype dbtype)
host (or host "127.0.0.1")
port (or port (condp = subprotocol
"jtds:sqlserver" 1433
"mysql" 3306
"oracle:oci" 1521
"oracle:thin" 1521
"postgresql" 5432
"sqlserver" 1433
nil))
db-sep (if (= "sqlserver" subprotocol) ";DATABASENAME=" "/")
url (if (#{"derby" "h2" "hsqldb" "sqlite"} subprotocol)
(str "jdbc:" subprotocol ":" dbname)
(str "jdbc:" subprotocol ":"
(host-prefixes subprotocol "//")
host
(when port (str ":" port))
db-sep dbname))
etc (dissoc db-spec :dbtype :dbname)]
(if-let [class-name (or classname (classnames subprotocol))]
(do
;; force DriverManager to be loaded
(DriverManager/getLoginTimeout)
(clojure.lang.RT/loadClassForName class-name))
(throw (ex-info (str "Unknown dbtype: " dbtype) db-spec)))
(-> (DriverManager/getConnection url (as-properties etc))
(modify-connection opts)))
(and subprotocol subname)
(let [;; allow aliases for subprotocols
subprotocol (subprotocols subprotocol subprotocol)
url (format "jdbc:%s:%s" subprotocol subname)
etc (dissoc db-spec :classname :subprotocol :subname)]
(if-let [class-name (or classname (classnames subprotocol))]
(do
;; force DriverManager to be loaded
(DriverManager/getLoginTimeout)
(clojure.lang.RT/loadClassForName class-name))
(throw (ex-info (str "Unknown subprotocol: " subprotocol) db-spec)))
(-> (DriverManager/getConnection url (as-properties etc))
(modify-connection opts)))
name
(or (when-available javax.naming.InitialContext
(let [env (and environment (Hashtable. ^Map environment))
context (javax.naming.InitialContext. env)
^DataSource datasource (.lookup context ^String name)]
(-> (.getConnection datasource)
(modify-connection opts))))
(throw (ex-info (str "javax.naming.InitialContext is not available for: "
name)
db-spec)))
:else
(let [^String msg (format "db-spec %s is missing a required parameter" db-spec)]
(throw (IllegalArgumentException. msg))))))
(defn- make-name-unique
"Given a collection of column names and a new column name,
return the new column name made unique, if necessary, by
appending _N where N is some unique integer suffix."
[cols col-name n]
(let [suffixed-name (if (= n 1) col-name (str col-name "_" n))]
(if (apply distinct? suffixed-name cols)
suffixed-name
(recur cols col-name (inc n)))))
(defn- make-cols-unique
"Given a collection of column names, rename duplicates so
that the result is a collection of unique column names."
[cols]
(if (or (empty? cols) (apply distinct? cols))
cols
(reduce (fn [unique-cols col-name]
(conj unique-cols (make-name-unique unique-cols col-name 1))) [] cols)))
(defprotocol ISQLValue
"Protocol for creating SQL values from Clojure values. Default
implementations (for Object and nil) just return the argument,
but it can be extended to provide custom behavior to support
exotic types supported by different databases."
(sql-value [val] "Convert a Clojure value into a SQL value."))
(extend-protocol ISQLValue
Object
(sql-value [v] v)
nil
(sql-value [_] nil))
(defprotocol ISQLParameter
"Protocol for setting SQL parameters in statement objects, which
can convert from Clojure values. The default implementation just
delegates the conversion to ISQLValue's sql-value conversion and
uses .setObject on the parameter. It can be extended to use other
methods of PreparedStatement to convert and set parameter values."
(set-parameter [val stmt ix]
"Convert a Clojure value into a SQL value and store it as the ix'th
parameter in the given SQL statement object."))
(extend-protocol ISQLParameter
Object
(set-parameter [v ^PreparedStatement s ^long i]
(.setObject s i (sql-value v)))
nil
(set-parameter [_ ^PreparedStatement s ^long i]
(.setObject s i (sql-value nil))))
(defn- dft-set-parameters
"Default implementation of parameter setting for the given statement."
[stmt params]
(dorun (map-indexed (fn [ix value]
(set-parameter value stmt (inc ix)))
params)))
(defprotocol IResultSetReadColumn
"Protocol for reading objects from the java.sql.ResultSet. Default
implementations (for Object and nil) return the argument, and the
Boolean implementation ensures a canonicalized true/false value,
but it can be extended to provide custom behavior for special types."
(result-set-read-column [val rsmeta idx]
"Function for transforming values after reading them from the database"))
(extend-protocol IResultSetReadColumn
Object
(result-set-read-column [x _2 _3] x)
Boolean
(result-set-read-column [x _2 _3] (if (= true x) true false))
nil
(result-set-read-column [_1 _2 _3] nil))
(defn- dft-read-columns
"Default implementation of reading row values from result set, given the
result set metadata and the indices."
[^ResultSet rs rsmeta idxs]
(mapv (fn [^Integer i] (result-set-read-column (.getObject rs i) rsmeta i)) idxs))
(defn result-set-seq
"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),
unless the :as-arrays? option is :cols-as-is, in which case the column names
are untouched (the result set maintains column name/value order).
The :identifiers option specifies how SQL column names are converted to Clojure
keywords. The default is to convert them to lower case.
The :qualifier option specifies the namespace qualifier for those identifiers."
([rs] (result-set-seq rs {}))
([^ResultSet rs {:keys [as-arrays? identifiers qualifier read-columns]
:or {identifiers str/lower-case
read-columns dft-read-columns}}]
(let [rsmeta (.getMetaData rs)
idxs (range 1 (inc (.getColumnCount rsmeta)))
col-name-fn (if (= :cols-as-is as-arrays?) identity make-cols-unique)
identifier-fn (if qualifier
(comp (partial keyword qualifier) identifiers)
(comp keyword identifiers))
keys (->> idxs
(mapv (fn [^Integer i] (.getColumnLabel rsmeta i)))
col-name-fn
(mapv identifier-fn))
row-values (fn [] (read-columns rs rsmeta idxs))
;; This used to use create-struct (on keys) and then struct to populate each row.
;; That had the side effect of preserving the order of columns in each row. As
;; part of JDBC-15, this was changed because structmaps are deprecated. We don't
;; want to switch to records so we're using regular maps instead. We no longer
;; guarantee column order in rows but using into {} should preserve order for up
;; to 16 columns (because it will use a PersistentArrayMap). If someone is relying
;; on the order-preserving behavior of structmaps, we can reconsider...
records (fn thisfn []
(when (.next rs)
(cons (zipmap keys (row-values)) (lazy-seq (thisfn)))))
rows (fn thisfn []
(when (.next rs)
(cons (vec (row-values)) (lazy-seq (thisfn)))))]
(if as-arrays?
(cons (vec keys) (rows))
(records)))))
(defn- execute-batch
"Executes a batch of SQL commands and returns a sequence of update counts.
(-2) indicates a single operation operating on an unknown number of rows.
Specifically, Oracle returns that and we must call getUpdateCount() to get
the actual number of rows affected. In general, operations return an array
of update counts, so this may not be a general solution for Oracle..."
[^Statement stmt]
(let [result (.executeBatch stmt)]
(if (and (= 1 (count result)) (= -2 (first result)))
(list (.getUpdateCount stmt))
(seq result))))
(def ^{:private true
:doc "Map friendly :concurrency values to ResultSet constants."}
result-set-concurrency
{:read-only ResultSet/CONCUR_READ_ONLY
:updatable ResultSet/CONCUR_UPDATABLE})
(def ^{:private true
:doc "Map friendly :cursors values to ResultSet constants."}
result-set-holdability
{:hold ResultSet/HOLD_CURSORS_OVER_COMMIT
:close ResultSet/CLOSE_CURSORS_AT_COMMIT})
(def ^{:private true
:doc "Map friendly :type values to ResultSet constants."}
result-set-type
{:forward-only ResultSet/TYPE_FORWARD_ONLY
:scroll-insensitive ResultSet/TYPE_SCROLL_INSENSITIVE
:scroll-sensitive ResultSet/TYPE_SCROLL_SENSITIVE})
(defn ^{:tag (class (into-array String []))} string-array
[return-keys]
(into-array String return-keys))
(defn prepare-statement
"Create a prepared statement from a connection, a SQL string and a map
of options:
:return-keys truthy | nil - default nil
for some drivers, this may be a vector of column names to identify
the generated keys to return, otherwise it should just be true
:result-type :forward-only | :scroll-insensitive | :scroll-sensitive
:concurrency :read-only | :updatable
:cursors
:fetch-size n
:max-rows n
:timeout n
Note that :result-type and :concurrency must be specified together as the
underlying Java API expects both (or neither)."
([con sql] (prepare-statement con sql {}))
([^java.sql.Connection con ^String sql
{:keys [return-keys result-type concurrency cursors
fetch-size max-rows timeout]}]
(let [^PreparedStatement
stmt (cond return-keys
(try
(when (or result-type concurrency cursors)
(throw (IllegalArgumentException.
(str ":concurrency, :cursors, and :result-type "
"may not be specified with :return-keys."))))
(if (vector? return-keys)
(try
(.prepareStatement con sql (string-array return-keys))
(catch Exception _
;; assume it is unsupported and try regular generated keys:
(.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS)))
(.prepareStatement con sql java.sql.Statement/RETURN_GENERATED_KEYS))
(catch Exception _
;; assume it is unsupported and try basic PreparedStatement:
(.prepareStatement con sql)))
(and result-type concurrency)
(if cursors
(.prepareStatement con sql
(get result-set-type result-type result-type)
(get result-set-concurrency concurrency concurrency)
(get result-set-holdability cursors cursors))
(.prepareStatement con sql
(get result-set-type result-type result-type)
(get result-set-concurrency concurrency concurrency)))
(or result-type concurrency cursors)
(throw (IllegalArgumentException.
(str ":concurrency, :cursors, and :result-type "
"may not be specified independently.")))
:else
(.prepareStatement con sql))]
(when fetch-size (.setFetchSize stmt fetch-size))
(when max-rows (.setMaxRows stmt max-rows))
(when timeout (.setQueryTimeout stmt timeout))
stmt)))
(defn print-sql-exception
"Prints the contents of an SQLException to *out*"
[^SQLException exception]
(let [^Class exception-class (class exception)]
(println
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName exception-class)
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception)))))
(defn print-sql-exception-chain
"Prints a chain of SQLExceptions to *out*"
[^SQLException exception]
(loop [e exception]
(when e
(print-sql-exception e)
(recur (.getNextException e)))))
(def ^{:private true} special-counts
{Statement/EXECUTE_FAILED "EXECUTE_FAILED"
Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"})
(defn print-update-counts
"Prints the update counts from a BatchUpdateException to *out*"
[^BatchUpdateException exception]
(println "Update counts:")
(dorun
(map-indexed
(fn [index count]
(println (format " Statement %d: %s"
index
(get special-counts count count))))
(.getUpdateCounts exception))))
;; java.jdbc pieces rewritten to not use dynamic bindings
(defn db-find-connection
"Returns the current database connection (or nil if there is none)"
^java.sql.Connection [db]
(and (map? db)
(:connection db)))
(defn db-connection
"Returns the current database connection (or throws if there is none)"
^java.sql.Connection [db]
(or (db-find-connection db)
(throw (Exception. "no current database connection"))))
(defn db-set-rollback-only!
"Marks the outermost transaction such that it will rollback rather than
commit when complete"
[db]
(reset! (:rollback db) true))
(defn db-unset-rollback-only!
"Marks the outermost transaction such that it will not rollback when complete"
[db]
(reset! (:rollback db) false))
(defn db-is-rollback-only
"Returns true if the outermost transaction will rollback rather than
commit when complete"
[db]
(deref (:rollback db)))
(def ^:private
isolation-levels
"Transaction isolation levels."
{:none java.sql.Connection/TRANSACTION_NONE
:read-committed java.sql.Connection/TRANSACTION_READ_COMMITTED
:read-uncommitted java.sql.Connection/TRANSACTION_READ_UNCOMMITTED
:repeatable-read java.sql.Connection/TRANSACTION_REPEATABLE_READ
:serializable java.sql.Connection/TRANSACTION_SERIALIZABLE})
(def ^:private isolation-kws
"Map transaction isolation constants to our keywords."
(set/map-invert isolation-levels))
(defn get-isolation-level
"Given a db-spec (with an optional connection), return the current
transaction isolation level, if known. Return nil if there is no
active connection in the db-spec. Return :unknown if we do not
recognize the isolation level."
[db]
(when-let [con (db-find-connection db)]
(isolation-kws (.getTransactionIsolation con) :unknown)))
(defn db-transaction*
"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.
The isolation option may be :none, :read-committed, :read-uncommitted,
:repeatable-read, or :serializable. Note that not all databases support
all of those isolation levels, and may either throw an exception or
substitute another isolation level.
The read-only? option puts the transaction in readonly mode (if supported)."
([db func] (db-transaction* db func {}))
([db func opts]
(let [{:keys [isolation read-only?] :as opts}
(merge (when (map? db) db) opts)]
(if (zero? (get-level db))
(if-let [con (db-find-connection db)]
(let [nested-db (inc-level db)
auto-commit (.getAutoCommit con)
old-isolation (.getTransactionIsolation con)
old-readonly (.isReadOnly con)]
(io!
(when isolation
(.setTransactionIsolation con (isolation isolation-levels)))
(when read-only?
(.setReadOnly con true))
(.setAutoCommit con false)
(try
(let [result (func nested-db)]
(if (db-is-rollback-only nested-db)
(.rollback con)
(.commit con))
result)
(catch Throwable t
(.rollback con)
(throw t))
(finally
(db-unset-rollback-only! nested-db)
;; the following can throw SQLExceptions but we do not
;; want those to replace any exception currently being
;; handled -- and if the connection got closed, we just
;; want to ignore exceptions here anyway
(try
(.setAutoCommit con auto-commit)
(catch Exception _))
(when isolation
(try
(.setTransactionIsolation con old-isolation)
(catch Exception _)))
(when read-only?
(try
(.setReadOnly con old-readonly)
(catch Exception _)))))))
(with-open [con (get-connection db opts)]
(db-transaction* (add-connection db con) func opts)))
(do
(when (and isolation
(let [con (db-find-connection db)]
(not= (isolation isolation-levels)
(.getTransactionIsolation con))))
(let [msg "Nested transactions may not have different isolation levels"]
(throw (IllegalStateException. msg))))
(func (inc-level db)))))))
(defmacro with-db-transaction
"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. The binding may also specify the isolation
level for the transaction, via the :isolation option and/or set the transaction to
readonly via the :read-only? option.
(with-db-transaction [t-con db-spec {:isolation level :read-only? true}]
... t-con ...)
See db-transaction* for more details."
[binding & body]
`(db-transaction* ~(second binding)
(^{:once true} fn* [~(first binding)] ~@body)
~@(rest (rest binding))))
(defmacro with-db-connection
"Evaluates body in the context of an active connection to the database.
(with-db-connection [con-db db-spec opts]
... con-db ...)"
[binding & body]
`(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})]
(with-open [con# (get-connection db-spec# opts#)]
(let [~(first binding) (add-connection db-spec# con#)]
~@body))))
(defmacro with-db-metadata
"Evaluates body in the context of an active connection with metadata bound
to the specified name. See also metadata-result for dealing with the results
of operations that retrieve information from the metadata.
(with-db-metadata [md db-spec opts]
... md ...)"
[binding & body]
`(let [db-spec# ~(second binding) opts# (or ~(second (rest binding)) {})]
(with-open [con# (get-connection db-spec# opts#)]
(let [~(first binding) (.getMetaData con#)]
~@body))))
(defn metadata-result
"If the argument is a java.sql.ResultSet, turn it into a result-set-seq,
else return it as-is. This makes working with metadata easier.
Also accepts an option map containing :identifiers, :qualifier, :as-arrays?,
:row-fn,and :result-set-fn to control how the ResultSet is transformed and
returned. See query for more details."
([rs-or-value] (metadata-result rs-or-value {}))
([rs-or-value opts]
(let [{:keys [as-arrays? result-set-fn row-fn] :as opts}
(merge {:identifiers str/lower-case :read-columns dft-read-columns
:row-fn identity} opts)
result-set-fn (or result-set-fn (if as-arrays? vec doall))]
(if (instance? java.sql.ResultSet rs-or-value)
((^{:once true} fn* [rs]
(result-set-fn (if as-arrays?
(cons (first rs)
(map row-fn (rest rs)))
(map row-fn rs))))
(result-set-seq rs-or-value opts))
rs-or-value))))
(defmacro metadata-query
"Given a Java expression that extracts metadata (in the context of with-db-metadata),
and a map of options like metadata-result, manage the connection for a single
metadata-based query. Example usage:
(with-db-metadata [meta db-spec]
(metadata-query (.getTables meta nil nil nil (into-array String [\"TABLE\"]))
{:row-fn ... :result-set-fn ...}))"
[meta-query & opt-args]
`(with-open [rs# ~meta-query]
(metadata-result rs# ~@opt-args)))
(defn db-do-commands
"Executes SQL commands on the specified database connection. Wraps the commands
in a transaction if transaction? is true. transaction? can be ommitted and it
defaults to true. Accepts a single SQL command (string) or a vector of them.
Uses executeBatch. This may affect what SQL you can run via db-do-commands."
([db sql-commands]
(db-do-commands db true (if (string? sql-commands) [sql-commands] sql-commands)))
([db transaction? sql-commands]
(if (string? sql-commands)
(db-do-commands db transaction? [sql-commands])
(if-let [con (db-find-connection db)]
(with-open [^Statement stmt (.createStatement con)]
(doseq [^String cmd sql-commands]
(.addBatch stmt cmd))
(if transaction?
(with-db-transaction [t-db (add-connection db (.getConnection stmt))]
(execute-batch stmt))
(execute-batch stmt)))
(with-open [con (get-connection db)]
(db-do-commands (add-connection db con) transaction? sql-commands))))))
(defn- db-do-execute-prepared-return-keys
"Executes a PreparedStatement, optionally in a transaction, and (attempts to)
return any generated keys."
[db ^PreparedStatement stmt param-group opts]
(let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts)
exec-and-return-keys
(^{:once true} fn* []
(let [counts (.executeUpdate stmt)]
(try
(let [rs (.getGeneratedKeys stmt)
result (first (result-set-seq rs opts))]
;; sqlite (and maybe others?) requires
;; record set to be closed
(.close rs)
result)
(catch Exception _
;; assume generated keys is unsupported and return counts instead:
counts))))]
((:set-parameters opts dft-set-parameters) stmt param-group)
(if transaction?
(with-db-transaction [t-db (add-connection db (.getConnection stmt))]
(exec-and-return-keys))
(exec-and-return-keys))))
(defn- sql-stmt?
"Given an expression, return true if it is either a string (SQL) or a
PreparedStatement."
[expr]
(or (string? expr) (instance? PreparedStatement expr)))
(defn db-do-prepared-return-keys
"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. transaction? can be ommitted and will default to true.
Return the generated keys for the (single) update/insert.
A PreparedStatement may be passed in, instead of a SQL string, in which
case :return-keys MUST BE SET on that PreparedStatement!"
([db sql-params]
(db-do-prepared-return-keys db true sql-params {}))
([db transaction? sql-params]
(if (map? sql-params)
(db-do-prepared-return-keys db true transaction? sql-params)
(db-do-prepared-return-keys db transaction? sql-params {})))
([db transaction? sql-params opts]
(let [opts (merge (when (map? db) db) opts)]
(if-let [con (db-find-connection db)]
(let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))]
(if (instance? PreparedStatement sql)
(db-do-execute-prepared-return-keys db sql params (assoc opts :transaction? transaction?))
(with-open [^PreparedStatement stmt (prepare-statement con sql (assoc opts :return-keys true))]
(db-do-execute-prepared-return-keys db stmt params (assoc opts :transaction? transaction?)))))
(with-open [con (get-connection db opts)]
(db-do-prepared-return-keys (add-connection db con) transaction? sql-params opts))))))
(defn- db-do-execute-prepared-statement
"Execute a PreparedStatement, optionally in a transaction."
[db ^PreparedStatement stmt param-groups opts]
(let [{:keys [transaction?] :as opts} (merge (when (map? db) db) opts)]
(if (empty? param-groups)
(if transaction?
(with-db-transaction [t-db (add-connection db (.getConnection stmt))]
(vector (.executeUpdate stmt)))
(vector (.executeUpdate stmt)))
(do
(doseq [param-group param-groups]
((:set-parameters opts dft-set-parameters) stmt param-group)
(.addBatch stmt))
(if transaction?
(with-db-transaction [t-db (add-connection db (.getConnection stmt))]
(execute-batch stmt))
(execute-batch stmt))))))
(defn db-do-prepared
"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. transaction? can be omitted and defaults to true.
The sql parameter can either be a SQL string or a PreparedStatement.
Return a seq of update counts (one count for each param-group)."
([db sql-params]
(db-do-prepared db true sql-params {}))
([db transaction? sql-params]
(if (map? sql-params)
(db-do-prepared db true transaction? sql-params)
(db-do-prepared db transaction? sql-params {})))
([db transaction? sql-params opts]
(let [opts (merge (when (map? db) db) opts)]
(if-let [con (db-find-connection db)]
(let [[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))
params (if (or (:multi? opts) (empty? params)) params [params])]
(if (instance? PreparedStatement sql)
(db-do-execute-prepared-statement db sql params (assoc opts :transaction? transaction?))
(with-open [^PreparedStatement stmt (prepare-statement con sql opts)]
(db-do-execute-prepared-statement db stmt params (assoc opts :transaction? transaction?)))))
(with-open [con (get-connection db opts)]
(db-do-prepared (add-connection db con) transaction? sql-params opts))))))
(defn db-query-with-resultset
"Executes a query, then evaluates func passing in the raw ResultSet as an
argument. The second 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)
The opts map is passed to prepare-statement.
Uses executeQuery. This may affect what SQL you can run via query."
([db sql-params func] (db-query-with-resultset db sql-params func {}))
([db sql-params func opts]
(let [opts (merge (when (map? db) db) opts)
[sql & params] (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))
run-query-with-params (^{:once true} fn* [^PreparedStatement stmt]
((:set-parameters opts dft-set-parameters) stmt params)
(with-open [rset (.executeQuery stmt)]
(func rset)))]
(when-not (sql-stmt? sql)
(let [^Class sql-class (class sql)
^String msg (format "\"%s\" expected %s %s, found %s %s"
"sql-params"
"vector"
"[sql param*]"
(.getName sql-class)
(pr-str sql))]
(throw (IllegalArgumentException. msg))))
(if (instance? PreparedStatement sql)
(let [^PreparedStatement stmt sql]
(run-query-with-params stmt))
(if-let [con (db-find-connection db)]
(with-open [^PreparedStatement stmt (prepare-statement con sql opts)]
(run-query-with-params stmt))
(with-open [con (get-connection db opts)]
(with-open [^PreparedStatement stmt (prepare-statement con sql opts)]
(run-query-with-params stmt))))))))
;; top-level API for actual SQL operations
(defn query
"Given a database connection and a vector containing SQL and optional parameters,
perform a simple database query. The options specify how to construct the result
set (and are also passed to prepare-statement as needed):
:as-arrays? - return the results as a set of arrays, default false.
:identifiers - applied to each column name in the result set, default lower-case
:qualifier - optionally provides the namespace qualifier for identifiers
:result-set-fn - applied to the entire result set, default doall / vec
if :as-arrays? true, :result-set-fn will default to vec
if :as-arrays? false, :result-set-fn will default to doall
:row-fn - applied to each row as the result set is constructed, default identity
The second argument is a vector containing a SQL string or PreparedStatement, followed
by any parameters it needs.
See also prepare-statement for additional options."
([db sql-params] (query db sql-params {}))
([db sql-params opts]
(let [{:keys [as-arrays? explain? explain-fn result-set-fn row-fn] :as opts}
(merge {:explain-fn println :identifiers str/lower-case
:read-columns dft-read-columns :row-fn identity}
(when (map? db) db)
opts)
result-set-fn (or result-set-fn (if as-arrays? vec doall))
sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))]
(when (and explain? (string? (first sql-params-vector)))
(query db (into [(str (if (string? explain?) explain? "EXPLAIN")
" "
(first sql-params-vector))]
(rest sql-params-vector))
(-> opts
(dissoc :explain? :result-set-fn :row-fn)
(assoc :result-set-fn explain-fn))))
(db-query-with-resultset db sql-params-vector
(^{:once true} fn* [rset]
((^{:once true} fn* [rs]
(result-set-fn (if as-arrays?
(cons (first rs)
(map row-fn (rest rs)))
(map row-fn rs))))
(result-set-seq rset opts)))
opts))))
(defn reducible-result-set
"Given a java.sql.ResultSet return a reducible collection.
Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce
Note: :as-arrays? is not accepted here."
[^ResultSet rs {:keys [identifiers qualifier read-columns]
:or {identifiers str/lower-case
read-columns dft-read-columns}}]
(let [identifier-fn (if qualifier
(comp (partial keyword qualifier) identifiers)
(comp keyword identifiers))
make-keys (fn [idxs ^ResultSetMetaData rsmeta]
(->> idxs
(mapv (fn [^Integer i] (.getColumnLabel rsmeta i)))
(make-cols-unique)
(mapv identifier-fn)))
init-reduce (fn [keys ^ResultSet rs rsmeta idxs f init]
(loop [init' init]
(if (.next rs)
(let [result (f init' (zipmap keys (read-columns rs rsmeta idxs)))]
(if (reduced? result)
@result
(recur result)))
init')))]
(reify clojure.lang.IReduce
(reduce [this f]
(let [rsmeta (.getMetaData rs)
idxs (range 1 (inc (.getColumnCount rsmeta)))
keys (make-keys idxs rsmeta)]
(if (.next rs)
;; reduce init is first row of ResultSet
(init-reduce keys rs rsmeta idxs f
(zipmap keys (read-columns rs rsmeta idxs)))
;; no rows so call 0-arity f to get result value
;; per reduce docstring contract
(f))))
(reduce [this f init]
(let [rsmeta (.getMetaData rs)
idxs (range 1 (inc (.getColumnCount rsmeta)))
keys (make-keys idxs rsmeta)]
(init-reduce keys rs rsmeta idxs f init))))))
(defn reducible-query
"Given a database connection, a vector containing SQL and optional parameters,
return a reducible collection. When reduced, it will start the database query
and reduce the result set, and then close the connection:
(transduce (map :cost) + (reducible-query db sql-params))
Compiled with Clojure 1.7 or later -- uses clojure.lang.IReduce
The following options from query etc are not accepted here:
:as-arrays? :explain :explain-fn :result-set-fn :row-fn
See also prepare-statement for additional options."
([db sql-params] (reducible-query db sql-params {}))
([db sql-params opts]
(let [{:keys [reducing-fn] :as opts}
(merge {:identifiers str/lower-case :read-columns dft-read-columns}
(when (map? db) db)
opts)
sql-params-vector (if (sql-stmt? sql-params) (vector sql-params) (vec sql-params))]
(reify clojure.lang.IReduce
(reduce [this f]
(db-query-with-resultset
db sql-params-vector
(^{:once true} fn* [rset]
(reduce f (reducible-result-set rset opts)))
opts))
(reduce [this f init]
(db-query-with-resultset
db sql-params-vector
(^{:once true} fn* [rset]
(reduce f init (reducible-result-set rset opts)))
opts))))))
(defn- direction
"Given an entities function, a column name, and a direction,
return the matching SQL column / order.
Throw an exception for an invalid direction."
[entities c d]
(str (as-sql-name entities c) " "
(if-let [dir (#{"ASC" "DESC"} (str/upper-case (name d)))]
dir
(throw (IllegalArgumentException. (str "expected :asc or :desc, found: " d))))))
(defn- order-by-sql
"Given a sequence of column specs and an entities function, return
a SQL fragment for the ORDER BY clause. A column spec may be a name
(either a string or keyword) or a map from column name to direction
(:asc or :desc)."
[order-by entities]
(str/join ", " (mapcat (fn [col]
(if (map? col)
(reduce-kv (fn [v c d]
(conj v (direction entities c d)))
[]
col)
[(direction entities col :asc)])) order-by)))
(defn find-by-keys
"Given a database connection, a table name, a map of column name/value
pairs, and an optional options map, return any matching rows.
An :order-by option may be supplied to sort the rows by a sequence of
columns, e.g,. {:order-by [:name {:age :desc]}"
([db table columns] (find-by-keys db table columns {}))
([db table columns opts]
(let [{:keys [entities order-by] :as opts}
(merge {:entities identity} (when (map? db) db) opts)
ks (keys columns)
vs (vals columns)]
(query db (into [(str "SELECT * FROM " (table-str table entities)
" WHERE " (str/join " AND "
(kv-sql ks vs entities " IS NULL"))
(when (seq order-by)
(str " ORDER BY "
(order-by-sql order-by entities))))]
(remove nil? vs))
opts))))
(defn get-by-id
"Given a database connection, a table name, a primary key value, an
optional primary key column name, and an optional options map, return
a single matching row, or nil.
The primary key column name defaults to :id."
([db table pk-value] (get-by-id db table pk-value :id {}))
([db table pk-value pk-name-or-opts]
(if (map? pk-name-or-opts)
(get-by-id db table pk-value :id pk-name-or-opts)
(get-by-id db table pk-value pk-name-or-opts {})))
([db table pk-value pk-name opts]
(let [opts (merge (when (map? db) db) opts)
r-s-fn (or (:result-set-fn opts) identity)]
(find-by-keys db table {pk-name pk-value}
(assoc opts :result-set-fn (comp first r-s-fn))))))
(defn execute!
"Given a database connection and a vector containing SQL (or PreparedStatement)
followed by optional parameters, perform a general (non-select) SQL operation.
The :transaction? option specifies whether to run the operation in a
transaction or not (default true).
If the :multi? option is false (the default), the SQL statement should be
followed by the parameters for that statement.
If the :multi? option is true, the SQL statement should be followed by one or
more vectors of parameters, one for each application of the SQL statement.
If there are no parameters specified, executeUpdate will be used, otherwise
executeBatch will be used. This may affect what SQL you can run via execute!"
([db sql-params] (execute! db sql-params {}))
([db sql-params opts]
(let [{:keys [transaction?] :as opts}
(merge {:transaction? true :multi? false} (when (map? db) db) opts)
execute-helper (^{:once true} fn* [db]
(db-do-prepared db transaction? sql-params opts))]
(if-let [con (db-find-connection db)]
(execute-helper db)
(with-open [con (get-connection db opts)]
(execute-helper (add-connection db con)))))))
(defn- delete-sql
"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."
[table [where & params] entities]
(into [(str "DELETE FROM " (table-str table entities)
(when where " WHERE ") where)]
params))
(defn delete!
"Given a database connection, a table name and a where clause of columns to match,
perform a delete. The options may 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 [\"zip = ?\" 94546])
is equivalent to:
(execute! db [\"DELETE FROM person WHERE zip = ?\" 94546])"
([db table where-clause] (delete! db table where-clause {}))
([db table where-clause opts]
(let [{:keys [entities] :as opts}
(merge {:entities identity :transaction? true} (when (map? db) db) opts)]
(execute! db (delete-sql table where-clause entities) opts))))
(defn- multi-insert-helper
"Given a (connected) database connection and some SQL statements (for multiple
inserts), run a prepared statement on each and return any generated keys.
Note: we are eager so an unrealized lazy-seq cannot escape from the connection."
[db stmts opts]
(doall (map (fn [row] (db-do-prepared-return-keys db false row opts)) stmts)))
(defn- insert-helper
"Given a (connected) database connection, a transaction flag and some SQL statements
(for one or more inserts), run a prepared statement or a sequence of them."
[db transaction? stmts opts]
(if transaction?
(with-db-transaction [t-db db] (multi-insert-helper t-db stmts opts))
(multi-insert-helper db stmts opts)))
(defn- col-str
"Transform a column spec to an entity name for SQL. The column spec may be a
string, a keyword or a map with a single pair - column name and alias."
[col entities]
(if (map? col)
(let [[k v] (first col)]
(str (as-sql-name entities k) " AS " (as-sql-name entities v)))
(as-sql-name entities col)))
(defn- insert-multi-row-sql
"Given a table and a list of columns, followed by a list of column value sequences,
return a vector of the SQL needed for the insert followed by the list of column
value sequences. The entities function specifies how column names are transformed."
[table columns values entities]
(let [nc (count columns)
vcs (map count values)]
(if (not (and (or (zero? nc) (= nc (first vcs))) (apply = vcs)))
(throw (IllegalArgumentException. "insert! called with inconsistent number of columns / values"))
(into [(str "INSERT INTO " (table-str table entities)
(when (seq columns)
(str " ( "
(str/join ", " (map (fn [col] (col-str col entities)) columns))
" )"))
" VALUES ( "
(str/join ", " (repeat (first vcs) "?"))
" )")]
values))))
(defn- insert-single-row-sql
"Given a table and a map representing a row, return a vector of the SQL needed for
the insert followed by the list of column values. The entities function specifies
how column names are transformed."
[table row entities]
(let [ks (keys row)]
(into [(str "INSERT INTO " (table-str table entities) " ( "
(str/join ", " (map (fn [col] (col-str col entities)) ks))
" ) VALUES ( "
(str/join ", " (repeat (count ks) "?"))
" )")]
(vals row))))
(defn- insert-rows!
"Given a database connection, a table name, a sequence of rows, and an options
map, insert the rows into the database."
[db table rows opts]
(let [{:keys [entities transaction?] :as opts}
(merge {:entities identity :identifiers str/lower-case :transaction? true}
(when (map? db) db)
opts)
sql-params (map (fn [row]
(when-not (map? row)
(throw (IllegalArgumentException. "insert! / insert-multi! called with a non-map row")))
(insert-single-row-sql table row entities)) rows)]
(if-let [con (db-find-connection db)]
(insert-helper db transaction? sql-params opts)
(with-open [con (get-connection db opts)]
(insert-helper (add-connection db con) transaction? sql-params opts)))))
(defn- insert-cols!
"Given a database connection, a table name, a sequence of columns names, a
sequence of vectors of column values, one per row, and an options map,
insert the rows into the database."
[db table cols values opts]
(let [{:keys [entities transaction?] :as opts}
(merge {:entities identity :transaction? true} (when (map? db) db) opts)
sql-params (insert-multi-row-sql table cols values entities)]
(if-let [con (db-find-connection db)]
(db-do-prepared db transaction? sql-params (assoc opts :multi? true))
(with-open [con (get-connection db opts)]
(db-do-prepared (add-connection db con) transaction? sql-params
(assoc opts :multi? true))))))
(defn insert!
"Given a database connection, a table name and either a map representing a rows,
or a list of column names followed by a list of column values also representing
a single row, perform an insert.
When inserting a row as a map, the result is the database-specific form of the
generated keys, if available (note: PostgreSQL returns the whole row).
When inserting a row as a list of column values, the result is the count of
rows affected (1), if available (from getUpdateCount after executeBatch).
The row map or column value vector may be followed by a map of options:
The :transaction? option specifies whether to run in a transaction or not.
The default is true (use a transaction). The :entities option specifies how
to convert the table name and column names to SQL entities."
([db table row] (insert! db table row {}))
([db table cols-or-row values-or-opts]
(if (map? values-or-opts)
(insert-rows! db table [cols-or-row] values-or-opts)
(insert-cols! db table cols-or-row [values-or-opts] {})))
([db table cols values opts]
(insert-cols! db table cols [values] opts)))
(defn insert-multi!
"Given a database connection, a table name and either a sequence of maps (for
rows) or a sequence of column names, followed by a sequence of vectors (for
the values in each row), and possibly a map of options, insert that data into
the database.
When inserting rows as a sequence of maps, the result is a sequence of the
generated keys, if available (note: PostgreSQL returns the whole rows). A
separate database operation is used for each row inserted. This may be slow
for if a large sequence of maps is provided.
When inserting rows as a sequence of lists of column values, the result is
a sequence of the counts of rows affected (a sequence of 1's), if available.
Yes, that is singularly unhelpful. Thank you getUpdateCount and executeBatch!
A single database operation is used to insert all the rows at once. This may
be much faster than inserting a sequence of rows (which performs an insert for
each map in the sequence).
The :transaction? option specifies whether to run in a transaction or not.
The default is true (use a transaction). The :entities option specifies how
to convert the table name and column names to SQL entities."
([db table rows] (insert-rows! db table rows {}))
([db table cols-or-rows values-or-opts]
(if (map? values-or-opts)
(insert-rows! db table cols-or-rows values-or-opts)
(insert-cols! db table cols-or-rows values-or-opts {})))
([db table cols values opts]
(insert-cols! db table cols values opts)))
(defn- update-sql
"Given a table name, a map of columns to set, a optional map of columns to
match, and an entities, return a vector of the SQL for that update followed
by its parameters. Example:
(update :person {:zip 94540} [\"zip = ?\" 94546] identity)
returns:
[\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546]"
[table set-map [where & params] entities]
(let [ks (keys set-map)
vs (vals set-map)]
(cons (str "UPDATE " (table-str table entities)
" SET " (str/join
","
(kv-sql ks vs entities " = NULL"))
(when where " WHERE ")
where)
(concat (remove nil? vs) params))))
(defn update!
"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 options may 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} [\"zip = ?\" 94546])
is equivalent to:
(execute! db [\"UPDATE person SET zip = ? WHERE zip = ?\" 94540 94546])"
([db table set-map where-clause] (update! db table set-map where-clause {}))
([db table set-map where-clause opts]
(let [{:keys [entities] :as opts}
(merge {:entities identity :transaction? true} (when (map? db) db) opts)]
(execute! db (update-sql table set-map where-clause entities) opts))))
(defn create-table-ddl
"Given a table name and a vector of column specs, return the DDL string for
creating that table. Each column spec is, in turn, a vector of keywords or
strings that is converted to strings and concatenated with spaces to form
a single column description in DDL, e.g.,
[:cost :int \"not null\"]
[:name \"varchar(32)\"]
The first element of a column spec is treated as a SQL entity (so if you
provide the :entities option, that will be used to transform it). The
remaining elements are left as-is when converting them to strings.
An options map may be provided that can contain:
:table-spec -- a string that is appended to the DDL -- and/or
:entities -- a function to specify how column names are transformed.
:conditional? -- either a boolean, indicating whether to add 'IF NOT EXISTS',
or a string, which is inserted literally before the table name, or a
function of two arguments (table name and the create statement), that can
manipulate the generated statement to better support other databases, e.g.,
MS SQL Server which need to wrap create table in an existence query."
([table specs] (create-table-ddl table specs {}))
([table specs opts]
(let [table-spec (:table-spec opts)
conditional? (:conditional? opts)
entities (:entities opts identity)
table-name (as-sql-name entities table)
table-spec-str (or (and table-spec (str " " table-spec)) "")
spec-to-string (fn [spec]
(try
(str/join " " (cons (as-sql-name entities (first spec))
(map name (rest spec))))
(catch Exception _
(throw (IllegalArgumentException.
"column spec is not a sequence of keywords / strings")))))]
(cond->> (format "CREATE TABLE%s %s (%s)%s"
(cond (or (nil? conditional?)
(instance? Boolean conditional?))
(if conditional? " IF NOT EXISTS" "")
(fn? conditional?)
""
:else
(str " " conditional?))
table-name
(str/join ", " (map spec-to-string specs))
table-spec-str)
(fn? conditional?) (conditional? table-name)))))
(defn drop-table-ddl
"Given a table name, return the DDL string for dropping that table.
An options map may be provided that can contain:
:entities -- a function to specify how column names are transformed.
:conditional? -- either a boolean, indicating whether to add 'IF EXISTS',
or a string, which is inserted literally before the table name, or a
function of two arguments (table name and the create statement), that can
manipulate the generated statement to better support other databases, e.g.,
MS SQL Server which need to wrap create table in an existence query."
([table] (drop-table-ddl table {}))
([table {:keys [entities conditional?] :or {entities identity}}]
(let [table-name (as-sql-name entities table)]
(cond->> (format "DROP TABLE%s %s"
(cond (or (nil? conditional?)
(instance? Boolean conditional?))
(if conditional? " IF EXISTS" "")
(fn? conditional?)
""
:else
(str " " conditional?))
table-name)
(fn? conditional?) (conditional? table-name)))))
java.jdbc-java.jdbc-0.7.0/src/main/clojure/clojure/java/jdbc/ 0000775 0000000 0000000 00000000000 13132773030 0023623 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/main/clojure/clojure/java/jdbc/spec.clj 0000664 0000000 0000000 00000041304 13132773030 0025251 0 ustar 00root root 0000000 0000000 ;; Copyright (c) 2016-2017 Sean Corfield. All rights reserved.
;; The use and distribution terms for this software are covered by
;; the Eclipse Public License 1.0
;; (http://opensource.org/licenses/eclipse-1.0.php) which can be
;; found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be
;; bound by the terms of this license. You must not remove this
;; notice, or any other, from this software.
;;
;; jdbc/spec.clj
;;
;; Optional specifications for clojure.java.jdbc
(ns ^{:author "Sean Corfield"
:doc "Optional specifications for use with Clojure 1.9 or later."}
clojure.java.jdbc.spec
(:require [clojure.spec.alpha :as s]
[clojure.java.jdbc :as sql]))
;; basic java.sql types -- cannot be generated!
(s/def ::connection #(instance? java.sql.Connection %))
(s/def ::connection-uri #(instance? java.net.URI %))
(s/def ::datasource #(instance? javax.sql.DataSource %))
(s/def ::prepared-statement #(instance? java.sql.PreparedStatement %))
(s/def ::result-set #(instance? java.sql.ResultSet %))
(s/def ::result-set-metadata #(instance? java.sql.ResultSetMetaData %))
;; database specification (connection description)
(s/def ::subprotocol-base #{"derby" "h2" "hsqldb" "jtds:sqlserver" "mysql"
"oracle:oci" "oracle:thin" "pgsql" "postgresql"
"redshift" "sqlite" "sqlserver"})
(s/def ::subprotocol-alias #{"hsql" "jtds" "mssql" "oracle" "postgres"})
;; technically :subprotocol can be any string...
(s/def ::subprotocol string?)
;; ...but :dbtype must be a recognizable database type
(s/def ::dbtype (s/or :alias ::subprotocol-alias
:name ::subprotocol-base))
(s/def ::dbname string?)
;; usually IP address or domain name but could be more general string
;; (e.g., it could be username:password@domain.name)
(s/def ::host string?)
;; usually a numeric port number, but could be an arbitrary string if
;; the specified database accepts URIs constructed that way
(s/def ::port (s/or :port pos-int?
:s string?))
(s/def ::subname string?)
;; will be a valid Java classname (including package)
(s/def ::classname string?)
(s/def ::factory (s/fspec :args (s/cat :db-spec ::db-spec)
:ret ::connection))
(s/def ::user string?)
(s/def ::username ::user) ; an alias
(s/def ::password string?)
(s/def ::name string?)
(s/def ::environment (s/nilable map?))
(s/def ::db-spec-connection (s/keys :req-un [::connection]))
(s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname] :opt-un [::host ::port]))
(s/def ::db-spec-raw (s/keys :req-un [::connection-uri]))
(s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname] :opt-un [::classname]))
(s/def ::db-spec-factory (s/keys :req-un [::factory]))
(s/def ::db-spec-data-source (s/keys :req-un [::datasource] :opt-un [::username ::user ::password]))
(s/def ::db-spec-jndi (s/keys :req-un [::name] :opt-un [::environment]))
(s/def ::db-spec-string string?)
(s/def ::db-spec (s/or :connection ::db-spec-connection
:friendly ::db-spec-friendly
:raw ::db-spec-raw
:driver-mgr ::db-spec-driver-manager
:factory ::db-spec-factory
:datasource ::db-spec-data-source
:jndi ::db-spec-jndi
:uri ::db-spec-string))
;; naming
(s/def ::entity string?)
(s/def ::identifier (s/or :kw keyword? :s string?))
;; SQL and parameters
(s/def ::sql-stmt (s/or :sql string? :stmt ::prepared-statement))
(s/def ::sql-value any?) ;; for now
(s/def ::sql-params (s/or :sql ::sql-stmt
:sql-params (s/cat :sql ::sql-stmt :params (s/* ::sql-value))))
(s/def ::where-clause (s/cat :where string? :params (s/* ::sql-value)))
;; results
(s/def ::execute-result (s/* integer?))
;; specific options that can be passed
;; a few of them are nilable, where the functions either pass a possibly nil
;; version of the option to a called function, but most are not nilable because
;; the corresponding options must either be omitted or given valid values
(s/def ::as-arrays? (s/or :as-is #{:cols-as-is} :truthy (s/nilable boolean?)))
(s/def ::auto-commit? boolean?)
(s/def ::concurrency (set (keys @#'sql/result-set-concurrency)))
(s/def ::cursors (set (keys @#'sql/result-set-holdability)))
(s/def ::fetch-size nat-int?)
;; note the asymmetry here: the identifiers function converts a SQL entity to
;; an identifier (a symbol or a string), whereas the entities function converts
;; a string (not an identifier) to a SQL entity; SQL entities are always strings
;; but whilst java.jdbc lets you produce a keyword from identifiers, it does not
;; assume that entities can accept keywords!
(s/def ::identifiers (s/fspec :args (s/cat :s ::entity)
:ret ::identifier))
(s/def ::isolation (set (keys @#'sql/isolation-levels)))
(s/def ::entities (s/fspec :args (s/cat :s string?)
:ret ::entity))
(s/def ::max-size nat-int?)
(s/def ::multi? boolean?)
;; strictly speaking we accept any keyword or string whose upper case name
;; is either ASC or DESC so this spec is overly restrictive; the :id-dir
;; can actually be an empty map although that is not very useful
(s/def ::direction #{:asc :desc "asc" "desc" "ASC" "DESC"})
(s/def ::column-direction (s/or :id ::identifier
:id-dir (s/map-of ::identifier ::direction)))
(s/def ::order-by (s/coll-of ::column-direction))
(s/def ::qualifier (s/nilable string?))
;; cannot generate a result set so we can't specify this yet
#_(s/def ::read-columns (s/fspec :args (s/cat :rs ::result-set
:rsmeta ::result-set-metadata
:idxs (s/coll-of pos-int?))
:ret (s/coll-of any?)))
(s/def ::read-columns fn?)
(s/def ::read-only? boolean?)
;; there's not much we can say about result-set-fn -- it accepts a collection of
;; transformed rows (from row-fn), and it produces whatever it wants
(s/def ::result-set-fn (s/fspec :args (s/cat :rs (s/coll-of any?))
:ret any?))
(s/def ::result-type (set (keys @#'sql/result-set-type)))
;; there's not much we can say about row-fn -- it accepts a row from a ResultSet
;; which is a map of keywords to SQL values, and it produces whatever it wants
(s/def ::row-fn (s/fspec :args (s/cat :row (s/map-of keyword? ::sql-value))
:ret any?))
(s/def ::return-keys (s/or :columns (s/coll-of ::entity :kind vector?)
:boolean boolean?))
(s/def ::table-spec string?)
(s/def ::timeout nat-int?)
(s/def ::transaction? boolean?)
(s/def ::explain? (s/or :b boolean? :s string?))
(s/def ::explain-fn fn?)
(s/def ::conditional? (s/or :b boolean? :s string? :f fn?))
;; various types of options
(s/def ::exec-sql-options (s/keys :req-un [] :opt-un [::entities ::transaction?]))
(s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?]))
(s/def ::find-by-keys-options (s/keys :req-un []
:opt-un [::entities ::order-by
::result-set-fn ::row-fn
::identifiers ::qualifier
::as-arrays? ::read-columns]))
(s/def ::connection-options (s/keys :req-un []
:opt-un [::auto-commit? ::read-only?]))
(s/def ::prepare-options (s/merge (s/keys :req-un []
:opt-un [::return-keys ::result-type
::concurrency ::cursors ::fetch-size
::max-rows ::timeout])
::connection-options))
(s/def ::transaction-options (s/keys :req-un []
:opt-un [::isolation ::read-only?]))
(s/def ::query-options (s/merge (s/keys :req-un []
:opt-un [::result-set-fn ::row-fn
::identifiers ::qualifier
::as-arrays? ::read-columns])
::prepare-options))
(s/def ::reducible-query-options (s/merge (s/keys :req-un []
:opt-un [::identifiers ::qualifier
::read-columns])
::prepare-options))
;; the function API
(s/def ::naming-strategy (s/fspec :args (s/cat :x ::identifier)
:ret ::identifier))
(s/fdef sql/as-sql-name
:args (s/cat :f ::naming-strategy :x ::identifier)
:ret ::identifier)
(s/def ::delimiter (s/or :s string? :c char?))
(s/fdef sql/quoted
:args (s/cat :q (s/or :pair (s/coll-of ::delimiter
:kind vector? :count 2)
:delimiter ::delimiter
:dialect #{:ansi :mysql :sqlserver :oracle}))
:ret ::naming-strategy)
(s/fdef sql/get-connection
:args (s/cat :db-spec ::db-spec
:opts (s/? ::connection-options))
:ret ::connection)
(s/fdef sql/result-set-seq
:args (s/cat :rs ::result-set
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/prepare-statement
:args (s/cat :con ::connection
:sql string?
:opts (s/? ::prepare-options))
:ret ::prepared-statement)
;; print-sql-exception, print-sql-exception-chain, print-update-counts
(s/fdef sql/db-find-connection
:args (s/cat :db-spec ::db-spec)
:ret (s/nilable ::connection))
(s/fdef sql/db-connection
:args (s/cat :db-spec ::db-spec)
:ret ::connection)
;; transaction functions
(s/fdef sql/db-set-rollback-only!
:args (s/cat :db ::db-spec))
(s/fdef sql/db-unset-rollback-only!
:args (s/cat :db ::db-spec))
(s/fdef sql/db-is-rollback-only
:args (s/cat :db ::db-spec)
:ret boolean?)
(s/fdef sql/get-isolation-level
:args (s/cat :db ::db-spec)
:ret (s/nilable (s/or :isolation ::isolation
:unknown #{:unknown})))
(s/fdef sql/db-transaction*
:args (s/cat :db ::db-spec
:func ifn?
:opts (s/? ::transaction-options))
:ret any?)
(s/def ::transaction-binding (s/spec (s/cat :t-con simple-symbol?
:db-spec any?
:opts (s/? any?))))
(s/fdef sql/with-db-transaction
:args (s/cat :binding ::transaction-binding
:body (s/* any?)))
(s/def ::simple-binding (s/spec (s/cat :con-db simple-symbol?
:db-spec any?)))
(s/fdef sql/with-db-connection
:args (s/cat :binding ::simple-binding
:body (s/* any?)))
(s/fdef sql/with-db-metadata
:args (s/cat :binding ::simple-binding
:body (s/* any?)))
(s/fdef sql/metadata-result
:args (s/cat :rs-or-value any?
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/metadata-query
:args (s/cat :meta-query any?
:opt-args (s/? any?)))
(s/fdef sql/db-do-commands
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-commands (s/or :command string?
:commands (s/coll-of string?)))
:ret any?)
(s/fdef sql/db-do-prepared-return-keys
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-params ::sql-params
:opts (s/? (s/merge ::execute-options ::query-options)))
:ret any?)
(s/fdef sql/db-do-prepared
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-params ::sql-params
;; TODO: this set of options needs reviewing:
:opts (s/? (s/merge ::execute-options ::query-options)))
:ret any?)
(s/fdef sql/db-query-with-resultset
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:func ifn?
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/query
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? (s/merge ::query-options
(s/keys :req-un []
:opt-un [::explain?
::explain-fn]))))
:ret any?)
(s/fdef sql/reducible-result-set
:args (s/cat :rs ::result-set
:opts (s/? ::reducible-query-options))
:ret any?)
(s/fdef sql/reducible-query
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? ::reducible-query-options))
:ret any?)
(s/fdef sql/find-by-keys
:args (s/cat :db ::db-spec
:table ::identifier
:columns (s/map-of ::identifier ::sql-value)
:opts (s/? ::find-by-keys-options))
:ret any?)
(s/fdef sql/get-by-id
:args (s/cat :db ::db-spec
:table ::identifier
:pk-value ::sql-value
:opt-args (s/cat :pk-name (s/? ::identifier)
:opts (s/? ::find-by-keys-options)))
:ret any?)
(s/fdef sql/execute!
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? ::execute-options))
:ret ::execute-result)
(s/fdef sql/delete!
:args (s/cat :db ::db-spec
:table ::identifier
:where-clause (s/spec ::where-clause)
:opts (s/? ::exec-sql-options))
:ret ::execute-result)
(s/fdef sql/insert!
:args (s/or :row (s/cat :db ::db-spec
:table ::identifier
:row (s/map-of ::identifier any?)
:opts (s/? (s/merge ::execute-options ::query-options)))
:cvs (s/cat :db ::db-spec
:table ::identifier
:cols (s/nilable (s/coll-of ::identifier))
:vals (s/coll-of any?)
:opts (s/? (s/merge ::execute-options ::query-options))))
:ret any?)
(s/fdef sql/insert-multi!
:args (s/or :rows (s/cat :db ::db-spec
:table ::identifier
:rows (s/coll-of (s/map-of ::identifier any?))
:opts (s/? (s/merge ::execute-options ::query-options)))
:cvs (s/cat :db ::db-spec
:table ::identifier
:cols (s/nilable (s/coll-of ::identifier))
:vals (s/coll-of (s/coll-of any?))
:opts (s/? (s/merge ::execute-options ::query-options))))
:ret any?)
(s/fdef sql/update!
:args (s/cat :db ::db-spec
:table ::identifier
:set-map (s/map-of ::identifier ::sql-value)
:where-clause (s/spec ::where-clause)
:opts (s/? ::exec-sql-options))
:ret ::execute-result)
(s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword? :str string?))))
(s/fdef sql/create-table-ddl
:args (s/cat :table ::identifier
:specs (s/coll-of ::column-spec)
:opts (s/? (s/keys :req-un []
:opt-un [::entities
::conditional?
::table-spec])))
:ret string?)
(s/fdef sql/drop-table-ddl
:args (s/cat :table ::identifier
:opts (s/? (s/keys :req-un []
:opt-un [::entities
::conditional?])))
:ret string?)
java.jdbc-java.jdbc-0.7.0/src/test/ 0000775 0000000 0000000 00000000000 13132773030 0016725 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/test/clojure/ 0000775 0000000 0000000 00000000000 13132773030 0020370 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/test/clojure/clojure/ 0000775 0000000 0000000 00000000000 13132773030 0022033 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/test/clojure/clojure/java/ 0000775 0000000 0000000 00000000000 13132773030 0022754 5 ustar 00root root 0000000 0000000 java.jdbc-java.jdbc-0.7.0/src/test/clojure/clojure/java/test_jdbc.clj 0000664 0000000 0000000 00000143530 13132773030 0025415 0 ustar 00root root 0000000 0000000 ;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; test_jdbc.clj
;;
;; This namespace contains tests that exercise the JDBC portion of java.jdbc
;; so these tests expect databases to be available. Embedded databases can
;; be tested without external infrastructure (Apache Derby, HSQLDB). Other
;; databases will be available for testing in different environments. The
;; available databases for testing can be configured below.
;;
;; scgilardi (gmail)
;; Created 13 September 2008
;;
;; seancorfield (gmail)
;; Migrated from clojure.contrib.test-sql 17 April 2011
(ns clojure.java.test-jdbc
(:require [clojure.test :refer :all]
[clojure.java.jdbc :as sql]
[clojure.string :as str]))
(def with-spec? (try
(require 'clojure.java.jdbc.spec)
(require 'clojure.spec.test.alpha)
;; require this to workaround rebinding of report multi-fn
(require 'clojure.test.check.clojure-test)
(let [syms ((resolve 'clojure.spec.test.alpha/enumerate-namespace) 'clojure.java.jdbc)]
((resolve 'clojure.spec.test.alpha/instrument) syms))
(println "Instrumenting clojure.java.jdbc with clojure.spec")
true
(catch Exception _
false)))
;; Set test-databases according to whether you have the local database available:
;; Possible values so far: [:mysql :postgres :derby :hsqldb :mysql-str :postgres-str]
;; Apache Derby and HSQLDB can run without an external setup.
(def test-databases
(if-let [dbs (System/getenv "TEST_DBS")]
(map keyword (.split dbs ","))
;; enable more by default once the build server is equipped?
[:derby :hsqldb :h2 :sqlite]))
;; MS SQL Server requires more specialized configuration:
(def mssql-host (or (System/getenv "TEST_MSSQL_HOST") "127.0.0.1\\SQLEXPRESS"))
(def mssql-port (or (System/getenv "TEST_MSSQL_PORT") "1433"))
(def mssql-user (or (System/getenv "TEST_MSSQL_USER") "sa"))
(def mssql-pass (or (System/getenv "TEST_MSSQL_PASS") ""))
(def mssql-dbname (or (System/getenv "TEST_MSSQL_NAME") "clojure_test"))
(def jtds-host (or (System/getenv "TEST_JTDS_HOST") mssql-host))
(def jtds-port (or (System/getenv "TEST_JTDS_PORT") mssql-port))
(def jtds-user (or (System/getenv "TEST_JTDS_USER") mssql-user))
(def jtds-pass (or (System/getenv "TEST_JTDS_PASS") mssql-pass))
(def jtds-dbname (or (System/getenv "TEST_JTDS_NAME") mssql-dbname))
;; PostgreSQL host/port
(def postgres-host (or (System/getenv "TEST_POSTGRES_HOST") "127.0.0.1"))
(def postgres-port (or (System/getenv "TEST_POSTGRES_PORT") "5432"))
;; database connections used for testing:
(def mysql-db {:dbtype "mysql"
:dbname "clojure_test"
:user "clojure_test"
:password "clojure_test"})
(def derby-db {:dbtype "derby"
:dbname "clojure_test_derby"
:create true})
(def hsqldb-db {:dbtype "hsql"
:dbname "clojure_test_hsqldb"})
(def h2-db {:dbtype "h2"
:dbname "./clojure_test_h2"})
(def sqlite-db {:dbtype "sqlite"
:dbname "clojure_test_sqlite"})
(def postgres-db {:dbtype "postgres"
:dbname "clojure_test"
:host postgres-host
:port postgres-port
:user "clojure_test"
:password "clojure_test"})
(def pgsql-db {:dbtype "pgsql"
:dbname "clojure_test"
:host postgres-host
:port postgres-port
:user "clojure_test"
:password "clojure_test"})
(def mssql-db {:dbtype "mssql"
:dbname mssql-dbname
:host mssql-host
:port mssql-port
:user mssql-user
:password mssql-pass})
(def jtds-db {:dbtype "jtds"
:dbname jtds-dbname
:host jtds-host
:port jtds-port
:user jtds-user
:password jtds-pass})
;; To test against the stringified DB connection settings:
(def mysql-str-db
"mysql://clojure_test:clojure_test@localhost:3306/clojure_test")
(def mysql-jdbc-str-db
"jdbc:mysql://clojure_test:clojure_test@localhost:3306/clojure_test")
(def postgres-str-db
"postgres://clojure_test:clojure_test@localhost/clojure_test")
(defn- test-specs
"Return a sequence of db-spec maps that should be used for tests"
[]
(for [db test-databases]
@(ns-resolve 'clojure.java.test-jdbc (symbol (str (name db) "-db")))))
(defn- clean-up
"Attempt to drop any test tables before we start a test."
[t]
(doseq [db (test-specs)]
(doseq [table [:fruit :fruit2 :veggies :veggies2]]
(try
(sql/db-do-commands db (sql/drop-table-ddl table))
(catch java.sql.SQLException _))))
;; ignore
(t))
(use-fixtures
:each clean-up)
;; We start with all tables dropped and each test has to create the tables
;; necessary for it to do its job, and populate it as needed...
(defn- derby? [db]
(if (string? db)
(re-find #"derby:" db)
(= "derby" (or (:subprotocol db) (:dbtype db)))))
(defn- hsqldb? [db]
(if (string? db)
(re-find #"hsqldb:" db)
(#{"hsql" "hsqldb"} (or (:subprotocol db) (:dbtype db)))))
(defn- mssql? [db]
(if (string? db)
(re-find #"sqlserver" db)
(#{"jtds" "jtds:sqlserver" "mssql" "sqlserver"}
(or (:subprotocol db) (:dbtype db)))))
(defn- mysql? [db]
(if (string? db)
(re-find #"mysql:" db)
(= "mysql" (or (:subprotocol db) (:dbtype db)))))
(defn- postgres? [db]
(if (string? db)
(or (re-find #"postgres" db) (re-find #"pgsql"))
(or (re-find #"postgres" (or (:subprotocol db) (:dbtype db)))
(re-find #"pgsql" (or (:subprotocol db) (:dbtype db))))))
(defn- pgsql? [db]
(if (string? db)
(re-find #"pgsql")
(re-find #"pgsql" (or (:subprotocol db) (:dbtype db)))))
(defn- sqlite? [db]
(if (string? db)
(re-find #"sqlite:" db)
(= "sqlite" (or (:subprotocol db) (:dbtype db)))))
(defmulti create-test-table
"Create a standard test table. Uses db-do-commands.
For MySQL, ensure table uses an engine that supports transactions!"
(fn [table db]
(cond
(mysql? db) :mysql
(postgres? db) :postgres
:else :default)))
(defmethod create-test-table :mysql
[table db]
(sql/db-do-commands
db (sql/create-table-ddl
table
[[:id :int "PRIMARY KEY AUTO_INCREMENT"]
[:name "VARCHAR(32)"]
[:appearance "VARCHAR(32)"]
[:cost :int]
[:grade :real]]
{:table-spec "ENGINE=InnoDB"})))
(defmethod create-test-table :postgres
[table db]
(sql/db-do-commands
db (sql/create-table-ddl
table
[[:id :serial "PRIMARY KEY"]
[:name "VARCHAR(32)"]
[:appearance "VARCHAR(32)"]
[:cost :int]
[:grade :real]]
{:table-spec ""})))
(defmethod create-test-table :default
[table db]
(sql/db-do-commands
db (sql/create-table-ddl
table
[[:id :int "DEFAULT 0"]
[:name "VARCHAR(32)" "PRIMARY KEY"]
[:appearance "VARCHAR(32)"]
[:cost :int]
[:grade :real]]
{:table-spec ""})))
(deftest test-drop-table-ddl
(is (= "DROP TABLE something" (sql/drop-table-ddl :something))))
(deftest test-uri-spec-parsing
(is (= {:advanced "false" :ssl "required" :password "clojure_test"
:user "clojure_test" :subname "//localhost/clojure_test"
:subprotocol "postgresql"}
(@#'sql/parse-properties-uri
(java.net.URI.
(str "postgres://clojure_test:clojure_test@localhost/clojure_test?"
"ssl=required&advanced=false")))))
(is (= {:password "clojure_test" :user "clojure_test"
:subname "//localhost:3306/clojure_test", :subprotocol "mysql"}
(@#'sql/parse-properties-uri
(java.net.URI.
"mysql://clojure_test:clojure_test@localhost:3306/clojure_test")))))
(defn- returned-key [db k]
(case (or (:subprotocol db) (:dbtype db))
"derby" {(keyword "1") nil}
("hsql" "hsqldb") nil
"h2" nil
"mysql" {:generated_key k}
nil (if (mysql? db) ; string-based tests
{:generated_key k}
k)
("jtds" "jtds:sqlserver") {:id nil}
("mssql" "sqlserver") {:generated_keys nil}
"sqlite" {(keyword "last_insert_rowid()") k}
k))
(defn- select-key [db]
(case (or (:subprotocol db) (:dbtype db))
("postgres" "postgresql" "pgsql") :id
identity))
(defn- generated-key [db k]
(case (or (:subprotocol db) (:dbtype db))
"derby" 0
("hsql" "hsqldb") 0
"h2" 0
("jtds" "jtds:sqlserver") 0
("mssql" "sqlserver") 0
"sqlite" 0
k))
(defn- float-or-double [db v]
(case (or (:subprotocol db) (:dbtype db))
"derby" (Float. v)
"h2" (Float. v)
("jtds" "jtds:sqlserver") (Float. v)
("mssql" "sqlserver") (Float. v)
("postgres" "postgresql" "pgsql") (Float. v)
v))
(deftest test-create-table
(doseq [db (test-specs)]
(create-test-table :fruit db)
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-drop-table
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-commands db (sql/drop-table-ddl :fruit2))
(is (thrown? java.sql.SQLException
(sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-commands
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-commands db "DROP TABLE fruit2")
(is (thrown? java.sql.SQLException
(sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-commands-transaction
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-commands db true "DROP TABLE fruit2")
(is (thrown? java.sql.SQLException
(sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-commands-multi
(doseq [db (test-specs)]
(sql/db-do-commands db
[(sql/create-table-ddl :fruit3
[[:name "VARCHAR(32)"]
[:appearance "VARCHAR(32)"]
[:cost :int]])
"DROP TABLE fruit3"])
(is (thrown? java.sql.SQLException
(sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-commands-multi-transaction
(doseq [db (test-specs)]
(sql/db-do-commands db true
[(sql/create-table-ddl :fruit3
[[:name "VARCHAR(32)"]
[:appearance "VARCHAR(32)"]
[:cost :int]])
"DROP TABLE fruit3"])
(is (thrown? java.sql.SQLException
(sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared1a
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
;; single string is acceptable
(sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")
(is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared1b
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(with-open [con (sql/get-connection db)]
(let [stmt (sql/prepare-statement con "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )")]
;; single PreparedStatement is acceptable
(is (= [1] (sql/db-do-prepared db stmt)))))
(is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared1ci
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(is (= (returned-key db 1)
((select-key db) (sql/db-do-prepared-return-keys db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"))))
(is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared1cii
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(is (= (returned-key db 1)
((select-key db) (sql/db-do-prepared-return-keys db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"]))))
(is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared1di
(doseq [db (test-specs)]
(create-test-table :fruit db)
(with-open [con (sql/get-connection db)]
(let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"
{:return-keys true})]
(is (= (returned-key db 1)
((select-key db) (sql/db-do-prepared-return-keys db [stmt]))))))
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-do-prepared1dii
(doseq [db (test-specs)]
(create-test-table :fruit db)
(with-open [con (sql/get-connection db)]
(let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"
{:return-keys true})]
(is (= (returned-key db 1)
((select-key db) (sql/db-do-prepared-return-keys db stmt))))))
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-do-prepared1e
(doseq [db (test-specs)]
;; Derby/SQL Server does not have auto-generated id column which we're testing here
(when-not (#{"derby" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db)))
(create-test-table :fruit db)
(with-open [con (sql/get-connection db)]
(let [stmt (sql/prepare-statement con "INSERT INTO fruit ( name, appearance, cost, grade ) VALUES ( 'test', 'test', 1, 1.0 )"
{:return-keys ["id"]})]
(is (= (returned-key db 1) ((select-key db) (sql/db-do-prepared-return-keys db stmt))))))
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))))
(deftest test-do-prepared2
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-prepared db "DROP TABLE fruit2")
(is (thrown? java.sql.SQLException
(sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared3a
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-prepared db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0]] {:multi? true})
(is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared3b
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-prepared db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" "test" "test" 1 1.0])
(is (= 1 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-do-prepared4
(doseq [db (test-specs)]
(create-test-table :fruit2 db)
(sql/db-do-prepared db ["INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["two" "two" 2 2.0]] {:multi? true})
(is (= 2 (sql/query db ["SELECT * FROM fruit2"] {:result-set-fn count})))))
(deftest test-insert-rows
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [r (sql/insert-multi! db
:fruit
nil
[[1 "Apple" "red" 59 87]
[2 "Banana" "yellow" 29 92.2]
[3 "Peach" "fuzzy" 139 90.0]
[4 "Orange" "juicy" 139 88.6]])]
(is (= '(1 1 1 1) r)))
(is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= 4 (sql/with-db-connection [con db]
(sql/query con (sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit") {:result-set-fn count}))))
(when-not (pgsql? db)
;; maxRows does not appear to be supported on Impossibl pgsql?
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count :max-rows 2})))
(is (= 2 (sql/with-db-connection [con db]
(sql/query con [(sql/prepare-statement (sql/db-connection con) "SELECT * FROM fruit" {:max-rows 2})] {:result-set-fn count})))))
(is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"] {:row-fn :name :result-set-fn first})))
(is (= "juicy" (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Orange"] {:row-fn :appearance :result-set-fn first})))
(is (= "Apple" (:name (sql/get-by-id db :fruit 1))))
(is (= ["Apple"] (map :name (sql/find-by-keys db :fruit {:appearance "red"}))))
(is (= "Peach" (:name (sql/get-by-id db :fruit 3 :id))))
(is (= ["Peach"] (map :name (sql/find-by-keys db :fruit {:id 3 :cost 139}))))
(is (= ["Peach" "Orange"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [:id]}))))
(is (= ["Orange" "Peach"] (map :name (sql/find-by-keys db :fruit {:cost 139} {:order-by [{:appearance :desc}]}))))
;; reduce with init (and ensure we can pass :fetch-size & connection opts through)
(is (= 466 (reduce (fn [n r] (+ n (:cost r))) 100
(sql/reducible-query db "SELECT * FROM fruit"
(cond-> {:fetch-size 100}
(not (sqlite? db))
(assoc :read-only? true)
(not (derby? db))
(assoc :auto-commit? false))))))
;; reduce without init -- uses first row as init!
(is (= 366
(:cost (reduce (fn
([] (throw (ex-info "I should not be called!" {})))
([m r] (update-in m [:cost] + (:cost r))))
(sql/reducible-query db "SELECT * FROM fruit")))))
;; verify reduce without init on empty rs calls 0-arity only
(is (= "Zero-arity!"
(reduce (fn
([] "Zero-arity!")
([m r] (throw (ex-info "I should not be called!"
{:m m :r r}))))
(sql/reducible-query db "SELECT * FROM fruit WHERE ID = -99"))))
;; verify reduce with init does not call f for empty rs
(is (= "Unchanged!"
(reduce (fn
([] (throw (ex-info "I should not be called!" {})))
([m r] (throw (ex-info "I should not be called!"
{:m m :r r}))))
"Unchanged!"
(sql/reducible-query db "SELECT * FROM fruit WHERE ID = -99"))))
;; verify reduce without init does not call f if only one row is in the rs
(is (= "Orange"
(:name (reduce (fn
([] (throw (ex-info "I should not be called!" {})))
([m r] (throw (ex-info "I should not be called!"
{:m m :r r}))))
(sql/reducible-query db "SELECT * FROM fruit WHERE ID = 4")))))
;; verify reduce with init does not call 0-arity f and
;; only calls 2-arity f once if only one row is in the rs
(is (= 239
(reduce (fn
([] (throw (ex-info "I should not be called!" {})))
;; cannot be called on its own result:
([m r] (+ (:a m) (:cost r))))
{:a 100}
(sql/reducible-query db "SELECT * FROM fruit WHERE ID = 4"))))
;; plain old into (uses (reduce conj coll) behind the scenes)
(is (= 4 (count (into [] (sql/reducible-query db "SELECT * FROM fruit")))))
;; transducing into
(is (= [29 59 139 139]
(into []
(map :cost)
(sql/reducible-query db (str "SELECT * FROM fruit"
" ORDER BY cost")))))
;; transduce without init (calls (+) to get init value)
(is (= 366 (transduce (map :cost) +
(sql/reducible-query db "SELECT * FROM fruit"))))
;; transduce with init
(is (= 466 (transduce (map :cost) + 100
(sql/reducible-query db "SELECT * FROM fruit"))))))
(deftest test-insert-values
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [r (sql/insert-multi! db
:fruit
[:name :cost]
[["Mango" 722]
["Feijoa" 441]])]
(is (= '(1 1) r)))
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= "Mango" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 722] {:row-fn :name :result-set-fn first})))))
(deftest test-insert-records
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [r (map (select-key db) (sql/insert-multi! db
:fruit
[{:name "Pomegranate" :appearance "fresh" :cost 585}
{:name "Kiwifruit" :grade 93}]))]
(is (= (list (returned-key db 1) (returned-key db 2)) r)))
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= "Pomegranate" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 585] {:row-fn :name :result-set-fn first})))))
(deftest test-insert-via-execute
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) "
"VALUES ( ?, ?, ? )")
"Apple" "Green" 75])
(sql/execute! db [(str "INSERT INTO fruit ( name, appearance, cost ) "
"VALUES ( 'Pear', 'Yellow', 99 )")])
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99]
{:row-fn :name :result-set-fn first})))))
(deftest execute-with-prepared-statement
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/with-db-connection [conn db]
(let [connection (:connection conn)
prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) "
"VALUES ( ?, ?, ? )"))]
(sql/execute! db [prepared-statement "Apple" "Green" 75])
(sql/execute! db [prepared-statement "Pear" "Yellow" 99])))
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99]
{:row-fn :name :result-set-fn first})))))
(deftest execute-with-prepared-statement-return-keys
(doseq [db (test-specs)]
;; Derby/SQL Server does not have auto-generated id column which we're testing here
(when-not (#{"derby" "jtds" "jtds:sqlserver"} (or (:subprotocol db) (:dbtype db)))
(create-test-table :fruit db)
(sql/with-db-connection [conn db]
(let [connection (:connection conn)
prepared-statement (sql/prepare-statement connection (str "INSERT INTO fruit ( name, appearance, cost ) "
"VALUES ( ?, ?, ? )")
{:return-keys ["id"]})]
;; what is returned is affected row counts due to how execute! works
(is (= [1] (sql/execute! db [prepared-statement "Apple" "Green" 75])))
(is (= [1] (sql/execute! db [prepared-statement "Pear" "Yellow" 99])))))
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= "Pear" (sql/query db ["SELECT * FROM fruit WHERE cost = ?" 99]
{:row-fn :name :result-set-fn first}))))))
(deftest test-update-values
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [r (sql/insert-multi! db
:fruit
nil
[[1 "Apple" "red" 59 87]
[2 "Banana" "yellow" 29 92.2]
[3 "Peach" "fuzzy" 139 90.0]
[4 "Orange" "juicy" 89 88.6]])]
(is (= '(1 1 1 1) r)))
(sql/update! db
:fruit
{:appearance "bruised" :cost 14}
["name=?" "Banana"])
(is (= 4 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= "Apple" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "red"]
{:row-fn :name :result-set-fn first})))
(is (= "Banana" (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "bruised"]
{:row-fn :name :result-set-fn first})))
(is (= 14 (sql/query db ["SELECT * FROM fruit WHERE name = ?" "Banana"]
{:row-fn :cost :result-set-fn first})))))
(defn update-or-insert-values
[db table row where]
(sql/with-db-transaction [t-conn db]
(let [result (sql/update! t-conn table row where)]
(if (zero? (first result))
(sql/insert! t-conn table row)
result))))
(defn update-or-insert-values-with-isolation
[db table row where]
(sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}]
(let [result (sql/update! t-conn table row where)]
(if (zero? (first result))
(sql/insert! t-conn table row)
result))))
(deftest test-update-or-insert-values
(doseq [db (test-specs)]
(create-test-table :fruit db)
(update-or-insert-values db
:fruit
{:name "Pomegranate" :appearance "fresh" :cost 585}
["name=?" "Pomegranate"])
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"]
{:row-fn :cost :result-set-fn first})))
(update-or-insert-values db
:fruit
{:name "Pomegranate" :appearance "ripe" :cost 565}
["name=?" "Pomegranate"])
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"]
{:row-fn :cost :result-set-fn first})))
(update-or-insert-values db
:fruit
{:name "Apple" :appearance "green" :cost 74}
["name=?" "Apple"])
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-update-or-insert-values-with-isolation
(doseq [db (test-specs)]
(create-test-table :fruit db)
(update-or-insert-values-with-isolation db
:fruit
{:name "Pomegranate" :appearance "fresh" :cost 585}
["name=?" "Pomegranate"])
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= 585 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "fresh"]
{:row-fn :cost :result-set-fn first})))
(update-or-insert-values db
:fruit
{:name "Pomegranate" :appearance "ripe" :cost 565}
["name=?" "Pomegranate"])
(is (= 1 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))
(is (= 565 (sql/query db ["SELECT * FROM fruit WHERE appearance = ?" "ripe"]
{:row-fn :cost :result-set-fn first})))
(update-or-insert-values db
:fruit
{:name "Apple" :appearance "green" :cost 74}
["name=?" "Apple"])
(is (= 2 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(defn- file-not-found-exception-via-reflection
"In Clojure 1.3.0 this caused a wrapped exception and we introduced throw-non-rte
to workaround that. This was fixed in 1.4.0 but we never removed the workaround.
Added this hack from the mailing list specifically to test the exception handling
so that we can verify only Clojure 1.3.0 fails the tests and drop support for it."
[f]
(java.io.FileReader. f))
(deftest test-partial-exception
(doseq [db (test-specs)]
(create-test-table :fruit db)
(try
(sql/with-db-transaction [t-conn db]
(sql/insert-multi! t-conn
:fruit
[:name :appearance]
[["Grape" "yummy"]
["Pear" "bruised"]])
(is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))
(file-not-found-exception-via-reflection "/etc/password_no_such_file"))
(catch java.io.FileNotFoundException _
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count}))))
(catch Exception _
(is false "Unexpected exception encountered (not wrapped?).")))))
(deftest test-partial-exception-with-isolation
(doseq [db (test-specs)]
(create-test-table :fruit db)
(try
(sql/with-db-transaction [t-conn db {:isolation :serializable}]
(sql/insert-multi! t-conn
:fruit
[:name :appearance]
[["Grape" "yummy"]
["Pear" "bruised"]])
(is (= 2 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count})))
(throw (Exception. "deliberate exception")))
(catch Exception _
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))))
(defmacro illegal-arg-or-spec
"Execute a form in the context of a try/catch that verifies either
IllegalArgumentException was thrown or a spec violation occurred
so that we can test transparently across Clojure 1.7 to 1.9+."
[fn-name & body]
`(try
~@body
(is false (str "Illegal arguments to " ~fn-name " were not detected!"))
(catch IllegalArgumentException _#)
(catch clojure.lang.ExceptionInfo e#
(is (re-find #"did not conform to spec" (.getMessage e#))))))
(deftest test-sql-exception
(doseq [db (test-specs)]
(create-test-table :fruit db)
(illegal-arg-or-spec "insert!"
(sql/with-db-transaction [t-conn db]
(sql/insert! t-conn
:fruit
[:name :appearance]
["Apple" "strange" "whoops"])))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-sql-exception-with-isolation
(doseq [db (test-specs)]
(create-test-table :fruit db)
(illegal-arg-or-spec "insert!"
(sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}]
(sql/insert! t-conn
:fruit
[:name :appearance]
["Apple" "strange" "whoops"])))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-insert-values-exception
(doseq [db (test-specs)]
(create-test-table :fruit db)
(illegal-arg-or-spec "insert-multi!"
(sql/with-db-transaction [t-conn db]
(sql/insert-multi! t-conn
:fruit
[:name :appearance]
[["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange" "whoops"]])))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-insert-values-exception-with-isolation
(doseq [db (test-specs)]
(create-test-table :fruit db)
(illegal-arg-or-spec
(sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}]
(sql/insert-multi! t-conn
:fruit
[:name :appearance]
[["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange" "whoops"]])))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-rollback
(doseq [db (test-specs)]
(create-test-table :fruit db)
(try
(sql/with-db-transaction [t-conn db]
(is (not (sql/db-is-rollback-only t-conn)))
(sql/db-set-rollback-only! t-conn)
(is (sql/db-is-rollback-only t-conn))
(sql/insert-multi! t-conn
:fruit
[:name :appearance]
[["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange"]])
(is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))))
(catch java.sql.SQLException _
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-rollback-with-isolation
(doseq [db (test-specs)]
(create-test-table :fruit db)
(try
(sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}]
(is (not (sql/db-is-rollback-only t-conn)))
(sql/db-set-rollback-only! t-conn)
(is (sql/db-is-rollback-only t-conn))
(sql/insert-multi! t-conn
:fruit
[:name :appearance]
[["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange"]])
(is (= 3 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))))
(catch java.sql.SQLException _
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-transactions-with-possible-generated-keys-result-set
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/with-db-transaction [t-conn db]
(sql/db-set-rollback-only! t-conn)
(sql/insert! t-conn
:fruit
[:name :appearance]
["Grape" "yummy"])
(is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-transactions-with-possible-generated-keys-result-set-and-isolation
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}]
(sql/db-set-rollback-only! t-conn)
(sql/insert! t-conn
:fruit
[:name :appearance]
["Grape" "yummy"])
(is (= 1 (sql/query t-conn ["SELECT * FROM fruit"] {:result-set-fn count}))))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-nested-transactions-check-transaction-isolation-level
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/with-db-transaction [t-conn db {:isolation :read-uncommitted}]
(is (thrown? IllegalStateException
(sql/with-db-transaction [t-conn' t-conn {:isolation :serializable}]
(sql/insert! t-conn'
:fruit
[:name :appearance]
["Grape" "yummy"])))))
(is (= 0 (sql/query db ["SELECT * FROM fruit"] {:result-set-fn count})))))
(deftest test-raw-metadata
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [table-info (with-open [conn (sql/get-connection db)]
(into []
(sql/result-set-seq
(-> conn
(.getMetaData)
(.getTables nil nil nil
(into-array ["TABLE" "VIEW"]))))))]
(is (not= [] table-info))
(is (= "fruit" (-> table-info
first
:table_name
clojure.string/lower-case))))))
(deftest test-metadata-managed
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/with-db-metadata [metadata db]
(let [table-info (sql/metadata-query (.getTables metadata
nil nil nil
(into-array ["TABLE" "VIEW"])))]
(is (not= [] table-info))
(is (= "fruit" (-> table-info
first
:table_name
clojure.string/lower-case)))))))
(deftest test-metadata-managed-computed
(doseq [db (test-specs)]
(create-test-table :fruit db)
(is (= "fruit"
(sql/with-db-metadata [metadata db]
(sql/metadata-query (.getTables metadata
nil nil nil
(into-array ["TABLE" "VIEW"]))
{:row-fn (comp clojure.string/lower-case str :table_name)
:result-set-fn first}))))))
(deftest test-metadata
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/with-db-metadata [metadata db]
;; make sure to close the ResultSet
(with-open [table-info-result (.getTables metadata
nil nil nil
(into-array ["TABLE" "VIEW"]))]
(let [table-info (sql/metadata-result table-info-result)]
(is (not= [] table-info))
(is (= "fruit" (-> table-info
first
:table_name
clojure.string/lower-case))))))))
(deftest empty-query
(doseq [db (test-specs)]
(create-test-table :fruit db)
(is (= [] (sql/query db ["SELECT * FROM fruit"])))))
(deftest query-with-string
(doseq [db (test-specs)]
(create-test-table :fruit db)
(is (= [] (sql/query db "SELECT * FROM fruit")))))
(deftest insert-one-row
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"}))]
(is (= [(returned-key db 1)] new-keys)))))
(deftest insert-one-row-opts
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"} {}))]
(is (= [(returned-key db 1)] new-keys)))))
(deftest insert-one-col-val
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (sql/insert! db :fruit [:name] ["Apple"])]
(is (= [1] new-keys)))))
(deftest insert-one-col-val-opts
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (sql/insert! db :fruit [:name] ["Apple"] {})]
(is (= [1] new-keys)))))
(deftest insert-query
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"}))]
(is (= [(returned-key db 1)] new-keys))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}]
(sql/query db "SELECT * FROM fruit")))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}]
(sql/query db ["SELECT * FROM fruit"])))
(is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}]
(sql/query db ["SELECT * FROM fruit"] {:identifiers str/upper-case})))
(is (= [{:ID (generated-key db 1) :NAME "Apple" :APPEARANCE nil :GRADE nil :COST nil}]
(sql/query (assoc db :identifiers str/upper-case) ["SELECT * FROM fruit"])))
(is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil
:fruit/grade nil :fruit/cost nil}]
(sql/query db ["SELECT * FROM fruit"] {:qualifier "fruit"})))
(is (= [{:fruit/name "Apple"}]
(sql/query db ["SELECT name FROM fruit"]
{:identifiers (comp (partial str "fruit/") str/lower-case)})))
(is (= [{:name "Apple"}]
(sql/query db ["SELECT name FROM fruit"]
{:identifiers (comp keyword str/lower-case)})))
(is (= [{:fruit/id (generated-key db 1) :fruit/name "Apple" :fruit/appearance nil
:fruit/grade nil :fruit/cost nil}]
(sql/query (assoc db :qualifier "fruit") ["SELECT * FROM fruit"])))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}]
(with-open [con (sql/get-connection db)]
(sql/query db [(sql/prepare-statement con "SELECT * FROM fruit")]))))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}]
(sql/query db ["SELECT * FROM fruit"] {:max-rows 1})))
(cond (derby? db) nil
(hsqldb? db) (is (seq (with-out-str
(sql/query db ["SELECT * FROM fruit"]
{:explain? "EXPLAIN PLAN FOR"}))))
(mssql? db) nil
:else (is (seq (with-out-str
(sql/query db ["SELECT * FROM fruit"]
{:explain? true}))))))))
(deftest insert-two-by-map-and-query
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}]))
rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])]
(is (= [(returned-key db 1) (returned-key db 2)] new-keys))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}
{:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows)))))
(deftest insert-identifiers-respected-1
(doseq [db (filter postgres? (test-specs))]
(create-test-table :fruit db)
(let [inserted (sql/insert! db
:fruit
{:name "Apple"}
{:identifiers clojure.string/upper-case
:qualifier "foo"})
rows (sql/query db ["SELECT * FROM fruit ORDER BY name"]
{:identifiers clojure.string/upper-case
:qualifier "foo"})]
(is (= rows inserted)))))
(deftest insert-identifiers-respected-2
(doseq [db (filter postgres? (test-specs))]
(create-test-table :fruit db)
(let [inserted (sql/insert-multi! db
:fruit
[{:name "Apple"} {:name "Pear"}]
{:identifiers clojure.string/upper-case})
rows (sql/query db ["SELECT * FROM fruit ORDER BY name"]
{:identifiers clojure.string/upper-case})]
(is (= rows inserted)))))
(deftest insert-two-by-map-and-query-as-arrays
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert-multi! db :fruit [{:name "Apple"} {:name "Pear"}]))
rows (sql/query db ["SELECT * FROM fruit ORDER BY name"]
{:as-arrays? :cols-as-is})]
(is (= [(returned-key db 1) (returned-key db 2)] new-keys))
(is (= [[:id :name :appearance :cost :grade]
[(generated-key db 1) "Apple" nil nil nil]
[(generated-key db 2) "Pear" nil nil nil]] rows)))))
(deftest insert-two-by-cols-and-query
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [update-counts (sql/insert-multi! db :fruit [:name] [["Apple"] ["Pear"]])
rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])]
(is (= [1 1] update-counts))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance nil :grade nil :cost nil}
{:id (generated-key db 2) :name "Pear" :appearance nil :grade nil :cost nil}] rows)))))
(deftest insert-update-and-query
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"}))
update-result (sql/update! db :fruit {:cost 12 :grade 1.2 :appearance "Green"}
["id = ?" (generated-key db 1)])
rows (sql/query db ["SELECT * FROM fruit"])]
(is (= [(returned-key db 1)] new-keys))
(is (= [1] update-result))
(is (= [{:id (generated-key db 1)
:name "Apple" :appearance "Green"
:grade (float-or-double db 1.2)
:cost 12}] rows)))))
(deftest insert-delete-and-query
(doseq [db (test-specs)]
(create-test-table :fruit db)
(let [new-keys (map (select-key db) (sql/insert! db :fruit {:name "Apple"}))
delete-result (sql/delete! db :fruit
["id = ?" (generated-key db 1)])
rows (sql/query db ["SELECT * FROM fruit"])]
(is (= [(returned-key db 1)] new-keys))
(is (= [1] delete-result))
(is (= [] rows)))))
(deftest insert-delete-and-query-in-connection
(doseq [db (test-specs)]
(sql/with-db-connection [con-db db]
(create-test-table :fruit con-db)
(let [new-keys (map (select-key db) (sql/insert! con-db :fruit {:name "Apple"}))
delete-result (sql/delete! con-db :fruit
["id = ?" (generated-key con-db 1)])
rows (sql/query con-db ["SELECT * FROM fruit"])]
(is (= [(returned-key con-db 1)] new-keys))
(is (= [1] delete-result))
(is (= [] rows))))))
(deftest illegal-insert-arguments
(doseq [db (test-specs)]
(illegal-arg-or-spec "insert!" (sql/insert! db))
(illegal-arg-or-spec "insert!" (sql/insert! db {:name "Apple"} [:name]))
(illegal-arg-or-spec "insert!" (sql/insert! db {:name "Apple"} [:name] {:entities identity}))
(illegal-arg-or-spec "insert!" (sql/insert! db [:name]))
(if with-spec? ; clojure.spec catches this differently
(is (thrown? clojure.lang.ExceptionInfo (sql/insert! db [:name] {:entities identity})))
(is (thrown? ClassCastException (sql/insert! db [:name] {:entities identity}))))))
(deftest test-execute!-fails-with-multi-param-groups
(doseq [db (test-specs)]
(create-test-table :fruit db)
;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException
(is (thrown? Exception
(sql/execute!
db
["INSERT INTO fruit (name,appearance) VALUES (?,?)"
["Apple" "rosy"]
["Pear" "yellow"]
["Orange" "round"]])))))
(deftest test-execute!-with-multi?-true-param-groups
(doseq [db (test-specs)]
(create-test-table :fruit db)
;; RuntimeException -> SQLException -> ArrayIndexOutOfBoundsException
(let [counts (sql/execute!
db
["INSERT INTO fruit (name,appearance) VALUES (?,?)"
["Apple" "rosy"]
["Pear" "yellow"]
["Orange" "round"]]
{:multi? true})
rows (sql/query db ["SELECT * FROM fruit ORDER BY name"])]
(is (= [1 1 1] counts))
(is (= [{:id (generated-key db 1) :name "Apple" :appearance "rosy" :cost nil :grade nil}
{:id (generated-key db 3) :name "Orange" :appearance "round" :cost nil :grade nil}
{:id (generated-key db 2) :name "Pear" :appearance "yellow" :cost nil :grade nil}] rows)))))
(deftest test-resultset-read-column
(extend-protocol sql/IResultSetReadColumn
String
(result-set-read-column [s _ _] ::FOO))
(try
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/insert-multi! db
:fruit
[:name :cost :grade]
[["Crepes" 12 87.7]
["Vegetables" -88 nil]
["Teenage Mutant Ninja Turtles" 0 100.0]])
(is (= {:name ::FOO, :cost -88, :grade nil}
(sql/query db ["SELECT name, cost, grade FROM fruit WHERE name = ?"
"Vegetables"]
{:result-set-fn first}))))
;; somewhat "undo" the first extension
(finally
(extend-protocol sql/IResultSetReadColumn
String
(result-set-read-column [s _ _] s)))))
(deftest test-sql-value
(extend-protocol sql/ISQLValue
clojure.lang.Keyword
(sql-value [_] "KW"))
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/insert! db
:fruit
[:name :cost :grade]
[:test 12 nil])
(is (= {:name "KW", :cost 12, :grade nil}
(sql/query db ["SELECT name, cost, grade FROM fruit"]
{:result-set-fn first}))))
;; somewhat "undo" the first extension
(extend-protocol sql/ISQLValue
clojure.lang.Keyword
(sql-value [k] k)))
(deftest test-sql-parameter
(extend-protocol sql/ISQLParameter
clojure.lang.Keyword
(set-parameter [v ^java.sql.PreparedStatement s ^long i]
(if (= :twelve v)
(.setLong s i 12)
(.setString s i (str (name v) i)))))
(doseq [db (test-specs)]
(create-test-table :fruit db)
(sql/insert! db
:fruit
[:name :cost :grade]
[:test :twelve nil])
(is (= {:name "test1", :cost 12, :grade nil}
(sql/query db ["SELECT name, cost, grade FROM fruit"]
{:result-set-fn first}))))
;; somewhat "undo" the first extension
(extend-protocol sql/ISQLParameter
clojure.lang.Keyword
(set-parameter [v ^java.sql.PreparedStatement s ^long i]
(.setObject s i (sql/sql-value v)))))
java.jdbc-java.jdbc-0.7.0/src/test/clojure/clojure/java/test_utilities.clj 0000664 0000000 0000000 00000010426 13132773030 0026523 0 ustar 00root root 0000000 0000000 ;; Copyright (c) 2008-2016 Sean Corfield, Stephen C. Gilardi.
;; All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; test_utilities.clj
;;
;; This namespace contains tests of all the utility functions within java.jdbc
;; and does not rely on any databases.
;;
;; scgilardi (gmail)
;; Created 13 September 2008
;;
;; seancorfield (gmail)
;; Migrated from clojure.contrib.test-sql 17 April 2011
(ns clojure.java.test-utilities
(:use clojure.test)
(:require [clojure.java.jdbc :as sql]))
(deftest test-print-update-counts
(let [bu-ex (java.sql.BatchUpdateException. (int-array [1 2 3]))]
(let [e (is (thrown? java.sql.BatchUpdateException (throw bu-ex)))
counts-str (with-out-str (sql/print-update-counts e))]
(is (re-find #"^Update counts" counts-str))
(is (re-find #"Statement 0: 1" counts-str))
(is (re-find #"Statement 2: 3" counts-str)))))
(deftest test-print-exception-chain
(let [base-ex (java.sql.SQLException. "Base Message" "Base State")
test-ex (java.sql.BatchUpdateException. "Test Message" "Test State" (int-array [1 2 3]))]
(.setNextException test-ex base-ex)
(let [e (is (thrown? java.sql.BatchUpdateException (throw test-ex)))
except-str (with-out-str (sql/print-sql-exception-chain e))
pattern (fn [s] (java.util.regex.Pattern/compile s java.util.regex.Pattern/DOTALL))]
(is (re-find (pattern "^BatchUpdateException:.*SQLException:") except-str))
(is (re-find (pattern "Message: Test Message.*Message: Base Message") except-str))
(is (re-find (pattern "SQLState: Test State.*SQLState: Base State") except-str)))))
(deftest test-make-name-unique
(let [make-name-unique @#'sql/make-name-unique]
(is (= "a" (make-name-unique '() "a" 1)))
(is (= "a_2" (make-name-unique '("a") "a" 1)))
(is (= "a_3" (make-name-unique '("a" "b" "a_2") "a" 1)))))
(deftest test-make-cols-unique
(let [make-cols-unique @#'sql/make-cols-unique]
(is (= '() (make-cols-unique '())))
(is (= '("a") (make-cols-unique '("a"))))
(is (= '("a" "a_2") (make-cols-unique '("a" "a"))))
(is (= '("a" "b" "a_2" "a_3") (make-cols-unique '("a" "b" "a" "a"))))
(is (= '("a" "b" "a_2" "b_2" "a_3" "b_3") (make-cols-unique '("a" "b" "a" "b" "a" "b"))))))
;; DDL tests
(deftest test-create-table-ddl
(is (= "CREATE TABLE THING (COL1 INT, COL2 int)"
(sql/create-table-ddl :thing [["col1 int"] [:col2 :int]]
{:entities clojure.string/upper-case})))
(is (= "CREATE TABLE THING (COL1 int, COL2 int) ENGINE=MyISAM"
(sql/create-table-ddl :thing [[:col1 "int"] ["col2" :int]]
{:table-spec "ENGINE=MyISAM"
:entities clojure.string/upper-case}))))
;; since we have clojure.spec instrumentation enabled for Clojure 1.9.0
;; we need to account for the fact that we'll get different exceptions
;; for Clojure < 1.9.0 since the spec will trigger first and obscure
;; our own argument checking on 1.9.0+
(defn argument-exception?
"Given a thunk, try to execute it and return true if it throws
either an IllegalArgumentException or a Clojure exception from
clojure.spec."
[thunk]
(try
(thunk)
false
(catch IllegalArgumentException _ true)
(catch clojure.lang.ExceptionInfo e
(re-find #"did not conform to spec" (.getMessage e)))))
(deftest test-invalid-create-table-ddl
(is (argument-exception? (fn [] (sql/create-table-ddl :thing [[]]))))
(is (argument-exception? (fn [] (sql/create-table-ddl :thing [[:col1 "int"] []]))))
(is (argument-exception? (fn [] (sql/create-table-ddl :thing [:col1 "int"])))))
(deftest test-quoted
(is (= "`x`" ((sql/quoted \`) "x")))
(is (= "[x]" ((sql/quoted [\[ \]]) "x")))
(is (= "`x`" ((sql/quoted :mysql) "x")))
(is (= "\"x\"" ((sql/quoted :ansi) "x")))
(is (= "\"x\"" ((sql/quoted :oracle) "x")))
(is (= "[x]" ((sql/quoted :sqlserver) "x"))))