Skip to content

Commit 5e876de

Browse files
committed
fix: share MySQL initialization with OceanBase
1 parent ad38688 commit 5e876de

8 files changed

Lines changed: 212 additions & 2483 deletions

File tree

‎.github/scripts/check-agent-gateway-migrations.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
}
3030
# The seed statements use SQL literals, including JSON strings and Oracle hints.
3131
# Tokenize quoted text before stripping comments or normalizing whitespace.
32-
TOKEN = re.compile(r"'(?:''|[^'])*'|/\*.*?\*/|--[^\n]*|[^\s]", re.S)
32+
TOKEN = re.compile(r"'(?:''|[^'])*'|/\*.*?\*/|--[^\n]*|\bNULL\b|[^\s]", re.S | re.I)
3333
INSERT = re.compile(
3434
r'INSERT\s+(?:/\*.*?\*/\s*)?INTO\s+(?:"public"\.)?'
3535
r'[`"]?(\w+)[`"]?\s*(.*?)\bVALUES\s*\(\s*\'(\d+)\'', re.I | re.S
@@ -55,8 +55,8 @@ def seeds(sql):
5555
key = (table, row_id)
5656
if key in result:
5757
raise ValueError(f"duplicate seed {key}")
58-
# Ignore formatting only; keep column lists, values, case and SQL hints.
59-
result[key] = tuple(m.group() for m in TOKEN.finditer(text))
58+
# NULL is case-insensitive; preserve quoted values, column lists and hints.
59+
result[key] = tuple("NULL" if m.group().lower() == "null" else m.group() for m in TOKEN.finditer(text))
6060
required = {(table, row_id) for table, ids in EXPECTED.items() for row_id in ids}
6161
if result.keys() != required:
6262
raise ValueError(f"missing seeds: {sorted(required - result.keys())}")
@@ -76,7 +76,7 @@ def check(root):
7676
"""Verify all supported upgrade dialects, regardless of working directory."""
7777
for dialect in DIALECTS:
7878
filename = "create-table.sql" if dialect in ("og", "pg") else "schema.sql"
79-
schema = root / "db" / "init" / dialect / filename
79+
schema = root / "db" / "init" / ("mysql" if dialect == "ob" else dialect) / filename
8080
migration = root / "db" / "upgrade" / f"2.7.1-upgrade-2.7.2-{dialect}.sql"
8181
try:
8282
count = check_pair(schema.read_text(encoding="utf-8"), migration.read_text(encoding="utf-8"))

‎.github/scripts/native-sql-matrix.py‎

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
JAR_HEX = "0001027fff"
3131
DIALECTS = {
3232
"mysql": ("mysql:8.0@sha256:7dcddc01f13bab2f15cde676d44d01f61fc9f99fe7785e86196dfc07d358ae2b", "db/init/mysql/schema.sql"),
33-
"ob": ("oceanbase/oceanbase-ce:4.3.5-lts@sha256:31086a6900c21c479c2bcd942b6a28c53b17a51f4e9b9eb8eafcc596adfcd2e3", "db/init/ob/schema.sql"),
33+
"ob": ("oceanbase/oceanbase-ce:4.3.5-lts@sha256:31086a6900c21c479c2bcd942b6a28c53b17a51f4e9b9eb8eafcc596adfcd2e3", "db/init/mysql/schema.sql"),
3434
"pg": ("postgres:15@sha256:724292da1f2e50bdccfc3302ce75bbba7f4a6076701b588cc795fcac65683550", "db/init/pg/create-table.sql"),
3535
"og": ("enmotech/opengauss-lite:5.0.1@sha256:b0e9d4e7452007cb0a216e39f1927c889178dac695176af7ab0eec43ce077af3", "db/init/og/create-table.sql"),
3636
"oracle": ("gvenzl/oracle-free:23.26.3-slim@sha256:6d61d267a3b978c24c5ac1790e62e927416a0aec446bd86e4b3a1527562757bd", "db/init/oracle/schema.sql"),
@@ -39,6 +39,14 @@
3939
REQUIRED = {"selector": "plugin_id", "resource": "parent_id", "user_role": "user_id"}
4040

4141

42+
def schema_source(dialect, flow):
43+
# The released OceanBase baseline belongs to the historical upgrade flow.
44+
# Only fresh installations share the current MySQL initialization source.
45+
if dialect == "ob" and flow == "upgrade":
46+
return "db/init/ob/schema.sql"
47+
return DIALECTS[dialect][1]
48+
49+
4250
def run(command, data=None, timeout=180):
4351
result = subprocess.run(command, input=data, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
4452
text=True, encoding="utf-8", errors="replace", timeout=timeout)
@@ -122,6 +130,10 @@ def start(self):
122130
"oracle": ["ORACLE_PASSWORD=" + PASSWORD, "APP_USER=sqlmatrix", "APP_USER_PASSWORD=" + PASSWORD],
123131
}[self.dialect]
124132
command = ["docker", "run", "-d", "--name", self.name, "--shm-size=1g"]
133+
if self.dialect == "ob":
134+
# OceanBase requires at least 20000 file descriptors. Docker daemon
135+
# defaults vary, so set the limit for this disposable container only.
136+
command += ["--ulimit", "nofile=65536:65536"]
125137
for variable in environment:
126138
command += ["-e", variable]
127139
run(command + [image])
@@ -215,11 +227,74 @@ def indexes(self):
215227
(self.output / (self.name + ".indexes.txt")).write_text(rows, encoding="utf-8")
216228
return verify_index_rows(rows, self.dialect in ("pg", "og"))
217229

230+
def check_fresh_mysql_schema(self, schema, indexes):
231+
"""Validate the shared fresh-install contract on MySQL and OceanBase."""
232+
tables = {name.lower() for name in re.findall(r"CREATE TABLE\s+(?:IF NOT EXISTS\s+)?`?(\w+)`?", schema, re.I)}
233+
actual = set(self.sql("SELECT table_name FROM information_schema.tables WHERE table_schema='shenyu';").lower().split())
234+
if actual != tables:
235+
raise AssertionError(f"Fresh tables differ: missing={tables - actual}, extra={actual - tables}")
236+
for name, table, columns in re.findall(r"CREATE INDEX (\w+) ON `(\w+)` \(([^)]+)\)", schema):
237+
if indexes.get((table, name)) != [column.strip() for column in columns.split(",")]:
238+
raise AssertionError(f"Missing shared secondary index: {table}.{name}")
239+
unique = set(self.sql("SELECT DISTINCT CONCAT(table_name,'|',index_name) FROM information_schema.statistics "
240+
"WHERE table_schema='shenyu' AND non_unique=0;").lower().split())
241+
for key in ("dashboard_user|unique_user_name", "proxy_api_key_mapping|uk_selector_proxy_key",
242+
"plugin_handle|plugin_id_field_type", "shenyu_dict|dict_type_dict_code_dict_name",
243+
"discovery_upstream|discovery_upstream_discovery_handler_id_IDX"):
244+
if key.lower() not in unique:
245+
raise AssertionError("Missing shared unique constraint: " + key)
246+
247+
checks = []
248+
for table, column, parent, parent_column in (
249+
("plugin_handle", "plugin_id", "plugin", "id"),
250+
("permission", "resource_id", "resource", "id"),
251+
("permission", "object_id", "role", "id"),
252+
("user_role", "user_id", "dashboard_user", "id"),
253+
("user_role", "role_id", "role", "id"),
254+
("namespace_plugin_rel", "plugin_id", "plugin", "id"),
255+
("namespace_plugin_rel", "namespace_id", "namespace", "namespace_id"),
256+
("namespace_user_rel", "namespace_id", "namespace", "namespace_id"),
257+
("namespace_user_rel", "user_id", "dashboard_user", "id"),
258+
("selector", "plugin_id", "plugin", "id"),
259+
("selector", "namespace_id", "namespace", "namespace_id"),
260+
("rule", "selector_id", "selector", "id"),
261+
("rule", "namespace_id", "namespace", "namespace_id")):
262+
# Some legacy tables use different collations. Compare identifier bytes
263+
# so validation does not depend on either engine's default collation.
264+
checks.append((f"{table}.{column} orphan", f"SELECT child.id FROM {table} child LEFT JOIN {parent} parent "
265+
f"ON BINARY child.{column}=BINARY parent.{parent_column} WHERE parent.{parent_column} IS NULL"))
266+
checks.append(("resource.parent_id orphan", "SELECT child.id FROM resource child LEFT JOIN resource parent "
267+
"ON BINARY child.parent_id=BINARY parent.id WHERE child.parent_id NOT IN ('', '0') AND parent.id IS NULL"))
268+
for table, columns in (("plugin_handle", "plugin_id,field,type"),
269+
("permission", "object_id,resource_id"),
270+
("namespace_plugin_rel", "namespace_id,plugin_id")):
271+
checks.append((table + " duplicate natural key",
272+
f"SELECT {columns} FROM {table} GROUP BY {columns} HAVING COUNT(*)>1"))
273+
checks.append(("missing admin resource permission", "SELECT r.id FROM resource r LEFT JOIN permission p "
274+
"ON BINARY p.resource_id=BINARY r.id AND p.object_id='1346358560427216896' WHERE p.id IS NULL"))
275+
checks.append(("missing default namespace plugin", "SELECT p.id FROM plugin p LEFT JOIN namespace_plugin_rel r "
276+
"ON BINARY r.plugin_id=BINARY p.id AND r.namespace_id='649330b6-c2d7-4edc-be8e-8a54df9eb385' "
277+
f"WHERE p.id<>'{SENTINEL}' AND r.id IS NULL"))
278+
for label, query in checks:
279+
if scalar(self.sql("SELECT COUNT(*) FROM (" + query + ") violations;")) != "0":
280+
raise AssertionError("Invalid fresh seed: " + label)
281+
if scalar(self.sql("SELECT COUNT(*) FROM namespace WHERE namespace_id='649330b6-c2d7-4edc-be8e-8a54df9eb385' "
282+
"AND name='default';")) != "1":
283+
raise AssertionError("Missing default namespace")
284+
for plugin_id in ("33", "50"):
285+
config = json.loads(scalar(self.sql(f"SELECT config FROM plugin WHERE id='{plugin_id}';")))
286+
namespace_config = json.loads(scalar(self.sql("SELECT config FROM namespace_plugin_rel "
287+
f"WHERE plugin_id='{plugin_id}' AND "
288+
"namespace_id='649330b6-c2d7-4edc-be8e-8a54df9eb385';")))
289+
if config != namespace_config:
290+
raise AssertionError("Default namespace config differs for plugin " + plugin_id)
291+
if plugin_id == "33" and config.get("bootstrapServer") != "localhost:9092":
292+
raise AssertionError("loggingKafka must seed bootstrapServer")
293+
218294

219295
def execute_matrix(dialect, root, output):
220296
output.mkdir(parents=True, exist_ok=True)
221297
listing, detail = fragment_columns(root / "shenyu-admin/src/main/resources/mappers/plugin-sqlmap.xml")
222-
_, schema_path = DIALECTS[dialect]
223298
results = {"dialect": dialect, "baseline": BASELINE, "image": DIALECTS[dialect][0], "flows": []}
224299
for flow in ("upgrade", "fresh"):
225300
engine = Engine(dialect, flow, output)
@@ -228,6 +303,7 @@ def execute_matrix(dialect, root, output):
228303
results["flows"].append(report)
229304
try:
230305
engine.start()
306+
schema_path = schema_source(dialect, flow)
231307
schema = (run(["git", "show", f"{BASELINE}:{schema_path}"]) if flow == "upgrade"
232308
else (root / schema_path).read_text(encoding="utf-8"))
233309
engine.sql(schema, database=False)
@@ -245,7 +321,9 @@ def execute_matrix(dialect, root, output):
245321
after = set(engine.sql("SELECT id FROM " + engine.table(table) + ";").split())
246322
if not identifiers.issubset(after):
247323
raise AssertionError(f"Migration removed rows from {table}: {sorted(identifiers - after)}")
248-
engine.indexes()
324+
indexes = engine.indexes()
325+
if flow == "fresh" and dialect in ("mysql", "ob"):
326+
engine.check_fresh_mysql_schema(schema, indexes)
249327
report["status"] = "success"
250328
print(f"{dialect}: {flow} SQL, projections, JAR preservation and index metadata passed", flush=True)
251329
except Exception as error:

‎.github/scripts/test-agent-gateway-migrations.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,14 @@ def test_changed_default_is_detected(self):
6262
def test_formatting_is_ignored(self):
6363
self.assertEqual(24, CHECK.check_pair(self.schema, self.migration.replace("VALUES (", "VALUES\n (")))
6464

65+
def test_null_keyword_case_is_ignored(self):
66+
self.assertEqual(24, CHECK.check_pair(self.schema, self.migration.replace("NULL", "null")))
67+
68+
def test_quoted_null_is_not_a_null_literal(self):
69+
changed = self.migration.replace("'68', NULL, 198", "'68', 'NULL', 198")
70+
with self.assertRaisesRegex(ValueError, "mismatch"):
71+
CHECK.check_pair(self.schema, changed)
72+
6573
def test_commented_out_migration_is_rejected(self):
6674
disabled = "\n".join("-- " + line for line in self.migration.splitlines())
6775
with self.assertRaisesRegex(ValueError, "missing seeds"):

‎.github/scripts/test-native-sql-matrix.py‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,53 @@ def test_exactly_five_digest_pinned_native_engines(self):
8787
self.assertTrue((ROOT / schema).is_file())
8888
self.assertRegex(matrix.BASELINE, r"^[0-9a-f]{40}$")
8989

90+
def test_oceanbase_shares_current_mysql_schema_but_keeps_released_baseline(self):
91+
self.assertEqual(matrix.DIALECTS["mysql"][1], matrix.DIALECTS["ob"][1])
92+
engine = MagicMock()
93+
engine.sql.return_value = "unchanged"
94+
with tempfile.TemporaryDirectory() as directory:
95+
with patch.object(matrix, "Engine", return_value=engine), \
96+
patch.object(matrix, "run", return_value="-- released OceanBase schema") as invoke:
97+
matrix.execute_matrix("ob", ROOT, Path(directory))
98+
invoke.assert_called_once_with(["git", "show", f"{matrix.BASELINE}:db/init/ob/schema.sql"])
99+
self.assertEqual(engine.sql.call_args_list[0].args[0], "-- released OceanBase schema")
100+
self.assertIn(unittest.mock.call((ROOT / "db/upgrade/2.7.1-upgrade-2.7.2-ob.sql").read_text(encoding="utf-8")),
101+
engine.sql.call_args_list)
102+
schema = (ROOT / "db/init/mysql/schema.sql").read_text(encoding="utf-8")
103+
self.assertIn(unittest.mock.call(schema, database=False), engine.sql.call_args_list)
104+
engine.check_fresh_mysql_schema.assert_called_once_with(schema, engine.indexes.return_value)
105+
106+
def test_fresh_shared_schema_rejects_missing_table_index_and_constraint(self):
107+
schema = "CREATE TABLE IF NOT EXISTS plugin (id int); CREATE INDEX idx_plugin ON `plugin` (id);"
108+
with tempfile.TemporaryDirectory() as directory:
109+
engine = matrix.Engine("ob", "fresh", Path(directory))
110+
with patch.object(engine, "sql", return_value=""), self.assertRaisesRegex(AssertionError, "Fresh tables"):
111+
engine.check_fresh_mysql_schema(schema, {})
112+
with patch.object(engine, "sql", return_value="plugin"), self.assertRaisesRegex(AssertionError, "secondary index"):
113+
engine.check_fresh_mysql_schema(schema, {})
114+
with patch.object(engine, "sql", return_value="plugin"), self.assertRaisesRegex(AssertionError, "unique constraint"):
115+
engine.check_fresh_mysql_schema(schema, {("plugin", "idx_plugin"): ["id"]})
116+
117+
def test_fresh_shared_schema_rejects_orphan_and_duplicate_seeds(self):
118+
unique = "\n".join(("dashboard_user|unique_user_name", "proxy_api_key_mapping|uk_selector_proxy_key",
119+
"plugin_handle|plugin_id_field_type", "shenyu_dict|dict_type_dict_code_dict_name",
120+
"discovery_upstream|discovery_upstream_discovery_handler_id_IDX"))
121+
for violation, label in (("FROM permission child LEFT JOIN resource", "permission.resource_id orphan"),
122+
("FROM plugin_handle GROUP BY", "plugin_handle duplicate natural key"),
123+
("FROM resource r LEFT JOIN permission", "missing admin resource permission"),
124+
("FROM plugin p LEFT JOIN namespace_plugin_rel", "missing default namespace plugin")):
125+
def sql(query):
126+
if "information_schema.tables" in query:
127+
return "plugin"
128+
if "information_schema.statistics" in query:
129+
return unique
130+
return "1" if violation in query else "0"
131+
132+
with self.subTest(violation=violation), tempfile.TemporaryDirectory() as directory:
133+
engine = matrix.Engine("mysql", "fresh", Path(directory))
134+
with patch.object(engine, "sql", side_effect=sql), self.assertRaisesRegex(AssertionError, label):
135+
engine.check_fresh_mysql_schema("CREATE TABLE `plugin` (id int);", {})
136+
90137
def test_actual_mapper_projects_metadata_and_preserves_detail_jar(self):
91138
listing, detail = matrix.fragment_columns(ROOT / "shenyu-admin/src/main/resources/mappers/plugin-sqlmap.xml")
92139
self.assertNotIn("plugin_jar", listing)
@@ -138,13 +185,16 @@ def test_pg_and_og_catalogs(self):
138185
def test_oceanbase_waits_for_writable_ddl_not_only_select(self):
139186
with tempfile.TemporaryDirectory() as directory:
140187
engine = matrix.Engine("ob", "upgrade", Path(directory))
141-
with patch.object(matrix, "run"), patch.object(matrix.time, "monotonic", side_effect=[0, 1, 2]), \
188+
with patch.object(matrix, "run") as invoke, patch.object(matrix.time, "monotonic", side_effect=[0, 1, 2]), \
142189
patch.object(matrix.time, "sleep") as sleep, \
143190
patch.object(engine, "sql", side_effect=["1", RuntimeError("4179 creating tenant"), "1", ""]) as sql:
144191
engine.start()
145192
self.assertEqual(sql.call_count, 4)
146193
self.assertIn("CREATE DATABASE IF NOT EXISTS sql_matrix_ready", sql.call_args_list[1].args[0])
147194
self.assertIn("DROP DATABASE sql_matrix_ready", sql.call_args_list[3].args[0])
195+
command = invoke.call_args_list[1].args[0]
196+
self.assertIn("--ulimit", command)
197+
self.assertIn("nofile=65536:65536", command)
148198
sleep.assert_called_once_with(5)
149199

150200
def test_scalars_reject_empty_or_multiple_results(self):

‎db/init/init-guide.md‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,27 @@
11
# Initialization Guide
22

3-
> The mysql, oracle, and pg directories contain database initialization scripts for Mysql, Oracle, and PostgreSql.
3+
The directories contain initialization scripts for MySQL, OceanBase in MySQL mode,
4+
Oracle, PostgreSQL, and openGauss.
45

56
## To Shenyu Users
67

78
- mysql/schema.sql
89

9-
> The file is the Mysql initialization script.
10+
> The canonical initialization script for both MySQL and OceanBase in MySQL mode.
11+
12+
For OceanBase, execute this script against a MySQL-mode tenant with an account
13+
allowed to create the `shenyu` database. For example, using `obclient`:
14+
15+
```sh
16+
obclient -h <host> -P <port> -u '<user>@<tenant>' -p < db/init/mysql/schema.sql
17+
```
18+
19+
Start ShenYu Admin with the `ob` Spring profile (`--spring.profiles.active=ob`)
20+
and configure `application-ob.yml` for the tenant. Keep the `oceanbase` database
21+
dialect, `jdbc:oceanbase://` URL and `com.oceanbase.jdbc.Driver`.
22+
This script is for fresh installations and recreates tables. Existing OceanBase
23+
installations must use their version-specific `*-ob.sql` scripts in `db/upgrade`.
24+
OceanBase Oracle mode is outside the scope of this shared MySQL initialization.
1025

1126
- oracle/schema.sql
1227

@@ -16,3 +31,29 @@
1631

1732
> The files are the PostgreSql initialization script.
1833
34+
- og/create-table.sql
35+
36+
> The file is the openGauss initialization script.
37+
38+
## Maintaining the shared MySQL/OceanBase schema
39+
40+
Update `mysql/schema.sql` for both engines. The native SQL matrix validates MySQL
41+
8.0 and OceanBase 4.3.5 LTS; it does not establish compatibility with every version.
42+
43+
The shared source retains the MySQL scaling tables and permissions, MCP selector,
44+
namespace/lookup secondary indexes, and all common unique constraints. The old
45+
OceanBase permission/object, resource/parent and user-role/user indexes are covered
46+
by the shared indexes with the same leading columns. API-key permission IDs differ
47+
between the old copies, but their role/resource grants are identical.
48+
49+
Both engines now use the current aiProxy fallback fields and aiPrompt handles;
50+
the obsolete aiProxy `prompt` field is absent from `AiProxyHandle`. Token limiter
51+
dictionaries use the supported `contextPath` resolver instead of the old unsupported
52+
`default` entry. The loggingKafka plugin and default namespace use the same topic,
53+
sampling/body-size/compression defaults and the `bootstrapServer` field consumed
54+
by the Kafka plugin. Permissions pointing to absent resources have been removed
55+
from fresh seeds; every existing resource retains its admin grant.
56+
57+
Historical upgrade scripts remain separate and unchanged. The Admin distribution
58+
packages the whole `db` directory, including this guide and the shared script.
59+

0 commit comments

Comments
 (0)