sqlstatement - Generate complex SQL statements programmatically
The main goal of this library is to be able to construct an SQL
from “slices” that concern different aspects of the final query (perhaps
in different places in your code) and then combine them all together
one statement easily.
Another important goal of this library is to give some consistent Ruby
syntax to three statements (INSERT, SELECT, and UPDATE) that seem to
different enough syntax that one has two write different code to
each kind of statement.
I use my SQL database (specifically MySQL) largely as a bulk data
processing engine, by doing INSERTâ€¦SELECT or CREATE TABLEâ€¦SELECT
statements. This library is intended to make that kind of coding easier.
I expect that Object Relational mappers (such as ActiveRecord) are more
useful for most people, who are performing queries and
querying for individual records. I have nevertheless added INSERTâ€¦VALUES
statements, and will add other statements soon, for consistency.
This library is inspired by CLSQL for Common LISP, or SchemeQL for
Scheme, although it is very different from these two libraries. Scheme
and LISPâ€˜s use of s-expressions make it very easy to construct an entire
sublanguage for the WHERE clause, simply by list parsing. The Criteria
library for Ruby has attempted this, but in a more limited manner than
SchemeQL or CLSQL. My library aims to cover much of the functionality in
This library doesnâ€˜t try to abstract out the limitations of your DBMS,
and I think that the SQL it uses should be fairly portable, in large
measure because it hasnâ€˜t attempted to deal with serious CREATE TABLE
statements, where a lot of syntax concerning types, keys and sequences
much more variable.
This library can be downloaded from rubyforge.org/projects/sqlstatement
Changes in this release
* Vastly redesign the DSL. The methods for adding components to an
SQL statement have all been renamed, and internal state is no longer
directly exposed to the outside. The interface is now much more intutive
and consistent. Please read the documentation to find out how this
version of the library works.
* Left joins have been added
* Thereâ€˜s no more SelectParts class â€” the corresponding semantics
have been built directly into the Select class.
* Select.new do |s| â€¦ end syntax has been added
* Select statements now remember the order of fields and tables.
makes the next two changes feasible.
o Support for Mysqlâ€˜s STRAIGHT_JOIN modifier has been added
o Unit tests have been added
If we wanted to generate SQL code similar to
we could generate it as follows:
Select.new do |s|
(1…2).each do |x|
stmt << foo(x)
or like this:
stmt=Select.new do |s|
[1,2].each do |num|