修改问题、添加监管数据报送模块
这个提交包含在:
@@ -0,0 +1,92 @@
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Exact 278 increment. Existing seed rows are never updated or deleted. */
|
||||
class ReportingMenuMigration {
|
||||
static final String RANGE = "menu_id BETWEEN 1761700000000000800 AND 1761700000000000808";
|
||||
static final String KEY = "migration:20261124.278:reporting-menu";
|
||||
static int tables(Connection c, String schema, boolean verifyIndexes) throws SQLException {
|
||||
Map<String,Set<String>> expected=Map.of(
|
||||
"DG_REPORTING_CONFIG",Set.of("UK_REPORTING_CODE","IDX_REPORTING_PARENT","IDX_REPORTING_ROOT"),
|
||||
"DG_REPORTING_AUDIT",Set.of("IDX_REPORTING_AUDIT"),
|
||||
"DG_REPORTING_TEMPLATE",Set.of("UK_REPORTING_TEMPLATE"),
|
||||
"DG_REPORTING_STANDARD",Set.of("UK_REPORTING_STANDARD"));
|
||||
int found=0;
|
||||
for (var entry:expected.entrySet()) {
|
||||
try (ResultSet r=c.getMetaData().getTables(null,schema,entry.getKey(),new String[]{"TABLE"})) { if(r.next()) found++; }
|
||||
if (verifyIndexes) {
|
||||
Set<String> indexes=new HashSet<>();
|
||||
try (ResultSet r=c.getMetaData().getIndexInfo(null,schema,entry.getKey(),false,false)) {
|
||||
while(r.next()) if(r.getString("INDEX_NAME")!=null) indexes.add(r.getString("INDEX_NAME").toUpperCase(Locale.ROOT));
|
||||
}
|
||||
require(indexes.containsAll(entry.getValue()),"Reporting index missing");
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
static int count(Connection c, String sql) throws SQLException {
|
||||
try (Statement s=c.createStatement()) {
|
||||
s.setQueryTimeout(15);
|
||||
try (ResultSet r=s.executeQuery(sql)) { r.next(); return r.getInt(1); }
|
||||
}
|
||||
}
|
||||
static void require(boolean ok, String message) {
|
||||
if (!ok) throw new IllegalStateException(message);
|
||||
}
|
||||
static void verify(Connection c, List<String[]> rows) throws SQLException {
|
||||
require(count(c,"SELECT COUNT(*) FROM sys_menu WHERE "+RANGE)==9,"Menu count differs");
|
||||
require(count(c,"SELECT COUNT(*) FROM sys_role_menu WHERE role_id=1761300000000000001 AND "+RANGE)==9,"Grant count differs");
|
||||
for (String[] row:rows) require(count(c,row[1])==1,"Installed menu content differs");
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
require(args.length==1 && Set.of("--preflight","--apply","--verify").contains(args[0]),"Explicit mode required");
|
||||
var in=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8));
|
||||
String hash=in.readLine();
|
||||
require(hash!=null && hash.matches("[a-f0-9]{64}"),"Invalid digest");
|
||||
List<String[]> rows=new ArrayList<>();
|
||||
for (String line; (line=in.readLine())!=null;) {
|
||||
String[] p=line.split("\t",2);
|
||||
rows.add(new String[]{new String(Base64.getDecoder().decode(p[0]),StandardCharsets.UTF_8),new String(Base64.getDecoder().decode(p[1]),StandardCharsets.UTF_8)});
|
||||
}
|
||||
require(rows.size()==18,"Exactly nine menus and nine grants required");
|
||||
String schema=System.getenv("DATAGOV_DM_SCHEMA");
|
||||
require(schema!=null && schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+"),"Dedicated schema required");
|
||||
Properties p=new Properties();
|
||||
p.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));
|
||||
p.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
p.setProperty("connectTimeout","6000"); p.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"),p)) {
|
||||
c.setSchema(schema); require(schema.equals(c.getSchema()),"Schema mismatch");
|
||||
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); c.setAutoCommit(false);
|
||||
require(count(c,"SELECT COUNT(*) FROM sys_role WHERE role_id=1761300000000000001 AND role_key='superadmin' AND status='0' AND del_flag='0'")==1,"Expected active superadmin missing");
|
||||
boolean installed=false;
|
||||
try (PreparedStatement s=c.prepareStatement("SELECT sha256,state FROM dg_dm_install_step WHERE step_key=?")) {
|
||||
s.setString(1,KEY);
|
||||
try (ResultSet r=s.executeQuery()) {
|
||||
if (r.next()) { require(hash.equals(r.getString(1)) && "SUCCESS".equals(r.getString(2)),"Reconcile journal before proceeding"); installed=true; }
|
||||
}
|
||||
}
|
||||
if (installed) { require(tables(c,schema,true)==4,"Reporting table missing"); verify(c,rows); c.rollback(); System.out.println("TABLES_VERIFIED=4 INDEXES_VERIFIED=6 MENU_VERIFIED=9 GRANTS_VERIFIED=9"); return; }
|
||||
require(!"--verify".equals(args[0]),"Migration not installed");
|
||||
require(count(c,"SELECT COUNT(*) FROM sys_menu WHERE "+RANGE+" OR path='/datagov-regulatory-reporting' OR perms LIKE 'aixun:integration:regulatory-reporting:%'")==0,"Menu collision; reconcile first");
|
||||
require(count(c,"SELECT COUNT(*) FROM sys_role_menu WHERE "+RANGE)==0,"Existing grant collision");
|
||||
int tables=tables(c,schema,"--apply".equals(args[0]));
|
||||
System.out.println("PREFLIGHT=PASS REPORTING_TABLES="+tables);
|
||||
if ("--preflight".equals(args[0])) { c.rollback(); return; }
|
||||
require(tables==4,"Install four reporting tables first");
|
||||
try {
|
||||
for (String[] row:rows) try (Statement s=c.createStatement()) { s.setQueryTimeout(15); require(s.executeUpdate(row[0])==1,"Unexpected inserted row count"); }
|
||||
verify(c,rows);
|
||||
try (PreparedStatement s=c.prepareStatement("INSERT INTO dg_dm_install_step(step_key,sha256,state) VALUES(?,?,'SUCCESS')")) {
|
||||
s.setString(1,KEY); s.setString(2,hash); s.executeUpdate();
|
||||
}
|
||||
c.commit(); System.out.println("MENU_APPLIED=9 GRANTS_APPLIED=9 TRANSACTION=COMMITTED");
|
||||
} catch (Exception e) { c.rollback(); throw e; }
|
||||
} catch (SQLException e) {
|
||||
System.err.println("DATABASE_FAILED SQLSTATE="+e.getSQLState()+" CODE="+e.getErrorCode()+"; reconcile journal and contents before retry"); System.exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply or verify only regulatory reporting 277/278 using the existing DM journal.
|
||||
|
||||
Invoke through with-dameng-env.py; no credentials or SQL are emitted.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TABLES = {'dg_reporting_config', 'dg_reporting_audit', 'dg_reporting_template', 'dg_reporting_standard'}
|
||||
|
||||
|
||||
def literal(value):
|
||||
if value is None:
|
||||
return 'NULL'
|
||||
if isinstance(value, (int, float)):
|
||||
return str(value)
|
||||
if value == '2000-01-01 00:00:00':
|
||||
return 'LOCALTIMESTAMP'
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
|
||||
|
||||
def encoded(value):
|
||||
return base64.b64encode(value.encode()).decode()
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('mode', choices=['preflight', 'apply', 'verify'])
|
||||
args = p.parse_args()
|
||||
# Bind this incremental runner to the reviewed migration sources.
|
||||
for path, expected in [
|
||||
('integration/V20261124.277__create_regulatory_reporting.sql', '6cd233f9de3e71f0d276423bccd7e9543ba5766d53ba1e23f30822b53b6d8130'),
|
||||
('system/V20261124.278__register_regulatory_reporting.sql', 'f1a7729b7f5a082442c967e125a83c7193b6c921003679222db3d504bfed0f05'),
|
||||
]:
|
||||
if hashlib.sha256((ROOT/'db/migration'/path).read_bytes()).hexdigest() != expected:
|
||||
raise ValueError('Reviewed migration checksum changed')
|
||||
ddl = []
|
||||
for part in (ROOT/'db/dameng/schema.sql').read_text().split('-- @statement ')[1:]:
|
||||
label, sql = part.split('\n', 1)
|
||||
if label not in TABLES:
|
||||
continue
|
||||
sql = sql.strip().removesuffix(';')
|
||||
name = re.match(r'CREATE\s+(?:UNIQUE\s+)?(?:TABLE|INDEX)\s+(\w+)', sql, re.I).group(1)
|
||||
ddl.append(label+':'+name+'\t'+hashlib.sha256(sql.encode()).hexdigest()+'\t'+encoded(sql))
|
||||
if len(ddl) != 10:
|
||||
raise ValueError('Expected exactly ten DDL statements')
|
||||
seed = json.loads((ROOT/'db/dameng/seed.json').read_text())
|
||||
rows = []
|
||||
for table in ('sys_menu', 'sys_role_menu'):
|
||||
columns = seed[table]['columns']
|
||||
selected = [r for r in seed[table]['rows'] if 1761700000000000800 <= int(r[columns.index('menu_id')]) <= 1761700000000000808]
|
||||
if len(selected) != 9:
|
||||
raise ValueError('Expected nine rows in '+table)
|
||||
for row in selected:
|
||||
if table == 'sys_role_menu' and int(row[columns.index('role_id')]) != 1761300000000000001:
|
||||
raise ValueError('Unexpected role')
|
||||
insert = 'INSERT INTO '+table+'('+','.join(columns)+') VALUES('+','.join(map(literal,row))+')'
|
||||
predicates = []
|
||||
for col, val in zip(columns, row):
|
||||
if col in ('create_time', 'update_time'):
|
||||
continue
|
||||
predicates.append(col+' IS NULL' if val is None else "COALESCE("+col+",'~')=COALESCE("+literal(val)+",'~')" if isinstance(val,str) else col+'='+literal(val))
|
||||
check = 'SELECT COUNT(*) FROM '+table+' WHERE '+' AND '.join(predicates)
|
||||
rows.append(encoded(insert)+'\t'+encoded(check))
|
||||
body = '\n'.join(rows)+'\n'
|
||||
body = hashlib.sha256(body.encode()).hexdigest()+'\n'+body
|
||||
java = ['java', '--class-path', str(ROOT/'script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar')]
|
||||
def menus(mode):
|
||||
subprocess.run(java+[str(ROOT/'script/database/ReportingMenuMigration.java'), '--'+mode], input=body, text=True, check=True)
|
||||
if args.mode == 'preflight':
|
||||
menus('preflight')
|
||||
print('SCOPED_DDL=10 MENU_ROWS=9 ROLE_GRANTS=9 RUNTIME_MUTATION=NONE')
|
||||
return
|
||||
if args.mode == 'apply':
|
||||
menus('preflight')
|
||||
subprocess.run(java+[str(ROOT/'script/database/DamengSchema.java')]+(['--verify'] if args.mode=='verify' else []), input='\n'.join(ddl)+'\n', text=True, check=True)
|
||||
menus(args.mode)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
在新工单中引用
屏蔽一个用户