Skip to content

Commit e357d83

Browse files
author
Philip Z
committed
fix(schema): validate existing column compatibility
1 parent 667cad7 commit e357d83

8 files changed

Lines changed: 426 additions & 3 deletions

File tree

‎teaql-duckdb/src/main/java/io/teaql/core/duck/DuckDataServiceExecutor.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public class DuckDataServiceExecutor extends SqlDataServiceExecutor {
1515

1616
public DuckDataServiceExecutor(String name, SqlExecutionAdapter executionAdapter) {
1717
super(name, executionAdapter);
18+
this.debugDatabaseKind = "duckdb";
1819
}
1920

2021
@Override
@@ -50,7 +51,11 @@ public void executeInTransaction(Runnable action) {
5051

5152
@Override
5253
public List<Map<String, Object>> getTableColumns(String tableName) {
53-
String sql = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = ?";
54+
String sql = "SELECT column_name, data_type, data_type AS type_name, "
55+
+ "character_maximum_length AS column_size, "
56+
+ "numeric_precision, numeric_scale AS decimal_digits, "
57+
+ "CASE WHEN is_nullable = 'YES' THEN 1 ELSE 0 END AS nullable "
58+
+ "FROM information_schema.columns WHERE table_name = ?";
5459
return getExecutionAdapter().queryForList(sql, new Object[] {tableName});
5560
}
5661
};

‎teaql-mysql/src/main/java/io/teaql/core/mysql/MysqlDataServiceExecutor.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,12 @@ public void executeInTransaction(Runnable action) {
5757

5858
@Override
5959
public List<Map<String, Object>> getTableColumns(String tableName) {
60-
String sql = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = ? AND table_schema = DATABASE()";
60+
String sql = "SELECT column_name, data_type, data_type AS type_name, "
61+
+ "character_maximum_length AS column_size, "
62+
+ "numeric_precision, numeric_scale AS decimal_digits, "
63+
+ "CASE WHEN is_nullable = 'YES' THEN 1 ELSE 0 END AS nullable "
64+
+ "FROM information_schema.columns "
65+
+ "WHERE table_name = ? AND table_schema = DATABASE()";
6166
return getExecutionAdapter().queryForList(sql, new Object[] {tableName});
6267
}
6368

‎teaql-postgres/src/main/java/io/teaql/core/postgres/PostgresDataServiceExecutor.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,12 @@ public void executeInTransaction(Runnable action) {
5050

5151
@Override
5252
public List<Map<String, Object>> getTableColumns(String tableName) {
53-
String sql = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = ? AND table_schema = 'public'";
53+
String sql = "SELECT column_name, data_type, data_type AS type_name, "
54+
+ "character_maximum_length AS column_size, "
55+
+ "numeric_precision, numeric_scale AS decimal_digits, "
56+
+ "CASE WHEN is_nullable = 'YES' THEN 1 ELSE 0 END AS nullable "
57+
+ "FROM information_schema.columns "
58+
+ "WHERE table_name = ? AND table_schema = 'public'";
5459
return getExecutionAdapter().queryForList(sql, new Object[] {tableName.toLowerCase()});
5560
}
5661

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/GenericSQLProperty.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public void setName(String name) {
4040
public List<SQLColumn> columns() {
4141
SQLColumn sqlColumn = new SQLColumn(tableName, columnName);
4242
sqlColumn.setType(columnType);
43+
sqlColumn.setRequired(getBoolean("required", false));
4344
return ListUtil.of(sqlColumn);
4445
}
4546

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/dialect/SqlDialect.java‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import io.teaql.core.SearchRequest;
44
import java.util.List;
5+
import java.util.Locale;
6+
import java.util.Map;
57

68
public interface SqlDialect {
79
/**
@@ -51,4 +53,40 @@ default String prepareParameterizedLimit(
5153
default String mapColumnType(String type) {
5254
return type;
5355
}
56+
57+
/**
58+
* Compare the storage families reported by the provider with the type selected for the model.
59+
* Providers may override this when their storage type system has wider compatibility rules.
60+
*/
61+
default boolean isCompatibleColumnType(String expected, String actual) {
62+
String expectedFamily = normalizedTypeFamily(expected);
63+
String actualFamily = normalizedTypeFamily(actual);
64+
return expectedFamily.isEmpty()
65+
|| actualFamily.isEmpty()
66+
|| expectedFamily.equals(actualFamily);
67+
}
68+
69+
private static String normalizedTypeFamily(String type) {
70+
if (type == null) return "";
71+
String family = type.trim().toUpperCase(Locale.ROOT)
72+
.replaceFirst("\\s*\\(.*", "")
73+
.replaceAll("\\s+", " ");
74+
return Map.ofEntries(
75+
Map.entry("CHARACTER VARYING", "VARCHAR"),
76+
Map.entry("VARCHAR2", "VARCHAR"),
77+
Map.entry("NVARCHAR2", "NVARCHAR"),
78+
Map.entry("CHARACTER", "CHAR"),
79+
Map.entry("INT", "INTEGER"),
80+
Map.entry("INT4", "INTEGER"),
81+
Map.entry("INT8", "BIGINT"),
82+
Map.entry("DEC", "DECIMAL"),
83+
Map.entry("NUMERIC", "DECIMAL"),
84+
Map.entry("DOUBLE PRECISION", "DOUBLE"),
85+
Map.entry("FLOAT8", "DOUBLE"),
86+
Map.entry("FLOAT4", "REAL"),
87+
Map.entry("BOOL", "BOOLEAN"),
88+
Map.entry("TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP"),
89+
Map.entry("TIMESTAMP WITH TIME ZONE", "TIMESTAMPTZ"))
90+
.getOrDefault(family, family);
91+
}
5492
}

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLRepository.java‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1537,10 +1537,170 @@ protected void ensure(UserContext context, List<Map<String, Object>> tableInfo,
15371537
String dbColumnName = column.getColumnName().toLowerCase();
15381538
if (!fields.containsKey(dbColumnName)) {
15391539
addColumn(context, column);
1540+
} else {
1541+
ensureCompatibleColumn(table, column, fields.get(dbColumnName));
15401542
}
15411543
}
15421544
}
15431545

1546+
private void ensureCompatibleColumn(
1547+
String table, SQLColumn column, Map<String, Object> databaseColumn) {
1548+
Object actualTypeValue = metadataValue(databaseColumn, "type_name", "data_type");
1549+
if (actualTypeValue == null || actualTypeValue instanceof Number) return;
1550+
1551+
String expectedType = dialect.mapColumnType(column.getType());
1552+
String actualType = String.valueOf(actualTypeValue);
1553+
if (!dialect.isCompatibleColumnType(expectedType, actualType)) {
1554+
throw incompatibleColumn(table, column,
1555+
"expected type " + expectedType + " but database reports " + actualType);
1556+
}
1557+
1558+
ensureCompatibleNullability(table, column, databaseColumn);
1559+
ensureCompatibleValueDomain(table, column, expectedType, actualType, databaseColumn);
1560+
}
1561+
1562+
private void ensureCompatibleNullability(
1563+
String table, SQLColumn column, Map<String, Object> databaseColumn) {
1564+
Object nullable = metadataValue(databaseColumn, "nullable", "is_nullable");
1565+
if (nullable == null) return;
1566+
boolean expectedNullable = !column.isIdColumn() && !column.isRequired();
1567+
boolean actualNullable = nullableMetadata(nullable);
1568+
if (expectedNullable != actualNullable) {
1569+
throw incompatibleColumn(table, column,
1570+
"expected nullable=" + expectedNullable
1571+
+ " but database reports nullable=" + actualNullable);
1572+
}
1573+
}
1574+
1575+
private void ensureCompatibleValueDomain(
1576+
String table,
1577+
SQLColumn column,
1578+
String expectedType,
1579+
String actualType,
1580+
Map<String, Object> databaseColumn) {
1581+
List<Integer> expectedArguments = declaredTypeArguments(expectedType);
1582+
String expectedFamily = declaredTypeFamily(expectedType);
1583+
String actualFamily = declaredTypeFamily(actualType);
1584+
1585+
if (isTextFamily(expectedFamily) && !expectedArguments.isEmpty()
1586+
&& !isUnboundedTextFamily(actualFamily)) {
1587+
Integer actualLength = integerMetadata(metadataValue(
1588+
databaseColumn, "column_size", "character_maximum_length"));
1589+
if (actualLength == null) {
1590+
List<Integer> actualArguments = declaredTypeArguments(actualType);
1591+
actualLength = actualArguments.isEmpty() ? null : actualArguments.get(0);
1592+
}
1593+
int requiredLength = expectedArguments.get(0);
1594+
if (actualLength != null && actualLength < requiredLength) {
1595+
throw incompatibleColumn(table, column,
1596+
"required max length=" + requiredLength
1597+
+ " but database reports max length=" + actualLength);
1598+
}
1599+
}
1600+
1601+
if (isDecimalFamily(expectedFamily) && expectedArguments.size() >= 2) {
1602+
int expectedPrecision = expectedArguments.get(0);
1603+
int expectedScale = expectedArguments.get(1);
1604+
Integer actualPrecision = integerMetadata(metadataValue(
1605+
databaseColumn, "numeric_precision", "column_size"));
1606+
Integer actualScale = integerMetadata(metadataValue(
1607+
databaseColumn, "numeric_scale", "decimal_digits"));
1608+
if (actualPrecision == null || actualScale == null) {
1609+
List<Integer> actualArguments = declaredTypeArguments(actualType);
1610+
if (actualArguments.size() >= 2) {
1611+
actualPrecision = actualArguments.get(0);
1612+
actualScale = actualArguments.get(1);
1613+
}
1614+
}
1615+
if (actualPrecision == null && actualScale == null) return;
1616+
boolean covers = actualPrecision != null
1617+
&& actualScale != null
1618+
&& actualScale >= expectedScale
1619+
&& actualPrecision - actualScale >= expectedPrecision - expectedScale;
1620+
if (!covers) {
1621+
throw incompatibleColumn(table, column,
1622+
"required precision=" + expectedPrecision + ", scale=" + expectedScale
1623+
+ " but database reports precision=" + actualPrecision
1624+
+ ", scale=" + actualScale);
1625+
}
1626+
}
1627+
}
1628+
1629+
private IllegalStateException incompatibleColumn(
1630+
String table, SQLColumn column, String detail) {
1631+
return new IllegalStateException(
1632+
"Ensure Schema incompatible existing column for entity '"
1633+
+ entityDescriptor.getType() + "' on table '" + table
1634+
+ "', column '" + column.getColumnName() + "', dialect '"
1635+
+ dialect.getClass().getSimpleName() + "': " + detail);
1636+
}
1637+
1638+
private static Object metadataValue(Map<String, Object> metadata, String... names) {
1639+
for (String name : names) {
1640+
for (Map.Entry<String, Object> entry : metadata.entrySet()) {
1641+
if (name.equalsIgnoreCase(entry.getKey())) return entry.getValue();
1642+
}
1643+
}
1644+
return null;
1645+
}
1646+
1647+
private static boolean nullableMetadata(Object value) {
1648+
if (value instanceof Boolean bool) return bool;
1649+
if (value instanceof Number number) return number.intValue() != 0;
1650+
String text = String.valueOf(value).trim();
1651+
return "YES".equalsIgnoreCase(text)
1652+
|| "Y".equalsIgnoreCase(text)
1653+
|| "TRUE".equalsIgnoreCase(text)
1654+
|| "1".equals(text);
1655+
}
1656+
1657+
private static Integer integerMetadata(Object value) {
1658+
if (value == null) return null;
1659+
if (value instanceof Number number) return number.intValue();
1660+
try {
1661+
return Integer.valueOf(String.valueOf(value));
1662+
} catch (NumberFormatException ignored) {
1663+
return null;
1664+
}
1665+
}
1666+
1667+
private static String declaredTypeFamily(String type) {
1668+
int argumentStart = type.indexOf('(');
1669+
return (argumentStart < 0 ? type : type.substring(0, argumentStart))
1670+
.trim().toUpperCase(java.util.Locale.ROOT);
1671+
}
1672+
1673+
private static List<Integer> declaredTypeArguments(String type) {
1674+
int start = type.indexOf('(');
1675+
int end = type.indexOf(')', start + 1);
1676+
if (start < 0 || end < 0) return List.of();
1677+
return Arrays.stream(type.substring(start + 1, end).split(","))
1678+
.map(String::trim)
1679+
.map(value -> {
1680+
try {
1681+
return Integer.valueOf(value);
1682+
} catch (NumberFormatException ignored) {
1683+
return null;
1684+
}
1685+
})
1686+
.filter(ObjectUtil::isNotNull)
1687+
.collect(Collectors.toList());
1688+
}
1689+
1690+
private static boolean isTextFamily(String family) {
1691+
return family.contains("CHAR") || family.contains("TEXT") || family.contains("CLOB");
1692+
}
1693+
1694+
private static boolean isUnboundedTextFamily(String family) {
1695+
return family.contains("TEXT") || family.contains("CLOB");
1696+
}
1697+
1698+
private static boolean isDecimalFamily(String family) {
1699+
return "DECIMAL".equals(family)
1700+
|| "NUMERIC".equals(family)
1701+
|| "NUMBER".equals(family);
1702+
}
1703+
15441704
private String metadataColumnName(Map<String, Object> column, String table) {
15451705
for (Map.Entry<String, Object> entry : column.entrySet()) {
15461706
if ("column_name".equalsIgnoreCase(entry.getKey())

0 commit comments

Comments
 (0)