Search in sources :

Example 1 with HsqlProperties

use of org.hsqldb_voltpatches.persist.HsqlProperties in project voltdb by VoltDB.

the class DatabaseInformationMain method SYSTEM_PRIMARYKEYS.

/**
     * Retrieves a <code>Table</code> object describing the visible
     * primary key columns of each accessible table defined within
     * this database. <p>
     *
     * Each row is a PRIMARY KEY column description with the following
     * columns: <p>
     *
     * <pre class="SqlCodeExample">
     * TABLE_CAT   VARCHAR   table catalog
     * TABLE_SCHEM VARCHAR   table schema
     * TABLE_NAME  VARCHAR   table name
     * COLUMN_NAME VARCHAR   column name
     * KEY_SEQ     SMALLINT  sequence number within primary key
     * PK_NAME     VARCHAR   primary key constraint name
     * </pre> <p>
     *
     * @return a <code>Table</code> object describing the visible
     *        primary key columns of each accessible table
     *        defined within this database.
     */
final Table SYSTEM_PRIMARYKEYS() {
    Table t = sysTables[SYSTEM_PRIMARYKEYS];
    if (t == null) {
        t = createBlankTable(sysTableHsqlNames[SYSTEM_PRIMARYKEYS]);
        addColumn(t, "TABLE_CAT", SQL_IDENTIFIER);
        addColumn(t, "TABLE_SCHEM", SQL_IDENTIFIER);
        // not null
        addColumn(t, "TABLE_NAME", SQL_IDENTIFIER);
        // not null
        addColumn(t, "COLUMN_NAME", SQL_IDENTIFIER);
        // not null
        addColumn(t, "KEY_SEQ", Type.SQL_SMALLINT);
        addColumn(t, "PK_NAME", SQL_IDENTIFIER);
        // order: COLUMN_NAME
        // added for unique: TABLE_NAME, TABLE_SCHEM, TABLE_CAT
        // false PK, as  TABLE_SCHEM and/or TABLE_CAT may be null
        HsqlName name = HsqlNameManager.newInfoSchemaObjectName(sysTableHsqlNames[SYSTEM_PRIMARYKEYS].name, false, SchemaObject.INDEX);
        t.createPrimaryKey(name, new int[] { 3, 2, 1, 0 }, false);
        return t;
    }
    PersistentStore store = database.persistentStoreCollection.getStore(t);
    // calculated column values
    String tableCatalog;
    String tableSchema;
    String tableName;
    //String  columnName;
    //Integer keySequence;
    String primaryKeyName;
    // Intermediate holders
    Iterator tables;
    Table table;
    Object[] row;
    Constraint constraint;
    int[] cols;
    int colCount;
    HsqlProperties p;
    // column number mappings
    final int itable_cat = 0;
    final int itable_schem = 1;
    final int itable_name = 2;
    final int icolumn_name = 3;
    final int ikey_seq = 4;
    final int ipk_name = 5;
    // Initialization
    p = database.getProperties();
    tables = p.isPropertyTrue("hsqldb.system_table_primarykeys") ? allTables() : database.schemaManager.databaseObjectIterator(SchemaObject.TABLE);
    while (tables.hasNext()) {
        table = (Table) tables.next();
        if (table.isView() || !isAccessibleTable(table) || !table.hasPrimaryKey()) {
            continue;
        }
        constraint = table.getPrimaryConstraint();
        tableCatalog = table.getCatalogName().name;
        tableSchema = table.getSchemaName().name;
        tableName = table.getName().name;
        primaryKeyName = constraint.getName().name;
        cols = constraint.getMainColumns();
        colCount = cols.length;
        for (int j = 0; j < colCount; j++) {
            row = t.getEmptyRowData();
            row[itable_cat] = tableCatalog;
            row[itable_schem] = tableSchema;
            row[itable_name] = tableName;
            row[icolumn_name] = table.getColumn(cols[j]).getName().name;
            row[ikey_seq] = ValuePool.getInt(j + 1);
            row[ipk_name] = primaryKeyName;
            t.insertSys(store, row);
        }
    }
    return t;
}
Also used : Table(org.hsqldb_voltpatches.Table) Constraint(org.hsqldb_voltpatches.Constraint) Iterator(org.hsqldb_voltpatches.lib.Iterator) WrapperIterator(org.hsqldb_voltpatches.lib.WrapperIterator) HsqlProperties(org.hsqldb_voltpatches.persist.HsqlProperties) PersistentStore(org.hsqldb_voltpatches.persist.PersistentStore) HsqlName(org.hsqldb_voltpatches.HsqlNameManager.HsqlName) SchemaObject(org.hsqldb_voltpatches.SchemaObject) Constraint(org.hsqldb_voltpatches.Constraint)

