Check to see if the system is managing the KAMStore schemas. The system manages Derby schemas
by default. Oracle is only DBA managed and MySQL can be either although the default is to
enable system managed

@param dbc
@return
777987
private boolean getSchemaManagementStatus(DBConnection dbc) {

        boolean createSchemas = false;
        if (dbc.isDerby()) {
            createSchemas = true;
        } else if (dbc.isMysql() || dbc.isPostgresql()) {
            createSchemas = getSystemConfiguration().getSystemManagedSchemas();
        }
        return createSchemas;
    }
943179
private void ensureSchemaVersion(Connection conn) throws DatabaseException {
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            //TODO convert this to use DatabaseProperties
            ps = conn.prepareStatement("SELECT value FROM properties WHERE id = 'version'");
            rs = ps.executeQuery();
            if (rs.next()) {
                final String dbSchemaVersion = settings.getString(Settings.KEYS.DB_VERSION);
                final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(dbSchemaVersion);
                if (appDbVersion == null) {
                    throw new DatabaseException("Invalid application database schema");
                }
                final DependencyVersion db = DependencyVersionUtil.parseVersion(rs.getString(1));
                if (db == null) {
                    throw new DatabaseException("Invalid database schema");
                }
                LOGGER.debug("DC Schema: {}", appDbVersion.toString());
                LOGGER.debug("DB Schema: {}", db.toString());
                if (appDbVersion.compareTo(db) > 0) {
                    updateSchema(conn, appDbVersion, db);
                    if (++callDepth < 10) {
                        ensureSchemaVersion(conn);
                    }
                }
            } else {
                throw new DatabaseException("Database schema is missing");
            }
        } catch (SQLException ex) {
            LOGGER.debug("", ex);
            throw new DatabaseException("Unable to check the database schema version", ex);
        } finally {
            DBUtils.closeResultSet(rs);
            DBUtils.closeStatement(ps);
        }
    }
518936
@Override
	public HsqlDatabaseDescriptor dbByName(final String dbName) {
		Collection<HsqlDatabaseDescriptor> select = CollectionUtils.select(dbs,
				new Predicate<HsqlDatabaseDescriptor>() {

					@Override
					public boolean evaluate(HsqlDatabaseDescriptor db) {
						return dbName.equals(db.getDbName());
					}

				});
		if (CollectionUtils.size(select) == 0) {
			throw new IllegalArgumentException(
					"There are no databases called '" + dbName + "'");
		}
		if (CollectionUtils.size(select) >= 2) {
			throw new IllegalArgumentException(
					"More than one database is called '" + dbName + "'");
		}
		return CollectionUtils.extractSingleton(select);
	}
315446
@Override
	public SqlEntityQuery<E> asc(final String... cols) {
		for (String col : cols) {
			this.sortOrders.add(new SortOrder(col, Order.ASCENDING));
		}
		return this;
	}
419873
public ISessionAffinityManager createSessionAffinityManager(SessionManagerConfig smc, SessionContext sctx, IStore istore) {
        return new SessionAffinityManager(smc, sctx, istore);
    }
484409
@Override
	public SqlEntityQuery<E> desc(final String col, final Nulls nulls) {
		this.sortOrders.add(new SortOrder(col, Order.DESCENDING, nulls));
		return this;
	}
573658
private EntityManager getEntityManager() {

        EntityManager em;

        if (TxUtils.isActive(transactionManager)) {

            em = (EntityManager) transactionSynchronizationRegistry.getResource(unitName);

            if (em == null) {

                em = createEntityManager();

                transactionSynchronizationRegistry.registerInterposedSynchronization(new TxSynchronization(em));
                transactionSynchronizationRegistry.putResource(unitName, em);
            } else {

                validateCompatibleSyncTypes(em);
            }
        } else {

            em = nonTxEmHolder.getEntityManager();

            if (em == null) {

                em = createEntityManager();

                nonTxEmHolder.setEntityManager(em);
            }
        }

        return em;
    }
823466
@Override
    public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
1249587
public boolean createTableIfNotExists(final String tableName, final String schema) {
        Connection conn = getConnection();

        try {
            return JdbcUtil.createTableIfNotExists(conn, tableName, schema);
        } finally {
            closeQuietly(conn);
        }
    }
