Skip to content

Commit 351c74c

Browse files
author
Philip Z
committed
Make Business ID schema setup portable for SQL Server
1 parent 560017e commit 351c74c

5 files changed

Lines changed: 195 additions & 8 deletions

File tree

‎.github/workflows/live-dialects.yml‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,42 @@ jobs:
5050
- name: Verify both live dialects (skips are forbidden)
5151
run: >-
5252
mvn -B -ntp -pl teaql-postgres,teaql-mysql,examples/business-id-runtime -am
53-
-Dtest=PostgresIntegrationTest,MysqlIntegrationTest,JdbcBusinessIdLiveDialectIT
53+
-Dtest=PostgresIntegrationTest,MysqlIntegrationTest,JdbcBusinessIdLiveDialectIT#postgresAllocatesAcrossInstancesAndRestart+mysqlAllocatesAcrossInstancesAndRestart
54+
-Dsurefire.failIfNoSpecifiedTests=false test
55+
56+
business-id-sqlserver:
57+
runs-on: ubuntu-latest
58+
services:
59+
sqlserver:
60+
image: mcr.microsoft.com/mssql/server:2022-latest
61+
env:
62+
ACCEPT_EULA: "Y"
63+
MSSQL_SA_PASSWORD: TeaqlBusinessLiveTest123!
64+
ports:
65+
- 1433:1433
66+
options: >-
67+
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P TeaqlBusinessLiveTest123! -C -Q 'SELECT 1' -b"
68+
--health-interval 10s --health-timeout 5s --health-retries 20
69+
env:
70+
TEAQL_REQUIRE_LIVE_DB: "true"
71+
TEAQL_TEST_MSSQL_URL: "jdbc:sqlserver://127.0.0.1:1433;databaseName=teaql_live_ci;encrypt=false;trustServerCertificate=true"
72+
TEAQL_TEST_MSSQL_USER: sa
73+
TEAQL_TEST_MSSQL_PASSWORD: TeaqlBusinessLiveTest123!
74+
steps:
75+
- uses: actions/checkout@v4
76+
- uses: actions/setup-java@v4
77+
with:
78+
distribution: temurin
79+
java-version: "21"
80+
cache: maven
81+
- name: Create isolated Business ID test database
82+
run: >-
83+
docker exec "${{ job.services.sqlserver.id }}"
84+
/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa
85+
-P TeaqlBusinessLiveTest123! -C
86+
-Q 'CREATE DATABASE teaql_live_ci'
87+
- name: Verify SQL Server Business ID schema and allocation (skips are forbidden)
88+
run: >-
89+
mvn -B -ntp -pl examples/business-id-runtime -am
90+
'-Dtest=JdbcBusinessIdLiveDialectIT#sqlServerAllocatesAcrossInstancesAndRestart+sqlServerConcurrentSchemaStartupIsIdempotent'
5491
-Dsurefire.failIfNoSpecifiedTests=false test

‎examples/business-id-runtime/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,11 @@
4343
<artifactId>junit</artifactId>
4444
<scope>test</scope>
4545
</dependency>
46+
<dependency>
47+
<groupId>com.microsoft.sqlserver</groupId>
48+
<artifactId>mssql-jdbc</artifactId>
49+
<version>13.4.0.jre11</version>
50+
<scope>test</scope>
51+
</dependency>
4652
</dependencies>
4753
</project>

‎examples/business-id-runtime/src/test/java/io/teaql/examples/businessid/BusinessIdRuntimeExampleTest.java‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,27 @@ public void sqliteAllocatorRejectsMalformedSequenceRowWithoutRetryExhaustion()
238238
}
239239
}
240240