Example 2 with HsqlProperties

use of org.hsqldb_voltpatches.persist.HsqlProperties in project voltdb by VoltDB.

the class DatabaseInformationMain method SYSTEM_INDEXINFO.

/**
     * Retrieves a <code>Table</code> object describing the visible
     * <code>Index</code> objects for each accessible table defined
     * within this database.<p>
     *
     * Each row is an index column description with the following
     * columns: <p>
     *
     * <pre class="SqlCodeExample">
     * TABLE_CAT        VARCHAR   table's catalog
     * TABLE_SCHEM      VARCHAR   simple name of table's schema
     * TABLE_NAME       VARCHAR   simple name of the table using the index
     * NON_UNIQUE       BOOLEAN   can index values be non-unique?
     * INDEX_QUALIFIER  VARCHAR   catalog in which the index is defined
     * INDEX_NAME       VARCHAR   simple name of the index
     * TYPE             SMALLINT  index type: { Clustered | Hashed | Other }
     * ORDINAL_POSITION SMALLINT  column sequence number within index
     * COLUMN_NAME      VARCHAR   simple column name
     * ASC_OR_DESC      VARCHAR   col. sort sequence: {"A" (Asc) | "D" (Desc)}
     * CARDINALITY      INTEGER   # of unique values in index (not implemented)
     * PAGES            INTEGER   index page use (not implemented)
     * FILTER_CONDITION VARCHAR   filter condition, if any (not implemented)
     * // HSQLDB-extension
     * ROW_CARDINALITY  INTEGER   total # of rows in index (not implemented)
     * </pre> <p>
     *
     * @return a <code>Table</code> object describing the visible
     *        <code>Index</code> objects for each accessible
     *        table defined within this database.
     */