146757
private static <S extends Storable> JDBCStorableInfo<S> examine
        (StorableInfo<S> mainInfo, Connection con,
         final String searchCatalog, final String searchSchema,
         SchemaResolver resolver, boolean primaryKeyCheckDisabled)
        throws SQLException, SupportException
    {
        final DatabaseMetaData meta = con.getMetaData();

        final String databaseProductName = meta.getDatabaseProductName();
        final String userName = meta.getUserName();

        String[] tableAliases;
        if (mainInfo.getAliasCount() > 0) {
            tableAliases = mainInfo.getAliases();
        } else {
            String name = mainInfo.getStorableType().getSimpleName();
            tableAliases = generateAliases(name);
        }

        // Try to find matching table from aliases.
        String catalog = null, schema = null, tableName = null, tableType = null;
        findName: {
            // The call to getTables may return several matching tables. This
            // map defines the "best" table type we'd like to use. The higher
            // the number the better.
            Map<String, Integer> fitnessMap = new HashMap<String, Integer>();
            fitnessMap.put("LOCAL TEMPORARY", 1);
            fitnessMap.put("GLOBAL TEMPORARY", 2);
            fitnessMap.put("VIEW", 3);
            fitnessMap.put("SYSTEM TABLE", 4);
            fitnessMap.put("TABLE", 5);
            fitnessMap.put("ALIAS", 6);
            fitnessMap.put("SYNONYM", 7);

            for (int i=0; i<tableAliases.length; i++) {
                ResultSet rs = meta.getTables(searchCatalog, searchSchema, tableAliases[i], null);
                try {
                    int bestFitness = 0;
                    while (rs.next()) {
                        String type = rs.getString("TABLE_TYPE");
                        Integer fitness = fitnessMap.get(type);
                        if (fitness != null) {
                            String rsSchema = rs.getString("TABLE_SCHEM");

                            if (searchSchema == null) {
                                if (userName != null && userName.equalsIgnoreCase(rsSchema)) {
                                    // Favor entities whose schema name matches
                                    // the user name.
                                    fitness += 7;
                                }
                            }

                            if (fitness > bestFitness) {
                                bestFitness = fitness;
                                catalog = rs.getString("TABLE_CAT");
                                schema = rsSchema;
                                tableName = rs.getString("TABLE_NAME");
                                tableType = type;
                            }
                        }
                    }
                } finally {
                    rs.close();
                }

                if (tableName != null) {
                    // Found a match, so stop checking aliases.
                    break;
                }
            }
        }

        if (tableName == null && !mainInfo.isIndependent()) {
            StringBuilder buf = new StringBuilder();
            buf.append("Unable to find matching table name for type \"");
            buf.append(mainInfo.getStorableType().getName());
            buf.append("\" by looking for ");
            appendToSentence(buf, tableAliases);
            buf.append(" with catalog " + searchCatalog + " and schema " + searchSchema);
            throw new MismatchException(buf.toString());
        }

        String qualifiedTableName = tableName;
        String resolvedTableName = tableName;

        // Oracle specific stuff...
        // TODO: Migrate this to OracleSupportStrategy.
        if (tableName != null && databaseProductName.toUpperCase().contains("ORACLE")) {
            if ("TABLE".equals(tableType) && searchSchema != null) {
                // Qualified table name references the schema. Used by SQL statements.
                qualifiedTableName = searchSchema + '.' + tableName;
            } else if ("SYNONYM".equals(tableType)) {
                // Try to get the real schema. This call is Oracle specific, however.
                String select = "SELECT TABLE_OWNER,TABLE_NAME " +
                    "FROM ALL_SYNONYMS " +
                    "WHERE OWNER=? AND SYNONYM_NAME=?";
                PreparedStatement ps = con.prepareStatement(select);
                ps.setString(1, schema); // in Oracle, schema is the owner
                ps.setString(2, tableName);
                try {
                    ResultSet rs = ps.executeQuery();
                    try {
                        if (rs.next()) {
                            schema = rs.getString("TABLE_OWNER");
                            resolvedTableName = rs.getString("TABLE_NAME");
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    ps.close();
                }
            }
        }

        // Gather information on all columns such that metadata only needs to
        // be retrieved once.
        Map<String, ColumnInfo> columnMap =
            new TreeMap<String, ColumnInfo>(String.CASE_INSENSITIVE_ORDER);

        if (resolvedTableName != null) {
            ResultSet rs = meta.getColumns(catalog, schema, resolvedTableName, null);
            rs.setFetchSize(1000);
            try {
                while (rs.next()) {
                    ColumnInfo info = new ColumnInfo(rs);
                    columnMap.put(info.columnName, info);
                }
            } finally {
                rs.close();
            }
        }

        // Make sure that all properties have a corresponding column.
        Map<String, ? extends StorableProperty<S>> mainProperties = mainInfo.getAllProperties();
        Map<String, String> columnToProperty = new HashMap<String, String>();
        Map<String, JDBCStorableProperty<S>> jProperties =
            new LinkedHashMap<String, JDBCStorableProperty<S>>(mainProperties.size());

        ArrayList<String> errorMessages = new ArrayList<String>();

        for (StorableProperty<S> mainProperty : mainProperties.values()) {
            if (mainProperty.isDerived() || mainProperty.isJoin() || tableName == null) {
                jProperties.put(mainProperty.getName(),
                                new JProperty<S>(mainProperty, primaryKeyCheckDisabled));
                continue;
            }

            String[] columnAliases;
            if (mainProperty.getAliasCount() > 0) {
                columnAliases = mainProperty.getAliases();
            } else {
                columnAliases = generateAliases(mainProperty.getName());
            }

            JDBCStorableProperty<S> jProperty = null;
            boolean addedError = false;

            findName: for (int i=0; i<columnAliases.length; i++) {
                ColumnInfo columnInfo = columnMap.get(columnAliases[i]);
                if (columnInfo != null) {
                    AccessInfo accessInfo = getAccessInfo
                        (mainProperty,
                         columnInfo.dataType, columnInfo.dataTypeName,
                         columnInfo.columnSize, columnInfo.decimalDigits);

                    if (accessInfo == null) {
                        TypeDesc propertyType = TypeDesc.forClass(mainProperty.getType());
                        String message =
                            "Property \"" + mainProperty.getName() +
                            "\" has type \"" + propertyType.getFullName() +
                            "\" which is incompatible with database type \"" +
                            columnInfo.dataTypeName + '"';

                        if (columnInfo.decimalDigits > 0) {
                            message += " (decimal digits = " + columnInfo.decimalDigits + ')';
                        }

                        errorMessages.add(message);
                        addedError = true;
                        break findName;
                    }

                    if (columnInfo.nullable) {
                        if (!mainProperty.isNullable() && !mainProperty.isIndependent()) {
                            errorMessages.add
                                ("Property \"" + mainProperty.getName() +
                                 "\" must have a Nullable annotation");
                        }
                    } else {
                        if (mainProperty.isNullable() && !mainProperty.isIndependent()) {
                            errorMessages.add
                                ("Property \"" + mainProperty.getName() +
                                 "\" must not have a Nullable annotation");
                        }
                    }

                    boolean autoIncrement = mainProperty.isAutomatic();
                    if (autoIncrement) {
                        // Need to execute a little query to check if column is
                        // auto-increment or not. This information is not available in
                        // the regular database metadata prior to jdk1.6.

                        PreparedStatement ps = con.prepareStatement
                            ("SELECT " + columnInfo.columnName +
                             " FROM " + tableName +
                             " WHERE 1=0");

                        try {
                            ResultSet rs = ps.executeQuery();
                            try {
                                autoIncrement = rs.getMetaData().isAutoIncrement(1);
                            } finally {
                                rs.close();
                            }
                        } finally {
                            ps.close();
                        }
                    }

                    jProperty = new JProperty<S>(mainProperty, columnInfo,
                                                 autoIncrement, primaryKeyCheckDisabled,
                                                 accessInfo.mResultSetGet,
                                                 accessInfo.mPreparedStatementSet,
                                                 accessInfo.getAdapter());

                    break findName;
                }
            }

            if (jProperty != null) {
                jProperties.put(mainProperty.getName(), jProperty);
                columnToProperty.put(jProperty.getColumnName(), jProperty.getName());
            } else {
                if (mainProperty.isIndependent()) {
                    jProperties.put(mainProperty.getName(),
                                    new JProperty<S>(mainProperty, primaryKeyCheckDisabled));
                } else if (!addedError) {
                    StringBuilder buf = new StringBuilder();
                    buf.append("Unable to find matching database column for property \"");
                    buf.append(mainProperty.getName());
                    buf.append("\" by looking for ");
                    appendToSentence(buf, columnAliases);
                    errorMessages.add(buf.toString());
                }
            }
        }

        if (errorMessages.size() > 0) {
            throw new MismatchException(mainInfo.getStorableType(), errorMessages);
        }

        // Now verify that primary or alternate keys match.

        if (resolvedTableName != null) checkPrimaryKey: {
            ResultSet rs;
            try {
                rs = meta.getPrimaryKeys(catalog, schema, resolvedTableName);
            } catch (SQLException e) {
                getLog().info
                    ("Unable to get primary keys for table \"" + resolvedTableName +
                     "\" with catalog " + catalog + " and schema " + schema + ": " + e);
                break checkPrimaryKey;
            }

            List<String> pkProps = new ArrayList<String>();

            try {
                while (rs.next()) {
                    String columnName = rs.getString("COLUMN_NAME");
                    String propertyName = columnToProperty.get(columnName);

                    if (propertyName == null) {
                        errorMessages.add
                            ("Column \"" + columnName +
                             "\" must be part of primary or alternate key");
                        continue;
                    }

                    pkProps.add(propertyName);
                }
            } finally {
                rs.close();
            }

            if (errorMessages.size() > 0) {
                // Skip any extra checks.
                break checkPrimaryKey;
            }

            if (pkProps.size() == 0) {
                // If no primary keys are reported, don't even bother checking.
                // There's no consistent way to get primary keys, and entities
                // like views and synonyms don't usually report primary keys.
                // A primary key might even be logically defined as a unique
                // constraint.
                break checkPrimaryKey;
            }

            if (matchesKey(pkProps, mainInfo.getPrimaryKey())) {
                // Good. Primary key in database is same as in Storable.
                break checkPrimaryKey;
            }

            // Check if Storable has an alternate key which matches the
            // database's primary key.
            boolean foundAnyAltKey = false;
            for (StorableKey<S> altKey : mainInfo.getAlternateKeys()) {
                if (matchesKey(pkProps, altKey)) {
                    // Okay. Primary key in database matches a Storable
                    // alternate key.
                    foundAnyAltKey = true;

                    // Also check that declared primary key is a strict subset
                    // of the alternate key. If not, keep checking alt keys.

                    if (matchesSubKey(pkProps, mainInfo.getPrimaryKey())) {
                        break checkPrimaryKey;
                    }
                }
            }

            if (foundAnyAltKey) {
                errorMessages.add("Actual primary key matches a declared alternate key, " +
                                  "but declared primary key must be a strict subset. " +
                                  mainInfo.getPrimaryKey().getProperties() +
                                  " is not a subset of " + pkProps);
            } else {
                errorMessages.add("Actual primary key does not match any " +
                                  "declared primary or alternate key: " + pkProps);
            }
        }

        if (errorMessages.size() > 0) {
            if (primaryKeyCheckDisabled) {
                for (String errorMessage:errorMessages) {
                    getLog().warn("Suppressed error: " + errorMessage);
                }
                errorMessages.clear();
            } else {
                throw new MismatchException(mainInfo.getStorableType(), errorMessages);
            }
        }

        // IndexInfo is empty, as querying for it tends to cause a table analyze to run.
        IndexInfo[] indexInfo = new IndexInfo[0];

        if (needsQuotes(tableName)) {
            String quote = meta.getIdentifierQuoteString();
            if (quote != null && !quote.equals(" ")) {
                tableName = quote + tableName + quote;
                qualifiedTableName = quote + qualifiedTableName + quote;
            }
        }

        return new JInfo<S>
            (mainInfo, catalog, schema, tableName, qualifiedTableName, indexInfo, jProperties);
    }
737987
public boolean hasPrevious() throws DBException
    {
        if (m_iCurrentRecord >= m_iRecordsAccessed)
            return true;
        Object record = this.previous();
        if (record == null)
            return false;
        else
        {
            m_iRecordsAccessed--;   // Offically this record has not been accessed
            return true;
        }
    }
132871
@Override
    public SchemaManager getSchemaManager(Map<String, Object> puProperties)
    {
        if (schemaManager == null)
        {
            initializePropertyReader();
            setExternalProperties(puProperties);
            schemaManager = new RethinkDBSchemaManager(RethinkDBClientFactory.class.getName(), puProperties,
                    kunderaMetadata);
        }
        return schemaManager;
    }
1078986
private static SchemaStoreItemStream getSchemaStore(MessageStore msgStore) throws MessageStoreException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getSchemaStore");

    // Check the local cache first.
    SchemaStoreItemStream store = schemaStores.get(msgStore);

    // Not in the local cache, so try to find it in the MessageStore
    if (store == null) {
      Filter filter = new Filter() {
        public boolean filterMatches(AbstractItem item) {
          return (item instanceof SchemaStoreItemStream);
        }
      };
      store = (SchemaStoreItemStream)msgStore.findFirstMatching(filter);
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() && store != null) SibTr.debug(tc, "Schema store found in message store");

      // Not in the MessageStore, so try to create a new one
      if (store == null) {
        store = new SchemaStoreItemStream();
        msgStore.add(store, msgStore.getTransactionFactory().createAutoCommitTransaction());
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "New schema store created");
      }

      schemaStores.put(msgStore, store);

    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getSchemaStore");
    return store;
  }
