use of org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList in project derby by apache.
the class ConsistencyChecker method checkTable.
/**
* Check the named table, ensuring that all of its indexes are consistent
* with the base table.
* Use this
* method only within an SQL-J statement; do not call it directly.
* <P>When tables are consistent, the method returns true. Otherwise, the method throws an exception.
* <p>To check the consistency of a single table:
* <p><code>
* VALUES ConsistencyChecker::checkTable(<i>SchemaName</i>, <i>TableName</i>)</code></p>
* <P>For example, to check the consistency of the table <i>APP.Flights</i>:
* <p><code>
* VALUES ConsistencyChecker::checkTable('APP', 'FLIGHTS')</code></p>
* <p>To check the consistency of all of the tables in the 'APP' schema,
* stopping at the first failure:
*
* <P><code>SELECT tablename, ConsistencyChecker::checkTable(<br>
* 'APP', tablename)<br>
* FROM sys.sysschemas s, sys.systables t
* WHERE s.schemaname = 'APP' AND s.schemaid = t.schemaid</code>
*
* <p> To check the consistency of an entire database, stopping at the first failure:
*
* <p><code>SELECT schemaname, tablename,<br>
* ConsistencyChecker::checkTable(schemaname, tablename)<br>
* FROM sys.sysschemas s, sys.systables t<br>
* WHERE s.schemaid = t.schemaid</code>
*
* @param schemaName The schema name of the table.
* @param tableName The name of the table
*
* @return true, if the table is consistent, exception thrown if inconsistent
*
* @exception SQLException Thrown if some inconsistency
* is found, or if some unexpected
* exception is thrown..
*/
public static boolean checkTable(String schemaName, String tableName) throws SQLException {
DataDictionary dd;
TableDescriptor td;
long baseRowCount = -1;
TransactionController tc;
ConglomerateDescriptor heapCD;
ConglomerateDescriptor indexCD;
ExecRow baseRow;
ExecRow indexRow;
RowLocation rl = null;
RowLocation scanRL = null;
ScanController scan = null;
int[] baseColumnPositions;
int baseColumns = 0;
DataValueFactory dvf;
long indexRows;
ConglomerateController baseCC = null;
ConglomerateController indexCC = null;
SchemaDescriptor sd;
ConstraintDescriptor constraintDesc;
LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC();
tc = lcc.getTransactionExecute();
try {
// make sure that application code doesn't bypass security checks
// by calling this public entry point
SecurityUtil.authorize(Securable.CHECK_TABLE);
dd = lcc.getDataDictionary();
dvf = lcc.getDataValueFactory();
ExecutionFactory ef = lcc.getLanguageConnectionFactory().getExecutionFactory();
sd = dd.getSchemaDescriptor(schemaName, tc, true);
td = dd.getTableDescriptor(tableName, sd, tc);
if (td == null) {
throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND, schemaName + "." + tableName);
}
/* Skip views */
if (td.getTableType() == TableDescriptor.VIEW_TYPE) {
return true;
}
/* Open the heap for reading */
baseCC = tc.openConglomerate(td.getHeapConglomerateId(), false, 0, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE);
/* Check the consistency of the heap */
baseCC.checkConsistency();
heapCD = td.getConglomerateDescriptor(td.getHeapConglomerateId());
/* Get a row template for the base table */
baseRow = ef.getValueRow(td.getNumberOfColumns());
/* Fill the row with nulls of the correct type */
ColumnDescriptorList cdl = td.getColumnDescriptorList();
int cdlSize = cdl.size();
for (int index = 0; index < cdlSize; index++) {
ColumnDescriptor cd = (ColumnDescriptor) cdl.elementAt(index);
baseRow.setColumn(cd.getPosition(), cd.getType().getNull());
}
/* Look at all the indexes on the table */
ConglomerateDescriptor[] cds = td.getConglomerateDescriptors();
for (int index = 0; index < cds.length; index++) {
indexCD = cds[index];
/* Skip the heap */
if (!indexCD.isIndex())
continue;
/* Check the internal consistency of the index */
indexCC = tc.openConglomerate(indexCD.getConglomerateNumber(), false, 0, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE);
indexCC.checkConsistency();
indexCC.close();
indexCC = null;
if (indexCD.isConstraint()) {
constraintDesc = dd.getConstraintDescriptor(td, indexCD.getUUID());
if (constraintDesc == null) {
throw StandardException.newException(SQLState.LANG_OBJECT_NOT_FOUND, "CONSTRAINT for INDEX", indexCD.getConglomerateName());
}
}
/*
** Set the base row count when we get to the first index.
** We do this here, rather than outside the index loop, so
** we won't do the work of counting the rows in the base table
** if there are no indexes to check.
*/
if (baseRowCount < 0) {
scan = tc.openScan(heapCD.getConglomerateNumber(), // hold
false, // not forUpdate
0, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE, RowUtil.EMPTY_ROW_BITSET, // startKeyValue
null, // not used with null start posn.
0, // qualifier
null, // stopKeyValue
null, // not used with null stop posn.
0);
/* Also, get the row location template for index rows */
rl = scan.newRowLocationTemplate();
scanRL = scan.newRowLocationTemplate();
for (baseRowCount = 0; scan.next(); baseRowCount++) ;
/* Empty statement */
scan.close();
scan = null;
}
baseColumnPositions = indexCD.getIndexDescriptor().baseColumnPositions();
baseColumns = baseColumnPositions.length;
FormatableBitSet indexColsBitSet = new FormatableBitSet();
for (int i = 0; i < baseColumns; i++) {
indexColsBitSet.grow(baseColumnPositions[i]);
indexColsBitSet.set(baseColumnPositions[i] - 1);
}
/* Get one row template for the index scan, and one for the fetch */
indexRow = ef.getValueRow(baseColumns + 1);
/* Fill the row with nulls of the correct type */
for (int column = 0; column < baseColumns; column++) {
/* Column positions in the data dictionary are one-based */
ColumnDescriptor cd = td.getColumnDescriptor(baseColumnPositions[column]);
indexRow.setColumn(column + 1, cd.getType().getNull());
}
/* Set the row location in the last column of the index row */
indexRow.setColumn(baseColumns + 1, rl);
/* Do a full scan of the index */
scan = tc.openScan(indexCD.getConglomerateNumber(), // hold
false, // not forUpdate
0, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE, (FormatableBitSet) null, // startKeyValue
null, // not used with null start posn.
0, // qualifier
null, // stopKeyValue
null, // not used with null stop posn.
0);
DataValueDescriptor[] baseRowIndexOrder = new DataValueDescriptor[baseColumns];
DataValueDescriptor[] baseObjectArray = baseRow.getRowArray();
for (int i = 0; i < baseColumns; i++) {
baseRowIndexOrder[i] = baseObjectArray[baseColumnPositions[i] - 1];
}
/* Get the index rows and count them */
for (indexRows = 0; scan.fetchNext(indexRow.getRowArray()); indexRows++) {
/*
** Get the base row using the RowLocation in the index row,
** which is in the last column.
*/
RowLocation baseRL = (RowLocation) indexRow.getColumn(baseColumns + 1);
boolean base_row_exists = baseCC.fetch(baseRL, baseObjectArray, indexColsBitSet);
/* Throw exception if fetch() returns false */
if (!base_row_exists) {
String indexName = indexCD.getConglomerateName();
throw StandardException.newException(SQLState.LANG_INCONSISTENT_ROW_LOCATION, (schemaName + "." + tableName), indexName, baseRL.toString(), indexRow.toString());
}
/* Compare all the column values */
for (int column = 0; column < baseColumns; column++) {
DataValueDescriptor indexColumn = indexRow.getColumn(column + 1);
DataValueDescriptor baseColumn = baseRowIndexOrder[column];
/*
** With this form of compare(), null is considered equal
** to null.
*/
if (indexColumn.compare(baseColumn) != 0) {
ColumnDescriptor cd = td.getColumnDescriptor(baseColumnPositions[column]);
throw StandardException.newException(SQLState.LANG_INDEX_COLUMN_NOT_EQUAL, indexCD.getConglomerateName(), td.getSchemaName(), td.getName(), baseRL.toString(), cd.getColumnName(), indexColumn.toString(), baseColumn.toString(), indexRow.toString());
}
}
}
/* Clean up after the index scan */
scan.close();
scan = null;
/*
** The index is supposed to have the same number of rows as the
** base conglomerate.
*/
if (indexRows != baseRowCount) {
throw StandardException.newException(SQLState.LANG_INDEX_ROW_COUNT_MISMATCH, indexCD.getConglomerateName(), td.getSchemaName(), td.getName(), Long.toString(indexRows), Long.toString(baseRowCount));
}
}
/* check that all constraints have backing index */
ConstraintDescriptorList constraintDescList = dd.getConstraintDescriptors(td);
for (int index = 0; index < constraintDescList.size(); index++) {
constraintDesc = constraintDescList.elementAt(index);
if (constraintDesc.hasBackingIndex()) {
ConglomerateDescriptor conglomDesc;
conglomDesc = td.getConglomerateDescriptor(constraintDesc.getConglomerateId());
if (conglomDesc == null) {
throw StandardException.newException(SQLState.LANG_OBJECT_NOT_FOUND, "INDEX for CONSTRAINT", constraintDesc.getConstraintName());
}
}
}
} catch (StandardException se) {
throw PublicAPI.wrapStandardException(se);
} finally {
try {
/* Clean up before we leave */
if (baseCC != null) {
baseCC.close();
baseCC = null;
}
if (indexCC != null) {
indexCC.close();
indexCC = null;
}
if (scan != null) {
scan.close();
scan = null;
}
} catch (StandardException se) {
throw PublicAPI.wrapStandardException(se);
}
}
return true;
}
use of org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList in project derby by apache.
the class DataDictionaryImpl method addSystemTableToDictionary.
/**
* Add the required entries to the data dictionary for a System table.
*/
private void addSystemTableToDictionary(TabInfoImpl ti, SchemaDescriptor sd, TransactionController tc, DataDescriptorGenerator ddg) throws StandardException {
CatalogRowFactory crf = ti.getCatalogRowFactory();
String name = ti.getTableName();
long conglomId = ti.getHeapConglomerate();
SystemColumn[] columnList = crf.buildColumnList();
UUID heapUUID = crf.getCanonicalHeapUUID();
String heapName = crf.getCanonicalHeapName();
TableDescriptor td;
UUID toid;
int columnCount;
SystemColumn column;
// add table to the data dictionary
columnCount = columnList.length;
td = ddg.newTableDescriptor(name, sd, TableDescriptor.SYSTEM_TABLE_TYPE, TableDescriptor.ROW_LOCK_GRANULARITY);
td.setUUID(crf.getCanonicalTableUUID());
addDescriptor(td, sd, SYSTABLES_CATALOG_NUM, false, tc);
toid = td.getUUID();
/* Add the conglomerate for the heap */
ConglomerateDescriptor cgd = ddg.newConglomerateDescriptor(conglomId, heapName, false, null, false, heapUUID, toid, sd.getUUID());
addDescriptor(cgd, sd, SYSCONGLOMERATES_CATALOG_NUM, false, tc);
/* Create the columns */
ColumnDescriptor[] cdlArray = new ColumnDescriptor[columnCount];
for (int columnNumber = 0; columnNumber < columnCount; columnNumber++) {
column = columnList[columnNumber];
if (SanityManager.DEBUG) {
if (column == null) {
SanityManager.THROWASSERT("column " + columnNumber + " for table " + ti.getTableName() + " is null");
}
}
cdlArray[columnNumber] = makeColumnDescriptor(column, columnNumber + 1, td);
}
addDescriptorArray(cdlArray, td, SYSCOLUMNS_CATALOG_NUM, false, tc);
// now add the columns to the cdl of the table.
ColumnDescriptorList cdl = td.getColumnDescriptorList();
for (int i = 0; i < columnCount; i++) cdl.add(cdlArray[i]);
}
use of org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList in project derby by apache.
the class DataDictionaryImpl method getColumnDescriptorsScan.
/**
* Populate the ColumnDescriptorList for the specified TableDescriptor.
*
* MT synchronization: it is assumed that the caller has synchronized
* on the CDL in the given TD.
*
* @param uuid The referencing UUID
* @param cdl The column descriptor list
* @param td The parent tuple descriptor
*
* @exception StandardException Thrown on failure
*/
private void getColumnDescriptorsScan(UUID uuid, ColumnDescriptorList cdl, TupleDescriptor td) throws StandardException {
ColumnDescriptor cd;
ColumnDescriptorList cdlCopy = new ColumnDescriptorList();
DataValueDescriptor refIDOrderable = null;
TabInfoImpl ti = coreInfo[SYSCOLUMNS_CORE_NUM];
/* Use refIDOrderable in both start and stop position for scan. */
refIDOrderable = getIDValueAsCHAR(uuid);
/* Set up the start/stop position for the scan */
ExecIndexRow keyRow = exFactory.getIndexableRow(1);
keyRow.setColumn(1, refIDOrderable);
getDescriptorViaIndex(SYSCOLUMNSRowFactory.SYSCOLUMNS_INDEX1_ID, keyRow, (ScanQualifier[][]) null, ti, td, cdl, ColumnDescriptor.class, false);
/* The TableDescriptor's column descriptor list must be ordered by
* columnNumber. (It is probably not ordered correctly at this point due
* to the index on syscolumns being on (tableId, columnName).) The
* cheapest way to reorder the list appears to be to copy it (above), and then
* walk the copy and put the elements back into the original in the
* expected locations.
*/
int cdlSize = cdl.size();
for (int index = 0; index < cdlSize; index++) {
cdlCopy.add(cdl.get(index));
}
for (int index = 0; index < cdlSize; index++) {
cd = (ColumnDescriptor) cdlCopy.elementAt(index);
cdl.set(cd.getPosition() - 1, cd);
}
}
use of org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList in project derby by apache.
the class DataDictionaryImpl method getSPSParams.
/**
* Get all the parameter descriptors for an SPS.
* Look up the params in SYSCOLUMNS and turn them
* into parameter descriptors.
*
* @param spsd sps descriptor
* @param defaults list for storing column defaults
*
* @return array of data type descriptors
*
* @exception StandardException Thrown on error
*/
public DataTypeDescriptor[] getSPSParams(SPSDescriptor spsd, List<DataValueDescriptor> defaults) throws StandardException {
ColumnDescriptorList cdl = new ColumnDescriptorList();
getColumnDescriptorsScan(spsd.getUUID(), cdl, spsd);
int cdlSize = cdl.size();
DataTypeDescriptor[] params = new DataTypeDescriptor[cdlSize];
for (int index = 0; index < cdlSize; index++) {
ColumnDescriptor cd = (ColumnDescriptor) cdl.elementAt(index);
params[index] = cd.getType();
if (defaults != null) {
defaults.add(cd.getDefaultValue());
}
}
return params;
}
use of org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList in project derby by apache.
the class InsertNode method generate.
/**
* Code generation for insert
* creates an expression for:
* ResultSetFactory.getInsertResultSet(resultSet.generate(ps), generationClausesResult, checkConstrainResult, this )
*
* @param acb The ActivationClassBuilder for the class being built
* @param mb the method for the execute() method to be built
*
* @exception StandardException Thrown on error
*/
@Override
void generate(ActivationClassBuilder acb, MethodBuilder mb) throws StandardException {
// If the DML is on the temporary table, generate the code to
// mark temporary table as modified in the current UOW. After
// DERBY-827 this must be done in execute() since
// createResultSet() will only be called once.
generateCodeForTemporaryTable(acb);
/* generate the parameters */
generateParameterValueSet(acb);
// Base table
if (targetTableDescriptor != null) {
/*
** Generate the insert result set, giving it either the original
** source or the normalize result set, the constant action,
** and "this".
*/
acb.pushGetResultSetFactoryExpression(mb);
// arg 1
if (inMatchingClause()) {
matchingClause.generateResultSetField(acb, mb);
} else {
resultSet.generate(acb, mb);
}
// arg 2 generate code to evaluate generation clauses
generateGenerationClauses(resultColumnList, resultSet.getResultSetNumber(), false, acb, mb);
// arg 3 generate code to evaluate CHECK CONSTRAINTS
generateCheckConstraints(checkConstraints, acb, mb);
// arg 4 row template used by bulk insert
if (bulkInsert) {
ColumnDescriptorList cdl = targetTableDescriptor.getColumnDescriptorList();
ExecRowBuilder builder = new ExecRowBuilder(cdl.size(), false);
for (int i = 0; i < cdl.size(); i++) {
ColumnDescriptor cd = cdl.get(i);
builder.setColumn(i + 1, cd.getType());
}
mb.push(acb.addItem(builder));
} else {
mb.push(-1);
}
// arg 5, 6 table name
if (targetTableName.getSchemaName() == null) {
mb.pushNull("java.lang.String");
} else {
mb.push(targetTableName.getSchemaName());
}
mb.push(targetTableName.getTableName());
mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getInsertResultSet", ClassName.ResultSet, 6);
} else {
/* Generate code for the VTI
* NOTE: we need to create a dummy cost estimate for the
* targetVTI since we never optimized it.
* RESOLVEVTI - we will have to optimize it in order to
* push predicates into the VTI.
*/
targetVTI.assignCostEstimate(resultSet.getNewCostEstimate());
/*
** Generate the insert VTI result set, giving it either the original
** source or the normalize result set, the constant action,
*/
acb.pushGetResultSetFactoryExpression(mb);
// arg 1
resultSet.generate(acb, mb);
// arg 2
targetVTI.generate(acb, mb);
mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getInsertVTIResultSet", ClassName.ResultSet, 2);
}
}
Aggregations