final Table SYSTEM_INDEXINFO() {
    Table t = sysTables[SYSTEM_INDEXINFO];
    if (t == null) {
        t = createBlankTable(sysTableHsqlNames[SYSTEM_INDEXINFO]);
        // JDBC
        addColumn(t, "TABLE_CAT", SQL_IDENTIFIER);
        addColumn(t, "TABLE_SCHEM", SQL_IDENTIFIER);
        // NOT NULL
        addColumn(t, "TABLE_NAME", SQL_IDENTIFIER);
        // NOT NULL
        addColumn(t, "NON_UNIQUE", Type.SQL_BOOLEAN);
        addColumn(t, "INDEX_QUALIFIER", SQL_IDENTIFIER);
        addColumn(t, "INDEX_NAME", SQL_IDENTIFIER);
        // NOT NULL
        addColumn(t, "TYPE", Type.SQL_SMALLINT);
        // NOT NULL
        addColumn(t, "ORDINAL_POSITION", Type.SQL_SMALLINT);
        addColumn(t, "COLUMN_NAME", SQL_IDENTIFIER);
        addColumn(t, "ASC_OR_DESC", CHARACTER_DATA);
        addColumn(t, "CARDINALITY", Type.SQL_INTEGER);
        addColumn(t, "PAGES", Type.SQL_INTEGER);
        addColumn(t, "FILTER_CONDITION", CHARACTER_DATA);
        // HSQLDB extension
        addColumn(t, "ROW_CARDINALITY", Type.SQL_INTEGER);
        // order: NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION.
        // added for unique: INDEX_QUALIFIER, TABLE_NAME
        // false PK, as INDEX_QUALIFIER may be null
        HsqlName name = HsqlNameManager.newInfoSchemaObjectName(sysTableHsqlNames[SYSTEM_INDEXINFO].name, false, SchemaObject.INDEX);
        t.createPrimaryKey(name, new int[] { 3, 6, 5, 7, 4, 2, 1 }, false);
        return t;
    }
    PersistentStore store = database.persistentStoreCollection.getStore(t);
    // calculated column values
    String tableCatalog;
    String tableSchema;
    String tableName;
    Boolean nonUnique;
    String indexQualifier;
    String indexName;
    Integer indexType;
    //Integer ordinalPosition;
    //String  columnName;
    //String  ascOrDesc;
    Integer cardinality;
    Integer pages;
    String filterCondition;
    Integer rowCardinality;
    // Intermediate holders
    Iterator tables;
    Table table;
    int indexCount;
    int[] cols;
    int col;
    int colCount;
    Object[] row;
    DITableInfo ti;
    HsqlProperties p;
    // column number mappings
    final int itable_cat = 0;
    final int itable_schem = 1;
    final int itable_name = 2;
    final int inon_unique = 3;
    final int iindex_qualifier = 4;
    final int iindex_name = 5;
    final int itype = 6;
    final int iordinal_position = 7;
    final int icolumn_name = 8;
    final int iasc_or_desc = 9;
    final int icardinality = 10;
    final int ipages = 11;
    final int ifilter_condition = 12;
    final int irow_cardinality = 13;
    // Initialization
    ti = new DITableInfo();
    p = database.getProperties();
    tables = p.isPropertyTrue("hsqldb.system_table_indexinfo") ? allTables() : database.schemaManager.databaseObjectIterator(SchemaObject.TABLE);
    // Do it.
    while (tables.hasNext()) {
        table = (Table) tables.next();
        if (table.isView() || !isAccessibleTable(table)) {
            continue;
        }
        ti.setTable(table);
        tableCatalog = table.getCatalogName().name;
        tableSchema = table.getSchemaName().name;
        tableName = ti.getName();
        // not supported yet
        filterCondition = null;
        // different cat for index not supported yet
        indexQualifier = tableCatalog;
        indexCount = table.getIndexCount();
        // process all of the visible indices for this table
        for (int i = 0; i < indexCount; i++) {
            colCount = ti.getIndexVisibleColumns(i);
            if (colCount < 1) {
                continue;
            }
            indexName = ti.getIndexName(i);
            nonUnique = ti.isIndexNonUnique(i);
            cardinality = ti.getIndexCardinality(i);
            pages = ValuePool.INTEGER_0;
            rowCardinality = ti.getIndexRowCardinality(i);
            cols = ti.getIndexColumns(i);
            indexType = ti.getIndexType(i);
            for (int k = 0; k < colCount; k++) {
                col = cols[k];
                row = t.getEmptyRowData();
                row[itable_cat] = tableCatalog;
                row[itable_schem] = tableSchema;
                row[itable_name] = tableName;
                row[inon_unique] = nonUnique;
                row[iindex_qualifier] = indexQualifier;
                row[iindex_name] = indexName;
                row[itype] = indexType;
                row[iordinal_position] = ValuePool.getInt(k + 1);
                row[icolumn_name] = ti.getColName(col);
                row[iasc_or_desc] = ti.getIndexColDirection(i, col);
                row[icardinality] = cardinality;
                row[ipages] = pages;
                row[irow_cardinality] = rowCardinality;
                row[ifilter_condition] = filterCondition;
                t.insertSys(store, row);
            }
        }
    }
    return t;
}
Also used : Table(org.hsqldb_voltpatches.Table) PersistentStore(org.hsqldb_voltpatches.persist.PersistentStore) Constraint(org.hsqldb_voltpatches.Constraint) Iterator(org.hsqldb_voltpatches.lib.Iterator) WrapperIterator(org.hsqldb_voltpatches.lib.WrapperIterator) HsqlProperties(org.hsqldb_voltpatches.persist.HsqlProperties) HsqlName(org.hsqldb_voltpatches.HsqlNameManager.HsqlName) SchemaObject(org.hsqldb_voltpatches.SchemaObject)

Example 3 with HsqlProperties

use of org.hsqldb_voltpatches.persist.HsqlProperties in project voltdb by VoltDB.

