Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2007 Daniel Spiewak
   * 
   * 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.
  */
 package net.java.ao.db;
 
 import java.sql.Types;
 import java.util.Set;
 
 
 
 import static com.google.common.collect.Iterables.concat;
 import static net.java.ao.sql.SqlUtils.closeQuietly;

Author(s):
Daniel Spiewak
 
 public final class HSQLDatabaseProvider extends DatabaseProvider
 {
     public HSQLDatabaseProvider(DisposableDataSource dataSource)
     {
         this(dataSource"PUBLIC");
     }
 
     public HSQLDatabaseProvider(DisposableDataSource dataSourceString schema)
     {
         super(dataSourceschema, TypeManager.hsql());
     }
 
     @Override
     public String renderMetadataQuery(final String tableName)
     {
         return "SELECT LIMIT 0 1 * FROM " + withSchema(tableName);
     }
 
     @Override
 	@SuppressWarnings("unused")
     public <T extends RawEntity<K>, K> K insertReturningKey(EntityManager managerConnection conn,
                                                             Class<T> entityTypeClass<K> pkType,
                                                             String pkFieldboolean pkIdentityString tableDBParam... paramsthrows SQLException
     {
 		StringBuilder sql = new StringBuilder("INSERT INTO " + processID(table) + " (");
 
 		for (DBParam param : params) {
 			sql.append(processID(param.getField()));
 			sql.append(',');
 		}
 		if (params.length > 0) {
 			sql.setLength(sql.length() - 1);
 		} else {
 			sql.append(processID(pkField));
 		}
 
 		sql.append(") VALUES (");
 
 		for (DBParam param : params) {
 			sql.append("?,");
 		}
 		if (params.length > 0) {
 			sql.setLength(sql.length() - 1);
 		} else {
			sql.append("NULL");
		}
		sql.append(")");
		return executeInsertReturningKey(managerconnentityTypepkTypepkFieldsql.toString(), params);
	}
    protected synchronized <T extends RawEntity<K>, K> K executeInsertReturningKey(EntityManager managerConnection conn
            Class<T> entityTypeClass<K> pkType,
            String pkFieldString sqlDBParam... paramsthrows SQLException
    {
	    K back = null;
		PreparedStatement stmt = preparedStatement(connsql);
		for (int i = 0; i < params.lengthi++) {
			Object value = params[i].getValue();
			if (value instanceof RawEntity<?>) {
				value = Common.getPrimaryKeyValue((RawEntity<Object>) value);
			}
			if (params[i].getField().equalsIgnoreCase(pkField)) {
				back = (K) value;
			}
			if (value == null) {
				putNull(stmti + 1);
else {
				type.getLogicalType().putToDatabase(managerstmti + 1, valuetype.getJdbcWriteType());
			}
		}
		stmt.close();
		if (back == null) {
			stmt = conn.prepareStatement("CALL IDENTITY()");		// WARNING	potential breakage here if dealing with INSERTs outside ORM control
			ResultSet res = stmt.executeQuery();
			if (res.next()) {
				 back = .getType(pkType).getLogicalType().pullFromDatabase(nullrespkType, 1);
			}
			res.close();
			stmt.close();
		}
		return back;
	}
	public Object parseValue(int typeString value) {
		if (value == null || value.equals("") || value.equals("NULL")) {
			return null;
		}
		switch (type) {
			case .:
			case .:
            case .:
				Matcher matcher = Pattern.compile("'(.*)'.*").matcher(value);
				if (matcher.find()) {
					value = matcher.group(1);
				}
			break;
		}
		return super.parseValue(typevalue);
	}
	public ResultSet getTables(Connection connthrows SQLException {
		return conn.getMetaData().getTables(nullgetSchema(), nullnew String[] {"TABLE"});
	}
    @Override
    public void dispose()
    {
        Connection conn = null;
        Statement stmt = null;
        try
        {
            conn = getConnection();
            stmt = conn.createStatement();
            stmt.executeUpdate("SHUTDOWN");
        }
        catch (SQLException e)
        {
            // ignored
        }
        finally
        {
            closeQuietly(stmt);
            closeQuietly(conn);
        }
        super.dispose();
    }
    @Override
	protected String renderQuerySelect(final Query queryTableNameConverter converterboolean count) {
		String tableName = query.getTable();
		if (tableName == null) {
			tableName = converter.getName(query.getTableType());
		}
		switch (query.getType()) {
			case :
                // Must match this syntax: http://www.hsqldb.org/doc/guide/ch09.html#select-section
				sql.append("SELECT ");
                int limit = query.getLimit();
                int offset = query.getOffset();
                if (limit >= 0 || offset > 0)
                {
                    sql.append("LIMIT ");
                    if (offset > 0)
                    {
                        sql.append(offset);
                    }
                    else
                    {
                        sql.append(0);
                    }
                    sql.append(" ");
                    if (limit >= 0)
                    {
                        sql.append(limit);
                    }
                    else
                    {
                        sql.append(0);
                    }
                    sql.append(" ");
                }
                if (query.isDistinct())
                {
                    sql.append("DISTINCT ");
                }
                if (count)
                {
                    sql.append("COUNT(*)");
                }
                else
                {
                    sql.append(querySelectFields(queryconverter));
                }
                sql.append(" FROM ").append(queryTableName(queryconverter));
			break;
		}
		return sql.toString();
	}
    @Override
	protected String renderQueryLimit(Query query) {
		return "";
	}
    @Override
	protected String renderAutoIncrement() {
		return "GENERATED BY DEFAULT AS IDENTITY (START WITH 1)";
	}
	protected String getDateFormat() {
		return "yyyy-MM-dd HH:mm:ss.SSS";
	}
	protected String renderUnique(UniqueNameConverter uniqueNameConverterDDLTable tableDDLField field) {
		return "";
	}
	protected String renderConstraintsForTable(UniqueNameConverter uniqueNameConverterDDLTable table) {
		StringBuilder back = new StringBuilder(super.renderConstraintsForTable(uniqueNameConvertertable));
		for (DDLField field : table.getFields()) {
			if (field.isUnique()) {
				back.append(" CONSTRAINT ").append(uniqueNameConverter.getName(table.getName(), field.getName())).append(" UNIQUE(").append(processID(field.getName())).append("),\n");
			}
		}
		return back.toString();
	}
	protected String renderValue(Object value) {
		if (value instanceof Boolean) {
			if (value.equals(true)) {
				return "TRUE";
			}
			return "FALSE";
		}
		return super.renderValue(value);
	}
    @Override
    protected Iterable<SQLActionrenderAlterTableAddColumn(NameConverters nameConvertersDDLTable tableDDLField field)
    {
        final Iterable<SQLActionback = super.renderAlterTableAddColumn(nameConverterstablefield);
        if (field.isUnique())
        {
            return concat(back, ImmutableList.of(renderAddUniqueConstraint(nameConverters.getUniqueNameConverter(), tablefield)));
        }
        return back;
    }
    @Override
    protected Iterable<SQLActionrenderAlterTableChangeColumn(NameConverters nameConvertersDDLTable tableDDLField oldFieldDDLField field)
    {
        ImmutableList.Builder<SQLActionsql = ImmutableList.builder();
        // dropping foreign keys that affect the given column, as they HSQL doesn't like updating columns used in foreign keys!
        final Iterable<DDLForeignKeyforeignKeysForField = findForeignKeysForField(tableoldField);
        for (DDLForeignKey fk : foreignKeysForField)
        {
                sql.add(renderAlterTableDropKey(fk));
        }
        sql.addAll(super.renderAlterTableChangeColumn(nameConverterstableoldFieldfield));
        if (!field.isPrimaryKey())
        {
            final UniqueNameConverter uniqueNameConverter = nameConverters.getUniqueNameConverter();
            if (!oldField.isUnique() && field.isUnique())
            {
                sql.add(renderAddUniqueConstraint(uniqueNameConvertertablefield));
            }
            if (oldField.isUnique() && !field.isUnique())
            {
                sql.add(SQLAction.of(new StringBuilder().append("ALTER TABLE ")
                        .append(withSchema(table.getName()))
                        .append(" DROP CONSTRAINT ").append(uniqueNameConverter.getName(table.getName(), field.getName()))));
            }
            if (!field.isNotNull())
            {
                sql.add(SQLAction.of(new StringBuilder()
                        .append("ALTER TABLE ").append(withSchema(table.getName()))
                        .append(" ALTER COLUMN ").append(oldField.getName())
                        .append(" SET NULL")));
            }
            if (field.isNotNull())
            {
                sql.add(SQLAction.of(new StringBuilder()
                        .append("ALTER TABLE ").append(withSchema(table.getName()))
                        .append(" ALTER COLUMN ").append(oldField.getName())
                        .append(" SET NOT NULL")));
            }
            if (field.getDefaultValue() != null && !field.getDefaultValue().equals(oldField.getDefaultValue()))
            {
                sql.add(SQLAction.of(new StringBuilder()
                        .append("ALTER TABLE ").append(withSchema(table.getName()))
                        .append(" ALTER COLUMN ").append(oldField.getName())
                        .append(" SET DEFAULT ").append(renderValue(field.getDefaultValue()))));
            }
            if (field.getDefaultValue() == null && oldField.getDefaultValue() != null)
            {
                sql.add(SQLAction.of(new StringBuilder()
                        .append("ALTER TABLE ").append(withSchema(table.getName()))
                        .append(" ALTER COLUMN ").append(oldField.getName())
                        .append(" DROP DEFAULT")));
            }
        }
        // re-enabling the foreign keys!
        for (DDLForeignKey fk : foreignKeysForField)
        {
            sql.add(renderAlterTableAddKey(fk));
        }
        return sql.build();
    }
    private SQLAction renderAddUniqueConstraint(UniqueNameConverter uniqueNameConverterDDLTable tableDDLField field)
    {
        return SQLAction.of(new StringBuilder()
                .append("ALTER TABLE ").append(withSchema(table.getName()))
                .append(" ADD CONSTRAINT ").append(uniqueNameConverter.getName(table.getName(), field.getName()))
                .append(" UNIQUE (").append(processID(field.getName())).append(")"));
    }
    @Override
	protected SQLAction renderAlterTableChangeColumnStatement(NameConverters nameConvertersDDLTable tableDDLField oldFieldDDLField fieldRenderFieldOptions options)
	{
		StringBuilder current = new StringBuilder();
		current.append("ALTER TABLE ").append(withSchema(table.getName())).append(" ALTER COLUMN ");
		current.append(renderField(nameConverterstablefieldoptions));
		return SQLAction.of(current);
	}
    @Override
    {
        return new RenderFieldOptions(truefalsefalse);
    }
    @Override
	{
		StringBuilder back = new StringBuilder("ALTER TABLE ");
		back.append(withSchema(key.getDomesticTable())).append(" DROP CONSTRAINT ").append(processID(key.getFKName()));
		return SQLAction.of(back);
	}
    @Override
    protected SQLAction renderDropIndex(IndexNameConverter indexNameConverterDDLIndex index)
    {
        String indexName = getExistingIndexName(indexNameConverterindex);
        return SQLAction.of(new StringBuilder("DROP INDEX ")
                .append(withSchema(indexName))
                .append(" IF EXISTS"));
    }
    @Override
	protected Set<StringgetReservedWords() {
	}
	public boolean isCaseSensitive() {
		return false;
	}
    private static final Set<StringRESERVED_WORDS = ImmutableSet.of(
            "ADD""ALL""ALLOCATE""ALTER""AND""ANY""ARE""ARRAY",
            "AS""ASENSITIVE""ASYMMETRIC""AT""ATOMIC""AUTHORIZATION""BEGIN",
            "BIGINT""BINARY""BLOB""BOOLEAN""BY""CALL""CALLED""CASCADED",
            "CASE""CAST""CHAR""CHARACTER""CHECK""CLOB""CLOSE""COLLATE",
            "COLUMN""COMMIT""CONDIITON""CONNECT""CONSTRAINT""CONTINUE",
            "CORRESPONDING""CREATE""CROSS""CUBE""CURRENT""CURRENT_DATE",
            "CURRENT_DEFAULT_TRANSFORM_GROUP""CURRENT_PATH""CURRENT_ROLE",
            "CURRENT_TIME""CURRENT_TIMESTAMP""CURRENT_TRANSFORM_GROUP_FOR_TYPE",
            "CURRENT_USER""CURSOR""CYCLE""DATE""DAY""DEALLOCATE""DEC""DECIMAL",
            "DECLARE""DEFAULT""DELETE""DEREF""DESCRIBE""DETERMINISTIC",
            "DISCONNECT""DISTINCT""DO""DOUBLE""DAYOFWEEK""DROP""DYNAMIC""EACH",
            "ELEMENT""ELSE""ELSEIF""END""ESCAPE""EXCEPT""EXEC""EXECUTE",
            "EXISTS""EXIT""EXTERNAL""FALSE""FETCH""FILTER""FLOAT""FOR",
            "FOREIGN""FREE""FROM""FULL""FUNCTION""GET""GLOBAL""GRANT",
            "GROUP""GROUPING""HANDLER""HAVING""HEADER""HOLD""HOUR""IDENTITY",
            "IF""IMMEDIATE""IN""INDICATOR""INNER""INOUT""INPUT""INSENSITIVE",
            "INSERT""INT""INTEGER""INTERSECT""INTERVAL""INTO""IS""ITERATE",
            "JOIN""LANGUAGE""LARGE""LATERAL""LEADING""LEAVE""LEFT""LIKE",
            "LOCAL""LOCALTIME""LOCALTIMESTAMP""LOOP""MATCH""MEMBER""METHOD",
            "MINUTE""MODIFIES""MODULE""MONTH""MULTISET""NATIONAL""NAUTRAL",
            "NCHAR""NCLOB""NEW""NEXT""NO""NONE""NOT""NULL""NUMERIC""OF",
            "OLD""ON""ONLY""OPEN""OR""ORDER""OUT""OUTER""OUTPUT""OVER",
            "OVERLAPS""PARAMETER""PARTITION""PRECISION""PREPARE""PRIMARY",
            "PROCEDURE""RANGE""READS""REAL""RECURSIVE""REF""REFERENCES",
            "REFERENCING""RELEASE""REPEAT""RESIGNAL""RESULT""RETURN""RETURNS",
            "REVOKE""RIGHT""ROLLBACK""ROLLUP""ROW""ROWS""SAVEPOINT""SCOPE",
            "SCROLL""SECOND""SEARCH""SELECT""SENSITIVE""SESSION_USER""SET",
            "SIGNAL""SIMILAR""SMALLINT""SOME""SPECIFIC""SPECIFICTYPE""SQL",
            "SQLEXCEPTION""SQLSTATE""SQLWARNING""START""STATIC""SUBMULTISET",
            "SYMMETRIC""SYSTEM""SYSTEM_USER""TABLE""TABLESAMPLE""THEN""TIME",
            "TIMESTAMP""TIMEZONE_HOUR""TIMEZONE_MINUTE""TO""TRAILING""TRANSLATION",
            "TREAT""TRIGGER""TRUE""UNDO""UNION""UNIQUE""UNKNOWN""UNNEST",
            "UNTIL""UPDATE""USER""USING""VALUE""VALUES""VARCHAR""VARYING",
            "WHEN""WHENEVER""WHERE""WHILE""WINDOW""WITH""WITHIN""WITHOUT""YEAR",
            "MIN""MAX""POSITION");
New to GrepCode? Check out our FAQ X