Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions release.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@
combining an empty MIN(mpg) with a character literal is rejected with SQLState 42000.
Fixes #320.

- **Behavior change:** Support `SIGNED INTEGER` and `SIGNED_INTEGER` as synonyms of `SIGNED` in CAST and
CONVERT, retaining the established 32-bit INTEGER mapping rather than MySQL's 64-bit semantics, and reject
`UNSIGNED`, `UNSIGNED INTEGER`, and other unrecognized CAST targets with SQLState 42000 instead of returning
the input unchanged (#322). For example, `CAST('123' AS SIGNED INTEGER)` returns Integer 123,
`CAST('3000000000' AS SIGNED INTEGER)` fails with 22003 like `SIGNED`, and `CAST('1' AS JSON)` or
`CAST('1' AS UNSIGNED)` fail with 42000.
Fixes #322.

- Derive common numeric CASE types from scalar subquery declarations, including correlated, empty, and NULL
results, and the remaining supported numeric scalar functions (#319). Retain unbounded decimal types without
executing unselected branches. Keep value classes and metadata consistent through grouping, derived tables,
Expand Down
25 changes: 21 additions & 4 deletions src/main/java/se/alipsa/jparq/engine/NumericCastTarget.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import se.alipsa.jparq.NumericType;
import se.alipsa.jparq.engine.function.DateTimeFunctions;

/**
* Shares numeric CAST aliases and their JDBC types across parsing and
Expand All @@ -16,8 +18,8 @@ public enum NumericCastTarget {
TINYINT(new NumericType(Types.TINYINT, 3, 0), "tinyint"),
/** Signed sixteen-bit integer. */
SMALLINT(new NumericType(Types.SMALLINT, 5, 0), "smallint", "int2"),
/** Signed thirty-two-bit integer. */
INTEGER(NumericType.of(Types.INTEGER, 0, 0), "int", "integer", "signed", "int4"),
/** Signed thirty-two-bit integer, including the SIGNED INTEGER spelling. */
INTEGER(NumericType.of(Types.INTEGER, 0, 0), "int", "integer", "signed", "signedinteger", "int4"),
/** Signed sixty-four-bit integer. */
BIGINT(NumericType.of(Types.BIGINT, 0, 0), "bigint", "int8"),
/** Single-precision floating point, including precision-qualified FLOAT. */
Expand All @@ -26,6 +28,7 @@ public enum NumericCastTarget {
DOUBLE(NumericType.of(Types.DOUBLE, 0, 0), "double", "doubleprecision", "float8");

private static final Map<String, NumericCastTarget> BY_NAME;
private static final Set<String> UNSUPPORTED_ALIASES = Set.of("unsigned", "unsignedinteger");

static {
Map<String, NumericCastTarget> names = new HashMap<>();
Expand Down Expand Up @@ -61,12 +64,26 @@ public enum NumericCastTarget {
* @return the numeric target, or null for an unrecognized name
*/
public static NumericCastTarget fromName(String name) {
return name == null ? null : fromNormalizedName(DateTimeFunctions.normalizeTypeName(name));
}

/**
* Identifies the unsigned integer spellings that JParq does not support as cast
* targets, so cast-style CONVERT arguments resolve to a CAST that fails with
* SQLState 42000 instead of silently returning the operand. Underscores are
* retained so underscored column names keep their value role.
*
* @param name
* the SQL target name, possibly null
* @return whether the name spells an unsupported unsigned integer target
*/
public static boolean isUnsupportedAlias(String name) {
if (name == null) {
return null;
return false;
}
int parameters = name.indexOf('(');
String base = parameters < 0 ? name : name.substring(0, parameters);
return fromNormalizedName(base.toLowerCase(Locale.ROOT).trim().replace(" ", "").replace("_", ""));
return UNSUPPORTED_ALIASES.contains(base.toLowerCase(Locale.ROOT).trim().replace(" ", ""));
}

/**
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/se/alipsa/jparq/engine/SqlParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,12 @@ static boolean isConvertTypeName(String name) {
if (paren > 0) {
normalized = normalized.substring(0, paren).trim();
}
// Spaces join multi-word spellings such as SIGNED INTEGER, while underscores
// keep names like big_int in their column role.
String compact = normalized.replace(" ", "");
return CONVERT_TYPE_NAMES.contains(normalized) || ScalarExpressionSchemas.declaredJdbcType(normalized) != null
|| NumericCastTarget.fromNormalizedName(normalized) != null || DecimalCasts.isDecimalType(normalized);
|| NumericCastTarget.fromNormalizedName(compact) != null || NumericCastTarget.isUnsupportedAlias(normalized)
|| DecimalCasts.isDecimalType(normalized);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,8 @@ private static Object applyInterval(Object temporal, TemporalInterval interval)
* @return the cast result converted to the requested type when possible
* @throws IllegalArgumentException
* if decimal bounds or binary lengths or source types are invalid
* (SQLState 42000) or the rounded value exceeds the target's range or
* (SQLState 42000) or the target is not a recognized CAST data type
* (42000) or the rounded value exceeds the target's range or
* precision (SQLState 22003), or numeric input is invalid or
* non-finite (SQLState 22018), or temporal input has invalid format
* (22007) or out-of-range fields (22008), or a non-character interval
Expand Down Expand Up @@ -832,7 +833,44 @@ public static Object castLiteral(CastExpression cast, Object value) {
case "text", "clob", "characterlargeobject", "nclob", "nationalcharacterlargeobject" -> SqlText.cast(value);
case "binary", "varbinary", "binaryvarying", "blob", "binarylargeobject" ->
compileBinaryCast(cast).convert(value);
default -> value;
default -> unsupportedCastTarget(normalized, dataType, value);
};
}

/**
* Retains temporal alias targets whose conversion the temporal promotion path
* applies, and rejects declarations that no converter recognizes.
*
* @param normalized
* normalized target name
* @param dataType
* declared type text for diagnostics
* @param value
* evaluated operand, possibly null
* @return value unchanged for temporal promotion targets
* @throws IllegalArgumentException
* carrying SQLState 42000 for an unrecognized target
*/
private static Object unsupportedCastTarget(String normalized, String dataType, Object value) {
if (isTemporalPromotionTarget(normalized)) {
return value;
}
throw SqlExceptions.syntaxFailure("Invalid data type for CAST: " + dataType);
}

/**
* Identifies temporal CAST aliases converted by the temporal promotion path
* after literal conversion instead of by this converter.
*
* @param normalized
* normalized target name
* @return whether temporal promotion applies the conversion
*/
static boolean isTemporalPromotionTarget(String normalized) {
return switch (normalized) {
case "datetime", "timestampwithouttimezone", "timewithouttimezone", "timewithtimezone", "timestampwithtimezone" ->
true;
default -> false;
};
}

Expand Down
220 changes: 220 additions & 0 deletions src/test/java/jparq/SignedUnsignedCastTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package jparq;

import static org.junit.jupiter.api.Assertions.*;

import java.nio.file.Path;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

/**
* Verifies that SIGNED INTEGER and SIGNED_INTEGER convert like SIGNED, while
* UNSIGNED, UNSIGNED INTEGER, and other unrecognized CAST targets fail with
* SQLState 42000 instead of returning the input unchanged (#322).
*/
class SignedUnsignedCastTest {

/**
* The SIGNED, SIGNED INTEGER, and SIGNED_INTEGER spellings declare and convert
* a thirty-two-bit integer.
*
* @param spelling
* signed integer target spelling
* @throws Exception
* if query execution fails
*/
@ParameterizedTest
@ValueSource(strings = {
"SIGNED", "SIGNED INTEGER", "SIGNED_INTEGER"
})
void signedSpellingsConvertToInteger(String spelling) throws Exception {
String sql = "SELECT CAST('123' AS " + spelling + ")";
try (var connection = DriverManager.getConnection(url()); var statement = connection.createStatement()) {
try (var result = statement.executeQuery(sql)) {
var meta = result.getMetaData();
assertEquals(Types.INTEGER, meta.getColumnType(1), sql);
assertEquals("java.lang.Integer", meta.getColumnClassName(1), sql);
assertEquals(10, meta.getPrecision(1), sql);
assertTrue(result.next(), sql);
assertEquals(123, result.getInt(1), sql);
assertFalse(result.next(), sql);
}
}
}

/**
* Signed integer casts truncate the fractional part and keep the established
* thirty-two-bit range, so oversized values fail like SIGNED.
*
* @throws Exception
* if query execution fails
*/
@Test
void signedIntegerRetainsThirtyTwoBitRange() throws Exception {
try (var connection = DriverManager.getConnection(url()); var statement = connection.createStatement()) {
try (var result = statement.executeQuery("SELECT CAST(mpg AS SIGNED INTEGER) FROM mtcars LIMIT 1")) {
assertEquals(Types.INTEGER, result.getMetaData().getColumnType(1));
assertTrue(result.next());
assertEquals(21, result.getInt(1));
assertFalse(result.next());
}
try (var result = statement.executeQuery("SELECT CAST('10.4' AS SIGNED INTEGER)")) {
assertTrue(result.next());
assertEquals(10, result.getInt(1));
assertFalse(result.next());
}
}
assertRejected("22003", "value out of range", "SELECT CAST('3000000000' AS SIGNED INTEGER)");
assertRejected("22003", "value out of range", "SELECT CAST('3000000000' AS SIGNED)");
}

/**
* UNSIGNED and UNSIGNED INTEGER name no JParq target, so both literal and
* column operands fail instead of returning the input unchanged.
*
* @param spelling
* unsigned integer target spelling
* @throws Exception
* if connection creation fails
*/
@ParameterizedTest
@ValueSource(strings = {
"UNSIGNED", "UNSIGNED INTEGER"
})
void unsignedSpellingsAreRejected(String spelling) throws Exception {
assertRejected("42000", "Invalid data type for CAST", "SELECT CAST('123' AS " + spelling + ")");
assertRejected("42000", "Invalid data type for CAST", "SELECT CAST(cyl AS " + spelling + ") FROM mtcars");
}

/**
* Other unrecognized targets fail with the same classification.
*
* @param target
* unrecognized CAST target
* @throws Exception
* if connection creation fails
*/
@ParameterizedTest
@ValueSource(strings = {
"FOOBAR", "JSON", "INTERVAL DAY"
})
void unrecognizedTargetsAreRejected(String target) throws Exception {
assertRejected("42000", "Invalid data type for CAST", "SELECT CAST('1' AS " + target + ")");
}

/**
* A NULL operand retains the signed declaration without failing.
*
* @throws Exception
* if query execution fails
*/
@Test
void nullInputKeepsSignedDeclaration() throws Exception {
try (var connection = DriverManager.getConnection(url()); var statement = connection.createStatement()) {
try (var result = statement.executeQuery("SELECT CAST(NULL AS SIGNED INTEGER)")) {
var meta = result.getMetaData();
assertEquals(Types.INTEGER, meta.getColumnType(1));
assertEquals("java.lang.Integer", meta.getColumnClassName(1));
assertTrue(result.next());
assertNull(result.getObject(1));
assertFalse(result.next());
}
}
}

/**
* Unsigned targets inside a scalar subquery fail with the same error.
*
* @throws Exception
* if connection creation fails
*/
@Test
void scalarSubqueryUnsignedRejected() throws Exception {
assertRejected("42000", "Invalid data type for CAST", "SELECT (SELECT CAST('1' AS UNSIGNED))");
}

/**
* Cast-style CONVERT shares the signed declaration and the unsigned rejection
* for both argument orders.
*
* @throws Exception
* if query execution fails
*/
@Test
void convertSharesSignedAndUnsignedDeclarations() throws Exception {
try (var connection = DriverManager.getConnection(url()); var statement = connection.createStatement()) {
try (var result = statement.executeQuery("SELECT CONVERT(SIGNED INTEGER, '123')")) {
var meta = result.getMetaData();
assertEquals(Types.INTEGER, meta.getColumnType(1));
assertEquals("java.lang.Integer", meta.getColumnClassName(1));
assertTrue(result.next());
assertEquals(123, result.getInt(1));
assertFalse(result.next());
}
}
assertRejected("42000", "Invalid data type for CAST", "SELECT CONVERT(UNSIGNED, '123')");
assertRejected("42000", "Invalid data type for CAST", "SELECT CONVERT(model, UNSIGNED) FROM mtcars");
}

/**
* Set operations see the declared INTEGER branch, so an empty signed branch
* rejects a character peer while a numeric peer still merges.
*
* @throws Exception
* if query execution fails
*/
@Test
void setOperationSeesDeclaredSignedIntegerBranch() throws Exception {
assertRejected("42000", "compatible column types",
"SELECT CAST(cyl AS SIGNED INTEGER) FROM mtcars WHERE 1=0 UNION ALL SELECT 'a'");
try (var connection = DriverManager.getConnection(url()); var statement = connection.createStatement()) {
try (var result = statement
.executeQuery("SELECT CAST(cyl AS SIGNED INTEGER) FROM mtcars LIMIT 1 UNION ALL SELECT 7")) {
assertEquals(Types.INTEGER, result.getMetaData().getColumnType(1));
assertTrue(result.next());
assertEquals(6, result.getInt(1));
assertTrue(result.next());
assertEquals(7, result.getInt(1));
assertFalse(result.next());
}
}
}

/**
* Executes a query and asserts the SQLState and message of its failure.
*
* @param sqlState
* expected SQLState
* @param expectedMessage
* expected message fragment
* @param sql
* query expected to fail
* @throws Exception
* if connection creation fails
*/
private static void assertRejected(String sqlState, String expectedMessage, String sql) throws Exception {
try (var connection = DriverManager.getConnection(url())) {
SQLException error = assertThrows(SQLException.class, () -> {
try (var statement = connection.createStatement(); var result = statement.executeQuery(sql)) {
while (result.next()) {
result.getObject(1);
}
}
}, sql);
assertEquals(sqlState, error.getSQLState(), sql);
assertTrue(error.getMessage().contains(expectedMessage), error.getMessage());
}
}

/**
* Returns the fixture database URL.
*
* @return JDBC connection URL
*/
private static String url() {
return "jdbc:jparq:" + Path.of("src/test/resources").toAbsolutePath();
}
}
Loading