the class JDBCDriver method getConnection.

/**
     * The static equivalent of the <code>connect(String,Properties)</code>
     * method. <p>
     *
     * @param url the URL of the database to which to connect
     * @param info a list of arbitrary string tag/value pairs as connection
     *      arguments including at least at a "user" and a "password" property
     * @throws java.sql.SQLException if a database access error occurs
     * @return a <code>Connection</code> object that represents a
     *      connection to the URL
     */
//#ifdef JAVA6
@SuppressWarnings("deprecation")
public static //#endif JAVA6
Connection getConnection(String url, Properties info) throws SQLException {
    final HsqlProperties props = DatabaseURL.parseURL(url, true, false);
    if (props == null) {
        // supposed to be an HSQLDB driver url but has errors
        throw Util.invalidArgument();
    } else if (props.isEmpty()) {
        // is not an HSQLDB driver url
        return null;
    }
    props.addProperties(info);
    long timeout = DriverManager.getLoginTimeout();
    if (timeout == 0) {
        // no timeout restriction
        return new JDBCConnection(props);
    }
    String connType = props.getProperty("connection_type");
    if (DatabaseURL.isInProcessDatabaseType(connType)) {
        return new JDBCConnection(props);
    }
    /** @todo:  Better: ThreadPool? HsqlTimer with callback? */
    final JDBCConnection[] conn = new JDBCConnection[1];
    final SQLException[] ex = new SQLException[1];
    Thread t = new Thread() {

        public void run() {
            try {
                conn[0] = new JDBCConnection(props);
            } catch (SQLException se) {
                ex[0] = se;
            }
        }
    };
    t.start();
    final long start = System.currentTimeMillis();
    try {
        t.join(1000 * timeout);
    } catch (InterruptedException ie) {
    }
    try {
        // PRE:
        // deprecated, but should be ok, since neither
        // the HSQLClientConnection or the HTTPClientConnection
        // constructor will ever hold monitors on objects in
        // an inconsistent state, such that damaged objects
        // become visible to other threads with the
        // potential of arbitrary behavior.
        t.stop();
    } catch (Exception e) {
    }
    if (ex[0] != null) {
        throw ex[0];
    }
    if (conn[0] != null) {
        return conn[0];
    }
    throw Util.sqlException(ErrorCode.X_08501);
}
Also used : SQLException(java.sql.SQLException) HsqlProperties(org.hsqldb_voltpatches.persist.HsqlProperties) SQLException(java.sql.SQLException)

Example 4 with HsqlProperties

use of org.hsqldb_voltpatches.persist.HsqlProperties in project voltdb by VoltDB.

the class DatabaseURL method parseURL.

/**
     * Parses the url into components that are returned in a properties object.
     *
     * <p> The following components are isolated:
     *
     * <p>
     * <ul> url: the original url
     *
     * <p> connection_type: a static string that indicate the protocol. If the
     * url does not begin with a valid protocol, null is returned by this method
     * instead of the properties object.
     *
     * <p> host: name of host in networked modes in lowercase
     *
     * <p> port: port number in networked mode, or 0 if not present
     *
     * <p> path: path of the resource on server in networked modes, minimum
     * (slash) with path elements appended apart from servlet path which is
     * (slash) plus the name of the servlet
     *
     * <p> database: database name. For memory, resource and networked modes,
     * this is returned in lowercase, for file databases the original case of
     * characters is preserved. Returns empty string if name is not present in
     * the url.
     *
     * <p> for each protocol if port number is not in the url
     *
     * <p> Additional connection properties specified as key/value pairs.
     * </ul>
     *
     * @return null returned if the part that should represent the port is not
     *   an integer or the part for database name is empty. Empty
     *   HsqlProperties returned if if url does not begin with valid protocol
     *   and could refer to another JDBC driver.
     * @param url String
     * @param hasPrefix indicates URL prefix is present
     * @param noPath indicates empty path and verbatim use of path elements as
     * database
     */
