org.hsqldb.Table - java examples

Here are the examples of the java api org.hsqldb.Table taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

90 Examples 7

19 View Complete Implementation : DITableInfo.java
Copyright Apache License 2.0
Author : SERG-Delft
/**
 * Provides extended information about HSQLDB tables and their
 * columns/indices. <p>
 *
 * Current version has been reduced in scope.<p>
 *
 * @author boucherb@users
 * @version 2.2.7
 * @since 1.7.2
 */
final clreplaced DITableInfo {

    // related to DatabaseMetaData
    int bestRowTemporary = 0;

    int bestRowTransaction = 1;

    int bestRowSession = 2;

    int bestRowUnknown = 0;

    int bestRowNotPseudo = 1;

    static final short tableIndexOther = 3;

    /**
     * Used in buffer size and character octet length determinations.
     */
    private static final int HALF_MAX_INT = Integer.MAX_VALUE >>> 1;

    /**
     * BundleHandler id for column remarks resource bundle.
     */
    private int hnd_column_remarks = -1;

    /**
     * BundleHandler id for table remarks resource bundle.
     */
    private int hnd_table_remarks = -1;

    /**
     * The Table object upon which this object is reporting.
     */
    private Table table;

    /**
     * Creates a new DITableInfo object with the default Locale and reporting
     * on no table.  It is absolutely essential the a valid Table object is
     * replacedigned to this object, using the setTable method, before any Table,
     * Column or Index oriented value retrieval methods are called; this clreplaced
     * contains no replacedertions or exception handling related to a null or
     * invalid table member attribute.
     */
    DITableInfo() {
        setupBundles();
    }

    /**
     * Sets the Locale for table and column remarks. <p>
     */
    void setupBundles() {
        Locale oldLocale;
        synchronized (ResourceBundleHandler.clreplaced) {
            oldLocale = ResourceBundleHandler.getLocale();
            ResourceBundleHandler.setLocale(Locale.getDefault());
            hnd_column_remarks = ResourceBundleHandler.getBundleHandle("info-column-remarks", null);
            hnd_table_remarks = ResourceBundleHandler.getBundleHandle("info-table-remarks", null);
            ResourceBundleHandler.setLocale(oldLocale);
        }
    }

    /**
     * Retrieves whether the best row identifier column is
     * a pseudo column, like an Oracle ROWID. <p>
     *
     * Currently, this always returns an Integer whose value is
     * DatabaseMetaData.bestRowNotPseudo, as HSQLDB does not support
     * pseudo columns such as ROWID. <p>
     *
     * @return whether the best row identifier column is
     * a pseudo column
     */
    Integer getBRIPseudo() {
        return ValuePool.getInt(bestRowNotPseudo);
    }

    /**
     * Retrieves the scope of the best row identifier. <p>
     *
     * This implements the rules described in
     * DatabaseInformationMain.SYSTEM_BESTROWIDENTIFIER. <p>
     *
     * @return the scope of the best row identifier
     */
    Integer getBRIScope() {
        return (table.isWritable()) ? ValuePool.getInt(bestRowTemporary) : ValuePool.getInt(bestRowSession);
    }

    /**
     * Retrieves the simple name of the specified column. <p>
     *
     * @param i zero-based column index
     * @return the simple name of the specified column.
     */
    String getColName(int i) {
        return table.getColumn(i).getName().name;
    }

    /**
     * Retrieves the remarks, if any, recorded against the specified
     * column. <p>
     *
     * @param i zero-based column index
     * @return the remarks recorded against the specified column.
     */
    String getColRemarks(int i) {
        String key;
        if (table.getTableType() != TableBase.INFO_SCHEMA_TABLE) {
            return table.getColumn(i).getName().comment;
        }
        key = getName() + "_" + getColName(i);
        return ResourceBundleHandler.getString(hnd_column_remarks, key);
    }

    /**
     * Retrieves the HSQLDB-specific type of the table. <p>
     *
     * @return the HSQLDB-specific type of the table
     */
    String getHsqlType() {
        switch(table.getTableType()) {
            case TableBase.MEMORY_TABLE:
            case TableBase.TEMP_TABLE:
            case TableBase.INFO_SCHEMA_TABLE:
                return "MEMORY";
            case TableBase.CACHED_TABLE:
                return "CACHED";
            case TableBase.TEMP_TEXT_TABLE:
            case TableBase.TEXT_TABLE:
                return "TEXT";
            case TableBase.VIEW_TABLE:
            default:
                return null;
        }
    }

    /**
     * Retrieves the simple name of the table. <p>
     *
     * @return the simple name of the table
     */
    String getName() {
        return table.getName().name;
    }

    /**
     * Retrieves the remarks (if any) recorded against the Table. <p>
     *
     * @return the remarks recorded against the Table
     */
    String getRemark() {
        return (table.getTableType() == TableBase.INFO_SCHEMA_TABLE) ? ResourceBundleHandler.getString(hnd_table_remarks, getName()) : table.getName().comment;
    }

    /**
     * Retrieves the standard JDBC type of the table. <p>
     *
     * "TABLE" for user-defined tables, "VIEW" for user-defined views,
     * and so on.
     *
     * @return the standard JDBC type of the table
     */
    String getJDBCStandardType() {
        switch(table.getTableType()) {
            case TableBase.VIEW_TABLE:
                return "VIEW";
            case TableBase.TEMP_TABLE:
            case TableBase.TEMP_TEXT_TABLE:
                return "GLOBAL TEMPORARY";
            case TableBase.INFO_SCHEMA_TABLE:
                return "SYSTEM TABLE";
            default:
                if (table.getOwner().isSystem()) {
                    return "SYSTEM TABLE";
                }
                return "TABLE";
        }
    }

    /**
     * Retrieves the Table object on which this object is currently
     * reporting. <p>
     *
     * @return the Table object on which this object
     *    is currently reporting
     */
    Table getTable() {
        return this.table;
    }

    /**
     * replacedigns the Table object on which this object is to report. <p>
     *
     * @param table the Table object on which this object is to report
     */
    void setTable(Table table) {
        this.table = table;
    }
}

19 View Complete Implementation : ScriptWriterBase.java
Copyright Apache License 2.0
Author : SERG-Delft
public void writeTableInit(Table t) throws IOException {
}

19 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public boolean hasNonSelectTableRight(Table table) {
    if (isFullyAccessibleByRole(table)) {
        return true;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right == null) {
        return false;
    }
    return right.isFull || right.isFullDelete || right.isFullInsert || right.isFullUpdate || right.isFullReferences || right.isFullTrigger;
}

19 View Complete Implementation : Log.java
Copyright GNU General Public License v3.0
Author : apavlo
void closeTextCache(Table table) {
    TextCache c = (TextCache) textCacheList.remove(table.getName());
    if (c != null) {
        try {
            c.close(true);
        } catch (HsqlException e) {
        }
    }
}

19 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Supports column level rights
 */
boolean canTrigger(Table table, boolean[] columnCheckList) {
    if (isFull || isFullTrigger) {
        return true;
    }
    return containsAllColumns(triggerColumnSet, table, columnCheckList);
}

19 View Complete Implementation : Logger.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 *  Closes the TextCache object.
 */
public void closeTextCache(Table table) {
    log.closeTextCache(table);
}

19 View Complete Implementation : ScriptWriterBase.java
Copyright GNU General Public License v3.0
Author : apavlo
protected void writeTableTerm(Table t) throws IOException {
    if (t.isDataReadOnly() && !t.isTemp() && !t.isText()) {
        StringBuffer a = new StringBuffer("SET TABLE ");
        a.append(t.getName().statementName);
        a.append(" READONLY TRUE");
        writeLogStatement(currentSession, a.toString());
    }
}

19 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Supports column level rights
 */
boolean canUpdate(Table table, boolean[] columnCheckList) {
    if (isFull || isFullUpdate) {
        return true;
    }
    return containsAllColumns(updateColumnSet, table, columnCheckList);
}

19 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Supports column level rights
 */
boolean canReference(Table table, boolean[] columnCheckList) {
    if (isFull || isFullReferences) {
        return true;
    }
    return containsAllColumns(referencesColumnSet, table, columnCheckList);
}

19 View Complete Implementation : ScriptWriterBase.java
Copyright Apache License 2.0
Author : SERG-Delft
public void writeTableTerm(Table t) throws IOException {
}

19 View Complete Implementation : Logger.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 *  Opens the TextCache object.
 */
