由于大多数数据库将这些约束存储为索引,因此您可以使用前面提到的DatabaseMetaData.getIndexInfo()。这在我使用 Postgresql 时效果很好。
如文档所述,使用第 4 个参数为 true 调用 getIndexInfo() 很重要:
unique - 如果为真,则只返回唯一值的索引;假的时候,
无论是否唯一,都返回索引
使用以下代码:
// Class to combine all columns for the same index into one object
public static class UniqueConstraint {
public String table;
public String name;
public List<String> columns = new ArrayList<>();
public String toString() {
return String.format("[%s] %s: %s", table, name, columns);
}
}
public static List<UniqueConstraint> getUniqueConstraints(Connection conn, String schema, String table) throws SQLException {
Map<String, UniqueConstraint> constraints = new HashMap<>();
DatabaseMetaData dm = conn.getMetaData();
ResultSet rs = dm.getIndexInfo(null, schema, table, true, true);
while(rs.next()) {
String indexName = rs.getString("index_name");
String columnName = rs.getString("column_name");
UniqueConstraint constraint = new UniqueConstraint();
constraint.table = table;
constraint.name = indexName;
constraint.columns.add(columnName);
constraints.compute(indexName, (key, value) -> {
if (value == null) { return constraint; }
value.columns.add(columnName);
return value;
});
}
return new ArrayList<>(constraints.values());
}
你可以打电话:
getUniqueConstraints(conn, "public", tableName);
并获取给定表的所有唯一约束的列表。约束是按索引分组的,因为一个索引可以覆盖多列,前提是它们组合起来是唯一的。