public static HsqlProperties parseURL(String url, boolean hasPrefix, boolean noPath) {
    String urlImage = url.toLowerCase(Locale.ENGLISH);
    HsqlProperties props = new HsqlProperties();
    HsqlProperties extraProps = null;
    String arguments = null;
    int pos = 0;
    if (hasPrefix) {
        if (urlImage.startsWith(S_URL_PREFIX)) {
            pos = S_URL_PREFIX.length();
        } else {
            return props;
        }
    }
    String type = null;
    int port = 0;
    String database;
    String path;
    boolean isNetwork = false;
    props.setProperty("url", url);
    int postUrlPos = url.length();
    // postUrlPos is the END position in url String,
    // wrt what remains to be processed.
    // I.e., if postUrlPos is 100, url no longer needs to examined at
    // index 100 or later.
    int semiPos = url.indexOf(';', pos);
    if (semiPos > -1) {
        arguments = urlImage.substring(semiPos + 1, urlImage.length());
        postUrlPos = semiPos;
        extraProps = HsqlProperties.delimitedArgPairsToProps(arguments, "=", ";", null);
        /** @todo 1.9.0 - check if properties have valid names / values */
        props.addProperties(extraProps);
    }
    if (postUrlPos == pos + 1 && urlImage.startsWith(S_DOT, pos)) {
        type = S_DOT;
    } else if (urlImage.startsWith(S_MEM, pos)) {
        type = S_MEM;
    } else if (urlImage.startsWith(S_FILE, pos)) {
        type = S_FILE;
    } else if (urlImage.startsWith(S_RES, pos)) {
        type = S_RES;
    } else if (urlImage.startsWith(S_ALIAS, pos)) {
        type = S_ALIAS;
    } else if (urlImage.startsWith(S_HSQL, pos)) {
        type = S_HSQL;
        port = ServerConstants.SC_DEFAULT_HSQL_SERVER_PORT;
        isNetwork = true;
    } else if (urlImage.startsWith(S_HSQLS, pos)) {
        type = S_HSQLS;
        port = ServerConstants.SC_DEFAULT_HSQLS_SERVER_PORT;
        isNetwork = true;
    } else if (urlImage.startsWith(S_HTTP, pos)) {
        type = S_HTTP;
        port = ServerConstants.SC_DEFAULT_HTTP_SERVER_PORT;
        isNetwork = true;
    } else if (urlImage.startsWith(S_HTTPS, pos)) {
        type = S_HTTPS;
        port = ServerConstants.SC_DEFAULT_HTTPS_SERVER_PORT;
        isNetwork = true;
    }
    if (type == null) {
        type = S_FILE;
    } else if (type == S_DOT) {
        type = S_MEM;
    // keep pos
    } else {
        pos += type.length();
    }
    props.setProperty("connection_type", type);
    if (isNetwork) {
        // First capture 3 segments:  host + port + path
        String pathSeg = null;
        String hostSeg = null;
        String portSeg = null;
        int slashPos = url.indexOf('/', pos);
        if (slashPos > 0 && slashPos < postUrlPos) {
            pathSeg = url.substring(slashPos, postUrlPos);
            // N.b. pathSeg necessarily begins with /.
            postUrlPos = slashPos;
        }
        // Assertion
        if (postUrlPos <= pos) {
            return null;
        }
        // Processing different for ipv6 host address and all others:
        if (url.charAt(pos) == '[') {
            // ipv6
            int endIpv6 = url.indexOf(']', pos + 2);
            // Notice 2 instead of 1 to require non-empty addr segment
            if (endIpv6 < 0 || endIpv6 >= postUrlPos) {
                return null;
            // Wish could throw something with a useful message for user
            // here.
            }
            hostSeg = urlImage.substring(pos + 1, endIpv6);
            if (postUrlPos > endIpv6 + 1) {
                portSeg = url.substring(endIpv6 + 1, postUrlPos);
            }
        } else {
            // non-ipv6
            int colPos = url.indexOf(':', pos + 1);
            // Notice + 1 to require non-empty addr segment
            hostSeg = urlImage.substring(pos, (colPos > 0) ? colPos : postUrlPos);
            if (colPos > -1 && postUrlPos > colPos + 1) {
                // portSeg will be non-empty, but could contain just ":"
                portSeg = url.substring(colPos, postUrlPos);
            }
        }
        // hostSeg + portSeg + pathSeg.
        if (portSeg != null) {
            if (portSeg.length() < 2 || portSeg.charAt(0) != ':') {
                // here.
                return null;
            }
            try {
                port = Integer.parseInt(portSeg.substring(1));
            } catch (NumberFormatException e) {
                // System.err.println("NFE for (" + portSeg + ')'); debug
                return null;
            }
        }
        if (noPath) {
            path = "";
            database = pathSeg;
        } else if (pathSeg == null) {
            path = "/";
            database = "";
        } else {
            int lastSlashPos = pathSeg.lastIndexOf('/');
            if (lastSlashPos < 1) {
                path = "/";
                database = pathSeg.substring(1).toLowerCase(Locale.ENGLISH);
            } else {
                path = pathSeg.substring(0, lastSlashPos);
                database = pathSeg.substring(lastSlashPos + 1);
            }
        }
        /* Just for debug.  Remove once stable:
            System.err.println("Host seg (" + hostSeg + "), Port val (" + port
                    + "), Path val (" + pathSeg + "), path (" + path
                    + "), db (" + database + ')');
             */
        props.setProperty("port", port);
        props.setProperty("host", hostSeg);
        props.setProperty("path", path);
        if (!noPath && extraProps != null) {
            String filePath = extraProps.getProperty("filepath");
            if (filePath != null && database.length() != 0) {
                database += ";" + filePath;
            }
        }
    } else {
        if (type == S_MEM || type == S_RES) {
            database = urlImage.substring(pos, postUrlPos).toLowerCase();
            if (type == S_RES) {
                if (database.indexOf('/') != 0) {
                    database = '/' + database;
                }
            }
        } else {
            database = url.substring(pos, postUrlPos);
        }
        if (database.length() == 0) {
            return null;
        }
    }
    props.setProperty("database", database);
    return props;
}
Also used : HsqlProperties(org.hsqldb_voltpatches.persist.HsqlProperties)