public DataFileCache openTextCache(Table table, String source, boolean readOnlyData, boolean reversed) {
    return log.openTextCache(table, source, readOnlyData, reversed);
}

19 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
public void setColumns(Table table) {
    if (selectColumnSet != null) {
        setColumns(table, selectColumnSet);
    }
    if (insertColumnSet != null) {
        setColumns(table, insertColumnSet);
    }
    if (updateColumnSet != null) {
        setColumns(table, updateColumnSet);
    }
    if (referencesColumnSet != null) {
        setColumns(table, referencesColumnSet);
    }
    if (triggerColumnSet != null) {
        setColumns(table, triggerColumnSet);
    }
}

19 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public boolean hasTableRight(Table table) {
    if (isFullyAccessibleByRole(table)) {
        return true;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right == null) {
        return false;
    }
    return right.isFull || right.isFullDelete || right.isFullInsert || right.isFullUpdate || right.isFullReferences || right.isFullTrigger || right.isFullSelect;
}

19 View Complete Implementation : PersistentStoreCollectionSession.java
Copyright Apache License 2.0
Author : SERG-Delft
synchronized public void moveData(Table oldTable, Table newTable, int colIndex, int adjust) {
    PersistentStore store = findStore(oldTable);
    if (store == null) {
        return;
    }
    PersistentStore newStore = getStore(newTable);
    try {
        newStore.moveData(session, store, colIndex, adjust);
    } catch (HsqlException e) {
        newStore.release();
        removeStore(newTable);
        throw e;
    }
    removeStore(oldTable);
}

19 View Complete Implementation : DITableInfo.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * replacedigns the Table object on which this object is to report. <p>
 *
 * @param table the Table object on which this object is to report
 */
void setTable(Table table) {
    this.table = table;
}

19 View Complete Implementation : ScriptWriterBase.java
Copyright GNU General Public License v3.0
Author : apavlo
protected void writeTableInit(Table t) throws IOException {
}

