From d2423f99b8d47547c66f2e79d49979dc795e84b0 Mon Sep 17 00:00:00 2001 From: James Moger Date: Thu, 14 Mar 2013 13:17:22 -0400 Subject: update Maven submodule reference --- src/site/00_index.mkd | 63 ------- src/site/01_model_classes.mkd | 335 ---------------------------------- src/site/02_table_versioning.mkd | 29 --- src/site/02_usage.mkd | 197 -------------------- src/site/03_performance.mkd | 22 --- src/site/04_examples.mkd | 196 -------------------- src/site/04_tools.mkd | 95 ---------- src/site/05_building.mkd | 35 ---- src/site/05_javadoc.mkd | 7 - src/site/05_releases.mkd | 223 ---------------------- src/site/06_jaqu_comparison.mkd | 31 ---- src/site/building.mkd | 35 ++++ src/site/custom.less | 2 +- src/site/examples.mkd | 196 ++++++++++++++++++++ src/site/index.mkd | 63 +++++++ src/site/jaqu_comparison.mkd | 31 ++++ src/site/javadoc.mkd | 7 + src/site/model_classes.mkd | 335 ++++++++++++++++++++++++++++++++++ src/site/performance.mkd | 22 +++ src/site/table_versioning.mkd | 29 +++ src/site/templates/atom.ftl | 2 + src/site/templates/macros.ftl | 147 +++++++++++++++ src/site/templates/releasecurrent.ftl | 25 +++ src/site/templates/releasehistory.ftl | 21 +++ src/site/templates/rss.ftl | 2 + src/site/tools.mkd | 95 ++++++++++ src/site/usage.mkd | 197 ++++++++++++++++++++ 27 files changed, 1208 insertions(+), 1234 deletions(-) delete mode 100644 src/site/00_index.mkd delete mode 100644 src/site/01_model_classes.mkd delete mode 100644 src/site/02_table_versioning.mkd delete mode 100644 src/site/02_usage.mkd delete mode 100644 src/site/03_performance.mkd delete mode 100644 src/site/04_examples.mkd delete mode 100644 src/site/04_tools.mkd delete mode 100644 src/site/05_building.mkd delete mode 100644 src/site/05_javadoc.mkd delete mode 100644 src/site/05_releases.mkd delete mode 100644 src/site/06_jaqu_comparison.mkd create mode 100644 src/site/building.mkd create mode 100644 src/site/examples.mkd create mode 100644 src/site/index.mkd create mode 100644 src/site/jaqu_comparison.mkd create mode 100644 src/site/javadoc.mkd create mode 100644 src/site/model_classes.mkd create mode 100644 src/site/performance.mkd create mode 100644 src/site/table_versioning.mkd create mode 100644 src/site/templates/atom.ftl create mode 100644 src/site/templates/macros.ftl create mode 100644 src/site/templates/releasecurrent.ftl create mode 100644 src/site/templates/releasehistory.ftl create mode 100644 src/site/templates/rss.ftl create mode 100644 src/site/tools.mkd create mode 100644 src/site/usage.mkd (limited to 'src') diff --git a/src/site/00_index.mkd b/src/site/00_index.mkd deleted file mode 100644 index 1c2bbd3..0000000 --- a/src/site/00_index.mkd +++ /dev/null @@ -1,63 +0,0 @@ -## Overview - -iciql **is**... - -- a model-based, database access wrapper for JDBC -- for modest database schemas and basic statement generation -- for those who want to write code, instead of SQL, using IDE completion and compile-time type-safety -- small (200KB) with debug symbols and no runtime dependencies -- pronounced *icicle* (although it could be French: *ici ql* - here query language) -- a friendly fork of the H2 [JaQu][jaqu] project - -iciql **is not**... - -- a complete alternative to JDBC -- designed to compete with more powerful database query tools like [jOOQ][jooq] or [Querydsl][querydsl] -- designed to compete with enterprise [ORM][orm] tools like [Hibernate][hibernate] or [mybatis][mybatis] - -### Example Usage - - - - - - - -
iciqlsql
-%BEGINCODE% -Product p = new Product(); -List restock = db.from(p).where(p.unitsInStock).is(0).select(); -List all = db.executeQuery(Product.class, "select * from products"); -%ENDCODE% - - -
-select * from products p where p.unitsInStock = 0
-select * from products -
- -### Supported Databases (Unit-Tested) -- [H2](http://h2database.com) ${h2.version} -- [HSQLDB](http://hsqldb.org) ${hsqldb.version} -- [Derby](http://db.apache.org/derby) ${derby.version} -- [MySQL](http://mysql.com) ${mysql.version} -- [PostgreSQL](http://postgresql.org) ${postgresql.version} - -Support for others is possible and may only require creating a simple "dialect" class. - -### Java Runtime Requirement - -iciql requires a Java 6 Runtime Environment (JRE) or a Java 6 Development Kit (JDK). - -### License -iciql is distributed under the terms of the [Apache Software Foundation license, version 2.0][apachelicense] - -[jaqu]: http://h2database.com/html/jaqu.html "H2 JaQu project" -[orm]: http://en.wikipedia.org/wiki/Object-relational_mapping "Object Relational Mapping" -[jooq]: http://jooq.sourceforge.net "jOOQ" -[querydsl]: http://source.mysema.com/display/querydsl/Querydsl "Querydsl" -[hibernate]: http://www.hibernate.org "Hibernate" -[mybatis]: http://www.mybatis.org "mybatis" -[github]: http://github.com/gitblit/iciql "iciql git repository" -[googlecode]: http://code.google.com/p/iciql "iciql project management" -[apachelicense]: http://www.apache.org/licenses/LICENSE-2.0 "Apache License, Version 2.0" \ No newline at end of file diff --git a/src/site/01_model_classes.mkd b/src/site/01_model_classes.mkd deleted file mode 100644 index 8fedf18..0000000 --- a/src/site/01_model_classes.mkd +++ /dev/null @@ -1,335 +0,0 @@ -## Model Classes -A model class represents a single table within your database. Fields within your model class represent columns in the table. The object types of your fields are reflectively mapped to SQL types by iciql at runtime. - -Models can be manually written using one of three approaches: *annotation configuration*, *interface configuration*, or *POJO configuration*. All approaches can be used within a project and all can be used within a single model class, although that is discouraged. - -Alternatively, model classes can be automatically generated by iciql using the model generation tool. Please see the [tools](tools.html) page for details. - -### Configuration Requirements and Limitations - -1. Your model class **must** provide a public default constructor. -2. All **Object** fields are assumed NULLABLE unless explicitly set *@IQColumn(nullable = false)* or *Define.nullable(field, false)*. -3. All **Primitive** fields are assumed NOT NULLABLE unless explicitly set *@IQColumn(nullable = true)* or *Define.nullable(field, true)*. -4. Only the specified types are supported. Any other types are not supported. -5. Triggers, views, and other advanced database features are not supported. - -### Supported Data Types - ----NOMARKDOWN--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Fully Supported Types
-can be used for all iciql expressions -
ObjectPrimitiveSQL Type
java.lang.StringVARCHAR (length > 0) or CLOB (length == 0)
java.lang.BooleanbooleanBOOLEAN
can only declare and explicitly reference one primitive boolean per model
multiple primitives are allowed if not using where/set/on/and/or/groupBy/orderBy(boolean)
java.lang.BytebyteTINYINT
java.lang.ShortshortSMALLINT
java.lang.IntegerintINT
java.lang.LonglongBIGINT
java.lang.FloatfloatREAL
java.lang.DoubledoubleDOUBLE
java.math.BigDecimal DECIMAL (length == 0) or DECIMAL(length,scale) (length > 0)
java.sql.Date DATE
java.sql.Time TIME
java.sql.Timestamp TIMESTAMP
java.util.Date TIMESTAMP
java.lang.Enum.name()
default type
VARCHAR (length > 0) or CLOB (length == 0)
EnumType.NAME
can only declare and explicitly reference one instance of each enum type per model
multiple instances of an enum type within a model is allowed if not using where/set/on/and/or/groupBy/orderBy(enum)
java.lang.Enum.ordinal() INT
EnumType.ORDINAL
can only declare and explicitly reference one instance of each enum type per model
multiple instances of an enum type within a model is allowed if not using where/set/on/and/or/groupBy/orderBy(enum)
java.lang.Enum implements
com.iciql.Iciql.EnumId.enumId()
INT
EnumType.ENUMID
can only declare and explicitly reference one instance of each enum type per model
multiple instances of an enum type within a model is allowed if not using where/set/on/and/or/groupBy/orderBy(enum)
Partially Supported Types
-can not be directly referenced in an expression
byte [] BLOB
H2 Database Types
-fully supported when paired with an H2 database -
java.util.UUID UUID
----NOMARKDOWN--- -**NOTE:**
-The reverse lookup used for model generation, SQL type -> Java type, contains more mappings.
-Please consult the `com.iciql.ModelUtils` class for details. - -## Annotation Configuration -The recommended approach to setup a model class is to annotate the class and field declarations. - -### advantages - -- annotated models support annotated field inheritance making it possible to design a single base class that defines the fields and then create table subclasses that specify the table mappings. -- model runtime dependency is limited to the small, portable `com.iciql.Iciql` class file which contains the annotation definitions - -### disadvantages - -- more verbose model classes -- indexes are defined using "fragile" string column names -- compound primary keys are defined using "fragile" string column names - -### field mapping - -- By default, **ONLY** fields annotated with *@IQColumn* are mapped. -- scope is irrelevant. -- transient is irrelevant. - -### default values - -You may specify default values for an *@IQColumn* by either: - -1. specifying the default value string within your annotation
-**NOTE:**
-The annotated default value always takes priority over a field default value. -%BEGINCODE% -// notice the single ticks! -@IQColumn(defaultValue="'2000-01-01 00:00:00'") -Date myDate; -%ENDCODE% - -2. setting a default value on the field
-**NOTE:**
-Primitive types have an implicit default value of *0* or *false*. -%BEGINCODE% -@IQColumn -Date myDate = new Date(100, 0, 1); - -@IQColumn -int myId; -%ENDCODE% - -If you want to specify a database-specific variable or function as your default value (e.g. CURRENT_TIMESTAMP) you must do that within the annotation. Also note that the *IQColumn.defaultValue* must be a well-formatted SQL DEFAULT expression whereas object defaults will be automatically converted to an SQL DEFAULT expression. - -### Special Case: primitive autoincrement fields and 0 -%BEGINCODE% -@IQColumn(autoIncrement = true) -int myId; -%ENDCODE% - -Because primitive types have implicit default values, this field will be excluded from an INSERT statement if its value is 0. Iciql can not differentiate an implicit/uninitialized 0 from a explicitly assigned 0. - -### Example Annotated Model -%BEGINCODE% -import com.iciql.Iciql.EnumType; -import com.iciql.Iciql.IQColumn; -import com.iciql.Iciql.IQEnum; -import com.iciql.Iciql.IQIndex; -import com.iciql.Iciql.IQTable; - -@IQTable -@IQIndexes({ - @IQIndex({"productName", "category"}), - @IQIndex(name="nameindex", value="productName") -}) -public class Product { - - @IQEnum(EnumType.ORDINAL) - public enum Availability { - ACTIVE, DISCONTINUED; - } - - @IQColumn(primaryKey = true) - public Integer productId; - - @IQColumn(length = 200, trim = true) - public String productName; - - @IQColumn(length = 50, trim = true) - public String category; - - @IQColumn - public Double unitPrice; - - @IQColumn(name = "units") - public Integer unitsInStock; - - @IQColumn - private Integer reorderQuantity; - - @IQColumn - private Availability availability; - - // ignored because it is not annotated AND the class is @IQTable annotated - private Integer ignoredField; - - public Product() { - // default constructor - } -} -%ENDCODE% - -## Interface Configuration -Alternatively, you may map your model classes using the interface approach by implementing the `com.iciql.Iciql` interface. - -This is a less verbose configuration style, but it comes at the expense of introducing a compile-time dependency on the logic of the iciql library. This might be a deterrent, for example, if you were serializing your model classes to another process that may not have the iciql library. - -The `com.iciql.Iciql` interface specifies a single method, *defineIQ()*. In your implementation of *defineIQ()* you would use static method calls to set: - -- the schema name -- the table name (if it's not the class name) -- the column name (if it's not the field name) -- the max length and trim of a string field -- the precision and scale of a decimal field -- the autoincrement flag of a long or integer field -- the nullable flag of a field -- the primaryKey (single field or compound) -- any indexes (single field or compound) - -### advantages - -- less verbose model class -- compile-time index definitions -- compile-time compound primary key definitions - -### disadvantages - -- model runtime dependency on entire iciql library -- *defineIQ()* is called from a static synchronized block which may be a bottleneck for highly concurrent systems - -### field mapping - -- **ALL** fields are mapped unless annotated with *@IQIgnore*. -- scope is irrelevant. -- transient is irrelevant. - -### default values - -You may specify default values for an field by either: - -1. specifying the default value string within your *defineIQ()* method
-**NOTE:**
-The defineIQ() value always takes priority over a field default value. -%BEGINCODE% -Date myDate; - -public void defineIQ() { - // notice the single ticks! - Define.defaultValue(myDate, "'2000-01-01 00:00:00'"); -} -%ENDCODE% - -2. setting a default value on the field
-**NOTE:**
-Primitive types have an implicit default value of *0* or *false*. -%BEGINCODE% -Date myDate = new Date(100, 0, 1); - -int myId; -%ENDCODE% - -### Example Interface Model -%BEGINCODE% -import com.iciql.Iciql; -import com.iciql.Iciql.IQIgnore; - -public class Product implements Iciql { - public Integer productId; - public String productName; - public String category; - public Double unitPrice; - public Integer unitsInStock; - - @IQIgnore - Integer reorderQuantity; - - public Product() { - } - - @Override - public void defineIQ() { - com.iciql.Define.primaryKey(productId); - com.iciql.Define.columnName(unitsInStock, "units"); - com.iciql.Define.length(productName, 200); - com.iciql.Define.length(category, 50); - com.iciql.Define.index(productName, category); - } -} -%ENDCODE% - - -## POJO (Plain Old Java Object) Configuration - -This approach is very similar to the *interface configuration* approach; it is the least verbose and also the least useful. - -This approach would be suitable for quickly modeling an existing table where only SELECT and INSERT statements will be generated. - -### advantages - -- nearly zero-configuration - -### disadvantages - -- can not execute DELETE, UPDATE, or MERGE statements (they require a primary key specification) -- table name MUST MATCH model class name -- column names MUST MATCH model field names -- can not specify any column attributes -- can not specify indexes - -### field mapping - -- **ALL** fields are mapped unless annotated with *@IQIgnore*. -- scope is irrelevant. -- transient is irrelevant. - -### default values - -You may specify a default value on the field. - -**NOTE:**
-Primitive types have an implicit default value of *0* or *false*. -%BEGINCODE% -Date myDate = new Date(100, 0, 1); - -int myId; -%ENDCODE% - -### Example POJO Model -%BEGINCODE% -import com.iciql.Iciql.IQIgnore; - -public class Product { - public Integer productId; - public String productName; - public String category; - public Double unitPrice; - public Integer units; - - @IQIgnore - Integer reorderQuantity; - - public Product() { - } -} -%ENDCODE% \ No newline at end of file diff --git a/src/site/02_table_versioning.mkd b/src/site/02_table_versioning.mkd deleted file mode 100644 index 2e95aaa..0000000 --- a/src/site/02_table_versioning.mkd +++ /dev/null @@ -1,29 +0,0 @@ -## Database & Table Versioning - -Iciql supports an optional, simple versioning mechanism. There are two parts to the mechanism. - -1. You must supply an implementation of `com.iciql.DbUpgrader` to your `com.iciql.Db` instance. -2. One or more of your table model classes must specify the `IQVersion(version)` annotation
-AND/OR
-Your `com.iciql.DbUpgrader` implementation must specify the `IQVersion(version)` annotation - -### How does it work? -If you choose to use versioning, iciql will maintain a table within your database named *iq_versions* which is defined as: - - CREATE TABLE IQ_VERSIONS(SCHEMANAME VARCHAR(255) NOT NULL, TABLENAME VARCHAR(255) NOT NULL, VERSION INT NOT NULL) - -This database table is automatically created if and only if at least one of your model classes specifies a *version* > 0. - -When you generate a statement, iciql will compare the annotated version field of your model class to its last known value in the *iq_versions* table. If *iq_versions* lags behind the model annotation, iciql will immediately call the registered `com.iciql.DbUpgrader` implementation before generating and executing the current statement. - -When an upgrade scenario is identified, the current version and the annotated version information is passed to either: - -- `DbUpgrader.upgradeDatabase(db, fromVersion, toVersion)` -- `DbUpgrader.upgradeTable(db, schema, table, fromVersion, toVersion)` - -both of which allow for non-linear upgrades. If the upgrade method call is successful and returns *true*, iciql will update the *iq_versions* table with the annotated version number. - -The actual upgrade procedure is beyond the scope of iciql and is your responsibility to implement. This is simply a mechanism to automatically identify when an upgrade is necessary. - -**NOTE:**
-The database entry of the *iq_versions* table is specified as SCHEMANAME='' and TABLENAME=''. \ No newline at end of file diff --git a/src/site/02_usage.mkd b/src/site/02_usage.mkd deleted file mode 100644 index 7b9d89d..0000000 --- a/src/site/02_usage.mkd +++ /dev/null @@ -1,197 +0,0 @@ -## Usage - -Aside from this brief usage guide, please consult the [examples](examples.html), the [javadoc](javadoc.html) and the [source code](${project.scmUrl}). - -### Instantiating a Db - -Use one of the static utility methods to instantiate a Db instance: - - Db.open(String url, String user, String password); - Db.open(String url, String user, char[] password); - Db.open(Connection conn); - Db.open(DataSource dataSource); - -### Compile-Time Statements - -You compose your statements using the builder pattern where each method call returns an object that is used to specify the next part of the statement. Through clever usage of generics, pioneered by the original JaQu project, compile-time safety flows through the statement. - -%BEGINCODE% -Db db = Db.open("jdbc:h2:mem:", "sa", "sa"); -db.insertAll(Product.getList()); -db.insertAll(Customer.getList()); - -List restock = - db.from(p). - where(p.unitsInStock). - is(0).orderBy(p.productId).select(); - -for (Product product : restock) { - db.from(p). - set(p.unitsInStock).to(25). - where(p.productId).is(product.productId).update(); -} -db.close(); -%ENDCODE% - -Please see the [examples](examples.html) page for more code samples. - -### Dynamic Runtime Queries - -Iciql gives you compile-time type-safety, but it becomes inconvenient if your design requires more dynamic statement generation. For these scenarios iciql offers some runtime query support through a hybrid approach or a pure JDBC approach. - -#### Where String Fragment Approach -This approach is a mixture of iciql and jdbc. It uses the traditional prepared statement *field=?* tokens with iciql compile-time model class type checking. There is no field token type-safety checking. -%BEGINCODE% -List restock = db.from(p).where("unitsInStock=? and productName like ? order by productId", 0, "Chef%").select(); -%ENDCODE% - -#### Db.executeQuery Approaches -There may be times when the hybrid approach is still too restrictive and you'd prefer to write straight SQL. You can do that too and use iciql to build objects from your ResultSet, but be careful: - -1. Make sure to _select *_ in your query otherwise db.buildObjects() will throw a RuntimeException -2. There is no model class type checking nor field type checking. - -%BEGINCODE% -List allProducts = db.executeQuery(Product.class, "select * from products"); -List restock = db.executeQuery(Product.class, "select * from products where unitsInStock=?", 0); - -// parameterized query which can be cached and re-used later -String q = db.from(p).where(p.unitsInStock).isParameter().toSQL(); -List restock = db.executeQuery(Product.class, q, 0); - -%ENDCODE% - -Or if you want access to the raw *ResultSet* before building your model object instances... - -%BEGINCODE% -ResultSet rs = db.executeQuery("select * from products"); -List allProducts = db.buildObjects(Product.class, rs); -// This method ensures the creating statement is closed -JdbcUtils.closeSilently(rs, true); -%ENDCODE% - -### Natural Syntax - -work-in-progress - -The original JaQu source offers partial support for Java expressions in *where* clauses. - -This works by decompiling a Java expression, at runtime, to an SQL condition. The expression is written as an anonymous inner class implementation of the `com.iciql.Filter` interface. -A proof-of-concept decompiler is included, but is incomplete. - -The proposed syntax is: -%BEGINCODE% -long count = db.from(co). - where(new Filter() { public boolean where() { - return co.id == x - && co.name.equals(name) - && co.value == new BigDecimal("1") - && co.amount == 1L - && co.birthday.before(new java.util.Date()) - && co.created.before(java.sql.Timestamp.valueOf("2005-05-05 05:05:05")) - && co.time.before(java.sql.Time.valueOf("23:23:23")); - } - }).selectCount(); -%ENDCODE% - -### JDBC Statements, ResultSets, and Exception Handling - -Iciql opens and closes all JDBC objects automatically. SQLExceptions thrown during execution of a statement (except for *close()* calls), will be caught, wrapped, and rethrown as an `IciqlException`, which is a RuntimeException. - -Iciql does not throw any [checked exceptions](http://en.wikipedia.org/wiki/Exception_handling#Checked_exceptions). - -### Statement Logging - -Iciql provides a mechanism to log generated statements and warnings to the console, to SLF4J, or to your own logging framework. Exceptions are not logged using this mechanism; exceptions are wrapped and rethrown as `IciqlException`, which is a RuntimeException. - -#### Console Logging -%BEGINCODE% -IciqlLogger.activeConsoleLogger(); -IciqlLogger.deactiveConsoleLogger(); -%ENDCODE% - -#### SLF4J Logging -%BEGINCODE% -Slf4jIciqlListener slf4j = new Slf4jIciqlListener(); -slf4j.setLevel(StatementType.CREATE, Level.WARN); -slf4j.setLevel(StatementType.DELETE, Level.WARN); -slf4j.setLevel(StatementType.MERGE, Level.OFF); -IciqlLogger.registerListener(slf4j); -IciqlLogger.unregisterListener(slf4j); -%ENDCODE% - -#### Custom Logging -%BEGINCODE% -IciqlListener custom = new IciqlListener() { - public void logIciql(StatementType type, String statement) { - // do log - } -}; -IciqlLogger.registerListener(custom); -IciqlLogger.unregisterListener(custom); -%ENDCODE% - -## Understanding Aliases and Model Classes -Consider the following example: -%BEGINCODE% -Product p = new Product(); -List restock = db.from(p).where(p.unitsInStock).is(0).select(); -%ENDCODE% - -The Product model class instance named **p** is an *alias* object. An *alias* is simply an instance of your model class that is only used to build the compile-time/runtime representation of your table. - -1. *Alias* instances are **NOT** thread-safe and must not be used concurrently. -2. *Alias* instances have no other purpose than to provide a compile-time/runtime map of your table. -3. If you inspected an *alias* instance after using one you would find that it's fields have been assigned numeric values.
These values are assigned from a static counter in `com.iciql.Utils.newObject()` during execution of the *db.from()* method.

For *Object* fields, these values are meaningless since objects are mapped by reference.
For *Primitive* fields these values do matter because primitives are mapped by value. The proper alias is selected as long as the primitive variant methods are used. e.g. db.from(p).where(int).is(Integer).select() - -If your statement is a query, like in the above example, iciql will generate new instances of your *alias* model class and return them as a list where each entry of the list represents a row from the JDBC `ResultSet`. - -### Why are Aliases not thread-safe? - -The _db.from(p)_ call reinstantiates each member field of p. Those reinstantiated fields are then subsequently used in clauses like _where(p.unitsInStock)_. If your *alias* instance is shared concurrently then its highly probable that when _queryA_ executes, _queryC_ has reinstantiated all the *alias* fields and broken _queryA's_ runtime field mapping. - -Depending on your design, you might consider using a [ThreadLocal](http://download.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html) variable if you do not want to keep instantiating *alias* instances. A utility function is included for easily creating ThreadLocal variables. - -%BEGINCODE% -final ThreadLocal p = Utils.newThreadLocal(Product.class); -db.from(p.get()).select(); -%ENDCODE% - -## Best Practices - -1. Close your *Db* instances when you are done with them, this closes the underlying connection or directs the pool to "close" the connection. -2. Aliases instances are not thread-safe so DO NOT SHARE an alias!
Consider using a *ThreadLocal* alias instance with the `com.iciql.Utils.newThreadLocal()` utility method. - -

- - - -
Not Thread-SafeThread-Safe
-%BEGINCODE% -final Product p = new Product(); -for (int i = 0; i < 5; i++) { - Thread thread = new Thread(new Runnable() { - public void run() { - // from(p) reinstantiates p's fields - db.from(p).select(); - } - }, "Thread-" + i); - thread.start(); -} -%ENDCODE% - - -%BEGINCODE% -final ThreadLocal p = Utils.newThreadLocal(Product.class); -for (int i = 0; i < 5; i++) { - Thread thread = new Thread(new Runnable() { - public void run() { - // a unique p for this thread - db.from(p.get()).select(); - } - }, "Thread-" + i); - thread.start(); -} -%ENDCODE% - -
\ No newline at end of file diff --git a/src/site/03_performance.mkd b/src/site/03_performance.mkd deleted file mode 100644 index 34e545c..0000000 --- a/src/site/03_performance.mkd +++ /dev/null @@ -1,22 +0,0 @@ - -## Performance - -The information provided here may be based on flawed test procedures. You have to be the judge of what is performant and non-performant. - -### iciql statement generation - -Performance of iciql statement generation is not currently benchmarked. - -### iciql+database performance comparison - -The following data was generated by running the *single-threaded* iciql test suite. All database connections are pooled and re-used within each execution of the test suite using [Apache Commons DBCP](http://commons.apache.org/dbcp). - -Connections are pooled to normalize embedded database performance with out-of-process database performance. Some of the Java embedded database configurations have a very high startup-time penalty. Notably, H2 is slow to open a database and its performance is substantially affected if connection pooling is not enabled to keep the embedded database open. - -All tables are created as CACHED when the database distinguishes between CACHED and MEMORY tables. - -All performance numbers include the combined overhead of iciql statement generation and JUnit 4 test framework execution so they are not bare-metal database metrics. - -

-%DBPERFORMANCE%
-
\ No newline at end of file diff --git a/src/site/04_examples.mkd b/src/site/04_examples.mkd deleted file mode 100644 index 33cb9c4..0000000 --- a/src/site/04_examples.mkd +++ /dev/null @@ -1,196 +0,0 @@ -## Select Statements - -%BEGINCODE% -// select * from products -List allProducts = db.from(p).select(); - -// select * from customers where region='WA' -Customer c = new Customer(); -List waCustomers = db.from(c). where(c.region).is("WA").select(); - -public static class ProductPrice { - public String productName; - public String category; - public Double price; -} - -// select with generation of new anonymous inner class -List productPrices = - db.from(p). - orderBy(p.productId). - select(new ProductPrice() {{ - productName = p.productName; - category = p.category; - price = p.unitPrice; - }}); -%ENDCODE% - -## Insert Statements - -%BEGINCODE% -// single record insertion -db.insert(singleProduct); - -// single record insertion with primary key retrieval -Long key = db.insertAndGetKey(singleProduct); - -// batch record insertion -db.insertAll(myProducts); - -// batch insertion with primary key retrieval -List myKeys = db.insertAllAndGetKeys(list); -%ENDCODE% - -## Update Statements - -%BEGINCODE% -// single record update -db.update(singleProduct); - -// batch record updates -db.updateAll(myProducts); - -// update query -db.from(p).set(p.productName).to("updated") - .increment(p.unitPrice).by(3.14) - .increment(p.unitsInStock).by(2) - .where(p.productId).is(1).update(); - -// reusable, parameterized update query -String q = db.from(p).set(p.productName).toParameter().where(p.productId).is(1).toSQL(); -db.executeUpdate(q, "Lettuce"); - -%ENDCODE% - -## Merge Statements -Merge statements currently generate the [H2 merge syntax](http://h2database.com/html/grammar.html#merge). - -%BEGINCODE% -Product pChang = db.from(p).where(p.productName).is("Chang").selectFirst(); -pChang.unitPrice = 19.5; -pChang.unitsInStock = 16; -db.merge(pChang); -%ENDCODE% - -## Delete Statements - -%BEGINCODE% -// single record deletion -db.delete(singleProduct); - -// batch record deletion -db.deleteAll(myProducts); - -// delete query -db.from(p).where(p.productId).atLeast(10).delete(); - -%ENDCODE% - -## Inner Join Statements - -%BEGINCODE% -final Customer c = new Customer(); -final Order o = new Order(); - -List customersWithLargeOrders = - db.from(c). - innerJoin(o).on(c.customerId).is(o.customerId). - where(o.total).greaterThan(new BigDecimal("500.00")). - groupBy(c.customerId).select(); - - -List orders = - db.from(c). - innerJoin(o).on(c.customerId).is(o.customerId). - where(o.total).lessThan(new BigDecimal("500.00")). - orderBy(1). - select(new CustOrder() {{ - customerId = c.customerId; - orderId = o.orderId; - total = o.total; - }}); -%ENDCODE% - -## View Statements - -%BEGINCODE% -// the view named "ProductView" is created from the "Products" table -@IQView(viewTableName = "Products") -public class ProductView { - - @IQColumn - @IQConstraint("this >= 200 AND this < 300") - Long id; - - @IQColumn - String name; -} - -final ProductView v = new ProductView(); -List allProducts = db.from(v).select(); - -// this version of the view model "ProductView" inherits table metadata -// from the Products class which is annotated with IQTable -@IQView(inheritColumns = true) -public class ProductView extends Products { - - // inherited BUT replaced to define the constraint - @IQColumn - @IQConstraint("this >= 200 AND this < 300") - Long id; - - // inherited from Products - //@IQColumn - //String name; -} - -final ProductView v = new ProductView(); -List allProducts = db.from(v).select(); - -// in this example we are creating a view based on a fluent query -// and using 2 levels of inheritance. IQConstraints are ignored -// when using this approach because we are fluently defining them. -@IQView(inheritColumns = true) -public class ProductViewInherited extends ProductView { - -} - -final Products p = new Products(); -db.from(p).where(p.id).atLeast(200L).and(p.id).lessThan(300L).createView(ProductViewInherited.class); - -// now replace the view with a variation -db.from(p).where(p.id).atLeast(250L).and(p.id).lessThan(350L).replaceView(ProductViewInherited.class); - -// now drop the view from the database -db.dropView(ProductViewInherited.class); - -%ENDCODE% - -## Dynamic Queries - -Dynamic queries skip all field type checking and, depending on which approach you use, may skip model class/table name checking too. - -%BEGINCODE% -// where fragment with object parameters -List restock = db.from(p).where("unitsInStock=? and productName like ? order by productId", 0, "Chef%").select(); - -// parameterized query which can be cached and re-used later -String q = db.from(p).where(p.unitsInStock).isParameter().and(p.productName).likeParameter().orderBy(p.productId).toSQL(); -List allProducts = db.executeQuery(Product.class, q, 0, "Chef%"); - -// statement with binding to your model class -List allProducts = db.executeQuery(Product.class, "select * from products"); - -// statement with object parameters and binding to your model class -List restock = db.executeQuery(Product.class, "select * from products where unitsInStock=?", 0); - -/** - * If you want to process the intermediate ResultSet - * yourself make sure to use the closeSilently() method - * to ensure the parent statement is closed too. - */ -ResultSet rs = db.executeQuery("select * from products"); -List allProducts = db.buildObjects(Product.class, rs); -JdbcUtils.closeSilently(rs, true); - -%ENDCODE% \ No newline at end of file diff --git a/src/site/04_tools.mkd b/src/site/04_tools.mkd deleted file mode 100644 index 6d8c348..0000000 --- a/src/site/04_tools.mkd +++ /dev/null @@ -1,95 +0,0 @@ -## Model Generation -If you do not have or do not want to annotate your existing model classes, you can use the included model generation tool to create iciql model classes. - - java -jar iciql.jar - -### Parameters - - - - - - - - - - -
-urlJDBC url for the databaseREQUIRED
-usernameusername for JDBC connectionoptional
-passwordpassword for JDBC connectionoptional
-schemathe target schema for model generationdefault: all schemas
-tablethe target table for model generationdefault: all tables
-packagethe destination package name for generated modelsdefault: default package
-folderthe output folder for .java filesdefault: current folder
-annotateSchemainclude the schema name in the class annotationsdefault: true
-trimStringsannotate trimStrings=true for any VARCHAR string mappings   default: false
- -## Model Validation -Iciql can validate your model classes against your database to ensure that your models are optimally defined and are consistent with the current table and index definitions. - -Each `com.iciql.ValidationRemark` returned by the validation has an associated level from the following enum: -%BEGINCODE% -public static enum Level { - CONSIDER, WARN, ERROR; -} -%ENDCODE% - -A typical validation may output recommendations for adjusting a model field annotation such as setting the *maxLength* of a string to match the length of its linked VARCHAR column. - -### Sample Model Validation using JUnit 4 -%BEGINCODE% -import static org.junit.Assert.assertTrue; - -import java.sql.SQLException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; - -import com.iciql.Db; -import com.iciql.DbInspector; -import com.iciql.ValidationRemark; -import com.iciql.test.models.Product; -import com.iciql.test.models.ProductAnnotationOnly; -import com.iciql.test.models.ProductMixedAnnotation; - -public class ValidateModels { - - /* - * The ErrorCollector Rule allows execution of a test to continue after the - * first problem is found and report them all at once - */ - @Rule - public ErrorCollector errorCollector = new ErrorCollector(); - - private Db db; - - @Before - public void setUp() { - db = Db.open("jdbc:h2:mem:", "sa", "sa"); - } - - @After - public void tearDown() { - db.close(); - } - - @Test - public void testValidateModels() { - DbInspector inspector = new DbInspector(db); - validateModel(inspector, new Product()); - validateModel(inspector, new ProductAnnotationOnly()); - validateModel(inspector, new ProductMixedAnnotation()); - } - - private void validateModel(DbInspector inspector, Object o) { - List remarks = inspector.validateModel(o, false); - assertTrue("Validation remarks are null for " + o.getClass().getName(), remarks != null); - log("Validation remarks for " + o.getClass().getName()); - for (ValidationRemark remark : remarks) { - log(remark.toString()); - if (remark.isError()) { - errorCollector.addError(new SQLException(remark.toString())); - } - } - } - - private void log(String message) { - System.out.println(message); - } -} -%ENDCODE% \ No newline at end of file diff --git a/src/site/05_building.mkd b/src/site/05_building.mkd deleted file mode 100644 index b5548bc..0000000 --- a/src/site/05_building.mkd +++ /dev/null @@ -1,35 +0,0 @@ -## Building from Source - -[Eclipse](http://eclipse.org) is recommended for development as the project settings are preconfigured. - -Additionally, [eclipse-cs](http://eclipse-cs.sourceforge.net), [FindBugs](http://findbugs.sourceforge.net), and [EclEmma](http://www.eclemma.org) are recommended development tools. - -### Build Dependencies (bundled in repository) -- [ant-googlecode](http://code.google.com/p/ant-googlecode) (New BSD) - -### Build Dependencies (downloaded during build) -- [Moxie Build Toolkit](http://moxie.gitblit.com) (Apache 2.0) -- [H2 Database](http://h2database.com) (Eclipse Public License 1.0) -- [HSQL Database Engine](http://hsqldb.org) (BSD) -- [Apache Derby Database](http://db.apache.org/derby) (Apache 2.0) -- [MySQL Connector/J](http://dev.mysql.com/downloads/connector/j) (GPL) -- [PostgreSQL JDBC Connector](http://jdbc.postgresql.org) (BSD) -- [JUnit](http://junit.org) (Common Public License) -- [SLF4J](http://www.slf4j.org) (MIT/X11) -- [Apache Commons Pool](http://commons.apache.org/pool) (Apache 2.0) -- [Apache Commons DBCP](http://commons.apache.org/dbcp) (Apache 2.0) - -### Instructions -1. Clone the git repository from [Github](${project.scmUrl}). -2. Import the iciql project into your Eclipse workspace.
-*There will be some build errors.* -3. Using Ant, execute the `build.xml` script in the project root.
-*This will download all necessary build dependencies.* -4. Select your iciql project root and **Refresh** the project, this should correct all build problems. - -## Contributing -Patches welcome in any form. - -Contributions must be your own original work and must licensed under the [Apache License, Version 2.0][apachelicense], the same license used by iciql. - -[apachelicense]: http://www.apache.org/licenses/LICENSE-2.0 "Apache License, Version 2.0" \ No newline at end of file diff --git a/src/site/05_javadoc.mkd b/src/site/05_javadoc.mkd deleted file mode 100644 index 0d0f161..0000000 --- a/src/site/05_javadoc.mkd +++ /dev/null @@ -1,7 +0,0 @@ -
-packages - | tree - | deprecated - | index -
- diff --git a/src/site/05_releases.mkd b/src/site/05_releases.mkd deleted file mode 100644 index 3e66494..0000000 --- a/src/site/05_releases.mkd +++ /dev/null @@ -1,223 +0,0 @@ -## Release History - -### Current Release - -**${project.version}** - -- Fixed case-sensitivity bug on setting a compound primary key from an annotation (issue 12) -- Implemented readonly view support. (issue 8)
-View models may be specified using the IQView annotation or Iciql.define(). Views can either be created automatically as part of a query of the view OR views may be constructed from a fluent statement. -- Support inheriting columns from super.super class, if super.super is annotated.
This allows for an inheritance hierarchy like:
-@IQTable class MyTable -> @IQView abstract class MyBaseView -> @IQView class MyConstrainedView -- Fixed order of DEFAULT value in create table statement (issue 11) -- Support inheritance of IQVersion for DbUpgrader implementations (issue 10) -- Fixed password bug in model generator (issue 7) - -### Older Releases - -**1.1.0**   *released 2012-08-20* - -- All bulk operations (insert all, update all, delete all) now use JDBC savepoints to ensure atomicity of the transaction - -**1.0.0**   *released 2012-07-14* - -- Issue CREATE TABLE and CREATE INDEX statements once per-db instance/table-mapping -- Fixed bug in using 0L primitive values in where clauses. These were confused with the COUNT(*) function. (Github/kc5nra,issue 5) -- Added support for single column subquery *select name, address from user_table where user_id in (select user_id from invoice table where paid = false)* -- Added support for left outer join (Github/backpaper0) - -**0.7.10**   *released 2012-01-27* - -- Fixed default String value bug where a default empty string threw an IndexOutOfBounds exception - -**0.7.9**   *released 2012-01-24* - -- Added toParameter() option for SET commands and allow generating parameterized UPDATE statements
-String q = db.from(t).set(t.timestamp).toParameter().where(t.id).is(5).toSQL();
-db.executeUpdate(q, new Date()); - -**0.7.8**   *released 2012-01-11* - -- Replaced non-threadsafe counter used for assigning AS identifiers in JOIN statements with an AtomicInteger -- Prevent negative rollover of the AS counter -- Added optional alias parameter to *Query.toSQL* and *QueryWhere.toSQL* to force generated statement to prefix an AS identifier or, alternatively, the tablename. - - Query.toSQL(boolean distinct, K alias) - - QueryWhere.toSQL(boolean distinct, K alias) -- Fixed bug in Query.select(Z z) which assumed that Z must always be an anonymous inner class which may not always be true. This allows for specifying an existing alias to force table or identifier usage in the generated select list. This is very useful for DISTINCT JOIN statements where only the columns of the primary table are of interest. - -**0.7.7**   *released 2012-01-05* - -- added *Query.toSQL()* and *QueryWhere.toSQL()* methods which, when combined with the following new methods, allows for generation of a parameterized, static sql string to be reused with a dynamic query or a PreparedStatement. - - QueryCondition.isParameter() - - QueryCondition.atLeastParameter() - - QueryCondition.atMostParameter() - - QueryCondition.exceedsParameter() - - QueryCondition.lessThanParameter() - - QueryCondition.likeParameter() - - QueryCondition.isNotParameter() -- Disallow **declaring and explicitly referencing** multiple instances of an enum type within a single model.
A runtime exception will be thrown if an attempt to use where/set/on/and/or/groupBy/orderBy(enum) and your model has multiple fields of a single enum type. - -**0.7.6**   *released 2011-12-21* - -- Iciql now tries to instantiate a default value from an annotated default value IFF the field object is null, it is specified *nullable = false*, and a defaultValue exists. This only applies to *db.insert* or *db.update*. - -**0.7.5**   *released 2011-12-12* - -- Iciql now identifies wildcard queries and builds a dynamic column lookup. Otherwise, the original field-position-based approach is used. This corrects the performance regression released in 0.7.4 while still fixing the wildcard statement column mapping problem. - -**0.7.4**   *released 2011-12-06* - -- Disallow **declaring and explicitly referencing** multiple primitive booleans in a single model.
A runtime exception will be thrown if an attempt to use where/set/on/and/or/groupBy/orderBy(boolean) and your model has multiple mapped primitive boolean fields. -- Added list alternatives to the varargs methods because it was too easy to forget list.toArray()
-*Db.executeQuery(Class<? extends T> modelClass, String sql, List<?> args)*
-*Db.executeQuery(String sql, List<?> args)*
-*Query.where(String fragment, List<?> args)*
-- Fixed inherited JaQu bug related to model classes and wildcard queries (select *).

-Iciql maps resultset columns by the index of the model class field from a list. This assumes that *all* columns in the resultset have a corresponding model field definition. This works fine for most queries because iciql explicitly selects columns from the table (*select alpha, beta...*) when you execute *select()*. The problem is when iciql issues a dynamic wildcard query and your model does not represent all columns in the resultset: columns and fields may fail to correctly line-up.

-Iciql now maps all fields by their column name, not by their position. - -**0.7.3**   *released 2011-12-06* - -- api change release (API v8) -- Fixed JOIN ON primitives -- Fixed GROUP BY primitives -- Fixed primitive references when selecting into a custom type with primitives -- Improved fluent/type-safety of joins - -**0.7.2**   *released 2011-11-30* - -- generated models are now serializable with a default serial version id of 1 -- Updated to H2 1.3.162 -- Updated to HSQL 2.2.6 (100% unit test pass now that [this bug](https://sourceforge.net/tracker/?func=detail&aid=3390047&group_id=23316&atid=378131) was fixed) - -**0.7.1**   *released 2011-08-31* - -- api change release (API v7) -- Undeprecated interface configuration -- Interface configuration now maps ALL fields, not just public fields -- Added @IQIgnore annotation to explicitly skip fields for interface configuration -- Created additional Define static methods to bring interface configuration to near-parity with annotation configuration -- Documented POJO configuration option (limited subset of interface configuration) -- Fix to PostgreSQL dialect when creating autoincrement columns -- Fix to default dialect when creating autoincrement columns -- Added Db.open(url) method - -**0.7.0**   *released 2011-08-17* - -- api change release (API v6) -- Finished MySQL dialect implementation. MySQL 5.0.51b passes 100% of tests. -- Added PostgreSQL dialect. PostgreSQL 9.0 passes all but the boolean-as-int tests. -- Added Db.dropTable(T) method -- Overhauled test suite and included more database configurations. -- Renamed StatementLogger to IciqlLogger -- Added IciqlLogger.warn method -- Added IciqlLogger.drop method - -**0.6.6**   *released 2011-08-15* - -- api change release (API v5) -- Disabled two concurrency unit tests since I believe they are flawed and do not yield reproducible results -- Added Derby database dialect. Derby 10.7.1.1 and 10.8.1.2 pass 100% of tests. -- Implemented HSQL MERGE syntax. HSQL 2.2.4 fails 1 test which is a known [bug in HSQL](https://sourceforge.net/tracker/?func=detail&aid=3390047&group_id=23316&atid=378131) -- Updated to H2 1.3.159 - -**0.6.5**   *released 2011-08-12* - -- fixed failure of db.delete(PrimitiveModel) and db.update(PrimitiveModel) - -**0.6.4**   *released 2011-08-12* - -- api change release (API v4) -- @IQTable.createIfRequired -> @IQTable.create -- don't INSERT primitive autoIncrement fields, let database assign value -- full support for primitives in all clauses -- DECIMAL(length, scale) support -- unspecified length String fields are now CLOB instead of TEXT. dialects can intercept this and convert to another type. e.g. MySQL dialect can change CLOB to TEXT. -- java.lang.Boolean now maps to BOOLEAN instead of BIT -- expressions on unmapped fields will throw an IciqlException -- expressions on unsupported types will throw an IciqlException -- improved exception reporting by including generated statement, if available -- moved dialects back to main package -- improved automatic dialect determination on pooled connections -- moved create table and create index statement generation into dialects -- added HSQL dialect. HSQL fails 4 out of 50 unit tests. - - 2 failures are unimplemented merge - - 1 has been filed and accepted as a [bug in HSQL](https://sourceforge.net/tracker/?func=detail&aid=3390047&group_id=23316&atid=378131) - - 1 is a concurrency issue, but the test may be flawed -- added untested MySQL dialect -- renamed _ iq_versions table to *iq_versions* since leading _ character is troublesome for some databases. -- @IQColumn(allowNull=true) -> @IQColumn(nullable=true) -- All **Object** columns are assumed NULLABLE unless explicitly set *@IQColumn(nullable = false)* -- All **Primitive** columns are assumed NOT NULLABLE unless explicitly set *@IQColumn(nullable = true)* -- allow using objects to assign default values
-%BEGINCODE% -// CREATE TABLE ... myDate DATETIME DEFAULT '2000-02-01 00:00:00' -@IQColumn -Date myDate = new Date(100, 1, 1); -%ENDCODE% -- changed @IQTable.primaryKey definition to use array of column names
-%BEGINCODE% -@IQTable( primaryKey = {"name", "nickname"}) -%ENDCODE% - -**0.6.3**   *released 2011-08-08* - -- api change release (API v3) -- finished enum support (issue 4) -- added UUID type support (H2 databases only) -- added partial primitives support *(primitives may not be used for compile-time condition clauses)* -- added *between(A y).and(A z)* condition syntax -- moved dialects into separate package - -**0.6.2**   *released 2011-08-05* - -- api change release (API v2) -- fix to versioning to support H2 1.3.158+ -- added BLOB support (issue 1) -- added java.lang.Enum support (issue 2) -- allow runtime flexible mapping of BOOL columns to Integer fields -- allow runtime flexible mapping of INT columns to Boolean fields -- annotations overhaul to reduce verbosity - - @IQSchema(name="public") -> @IQSchema("public") - - @IQDatabase(version=2) -> @IQVersion(2) - - @IQTable(version=2) -> @IQVersion(2) - - @IQIndex annotation simplified to be used for one index definition and expanded to specify index name - - added @IQIndexes annotation to specify multiple IQIndex annotations
-%BEGINCODE% -@IQIndexes({ @IQIndex("name"), @IQIndex(name="myindexname" value={"name", "nickname"}) }) -%ENDCODE% - - @IQColumn(maxLength=20) -> @IQColumn(length=20) - - @IQColumn(trimString=true) -> @IQColumn(trim=true) - -**0.5.0**   *released 2011-08-03* - -- initial release (API v1) - -*API changes compared to JaQu from H2 1.3.157 sources* - -- deprecated model class interface configuration -- added *Db.open(Connection conn)* method, changed constructor to default scope -- added *Db.registerDialect* static methods to register custom dialects -- added *Query.where(String fragment, Object... args)* method to build a runtime query fragment when compile-time queries are too strict -- added *Db.executeQuery(String query, Object... args)* to execute a complete sql query with optional arguments -- added *Db.executeQuery(Class modelClass, String query, Object... args)* to execute a complete sql query, with optional arguments, and build objects from the result -- added *Db.buildObjects(Class modelClass, ResultSet rs)* method to build objects from the ResultSet of a plain sql query -- added *ThreadLocal<T> com.iciql.Utils.newThreadLocal(final Class<? extends T> clazz)* method -- added optional console statement logger and SLF4J statement logger -- refactored dialect support -- throw *IciqlException* (which is a RuntimeException) instead of RuntimeException -- synchronized *Db.classMap* for concurrent sharing of a Db instance -- Database/table versioning uses the _iq_versions table, the _ jq_versions table, if present, is ignored -- Changed the following class names: - - org.h2.jaqu.Table => com.iciql.Iciql - - org.h2.jaqu.JQSchema => com.iciql.IQSchema - - org.h2.jaqu.JQDatabase => com.iciql.IQDatabase - - org.h2.jaqu.JQIndex => com.iciql.IQIndex - - org.h2.jaqu.JQTable => com.iciql.IQTable - - org.h2.jaqu.JQColumn => com.iciql.IQColumn -- Changed the following method names: - - org.h2.jaqu.Table.define() => com.iciql.Iciql.defineIQ() - - QueryConditon.bigger => QueryCondition.exceeds - - QueryConditon.biggerEqual => QueryCondition.atLeast - - QueryConditon.smaller => QueryCondition.lessThan - - QueryConditon.smallEqual => QueryCondition.atMost diff --git a/src/site/06_jaqu_comparison.mkd b/src/site/06_jaqu_comparison.mkd deleted file mode 100644 index 20df5d5..0000000 --- a/src/site/06_jaqu_comparison.mkd +++ /dev/null @@ -1,31 +0,0 @@ - -## Comparison to JaQu - -This is an overview of the fundamental differences between the original JaQu project and the current featureset of iciql. - - - - - - - - - - - - - - - - - - - - - - - - - - -
IciqlJaQu
core
deploymentsmall, discrete librarydepends on H2 database jar file
databasesH2, HSQL, Derby, MySQL, and PostreSQLH2 only
loggingconsole, SLF4J, or custom loggingconsole logging
exceptionsalways includes generated statement in exception, when available--
column mappingswildcard queries index result sets by column nameall result sets built by field index
this can fail for wildcard queries
savepointsbulk operations (insert, update, delete) use savepoints with rollback in the event of failure--
syntax and api
VIEWscreate readonly views either from a class definition or from a fluent statement--
dynamic queriesmethods and where clauses for dynamic queries that build iciql objects--
DROPsyntax to drop a table or view
BETWEENsyntax for specifying a BETWEEN x AND y clause--
types
primitivesfully supported--
enumsfully supported--
DECIMAL(length,scale)can specify length/precision and scale--
BOOLEANflexible mapping of boolean as bool, varchar, or int--
BLOBpartially supported (can not be used in a WHERE clause)--
UUIDfully supported (H2 only) --
configuration
DEFAULT valuesset from annotation, default object values, or Define.defaultValue()set from annotations
Interface Configuration
Mapped Fields
all fields are mapped regardless of scope
fields are ignored by annotating with @IQIgnore
all public fields are mapped
fields are ignored by reducing their scope
Index namescan be set--
\ No newline at end of file diff --git a/src/site/building.mkd b/src/site/building.mkd new file mode 100644 index 0000000..b5548bc --- /dev/null +++ b/src/site/building.mkd @@ -0,0 +1,35 @@ +## Building from Source + +[Eclipse](http://eclipse.org) is recommended for development as the project settings are preconfigured. + +Additionally, [eclipse-cs](http://eclipse-cs.sourceforge.net), [FindBugs](http://findbugs.sourceforge.net), and [EclEmma](http://www.eclemma.org) are recommended development tools. + +### Build Dependencies (bundled in repository) +- [ant-googlecode](http://code.google.com/p/ant-googlecode) (New BSD) + +### Build Dependencies (downloaded during build) +- [Moxie Build Toolkit](http://moxie.gitblit.com) (Apache 2.0) +- [H2 Database](http://h2database.com) (Eclipse Public License 1.0) +- [HSQL Database Engine](http://hsqldb.org) (BSD) +- [Apache Derby Database](http://db.apache.org/derby) (Apache 2.0) +- [MySQL Connector/J](http://dev.mysql.com/downloads/connector/j) (GPL) +- [PostgreSQL JDBC Connector](http://jdbc.postgresql.org) (BSD) +- [JUnit](http://junit.org) (Common Public License) +- [SLF4J](http://www.slf4j.org) (MIT/X11) +- [Apache Commons Pool](http://commons.apache.org/pool) (Apache 2.0) +- [Apache Commons DBCP](http://commons.apache.org/dbcp) (Apache 2.0) + +### Instructions +1. Clone the git repository from [Github](${project.scmUrl}). +2. Import the iciql project into your Eclipse workspace.
+*There will be some build errors.* +3. Using Ant, execute the `build.xml` script in the project root.
+*This will download all necessary build dependencies.* +4. Select your iciql project root and **Refresh** the project, this should correct all build problems. + +## Contributing +Patches welcome in any form. + +Contributions must be your own original work and must licensed under the [Apache License, Version 2.0][apachelicense], the same license used by iciql. + +[apachelicense]: http://www.apache.org/licenses/LICENSE-2.0 "Apache License, Version 2.0" \ No newline at end of file diff --git a/src/site/custom.less b/src/site/custom.less index 31098f5..f7130d4 100644 --- a/src/site/custom.less +++ b/src/site/custom.less @@ -2,7 +2,7 @@ // GLOBAL VALUES // -------------------------------------------------- @standardGray: #ccc; -@cornflower: #abd4ff; +@cornflower: #99cbff; @white: #fff; // Dropdown diff --git a/src/site/examples.mkd b/src/site/examples.mkd new file mode 100644 index 0000000..33cb9c4 --- /dev/null +++ b/src/site/examples.mkd @@ -0,0 +1,196 @@ +## Select Statements + +%BEGINCODE% +// select * from products +List allProducts = db.from(p).select(); + +// select * from customers where region='WA' +Customer c = new Customer(); +List waCustomers = db.from(c). where(c.region).is("WA").select(); + +public static class ProductPrice { + public String productName; + public String category; + public Double price; +} + +// select with generation of new anonymous inner class +List productPrices = + db.from(p). + orderBy(p.productId). + select(new ProductPrice() {{ + productName = p.productName; + category = p.category; + price = p.unitPrice; + }}); +%ENDCODE% + +## Insert Statements + +%BEGINCODE% +// single record insertion +db.insert(singleProduct); + +// single record insertion with primary key retrieval +Long key = db.insertAndGetKey(singleProduct); + +// batch record insertion +db.insertAll(myProducts); + +// batch insertion with primary key retrieval +List myKeys = db.insertAllAndGetKeys(list); +%ENDCODE% + +## Update Statements + +%BEGINCODE% +// single record update +db.update(singleProduct); + +// batch record updates +db.updateAll(myProducts); + +// update query +db.from(p).set(p.productName).to("updated") + .increment(p.unitPrice).by(3.14) + .increment(p.unitsInStock).by(2) + .where(p.productId).is(1).update(); + +// reusable, parameterized update query +String q = db.from(p).set(p.productName).toParameter().where(p.productId).is(1).toSQL(); +db.executeUpdate(q, "Lettuce"); + +%ENDCODE% + +## Merge Statements +Merge statements currently generate the [H2 merge syntax](http://h2database.com/html/grammar.html#merge). + +%BEGINCODE% +Product pChang = db.from(p).where(p.productName).is("Chang").selectFirst(); +pChang.unitPrice = 19.5; +pChang.unitsInStock = 16; +db.merge(pChang); +%ENDCODE% + +## Delete Statements + +%BEGINCODE% +// single record deletion +db.delete(singleProduct); + +// batch record deletion +db.deleteAll(myProducts); + +// delete query +db.from(p).where(p.productId).atLeast(10).delete(); + +%ENDCODE% + +## Inner Join Statements + +%BEGINCODE% +final Customer c = new Customer(); +final Order o = new Order(); + +List customersWithLargeOrders = + db.from(c). + innerJoin(o).on(c.customerId).is(o.customerId). + where(o.total).greaterThan(new BigDecimal("500.00")). + groupBy(c.customerId).select(); + + +List orders = + db.from(c). + innerJoin(o).on(c.customerId).is(o.customerId). + where(o.total).lessThan(new BigDecimal("500.00")). + orderBy(1). + select(new CustOrder() {{ + customerId = c.customerId; + orderId = o.orderId; + total = o.total; + }}); +%ENDCODE% + +## View Statements + +%BEGINCODE% +// the view named "ProductView" is created from the "Products" table +@IQView(viewTableName = "Products") +public class ProductView { + + @IQColumn + @IQConstraint("this >= 200 AND this < 300") + Long id; + + @IQColumn + String name; +} + +final ProductView v = new ProductView(); +List allProducts = db.from(v).select(); + +// this version of the view model "ProductView" inherits table metadata +// from the Products class which is annotated with IQTable +@IQView(inheritColumns = true) +public class ProductView extends Products { + + // inherited BUT replaced to define the constraint + @IQColumn + @IQConstraint("this >= 200 AND this < 300") + Long id; + + // inherited from Products + //@IQColumn + //String name; +} + +final ProductView v = new ProductView(); +List allProducts = db.from(v).select(); + +// in this example we are creating a view based on a fluent query +// and using 2 levels of inheritance. IQConstraints are ignored +// when using this approach because we are fluently defining them. +@IQView(inheritColumns = true) +public class ProductViewInherited extends ProductView { + +} + +final Products p = new Products(); +db.from(p).where(p.id).atLeast(200L).and(p.id).lessThan(300L).createView(ProductViewInherited.class); + +// now replace the view with a variation +db.from(p).where(p.id).atLeast(250L).and(p.id).lessThan(350L).replaceView(ProductViewInherited.class); + +// now drop the view from the database +db.dropView(ProductViewInherited.class); + +%ENDCODE% + +## Dynamic Queries + +Dynamic queries skip all field type checking and, depending on which approach you use, may skip model class/table name checking too. + +%BEGINCODE% +// where fragment with object parameters +List restock = db.from(p).where("unitsInStock=? and productName like ? order by productId", 0, "Chef%").select(); + +// parameterized query which can be cached and re-used later +String q = db.from(p).where(p.unitsInStock).isParameter().and(p.productName).likeParameter().orderBy(p.productId).toSQL(); +List allProducts = db.executeQuery(Product.class, q, 0, "Chef%"); + +// statement with binding to your model class +List allProducts = db.executeQuery(Product.class, "select * from products"); + +// statement with object parameters and binding to your model class +List restock = db.executeQuery(Product.class, "select * from products where unitsInStock=?", 0); + +/** + * If you want to process the intermediate ResultSet + * yourself make sure to use the closeSilently() method + * to ensure the parent statement is closed too. + */ +ResultSet rs = db.executeQuery("select * from products"); +List allProducts = db.buildObjects(Product.class, rs); +JdbcUtils.closeSilently(rs, true); + +%ENDCODE% \ No newline at end of file diff --git a/src/site/index.mkd b/src/site/index.mkd new file mode 100644 index 0000000..1c2bbd3 --- /dev/null +++ b/src/site/index.mkd @@ -0,0 +1,63 @@ +## Overview + +iciql **is**... + +- a model-based, database access wrapper for JDBC +- for modest database schemas and basic statement generation +- for those who want to write code, instead of SQL, using IDE completion and compile-time type-safety +- small (200KB) with debug symbols and no runtime dependencies +- pronounced *icicle* (although it could be French: *ici ql* - here query language) +- a friendly fork of the H2 [JaQu][jaqu] project + +iciql **is not**... + +- a complete alternative to JDBC +- designed to compete with more powerful database query tools like [jOOQ][jooq] or [Querydsl][querydsl] +- designed to compete with enterprise [ORM][orm] tools like [Hibernate][hibernate] or [mybatis][mybatis] + +### Example Usage + + + + + + + +
iciqlsql
+%BEGINCODE% +Product p = new Product(); +List restock = db.from(p).where(p.unitsInStock).is(0).select(); +List all = db.executeQuery(Product.class, "select * from products"); +%ENDCODE% + + +
+select * from products p where p.unitsInStock = 0
+select * from products +
+ +### Supported Databases (Unit-Tested) +- [H2](http://h2database.com) ${h2.version} +- [HSQLDB](http://hsqldb.org) ${hsqldb.version} +- [Derby](http://db.apache.org/derby) ${derby.version} +- [MySQL](http://mysql.com) ${mysql.version} +- [PostgreSQL](http://postgresql.org) ${postgresql.version} + +Support for others is possible and may only require creating a simple "dialect" class. + +### Java Runtime Requirement + +iciql requires a Java 6 Runtime Environment (JRE) or a Java 6 Development Kit (JDK). + +### License +iciql is distributed under the terms of the [Apache Software Foundation license, version 2.0][apachelicense] + +[jaqu]: http://h2database.com/html/jaqu.html "H2 JaQu project" +[orm]: http://en.wikipedia.org/wiki/Object-relational_mapping "Object Relational Mapping" +[jooq]: http://jooq.sourceforge.net "jOOQ" +[querydsl]: http://source.mysema.com/display/querydsl/Querydsl "Querydsl" +[hibernate]: http://www.hibernate.org "Hibernate" +[mybatis]: http://www.mybatis.org "mybatis" +[github]: http://github.com/gitblit/iciql "iciql git repository" +[googlecode]: http://code.google.com/p/iciql "iciql project management" +[apachelicense]: http://www.apache.org/licenses/LICENSE-2.0 "Apache License, Version 2.0" \ No newline at end of file diff --git a/src/site/jaqu_comparison.mkd b/src/site/jaqu_comparison.mkd new file mode 100644 index 0000000..20df5d5 --- /dev/null +++ b/src/site/jaqu_comparison.mkd @@ -0,0 +1,31 @@ + +## Comparison to JaQu + +This is an overview of the fundamental differences between the original JaQu project and the current featureset of iciql. + + + + + + + + + + + + + + + + + + + + + + + + + + +
IciqlJaQu
core
deploymentsmall, discrete librarydepends on H2 database jar file
databasesH2, HSQL, Derby, MySQL, and PostreSQLH2 only
loggingconsole, SLF4J, or custom loggingconsole logging
exceptionsalways includes generated statement in exception, when available--
column mappingswildcard queries index result sets by column nameall result sets built by field index
this can fail for wildcard queries
savepointsbulk operations (insert, update, delete) use savepoints with rollback in the event of failure--
syntax and api
VIEWscreate readonly views either from a class definition or from a fluent statement--
dynamic queriesmethods and where clauses for dynamic queries that build iciql objects--
DROPsyntax to drop a table or view
BETWEENsyntax for specifying a BETWEEN x AND y clause--
types
primitivesfully supported--
enumsfully supported--
DECIMAL(length,scale)can specify length/precision and scale--
BOOLEANflexible mapping of boolean as bool, varchar, or int--
BLOBpartially supported (can not be used in a WHERE clause)--
UUIDfully supported (H2 only) --
configuration
DEFAULT valuesset from annotation, default object values, or Define.defaultValue()set from annotations
Interface Configuration
Mapped Fields
all fields are mapped regardless of scope
fields are ignored by annotating with @IQIgnore
all public fields are mapped
fields are ignored by reducing their scope
Index namescan be set--
\ No newline at end of file diff --git a/src/site/javadoc.mkd b/src/site/javadoc.mkd new file mode 100644 index 0000000..0d0f161 --- /dev/null +++ b/src/site/javadoc.mkd @@ -0,0 +1,7 @@ +

+packages + | tree + | deprecated + | index +
+ diff --git a/src/site/model_classes.mkd b/src/site/model_classes.mkd new file mode 100644 index 0000000..8fedf18 --- /dev/null +++ b/src/site/model_classes.mkd @@ -0,0 +1,335 @@ +## Model Classes +A model class represents a single table within your database. Fields within your model class represent columns in the table. The object types of your fields are reflectively mapped to SQL types by iciql at runtime. + +Models can be manually written using one of three approaches: *annotation configuration*, *interface configuration*, or *POJO configuration*. All approaches can be used within a project and all can be used within a single model class, although that is discouraged. + +Alternatively, model classes can be automatically generated by iciql using the model generation tool. Please see the [tools](tools.html) page for details. + +### Configuration Requirements and Limitations + +1. Your model class **must** provide a public default constructor. +2. All **Object** fields are assumed NULLABLE unless explicitly set *@IQColumn(nullable = false)* or *Define.nullable(field, false)*. +3. All **Primitive** fields are assumed NOT NULLABLE unless explicitly set *@IQColumn(nullable = true)* or *Define.nullable(field, true)*. +4. Only the specified types are supported. Any other types are not supported. +5. Triggers, views, and other advanced database features are not supported. + +### Supported Data Types + +---NOMARKDOWN--- + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Fully Supported Types
+can be used for all iciql expressions +
ObjectPrimitiveSQL Type
java.lang.StringVARCHAR (length > 0) or CLOB (length == 0)
java.lang.BooleanbooleanBOOLEAN
can only declare and explicitly reference one primitive boolean per model
multiple primitives are allowed if not using where/set/on/and/or/groupBy/orderBy(boolean)
java.lang.BytebyteTINYINT
java.lang.ShortshortSMALLINT
java.lang.IntegerintINT
java.lang.LonglongBIGINT
java.lang.FloatfloatREAL
java.lang.DoubledoubleDOUBLE
java.math.BigDecimal DECIMAL (length == 0) or DECIMAL(length,scale) (length > 0)
java.sql.Date DATE
java.sql.Time TIME
java.sql.Timestamp TIMESTAMP
java.util.Date TIMESTAMP
java.lang.Enum.name()
default type
VARCHAR (length > 0) or CLOB (length == 0)
EnumType.NAME
can only declare and explicitly reference one instance of each enum type per model
multiple instances of an enum type within a model is allowed if not using where/set/on/and/or/groupBy/orderBy(enum)
java.lang.Enum.ordinal() INT
EnumType.ORDINAL
can only declare and explicitly reference one instance of each enum type per model
multiple instances of an enum type within a model is allowed if not using where/set/on/and/or/groupBy/orderBy(enum)
java.lang.Enum implements
com.iciql.Iciql.EnumId.enumId()
INT
EnumType.ENUMID
can only declare and explicitly reference one instance of each enum type per model
multiple instances of an enum type within a model is allowed if not using where/set/on/and/or/groupBy/orderBy(enum)
Partially Supported Types
+can not be directly referenced in an expression
byte [] BLOB
H2 Database Types
+fully supported when paired with an H2 database +
java.util.UUID UUID
+---NOMARKDOWN--- +**NOTE:**
+The reverse lookup used for model generation, SQL type -> Java type, contains more mappings.
+Please consult the `com.iciql.ModelUtils` class for details. + +## Annotation Configuration +The recommended approach to setup a model class is to annotate the class and field declarations. + +### advantages + +- annotated models support annotated field inheritance making it possible to design a single base class that defines the fields and then create table subclasses that specify the table mappings. +- model runtime dependency is limited to the small, portable `com.iciql.Iciql` class file which contains the annotation definitions + +### disadvantages + +- more verbose model classes +- indexes are defined using "fragile" string column names +- compound primary keys are defined using "fragile" string column names + +### field mapping + +- By default, **ONLY** fields annotated with *@IQColumn* are mapped. +- scope is irrelevant. +- transient is irrelevant. + +### default values + +You may specify default values for an *@IQColumn* by either: + +1. specifying the default value string within your annotation
+**NOTE:**
+The annotated default value always takes priority over a field default value. +%BEGINCODE% +// notice the single ticks! +@IQColumn(defaultValue="'2000-01-01 00:00:00'") +Date myDate; +%ENDCODE% + +2. setting a default value on the field
+**NOTE:**
+Primitive types have an implicit default value of *0* or *false*. +%BEGINCODE% +@IQColumn +Date myDate = new Date(100, 0, 1); + +@IQColumn +int myId; +%ENDCODE% + +If you want to specify a database-specific variable or function as your default value (e.g. CURRENT_TIMESTAMP) you must do that within the annotation. Also note that the *IQColumn.defaultValue* must be a well-formatted SQL DEFAULT expression whereas object defaults will be automatically converted to an SQL DEFAULT expression. + +### Special Case: primitive autoincrement fields and 0 +%BEGINCODE% +@IQColumn(autoIncrement = true) +int myId; +%ENDCODE% + +Because primitive types have implicit default values, this field will be excluded from an INSERT statement if its value is 0. Iciql can not differentiate an implicit/uninitialized 0 from a explicitly assigned 0. + +### Example Annotated Model +%BEGINCODE% +import com.iciql.Iciql.EnumType; +import com.iciql.Iciql.IQColumn; +import com.iciql.Iciql.IQEnum; +import com.iciql.Iciql.IQIndex; +import com.iciql.Iciql.IQTable; + +@IQTable +@IQIndexes({ + @IQIndex({"productName", "category"}), + @IQIndex(name="nameindex", value="productName") +}) +public class Product { + + @IQEnum(EnumType.ORDINAL) + public enum Availability { + ACTIVE, DISCONTINUED; + } + + @IQColumn(primaryKey = true) + public Integer productId; + + @IQColumn(length = 200, trim = true) + public String productName; + + @IQColumn(length = 50, trim = true) + public String category; + + @IQColumn + public Double unitPrice; + + @IQColumn(name = "units") + public Integer unitsInStock; + + @IQColumn + private Integer reorderQuantity; + + @IQColumn + private Availability availability; + + // ignored because it is not annotated AND the class is @IQTable annotated + private Integer ignoredField; + + public Product() { + // default constructor + } +} +%ENDCODE% + +## Interface Configuration +Alternatively, you may map your model classes using the interface approach by implementing the `com.iciql.Iciql` interface. + +This is a less verbose configuration style, but it comes at the expense of introducing a compile-time dependency on the logic of the iciql library. This might be a deterrent, for example, if you were serializing your model classes to another process that may not have the iciql library. + +The `com.iciql.Iciql` interface specifies a single method, *defineIQ()*. In your implementation of *defineIQ()* you would use static method calls to set: + +- the schema name +- the table name (if it's not the class name) +- the column name (if it's not the field name) +- the max length and trim of a string field +- the precision and scale of a decimal field +- the autoincrement flag of a long or integer field +- the nullable flag of a field +- the primaryKey (single field or compound) +- any indexes (single field or compound) + +### advantages + +- less verbose model class +- compile-time index definitions +- compile-time compound primary key definitions + +### disadvantages + +- model runtime dependency on entire iciql library +- *defineIQ()* is called from a static synchronized block which may be a bottleneck for highly concurrent systems + +### field mapping + +- **ALL** fields are mapped unless annotated with *@IQIgnore*. +- scope is irrelevant. +- transient is irrelevant. + +### default values + +You may specify default values for an field by either: + +1. specifying the default value string within your *defineIQ()* method
+**NOTE:**
+The defineIQ() value always takes priority over a field default value. +%BEGINCODE% +Date myDate; + +public void defineIQ() { + // notice the single ticks! + Define.defaultValue(myDate, "'2000-01-01 00:00:00'"); +} +%ENDCODE% + +2. setting a default value on the field
+**NOTE:**
+Primitive types have an implicit default value of *0* or *false*. +%BEGINCODE% +Date myDate = new Date(100, 0, 1); + +int myId; +%ENDCODE% + +### Example Interface Model +%BEGINCODE% +import com.iciql.Iciql; +import com.iciql.Iciql.IQIgnore; + +public class Product implements Iciql { + public Integer productId; + public String productName; + public String category; + public Double unitPrice; + public Integer unitsInStock; + + @IQIgnore + Integer reorderQuantity; + + public Product() { + } + + @Override + public void defineIQ() { + com.iciql.Define.primaryKey(productId); + com.iciql.Define.columnName(unitsInStock, "units"); + com.iciql.Define.length(productName, 200); + com.iciql.Define.length(category, 50); + com.iciql.Define.index(productName, category); + } +} +%ENDCODE% + + +## POJO (Plain Old Java Object) Configuration + +This approach is very similar to the *interface configuration* approach; it is the least verbose and also the least useful. + +This approach would be suitable for quickly modeling an existing table where only SELECT and INSERT statements will be generated. + +### advantages + +- nearly zero-configuration + +### disadvantages + +- can not execute DELETE, UPDATE, or MERGE statements (they require a primary key specification) +- table name MUST MATCH model class name +- column names MUST MATCH model field names +- can not specify any column attributes +- can not specify indexes + +### field mapping + +- **ALL** fields are mapped unless annotated with *@IQIgnore*. +- scope is irrelevant. +- transient is irrelevant. + +### default values + +You may specify a default value on the field. + +**NOTE:**
+Primitive types have an implicit default value of *0* or *false*. +%BEGINCODE% +Date myDate = new Date(100, 0, 1); + +int myId; +%ENDCODE% + +### Example POJO Model +%BEGINCODE% +import com.iciql.Iciql.IQIgnore; + +public class Product { + public Integer productId; + public String productName; + public String category; + public Double unitPrice; + public Integer units; + + @IQIgnore + Integer reorderQuantity; + + public Product() { + } +} +%ENDCODE% \ No newline at end of file diff --git a/src/site/performance.mkd b/src/site/performance.mkd new file mode 100644 index 0000000..34e545c --- /dev/null +++ b/src/site/performance.mkd @@ -0,0 +1,22 @@ + +## Performance + +The information provided here may be based on flawed test procedures. You have to be the judge of what is performant and non-performant. + +### iciql statement generation + +Performance of iciql statement generation is not currently benchmarked. + +### iciql+database performance comparison + +The following data was generated by running the *single-threaded* iciql test suite. All database connections are pooled and re-used within each execution of the test suite using [Apache Commons DBCP](http://commons.apache.org/dbcp). + +Connections are pooled to normalize embedded database performance with out-of-process database performance. Some of the Java embedded database configurations have a very high startup-time penalty. Notably, H2 is slow to open a database and its performance is substantially affected if connection pooling is not enabled to keep the embedded database open. + +All tables are created as CACHED when the database distinguishes between CACHED and MEMORY tables. + +All performance numbers include the combined overhead of iciql statement generation and JUnit 4 test framework execution so they are not bare-metal database metrics. + +
+%DBPERFORMANCE%
+
\ No newline at end of file diff --git a/src/site/table_versioning.mkd b/src/site/table_versioning.mkd new file mode 100644 index 0000000..2e95aaa --- /dev/null +++ b/src/site/table_versioning.mkd @@ -0,0 +1,29 @@ +## Database & Table Versioning + +Iciql supports an optional, simple versioning mechanism. There are two parts to the mechanism. + +1. You must supply an implementation of `com.iciql.DbUpgrader` to your `com.iciql.Db` instance. +2. One or more of your table model classes must specify the `IQVersion(version)` annotation
+AND/OR
+Your `com.iciql.DbUpgrader` implementation must specify the `IQVersion(version)` annotation + +### How does it work? +If you choose to use versioning, iciql will maintain a table within your database named *iq_versions* which is defined as: + + CREATE TABLE IQ_VERSIONS(SCHEMANAME VARCHAR(255) NOT NULL, TABLENAME VARCHAR(255) NOT NULL, VERSION INT NOT NULL) + +This database table is automatically created if and only if at least one of your model classes specifies a *version* > 0. + +When you generate a statement, iciql will compare the annotated version field of your model class to its last known value in the *iq_versions* table. If *iq_versions* lags behind the model annotation, iciql will immediately call the registered `com.iciql.DbUpgrader` implementation before generating and executing the current statement. + +When an upgrade scenario is identified, the current version and the annotated version information is passed to either: + +- `DbUpgrader.upgradeDatabase(db, fromVersion, toVersion)` +- `DbUpgrader.upgradeTable(db, schema, table, fromVersion, toVersion)` + +both of which allow for non-linear upgrades. If the upgrade method call is successful and returns *true*, iciql will update the *iq_versions* table with the annotated version number. + +The actual upgrade procedure is beyond the scope of iciql and is your responsibility to implement. This is simply a mechanism to automatically identify when an upgrade is necessary. + +**NOTE:**
+The database entry of the *iq_versions* table is specified as SCHEMANAME='' and TABLENAME=''. \ No newline at end of file diff --git a/src/site/templates/atom.ftl b/src/site/templates/atom.ftl new file mode 100644 index 0000000..06d28da --- /dev/null +++ b/src/site/templates/atom.ftl @@ -0,0 +1,2 @@ +<#include "macros.ftl"> +<@AtomMacro posts=releases posturl="${project.url}/history.html#" /> \ No newline at end of file diff --git a/src/site/templates/macros.ftl b/src/site/templates/macros.ftl new file mode 100644 index 0000000..e7c275b --- /dev/null +++ b/src/site/templates/macros.ftl @@ -0,0 +1,147 @@ +<#macro LogMacro title version date description log logTitle=""> + <#if log??> +

${title} (${version}) ${description}

+ + + + + + + +
${date}<@LogDescriptionMacro log=log title=logTitle />
+ + + +<#macro LogDescriptionMacro log title=log.title> + <#if (title!?length > 0)> +

${title}

+ + + <#if (log.html!?length > 0)> +

${log.html}

+ + + <#if (log.text!?length > 0)> +

${log.text!?html?replace("\n", "
")}

+ + + <#if (log.note!?length > 0)> +
+

Note

+ ${log.note?html?replace("\n", "

")} +

+ + + <#if (log.security!?size > 0)> + <@SecurityListMacro title="security" list=log.security/> + + <#if (log.fixes!?size > 0)> + <@UnorderedListMacro title="fixes" list=log.fixes /> + + <#if (log.changes!?size > 0)> + <@UnorderedListMacro title="changes" list=log.changes /> + + <#if (log.additions!?size > 0)> + <@UnorderedListMacro title="additions" list=log.additions /> + + <#if (log.settings!?size > 0)> + <@SettingsTableMacro title="new settings" list=log.settings /> + + <#if (log.dependencyChanges!?size > 0)> + <@UnorderedListMacro title="dependency changes" list=log.dependencyChanges /> + + <#if (log.contributors!?size > 0)> + <@UnorderedListMacro title="contributors" list=log.contributors?sort /> + + + +<#macro SecurityListMacro list title> +

${title}

+
    + <#list list as item> +
  • ${item?html?replace("\n", "
    ")}
  • + +
+ + +<#macro UnorderedListMacro list title> +

${title}

+
    + <#list list as item> +
  • ${item?html?replace("\n", "
    ")}
  • + +
+ + +<#macro SettingsTableMacro list title> +

${title}

+ + <#list list as item> + + + + +
${item.name}${item.defaultValue}
+ + +<#macro RssMacro posts posturl> + + + + <![CDATA[${project.name}]]> + ${project.url} + + Moxie Toolkit + <#list posts as post> + + <![CDATA[${post.title}]]> + + ${posturl}${post.id} + <#if (post.text!?length > 0)> + + + <#if (post.keywords!?size > 0)> + <#list post.keywords as keyword> + + + + <#if (post.author!?length > 0)> + + <#else> + + + ${post.date?string("EEE, dd MMM yyyy HH:mm:ss Z")} + + + + + + +<#macro AtomMacro posts posturl> + + + ${project.name} + <![CDATA[${project.name}]]> + ${project.releaseDate} + <#list posts as post> + + + <![CDATA[${post.title}]]> + <#if (post.text!?length > 0)> + + + + ${posturl}${post.id} + <#if (post.text!?length > 0)> + + + <#if (post.keywords!?size > 0)> + <#list post.keywords as keyword> + + + + ${post.date?string("yyyy-MM-dd'T'HH:mm:ssZ")} + + + + \ No newline at end of file diff --git a/src/site/templates/releasecurrent.ftl b/src/site/templates/releasecurrent.ftl new file mode 100644 index 0000000..3bfd709 --- /dev/null +++ b/src/site/templates/releasecurrent.ftl @@ -0,0 +1,25 @@ +<#include "macros.ftl" > + + +<@LogMacro + title="Current Release" + log=release + version=project.releaseVersion + date=reference.releaseDate?string("yyyy-MM-dd") + description="this is the current stable release" /> + + +<#if snapshot??> +<@LogMacro + title="Next Release" + log=snapshot + version=project.version + date="PENDING" + description="these changes are queued for an upcoming release" /> + + + diff --git a/src/site/templates/releasehistory.ftl b/src/site/templates/releasehistory.ftl new file mode 100644 index 0000000..eaaaad2 --- /dev/null +++ b/src/site/templates/releasehistory.ftl @@ -0,0 +1,21 @@ +<#include "macros.ftl" > + + +<#if (releases!?size > 0)> +

+

All Releases

+ + + + <#list releases?sort_by("date")?reverse as log> + + + + + + +
+ ${log.id}
+ ${log.date?string("yyyy-MM-dd")} +
<@LogDescriptionMacro log=log />
+ \ No newline at end of file diff --git a/src/site/templates/rss.ftl b/src/site/templates/rss.ftl new file mode 100644 index 0000000..90e86eb --- /dev/null +++ b/src/site/templates/rss.ftl @@ -0,0 +1,2 @@ +<#include "macros.ftl"> +<@RssMacro posts=releases posturl="${project.url}/releases.html#" /> \ No newline at end of file diff --git a/src/site/tools.mkd b/src/site/tools.mkd new file mode 100644 index 0000000..6d8c348 --- /dev/null +++ b/src/site/tools.mkd @@ -0,0 +1,95 @@ +## Model Generation +If you do not have or do not want to annotate your existing model classes, you can use the included model generation tool to create iciql model classes. + + java -jar iciql.jar + +### Parameters + + + + + + + + + + +
-urlJDBC url for the databaseREQUIRED
-usernameusername for JDBC connectionoptional
-passwordpassword for JDBC connectionoptional
-schemathe target schema for model generationdefault: all schemas
-tablethe target table for model generationdefault: all tables
-packagethe destination package name for generated modelsdefault: default package
-folderthe output folder for .java filesdefault: current folder
-annotateSchemainclude the schema name in the class annotationsdefault: true
-trimStringsannotate trimStrings=true for any VARCHAR string mappings   default: false
+ +## Model Validation +Iciql can validate your model classes against your database to ensure that your models are optimally defined and are consistent with the current table and index definitions. + +Each `com.iciql.ValidationRemark` returned by the validation has an associated level from the following enum: +%BEGINCODE% +public static enum Level { + CONSIDER, WARN, ERROR; +} +%ENDCODE% + +A typical validation may output recommendations for adjusting a model field annotation such as setting the *maxLength* of a string to match the length of its linked VARCHAR column. + +### Sample Model Validation using JUnit 4 +%BEGINCODE% +import static org.junit.Assert.assertTrue; + +import java.sql.SQLException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ErrorCollector; + +import com.iciql.Db; +import com.iciql.DbInspector; +import com.iciql.ValidationRemark; +import com.iciql.test.models.Product; +import com.iciql.test.models.ProductAnnotationOnly; +import com.iciql.test.models.ProductMixedAnnotation; + +public class ValidateModels { + + /* + * The ErrorCollector Rule allows execution of a test to continue after the + * first problem is found and report them all at once + */ + @Rule + public ErrorCollector errorCollector = new ErrorCollector(); + + private Db db; + + @Before + public void setUp() { + db = Db.open("jdbc:h2:mem:", "sa", "sa"); + } + + @After + public void tearDown() { + db.close(); + } + + @Test + public void testValidateModels() { + DbInspector inspector = new DbInspector(db); + validateModel(inspector, new Product()); + validateModel(inspector, new ProductAnnotationOnly()); + validateModel(inspector, new ProductMixedAnnotation()); + } + + private void validateModel(DbInspector inspector, Object o) { + List remarks = inspector.validateModel(o, false); + assertTrue("Validation remarks are null for " + o.getClass().getName(), remarks != null); + log("Validation remarks for " + o.getClass().getName()); + for (ValidationRemark remark : remarks) { + log(remark.toString()); + if (remark.isError()) { + errorCollector.addError(new SQLException(remark.toString())); + } + } + } + + private void log(String message) { + System.out.println(message); + } +} +%ENDCODE% \ No newline at end of file diff --git a/src/site/usage.mkd b/src/site/usage.mkd new file mode 100644 index 0000000..7b9d89d --- /dev/null +++ b/src/site/usage.mkd @@ -0,0 +1,197 @@ +## Usage + +Aside from this brief usage guide, please consult the [examples](examples.html), the [javadoc](javadoc.html) and the [source code](${project.scmUrl}). + +### Instantiating a Db + +Use one of the static utility methods to instantiate a Db instance: + + Db.open(String url, String user, String password); + Db.open(String url, String user, char[] password); + Db.open(Connection conn); + Db.open(DataSource dataSource); + +### Compile-Time Statements + +You compose your statements using the builder pattern where each method call returns an object that is used to specify the next part of the statement. Through clever usage of generics, pioneered by the original JaQu project, compile-time safety flows through the statement. + +%BEGINCODE% +Db db = Db.open("jdbc:h2:mem:", "sa", "sa"); +db.insertAll(Product.getList()); +db.insertAll(Customer.getList()); + +List restock = + db.from(p). + where(p.unitsInStock). + is(0).orderBy(p.productId).select(); + +for (Product product : restock) { + db.from(p). + set(p.unitsInStock).to(25). + where(p.productId).is(product.productId).update(); +} +db.close(); +%ENDCODE% + +Please see the [examples](examples.html) page for more code samples. + +### Dynamic Runtime Queries + +Iciql gives you compile-time type-safety, but it becomes inconvenient if your design requires more dynamic statement generation. For these scenarios iciql offers some runtime query support through a hybrid approach or a pure JDBC approach. + +#### Where String Fragment Approach +This approach is a mixture of iciql and jdbc. It uses the traditional prepared statement *field=?* tokens with iciql compile-time model class type checking. There is no field token type-safety checking. +%BEGINCODE% +List restock = db.from(p).where("unitsInStock=? and productName like ? order by productId", 0, "Chef%").select(); +%ENDCODE% + +#### Db.executeQuery Approaches +There may be times when the hybrid approach is still too restrictive and you'd prefer to write straight SQL. You can do that too and use iciql to build objects from your ResultSet, but be careful: + +1. Make sure to _select *_ in your query otherwise db.buildObjects() will throw a RuntimeException +2. There is no model class type checking nor field type checking. + +%BEGINCODE% +List allProducts = db.executeQuery(Product.class, "select * from products"); +List restock = db.executeQuery(Product.class, "select * from products where unitsInStock=?", 0); + +// parameterized query which can be cached and re-used later +String q = db.from(p).where(p.unitsInStock).isParameter().toSQL(); +List restock = db.executeQuery(Product.class, q, 0); + +%ENDCODE% + +Or if you want access to the raw *ResultSet* before building your model object instances... + +%BEGINCODE% +ResultSet rs = db.executeQuery("select * from products"); +List allProducts = db.buildObjects(Product.class, rs); +// This method ensures the creating statement is closed +JdbcUtils.closeSilently(rs, true); +%ENDCODE% + +### Natural Syntax + +work-in-progress + +The original JaQu source offers partial support for Java expressions in *where* clauses. + +This works by decompiling a Java expression, at runtime, to an SQL condition. The expression is written as an anonymous inner class implementation of the `com.iciql.Filter` interface. +A proof-of-concept decompiler is included, but is incomplete. + +The proposed syntax is: +%BEGINCODE% +long count = db.from(co). + where(new Filter() { public boolean where() { + return co.id == x + && co.name.equals(name) + && co.value == new BigDecimal("1") + && co.amount == 1L + && co.birthday.before(new java.util.Date()) + && co.created.before(java.sql.Timestamp.valueOf("2005-05-05 05:05:05")) + && co.time.before(java.sql.Time.valueOf("23:23:23")); + } + }).selectCount(); +%ENDCODE% + +### JDBC Statements, ResultSets, and Exception Handling + +Iciql opens and closes all JDBC objects automatically. SQLExceptions thrown during execution of a statement (except for *close()* calls), will be caught, wrapped, and rethrown as an `IciqlException`, which is a RuntimeException. + +Iciql does not throw any [checked exceptions](http://en.wikipedia.org/wiki/Exception_handling#Checked_exceptions). + +### Statement Logging + +Iciql provides a mechanism to log generated statements and warnings to the console, to SLF4J, or to your own logging framework. Exceptions are not logged using this mechanism; exceptions are wrapped and rethrown as `IciqlException`, which is a RuntimeException. + +#### Console Logging +%BEGINCODE% +IciqlLogger.activeConsoleLogger(); +IciqlLogger.deactiveConsoleLogger(); +%ENDCODE% + +#### SLF4J Logging +%BEGINCODE% +Slf4jIciqlListener slf4j = new Slf4jIciqlListener(); +slf4j.setLevel(StatementType.CREATE, Level.WARN); +slf4j.setLevel(StatementType.DELETE, Level.WARN); +slf4j.setLevel(StatementType.MERGE, Level.OFF); +IciqlLogger.registerListener(slf4j); +IciqlLogger.unregisterListener(slf4j); +%ENDCODE% + +#### Custom Logging +%BEGINCODE% +IciqlListener custom = new IciqlListener() { + public void logIciql(StatementType type, String statement) { + // do log + } +}; +IciqlLogger.registerListener(custom); +IciqlLogger.unregisterListener(custom); +%ENDCODE% + +## Understanding Aliases and Model Classes +Consider the following example: +%BEGINCODE% +Product p = new Product(); +List restock = db.from(p).where(p.unitsInStock).is(0).select(); +%ENDCODE% + +The Product model class instance named **p** is an *alias* object. An *alias* is simply an instance of your model class that is only used to build the compile-time/runtime representation of your table. + +1. *Alias* instances are **NOT** thread-safe and must not be used concurrently. +2. *Alias* instances have no other purpose than to provide a compile-time/runtime map of your table. +3. If you inspected an *alias* instance after using one you would find that it's fields have been assigned numeric values.
These values are assigned from a static counter in `com.iciql.Utils.newObject()` during execution of the *db.from()* method.

For *Object* fields, these values are meaningless since objects are mapped by reference.
For *Primitive* fields these values do matter because primitives are mapped by value. The proper alias is selected as long as the primitive variant methods are used. e.g. db.from(p).where(int).is(Integer).select() + +If your statement is a query, like in the above example, iciql will generate new instances of your *alias* model class and return them as a list where each entry of the list represents a row from the JDBC `ResultSet`. + +### Why are Aliases not thread-safe? + +The _db.from(p)_ call reinstantiates each member field of p. Those reinstantiated fields are then subsequently used in clauses like _where(p.unitsInStock)_. If your *alias* instance is shared concurrently then its highly probable that when _queryA_ executes, _queryC_ has reinstantiated all the *alias* fields and broken _queryA's_ runtime field mapping. + +Depending on your design, you might consider using a [ThreadLocal](http://download.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html) variable if you do not want to keep instantiating *alias* instances. A utility function is included for easily creating ThreadLocal variables. + +%BEGINCODE% +final ThreadLocal p = Utils.newThreadLocal(Product.class); +db.from(p.get()).select(); +%ENDCODE% + +## Best Practices + +1. Close your *Db* instances when you are done with them, this closes the underlying connection or directs the pool to "close" the connection. +2. Aliases instances are not thread-safe so DO NOT SHARE an alias!
Consider using a *ThreadLocal* alias instance with the `com.iciql.Utils.newThreadLocal()` utility method. + +

+ + + +
Not Thread-SafeThread-Safe
+%BEGINCODE% +final Product p = new Product(); +for (int i = 0; i < 5; i++) { + Thread thread = new Thread(new Runnable() { + public void run() { + // from(p) reinstantiates p's fields + db.from(p).select(); + } + }, "Thread-" + i); + thread.start(); +} +%ENDCODE% + + +%BEGINCODE% +final ThreadLocal p = Utils.newThreadLocal(Product.class); +for (int i = 0; i < 5; i++) { + Thread thread = new Thread(new Runnable() { + public void run() { + // a unique p for this thread + db.from(p.get()).select(); + } + }, "Thread-" + i); + thread.start(); +} +%ENDCODE% + +
\ No newline at end of file -- cgit v1.2.3