添加达梦、MySQL 数据库适配功能
这个提交包含在:
@@ -0,0 +1,54 @@
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Prepare production SQL without executing writes. Rejects unsupported or absent objects. */
|
||||
class PlatformDatabaseProbe {
|
||||
static Connection connect() throws SQLException {
|
||||
Properties p = new Properties();
|
||||
p.setProperty("user", System.getenv("PLATFORM_DB_USERNAME"));
|
||||
p.setProperty("password", System.getenv("PLATFORM_DB_PASSWORD"));
|
||||
p.setProperty("connectTimeout", "10000");
|
||||
p.setProperty("socketTimeout", "30000");
|
||||
p.setProperty("useServerPrepStmts", "true");
|
||||
p.setProperty("emulateUnsupportedPstmts", "false");
|
||||
Connection c = DriverManager.getConnection(System.getenv("PLATFORM_DB_URL"), p);
|
||||
String schema = System.getenv("PLATFORM_DB_SCHEMA");
|
||||
if (schema != null && !schema.isBlank()) c.setSchema(schema);
|
||||
c.setAutoCommit(false);
|
||||
return c;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
int pass = 0, fail = 0;
|
||||
try (Connection c = connect()) {
|
||||
try (var ignored = c.prepareStatement("SELECT no_such_column FROM dg_no_such_probe_table")) {
|
||||
throw new IllegalStateException("Server preparation negative control failed");
|
||||
} catch (SQLException expected) { }
|
||||
var input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
|
||||
for (String line; (line = input.readLine()) != null;) {
|
||||
String[] parts = line.split("\t", 2);
|
||||
String sql = new String(Base64.getDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
try (PreparedStatement s = c.prepareStatement(sql)) {
|
||||
s.getParameterMetaData();
|
||||
pass++;
|
||||
} catch (SQLException error) {
|
||||
fail++;
|
||||
System.out.println("FAIL " + parts[0] + " CODE=" + error.getErrorCode() + " STATE=" + error.getSQLState());
|
||||
String message = error.getMessage();
|
||||
for (String key : List.of("PLATFORM_DB_USERNAME", "PLATFORM_DB_PASSWORD", "PLATFORM_DB_URL")) {
|
||||
String secret = System.getenv(key);
|
||||
if (secret != null && !secret.isBlank()) message = message.replace(secret, "[withheld]");
|
||||
}
|
||||
System.out.println(message);
|
||||
}
|
||||
}
|
||||
c.rollback();
|
||||
} catch (Exception error) {
|
||||
System.err.println("PROBE_FAILED " + error.getClass().getSimpleName());
|
||||
System.exit(2);
|
||||
}
|
||||
System.out.println("PREPARE_PASS=" + pass + " FAIL=" + fail);
|
||||
if (fail > 0) System.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Read-only bootstrap verification. Never creates or migrates a table. */
|
||||
class VerifyPlatformDatabase {
|
||||
public static void main(String[] args) {
|
||||
Properties p = new Properties();
|
||||
p.setProperty("user", System.getenv("PLATFORM_DB_USERNAME"));
|
||||
p.setProperty("password", System.getenv("PLATFORM_DB_PASSWORD"));
|
||||
p.setProperty("connectTimeout", "10000");
|
||||
p.setProperty("socketTimeout", "30000");
|
||||
try (Connection c = DriverManager.getConnection(System.getenv("PLATFORM_DB_URL"), p)) {
|
||||
String schema = System.getenv("PLATFORM_DB_SCHEMA");
|
||||
if (schema != null && !schema.isBlank()) c.setSchema(schema);
|
||||
c.setReadOnly(true);
|
||||
if (args.length == 1 && args[0].equals("--journal")) {
|
||||
try (var s=c.createStatement(); var r=s.executeQuery("SELECT step_key,state FROM dg_dm_install_step WHERE state<>'SUCCESS'")) {
|
||||
int incomplete=0;
|
||||
while(r.next()) {System.out.println(r.getString(1)+" "+r.getString(2));incomplete++;}
|
||||
System.out.println("INCOMPLETE_JOURNAL="+incomplete);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
|
||||
int tables = 0;
|
||||
for(String table; (table=input.readLine())!=null;) {
|
||||
if(!table.matches("[a-z][a-z0-9_]+"))throw new IllegalArgumentException();
|
||||
try(var s=c.createStatement(); var r=s.executeQuery("SELECT 1 FROM "+table+" WHERE 1=0")){tables++;}
|
||||
}
|
||||
for(String table:List.of("sys_menu","sys_role","sys_user")) {
|
||||
try(var s=c.createStatement(); var r=s.executeQuery("SELECT COUNT(*) FROM "+table)) {
|
||||
if(!r.next()||r.getLong(1)==0)throw new IllegalStateException("Missing seed: "+table);
|
||||
}
|
||||
}
|
||||
System.out.println("DATABASE_VERIFIED_TABLES="+tables+" CORE_SEED=PASS");
|
||||
} catch(Exception e) {
|
||||
System.err.println("DATABASE_VERIFY_FAILED "+e.getClass().getSimpleName()+(e instanceof SQLException s?" CODE="+s.getErrorCode():""));
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the fresh MySQL 8 schema and safe seed from the verified migration catalog."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from dameng_sql import mask_literals, restore_literals
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location('baseline', Path(__file__).with_name('build-dameng-baseline.py'))
|
||||
baseline = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(baseline)
|
||||
|
||||
def literal(value):
|
||||
if value is None: return 'NULL'
|
||||
if isinstance(value, (int, float)): return str(value)
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
|
||||
def main():
|
||||
tables, _ = baseline.collect()
|
||||
target = ROOT / 'db/mysql'
|
||||
target.mkdir(exist_ok=True)
|
||||
header = "-- Fresh dedicated database only; not an upgrade or data migration.\nSET NAMES utf8mb4;\nSET SESSION sql_mode='STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION,NO_BACKSLASH_ESCAPES';\n"
|
||||
ddl = []
|
||||
for name, nodes in tables.items():
|
||||
columns = []
|
||||
for key, node in nodes.items():
|
||||
if key.startswith('column:') and not re.match(r'(UNIQUE|CHECK|FOREIGN)\b', node, re.I):
|
||||
node = re.sub(r'^(\w+)', r'`\1`', node)
|
||||
masked, literals = mask_literals(node)
|
||||
masked = re.sub(r'\bCLOB\b', 'LONGTEXT', masked, flags=re.I)
|
||||
masked = re.sub(r'(?<!`)\b(rows|model)\b(?!`)', r'`\1`', masked, flags=re.I)
|
||||
node = restore_literals(masked, literals)
|
||||
columns.append(node)
|
||||
ddl.append('CREATE TABLE `' + name + '` (\n ' + ',\n '.join(columns) + '\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;')
|
||||
(target / 'schema.sql').write_text(header + '\n\n'.join(ddl) + '\n')
|
||||
seed = json.loads((ROOT / 'db/dameng/seed.json').read_text())
|
||||
inserts = []
|
||||
for table, data in seed.items():
|
||||
for row in data['rows']:
|
||||
inserts.append('INSERT INTO `' + table + '` (' + ','.join('`'+c+'`' for c in data['columns']) + ') VALUES (' + ','.join(literal(v) for v in row) + ');')
|
||||
(target / 'seed.sql').write_text(header + 'START TRANSACTION;\n' + '\n'.join(inserts) + '\nCOMMIT;\n')
|
||||
print('MYSQL_TABLES=' + str(len(tables)) + ' SEED_ROWS=' + str(len(inserts)))
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate positional parameters of explicit dialect pairs and export preparable SQL."""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import textwrap
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TOKEN = r'("""[\s\S]*?"""|"(?:\\.|[^"\\])*")'
|
||||
PAIR = re.compile(r'(?:databaseDialect|dialect)\.sql\(\s*' + TOKEN + r'\s*,\s*' + TOKEN + r'\s*\)')
|
||||
|
||||
def decode(token):
|
||||
if token.startswith('"""'): return textwrap.dedent(token[3:-3]).strip()
|
||||
return json.loads(token.replace("\\'", "'").replace('\\s', ' '))
|
||||
|
||||
def pairs():
|
||||
for directory in ('aixun-common', 'aixun-modules'):
|
||||
for path in (ROOT / directory).rglob('*.java'):
|
||||
if '/src/main/' not in str(path): continue
|
||||
source = path.read_text()
|
||||
for match in PAIR.finditer(source):
|
||||
yield path.name + ':' + str(source[:match.start()].count('\n')+1), decode(match[1]), decode(match[2])
|
||||
|
||||
def count(sql): return re.sub(r"'(?:''|[^'])*'", '', sql).count('?')
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--engine', choices=['dameng', 'mysql'], required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
rows = []; fragments = []
|
||||
for label, dm, mysql in pairs():
|
||||
if count(dm) != count(mysql): raise ValueError('parameter mismatch: ' + label)
|
||||
sql = dm if args.engine == 'dameng' else mysql
|
||||
# Supply the surrounding production statement for concatenated fragments.
|
||||
if label.startswith('DatasetContentInputRepository.java:'):
|
||||
sql += "submitted_by,idempotency_key,payload_sha,state,row_version,registration_json,created_at,updated_at) VALUES (?,?,?,?,?,?,UNHEX(?),'DECLARED',0,?,CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6))"
|
||||
if label.startswith('AssetIdentityJdbcRepository.java:'):
|
||||
if sql.startswith(',created_by'):
|
||||
sql = 'INSERT INTO asset_identity_source_binding(binding_id,organization_id,department_id,detail_id,lifecycle_id,source_owner,source_type,source_stable_id,binding_state,row_version,latest_observation_id' + sql
|
||||
elif sql.startswith('latest_observation_id='):
|
||||
sql = 'UPDATE asset_identity_source_binding SET lifecycle_id=?,source_stable_id=?,binding_state=?,row_version=?,' + sql + ' WHERE organization_id=? AND department_id=? AND binding_id=? AND row_version=? AND binding_state=? AND latest_observation_id IS NULL'
|
||||
if label.startswith('DatasetAnnotationJdbcRepository.java:'):
|
||||
sql = 'SELECT COUNT(*) FROM svc_dataset_content c JOIN svc_dataset_content_index i ON i.content_version_id=c.content_version_id JOIN svc_dataset_content_history h ON h.content_version_id=c.content_version_id WHERE 1=0 ' + sql
|
||||
if label.startswith('BiManagement.java:'):
|
||||
sql = 'SELECT ' + sql + ' FROM DUAL'
|
||||
if 'INSERT' in sql and 'dev_dataset_preparation_command (' in sql:
|
||||
sql += ' VALUES (?,?,?,?,?,?,UNHEX(?),CURRENT_TIMESTAMP(6))'
|
||||
if 'INSERT' in sql and 'dev_dataset_preparation_artifact (' in sql:
|
||||
sql += ' VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP(6))'
|
||||
if re.search(r'\bWHERE\s*$', sql, re.I): sql += ' 1=0'
|
||||
if not re.match(r'(SELECT|INSERT|UPDATE|DELETE|MERGE)\b', sql, re.I) or sql.count('(') != sql.count(')') or re.search(r'(AND|,)\s*$', sql, re.I) or (sql.startswith('INSERT') and not re.search(r'\b(VALUES|SELECT)\b', sql, re.I)):
|
||||
fragments.append(label); continue
|
||||
rows.append(label+'\t'+base64.b64encode(sql.encode()).decode())
|
||||
args.output.write_text('\n'.join(rows)+'\n')
|
||||
print('SQL_PAIRS='+str(len(rows)+len(fragments))+' PREPARABLE='+str(len(rows))+' FRAGMENTS='+str(len(fragments)))
|
||||
for label in fragments: print('FRAGMENT '+label)
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only verification of current platform tables and core seed on DM or MySQL."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location('baseline', Path(__file__).with_name('build-dameng-baseline.py'))
|
||||
baseline = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(baseline)
|
||||
if not os.environ.get('PLATFORM_DB_URL'):
|
||||
raise SystemExit('Run with with-platform-db-env.py and a private configuration')
|
||||
drivers = [ROOT/'script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar',
|
||||
Path(os.environ.get('MYSQL_JDBC_JAR', str(Path.home()/'.m2/repository/com/mysql/mysql-connector-j/9.7.0/mysql-connector-j-9.7.0.jar')))]
|
||||
if any(not path.is_file() for path in drivers): raise SystemExit('Missing JDBC driver; build backend first or set MYSQL_JDBC_JAR')
|
||||
tables, _ = baseline.collect()
|
||||
result = subprocess.run(['java', '--class-path', os.pathsep.join(map(str, drivers)), str(ROOT/'script/database/VerifyPlatformDatabase.java')],
|
||||
input='\n'.join(tables)+'\n', text=True)
|
||||
raise SystemExit(result.returncode)
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a command with a private MySQL/DM configuration; never expose credentials in argv."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--config', required=True, type=Path)
|
||||
parser.add_argument('command', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
path = args.config.resolve()
|
||||
if not path.is_relative_to(ROOT/'runtime/dev-private') or not path.is_file() or stat.S_IMODE(path.stat().st_mode) & 0o077:
|
||||
parser.error('private 0600 configuration required under runtime/dev-private')
|
||||
values = json.loads(path.read_text())
|
||||
engine = values.get('engine', 'dameng').lower()
|
||||
if engine not in ('dameng', 'mysql'): parser.error('engine must be dameng or mysql')
|
||||
for key in ('host', 'port', 'username', 'password'):
|
||||
if not values.get(key): parser.error('missing private field: ' + key)
|
||||
if not re.fullmatch(r'[A-Za-z0-9.-]+', str(values['host'])) or not 1 <= int(values['port']) <= 65535:
|
||||
parser.error('invalid endpoint')
|
||||
name = values.get('schema' if engine == 'dameng' else 'database', '')
|
||||
pattern = r'AIXUN_DATAGOV_[A-Z0-9_]+' if engine == 'dameng' else r'aixun_datagov_[a-z0-9_]+'
|
||||
if not re.fullmatch(pattern, name): parser.error('dedicated DataGov schema/database required')
|
||||
env = os.environ.copy()
|
||||
for key in list(env):
|
||||
if key.startswith('DM_') or key.startswith('DATAGOV_DM_'): env.pop(key)
|
||||
endpoint = str(values['host']) + ':' + str(values['port'])
|
||||
env.update(PLATFORM_DB_URL=('jdbc:dm://' + endpoint if engine == 'dameng' else 'jdbc:mysql://' + endpoint + '/' + name + '?useUnicode=true&characterEncoding=utf8&connectionTimeZone=UTC'),
|
||||
PLATFORM_DB_USERNAME=values['username'], PLATFORM_DB_PASSWORD=values['password'],
|
||||
PLATFORM_DB_SCHEMA=name if engine == 'dameng' else '', DATAGOV_PLATFORM_DB_CONFIG=str(path))
|
||||
if engine == 'dameng':
|
||||
for key in ('host', 'port', 'username', 'password', 'schema'):
|
||||
env['DM_' + key.upper()] = str(values[key])
|
||||
env['DATAGOV_DM_' + key.upper()] = str(values[key])
|
||||
env['DATAGOV_DM_CONFIG'] = str(path)
|
||||
command = args.command[1:] if args.command[:1] == ['--'] else args.command
|
||||
if not command: parser.error('missing project command')
|
||||
os.chdir(ROOT)
|
||||
os.execvpe(command[0], command, env)
|
||||
在新工单中引用
屏蔽一个用户