1337249
private DBHandling createDBHandling() throws BuildException
    {
        if ((_handling == null) || (_handling.length() == 0))
        {
            throw new BuildException("No handling specified");
        }
        try
        {
            String className     = "org.apache.ojb.broker.platforms."+
            					   Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+
            					   "DBHandling";
            Class  handlingClass = ClassHelper.getClass(className);

            return (DBHandling)handlingClass.newInstance();
        }
        catch (Exception ex)
        {
            throw new BuildException("Invalid handling '"+_handling+"' specified");
        }
    }
1060762
public void dbSchemaCheckVersion() {
        try {
            String dbVersion = getDbVersion();
            if (!ProcessEngine.VERSION.equals(dbVersion)) {
                throw new ActivitiWrongDbException(ProcessEngine.VERSION,
                                                   dbVersion);
            }

            String errorMessage = null;
            if (!isEngineTablePresent()) {
                errorMessage = addMissingComponent(errorMessage,
                                                   "engine");
            }
            if (dbSqlSessionFactory.isDbHistoryUsed() && !isHistoryTablePresent()) {
                errorMessage = addMissingComponent(errorMessage,
                                                   "history");
            }

            if (errorMessage != null) {
                throw new ActivitiException("Activiti database problem: " + errorMessage);
            }
        } catch (Exception e) {
            if (isMissingTablesException(e)) {
                throw new ActivitiException(
                        "no activiti tables in db. set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in activiti.cfg.xml for automatic schema creation",
                        e);
            } else {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                } else {
                    throw new ActivitiException("couldn't get db schema version",
                                                e);
                }
            }
        }

        log.debug("activiti db schema check successful");
    }
