提交 976bc8b3 authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 1e0db2e8
/**********************************************************************
Copyright (c) 2006 Andy Jefferson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
2006 Thomas Mueller - updated the dialect for the H2 database engine
**********************************************************************/
package org.jpox.store.rdbms.adapter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.sql.DataSource;
import org.jpox.store.DatastoreContainerObject;
import org.jpox.store.DatastoreIdentifier;
import org.jpox.store.Dictionary;
import org.jpox.store.expression.LogicSetExpression;
import org.jpox.store.expression.NumericExpression;
import org.jpox.store.expression.QueryExpression;
import org.jpox.store.expression.ScalarExpression;
import org.jpox.store.expression.TableExprAsJoins;
import org.jpox.store.rdbms.Column;
import org.jpox.store.rdbms.key.PrimaryKey;
import org.jpox.store.rdbms.table.Table;
/**
* Provides methods for adapting SQL language elements to the H2 Database Engine.
*
* @version $Revision: 1.1 $
*/
class H2Adapter extends DatabaseAdapter
{
private String schemaName;
/**
* Constructs a H2 adapter based on the given JDBCmetadata.
* @param dictionary The Dictionary to use
* @param metadata the database metadata.
*/
public H2Adapter(Dictionary dictionary, DatabaseMetaData metadata)
{
super(dictionary, metadata);
// Set schema name
try
{
ResultSet rs = metadata.getSchemas();
while (rs.next())
{
if (rs.getBoolean("IS_DEFAULT"))
{
schemaName = rs.getString("TABLE_SCHEM");
}
}
}
catch (SQLException e)
{
e.printStackTrace();
// ignore
}
}
/**
* Accessor for the vendor ID for this adapter.
* @return The vendor ID
*/
public String getVendorID()
{
return "h2";
}
/**
* Accessor for a Connection to the datastore.
* @param ds The data source. Possible to have more than one datasource for failover
* @param userName The username for the datastore
* @param password The password for the datastore
* @param isolationLevel The level of transaction isolation
* @return The Connection
* @throws SQLException Thrown when an error occurs in the creation.
**/
public Connection getConnection(DataSource[] ds, String userName, String password, int isolationLevel)
throws SQLException
{
return super.getConnection(ds,userName,password,Connection.TRANSACTION_SERIALIZABLE);
}
/**
* Accessor for the maximum table name length permitted on this
* datastore.
* @return Max table name length
**/
public int getMaxTableNameLength()
{
return SQLConstants.MAX_IDENTIFIER_LENGTH;
}
/**
* Accessor for the maximum constraint name length permitted on this
* datastore.
* @return Max constraint name length
**/
public int getMaxConstraintNameLength()
{
return SQLConstants.MAX_IDENTIFIER_LENGTH;
}
/**
* Accessor for the maximum index name length permitted on this datastore.
* @return Max index name length
**/
public int getMaxIndexNameLength()
{
return SQLConstants.MAX_IDENTIFIER_LENGTH;
}
/**
* Accessor for the maximum column name length permitted on this datastore.
* @return Max column name length
**/
public int getMaxColumnNameLength()
{
return SQLConstants.MAX_IDENTIFIER_LENGTH;
}
/**
* Accessor for the SQL statement to add a column to a table.
* @param table The table
* @param col The column
* @return The SQL necessary to add the column
*/
public String getAddColumnStatement(DatastoreContainerObject table, Column col)
{
return "ALTER TABLE " + table.toString() + " ADD COLUMN " + col.getSQLDefinition();
}
/**
* Method to return the SQL to append to the SELECT clause of a SELECT statement to handle
* restriction of ranges using the LIMUT keyword.
* @param offset The offset to return from
* @param count The number of items to return
* @return The SQL to append to allow for ranges using LIMIT.
*/
public String getRangeByLimitSelectClause(long offset, long count)
{
if (offset >= 0 && count > 0)
{
return " LIMIT " + offset + " " + count + " ";
}
else if (offset <= 0 && count > 0)
{
return " LIMIT 0 " + count + " ";
}
else
{
return "";
}
}
/**
* Accessor for whether the adapter supports the transaction isolation level
*
* @param isolationLevel the isolation level
* @return Whether the transaction isolation level setting is supported.
*/
public boolean supportsTransactionIsolationLevel(int isolationLevel)
{
if (isolationLevel == Connection.TRANSACTION_READ_COMMITTED || isolationLevel == Connection.TRANSACTION_SERIALIZABLE)
{
return true;
}
return false;
}
/**
* Whether the datastore supports specification of the primary key in CREATE
* TABLE statements.
* @return Whether it allows "PRIMARY KEY ..."
*/
public boolean supportsPrimaryKeyInCreateStatements()
{
return true;
}
/**
* Accessor for the Schema Name for this datastore.
*
* @param conn Connection to the datastore
* @return The schema name
**/
public String getSchemaName(Connection conn)
throws SQLException
{
return schemaName;
}
/**
* @param pk An object describing the primary key.
* @return The PK statement
*/
public String getAddPrimaryKeyStatement(PrimaryKey pk)
{
// PK is created by the CREATE TABLE statement so we just return null
return null;
}
/**
* Returns the appropriate SQL to drop the given table.
* It should return something like:
* <p>
* <blockquote><pre>
* DROP TABLE FOO
* </pre></blockquote>
*
* @param table The table to drop.
* @return The text of the SQL statement.
*/
public String getDropTableStatement(DatastoreContainerObject table)
{
return "DROP TABLE " + table.toString();
}
/**
* Whether we support deferred constraints in keys.
* @return whether we support deferred constraints in keys.
**/
public boolean supportsDeferredConstraints()
{
return false;
}
/**
* Whether we support autoincrementing fields.
* @return whether we support autoincrementing fields.
**/
public boolean supportsAutoIncrementFields()
{
return true;
}
/**
* Accessor for the auto-increment sql statement for this datastore.
* @param tableName Name of the table that the autoincrement is for
* @param columnName Name of the column that the autoincrement is for
* @return The statement for getting the latest auto-increment key
**/
public String getAutoIncrementStmt(String tableName, String columnName)
{
return "CALL IDENTITY()";
}
/**
* Accessor for the auto-increment keyword for generating DDLs (CREATE TABLEs...).
* @return The keyword for a column using auto-increment
**/
public String getAutoIncrementKeyword()
{
return "IDENTITY";
}
/**
* Method to retutn the INSERT statement to use when inserting into a table that has no
* columns specified. This is the case when we have a single column in the table and that column
* is autoincrement/identity (and so is assigned automatically in the datastore).
* @param table The table
* @return The INSERT statement
*/
public String getInsertStatementForNoColumns(Table table)
{
return "INSERT INTO " + table.toString() + " VALUES(NULL)";
}
/**
* Whether to allow Unique statements in the section of CREATE TABLE after the
* column definitions.
* @see org.jpox.store.rdbms.adapter.DatabaseAdapter#supportsUniqueConstraintsInEndCreateStatements()
*/
public boolean supportsUniqueConstraintsInEndCreateStatements()
{
return true;
}
/**
* Whether this datastore supports the use of CHECK after the column
* definitions in CREATE TABLE statements (DDL).
* e.g.
* CREATE TABLE XXX
* (
* COL_A int,
* COL_B char(1),
* PRIMARY KEY (COL_A),
* CHECK (COL_B IN ('Y','N'))
* )
* @return whether we can use CHECK after the column definitions in CREATE TABLE.
**/
public boolean supportsCheckConstraintsInEndCreateStatements()
{
return true;
}
/**
* Accessor for whether the specified type is allow to be part of a PK.
* @param datatype The JDBC type
* @return Whether it is permitted in the PK
*/
public boolean isValidPrimaryKeyType(int datatype)
{
return true;
}
/**
* Method to generate a modulus expression. The binary % operator is said to
* yield the remainder of its operands from an implied division; the
* left-hand operand is the dividend and the right-hand operand is the
* divisor. This returns MOD(expr1, expr2).
* @param operand1 the left expression
* @param operand2 the right expression
* @return The Expression for modulus
*/
public NumericExpression modOperator(ScalarExpression operand1, ScalarExpression operand2)
{
ArrayList args = new ArrayList();
args.add(operand1);
args.add(operand2);
return new NumericExpression("MOD", args);
}
/**
* Return a new TableExpression.
* @param qs The QueryStatement to add the expression to
* @param table The table in the expression
* @param rangeVar range variable to assign to the expression.
* @return The expression.
**/
public LogicSetExpression newTableExpression(QueryExpression qs, DatastoreContainerObject table, DatastoreIdentifier rangeVar)
{
return new TableExprAsJoins(qs, table, rangeVar);
}
}
\ No newline at end of file
package org.h2.tools.servlet;
import javax.servlet.*;
import java.sql.*;
public class DbStarter implements ServletContextListener {
private Connection conn;
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
Class.forName("org.h2.Driver");
// You can also get the setting from a context-param in web.xml:
ServletContext servletContext = servletContextEvent.getServletContext();
// String url = servletContext.getInitParameter("db.url");
conn = DriverManager.getConnection("jdbc:h2:test", "sa", "");
servletContext.setAttribute("connection", conn);
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return conn;
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package org.hibernate.dialect;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.Hibernate;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.exception.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.ViolatedConstraintNameExtracter;
import org.hibernate.util.ReflectHelper;
/**
* A dialect compatible with the H2 database.
*
* @author Thomas Mueller
*
*/
public class H2Dialect extends Dialect {
private String querySequenceString;
public H2Dialect() {
super();
querySequenceString = "select sequence_name from information_schema.sequences";
try {
Class constants = ReflectHelper.classForName( "org.h2.engine.Constants" );
Integer build = (Integer)constants.getDeclaredField("BUILD_ID" ).get(null);
int buildid = build.intValue();
if(buildid < 32) {
querySequenceString = "select name from information_schema.sequences";
}
} catch(Throwable e) {
// ignore (probably H2 not in the classpath)
}
registerColumnType(Types.BOOLEAN, "boolean");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.BINARY, "binary");
registerColumnType(Types.BIT, "boolean");
registerColumnType(Types.CHAR, "varchar($l)");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.DECIMAL, "decimal($p,$s)");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.LONGVARBINARY, "longvarbinary");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.VARCHAR, "varchar($l)");
registerColumnType(Types.VARBINARY, "binary($l)");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
// select topic, syntax from information_schema.help
// where section like 'Function%' order by section, topic
// registerFunction("abs", new StandardSQLFunction("abs"));
registerFunction("acos", new StandardSQLFunction("acos", Hibernate.DOUBLE));
registerFunction("asin", new StandardSQLFunction("asin", Hibernate.DOUBLE));
registerFunction("atan", new StandardSQLFunction("atan", Hibernate.DOUBLE));
registerFunction("atan2", new StandardSQLFunction("atan2", Hibernate.DOUBLE));
registerFunction("bitand", new StandardSQLFunction("bitand", Hibernate.INTEGER));
registerFunction("bitor", new StandardSQLFunction("bitor", Hibernate.INTEGER));
registerFunction("bitxor", new StandardSQLFunction("bitxor", Hibernate.INTEGER));
registerFunction("ceiling", new StandardSQLFunction("ceiling", Hibernate.DOUBLE));
registerFunction("cos", new StandardSQLFunction("cos", Hibernate.DOUBLE));
registerFunction("cot", new StandardSQLFunction("cot", Hibernate.DOUBLE));
registerFunction("degrees", new StandardSQLFunction("degrees", Hibernate.DOUBLE));
registerFunction("exp", new StandardSQLFunction("exp", Hibernate.DOUBLE));
registerFunction("floor", new StandardSQLFunction("floor", Hibernate.DOUBLE));
registerFunction("log", new StandardSQLFunction("log", Hibernate.DOUBLE));
registerFunction("log10", new StandardSQLFunction("log10", Hibernate.DOUBLE));
// registerFunction("mod", new StandardSQLFunction("mod", Hibernate.INTEGER));
registerFunction("pi", new NoArgSQLFunction("pi", Hibernate.DOUBLE));
registerFunction("power", new StandardSQLFunction("power", Hibernate.DOUBLE));
registerFunction("radians", new StandardSQLFunction("radians", Hibernate.DOUBLE));
registerFunction("rand", new NoArgSQLFunction("rand", Hibernate.DOUBLE));
registerFunction("round", new StandardSQLFunction("round", Hibernate.DOUBLE));
registerFunction("roundmagic", new StandardSQLFunction("roundmagic", Hibernate.DOUBLE));
registerFunction("sign", new StandardSQLFunction("sign", Hibernate.INTEGER));
registerFunction("sin", new StandardSQLFunction("sin", Hibernate.DOUBLE));
// registerFunction("sqrt", new StandardSQLFunction("sqrt", Hibernate.DOUBLE));
registerFunction("tan", new StandardSQLFunction("tan", Hibernate.DOUBLE));
registerFunction("truncate", new StandardSQLFunction("truncate", Hibernate.DOUBLE));
registerFunction("compress", new StandardSQLFunction("compress", Hibernate.BINARY));
registerFunction("expand", new StandardSQLFunction("compress", Hibernate.BINARY));
registerFunction("decrypt", new StandardSQLFunction("decrypt", Hibernate.BINARY));
registerFunction("encrypt", new StandardSQLFunction("encrypt", Hibernate.BINARY));
registerFunction("hash", new StandardSQLFunction("hash", Hibernate.BINARY));
registerFunction("ascii", new StandardSQLFunction("ascii", Hibernate.INTEGER));
// registerFunction("bit_length", new StandardSQLFunction("bit_length", Hibernate.INTEGER));
registerFunction("char", new StandardSQLFunction("char", Hibernate.CHARACTER));
registerFunction("concat", new VarArgsSQLFunction(Hibernate.STRING, "(", "||", ")"));
registerFunction("difference", new StandardSQLFunction("difference", Hibernate.INTEGER));
registerFunction("hextoraw", new StandardSQLFunction("hextoraw", Hibernate.STRING));
registerFunction("lower", new StandardSQLFunction("lower", Hibernate.STRING));
registerFunction("insert", new StandardSQLFunction("lower", Hibernate.STRING));
registerFunction("left", new StandardSQLFunction("left", Hibernate.STRING));
// registerFunction("length", new StandardSQLFunction("length", Hibernate.INTEGER));
// registerFunction("locate", new StandardSQLFunction("locate", Hibernate.INTEGER));
// registerFunction("lower", new StandardSQLFunction("lower", Hibernate.STRING));
registerFunction("lcase", new StandardSQLFunction("lcase", Hibernate.STRING));
registerFunction("ltrim", new StandardSQLFunction("ltrim", Hibernate.STRING));
registerFunction("octet_length", new StandardSQLFunction("octet_length", Hibernate.INTEGER));
registerFunction("position", new StandardSQLFunction("position", Hibernate.INTEGER));
registerFunction("rawtohex", new StandardSQLFunction("rawtohex", Hibernate.STRING));
registerFunction("repeat", new StandardSQLFunction("repeat", Hibernate.STRING));
registerFunction("replace", new StandardSQLFunction("replace", Hibernate.STRING));
registerFunction("right", new StandardSQLFunction("right", Hibernate.STRING));
registerFunction("rtrim", new StandardSQLFunction("rtrim", Hibernate.STRING));
registerFunction("soundex", new StandardSQLFunction("soundex", Hibernate.STRING));
registerFunction("space", new StandardSQLFunction("space", Hibernate.STRING));
registerFunction("stringencode", new StandardSQLFunction("stringencode", Hibernate.STRING));
registerFunction("stringdecode", new StandardSQLFunction("stringdecode", Hibernate.STRING));
// registerFunction("substring", new StandardSQLFunction("substring", Hibernate.STRING));
// registerFunction("upper", new StandardSQLFunction("upper", Hibernate.STRING));
registerFunction("ucase", new StandardSQLFunction("ucase", Hibernate.STRING));
registerFunction("stringtoutf8", new StandardSQLFunction("stringtoutf8", Hibernate.BINARY));
registerFunction("utf8tostring", new StandardSQLFunction("utf8tostring", Hibernate.STRING));
registerFunction("current_date", new NoArgSQLFunction("current_date", Hibernate.DATE));
registerFunction("current_time", new NoArgSQLFunction("current_time", Hibernate.TIME));
registerFunction("current_timestamp", new NoArgSQLFunction("current_timestamp", Hibernate.TIMESTAMP));
registerFunction("datediff", new NoArgSQLFunction("datediff", Hibernate.INTEGER));
registerFunction("dayname", new StandardSQLFunction("dayname", Hibernate.STRING));
registerFunction("dayofmonth", new StandardSQLFunction("dayofmonth", Hibernate.INTEGER));
registerFunction("dayofweek", new StandardSQLFunction("dayofweek", Hibernate.INTEGER));
registerFunction("dayofyear", new StandardSQLFunction("dayofyear", Hibernate.INTEGER));
// registerFunction("hour", new StandardSQLFunction("hour", Hibernate.INTEGER));
// registerFunction("minute", new StandardSQLFunction("minute", Hibernate.INTEGER));
// registerFunction("month", new StandardSQLFunction("month", Hibernate.INTEGER));
registerFunction("monthname", new StandardSQLFunction("monthname", Hibernate.STRING));
registerFunction("quater", new StandardSQLFunction("quater", Hibernate.INTEGER));
// registerFunction("second", new StandardSQLFunction("second", Hibernate.INTEGER));
registerFunction("week", new StandardSQLFunction("week", Hibernate.INTEGER));
// registerFunction("year", new StandardSQLFunction("year", Hibernate.INTEGER));
registerFunction("curdate", new NoArgSQLFunction("curdate", Hibernate.DATE));
registerFunction("curtime", new NoArgSQLFunction("curtime", Hibernate.TIME));
registerFunction("curtimestamp", new NoArgSQLFunction("curtimestamp", Hibernate.TIME));
registerFunction("now", new NoArgSQLFunction("now", Hibernate.TIMESTAMP));
registerFunction("database", new NoArgSQLFunction("database", Hibernate.STRING));
registerFunction("user", new NoArgSQLFunction("user", Hibernate.STRING));
getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE);
}
public String getAddColumnString() {
return "add column";
}
public boolean supportsIdentityColumns() {
return true;
}
public String getIdentityColumnString() {
return "generated by default as identity"; // not null is implicit
}
public String getIdentitySelectString() {
return "call identity()";
}
public String getIdentityInsertString() {
return "null";
}
public String getForUpdateString() {
return " for update";
}
public boolean supportsUnique() {
return true;
}
public boolean supportsLimit() {
return true;
}
public String getLimitString(String sql, boolean hasOffset) {
return new StringBuffer(sql.length() + 20).
append(sql).
append(hasOffset ? " limit ? offset ?" : " limit ?").
toString();
}
public boolean bindLimitParametersInReverseOrder() {
return true;
}
public boolean bindLimitParametersFirst() {
return false;
}
public boolean supportsIfExistsAfterTableName() {
return true;
}
public String[] getCreateSequenceStrings(String sequenceName) {
return new String[] {
"create sequence " + sequenceName
};
}
public String[] getDropSequenceStrings(String sequenceName) {
return new String[] {
"drop sequence " + sequenceName
};
}
public String getSelectSequenceNextValString(String sequenceName) {
return "next value for " + sequenceName;
}
public String getSequenceNextValString(String sequenceName) {
return "call next value for " + sequenceName;
}
public String getQuerySequencesString() {
return querySequenceString;
}
public boolean supportsSequences() {
return true;
}
public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() {
return EXTRACTER;
}
private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() {
/**
* Extract the name of the violated constraint from the given SQLException.
*
* @param sqle The exception that was the result of the constraint violation.
* @return The extracted constraint name.
*/
public String extractConstraintName(SQLException sqle) {
String constraintName = null;
// 23000: Check constraint violation: {0}
// 23001: Unique index or primary key violation: {0}
if(sqle.getSQLState().startsWith("23")) {
String message = sqle.getMessage();
int idx = message.indexOf("violation: ");
if(idx > 0) {
constraintName = message.substring(idx + "violation: ".length());
}
}
return constraintName;
}
};
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "call current_timestamp()";
}
public boolean supportsUnionAll() {
return true;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论