import java.io.*; import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.*; /** Explicit schema application with a durable statement journal; never retries UNKNOWN. */ class DamengSchema { public static void main(String[] args) throws Exception { boolean verify=args.length==1&&"--verify".equals(args[0]); String schema = System.getenv("DATAGOV_DM_SCHEMA"); if (schema == null || !schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+")) throw new IllegalArgumentException("Dedicated DataGov schema required"); Properties properties = new Properties(); properties.setProperty("user", System.getenv("DATAGOV_DM_USERNAME")); properties.setProperty("password", System.getenv("DATAGOV_DM_PASSWORD")); properties.setProperty("connectTimeout", "6000"); properties.setProperty("socketTimeout", "30000"); Class.forName("dm.jdbc.driver.DmDriver"); try (Connection c = DriverManager.getConnection("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT"), properties)) { c.setSchema(schema); if (!schema.equals(c.getSchema())) throw new IllegalArgumentException("Schema does not match"); if(!verify)try (Statement s = c.createStatement()) { s.execute("CREATE TABLE IF NOT EXISTS dg_dm_install_step(step_key VARCHAR(256) PRIMARY KEY,sha256 CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,error_code INT,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"); } if (args.length == 1 && "--reset-empty-test-installation".equals(args[0])) { resetEmptyTestInstallation(c, schema, null); return; } if (args.length == 2 && "--reset-empty-test-table".equals(args[0])) { if(!args[1].matches("[a-z][a-z0-9_]+"))throw new IllegalArgumentException("Invalid table name"); resetEmptyTestInstallation(c,schema,args[1]); return; } var input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); Map journal = new HashMap<>(); try (Statement s=c.createStatement(); ResultSet r=s.executeQuery("SELECT step_key,sha256,state,error_code FROM dg_dm_install_step")) { while(r.next()) journal.put(r.getString(1),new String[]{r.getString(2),r.getString(3),r.getString(4)}); } String line; int applied = 0, skipped = 0; while ((line = input.readLine()) != null) { String[] parts = line.split("\t", 3); String key = parts[0], sha = parts[1]; String sql = new String(Base64.getDecoder().decode(parts[2]), StandardCharsets.UTF_8); String[] previous = journal.get(key); String oldSha = previous == null ? null : previous[0], state = previous == null ? null : previous[1]; if ("UNKNOWN".equals(state) && Set.of("-6121","-2706","-6119","-6120","-6105","-2026").contains(previous[2]) && sql.startsWith("CREATE TABLE ")) { String table=key.split(":")[0].toUpperCase(Locale.ROOT); try(ResultSet r=c.getMetaData().getTables(null,schema,table,new String[]{"TABLE"})) { if(r.next())throw new IllegalStateException("Rejected table unexpectedly exists; manual reconciliation required"); } state="FAILED"; System.out.println("RECONCILED_ABSENT_REJECTED_TABLE="+table); } if ("UNKNOWN".equals(state) && "-2169".equals(previous[2]) && sql.startsWith("CREATE UNIQUE INDEX ")) { String[] names=key.split(":"); boolean found=false; try(ResultSet r=c.getMetaData().getIndexInfo(null,schema,names[0].toUpperCase(Locale.ROOT),false,false)) { while(r.next())if(names[1].equalsIgnoreCase(r.getString("INDEX_NAME")))found=true; } if(found)throw new IllegalStateException("Rejected index unexpectedly exists; manual reconciliation required"); state="FAILED"; System.out.println("RECONCILED_ABSENT_REJECTED_INDEX="+names[1]); } if ("SUCCESS".equals(state)) { if (!sha.equals(oldSha)) throw new IllegalStateException("Applied statement checksum drift: " + key); skipped++; continue; } if(verify)throw new IllegalStateException("Schema statement is not installed: "+key); if (state != null && !"FAILED".equals(state)) throw new IllegalStateException("Reconcile incomplete statement before retry: " + key); if (state == null) { try (PreparedStatement s=c.prepareStatement("INSERT INTO dg_dm_install_step(step_key,sha256,state) VALUES(?,?,'STARTED')")) { s.setString(1,key);s.setString(2,sha);s.executeUpdate(); } } else { try (PreparedStatement s=c.prepareStatement("UPDATE dg_dm_install_step SET sha256=?,state='STARTED',error_code=NULL,updated_at=CURRENT_TIMESTAMP WHERE step_key=? AND sha256=? AND state IN ('FAILED','UNKNOWN')")) { s.setString(1,sha);s.setString(2,key);s.setString(3,oldSha); if(s.executeUpdate()!=1)throw new IllegalStateException("Installation state changed concurrently; stop before executing DDL: "+key); } } try (Statement s=c.createStatement()) { s.setQueryTimeout(30); s.execute(sql); } catch (SQLException error) { // Only deterministic statement rejection is retryable after a source correction. Set rejected=Set.of(-2007,-2207,-2994,-3719,-2119,-2111,-2665,-2724,-2723,-2707,-6160,-2725,-2169,-6121,-2706,-6119); String outcome=rejected.contains(error.getErrorCode())?"FAILED":"UNKNOWN"; try (PreparedStatement s=c.prepareStatement("UPDATE dg_dm_install_step SET state=?,error_code=?,updated_at=CURRENT_TIMESTAMP WHERE step_key=?")) { s.setString(1,outcome);s.setInt(2,error.getErrorCode());s.setString(3,key);s.executeUpdate(); } System.err.println("STOP " + key + " " + outcome + " CODE=" + error.getErrorCode()); String message=error.getMessage(); for(String env:List.of("DATAGOV_DM_PASSWORD","DATAGOV_DM_HOST","DATAGOV_DM_USERNAME")) { String value=System.getenv(env);if(value!=null&&!value.isEmpty())message=message.replace(value,"[withheld]"); } System.err.println(message); System.exit(2); } try (PreparedStatement s=c.prepareStatement("UPDATE dg_dm_install_step SET state='SUCCESS',updated_at=CURRENT_TIMESTAMP WHERE step_key=?")) { s.setString(1,key);s.executeUpdate(); } applied++; if(applied%100==0)System.out.println("APPLIED="+applied+" SKIPPED="+skipped); } System.out.println((verify?"SCHEMA_VERIFIED=":"SCHEMA_APPLIED=")+(verify?skipped:applied)+" SKIPPED="+skipped); } catch (SQLException error) { System.err.println("CONNECTION_OR_JOURNAL_FAILURE SQLSTATE="+error.getSQLState()+" CODE="+error.getErrorCode()); System.exit(2); } } private static void resetEmptyTestInstallation(Connection c, String schema, String onlyTable) throws SQLException { if (!"AIXUN_DATAGOV_DM_TEST".equals(schema)) throw new IllegalArgumentException("Only this task's empty test installation can be reset"); List tables = new ArrayList<>(); try (Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT step_key,state FROM dg_dm_install_step ORDER BY updated_at DESC")) { while(r.next()) { if(onlyTable!=null&&!r.getString(1).startsWith(onlyTable+":"))continue; String state=r.getString(2); if(!Set.of("SUCCESS","FAILED").contains(state)) throw new IllegalStateException("Unreconciled installation state"); String[] key=r.getString(1).split(":"); if("SUCCESS".equals(state)&&key.length==2&&key[0].equals(key[1])) { if(!key[0].matches("[a-z][a-z0-9_]+")) throw new IllegalStateException("Invalid tracked object"); tables.add(key[0].toUpperCase(Locale.ROOT)); } } } if(onlyTable!=null&&tables.size()!=1)throw new IllegalStateException("Expected exactly one tracked task-created table"); try(ResultSet r=c.getMetaData().getTables(null,schema,onlyTable==null?"%":onlyTable.toUpperCase(Locale.ROOT),new String[]{"TABLE"})) { while(r.next()) { String name=r.getString("TABLE_NAME"); if(!"DG_DM_INSTALL_STEP".equals(name)&&!tables.contains(name)) throw new IllegalStateException("Untracked table; reset refused"); } } // Verify every tracked table is empty before removing any task-created object. for(String table:tables) try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT COUNT(*) FROM "+table)) { if(!r.next()||r.getLong(1)!=0) throw new IllegalStateException("Nonempty table; reset refused"); } for(String table:tables)try(Statement s=c.createStatement()){s.execute("DROP TABLE "+table);} try(PreparedStatement s=c.prepareStatement(onlyTable==null?"DELETE FROM dg_dm_install_step":"DELETE FROM dg_dm_install_step WHERE INSTR(step_key,?)=1")) { if(onlyTable!=null)s.setString(1,onlyTable+":"); s.executeUpdate(); } System.out.println("REMOVED_TASK_CREATED_EMPTY_TABLES="+tables.size()+" SCHEMA_RETAINED=true"); } }