241+
@Test
242+
public void sqliteAllocatorRejectsIncompleteExistingSchema() throws Exception {
243+
Path databasePath = Files.createTempFile("teaql-business-id-incomplete-schema", ".db");
244+
try (Connection connection = open(databasePath)) {
245+
try (Statement statement = connection.createStatement()) {
246+
statement.execute("CREATE TABLE teaql_business_id_space (scope_key TEXT PRIMARY KEY)");
247+
}
248+
JdbcBusinessIdAllocator allocator =
249+
new JdbcBusinessIdAllocator(database(connection));
250+
UserContext context = context(LocalDate.of(2026, 9, 20), allocator);
251+
context.putAttribute(SchemaExecutor.class.getName(), noOpSchemaExecutor());
252+
253+
IllegalStateException failure = Assert.assertThrows(
254+
IllegalStateException.class, context::ensureSchema);
255+
Assert.assertTrue(failure.getMessage(),
256+
failure.getMessage().contains("missing required columns"));
257+
} finally {
258+
Files.deleteIfExists(databasePath);
259+
}
260+
}
261+
241262
@Test
242263
public void sqliteAllocatorRejectsExhaustedAndOverflowedSequencesWithoutMutation()
243264
throws Exception {
@@ -419,7 +440,22 @@ public void executeInTransaction(Runnable action) {
419440

420441
@Override
421442
public List<Map<String, Object>> getTableColumns(String tableName) {
422-
throw new UnsupportedOperationException();
443+
try {
444+
List<Map<String, Object>> columns = new ArrayList<>();
445+
java.sql.DatabaseMetaData metadata = connection.getMetaData();
446+
for (String name : List.of(tableName, tableName.toUpperCase(Locale.ROOT))) {
447+
try (ResultSet result = metadata.getColumns(
448+
connection.getCatalog(), connection.getSchema(), name, null)) {
449+
while (result.next()) {
450+
columns.add(Map.of("column_name", result.getString("COLUMN_NAME")));
451+
}
452+
}
453+
if (!columns.isEmpty()) break;
454+
}
455+
return columns;
456+
} catch (SQLException error) {
457+
throw new RuntimeException(error);
458+
}
423459
}
424460

425461
private void bind(PreparedStatement statement, Object[] args) throws SQLException {

‎examples/business-id-runtime/src/test/java/io/teaql/examples/businessid/JdbcBusinessIdLiveDialectIT.java‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import org.junit.Assume;
2525
import org.junit.Test;
2626

27-
/** Live, independent-connection Business ID allocation across PostgreSQL and MySQL. */
27+
/** Live, independent-connection Business ID allocation across SQL providers. */
2828
public class JdbcBusinessIdLiveDialectIT {
2929
private static final LocalDate BUSINESS_DATE = LocalDate.of(2026, 9, 20);
3030
private static final int ALLOCATIONS_PER_INSTANCE = 40;
@@ -39,6 +39,55 @@ public void mysqlAllocatesAcrossInstancesAndRestart() throws Exception {
3939
verify("MYSQL");
4040
}
4141

42+
@Test
43+
public void sqlServerAllocatesAcrossInstancesAndRestart() throws Exception {
44+
verify("MSSQL");
45+
}
46+
47+
@Test
48+
public void sqlServerConcurrentSchemaStartupIsIdempotent() throws Exception {
49+
String url = System.getenv("TEAQL_TEST_MSSQL_URL");
50+
String user = System.getenv("TEAQL_TEST_MSSQL_USER");
51+
String password = System.getenv("TEAQL_TEST_MSSQL_PASSWORD");
52+
if (url == null || user == null || password == null) {
53+
if (Boolean.parseBoolean(System.getenv("TEAQL_REQUIRE_LIVE_DB"))) {
54+
Assert.fail("MSSQL Business ID live gate requires URL, USER, and PASSWORD");
55+
}
56+
Assume.assumeTrue("MSSQL live database is not configured", false);
57+
}
58+
Assert.assertTrue("Use a dedicated teaql_live_* database for MSSQL",
59+
url.contains("teaql_live_"));
60+
String table = "bid_schema_" + UUID.randomUUID().toString().substring(0, 8);
61+
CountDownLatch start = new CountDownLatch(1);
62+
ExecutorService workers = Executors.newFixedThreadPool(2);
63+
try {
64+
List<Future<?>> futures = new ArrayList<>();
65+
for (int worker = 0; worker < 2; worker++) {
66+
futures.add(workers.submit(() -> {
67+
try (Connection connection = DriverManager.getConnection(url, user, password)) {
68+
JdbcBusinessIdAllocator allocator = new JdbcBusinessIdAllocator(
69+
BusinessIdRuntimeExampleTest.database(connection), table);
70+
UserContext context = BusinessIdRuntimeExampleTest.context(
71+
BUSINESS_DATE, allocator);
72+
context.putAttribute(SchemaExecutor.class.getName(),
73+
BusinessIdRuntimeExampleTest.noOpSchemaExecutor());
74+
Assert.assertTrue(start.await(15, TimeUnit.SECONDS));
75+
context.ensureSchema();
76+
return null;
77+
}
78+
}));
79+
}
80+
start.countDown();
81+
for (Future<?> future : futures) future.get(30, TimeUnit.SECONDS);
82+
} finally {
83+
workers.shutdownNow();
84+
}
85+
try (Connection connection = DriverManager.getConnection(url, user, password)) {
86+
Assert.assertEquals(4, BusinessIdRuntimeExampleTest.database(connection)
87+
.getTableColumns(table).size());
88+
}
89+
}
90+
4291
private void verify(String dialect) throws Exception {
4392
String prefix = "TEAQL_TEST_" + dialect + "_";
4493
String url = System.getenv(prefix + "URL");
@@ -67,6 +116,7 @@ private void verify(String dialect) throws Exception {
67116
context.putAttribute(SchemaExecutor.class.getName(),
68117
BusinessIdRuntimeExampleTest.noOpSchemaExecutor());
69118
context.ensureSchema();
119+
context.ensureSchema();
70120
}
71121

72122
CountDownLatch start = new CountDownLatch(1);

‎teaql-business-id-jdbc/src/main/java/io/teaql/businessid/jdbc/JdbcBusinessIdAllocator.java‎

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
import java.time.ZoneOffset;
77
import java.util.List;
88
import java.util.Map;
9+
import java.util.Set;
10+
import java.util.HashSet;
11+
import java.util.Locale;
912

1013
/** Portable optimistic Business ID allocator backed by a TeaQLDatabase. */
1114
public final class JdbcBusinessIdAllocator
@@ -31,11 +34,66 @@ public JdbcBusinessIdAllocator(TeaQLDatabase database, String table) {
3134
/** Explicit development/test schema operation; construction never executes DDL. */
3235
@Override
3336
public void ensureSchema(UserContext context) {
34-
database.execute(context, "CREATE TABLE IF NOT EXISTS " + table + " ("
35-
+ "scope_key VARCHAR(512) PRIMARY KEY, "
36-
+ "current_value BIGINT NOT NULL, "
37-
+ "version BIGINT NOT NULL, "
38-
+ "updated_at BIGINT NOT NULL)");
37+
List<Map<String, Object>> existing = inspectColumns();
38+
if (!existing.isEmpty()) {
39+
requireColumns(existing);
40+
return;
41+
}
42+
try {
43+
database.execute(context, "CREATE TABLE " + table + " ("
44+
+ "scope_key VARCHAR(512) PRIMARY KEY, "
45+
+ "current_value BIGINT NOT NULL, "
46+
+ "version BIGINT NOT NULL, "
47+
+ "updated_at BIGINT NOT NULL)");
48+
} catch (RuntimeException createFailure) {
49+
// Another instance may have created the table after inspection.
50+
// Only accept that race when the installed table can be inspected.
51+
try {
52+
List<Map<String, Object>> concurrent = inspectColumns();
53+
if (!concurrent.isEmpty()) {
54+
requireColumns(concurrent);
55+
return;
56+
}
57+
} catch (RuntimeException inspectFailure) {
58+
createFailure.addSuppressed(inspectFailure);
59+
}
60+
throw new IllegalStateException(
61+
"Cannot create Business ID table " + table, createFailure);
62+
}
63+
requireColumns(inspectColumns());
64+
}
65+
66+
private List<Map<String, Object>> inspectColumns() {
67+
try {
68+
List<Map<String, Object>> columns = database.getTableColumns(table);
69+
if (columns == null) {
70+
throw new IllegalStateException("Column inspection returned null for " + table);
71+
}
72+
return columns;
73+
} catch (RuntimeException failure) {
74+
throw new IllegalStateException(
75+
"Cannot inspect Business ID table " + table
76+
+ "; the database adapter must provide column metadata",
77+
failure);
78+
}
79+
}
80+
81+
private void requireColumns(List<Map<String, Object>> columns) {
82+
Set<String> found = new HashSet<>();
83+
for (Map<String, Object> column : columns) {
84+
for (Map.Entry<String, Object> entry : column.entrySet()) {
85+
if ("column_name".equalsIgnoreCase(entry.getKey()) && entry.getValue() != null) {
86+
found.add(String.valueOf(entry.getValue()).toLowerCase(Locale.ROOT));
87+
}
88+
}
89+
}
90+
Set<String> missing = new java.util.TreeSet<>(Set.of(
91+
"scope_key", "current_value", "version", "updated_at"));
92+
missing.removeAll(found);
93+
if (!missing.isEmpty()) {
94+
throw new IllegalStateException(
95+
"Business ID table " + table + " is missing required columns " + missing);
96+
}
3997
}
4098

4199
@Override

0 commit comments

Comments
 (0)