use of org.apache.derby.catalog.UUID in project derby by apache.
the class InsertResultSet method setUpAllSorts.
/**
* Set up to update all of the indexes on a table when doing a bulk insert
* on an empty table.
*
* @exception StandardException thrown on error
*/
private void setUpAllSorts(ExecRow sourceRow, RowLocation rl) throws StandardException {
int numIndexes = constants.irgs.length;
int numColumns = td.getNumberOfColumns();
ordering = new ColumnOrdering[numIndexes][];
collation = new int[numIndexes][];
needToDropSort = new boolean[numIndexes];
sortIds = new long[numIndexes];
rowSources = new RowLocationRetRowSource[numIndexes];
// indexedCols is 1-based
indexedCols = new FormatableBitSet(numColumns + 1);
/* For each index, build a single index row, collation templage,
* and a sorter.
*/
for (int index = 0; index < numIndexes; index++) {
// Update the bit map of indexed columns
int[] keyColumns = constants.irgs[index].baseColumnPositions();
for (int i2 = 0; i2 < keyColumns.length; i2++) {
// indexedCols is 1-based
indexedCols.set(keyColumns[i2]);
}
// create a single index row template for each index
indexRows[index] = constants.irgs[index].getIndexRowTemplate();
// Get an index row based on the base row
// (This call is only necessary here because we need to
// pass a template to the sorter.)
constants.irgs[index].getIndexRow(sourceRow, rl, indexRows[index], (FormatableBitSet) null);
/* For non-unique indexes, we order by all columns + the RID.
* For unique indexes, we just order by the columns.
* We create a unique index observer for unique indexes
* so that we can catch duplicate key
*/
// Get the ConglomerateDescriptor for the index
ConglomerateDescriptor cd = td.getConglomerateDescriptor(constants.indexCIDS[index]);
int[] baseColumnPositions = constants.irgs[index].baseColumnPositions();
boolean[] isAscending = constants.irgs[index].isAscending();
int numColumnOrderings;
SortObserver sortObserver;
/* We can only reuse the wrappers when doing an
* external sort if there is only 1 index. Otherwise,
* we could get in a situation where 1 sort reuses a
* wrapper that is still in use in another sort.
*/
boolean reuseWrappers = (numIndexes == 1);
final IndexRowGenerator indDes = cd.getIndexDescriptor();
Properties sortProperties = null;
String indexOrConstraintName = cd.getConglomerateName();
boolean deferred = false;
boolean deferrable = false;
UUID uniqueDeferrableConstraintId = null;
if (cd.isConstraint()) {
// so, the index is backing up a constraint
ConstraintDescriptor conDesc = dd.getConstraintDescriptor(td, cd.getUUID());
indexOrConstraintName = conDesc.getConstraintName();
deferred = lcc.isEffectivelyDeferred(lcc.getCurrentSQLSessionContext(activation), conDesc.getUUID());
deferrable = conDesc.deferrable();
uniqueDeferrableConstraintId = conDesc.getUUID();
}
if (indDes.isUnique() || indDes.isUniqueDeferrable()) {
numColumnOrderings = indDes.isUnique() ? baseColumnPositions.length : baseColumnPositions.length + 1;
sortObserver = new UniqueIndexSortObserver(lcc, uniqueDeferrableConstraintId, // don't clone rows
false, deferrable, deferred, indexOrConstraintName, indexRows[index], reuseWrappers, td.getName());
} else if (indDes.isUniqueWithDuplicateNulls()) {
numColumnOrderings = baseColumnPositions.length + 1;
// tell transaction controller to use the unique with
// duplicate nulls sorter, when making createSort() call.
sortProperties = new Properties();
sortProperties.put(AccessFactoryGlobals.IMPL_TYPE, AccessFactoryGlobals.SORT_UNIQUEWITHDUPLICATENULLS_EXTERNAL);
// use sort operator which treats nulls unequal
sortObserver = new UniqueWithDuplicateNullsIndexSortObserver(lcc, uniqueDeferrableConstraintId, true, deferrable, deferred, indexOrConstraintName, indexRows[index], true, td.getName());
} else {
numColumnOrderings = baseColumnPositions.length + 1;
sortObserver = new BasicSortObserver(false, false, indexRows[index], reuseWrappers);
}
ordering[index] = new ColumnOrdering[numColumnOrderings];
for (int ii = 0; ii < isAscending.length; ii++) {
ordering[index][ii] = new IndexColumnOrder(ii, isAscending[ii]);
}
if (numColumnOrderings > isAscending.length) {
ordering[index][isAscending.length] = new IndexColumnOrder(isAscending.length);
}
// set collation templates for later index creation
// call (createAndLoadConglomerate())
collation[index] = constants.irgs[index].getColumnCollationIds(td.getColumnDescriptorList());
// create the sorters
sortIds[index] = tc.createSort(sortProperties, indexRows[index].getRowArrayClone(), ordering[index], sortObserver, // not in order
false, // est rows
(int) sourceResultSet.getEstimatedRowCount(), // est row size, -1 means no idea
-1);
needToDropSort[index] = true;
}
sorters = new SortController[numIndexes];
// Open the sorts
for (int index = 0; index < numIndexes; index++) {
sorters[index] = tc.openSort(sortIds[index]);
needToDropSort[index] = true;
}
}
use of org.apache.derby.catalog.UUID in project derby by apache.
the class ReferencedKeyRIChecker method doCheck.
/**
* Check that the row either has a null column(s), or
* has no corresponding foreign keys.
* <p>
* If a foreign key is found, an exception is thrown.
* If not, the scan is closed.
*
* @param a the activation
* @param row the row to check
* @param restrictCheckOnly
* {@code true} if the check is relevant only for RESTRICTED
* referential action.
* @param deferredRowReq
* For referenced keys: The required number of duplicates that
* need to be present. Only used if {@code postCheck==false}.
*
* @exception StandardException on unexpected error, or
* on a primary/unique key violation
*/
@Override
void doCheck(Activation a, ExecRow row, boolean restrictCheckOnly, int deferredRowReq) throws StandardException {
/*
** If any of the columns are null, then the
** check always succeeds.
*/
if (isAnyFieldNull(row)) {
return;
}
if (fkInfo.refConstraintIsDeferrable) {
// violated. DERBY-6559
if (lcc.isEffectivelyDeferred(lcc.getCurrentSQLSessionContext(a), fkInfo.refConstraintID)) {
if (restrictCheckOnly) {
rememberKey(row);
return;
} else {
// rows code path, so go see if we have enough rows
if (isDuplicated(row, deferredRowReq)) {
return;
}
}
}
}
/*
** Otherwise, should be no rows found.
** Check each conglomerate.
*/
ScanController scan;
for (int i = 0; i < fkInfo.fkConglomNumbers.length; i++) {
if (restrictCheckOnly) {
if (fkInfo.raRules[i] != StatementType.RA_RESTRICT)
continue;
}
scan = getScanController(fkInfo.fkConglomNumbers[i], fkScocis[i], fkDcocis[i], row);
if (scan.next()) {
close();
final UUID fkId = fkInfo.fkIds[i];
// NO ACTION. CASCADE and SET NULL handled elsewhere.
if (fkInfo.deferrable[i] && fkInfo.raRules[i] != StatementType.RA_RESTRICT && lcc.isEffectivelyDeferred(lcc.getCurrentSQLSessionContext(a), fkId)) {
deferredRowsHashTable = DeferredConstraintsMemory.rememberFKViolation(lcc, deferredRowsHashTable, fkInfo.fkIds[i], indexQualifierRow.getRowArray(), fkInfo.schemaName, fkInfo.tableName);
} else {
StandardException se = StandardException.newException(SQLState.LANG_FK_VIOLATION, fkInfo.fkConstraintNames[i], fkInfo.tableName, StatementUtil.typeName(fkInfo.stmtType), RowUtil.toString(row, fkInfo.colArray));
throw se;
}
}
/*
** Move off of the current row to release any locks.
*/
scan.next();
}
}
use of org.apache.derby.catalog.UUID in project derby by apache.
the class TableDescriptor method statisticsExist.
/**
* Are there statistics for this particular conglomerate.
*
* @param cd Conglomerate/Index for which we want to check if statistics
* exist. cd can be null in which case user wants to know if there are any
* statistics at all on the table.
*/
public boolean statisticsExist(ConglomerateDescriptor cd) throws StandardException {
List<StatisticsDescriptor> sdl = getStatistics();
if (cd == null)
return (sdl.size() > 0);
UUID cdUUID = cd.getUUID();
for (StatisticsDescriptor statDesc : sdl) {
if (cdUUID.equals(statDesc.getReferenceID())) {
return true;
}
}
return false;
}
use of org.apache.derby.catalog.UUID in project derby by apache.
the class DMLModStatementNode method generateFKInfo.
/**
* Generate the FKInfo structures used during code generation.
* For each constraint that isn't a check constraint, add another
* one of these FKInfo structures and then package them up into
* a single array.
*
* @param cdl The constraint descriptor list
* @param dd The DataDictionary
* @param td The TableDescriptor
* @param readColsBitSet columns read
*
* @exception StandardException Thrown on failure
*/
private void generateFKInfo(ConstraintDescriptorList cdl, DataDictionary dd, TableDescriptor td, FormatableBitSet readColsBitSet) throws StandardException {
ArrayList<FKInfo> fkList = new ArrayList<FKInfo>();
int type;
UUID[] uuids;
long[] conglomNumbers;
String[] fkNames;
ConstraintDescriptorList fkcdl;
ReferencedKeyConstraintDescriptor refcd;
boolean[] isSelfReferencingFK;
ConstraintDescriptorList activeList = dd.getActiveConstraintDescriptors(cdl);
int[] rowMap = getRowMap(readColsBitSet, td);
int[] raRules;
boolean[] deferrable;
UUID[] fkIds;
ArrayList<String> refSchemaNames = new ArrayList<String>(1);
ArrayList<String> refTableNames = new ArrayList<String>(1);
ArrayList<Long> refIndexConglomNum = new ArrayList<Long>(1);
ArrayList<Integer> refActions = new ArrayList<Integer>(1);
ArrayList<ColumnDescriptorList> refColDescriptors = new ArrayList<ColumnDescriptorList>(1);
ArrayList<int[]> fkColMap = new ArrayList<int[]>(1);
int activeSize = activeList.size();
for (int index = 0; index < activeSize; index++) {
ConstraintDescriptor cd = activeList.elementAt(index);
if (cd instanceof ForeignKeyConstraintDescriptor) {
/*
** We are saving information for checking the
** primary/unique key that is referenced by this
** foreign key, so type is FOREIGN KEY.
*/
type = FKInfo.FOREIGN_KEY;
refcd = ((ForeignKeyConstraintDescriptor) cd).getReferencedConstraint();
uuids = new UUID[1];
deferrable = new boolean[1];
fkIds = new UUID[1];
conglomNumbers = new long[1];
fkNames = new String[1];
isSelfReferencingFK = new boolean[1];
raRules = new int[1];
fkSetupArrays(dd, (ForeignKeyConstraintDescriptor) cd, 0, uuids, conglomNumbers, fkNames, isSelfReferencingFK, raRules, deferrable, fkIds);
// oops, get the right constraint name -- for error
// handling we want the FK name, not refcd name
fkNames[0] = cd.getConstraintName();
} else if (cd instanceof ReferencedKeyConstraintDescriptor) {
refcd = (ReferencedKeyConstraintDescriptor) cd;
/*
** We are saving information for checking the
** foreign key(s) that is dependent on this referenced
** key, so type is REFERENCED KEY.
*/
type = FKInfo.REFERENCED_KEY;
fkcdl = dd.getActiveConstraintDescriptors(((ReferencedKeyConstraintDescriptor) cd).getForeignKeyConstraints(ConstraintDescriptor.ENABLED));
int size = fkcdl.size();
if (size == 0) {
continue;
}
uuids = new UUID[size];
deferrable = new boolean[size];
fkIds = new UUID[size];
fkNames = new String[size];
conglomNumbers = new long[size];
isSelfReferencingFK = new boolean[size];
raRules = new int[size];
TableDescriptor fktd;
ColumnDescriptorList coldl;
int[] refColumns;
ColumnDescriptor cold;
int[] colArray = remapReferencedColumns(cd, rowMap);
for (int inner = 0; inner < size; inner++) {
ForeignKeyConstraintDescriptor fkcd = (ForeignKeyConstraintDescriptor) fkcdl.elementAt(inner);
fkSetupArrays(dd, fkcd, inner, uuids, conglomNumbers, fkNames, isSelfReferencingFK, raRules, deferrable, fkIds);
if ((raRules[inner] == StatementType.RA_CASCADE) || (raRules[inner] == StatementType.RA_SETNULL)) {
// find the referencing table Name
fktd = fkcd.getTableDescriptor();
refSchemaNames.add(fktd.getSchemaName());
refTableNames.add(fktd.getName());
refActions.add(Integer.valueOf(raRules[inner]));
// find the referencing column name required for update null.
refColumns = fkcd.getReferencedColumns();
coldl = fktd.getColumnDescriptorList();
ColumnDescriptorList releventColDes = new ColumnDescriptorList();
for (int i = 0; i < refColumns.length; i++) {
cold = coldl.elementAt(refColumns[i] - 1);
releventColDes.add(cold);
}
refColDescriptors.add(releventColDes);
refIndexConglomNum.add(Long.valueOf(conglomNumbers[inner]));
fkColMap.add(colArray);
}
}
} else {
continue;
}
final TableDescriptor pktd = refcd.getTableDescriptor();
final UUID pkIndexId = refcd.getIndexId();
final ConglomerateDescriptor pkIndexConglom = pktd.getConglomerateDescriptor(pkIndexId);
final TableDescriptor refTd = cd.getTableDescriptor();
fkList.add(new FKInfo(// foreign key names
fkNames, cd.getSchemaDescriptor().getSchemaName(), // table being modified
refTd.getName(), // INSERT|UPDATE|DELETE
statementType, // FOREIGN_KEY|REFERENCED_KEY
type, // referenced backing index uuid
pkIndexId, pkIndexConglom.getConglomerateNumber(), // referenced backing index conglom
refcd.getUUID(), // referenced constraint is
refcd.deferrable(), // fk backing index uuids
uuids, // fk backing index congloms
conglomNumbers, // is self ref array of bool
isSelfReferencingFK, remapReferencedColumns(cd, rowMap), // columns referenced by key
dd.getRowLocationTemplate(getLanguageConnectionContext(), refTd), // referential action rules
raRules, // deferrable flags
deferrable, // UUID of fks
fkIds));
}
// Now convert the list into an array.
if (!fkList.isEmpty()) {
fkInfo = fkList.toArray(new FKInfo[fkList.size()]);
}
// Convert the ref action info lists to arrays.
int size = refActions.size();
if (size > 0) {
fkTableNames = new String[size];
fkSchemaNames = new String[size];
fkRefActions = new int[size];
fkColDescriptors = new ColumnDescriptorList[size];
fkIndexConglomNumbers = new long[size];
fkColArrays = new int[size][];
for (int i = 0; i < size; i++) {
fkTableNames[i] = refTableNames.get(i);
fkSchemaNames[i] = refSchemaNames.get(i);
fkRefActions[i] = (refActions.get(i)).intValue();
fkColDescriptors[i] = refColDescriptors.get(i);
fkIndexConglomNumbers[i] = (refIndexConglomNum.get(i)).longValue();
fkColArrays[i] = (fkColMap.get(i));
}
}
}
use of org.apache.derby.catalog.UUID in project derby by apache.
the class FromVTI method bindVTITables.
// end of getVTIName
/**
* Bind this VTI that appears in the FROM list.
*
* @param fromListParam FromList to use/append to.
*
* @return ResultSetNode The bound FromVTI.
*
* @exception StandardException Thrown on error
*/
@Override
ResultSetNode bindVTITables(FromList fromListParam) throws StandardException {
ResultColumnList derivedRCL = getResultColumns();
LanguageConnectionContext lcc = getLanguageConnectionContext();
/* NOTE - setting of table number moved to FromList.bindTables()
* in order to avoid an ordering problem with join columns in
* parameters.
*/
/* Bind the constructor or static method - does basic error checking.
* Correlated subqueries are not allowed as parameters to
* a VTI, so pass an empty FromList.
*/
ArrayList<AggregateNode> aggregates = new ArrayList<AggregateNode>();
methodCall.bindExpression(fromListParam, subqueryList, aggregates);
// Is the parameter list to the constructor valid for a VTI?
methodParms = methodCall.getMethodParms();
RoutineAliasInfo routineInfo = methodCall.getRoutineInfo();
if ((routineInfo != null) && routineInfo.getReturnType().isRowMultiSet() && (routineInfo.getParameterStyle() == RoutineAliasInfo.PS_DERBY_JDBC_RESULT_SET)) {
isDerbyStyleTableFunction = true;
}
if (isDerbyStyleTableFunction) {
Method boundMethod = (Method) methodCall.getResolvedMethod();
isRestrictedTableFunction = RestrictedVTI.class.isAssignableFrom(boundMethod.getReturnType());
}
if (isConstructor()) {
NewInvocationNode constructor = (NewInvocationNode) methodCall;
if (!constructor.assignableTo("java.sql.PreparedStatement")) {
if (version2) {
throw StandardException.newException(SQLState.LANG_DOES_NOT_IMPLEMENT, getVTIName(), "java.sql.PreparedStatement");
} else if (!constructor.assignableTo("java.sql.ResultSet")) {
throw StandardException.newException(SQLState.LANG_DOES_NOT_IMPLEMENT, getVTIName(), "java.sql.ResultSet");
}
} else {
version2 = true;
}
/* If this is a version 2 VTI */
if (version2) {
// Does it support predicates
implementsPushable = constructor.assignableTo("org.apache.derby.vti.IQualifyable");
}
// Remember whether or not the VTI implements the VTICosting interface
implementsVTICosting = constructor.assignableTo(ClassName.VTICosting);
}
if (isDerbyStyleTableFunction) {
implementsVTICosting = implementsDerbyStyleVTICosting(methodCall.getJavaClassName());
}
/* Build the RCL for this VTI. We instantiate an object in order
* to get the ResultSetMetaData.
*
* If we have a special trigger vti, then we branch off and get
* its rcl from the trigger table that is waiting for us in
* the compiler context.
*/
UUID triggerTableId;
if ((isConstructor()) && ((triggerTableId = getSpecialTriggerVTITableName(lcc, methodCall.getJavaClassName())) != null)) {
TableDescriptor td = getDataDictionary().getTableDescriptor(triggerTableId);
setResultColumns(genResultColList(td));
// costing info
vtiCosted = true;
estimatedCost = 50d;
estimatedRowCount = 5d;
supportsMultipleInstantiations = true;
} else {
setResultColumns(new ResultColumnList((getContextManager())));
if (isDerbyStyleTableFunction) {
createResultColumnsForTableFunction(routineInfo.getReturnType());
} else {
ResultSetMetaData rsmd = getResultSetMetaData();
/* Wouldn't it be nice if we knew that the class/object would never
* return a null ResultSetMetaData.
*/
if (rsmd == null) {
throw StandardException.newException(SQLState.LANG_NULL_RESULT_SET_META_DATA, getVTIName());
}
// Remember how many columns VTI returns for partial row calculation
try {
numVTICols = rsmd.getColumnCount();
} catch (SQLException sqle) {
numVTICols = 0;
}
getResultColumns().createListFromResultSetMetaData(rsmd, exposedName, getVTIName());
}
}
numVTICols = getResultColumns().size();
/* Propagate the name info from the derived column list */
if (derivedRCL != null) {
getResultColumns().propagateDCLInfo(derivedRCL, correlationName);
}
return this;
}
Aggregations