Example 5 with HsqlProperties

use of org.hsqldb_voltpatches.persist.HsqlProperties in project voltdb by VoltDB.

the class HSQLInterface method loadHsqldb.

/**
     * Load up an HSQLDB in-memory instance.
     *
     * @return A newly initialized in-memory HSQLDB instance accessible
     * through the returned instance of HSQLInterface
     */
public static HSQLInterface loadHsqldb() {
    // Specifically set the timezone to UTC to avoid the default usage local timezone in HSQL.
    // This ensures that all VoltDB data paths use the same timezone for representing time.
    TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
    String name = "hsqldbinstance-" + String.valueOf(instanceId) + "-" + String.valueOf(System.currentTimeMillis());
    instanceId++;
    HsqlProperties props = new HsqlProperties();
    try {
        Session sessionProxy = DatabaseManager.newSession(DatabaseURL.S_MEM, name, "SA", "", props, 0);
        // make HSQL case insensitive
        sessionProxy.executeDirectStatement("SET IGNORECASE TRUE;");
        return new HSQLInterface(sessionProxy);
    } catch (HsqlException caught) {
        m_logger.warn("Unexpected error initializing the SQL parser", caught);
        caught.printStackTrace();
        throw caught;
    }
}
Also used : HsqlProperties(org.hsqldb_voltpatches.persist.HsqlProperties)

Aggregations

HsqlProperties (org.hsqldb_voltpatches.persist.HsqlProperties)6 Constraint (org.hsqldb_voltpatches.Constraint)3 HsqlName (org.hsqldb_voltpatches.HsqlNameManager.HsqlName)3 SchemaObject (org.hsqldb_voltpatches.SchemaObject)3 Table (org.hsqldb_voltpatches.Table)3 Iterator (org.hsqldb_voltpatches.lib.Iterator)3 WrapperIterator (org.hsqldb_voltpatches.lib.WrapperIterator)3 PersistentStore (org.hsqldb_voltpatches.persist.PersistentStore)3 SQLException (java.sql.SQLException)1 ColumnSchema (org.hsqldb_voltpatches.ColumnSchema)1 NumberType (org.hsqldb_voltpatches.types.NumberType)1 Type (org.hsqldb_voltpatches.types.Type)1