use of org.apache.calcite.rel.RelReferentialConstraint in project hive by apache.
the class RelOptHiveTable method generateReferentialConstraints.
private List<RelReferentialConstraint> generateReferentialConstraints() {
final ForeignKeyInfo fki;
try {
fki = Hive.get().getReliableForeignKeys(hiveTblMetadata.getDbName(), hiveTblMetadata.getTableName());
} catch (HiveException e) {
throw new RuntimeException(e);
}
ImmutableList.Builder<RelReferentialConstraint> builder = ImmutableList.builder();
for (List<ForeignKeyCol> fkCols : fki.getForeignKeys().values()) {
List<String> foreignKeyTableQualifiedName = Lists.newArrayList(name);
String parentDatabaseName = fkCols.get(0).parentDatabaseName;
String parentTableName = fkCols.get(0).parentTableName;
String parentFullyQualifiedName;
if (parentDatabaseName != null && !parentDatabaseName.isEmpty()) {
parentFullyQualifiedName = parentDatabaseName + "." + parentTableName;
} else {
parentFullyQualifiedName = parentTableName;
}
List<String> parentTableQualifiedName = Lists.newArrayList(parentFullyQualifiedName);
Table parentTab = null;
try {
// TODO: We have a cache for Table objects in SemanticAnalyzer::getTableObjectByName()
// We need to move that cache elsewhere and use it from places like this.
parentTab = Hive.get().getTable(parentDatabaseName, parentTableName);
} catch (HiveException e) {
throw new RuntimeException(e);
}
if (parentTab == null) {
LOG.error("Table for primary key not found: " + "databaseName: " + parentDatabaseName + ", " + "tableName: " + parentTableName);
return ImmutableList.of();
}
ImmutableList.Builder<IntPair> keys = ImmutableList.builder();
for (ForeignKeyCol fkCol : fkCols) {
int fkPos;
for (fkPos = 0; fkPos < rowType.getFieldNames().size(); fkPos++) {
String fkColName = rowType.getFieldNames().get(fkPos);
if (fkColName.equals(fkCol.childColName)) {
break;
}
}
int pkPos;
for (pkPos = 0; pkPos < parentTab.getAllCols().size(); pkPos++) {
String pkColName = parentTab.getAllCols().get(pkPos).getName();
if (pkColName.equals(fkCol.parentColName)) {
break;
}
}
if (fkPos == rowType.getFieldNames().size() || pkPos == parentTab.getAllCols().size()) {
LOG.error("Column for foreign key definition " + fkCol + " not found");
return ImmutableList.of();
}
keys.add(IntPair.of(fkPos, pkPos));
}
builder.add(RelReferentialConstraintImpl.of(foreignKeyTableQualifiedName, parentTableQualifiedName, keys.build()));
}
return builder.build();
}
Aggregations