19 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public OrderedHashSet getColumnsForAllPrivileges(Table table) {
    if (isFullyAccessibleByRole(table)) {
        return table.getColumnNameSet();
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    return right == null ? Right.emptySet : right.getColumnsForAllRights(table);
}

19 View Complete Implementation : IndexAVL.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * ************ VOLTDB ********************
 */
String getColumnNameList() {
    String columnNameList = "";
    Table t2 = (Table) table;
    for (int j = 0; j < colIndex.length; ++j) {
        columnNameList += t2.getColumn(colIndex[j]).getName().statementName;
        if (j < colIndex.length - 1) {
            columnNameList += ",";
        }
    }
    return columnNameList;
}

19 View Complete Implementation : TextTableStorageManager.java
Copyright Apache License 2.0
Author : SERG-Delft
/**
 *  Closes the TextCache object.
 */
public void closeTextCache(Table table) {
    TextCache c = (TextCache) textCacheList.remove(table.getName());
    if (c != null) {
        try {
            c.close();
        } catch (HsqlException e) {
        }
    }
}

19 View Complete Implementation : DITableInfo.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Provides extended information about HSQLDB tables and their
 * columns/indices. <p>
 *
 * @author boucherb@users
 * @version 1.8.0
 * @since 1.7.2
 */
final clreplaced DITableInfo {

    // related to DatabaseMetaData
    int bestRowTemporary = 0;

    int bestRowTransaction = 1;

    int bestRowSession = 2;

    int bestRowUnknown = 0;

    int bestRowNotPseudo = 1;

    static final short tableIndexOther = 3;

    /**
     * Used in buffer size and character octet length determinations.
     */
    private static final int HALF_MAX_INT = Integer.MAX_VALUE >>> 1;

    /**
     * BundleHandler id for column remarks resource bundle.
     */
    private int hnd_column_remarks = -1;

    /**
     * BundleHandler id for table remarks resource bundle.
     */
    private int hnd_table_remarks = -1;

    /**
     * The Table object upon which this object is reporting.
     */
    private Table table;

    /**
     * Provides intrinsic type infformation support.
     */
    private static final DITypeInfo ti = new DITypeInfo();

    /**
     * Creates a new DITableInfo object with the default Locale and reporting
     * on no table.  It is absolutely essential the a valid Table object is
     * replacedigned to this object, using the setTable method, before any Table,
     * Column or Index oriented value retrieval methods are called; this clreplaced
     * contains no replacedertions or exception handling related to a null or
     * invalid table member attribute.
     */
    DITableInfo() {
        setupBundles();
    }

    /**
     * Sets the Locale for table and column remarks. <p>
     */
    void setupBundles() {
        Locale oldLocale;
        synchronized (BundleHandler.clreplaced) {
            oldLocale = BundleHandler.getLocale();
            BundleHandler.setLocale(Locale.getDefault());
            hnd_column_remarks = BundleHandler.getBundleHandle("column-remarks", null);
            hnd_table_remarks = BundleHandler.getBundleHandle("table-remarks", null);
            BundleHandler.setLocale(oldLocale);
        }
    }

    /**
     * Retrieves whether the best row identifier column is
     * a pseudo column, like an Oracle ROWID. <p>
     *
     * Currently, this always returns an Integer whose value is
     * DatabaseMetaData.bestRowNotPseudo, as HSQLDB does not support
     * pseudo columns such as ROWID. <p>
     *
     * @return whether the best row identifier column is
     * a pseudo column
     */
    Integer getBRIPseudo() {
        return ValuePool.getInt(bestRowNotPseudo);
    }

    /**
     * Retrieves the scope of the best row identifier. <p>
     *
     * This implements the rules described in
     * DatabaseInformationMain.SYSTEM_BESTROWIDENTIFIER. <p>
     *
     * @return the scope of the best row identifier
     */
    Integer getBRIScope() {
        return (table.isWritable()) ? ValuePool.getInt(bestRowTemporary) : ValuePool.getInt(bestRowSession);
    }

    /**
     * Retrieves, if definitely known, the transfer size for values of the
     * specified column, in bytes. <p>
     *
     * @param i zero-based column index
     * @return the transfer size for values of the
     * specified column, in bytes
     */
    Integer getColBufLen(int i) {
        int size;
        int type;
        ColumnSchema column;
        column = table.getColumn(i);
        type = column.getDataType().getJDBCTypeCode();
        switch(type) {
            case Types.SQL_CHAR:
            case Types.SQL_CLOB:
            case Types.VARCHAR_IGNORECASE:
            case Types.SQL_VARCHAR:
                {
                    size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision;
                    if (size == 0) {
                    } else if (size > HALF_MAX_INT) {
                        size = 0;
                    } else {
                        size = 2 * size;
                    }
                    break;
                }
            case Types.SQL_BINARY:
            case Types.SQL_BLOB:
            case Types.SQL_VARBINARY:
                {
                    size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision;
                    break;
                }
            case Types.SQL_BIGINT:
            case Types.SQL_DOUBLE:
            case Types.SQL_FLOAT:
            case Types.SQL_DATE:
            case Types.SQL_REAL:
            case Types.SQL_TIME_WITH_TIME_ZONE:
            case Types.SQL_TIME:
                {
                    size = 8;
                    break;
                }
            case Types.SQL_TIMESTAMP_WITH_TIME_ZONE:
            case Types.SQL_TIMESTAMP:
                {
                    size = 12;
                    break;
                }
            case Types.SQL_INTEGER:
            case Types.SQL_SMALLINT:
            case Types.TINYINT:
                {
                    size = 4;
                    break;
                }
            case Types.SQL_BOOLEAN:
                {
                    size = 1;
                    break;
                }
            default:
                {
                    size = 0;
                    break;
                }
        }
        return (size > 0) ? ValuePool.getInt(size) : null;
    }

    /**
     * Retrieves the declared size, in bytes, for character-valued
     * columns. <p>
     *
     * If the size cannot be represented in the range [0,Integer.MAX_VALUE],
     * this returns null. <p>
     *
     * @param i zero-based column index
     * @return the size, in bytes, for character-valued columns
     */
    Integer getColCharOctLen(int i) {
        int size;
        int type;
        ColumnSchema column;
        column = table.getColumn(i);
        type = column.getDataType().getJDBCTypeCode();
        switch(type) {
            case Types.SQL_CHAR:
            case Types.SQL_CLOB:
            case Types.VARCHAR_IGNORECASE:
            case Types.SQL_VARCHAR:
                {
                    size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision;
                    if (size == 0) {
                    } else if (size > HALF_MAX_INT) {
                        size = 0;
                    } else {
                        size = 2 * size;
                    }
                    break;
                }
            default:
                {
                    size = 0;
                    break;
                }
        }
        return (size == 0) ? null : ValuePool.getInt(size);
    }

    /**
     * Retrieves the SQL data type code for the specified column. <p>
     *
     * @param i zero-based column index
     * @return the SQL data type code for the specified column
     */
    Integer getColJDBCDataType(int i) {
        return ValuePool.getInt(table.getColumn(i).getDataType().getJDBCTypeCode());
    }

    /**
     * Retrieves the SQL data type name for the specified column. <p>
     *
     * @param i zero-based column index
     * @return the SQL data type name for the specified column
     */
    String getColDataTypeName(int i) {
        return table.getColumn(i).getDataType().getNameString();
    }

    /**
     * Retrieves the HSQLDB data subtype code for the specified column. <p>
     *
     * @param i zero-based column index
     * @return the HSQLDB data subtype code for the specified column
     */
    Integer getColDataTypeSub(int i) {
        int type = table.getColumn(i).getDataType().getJDBCTypeCode();
        int sub = type == Types.VARCHAR_IGNORECASE ? Types.TYPE_SUB_IGNORECASE : Types.TYPE_SUB_DEFAULT;
        return ValuePool.getInt(sub);
    }

    /**
     * Retrieves the declared default value expression for the column. <p>
     *
     * @param i zero-based column index
     * @return the declared default value expression for the column
     */
    String getColDefault(int i) {
        return table.getColumn(i).getDefaultSQL();
    }

    /**
     * Retrieves whether the specified column is the idenreplacedy column for
     * the table. <p>
     *
     * @param i zero-based column index
     * @return whether the specified column is the idenreplacedy column for
     * the table.
     */
    Boolean getColIsIdenreplacedy(int i) {
        return table.getColumn(i).isIdenreplacedy() ? Boolean.TRUE : Boolean.FALSE;
    }

    /**
     * Retrieves whether the specified column is nullable. <p>
     *
     * If the column is nullable, "YES" is retrieved, else "NO". <p>
     *
     * @param i zero-based column index
     * @return the nullability of the specified column
     */
    String getColIsNullable(int i) {
        ColumnSchema column = table.getColumn(i);
        return (column.isNullable() && !column.isPrimaryKey()) ? "YES" : "NO";
    }

    /**
     * Retrieves the simple name of the specified column. <p>
     *
     * @param i zero-based column index
     * @return the simple name of the specified column.
     */
    String getColName(int i) {
        return table.getColumn(i).getName().name;
    }

    /**
     * Retrieves the specified column's nullablility. <p>
     *
     * @param i zero-based column index
     * @return the specified column's nullablilit
     */
    Integer getColNullability(int i) {
        ColumnSchema column = table.getColumn(i);
        return (column.isNullable() && !column.isPrimaryKey()) ? ValuePool.getInt(DITypeInfo.columnNullable) : ValuePool.getInt(DITypeInfo.columnNoNulls);
    }

    /**
     * Retrieves the number base that should be used to interpret the
     * specified column's numeric precision, as reported by getColSize(int).
     *
     * @param i zero-based column index
     * @return the number base that should be used to
     *    interpret the column's numeric precision,
     *    as reported by getColSize(int).
     */
    Integer getColPrecRadix(int i) {
        ti.setTypeCode(table.getColumn(i).getDataType().getJDBCTypeCode());
        return ti.getNumPrecRadix();
    }

    /**
     * Retrieves the remarks, if any, recorded against the specified
     * column. <p>
     *
     * @param i zero-based column index
     * @return the remarks recorded against the specified column.
     */
    String getColRemarks(int i) {
        String key;
        if (table.getTableType() != TableBase.SYSTEM_TABLE) {
            return null;
        }
        key = getName() + "_" + getColName(i);
        return BundleHandler.getString(hnd_column_remarks, key);
    }

    /**
     * Retrieves the declared (but not currently enforced) or implicit fixed
     * number of digits to the right of the decimal point for exact numeric
     * types.
     *
     * If the column's type precludes scale declaration, null is returned.
     *
     * @param i zero-based column index
     * @return the fixed number of digits to the right of the decimal point
     * for exact numeric types.
     */
    Integer getColScaleOrNull(int i) {
        ColumnSchema column;
        int type;
        column = table.getColumn(i);
        type = column.getDataType().getJDBCTypeCode();
        return Types.acceptsScaleCreateParam(type) ? ValuePool.getInt(column.getDataType().scale) : null;
    }

    /**
     * Retrieves null (not implemented). <p>
     *
     * @param i zero-based column index
     * @return null (not implemented)
     */
    String getColScopeCat(int i) {
        return null;
    }

    /**
     * Retrieves null (not implemented). <p>
     *
     * @param i zero-based column index
     * @return null (not implemented)
     */
    String getColScopeSchem(int i) {
        return null;
    }

    /**
     * Retrieves null (not implemented). <p>
     *
     * @param i zero-based column index
     * @return null (not implemented)
     */
    String getColScopeTable(int i) {
        return null;
    }

    /**
     * Retrieves either the declared or maximum length/precision for
     * the specified column, if its type allows a precision/length
     * declaration, else null. <p>
     *
     * @param i zero-based column index
     * @return the declared or maximum length/precision for
     *    the specified column
     */
    Integer getColSize(int i) {
        ColumnSchema column;
        int type;
        int size;
        column = table.getColumn(i);
        type = column.getDataType().getJDBCTypeCode();
        if (!Types.acceptsPrecision(type)) {
            return null;
        }
        size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision;
        if (size > 0) {
            return ValuePool.getInt(size);
        } else {
            ti.setTypeCode(type);
            return ti.getPrecision();
        }
    }

    /**
     * Retrieves the SQL CLI data type code for the specified column. <p>
     *
     * @param i zero-based column index
     * @return the SQL CLI data type code for the specified column
     */
    Integer getColSqlDataType(int i) {
        ti.setTypeCode(table.getColumn(i).getDataType().getJDBCTypeCode());
        return ti.getSqlDataType();
    }

    /**
     * Retrieves the SQL CLI datetime subtype for the specified column. <p>
     *
     * @param i zero-based column index
     * @return the SQL CLI datetime subtype for the specified column
     */
    Integer getColSqlDateTimeSub(int i) {
        ti.setTypeCode(table.getColumn(i).getDataType().getJDBCTypeCode());
        return ti.getSqlDateTimeSub();
    }

    /**
     * Retrieves the full data source descriptor for [TEMP] TEXT tables. <p>
     *
     * @return the full data source descriptor
     */
    String getDataSource() {
        return table.isText() ? ((TextTable) table).getDataSource() : null;
    }

    /**
     * Retrieves the HSQLDB-specific type of the table. <p>
     *
     * @return the HSQLDB-specific type of the table
     */
    String getHsqlType() {
        switch(table.getTableType()) {
            case TableBase.MEMORY_TABLE:
            case TableBase.TEMP_TABLE:
            case TableBase.SYSTEM_TABLE:
                return "MEMORY";
            case TableBase.CACHED_TABLE:
                return "CACHED";
            case TableBase.TEMP_TEXT_TABLE:
            case TableBase.TEXT_TABLE:
                return "TEXT";
            case TableBase.VIEW_TABLE:
            default:
                return null;
        }
    }

    /**
     * Retrieves null (not implemented). <p>
     *
     * @param i zero-based index specifier
     * @return null (not implemented)
     */
    Integer getIndexCardinality(int i) {
        return null;
    }

    /**
     * Retrieves the sort-direction for the specified column in the
     * specified index. <p>
     *
     * @param i zero-based index specifier
     * @param columnPosition zero-based ordinal position of column in index
     * @return the sort-direction for the specified column in the
     * specified index
     */
    String getIndexColDirection(int i, int columnPosition) {
        // so far, hsqldb only supports completely ascending indexes
        return "A";
    }

    /**
     * Retrieves an array map from the zero-based ordinal positions of the
     * columns in the specfied Index to the zero-based ordinal positions of
     * the same columns in the table. <p>
     *
     * @param i zero-based index specifier
     * @return an array map from the zero-based ordinal positions of
     *    the columns in the specfied Index to the zero-based
     *    ordinal positions of the same columns in the table
     */
    int[] getIndexColumns(int i) {
        return table.getIndex(i).getColumns();
    }

    /**
     * Retrieves the simple name of the specified Index. <p>
     *
     * @param i zero-based index specifier
     * @return the simple name of the specified Index
     */
    String getIndexName(int i) {
        return table.getIndex(i).getName().name;
    }

    /**
     * Retrieves null (not implemented). <p>
     *
     * @param i zero-based index specifier
     * @return null (not implemented)
     */
    Integer getIndexRowCardinality(int i) {
        return null;
    }

    /**
     * Retrieves the DatabaseMetaData type code of the specified Index. <p>
     *
     * @param i zero-based index specifier
     * @return the DatabaseMetaData type code of the specified Index
     */
    Integer getIndexType(int i) {
        return ValuePool.getInt(tableIndexOther);
    }

    /**
     * Retrieves the number of visible columns in the specified Index.  That
     * is, this retrieves one less than the physical number of columns if the
     * table maintains an internal primary index on an internal idenreplacedy
     * column, as is the case when the table has no declared primary key or
     * idenreplacedy column. <p>
     *
     * @param i zero-based index specifier
     * @return the number of visible columns in the specified Index
     */
    int getIndexVisibleColumns(int i) {
        return table.getIndex(i).getColumnCount();
    }

    /**
     * Retrieves the simple name of the table. <p>
     *
     * @return the simple name of the table
     */
    String getName() {
        return table.getName().name;
    }

    /**
     * Retrieves the value of the next automatically replacedigned idenreplacedy. <p>
     *
     * Be aware that this is not necessarily the value that will be replacedigned
     * to the idenreplacedy column during the next insert or update.  This value is
     * used if NULL is either implicitly or explicity replacedigned. <p>
     *
     * @return the value of the next automatically replacedigned idenreplacedy
     */
    Long getNextIdenreplacedy() {
        if (table.hasIdenreplacedyColumn()) {
            return ValuePool.getLong(table.getNextIdenreplacedy());
        } else {
            return null;
        }
    }

    /**
     * Retrieves the remarks (if any) recorded against the Table. <p>
     *
     * @return the remarks recorded against the Table
     */
    String getRemark() {
        return (table.getTableType() == TableBase.SYSTEM_TABLE) ? BundleHandler.getString(hnd_table_remarks, getName()) : null;
    }

    /**
     * Retrieves the standard JDBC type of the table. <p>
     *
     * "TABLE" for user-defined tables, "VIEW" for user-defined views,
     * and so on.
     *
     * @return the standard JDBC type of the table
     */
    String getJDBCStandardType() {
        switch(table.getTableType()) {
            case TableBase.VIEW_TABLE:
                return "VIEW";
            case TableBase.TEMP_TABLE:
            case TableBase.TEMP_TEXT_TABLE:
                return "GLOBAL TEMPORARY";
            case TableBase.SYSTEM_TABLE:
                return "SYSTEM TABLE";
            default:
                return "TABLE";
        }
    }

    /**
     * Retrieves the Table object on which this object is currently
     * reporting. <p>
     *
     * @return the Table object on which this object
     *    is currently reporting
     */
    Table getTable() {
        return this.table;
    }

    /**
     * Retrieves, for [TEMP] TEXT tables, whether the table's data source
     * descriptor requests descending read semantics.  That is, when this
     * value is true, it indicate that the text file is to be read from
     * the bottom up. <p>
     *
     * @return whether the table's data source
     *    descriptor requests descending
     *    read semantics
     */
    Boolean isDataSourceDescending() {
        if (table.isText()) {
            return ((TextTable) table).isDescDataSource() ? Boolean.TRUE : Boolean.FALSE;
        }
        return Boolean.FALSE;
    }

    /**
     * Retrieves whether the specified Index is non-unique. <p>
     *
     * @param i zero-based index specifier
     * @return whether the specified Index is non-unique
     */
    Boolean isIndexNonUnique(int i) {
        return ValuePool.getBoolean(!table.getIndex(i).isUnique());
    }

    /**
     * Retrieves whether the table is in data read-only mode.  This value does
     * not reflect the various read-only modes of the database or the
     * read-only mode of the connection. <p>
     *
     * @return whether the table is in data read-only mode
     */
    Boolean isReadOnly() {
        return ValuePool.getBoolean(table.isDataReadOnly());
    }

    /**
     * replacedigns the Table object on which this object is to report. <p>
     *
     * @param table the Table object on which this object is to report
     */
    void setTable(Table table) {
        this.table = table;
    }
}

19 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Supports column level rights
 */
boolean canInsert(Table table, boolean[] columnCheckList) {
    if (isFull || isFullInsert) {
        return true;
    }
    return containsAllColumns(insertColumnSet, table, columnCheckList);
}

19 View Complete Implementation : IndexAVL.java
Copyright GNU General Public License v3.0
Author : apavlo
private static void getColumnList(Table t, int[] col, int len, StringBuffer a) {
    a.append('(');
    for (int i = 0; i < len; i++) {
        a.append(t.getColumn(col[i]).getName().statementName);
        if (i < len - 1) {
            a.append(',');
        }
    }
    a.append(')');
}

19 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Supports column level rights
 */
boolean canSelect(Table table, boolean[] columnCheckList) {
    if (isFull || isFullSelect) {
        return true;
    }
    return containsAllColumns(selectColumnSet, table, columnCheckList);
}

18 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public void checkInsert(Table table, boolean[] checkList) {
    if (isFullyAccessibleByRole(table)) {
        return;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right != null && right.canInsert(table, checkList)) {
        return;
    }
    throw Error.error(ErrorCode.X_42501, table.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public void checkDelete(Table table) {
    if (isFullyAccessibleByRole(table)) {
        return;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right != null && right.canDelete()) {
        return;
    }
    throw Error.error(ErrorCode.X_42501, table.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public void checkReferences(Table table, boolean[] checkList) {
    if (isFullyAccessibleByRole(table)) {
        return;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right != null && right.canReference(table, checkList)) {
        return;
    }
    throw Error.error(ErrorCode.X_42501, table.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public void checkTrigger(Table table, boolean[] checkList) {
    if (isFullyAccessibleByRole(table)) {
        return;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right != null && right.canReference(table, checkList)) {
        return;
    }
    throw Error.error(ErrorCode.X_42501, table.getName().name);
}

18 View Complete Implementation : ScriptWriterBase.java
Copyright GNU General Public License v3.0
Author : apavlo
abstract void writeRow(Session session, Table table, Object[] data) throws IOException;

18 View Complete Implementation : ScriptWriterBase.java
Copyright GNU General Public License v3.0
Author : apavlo
public abstract void writeInsertStatement(Session session, Table table, Object[] data) throws IOException;

18 View Complete Implementation : ScriptWriterBase.java
Copyright GNU General Public License v3.0
Author : apavlo
public abstract void writeDeleteStatement(Session session, Table table, Object[] data) throws IOException;

18 View Complete Implementation : Right.java
Copyright GNU General Public License v3.0
Author : apavlo
public OrderedHashSet getColumnsForPrivilege(Table table, int type) {
    if (isFull) {
        return table.getColumnNameSet();
    }
    switch(type) {
        case GrantConstants.SELECT:
            return isFullSelect ? table.getColumnNameSet() : selectColumnSet == null ? emptySet : selectColumnSet;
        case GrantConstants.INSERT:
            return isFullInsert ? table.getColumnNameSet() : insertColumnSet == null ? emptySet : insertColumnSet;
        case GrantConstants.UPDATE:
            return isFullUpdate ? table.getColumnNameSet() : updateColumnSet == null ? emptySet : updateColumnSet;
        case GrantConstants.REFERENCES:
            return isFullReferences ? table.getColumnNameSet() : referencesColumnSet == null ? emptySet : referencesColumnSet;
        case GrantConstants.TRIGGER:
            return isFullTrigger ? table.getColumnNameSet() : triggerColumnSet == null ? emptySet : triggerColumnSet;
    }
    return emptySet;
}

18 View Complete Implementation : ScriptWriterBinary.java
Copyright GNU General Public License v3.0
Author : apavlo
public void writeInsertStatement(Session session, Table table, Object[] data) throws IOException {
}

18 View Complete Implementation : ScriptWriterText.java
Copyright GNU General Public License v3.0
Author : apavlo
public void writeInsertStatement(Session session, Table table, Object[] data) throws IOException {
    schemaToLog = table.getName().schema;
    writeRow(session, table, data);
}

18 View Complete Implementation : Grantee.java
Copyright Apache License 2.0
Author : SERG-Delft
public void checkUpdate(SchemaObject object, boolean[] checkList) {
    if (object instanceof Table) {
        Table table = (Table) object;
        if (isFullyAccessibleByRole(table.getName())) {
            return;
        }
        Right right = (Right) fullRightsMap.get(table.getName());
        if (right != null && right.canUpdate(table, checkList)) {
            return;
        }
    }
    throw Error.error(ErrorCode.X_42501, object.getName().name);
}

18 View Complete Implementation : ScriptWriterBinary.java
Copyright GNU General Public License v3.0
Author : apavlo
public void writeDeleteStatement(Session session, Table table, Object[] ddata) throws IOException {
}

18 View Complete Implementation : Grantee.java
Copyright Apache License 2.0
Author : SERG-Delft
public void checkReferences(SchemaObject object, boolean[] checkList) {
    if (object instanceof Table) {
        Table table = (Table) object;
        if (isFullyAccessibleByRole(table.getName())) {
            return;
        }
        Right right = (Right) fullRightsMap.get(table.getName());
        if (right != null && right.canReference(table, checkList)) {
            return;
        }
    }
    throw Error.error(ErrorCode.X_42501, object.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright Apache License 2.0
Author : SERG-Delft
public void checkTrigger(SchemaObject object, boolean[] checkList) {
    if (object instanceof Table) {
        Table table = (Table) object;
        if (isFullyAccessibleByRole(table.getName())) {
            return;
        }
        Right right = (Right) fullRightsMap.get(table.getName());
        if (right != null && right.canReference(table, checkList)) {
            return;
        }
    }
    throw Error.error(ErrorCode.X_42501, object.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright Apache License 2.0
Author : SERG-Delft
public void checkDelete(SchemaObject object) {
    if (object instanceof Table) {
        Table table = (Table) object;
        if (isFullyAccessibleByRole(table.getName())) {
            return;
        }
        Right right = (Right) fullRightsMap.get(table.getName());
        if (right != null && right.canDelete()) {
            return;
        }
    }
    throw Error.error(ErrorCode.X_42501, object.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright Apache License 2.0
Author : SERG-Delft
/**
 * Checks if a right represented by the methods
 * have been granted on the specified database object. <p>
 *
 * This is done by checking that a mapping exists in the rights map
 * from the dbobject argument. Otherwise, it throws.
 */
public void checkSelect(SchemaObject object, boolean[] checkList) {
    if (object instanceof Table) {
        Table table = (Table) object;
        if (isFullyAccessibleByRole(table.getName())) {
            return;
        }
        Right right = (Right) fullRightsMap.get(table.getName());
        if (right != null && right.canSelect(table, checkList)) {
            return;
        }
    }
    throw Error.error(ErrorCode.X_42501, object.getName().name);
}

18 View Complete Implementation : Log.java
Copyright GNU General Public License v3.0
Author : apavlo
void writeDeleteStatement(Session session, Table t, Object[] row) {
    try {
        dbLogWriter.writeDeleteStatement(session, t, row);
    } catch (IOException e) {
        throw Error.error(ErrorCode.FILE_IO_ERROR, logFileName);
    }
    if (maxLogSize > 0 && dbLogWriter.size() > maxLogSize) {
        database.logger.needsCheckpoint = true;
    }
}

18 View Complete Implementation : Logger.java
Copyright GNU General Public License v3.0
Author : apavlo
public synchronized void writeDeleteStatement(Session session, Table t, Object[] row) {
    if (logStatements) {
        log.writeDeleteStatement(session, t, row);
    }
}

18 View Complete Implementation : Logger.java
Copyright GNU General Public License v3.0
Author : apavlo
public synchronized void writeInsertStatement(Session session, Table table, Object[] row) {
    if (logStatements) {
        log.writeInsertStatement(session, table, row);
    }
}

18 View Complete Implementation : RowStoreAVLDisk.java
Copyright GNU General Public License v3.0
Author : apavlo
/*
 * Implementation of PersistentStore for CACHED tables.
 *
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 1.9.0
 * @since 1.9.0
 */
public clreplaced RowStoreAVLDisk extends RowStoreAVL {

    DataFileCache cache;

    Table table;

    IntKeyHashMapConcurrent rowActionMap;

    public RowStoreAVLDisk(PersistentStoreCollection manager, DataFileCache cache, Table table) {
        this.manager = manager;
        this.table = table;
        this.indexList = table.getIndexList();
        this.accessorList = new CachedObject[indexList.length];
        this.cache = cache;
        manager.setStore(table, this);
        rowActionMap = table.database.txManager.rowActionMap;
    }

    public boolean isMemory() {
        return false;
    }

    public int getAccessCount() {
        return cache.getAccessCount();
    }

    public void set(CachedObject object) {
        Row row = ((Row) object);
        row.rowAction = (RowAction) rowActionMap.get(row.getPos());
    }

    public CachedObject get(int key) {
        CachedObject object = cache.get(key, this, false);
        return object;
    }

    public CachedObject getKeep(int key) {
        CachedObject object = cache.get(key, this, true);
        return object;
    }

    public CachedObject get(int key, boolean keep) {
        CachedObject object = cache.get(key, this, keep);
        return object;
    }

    public CachedObject get(CachedObject object, boolean keep) {
        object = cache.get(object, this, keep);
        return object;
    }

    public int getStorageSize(int i) {
        return cache.get(i, this, false).getStorageSize();
    }

    public void add(CachedObject object) {
        int size = object.getRealSize(cache.rowOut);
        size = cache.rowOut.getStorageSize(size);
        object.setStorageSize(size);
        cache.add(object);
    }

    public CachedObject get(RowInputInterface in) {
        try {
            return new RowAVLDisk(table, in);
        } catch (IOException e) {
            throw Error.error(ErrorCode.DATA_FILE_ERROR, e);
        }
    }

    public CachedObject getNewCachedObject(Session session, Object object) {
        Row row = new RowAVLDisk(table, (Object[]) object);
        add(row);
        if (session != null) {
            RowAction.addAction(session, RowAction.ACTION_INSERT, table, row);
        }
        return row;
    }

    public void removeAll() {
        ArrayUtil.fillArray(accessorList, null);
    }

    public void remove(int i) {
        cache.remove(i, this);
    }

    public void removePersistence(int i) {
    }

    public void release(int i) {
        cache.release(i);
    }

    public void commitPersistence(CachedObject row) {
    }

    public DataFileCache getCache() {
        return cache;
    }

    public void setCache(DataFileCache cache) {
        this.cache = cache;
    }

    public void release() {
        ArrayUtil.fillArray(accessorList, null);
        cache = null;
    }

    public void setAccessor(Index key, CachedObject accessor) {
        Index index = (Index) key;
        accessorList[index.getPosition()] = accessor;
    }

    public CachedObject getAccessor(Index key) {
        NodeAVL node = (NodeAVL) accessorList[key.getPosition()];
        if (node == null) {
            return null;
        }
        if (!node.isInMemory()) {
            RowAVL row = (RowAVL) get(node.getPos(), false);
            node = row.getNode(key.getPosition());
            accessorList[key.getPosition()] = node;
        }
        return node;
    }

    public void setAccessor(Index key, int accessor) {
        CachedObject object = get(accessor, false);
        if (object != null) {
            NodeAVL node = ((RowAVL) object).getNode(key.getPosition());
            object = node;
        }
        setAccessor(key, object);
    }

    public void resetAccessorKeys(Index[] keys) {
        if (indexList.length == 0 || indexList[0] == null || accessorList[0] == null) {
            indexList = keys;
            accessorList = new CachedObject[indexList.length];
            return;
        }
        throw Error.runtimeError(ErrorCode.U_S0500, "RowStoreCached");
    }

    public CachedObject getNewInstance(int size) {
        return null;
    }
}

18 View Complete Implementation : Grantee.java
Copyright Apache License 2.0
Author : SERG-Delft
public void checkInsert(SchemaObject object, boolean[] checkList) {
    if (object instanceof Table) {
        Table table = (Table) object;
        if (isFullyAccessibleByRole(table.getName())) {
            return;
        }
        Right right = (Right) fullRightsMap.get(table.getName());
        if (right != null && right.canInsert(table, checkList)) {
            return;
        }
    }
    throw Error.error(ErrorCode.X_42501, object.getName().name);
}

18 View Complete Implementation : RowStoreAVLMemory.java
Copyright GNU General Public License v3.0
Author : apavlo
/*
 * Implementation of PersistentStore for MEMORY tables.
 *
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 1.9.0
 * @since 1.9.0
 */
public clreplaced RowStoreAVLMemory extends RowStoreAVL implements PersistentStore {

    Table table;

    private IntKeyHashMapConcurrent rowIdMap;

    int rowIdSequence = 0;

    public RowStoreAVLMemory(PersistentStoreCollection manager, Table table) {
        this.manager = manager;
        this.table = table;
        this.indexList = table.getIndexList();
        this.accessorList = new CachedObject[indexList.length];
        rowIdMap = new IntKeyHashMapConcurrent();
        manager.setStore(table, this);
    }

    public boolean isMemory() {
        return true;
    }

    public int getAccessCount() {
        return 0;
    }

    public void set(CachedObject object) {
    }

    public CachedObject get(int i) {
        return (CachedObject) rowIdMap.get(i);
    }

    public CachedObject getKeep(int i) {
        return (CachedObject) rowIdMap.get(i);
    }

    public CachedObject get(int i, boolean keep) {
        return (CachedObject) rowIdMap.get(i);
    }

    public CachedObject get(CachedObject object, boolean keep) {
        return (CachedObject) rowIdMap.get(object.getPos());
    }

    public int getStorageSize(int i) {
        return 0;
    }

    public void add(CachedObject object) {
    }

    public CachedObject get(RowInputInterface in) {
        return null;
    }

    public CachedObject getNewCachedObject(Session session, Object object) {
        Row row = new RowAVL(table, (Object[]) object);
        if (session != null) {
            RowAction.addAction(session, RowAction.ACTION_INSERT, table, row);
        }
        int id = rowIdSequence++;
        row.setPos(id);
        rowIdMap.put(id, row);
        return row;
    }

    public void removeAll() {
        rowIdMap.clear();
        ArrayUtil.fillArray(accessorList, null);
    }

    public void remove(int i) {
        rowIdMap.remove(i);
    }

    public void removePersistence(int i) {
    }

    public void release(int i) {
    }

    public void commitPersistence(CachedObject row) {
    }

    public DataFileCache getCache() {
        return null;
    }

    public void setCache(DataFileCache cache) {
    }

    public void release() {
        ArrayUtil.fillArray(accessorList, null);
        rowIdMap.clear();
    }

    public void setAccessor(Index key, CachedObject accessor) {
        Index index = (Index) key;
        accessorList[index.getPosition()] = accessor;
    }

    public void setAccessor(Index key, int accessor) {
    }

    public void resetAccessorKeys(Index[] keys) {
        if (indexList.length == 0 || indexList[0] == null || accessorList[0] == null) {
            indexList = keys;
            accessorList = new CachedObject[indexList.length];
            return;
        }
        CachedObject[] oldAccessors = accessorList;
        Index[] oldIndexList = indexList;
        int limit = indexList.length;
        int diff = 1;
        int position = 0;
        if (keys.length < indexList.length) {
            diff = -1;
            limit = keys.length;
        }
        for (; position < limit; position++) {
            if (indexList[position] != keys[position]) {
                break;
            }
        }
        accessorList = (CachedObject[]) ArrayUtil.toAdjustedArray(accessorList, null, position, diff);
        indexList = keys;
        try {
            if (diff > 0) {
                insertIndexNodes(indexList[0], indexList[position]);
            } else {
                dropIndexFromRows(indexList[0], oldIndexList[position]);
            }
        } catch (HsqlException e) {
            accessorList = oldAccessors;
            indexList = oldIndexList;
            throw e;
        }
    }

    public CachedObject getNewInstance(int size) {
        return null;
    }

    void dropIndexFromRows(Index primaryIndex, Index oldIndex) {
        RowIterator it = primaryIndex.firstRow(this);
        int position = oldIndex.getPosition() - 1;
        while (it.hasNext()) {
            Row row = it.getNextRow();
            int i = position - 1;
            NodeAVL backnode = ((RowAVL) row).getNode(0);
            while (i-- > 0) {
                backnode = backnode.nNext;
            }
            backnode.nNext = backnode.nNext.nNext;
        }
    }

    boolean insertIndexNodes(Index primaryIndex, Index newIndex) {
        int position = newIndex.getPosition();
        RowIterator it = primaryIndex.firstRow(this);
        int rowCount = 0;
        HsqlException error = null;
        try {
            while (it.hasNext()) {
                Row row = it.getNextRow();
                ((RowAVL) row).insertNode(position);
                // count before inserting
                rowCount++;
                newIndex.insert(null, this, row);
            }
            return true;
        } catch (java.lang.OutOfMemoryError e) {
            error = Error.error(ErrorCode.OUT_OF_MEMORY);
        } catch (HsqlException e) {
            error = e;
        }
        // backtrack on error
        // rowCount rows have been modified
        it = primaryIndex.firstRow(this);
        for (int i = 0; i < rowCount; i++) {
            Row row = it.getNextRow();
            NodeAVL backnode = ((RowAVL) row).getNode(0);
            int j = position;
            while (--j > 0) {
                backnode = backnode.nNext;
            }
            backnode.nNext = backnode.nNext.nNext;
        }
        throw error;
    }

    /**
     * for result tables
     */
    void reindex(Session session, Index index) {
        setAccessor(index, null);
        RowIterator it = table.rowIterator(session);
        while (it.hasNext()) {
            Row row = it.getNextRow();
            // may need to clear the node before insert
            index.insert(session, this, row);
        }
    }
}

18 View Complete Implementation : TextCache.java
Copyright GNU General Public License v3.0
Author : apavlo
// Ito Kazumitsu 20030328 - patch 1.7.2 - character encoding support
// Dimitri Maziuk - patch for NL in string support
// sqlbob@users - updated for 1.8.0 to allow new-lines in fields
// fredt@users - updated for 1.8.0 to allow correct behaviour with transactions
/**
 * Acts as a buffer manager for a single TEXT table with respect its Row data.<p>
 *
 * Handles read/write operations on the table's text format data file using a
 * compatible pair of org.hsqldb.rowio input/output clreplaced instances.
 *
 * @author Bob Preston (sqlbob@users dot sourceforge.net)
 * @version 1.9.0
 * @since 1.7.0
 */
public clreplaced TextCache extends DataFileCache {

    // state of Cache
    public static final String NL = System.getProperty("line.separator");

    public String fs;

    public String vs;

    public String lvs;

    public String stringEncoding;

    public boolean isQuoted;

    public boolean isAllQuoted;

    public boolean ignoreFirst;

    protected String header;

    protected Table table;

    private ObjectCacheHashMap uncommittedCache;

    // 
    final static char DOUBLE_QUOTE_CHAR = '\"';

    final static char BACKSLASH_CHAR = '\\';

    final static char LF_CHAR = '\n';

    final static char CR_CHAR = '\r';

    /**
     *  The source string for a cached table is evaluated and the parameters
     *  are used to open the source file.<p>
     *
     *  Settings are used in this order: (1) settings specified in the
     *  source string for the table (2) global database settings in
     *  *.properties file (3) program defaults
     *
     *  fredt - this used to write rows as soon as they are inserted
     *  but now this is subject to session autoCommit / or commit
     *  storeOnInsert = true;
     */
    TextCache(Table table, String name) {
        super(table.database, name);
        this.table = table;
        uncommittedCache = new ObjectCacheHashMap(5);
    }

    protected void initParams(Database database, String baseFileName) {
        fileName = baseFileName;
        this.database = database;
        fa = FileUtil.getDefaultInstance();
        HsqlProperties tableprops = HsqlProperties.delimitedArgPairsToProps(fileName, "=", ";", null);
        // source file name is the only key without a value
        fileName = tableprops.errorKeys[0].trim();
        // -- Get separators:
        HsqlDatabaseProperties dbProps = database.getProperties();
        fs = translateSep(tableprops.getProperty("fs", dbProps.getProperty(HsqlDatabaseProperties.textdb_fs, ",")));
        vs = translateSep(tableprops.getProperty("vs", dbProps.getProperty(HsqlDatabaseProperties.textdb_vs, fs)));
        lvs = translateSep(tableprops.getProperty("lvs", dbProps.getProperty(HsqlDatabaseProperties.textdb_lvs, fs)));
        // -- Get booleans
        ignoreFirst = tableprops.isPropertyTrue("ignore_first", dbProps.isPropertyTrue(HsqlDatabaseProperties.textdb_ignore_first, false));
        isQuoted = tableprops.isPropertyTrue("quoted", dbProps.isPropertyTrue(HsqlDatabaseProperties.textdb_quoted, true));
        isAllQuoted = tableprops.isPropertyTrue("all_quoted", dbProps.isPropertyTrue(HsqlDatabaseProperties.textdb_all_quoted, false));
        // -- Get encoding
        stringEncoding = translateSep(tableprops.getProperty("encoding", dbProps.getProperty(HsqlDatabaseProperties.textdb_encoding, "ASCII")));
        // -- Get size and scale
        int cacheScale = tableprops.getIntegerProperty("cache_scale", dbProps.getIntegerProperty(HsqlDatabaseProperties.textdb_cache_scale, 10, 8, 16));
        int cacheSizeScale = tableprops.getIntegerProperty("cache_size_scale", dbProps.getIntegerProperty(HsqlDatabaseProperties.textdb_cache_size_scale, 10, 8, 20));
        int lookupTableLength = 1 << cacheScale;
        int avgRowBytes = 1 << cacheSizeScale;
        maxCacheSize = lookupTableLength * 3;
        maxCacheBytes = maxCacheSize * avgRowBytes;
        maxDataFileSize = Integer.MAX_VALUE;
        cachedRowPadding = 1;
        cacheFileScale = 1;
    }

    static void checkTextSouceString(String fileName, HsqlDatabaseProperties dbProps) {
        HsqlProperties tableprops = HsqlProperties.delimitedArgPairsToProps(fileName, "=", ";", null);
        // -- Get file name
        switch(tableprops.errorCodes.length) {
            case 0:
                throw Error.error(ErrorCode.X_S0501);
            case 1:
                // source file name is the only key without a value
                fileName = tableprops.errorKeys[0].trim();
                break;
            default:
                throw Error.error(ErrorCode.X_S0502);
        }
        // -- Get separators:
        String fs = translateSep(tableprops.getProperty("fs", dbProps.getProperty(HsqlDatabaseProperties.textdb_fs, ",")));
        String vs = translateSep(tableprops.getProperty("vs", dbProps.getProperty(HsqlDatabaseProperties.textdb_vs, fs)));
        String lvs = translateSep(tableprops.getProperty("lvs", dbProps.getProperty(HsqlDatabaseProperties.textdb_lvs, fs)));
        if (fs.length() == 0 || vs.length() == 0 || lvs.length() == 0) {
            throw Error.error(ErrorCode.X_S0503);
        }
    }

    protected void initBuffers() {
        if (isQuoted || isAllQuoted) {
            rowIn = new RowInputTextQuoted(fs, vs, lvs, isAllQuoted);
            rowOut = new RowOutputTextQuoted(fs, vs, lvs, isAllQuoted, stringEncoding);
        } else {
            rowIn = new RowInputText(fs, vs, lvs, false);
            rowOut = new RowOutputText(fs, vs, lvs, false, stringEncoding);
        }
    }

    private static String translateSep(String sep) {
        return translateSep(sep, false);
    }

    /**
     * Translates the escaped characters in a separator string and returns
     * the non-escaped string.
     */
    private static String translateSep(String sep, boolean isProperty) {
        if (sep == null) {
            return null;
        }
        int next = sep.indexOf(BACKSLASH_CHAR);
        if (next != -1) {
            int start = 0;
            char[] sepArray = sep.toCharArray();
            char ch = 0;
            int len = sep.length();
            StringBuffer sb = new StringBuffer(len);
            do {
                sb.append(sepArray, start, next - start);
                start = ++next;
                if (next >= len) {
                    sb.append(BACKSLASH_CHAR);
                    break;
                }
                if (!isProperty) {
                    ch = sepArray[next];
                }
                if (ch == 'n') {
                    sb.append(LF_CHAR);
                    start++;
                } else if (ch == 'r') {
                    sb.append(CR_CHAR);
                    start++;
                } else if (ch == 't') {
                    sb.append('\t');
                    start++;
                } else if (ch == BACKSLASH_CHAR) {
                    sb.append(BACKSLASH_CHAR);
                    start++;
                } else if (ch == 'u') {
                    start++;
                    sb.append((char) Integer.parseInt(sep.substring(start, start + 4), 16));
                    start += 4;
                } else if (sep.startsWith("semi", next)) {
                    sb.append(';');
                    start += 4;
                } else if (sep.startsWith("space", next)) {
                    sb.append(' ');
                    start += 5;
                } else if (sep.startsWith("quote", next)) {
                    sb.append(DOUBLE_QUOTE_CHAR);
                    start += 5;
                } else if (sep.startsWith("apos", next)) {
                    sb.append('\'');
                    start += 4;
                } else {
                    sb.append(BACKSLASH_CHAR);
                    sb.append(sepArray[next]);
                    start++;
                }
            } while ((next = sep.indexOf(BACKSLASH_CHAR, start)) != -1);
            sb.append(sepArray, start, len - start);
            sep = sb.toString();
        }
        return sep;
    }

    /**
     *  Opens a data source file.
     */
    public void open(boolean readonly) {
        fileFreePosition = 0;
        try {
            dataFile = ScaledRAFile.newScaledRAFile(database, fileName, readonly, ScaledRAFile.DATA_FILE_RAF, null, null);
            fileFreePosition = dataFile.length();
            if (fileFreePosition > Integer.MAX_VALUE) {
                throw new HsqlException("", "", 0);
            }
            initBuffers();
        } catch (Exception e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR, ErrorCode.M_TextCache_openning_file_error, new Object[] { fileName, e });
        }
        cacheReadonly = readonly;
    }

    void reopen() {
        open(cacheReadonly);
    }

    /**
     *  Writes newly created rows to disk. In the current implentation,
     *  such rows have already been saved, so this method just removes a
     *  source file that has no rows.
     */
    public synchronized void close(boolean write) {
        if (dataFile == null) {
            return;
        }
        try {
            cache.saveAll();
            boolean empty = (dataFile.length() <= NL.length());
            dataFile.close();
            dataFile = null;
            if (empty && !cacheReadonly) {
                FileUtil.getDefaultInstance().delete(fileName);
            }
        } catch (Exception e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR, ErrorCode.M_TextCache_closing_file_error, new Object[] { fileName, e });
        }
    }

    /**
     * Closes the source file and deletes it if it is not read-only.
     */
    void purge() {
        uncommittedCache.clear();
        try {
            if (cacheReadonly) {
                close(false);
            } else {
                if (dataFile != null) {
                    dataFile.close();
                    dataFile = null;
                }
                FileUtil.getDefaultInstance().delete(fileName);
            }
        } catch (Exception e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR, ErrorCode.M_TextCache_purging_file_error, new Object[] { fileName, e });
        }
    }

    /**
     */
    public synchronized void remove(int pos, PersistentStore store) {
        CachedObject row = (CachedObject) uncommittedCache.remove(pos);
        if (row != null) {
            return;
        }
        row = cache.release(pos);
        clearRowImage(row);
    // release(pos);
    }

    public synchronized void removePersistence(int pos) {
        CachedObject row = (CachedObject) uncommittedCache.get(pos);
        if (row != null) {
            return;
        }
        row = cache.get(pos);
        clearRowImage(row);
    }

    private void clearRowImage(CachedObject row) {
        try {
            int length = row.getStorageSize() - ScriptWriterText.BYTES_LINE_SEP.length;
            rowOut.reset();
            HsqlByteArrayOutputStream out = rowOut.getOutputStream();
            out.fill(' ', length);
            out.write(ScriptWriterText.BYTES_LINE_SEP);
            dataFile.seek(row.getPos());
            dataFile.write(out.getBuffer(), 0, out.size());
        } catch (IOException e) {
            throw Error.runtimeError(ErrorCode.U_S0500, e.getMessage());
        }
    }

    protected synchronized RowInputInterface readObject(int pos) {
        try {
            ByteArray buffer = new ByteArray(80);
            boolean complete = false;
            boolean wasCR = false;
            int c;
            boolean hasQuote = false;
            boolean wasNormal = false;
            pos = findNextUsedLinePos(pos);
            if (pos == -1) {
                return null;
            }
            dataFile.seek(pos);
            while (!complete) {
                wasNormal = false;
                c = dataFile.read();
                if (c == -1) {
                    if (buffer.length() == 0) {
                        return null;
                    }
                    complete = true;
                    if (wasCR) {
                        break;
                    }
                    if (!cacheReadonly) {
                        dataFile.write(ScriptWriterText.BYTES_LINE_SEP, 0, ScriptWriterText.BYTES_LINE_SEP.length);
                    }
                    break;
                }
                switch(c) {
                    case DOUBLE_QUOTE_CHAR:
                        wasNormal = true;
                        complete = wasCR;
                        wasCR = false;
                        if (isQuoted) {
                            hasQuote = !hasQuote;
                        }
                        break;
                    case CR_CHAR:
                        wasCR = !hasQuote;
                        break;
                    case LF_CHAR:
                        complete = !hasQuote;
                        break;
                    default:
                        wasNormal = true;
                        complete = wasCR;
                        wasCR = false;
                }
                buffer.append(c);
            }
            if (complete) {
                int length = (int) dataFile.getFilePointer() - pos;
                if (wasNormal) {
                    length--;
                }
                ((RowInputText) rowIn).setSource(buffer.toString(), pos, length);
                return rowIn;
            }
            return null;
        } catch (IOException e) {
            throw new HsqlException(e.getMessage(), "", 0);
        }
    }

    public int readHeaderLine() {
        boolean complete = false;
        boolean wasCR = false;
        boolean wasNormal = false;
        ByteArray buffer = new ByteArray(80);
        while (!complete) {
            wasNormal = false;
            int c;
            try {
                c = dataFile.read();
                if (c == -1) {
                    if (buffer.length() == 0) {
                        return 0;
                    }
                    complete = true;
                    if (!cacheReadonly) {
                        dataFile.write(ScriptWriterText.BYTES_LINE_SEP, 0, ScriptWriterText.BYTES_LINE_SEP.length);
                    }
                    break;
                }
            } catch (IOException e) {
                throw Error.error(ErrorCode.TEXT_FILE);
            }
            switch(c) {
                case CR_CHAR:
                    wasCR = true;
                    break;
                case LF_CHAR:
                    complete = true;
                    break;
                default:
                    wasNormal = true;
                    complete = wasCR;
                    wasCR = false;
            }
            buffer.append(c);
        }
        header = buffer.toString();
        try {
            int length = (int) dataFile.getFilePointer();
            if (wasNormal) {
                length--;
            }
            return length;
        } catch (IOException e) {
            throw Error.error(ErrorCode.TEXT_FILE);
        }
    }

    // fredt - new method
    /**
     * Searches from file pointer, pos, and finds the beginning of the first
     * line that contains any non-space character. Increments the row counter
     * when a blank line is skipped.
     *
     * If none found return -1
     */
    int findNextUsedLinePos(int pos) {
        try {
            int firstPos = pos;
            int currentPos = pos;
            boolean wasCR = false;
            dataFile.seek(pos);
            while (true) {
                int c = dataFile.read();
                currentPos++;
                switch(c) {
                    case CR_CHAR:
                        wasCR = true;
                        break;
                    case LF_CHAR:
                        wasCR = false;
                        ((RowInputText) rowIn).skippedLine();
                        firstPos = currentPos;
                        break;
                    case ' ':
                        if (wasCR) {
                            wasCR = false;
                            ((RowInputText) rowIn).skippedLine();
                        }
                        break;
                    case -1:
                        return -1;
                    default:
                        return firstPos;
                }
            }
        } catch (IOException e) {
            throw new HsqlException(e.getMessage(), "", 0);
        }
    }

    public synchronized void add(CachedObject object) {
        super.add(object);
        clearRowImage(object);
    }

    public synchronized CachedObject get(int i, PersistentStore store, boolean keep) {
        if (i < 0) {
            return null;
        }
        CachedObject o = (CachedObject) uncommittedCache.get(i);
        if (o == null) {
            o = super.get(i, store, keep);
        }
        /*
        if (o == null) {
            o = super.get(i, store, keep);
        }
*/
        return o;
    }

    /**
     * This is called internally when old rows need to be removed from the
     * cache. Text table rows that have not been saved are those that have not
     * been committed yet. So we don't save them but add them to the
     * uncommitted cache until such time that they are committed or rolled
     * back- fredt
     */
    protected synchronized void saveRows(CachedObject[] rows, int offset, int count) {
        if (count == 0) {
            return;
        }
        for (int i = offset; i < offset + count; i++) {
            CachedObject r = rows[i];
            uncommittedCache.put(r.getPos(), r);
            rows[i] = null;
        }
    }

    /**
     * In case the row has been moved to the uncommittedCache, removes it.
     * Then saves the row as normal.
     */
    public synchronized void saveRow(CachedObject row) {
        uncommittedCache.remove(row.getPos());
        super.saveRow(row);
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        if (ignoreFirst && fileFreePosition == 0) {
            try {
                writeHeader(header);
                this.header = header;
            } catch (HsqlException e) {
                throw new HsqlException(e, Error.getMessage(ErrorCode.GENERAL_IO_ERROR), ErrorCode.GENERAL_IO_ERROR);
            }
            return;
        }
        throw Error.error(ErrorCode.TEXT_TABLE_HEADER);
    }

    private void writeHeader(String header) {
        try {
            byte[] buf = null;
            String firstLine = header + NL;
            try {
                buf = firstLine.getBytes(stringEncoding);
            } catch (UnsupportedEncodingException e) {
                buf = firstLine.getBytes();
            }
            dataFile.write(buf, 0, buf.length);
            fileFreePosition = buf.length;
        } catch (IOException e) {
            throw new HsqlException(e.getMessage(), "", 0);
        }
    }

    private clreplaced ByteArray {

        private byte[] buffer;

        private int buflen;

        public ByteArray(int n) {
            buffer = new byte[n];
            buflen = 0;
        }

        public void append(int c) {
            if (buflen >= buffer.length) {
                byte[] newbuf = new byte[buflen + 80];
                System.arraycopy(buffer, 0, newbuf, 0, buflen);
                buffer = newbuf;
            }
            buffer[buflen] = (byte) c;
            buflen++;
        }

        public int length() {
            return buflen;
        }

        public void setLength(int l) {
            buflen = l;
        }

        public String toString() {
            try {
                return new String(buffer, 0, buflen, stringEncoding);
            } catch (UnsupportedEncodingException e) {
                return new String(buffer, 0, buflen);
            }
        }
    }

    public int getLineNumber() {
        return ((RowInputText) rowIn).getLineNumber();
    }

    protected void setFileModified() {
        fileModified = true;
    }
}

18 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
public void checkUpdate(Table table, boolean[] checkList) {
    if (isFullyAccessibleByRole(table)) {
        return;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right != null && right.canUpdate(table, checkList)) {
        return;
    }
    throw Error.error(ErrorCode.X_42501, table.getName().name);
}

18 View Complete Implementation : Grantee.java
Copyright GNU General Public License v3.0
Author : apavlo
/**
 * Checks if a right represented by the methods
 * have been granted on the specified database object. <p>
 *
 * This is done by checking that a mapping exists in the rights map
 * from the dbobject argument. Otherwise, it throws.
 */
public void checkSelect(Table table, boolean[] checkList) {
    if (isFullyAccessibleByRole(table)) {
        return;
    }
    Right right = (Right) fullRightsMap.get(table.getName());
    if (right != null && right.canSelect(table, checkList)) {
        return;
    }
    throw Error.error(ErrorCode.X_42501, table.getName().name);
}

17 View Complete Implementation : Log.java
Copyright GNU General Public License v3.0
Author : apavlo
void writeInsertStatement(Session session, Table t, Object[] row) {
    try {
        dbLogWriter.writeInsertStatement(session, t, row);
    } catch (IOException e) {
        throw Error.error(ErrorCode.FILE_IO_ERROR, logFileName);
    }
    if (maxLogSize > 0 && dbLogWriter.size() > maxLogSize) {
        database.logger.needsCheckpoint = true;
    }
}

17 View Complete Implementation : Log.java
Copyright GNU General Public License v3.0
Author : apavlo
DataFileCache openTextCache(Table table, String source, boolean readOnlyData, boolean reversed) {
    closeTextCache(table);
    if (!properties.isPropertyTrue(HsqlDatabaseProperties.textdb_allow_full_path)) {
        if (source.indexOf("..") != -1) {
            throw (Error.error(ErrorCode.ACCESS_IS_DENIED, source));
        }
        String path = new File(new File(database.getPath() + ".properties").getAbsolutePath()).getParent();
        if (path != null) {
            source = path + File.separator + source;
        }
    }
    TextCache c;
    // checks are performed separately as TextChar constructor cannot throw
    TextCache.checkTextSouceString(source, database.getProperties());
    if (reversed) {
        c = new TextCache(table, source);
    } else {
        c = new TextCache(table, source);
    }
    c.open(readOnlyData || filesReadOnly);
    textCacheList.put(table.getName(), c);
    return c;
}