647189
private boolean hasOperationOfType(SQLiteDatabaseSchema schema, MethodSpec.Builder methodBuilder, JQLType jqlType) {
		boolean hasOperation = false;
		for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {

			if (daoDefinition.getElement().getAnnotation(BindContentProviderPath.class) == null)
				continue;

			for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
				if (daoMethod.jql.operationType != jqlType) {
					continue;
				}
				if (!daoMethod.hasAnnotation(BindContentProviderEntry.class)) {
					continue;
				}

				hasOperation = true;
				// methodBuilder.addJavadoc("method $L.$L\n",
				// daoDefinition.getName(), daoMethod.getName());
			}
		}
		return hasOperation;
	}
1086961
public static boolean geometryColumnsExists(final Database database) {
      String geometryColumnsName = database.correctObjectName(
            "geometry_columns", Table.class);
      DatabaseObject example = null;
      if (database instanceof DerbyDatabase || database instanceof H2Database) {
         final Table tableExample = new Table();
         tableExample.setName(geometryColumnsName);
         tableExample.setSchema(database.getDefaultCatalogName(),
               database.getDefaultSchemaName());
         example = tableExample;
      } else if (database instanceof PostgresDatabase) {
         final View viewExample = new View();
         viewExample.setName(geometryColumnsName);
         viewExample.setSchema(database.getDefaultCatalogName(), "public");
         example = viewExample;
      }
      try {
         return example != null
               && SnapshotGeneratorFactory.getInstance().has(example, database);
      } catch (final LiquibaseException e) {
         throw new UnexpectedLiquibaseException(
               "Failed to determine if the geometry_columns table or view exists",
               e);
      }
   }