Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(oracle): add constraint and index editing

efeire61d3c5b3f6ae
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6b76102828..805df286a5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -97,6 +97,8 @@ jobs:
runs-on: ubuntu-24.04
env:
NPM_CONFIG_LOGLEVEL: error
+ # Sharded test runs across 900+ files exceed 4 GiB; public Linux runners provide 16 GiB RAM.
+ NODE_OPTIONS: --max-old-space-size=8192
strategy:
fail-fast: false
matrix:
diff --git a/agents/common/src/main/java/com/dbx/agent/ConstraintInfo.java b/agents/common/src/main/java/com/dbx/agent/ConstraintInfo.java
index cbed895861..ecf3ff3804 100644
--- a/agents/common/src/main/java/com/dbx/agent/ConstraintInfo.java
+++ b/agents/common/src/main/java/com/dbx/agent/ConstraintInfo.java
@@ -5,6 +5,25 @@ import java.util.List;
/** Shared wire shape; null state properties mean the database did not report them. */
public record ConstraintInfo(
String name, String constraint_type, String definition, List<String> columns,
- Boolean deferrable, Boolean initially_deferred, Boolean enabled, Boolean valid
+ Boolean deferrable, Boolean initially_deferred, Boolean enabled, Boolean valid,
+ OracleConstraintMetadata oracle_metadata
) {
+ public ConstraintInfo(
+ String name, String constraint_type, String definition, List<String> columns,
+ Boolean deferrable, Boolean initially_deferred, Boolean enabled, Boolean valid
+ ) {
+ this(name, constraint_type, definition, columns, deferrable, initially_deferred, enabled, valid, null);
+ }
+
+ public record OracleConstraintMetadata(
+ boolean metadataComplete, String owner, String constraintType, String status, String validated,
+ String deferrable, String deferred, String rely, String indexOwner, String indexName,
+ String indexSharing, OracleConstraintIndexMetadata index
+ ) {}
+
+ public record OracleConstraintIndexMetadata(
+ boolean metadataComplete, String owner, String tableOwner, String tableName, String indexType,
+ String uniqueness, String status, boolean partitioned, String visibility, String secondary,
+ List<String> columns, List<String> directions, List<Boolean> keyIsExpression, List<String> includedColumns
+ ) {}
}
diff --git a/agents/common/src/main/java/com/dbx/agent/ForeignKeyInfo.java b/agents/common/src/main/java/com/dbx/agent/ForeignKeyInfo.java
index de018df94c..1ffab7c648 100644
--- a/agents/common/src/main/java/com/dbx/agent/ForeignKeyInfo.java
+++ b/agents/common/src/main/java/com/dbx/agent/ForeignKeyInfo.java
@@ -7,16 +7,33 @@ public final class ForeignKeyInfo {
private String column;
private String ref_table;
private String ref_column;
+ private String ref_schema;
+ private String on_delete;
public ForeignKeyInfo() {
this("", "", "", "");
}
public ForeignKeyInfo(String name, String column, String ref_table, String ref_column) {
+ this(name, column, ref_table, ref_column, null, null);
+ }
+
+ public ForeignKeyInfo(String name, String column, String ref_table, String ref_column,
+ String ref_schema, String on_delete) {
this.name = name;
this.column = column;
this.ref_table = ref_table;
this.ref_column = ref_column;
+ this.ref_schema = ref_schema;
+ this.on_delete = on_delete;
+ }
+
+ public String getRef_schema() {
+ return ref_schema;
+ }
+
+ public String getOn_delete() {
+ return on_delete;
}
public String getName() {
@@ -59,12 +76,14 @@ public final class ForeignKeyInfo {
return Objects.equals(name, that.name)
&& Objects.equals(column, that.column)
&& Objects.equals(ref_table, that.ref_table)
- && Objects.equals(ref_column, that.ref_column);
+ && Objects.equals(ref_column, that.ref_column)
+ && Objects.equals(ref_schema, that.ref_schema)
+ && Objects.equals(on_delete, that.on_delete);
}
@Override
public int hashCode() {
- return Objects.hash(name, column, ref_table, ref_column);
+ return Objects.hash(name, column, ref_table, ref_column, ref_schema, on_delete);
}
@Override
diff --git a/agents/common/src/main/java/com/dbx/agent/IndexInfo.java b/agents/common/src/main/java/com/dbx/agent/IndexInfo.java
index ca8034b15c..4ca3109c99 100644
--- a/agents/common/src/main/java/com/dbx/agent/IndexInfo.java
+++ b/agents/common/src/main/java/com/dbx/agent/IndexInfo.java
@@ -18,6 +18,9 @@ public final class IndexInfo {
// doesn't track this (provenance unknown for that dialect/path). Mirrors
// crate::types::IndexInfo::key_is_expression on the Rust side (#6312 review).
private List<Boolean> key_is_expression;
+ private List<String> key_directions = Collections.emptyList();
+ private String visibility;
+ private boolean key_metadata_complete;
private List<Integer> key_options = Collections.emptyList();
// True when this index is the object behind a table constraint (PRIMARY KEY / UNIQUE)
// instead of a standalone index. Dameng lists both kinds in ALL_INDEXES but only accepts
@@ -105,6 +108,18 @@ public final class IndexInfo {
return key_is_expression;
}
+ public List<String> getKey_directions() {
+ return key_directions;
+ }
+
+ public String getVisibility() {
+ return visibility;
+ }
+
+ public boolean getKey_metadata_complete() {
+ return key_metadata_complete;
+ }
+
public List<Integer> getKey_options() {
return key_options;
}
@@ -149,6 +164,18 @@ public final class IndexInfo {
this.key_is_expression = key_is_expression;
}
+ public void setKey_directions(List<String> key_directions) {
+ this.key_directions = key_directions == null ? Collections.emptyList() : key_directions;
+ }
+
+ public void setVisibility(String visibility) {
+ this.visibility = visibility;
+ }
+
+ public void setKey_metadata_complete(boolean key_metadata_complete) {
+ this.key_metadata_complete = key_metadata_complete;
+ }
+
public void setKey_options(List<Integer> key_options) {
this.key_options = key_options == null ? Collections.emptyList() : key_options;
}
@@ -172,6 +199,9 @@ public final class IndexInfo {
&& Objects.equals(included_columns, that.included_columns)
&& Objects.equals(comment, that.comment)
&& Objects.equals(key_is_expression, that.key_is_expression)
+ && Objects.equals(key_directions, that.key_directions)
+ && Objects.equals(visibility, that.visibility)
+ && key_metadata_complete == that.key_metadata_complete
&& Objects.equals(key_options, that.key_options);
}
@@ -187,6 +217,9 @@ public final class IndexInfo {
included_columns,
comment,
key_is_expression,
+ key_directions,
+ visibility,
+ key_metadata_complete,
key_options,
constraint_backed
);
@@ -203,6 +236,9 @@ public final class IndexInfo {
+ ", included_columns=" + included_columns
+ ", comment=" + comment
+ ", key_is_expression=" + key_is_expression
+ + ", key_directions=" + key_directions
+ + ", visibility=" + visibility
+ + ", key_metadata_complete=" + key_metadata_complete
+ ", key_options=" + key_options
+ ", constraint_backed=" + constraint_backed
+ ")";
diff --git a/agents/common/src/test/java/com/dbx/agent/ForeignKeyInfoTest.java b/agents/common/src/test/java/com/dbx/agent/ForeignKeyInfoTest.java
new file mode 100644
index 0000000000..f401de380d
--- /dev/null
+++ b/agents/common/src/test/java/com/dbx/agent/ForeignKeyInfoTest.java
@@ -0,0 +1,32 @@
+package com.dbx.agent;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonParser;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class ForeignKeyInfoTest {
+ private final Gson gson = new Gson();
+
+ @Test
+ void legacyConstructorKeepsTheExistingJsonShape() {
+ ForeignKeyInfo key = new ForeignKeyInfo("FK", "A", "PARENT", "ID");
+ assertEquals(JsonParser.parseString("{\"name\":\"FK\",\"column\":\"A\",\"ref_table\":\"PARENT\",\"ref_column\":\"ID\"}"), gson.toJsonTree(key));
+ ForeignKeyInfo decoded = gson.fromJson(gson.toJson(key), ForeignKeyInfo.class);
+ assertEquals(key, decoded);
+ assertNull(decoded.getRef_schema());
+ assertNull(decoded.getOn_delete());
+ }
+
+ @Test
+ void ownerAndDeleteActionSurviveJsonAndParticipateInIdentity() {
+ ForeignKeyInfo key = new ForeignKeyInfo("FK", "A", "PARENT", "ID", "Mixed.Owner", "SET NULL");
+ var json = gson.toJsonTree(key).getAsJsonObject();
+ assertEquals("Mixed.Owner", json.get("ref_schema").getAsString());
+ assertEquals("SET NULL", json.get("on_delete").getAsString());
+ assertEquals(key, gson.fromJson(json, ForeignKeyInfo.class));
+ assertNotEquals(key, new ForeignKeyInfo("FK", "A", "PARENT", "ID", "OTHER", "SET NULL"));
+ assertNotEquals(key, new ForeignKeyInfo("FK", "A", "PARENT", "ID", "Mixed.Owner", "CASCADE"));
+ }
+}
diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java
index 38af2ddac4..d3be303534 100644
--- a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java
+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java
@@ -51,6 +51,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
@@ -1761,13 +1762,19 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
String tableName = normalizeObjectName(table);
String sql = """
SELECT i.INDEX_NAME, ic.COLUMN_NAME, ic.COLUMN_POSITION, i.UNIQUENESS,
- c.CONSTRAINT_TYPE, i.INDEX_TYPE
+ c.CONSTRAINT_TYPE, i.INDEX_TYPE, i.PARTITIONED, i.VISIBILITY, ic.DESCEND, ie.COLUMN_EXPRESSION
FROM ALL_INDEXES i
JOIN ALL_IND_COLUMNS ic
ON i.INDEX_NAME = ic.INDEX_NAME
AND i.OWNER = ic.INDEX_OWNER
AND i.TABLE_OWNER = ic.TABLE_OWNER
AND i.TABLE_NAME = ic.TABLE_NAME
+ LEFT JOIN ALL_IND_EXPRESSIONS ie
+ ON ie.INDEX_OWNER = ic.INDEX_OWNER
+ AND ie.INDEX_NAME = ic.INDEX_NAME
+ AND ie.TABLE_OWNER = ic.TABLE_OWNER
+ AND ie.TABLE_NAME = ic.TABLE_NAME
+ AND ie.COLUMN_POSITION = ic.COLUMN_POSITION
LEFT JOIN ALL_CONSTRAINTS c
ON i.INDEX_NAME = c.INDEX_NAME
AND i.TABLE_OWNER = c.OWNER
@@ -1777,39 +1784,51 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
ORDER BY i.INDEX_NAME, ic.COLUMN_POSITION
""".stripIndent().trim();
- Map<String, List<String>> columnsByIndex = new LinkedHashMap<>();
- Map<String, Boolean> uniqueByIndex = new LinkedHashMap<>();
- Map<String, Boolean> primaryByIndex = new LinkedHashMap<>();
- Map<String, String> typeByIndex = new LinkedHashMap<>();
+ Map<String, IndexInfo> indexesByName = new LinkedHashMap<>();
try (var stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, owner);
stmt.setString(2, tableName);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
- columnsByIndex.computeIfAbsent(indexName, ignored -> new ArrayList<>()).add(rs.getString("COLUMN_NAME"));
- uniqueByIndex.put(indexName, "UNIQUE".equalsIgnoreCase(rs.getString("UNIQUENESS")));
- primaryByIndex.put(indexName, "P".equalsIgnoreCase(rs.getString("CONSTRAINT_TYPE")));
- typeByIndex.put(indexName, rs.getString("INDEX_TYPE"));
+ IndexInfo index = indexesByName.get(indexName);
+ if (index == null) {
+ IndexInfo item = new IndexInfo(indexName, new ArrayList<>(),
+ "UNIQUE".equalsIgnoreCase(rs.getString("UNIQUENESS")),
+ "P".equalsIgnoreCase(rs.getString("CONSTRAINT_TYPE")),
+ null, rs.getString("INDEX_TYPE"), null, null);
+ item.setKey_is_expression(new ArrayList<>());
+ item.setKey_directions(new ArrayList<>());
+ item.setKey_metadata_complete(true);
+ item.setVisibility(rs.getString("VISIBILITY"));
+ indexesByName.put(indexName, item);
+ index = item;
+ }
+ String column = rs.getString("COLUMN_NAME");
+ String expression = rs.getString("COLUMN_EXPRESSION");
+ String indexType = rs.getString("INDEX_TYPE");
+ String partitioned = rs.getString("PARTITIONED");
+ boolean isExpression = expression != null && !expression.trim().isEmpty();
+ int position = rs.getInt("COLUMN_POSITION");
+ String direction = rs.getString("DESCEND");
+ String visibility = rs.getString("VISIBILITY");
+ if (position != index.getColumns().size() + 1
+ || !("ASC".equals(direction) || "DESC".equals(direction))
+ || !("VISIBLE".equals(visibility) || "INVISIBLE".equals(visibility))
+ || !Objects.equals(index.getVisibility(), visibility)
+ || !"NO".equals(partitioned)
+ || !("NORMAL".equals(indexType) || "FUNCTION-BASED NORMAL".equals(indexType))
+ || (!isExpression && column != null && column.startsWith("SYS_NC") && column.endsWith("$"))) {
+ index.setKey_metadata_complete(false);
+ }
+ index.getColumns().add(isExpression ? expression : Objects.toString(column, ""));
+ index.getKey_is_expression().add(isExpression);
+ index.getKey_directions().add(Objects.toString(direction, ""));
}
}
}
- List<IndexInfo> result = new ArrayList<>();
- for (Map.Entry<String, List<String>> entry : columnsByIndex.entrySet()) {
- String name = entry.getKey();
- result.add(new IndexInfo(
- name,
- entry.getValue(),
- Boolean.TRUE.equals(uniqueByIndex.get(name)),
- Boolean.TRUE.equals(primaryByIndex.get(name)),
- null,
- typeByIndex.get(name),
- null,
- null
- ));
- }
- return result;
+ return new ArrayList<>(indexesByName.values());
});
}
@@ -1818,31 +1837,57 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
return unchecked(() -> {
String owner = normalizeSchema(schema);
String tableName = normalizeObjectName(table);
- String sql = """
- SELECT c.CONSTRAINT_NAME, cc.COLUMN_NAME, rc.TABLE_NAME, rcc.COLUMN_NAME
- FROM ALL_CONSTRAINTS c
- JOIN ALL_CONS_COLUMNS cc ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME AND c.OWNER = cc.OWNER
- JOIN ALL_CONSTRAINTS rc ON c.R_CONSTRAINT_NAME = rc.CONSTRAINT_NAME AND c.R_OWNER = rc.OWNER
- JOIN ALL_CONS_COLUMNS rcc
- ON rc.CONSTRAINT_NAME = rcc.CONSTRAINT_NAME
- AND rc.OWNER = rcc.OWNER
- AND cc.POSITION = rcc.POSITION
- WHERE c.CONSTRAINT_TYPE = 'R' AND c.OWNER = ? AND c.TABLE_NAME = ?
- ORDER BY c.CONSTRAINT_NAME, cc.POSITION
- """.stripIndent().trim();
-
- List<ForeignKeyInfo> result = new ArrayList<>();
- try (var stmt = requireConnection().prepareStatement(sql)) {
+ try (var stmt = requireConnection().prepareStatement(
+ "SELECT TABLE_NAME FROM SYS.ALL_TABLES WHERE OWNER = ? AND TABLE_NAME = ?")) {
stmt.setString(1, owner);
stmt.setString(2, tableName);
+ try (ResultSet rs = stmt.executeQuery()) {
+ if (!rs.next()) throw new SQLException("Table does not exist or is not accessible", "42000");
+ }
+ }
+ String user;
+ try (var stmt = requireConnection().prepareStatement("SELECT USER FROM DUAL");
+ ResultSet rs = stmt.executeQuery()) {
+ if (!rs.next()) throw new SQLException("Current user is unavailable", "42000");
+ user = rs.getString(1);
+ if (user == null || user.isEmpty() || rs.next()) throw new SQLException("Invalid current user metadata", "42000");
+ }
+ // Column-level REFERENCES may hide even the source FK from ALL_CONSTRAINTS.
+ boolean ownTable = owner.equals(user);
+ String sql = ownTable
+ ? "SELECT c.CONSTRAINT_NAME, c.R_OWNER, c.DELETE_RULE FROM SYS.USER_CONSTRAINTS c WHERE c.CONSTRAINT_TYPE = 'R' AND c.TABLE_NAME = ? ORDER BY c.CONSTRAINT_NAME"
+ : "SELECT c.CONSTRAINT_NAME, c.R_OWNER, c.DELETE_RULE FROM SYS.ALL_CONSTRAINTS c WHERE c.CONSTRAINT_TYPE = 'R' AND c.OWNER = ? AND c.TABLE_NAME = ? ORDER BY c.CONSTRAINT_NAME";
+ record ForeignKeyReference(String name, String owner, String deleteRule) {}
+ List<ForeignKeyReference> references = new ArrayList<>();
+ var names = new java.util.HashSet<String>();
+ try (var stmt = requireConnection().prepareStatement(sql)) {
+ if (ownTable) {
+ stmt.setString(1, tableName);
+ } else {
+ stmt.setString(1, owner);
+ stmt.setString(2, tableName);
+ }
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
- result.add(new ForeignKeyInfo(
- rs.getString(1),
- rs.getString(2),
- rs.getString(3),
- rs.getString(4)
- ));
+ String name = rs.getString(1);
+ if (name == null || !names.add(name)) throw new SQLException("Invalid foreign key metadata", "42000");
+ references.add(new ForeignKeyReference(name, rs.getString(2), rs.getString(3)));
+ }
+ }
+ }
+ List<ForeignKeyInfo> result = new ArrayList<>();
+ // ALL_CONS_COLUMNS positions do not retain reordered referenced columns on OceanBase.
+ // Read the actual constraint definition rather than guessing pairs from the parent key.
+ for (var reference : references) {
+ try (var stmt = requireConnection().prepareStatement(
+ "SELECT DBMS_METADATA.GET_DDL('REF_CONSTRAINT', ?, ?) FROM DUAL")) {
+ stmt.setString(1, reference.name());
+ stmt.setString(2, owner);
+ try (ResultSet rs = stmt.executeQuery()) {
+ if (!rs.next()) throw new SQLException("Foreign key definition is unavailable", "42000");
+ result.addAll(OracleForeignKeyDefinition.read(rs.getString(1), owner, tableName,
+ reference.name(), reference.owner(), reference.deleteRule()));
+ if (rs.next()) throw new SQLException("Foreign key definition is ambiguous", "42000");
}
}
}
@@ -1858,6 +1903,7 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
String sql = """
SELECT c.CONSTRAINT_NAME, c.CONSTRAINT_TYPE, c.SEARCH_CONDITION,
c.STATUS, c.VALIDATED, c.DEFERRABLE, c.DEFERRED, c.GENERATED,
+ c.RELY, c.INDEX_OWNER, c.INDEX_NAME,
cc.COLUMN_NAME, tc.NULLABLE
FROM ALL_TABLES t
LEFT JOIN ALL_CONSTRAINTS c ON c.OWNER = t.OWNER AND c.TABLE_NAME = t.TABLE_NAME
@@ -1870,6 +1916,7 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
ORDER BY c.CONSTRAINT_NAME, cc.POSITION
""".stripIndent().trim();
Map<String, ConstraintInfo> result = new LinkedHashMap<>();
+ Map<String, ConstraintInfo.OracleConstraintMetadata> oracleMetadata = new LinkedHashMap<>();
try (var stmt = requireConnection().prepareStatement(sql)) {
stmt.setString(1, owner);
stmt.setString(2, tableName);
@@ -1890,6 +1937,7 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
+ "\\s+(?i:IS\\s+NOT\\s+NULL)\\s*")) continue;
ConstraintInfo constraint = result.get(name);
if (constraint == null) {
+ String constraintType = rs.getString("CONSTRAINT_TYPE");
String type = switch (rs.getString("CONSTRAINT_TYPE")) {
case "P" -> "PRIMARY KEY";
case "U" -> "UNIQUE";
@@ -1902,6 +1950,16 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
constraintState(rs.getString("STATUS"), "ENABLED", "DISABLED"),
constraintState(rs.getString("VALIDATED"), "VALIDATED", "NOT VALIDATED"));
result.put(name, constraint);
+ String status = rs.getString("STATUS");
+ String validated = rs.getString("VALIDATED");
+ String deferrable = rs.getString("DEFERRABLE");
+ String deferred = rs.getString("DEFERRED");
+ oracleMetadata.put(name, new ConstraintInfo.OracleConstraintMetadata(
+ status != null && validated != null && deferrable != null && deferred != null
+ && constraintType != null && ("C".equals(constraintType) ? condition != null : true),
+ owner, constraintType, status, validated, deferrable, deferred,
+ rs.getString("RELY"), rs.getString("INDEX_OWNER"), rs.getString("INDEX_NAME"),
+ null, null));
}
if (column != null) constraint.columns().add(column);
}
@@ -1915,13 +1973,110 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {
definition = constraint.constraint_type() + " (" + String.join(", ",
constraint.columns().stream().map(OceanBaseOracleAgent::quoteIdentifier).toList()) + ")";
}
+ ConstraintInfo.OracleConstraintMetadata metadata = oracleMetadata.get(constraint.name());
+ if ("UNIQUE".equals(constraint.constraint_type()) && metadata != null) {
+ ConstraintInfo.OracleConstraintIndexMetadata index = readOracleUniqueIndexMetadata(
+ owner, tableName, metadata.indexOwner(), metadata.indexName());
+ String sharing = index == null || !index.metadataComplete() ? null
+ : readOracleIndexSharing(owner, tableName, metadata.indexOwner(), metadata.indexName());
+ metadata = new ConstraintInfo.OracleConstraintMetadata(
+ metadata.metadataComplete() && index != null && index.metadataComplete() && sharing != null,
+ metadata.owner(), metadata.constraintType(), metadata.status(), metadata.validated(),
+ metadata.deferrable(), metadata.deferred(), metadata.rely(), metadata.indexOwner(),
+ metadata.indexName(), sharing, index);
+ }
return new ConstraintInfo(constraint.name(), constraint.constraint_type(), definition,
constraint.columns(), constraint.deferrable(), constraint.initially_deferred(),
- constraint.enabled(), constraint.valid());
+ constraint.enabled(), constraint.valid(), metadata);
}).toList();
});
}
+ private ConstraintInfo.OracleConstraintIndexMetadata readOracleUniqueIndexMetadata(
+ String tableOwner, String tableName, String indexOwner, String indexName
+ ) {
+ var columns = new ArrayList<String>();
+ var directions = new ArrayList<String>();
+ var expressions = new ArrayList<Boolean>();
+ String actualOwner = null, actualTableOwner = null, actualTable = null;
+ String indexType = null, uniqueness = null, status = null, partitioned = null, visibility = null, secondary = null;
+ try (var statement = requireConnection().prepareStatement("""
+ SELECT i.OWNER, i.TABLE_OWNER, i.TABLE_NAME, i.INDEX_TYPE, i.UNIQUENESS, i.STATUS,
+ i.PARTITIONED, i.VISIBILITY, i.SECONDARY, ic.COLUMN_NAME, ic.DESCEND,
+ ie.COLUMN_EXPRESSION, ic.COLUMN_POSITION
+ FROM ALL_INDEXES i
+ JOIN ALL_IND_COLUMNS ic ON ic.INDEX_OWNER = i.OWNER AND ic.INDEX_NAME = i.INDEX_NAME
+ LEFT JOIN ALL_IND_EXPRESSIONS ie ON ie.INDEX_OWNER = ic.INDEX_OWNER
+ AND ie.INDEX_NAME = ic.INDEX_NAME AND ie.TABLE_OWNER = ic.TABLE_OWNER
+ AND ie.TABLE_NAME = ic.TABLE_NAME AND ie.COLUMN_POSITION = ic.COLUMN_POSITION
+ WHERE i.OWNER = ? AND i.INDEX_NAME = ? AND i.TABLE_OWNER = ? AND i.TABLE_NAME = ?
+ ORDER BY ic.COLUMN_POSITION
+ """)) {
+ statement.setString(1, indexOwner);
+ statement.setString(2, indexName);
+ statement.setString(3, tableOwner);
+ statement.setString(4, tableName);
+ try (var rs = statement.executeQuery()) {
+ int expectedPosition = 1;
+ while (rs.next()) {
+ actualOwner = rs.getString("OWNER");
+ actualTableOwner = rs.getString("TABLE_OWNER");
+ actualTable = rs.getString("TABLE_NAME");
+ indexType = rs.getString("INDEX_TYPE");
+ uniqueness = rs.getString("UNIQUENESS");
+ status = rs.getString("STATUS");
+ partitioned = rs.getString("PARTITIONED");
+ visibility = rs.getString("VISIBILITY");
+ secondary = rs.getString("SECONDARY");
+ String column = rs.getString("COLUMN_NAME");
+ String direction = rs.getString("DESCEND");
+ String expression = rs.getString("COLUMN_EXPRESSION");
+ int position = rs.getInt("COLUMN_POSITION");
+ if (rs.wasNull() || position != expectedPosition++ || column == null || direction == null) return null;
+ columns.add(column);
+ directions.add(direction);
+ expressions.add(expression != null && !expression.isBlank());
+ }
+ }
+ } catch (SQLException failure) {
+ return null;
+ }
+ boolean complete = actualOwner != null && actualTableOwner != null && actualTable != null
+ && indexType != null && uniqueness != null && status != null
+ && ("YES".equals(partitioned) || "NO".equals(partitioned)) && visibility != null
+ && !columns.isEmpty() && columns.size() == directions.size()
+ && columns.size() == expressions.size();
+ return new ConstraintInfo.OracleConstraintIndexMetadata(complete,
+ actualOwner == null ? indexOwner : actualOwner,
+ actualTableOwner == null ? tableOwner : actualTableOwner,
+ actualTable == null ? tableName : actualTable,
+ indexType == null ? "" : indexType, uniqueness == null ? "" : uniqueness,
+ status == null ? "" : status, "YES".equals(partitioned),
+ visibility == null ? "" : visibility, secondary,
+ List.copyOf(columns), List.copyOf(directions), List.copyOf(expressions), List.of());
+ }
+
+ private String readOracleIndexSharing(String tableOwner, String tableName, String indexOwner, String indexName) {
+ try (var statement = requireConnection().prepareStatement("""
+ SELECT COUNT(*) FROM ALL_CONSTRAINTS
+ WHERE OWNER = ? AND TABLE_NAME = ? AND INDEX_OWNER = ? AND INDEX_NAME = ?
+ AND CONSTRAINT_TYPE IN ('P', 'U')
+ """)) {
+ statement.setString(1, tableOwner);
+ statement.setString(2, tableName);
+ statement.setString(3, indexOwner);
+ statement.setString(4, indexName);
+ try (var rs = statement.executeQuery()) {
+ if (!rs.next()) return null;
+ int count = rs.getInt(1);
+ if (rs.wasNull() || rs.next() || count < 1) return null;
+ return count == 1 ? "exclusive" : "shared";
+ }
+ } catch (SQLException failure) {
+ return null;
+ }
+ }
+
private static Boolean constraintState(String value, String yes, String no) {
if (yes.equals(value)) return true;
if (no.equals(value)) return false;
diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OracleForeignKeyDefinition.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OracleForeignKeyDefinition.java
new file mode 100644
index 0000000000..2aa122d0c8
--- /dev/null
+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OracleForeignKeyDefinition.java
@@ -0,0 +1,131 @@
+package com.dbx.agent.oceanbaseoracle;
+
+import com.dbx.agent.ForeignKeyInfo;
+
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/** Reads the quoted REF_CONSTRAINT DDL emitted by OceanBase, never executable SQL. */
+final class OracleForeignKeyDefinition {
+ private final String ddl;
+ private int offset;
+
+ private OracleForeignKeyDefinition(String ddl) throws SQLException {
+ if (ddl == null || ddl.isBlank()) throw invalid();
+ this.ddl = ddl;
+ }
+
+ static List<ForeignKeyInfo> read(String ddl, String owner, String table, String name,
+ String refOwner, String deleteRule) throws SQLException {
+ OracleForeignKeyDefinition input = new OracleForeignKeyDefinition(ddl);
+ input.word("ALTER"); input.word("TABLE");
+ String sourceOwner = input.identifier(); input.symbol('.');
+ String sourceTable = input.identifier();
+ input.word("ADD"); input.word("CONSTRAINT");
+ String constraint = input.identifier();
+ input.word("FOREIGN"); input.word("KEY");
+ List<String> columns = input.identifiers();
+ input.word("REFERENCES");
+ String targetOwner = input.identifier(); input.symbol('.');
+ String targetTable = input.identifier();
+ List<String> references = input.identifiers();
+ String action = "NO ACTION";
+ if (input.takeWord("ON")) {
+ input.word("DELETE");
+ if (input.takeWord("CASCADE")) action = "CASCADE";
+ else { input.word("SET"); input.word("NULL"); action = "SET NULL"; }
+ }
+ Set<String> states = new HashSet<>();
+ while (!input.finished()) {
+ String category;
+ if (input.takeWord("ENABLE") || input.takeWord("DISABLE")) category = "enabled";
+ else if (input.takeWord("VALIDATE") || input.takeWord("NOVALIDATE")) category = "validated";
+ else if (input.takeWord("RELY") || input.takeWord("NORELY")) category = "rely";
+ else if (input.takeWord("DEFERRABLE")) category = "deferrable";
+ else if (input.takeWord("NOT")) { input.word("DEFERRABLE"); category = "deferrable"; }
+ else if (input.takeWord("INITIALLY")) {
+ if (!input.takeWord("IMMEDIATE") && !input.takeWord("DEFERRED")) throw invalid();
+ category = "initially";
+ } else throw invalid();
+ if (!states.add(category)) throw invalid();
+ }
+ if (!owner.equals(sourceOwner) || !table.equals(sourceTable) || !name.equals(constraint)
+ || !targetOwner.equals(refOwner) || !action.equals(deleteRule) || columns.size() != references.size()) {
+ throw invalid();
+ }
+ List<ForeignKeyInfo> result = new ArrayList<>();
+ for (int i = 0; i < columns.size(); i++) {
+ result.add(new ForeignKeyInfo(name, columns.get(i), targetTable, references.get(i), targetOwner, action));
+ }
+ return result;
+ }
+
+ private List<String> identifiers() throws SQLException {
+ symbol('(');
+ List<String> result = new ArrayList<>();
+ result.add(identifier());
+ while (takeSymbol(',')) result.add(identifier());
+ symbol(')');
+ if (new HashSet<>(result).size() != result.size()) throw invalid();
+ return result;
+ }
+
+ private String identifier() throws SQLException {
+ symbol('"');
+ StringBuilder value = new StringBuilder();
+ while (offset < ddl.length()) {
+ char ch = ddl.charAt(offset++);
+ if (ch != '"') { value.append(ch); continue; }
+ if (offset < ddl.length() && ddl.charAt(offset) == '"') {
+ offset++; value.append('"'); continue;
+ }
+ if (value.isEmpty()) throw invalid();
+ return value.toString();
+ }
+ throw invalid();
+ }
+
+ private void whitespace() {
+ while (offset < ddl.length() && Character.isWhitespace(ddl.charAt(offset))) offset++;
+ }
+
+ private boolean takeSymbol(char symbol) {
+ whitespace();
+ if (offset >= ddl.length() || ddl.charAt(offset) != symbol) return false;
+ offset++;
+ return true;
+ }
+
+ private void symbol(char symbol) throws SQLException {
+ if (!takeSymbol(symbol)) throw invalid();
+ }
+
+ private boolean takeWord(String word) {
+ whitespace();
+ int end = offset + word.length();
+ if (!ddl.regionMatches(true, offset, word, 0, word.length())) return false;
+ if (end < ddl.length() && (Character.isLetterOrDigit(ddl.charAt(end)) || ddl.charAt(end) == '_')) return false;
+ offset = end;
+ return true;
+ }
+
+ private void word(String word) throws SQLException {
+ if (!takeWord(word)) throw invalid();
+ }
+
+ private boolean finished() throws SQLException {
+ whitespace();
+ if (takeSymbol(';')) {
+ whitespace();
+ if (offset != ddl.length()) throw invalid();
+ }
+ return offset == ddl.length();
+ }
+
+ private static SQLException invalid() {
+ return new SQLException("Foreign key definition is incomplete, unsupported, or inconsistent with its metadata", "42000");
+ }
+}
diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleForeignKeyRpcTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleForeignKeyRpcTest.java
new file mode 100644
index 0000000000..d36c1588be
--- /dev/null
+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleForeignKeyRpcTest.java
@@ -0,0 +1,192 @@
+package com.dbx.agent;
+
+import com.dbx.agent.oceanbaseoracle.OceanBaseOracleAgent;
+import com.dbx.agent.test.TestSupport;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class OceanBaseOracleForeignKeyRpcTest {
+ @Test
+ void readsOwnKeyHiddenFromAllByColumnLevelReferenceGrant() {
+ Fixture jdbc = new Fixture();
+ jdbc.hiddenFromAll = true;
+ assertEquals(2, jdbc.request().getAsJsonArray("result").size());
+ assertTrue(jdbc.queries.stream().anyMatch(sql -> sql.contains("SYS.USER_CONSTRAINTS") && !sql.contains("c.OWNER")));
+ }
+
+ @Test
+ void neverUsesUserConstraintsForAnotherOrDifferentlyCasedOwner() {
+ for (String user : List.of("OTHER", "app")) {
+ Fixture jdbc = new Fixture(); jdbc.currentUser = user; jdbc.hiddenFromAll = true;
+ assertEquals(0, jdbc.request().getAsJsonArray("result").size());
+ assertTrue(jdbc.queries.stream().anyMatch(sql -> sql.contains("SYS.ALL_CONSTRAINTS")));
+ assertFalse(jdbc.queries.stream().anyMatch(sql -> sql.contains("SYS.USER_CONSTRAINTS")));
+ }
+ }
+
+ @Test
+ void rejectsMissingOrAmbiguousUserInsteadOfFallingBackToEmptyAll() {
+ for (int count : List.of(0, 2)) {
+ Fixture jdbc = new Fixture(); jdbc.userCount = count;
+ assertTrue(jdbc.request().has("error"));
+ }
+ Fixture blank = new Fixture(); blank.currentUser = "";
+ assertTrue(blank.request().has("error"));
+ }
+ @Test
+ void returnsActualReferencedColumnPairsAndOwnerThroughProductionRpc() {
+ Fixture jdbc = new Fixture();
+ JsonObject response = jdbc.request();
+ assertFalse(response.has("error"), response.toString());
+ var keys = response.getAsJsonArray("result");
+ assertEquals(2, keys.size());
+ var first = keys.get(0).getAsJsonObject();
+ assertEquals("B", first.get("column").getAsString());
+ assertEquals("V", first.get("ref_column").getAsString());
+ assertEquals("PARENT_OWNER", first.get("ref_schema").getAsString());
+ assertEquals("CASCADE", first.get("on_delete").getAsString());
+ assertEquals("A", keys.get(1).getAsJsonObject().get("column").getAsString());
+ assertEquals("ID", keys.get(1).getAsJsonObject().get("ref_column").getAsString());
+ assertTrue(jdbc.parameters.contains(List.of("FK_SOURCE", "APP")), jdbc.parameters.toString());
+ }
+
+ @Test
+ void preservesQuotedCommaAndEscapedQuoteIdentifiers() {
+ Fixture jdbc = new Fixture();
+ jdbc.ddl = "ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"FK_SOURCE\" FOREIGN KEY (\"Local,One\", \"Local\"\"Two\") REFERENCES \"PARENT_OWNER\".\"Parent,Table\" (\"Ref,One\", \"Ref\"\"Two\") ON DELETE SET NULL ENABLE";
+ jdbc.deleteRule = "SET NULL";
+ var response = jdbc.request();
+ assertFalse(response.has("error"), response.toString());
+ var keys = response.getAsJsonArray("result");
+ assertEquals("Local,One", keys.get(0).getAsJsonObject().get("column").getAsString());
+ assertEquals("Ref,One", keys.get(0).getAsJsonObject().get("ref_column").getAsString());
+ assertEquals("Local\"Two", keys.get(1).getAsJsonObject().get("column").getAsString());
+ assertEquals("Parent,Table", keys.get(1).getAsJsonObject().get("ref_table").getAsString());
+ assertEquals("SET NULL", keys.get(1).getAsJsonObject().get("on_delete").getAsString());
+ }
+
+ @Test
+ void rejectsUnreadableAndInconsistentDefinitionsInsteadOfReturningWrongPairs() {
+ for (String ddl : List.of("", "ALTER TABLE \"APP\".\"SOURCE\" ADD",
+ "ALTER TABLE \"OTHER\".\"SOURCE\" ADD CONSTRAINT \"FK_SOURCE\" FOREIGN KEY (\"B\", \"A\") REFERENCES \"PARENT_OWNER\".\"PARENT\" (\"V\", \"ID\") ON DELETE CASCADE ENABLE")) {
+ Fixture jdbc = new Fixture(); jdbc.ddl = ddl;
+ JsonObject response = jdbc.request();
+ assertTrue(response.has("error"), response.toString());
+ assertFalse(response.has("result"), response.toString());
+ }
+ Fixture denied = new Fixture(); denied.ddlFailure = true;
+ JsonObject response = denied.request();
+ assertTrue(response.has("error"), response.toString());
+ }
+
+ @Test
+ void distinguishesVisibleEmptyTablesFromHiddenTables() {
+ Fixture empty = new Fixture(); empty.hasForeignKey = false;
+ assertEquals(0, empty.request().getAsJsonArray("result").size());
+ Fixture hidden = new Fixture(); hidden.hasForeignKey = false; hidden.visible = false;
+ assertTrue(hidden.request().has("error"));
+ }
+
+ @Test
+ void rejectsTrailingTextDuplicateColumnsAndConflictingStates() {
+ Fixture valid = new Fixture();
+ for (String ddl : List.of(valid.ddl + " trailing", valid.ddl + "; DROP TABLE X", valid.ddl + " DISABLE",
+ valid.ddl.replace("\"B\", \"A\"", "\"B\", \"B\""),
+ valid.ddl.replace("\"V\", \"ID\"", "\"V\""),
+ valid.ddl.replace("PARENT_OWNER", "OTHER"),
+ valid.ddl.replace("ON DELETE CASCADE", "ON DELETE SET NULL"))) {
+ Fixture jdbc = new Fixture(); jdbc.ddl = ddl;
+ assertTrue(jdbc.request().has("error"), ddl);
+ }
+ }
+
+ @Test
+ void acceptsKnownStateSuffixAndOneTerminalSemicolon() {
+ Fixture jdbc = new Fixture();
+ jdbc.deleteRule = "NO ACTION";
+ jdbc.ddl = jdbc.ddl.replace(" ON DELETE CASCADE ENABLE", " NOT DEFERRABLE INITIALLY IMMEDIATE RELY DISABLE NOVALIDATE;\n");
+ JsonObject response = jdbc.request();
+ assertFalse(response.has("error"), response.toString());
+ assertEquals("NO ACTION", response.getAsJsonArray("result").get(0).getAsJsonObject().get("on_delete").getAsString());
+ }
+
+ private static Map<String, String> row(String... values) {
+ Map<String, String> result = new LinkedHashMap<>();
+ for (int i = 0; i < values.length; i += 2) result.put(values[i], values[i + 1]);
+ return result;
+ }
+
+ private static final class Fixture {
+ String ddl = "ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"FK_SOURCE\" FOREIGN KEY (\"B\", \"A\") REFERENCES \"PARENT_OWNER\".\"PARENT\" (\"V\", \"ID\") ON DELETE CASCADE ENABLE";
+ String deleteRule = "CASCADE";
+ boolean visible = true;
+ boolean hasForeignKey = true;
+ boolean ddlFailure;
+ boolean hiddenFromAll;
+ String currentUser = "APP";
+ int userCount = 1;
+ final List<List<String>> parameters = new ArrayList<>();
+ final List<String> queries = new ArrayList<>();
+
+ List<Map<String, String>> rows(String sql) throws SQLException {
+ queries.add(sql);
+ if (sql.contains("DBMS_METADATA")) {
+ if (ddlFailure) throw new SQLException("ORA-01031: insufficient privileges", "42000", 1031);
+ return List.of(row("DDL", ddl));
+ }
+ if (sql.contains("JOIN ALL_CONS_COLUMNS")) {
+ return !hasForeignKey ? List.of() : List.of(
+ row("CONSTRAINT_NAME", "FK_SOURCE", "COLUMN_NAME", "B", "TABLE_NAME", "PARENT", "REF_COLUMN", "ID"),
+ row("CONSTRAINT_NAME", "FK_SOURCE", "COLUMN_NAME", "A", "TABLE_NAME", "PARENT", "REF_COLUMN", "V"));
+ }
+ if (sql.contains("SELECT USER")) {
+ List<Map<String, String>> users = new ArrayList<>();
+ for (int i = 0; i < userCount; i++) users.add(row("USER", currentUser));
+ return users;
+ }
+ if (sql.contains("USER_CONSTRAINTS")) return !hasForeignKey ? List.of() : List.of(row("CONSTRAINT_NAME", "FK_SOURCE", "R_OWNER", "PARENT_OWNER", "DELETE_RULE", deleteRule));
+ if (sql.contains("ALL_CONSTRAINTS")) return !hasForeignKey || hiddenFromAll ? List.of() : List.of(row("CONSTRAINT_NAME", "FK_SOURCE", "R_OWNER", "PARENT_OWNER", "DELETE_RULE", deleteRule));
+ if (sql.contains("ALL_TABLES")) return visible ? List.of(row("TABLE_NAME", "SOURCE")) : List.of();
+ throw new SQLException("Unexpected query: " + sql);
+ }
+
+ JsonObject request() {
+ Connection connection = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> {
+ if (method.getName().equals("isClosed")) return false;
+ if (!method.getName().equals("prepareStatement")) throw new UnsupportedOperationException(method.getName());
+ String sql = (String) args[0];
+ List<String> bound = new ArrayList<>(); parameters.add(bound);
+ return Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{PreparedStatement.class}, (statement, call, values) -> {
+ if (call.getName().equals("setString")) { bound.add((String) values[1]); return null; }
+ if (call.getName().equals("close")) return null;
+ if (!call.getName().equals("executeQuery")) throw new UnsupportedOperationException(call.getName());
+ List<Map<String, String>> data = rows(sql);
+ int[] index = {-1};
+ return Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{ResultSet.class}, (result, read, arguments) -> switch (read.getName()) {
+ case "next" -> ++index[0] < data.size();
+ case "getString" -> arguments[0] instanceof Integer n ? new ArrayList<>(data.get(index[0]).values()).get(n - 1) : data.get(index[0]).get((String) arguments[0]);
+ case "close" -> null;
+ default -> throw new UnsupportedOperationException(read.getName());
+ });
+ });
+ });
+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
+ TestSupport.setPrivateConnection(agent, connection);
+ JsonRpcServer server = new JsonRpcServer(agent);
+ return JsonParser.parseString(server.handleRequest("{\"id\":1,\"method\":\"list_foreign_keys\",\"params\":{\"schema\":\"APP\",\"table\":\"SOURCE\"}}")).getAsJsonObject();
+ }
+ }
+}
diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.java
new file mode 100644
index 0000000000..bac7910fff
--- /dev/null
+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/OceanBaseOracleIndexRpcTest.java
@@ -0,0 +1,126 @@
+package com.dbx.agent;
+
+import com.dbx.agent.oceanbaseoracle.OceanBaseOracleAgent;
+import com.dbx.agent.test.TestSupport;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class OceanBaseOracleIndexRpcTest {
+ @Test
+ void returnsExpressionDirectionAndVisibilityThroughProductionRpc() {
+ Fixture jdbc = new Fixture(List.of(
+ row("IX_EVENT_EXPR", "SYS_NC00001$", "1", "NONUNIQUE", "I", "FUNCTION-BASED NORMAL", "NO", "LOWER(\"EVENT_NAME\")", "DESC", "INVISIBLE"),
+ row("IX_EVENT_EXPR", "EVENT_TS", "2", "NONUNIQUE", "I", "FUNCTION-BASED NORMAL", "NO", null, "ASC", "INVISIBLE")
+ ));
+
+ JsonObject response = jdbc.request("APP", "EVENTS");
+
+ assertFalse(response.has("error"), response.toString());
+ var indexes = response.getAsJsonArray("result");
+ assertEquals(1, indexes.size());
+ JsonObject index = indexes.get(0).getAsJsonObject();
+ assertEquals(List.of("LOWER(\"EVENT_NAME\")", "EVENT_TS"), index.getAsJsonArray("columns").asList()
+ .stream().map(value -> value.getAsString()).toList());
+ assertEquals(List.of(true, false), index.getAsJsonArray("key_is_expression").asList()
+ .stream().map(value -> value.getAsBoolean()).toList());
+ assertEquals(List.of("DESC", "ASC"), index.getAsJsonArray("key_directions").asList()
+ .stream().map(value -> value.getAsString()).toList());
+ assertEquals("INVISIBLE", index.get("visibility").getAsString());
+ assertTrue(index.get("key_metadata_complete").getAsBoolean());
+ assertTrue(jdbc.sql.get(0).toUpperCase().contains("ALL_IND_EXPRESSIONS"), jdbc.sql.get(0));
+ assertTrue(jdbc.sql.get(0).toUpperCase().contains("DESCEND"), jdbc.sql.get(0));
+ assertTrue(jdbc.sql.get(0).toUpperCase().contains("VISIBILITY"), jdbc.sql.get(0));
+ assertTrue(jdbc.sql.get(0).toUpperCase().contains("PARTITIONED"), jdbc.sql.get(0));
+ assertEquals(List.of("APP", "EVENTS"), jdbc.parameters);
+ }
+
+ @Test
+ void marksUnsupportedIndexShapesIncompleteThroughProductionRpc() {
+ for (Map<String, String> unsupported : List.of(
+ row("IX_EVENT", "EVENT_TS", "1", "NONUNIQUE", "I", "NORMAL", "YES", null, "ASC", "VISIBLE"),
+ row("IX_EVENT", "EVENT_TS", "1", "NONUNIQUE", "I", "FUNCTION-BASED BITMAP", "NO", null, "ASC", "VISIBLE")
+ )) {
+ JsonObject response = new Fixture(List.of(unsupported)).request("APP", "EVENTS");
+
+ assertFalse(response.has("error"), response.toString());
+ var indexes = response.getAsJsonArray("result");
+ assertEquals(1, indexes.size());
+ assertFalse(indexes.get(0).getAsJsonObject().get("key_metadata_complete").getAsBoolean());
+ }
+ }
+
+ private static Map<String, String> row(String name, String column, String position, String uniqueness,
+ String constraintType, String indexType, String partitioned, String expression,
+ String descend, String visibility) {
+ Map<String, String> row = new HashMap<>();
+ row.put("INDEX_NAME", name);
+ row.put("COLUMN_NAME", column);
+ row.put("COLUMN_POSITION", position);
+ row.put("UNIQUENESS", uniqueness);
+ row.put("CONSTRAINT_TYPE", constraintType);
+ row.put("INDEX_TYPE", indexType);
+ row.put("PARTITIONED", partitioned);
+ row.put("COLUMN_EXPRESSION", expression);
+ row.put("DESCEND", descend);
+ row.put("VISIBILITY", visibility);
+ return row;
+ }
+
+ private static final class Fixture {
+ final List<String> sql = new ArrayList<>();
+ final List<String> parameters = new ArrayList<>();
+ final JsonRpcServer server;
+
+ Fixture(List<Map<String, String>> rows) {
+ int[] index = {-1};
+ ResultSet result = (ResultSet) Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class<?>[]{ResultSet.class}, (proxy, method, args) -> switch (method.getName()) {
+ case "next" -> ++index[0] < rows.size();
+ case "getString" -> rows.get(index[0]).get((String) args[0]);
+ case "getInt" -> Integer.parseInt(rows.get(index[0]).get((String) args[0]));
+ case "close" -> null;
+ default -> throw new UnsupportedOperationException(method.getName());
+ });
+ PreparedStatement statement = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class<?>[]{PreparedStatement.class}, (proxy, method, args) -> switch (method.getName()) {
+ case "setString" -> { parameters.add((String) args[1]); yield null; }
+ case "executeQuery" -> result;
+ case "close" -> null;
+ default -> throw new UnsupportedOperationException(method.getName());
+ });
+ Connection connection = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class<?>[]{Connection.class}, (proxy, method, args) -> switch (method.getName()) {
+ case "prepareStatement" -> { sql.add((String) args[0]); yield statement; }
+ case "isClosed" -> false;
+ default -> throw new UnsupportedOperationException(method.getName());
+ });
+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
+ TestSupport.setPrivateConnection(agent, connection);
+ server = new JsonRpcServer(agent);
+ }
+
+ JsonObject request(String schema, String table) {
+ JsonObject params = new JsonObject();
+ params.addProperty("schema", schema);
+ params.addProperty("table", table);
+ JsonObject request = new JsonObject();
+ request.addProperty("id", 1);
+ request.addProperty("method", "list_indexes");
+ request.add("params", params);
+ return JsonParser.parseString(server.handleRequest(request.toString())).getAsJsonObject();
+ }
+ }
+}
diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java
index 382c9be49d..405e7c6274 100644
--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java
+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java
@@ -1296,6 +1296,40 @@ class OceanBaseOracleAgentTest {
Assertions.assertTrue(sql.get(3).contains("ALL_TAB_SUBPARTITIONS"));
}
+ @Test
+ void listsCompleteOracleUniqueConstraintAndPairedIndexMetadata() {
+ List<String> sql = new ArrayList<>();
+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();
+ TestSupport.setPrivateConnection(agent, preparedConnection(sql,
+ resultSet(new String[]{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "STATUS", "VALIDATED",
+ "DEFERRABLE", "DEFERRED", "GENERATED", "RELY", "INDEX_OWNER", "INDEX_NAME", "COLUMN_NAME", "NULLABLE"},
+ new Object[][]{{"UQ_USERS_EMAIL", "U", null, "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE",
+ "USER NAME", null, "APP", "UQ_USERS_EMAIL", "EMAIL", "Y"}}),
+ resultSet(new String[]{"OWNER", "TABLE_OWNER", "TABLE_NAME", "INDEX_TYPE", "UNIQUENESS", "STATUS",
+ "PARTITIONED", "VISIBILITY", "SECONDARY", "COLUMN_NAME", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},
+ new Object[][]{{"APP", "APP", "USERS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", null,
+ "EMAIL", "ASC", null, 1}}),
+ resultSet(new String[]{"COUNT(*)"}, new Object[][]{{1}})));
+
+ var constraints = agent.listConstraints("APP", "USERS");
+
+ Assertions.assertEquals(1, constraints.size());
+ var metadata = constraints.get(0).oracle_metadata();
+ Assertions.assertTrue(metadata.metadataComplete());
+ Assertions.assertNull(metadata.rely());
+ Assertions.assertEquals("APP", metadata.indexOwner());
+ Assertions.assertEquals("exclusive", metadata.indexSharing());
+ Assertions.assertTrue(metadata.index().metadataComplete());
+ Assertions.assertNull(metadata.index().secondary());
+ Assertions.assertEquals(List.of("EMAIL"), metadata.index().columns());
+ Assertions.assertEquals(List.of("ASC"), metadata.index().directions());
+ Assertions.assertEquals(List.of(false), metadata.index().keyIsExpression());
+ Assertions.assertEquals(3, sql.size());
+ Assertions.assertTrue(sql.get(0).contains("c.RELY, c.INDEX_OWNER, c.INDEX_NAME"));
+ Assertions.assertTrue(sql.get(1).contains("ALL_IND_EXPRESSIONS"));
+ Assertions.assertTrue(sql.get(2).contains("COUNT(*) FROM ALL_CONSTRAINTS"));
+ }
+
private static ResultSet columnResultSet(Object[][] rows) {
return resultSet(
new String[]{
diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.go
index a4865e1c9c..41cddd41a4 100644
--- a/agents/drivers/oracle-go/main.go
+++ b/agents/drivers/oracle-go/main.go
@@ -485,19 +485,24 @@ type columnInfo struct {
Comment *string `json:"comment"`
NumericPrecision *int `json:"numeric_precision"`
NumericScale *int `json:"numeric_scale"`
+ DataLength *int `json:"-"`
CharacterMaximumLength *int `json:"character_maximum_length"`
CharacterLengthUnit *string `json:"-"`
}
type indexInfo struct {
- Name string `json:"name"`
- Columns []string `json:"columns"`
- IsUnique bool `json:"is_unique"`
- IsPrimary bool `json:"is_primary"`
- Filter *string `json:"filter"`
- IndexType *string `json:"index_type"`
- IncludedColumns []string `json:"included_columns"`
- Comment *string `json:"comment"`
+ Name string `json:"name"`
+ Columns []string `json:"columns"`
+ IsUnique bool `json:"is_unique"`
+ IsPrimary bool `json:"is_primary"`
+ Filter *string `json:"filter"`
+ IndexType *string `json:"index_type"`
+ IncludedColumns []string `json:"included_columns"`
+ Comment *string `json:"comment"`
+ KeyIsExpression []bool `json:"key_is_expression"`
+ KeyDirections []string `json:"key_directions"`
+ Visibility *string `json:"visibility"`
+ KeyMetadataComplete bool `json:"key_metadata_complete"`
}
func (i indexInfo) MarshalJSON() ([]byte, error) {
@@ -509,6 +514,12 @@ func (i indexInfo) MarshalJSON() ([]byte, error) {
if value.IncludedColumns == nil {
value.IncludedColumns = []string{}
}
+ if value.KeyIsExpression == nil {
+ value.KeyIsExpression = []bool{}
+ }
+ if value.KeyDirections == nil {
+ value.KeyDirections = []string{}
+ }
return json.Marshal(value)
}
@@ -533,20 +544,53 @@ type triggerInfo struct {
// table. Foreign keys are served separately by listForeignKeys, so this only
// covers constraint types 'P', 'U', and 'C'.
type constraintInfo struct {
- Name string `json:"name"`
- ConstraintType string `json:"constraint_type"`
- Definition string `json:"definition"`
- Columns []string `json:"columns"`
- RefSchema *string `json:"ref_schema,omitempty"`
- RefTable *string `json:"ref_table,omitempty"`
- RefColumns []string `json:"ref_columns"`
- MatchType *string `json:"match_type,omitempty"`
- OnUpdate *string `json:"on_update,omitempty"`
- OnDelete *string `json:"on_delete,omitempty"`
- Deferrable bool `json:"deferrable"`
- InitiallyDeferred bool `json:"initially_deferred"`
- Enabled bool `json:"enabled"`
- Valid bool `json:"valid"`
+ Name string `json:"name"`
+ ConstraintType string `json:"constraint_type"`
+ Definition string `json:"definition"`
+ Columns []string `json:"columns"`
+ RefSchema *string `json:"ref_schema,omitempty"`
+ RefTable *string `json:"ref_table,omitempty"`
+ RefColumns []string `json:"ref_columns"`
+ MatchType *string `json:"match_type,omitempty"`
+ OnUpdate *string `json:"on_update,omitempty"`
+ OnDelete *string `json:"on_delete,omitempty"`
+ Deferrable bool `json:"deferrable"`
+ InitiallyDeferred bool `json:"initially_deferred"`
+ Enabled bool `json:"enabled"`
+ Valid bool `json:"valid"`
+ OracleMetadata *oracleConstraintMetadata `json:"oracle_metadata,omitempty"`
+}
+
+type oracleConstraintMetadata struct {
+ MetadataComplete bool `json:"metadataComplete"`
+ Owner string `json:"owner"`
+ ConstraintType *string `json:"constraintType"`
+ Status *string `json:"status"`
+ Validated *string `json:"validated"`
+ Deferrable *string `json:"deferrable"`
+ Deferred *string `json:"deferred"`
+ Rely *string `json:"rely"`
+ IndexOwner *string `json:"indexOwner"`
+ IndexName *string `json:"indexName"`
+ IndexSharing *string `json:"indexSharing"`
+ Index *oracleConstraintIndexMetadata `json:"index"`
+}
+
+type oracleConstraintIndexMetadata struct {
+ MetadataComplete bool `json:"metadataComplete"`
+ Owner string `json:"owner"`
+ TableOwner string `json:"tableOwner"`
+ TableName string `json:"tableName"`
+ IndexType string `json:"indexType"`
+ Uniqueness string `json:"uniqueness"`
+ Status string `json:"status"`
+ Partitioned bool `json:"partitioned"`
+ Visibility string `json:"visibility"`
+ Secondary *string `json:"secondary"`
+ Columns []string `json:"columns"`
+ Directions []string `json:"directions"`
+ KeyIsExpression []bool `json:"keyIsExpression"`
+ IncludedColumns []string `json:"includedColumns"`
}
func (c constraintInfo) MarshalJSON() ([]byte, error) {
@@ -2636,6 +2680,7 @@ SELECT c.COLUMN_NAME,
cc.COMMENTS,
c.DATA_PRECISION,
c.DATA_SCALE,
+ c.DATA_LENGTH,
c.CHAR_LENGTH,
c.CHAR_USED
FROM ALL_TAB_COLUMNS c
@@ -2666,6 +2711,7 @@ ORDER BY c.COLUMN_ID`, []any{schema, table})
&item.Comment,
&item.NumericPrecision,
&item.NumericScale,
+ &item.DataLength,
&item.CharacterMaximumLength,
&item.CharacterLengthUnit,
); err != nil {
@@ -2766,9 +2812,16 @@ SELECT i.INDEX_NAME,
i.UNIQUENESS,
CASE WHEN pk.CONSTRAINT_NAME IS NULL THEN 0 ELSE 1 END AS IS_PRIMARY,
i.INDEX_TYPE,
+ i.PARTITIONED,
+ i.VISIBILITY,
+ ic.DESCEND,
+ ie.COLUMN_EXPRESSION,
ic.COLUMN_POSITION
FROM ALL_INDEXES i
JOIN ALL_IND_COLUMNS ic ON ic.INDEX_OWNER = i.OWNER AND ic.INDEX_NAME = i.INDEX_NAME
+ AND ic.TABLE_OWNER = i.TABLE_OWNER AND ic.TABLE_NAME = i.TABLE_NAME
+LEFT JOIN ALL_IND_EXPRESSIONS ie ON ie.INDEX_OWNER = ic.INDEX_OWNER AND ie.INDEX_NAME = ic.INDEX_NAME
+ AND ie.TABLE_OWNER = ic.TABLE_OWNER AND ie.TABLE_NAME = ic.TABLE_NAME AND ie.COLUMN_POSITION = ic.COLUMN_POSITION
LEFT JOIN ALL_CONSTRAINTS pk ON pk.OWNER = i.TABLE_OWNER
AND pk.TABLE_NAME = i.TABLE_NAME
AND pk.CONSTRAINT_TYPE = 'P'
@@ -2783,26 +2836,44 @@ ORDER BY i.INDEX_NAME, ic.COLUMN_POSITION`, []any{schema, table})
byName := map[string]*indexInfo{}
order := []string{}
for rows.Next() {
- var name, column, uniqueness, indexType string
+ var name, column, uniqueness, indexType, partitioned, visibility, direction string
+ var expression sql.NullString
var primary int
var position int
- if err := rows.Scan(&name, &column, &uniqueness, &primary, &indexType, &position); err != nil {
+ if err := rows.Scan(&name, &column, &uniqueness, &primary, &indexType, &partitioned, &visibility, &direction, &expression, &position); err != nil {
return nil, err
}
item := byName[name]
if item == nil {
+ visible := visibility
item = &indexInfo{
- Name: name,
- Columns: []string{},
- IsUnique: uniqueness == "UNIQUE",
- IsPrimary: primary != 0,
- IndexType: &indexType,
- IncludedColumns: []string{},
+ Name: name,
+ Columns: []string{},
+ IsUnique: uniqueness == "UNIQUE",
+ IsPrimary: primary != 0,
+ IndexType: &indexType,
+ IncludedColumns: []string{},
+ KeyIsExpression: []bool{},
+ KeyDirections: []string{},
+ Visibility: &visible,
+ KeyMetadataComplete: true,
}
byName[name] = item
order = append(order, name)
}
- item.Columns = append(item.Columns, column)
+ if position != len(item.Columns)+1 || (direction != "ASC" && direction != "DESC") || (visibility != "VISIBLE" && visibility != "INVISIBLE") || item.Visibility == nil || *item.Visibility != visibility || partitioned != "NO" || (indexType != "NORMAL" && indexType != "FUNCTION-BASED NORMAL") {
+ item.KeyMetadataComplete = false
+ }
+ key := column
+ isExpression := expression.Valid && strings.TrimSpace(expression.String) != ""
+ if isExpression {
+ key = expression.String
+ } else if strings.HasPrefix(column, "SYS_NC") && strings.HasSuffix(column, "$") {
+ item.KeyMetadataComplete = false
+ }
+ item.Columns = append(item.Columns, key)
+ item.KeyIsExpression = append(item.KeyIsExpression, isExpression)
+ item.KeyDirections = append(item.KeyDirections, direction)
}
if err := rows.Err(); err != nil {
return nil, err
@@ -2901,6 +2972,9 @@ SELECT ac.CONSTRAINT_NAME,
ac.DEFERRABLE,
ac.DEFERRED,
ac.VALIDATED,
+ ac.RELY,
+ ac.INDEX_OWNER,
+ ac.INDEX_NAME,
acc.COLUMN_NAME,
acc.POSITION,
atc.NULLABLE
@@ -2921,9 +2995,9 @@ ORDER BY ac.CONSTRAINT_NAME, acc.POSITION`, []any{schema, table})
order := []string{}
for rows.Next() {
var name, kind string
- var condition, generated, status, deferrable, deferred, validated, column, nullable sql.NullString
+ var condition, generated, status, deferrable, deferred, validated, rely, indexOwner, indexName, column, nullable sql.NullString
var position sql.NullInt64
- if err := rows.Scan(&name, &kind, &condition, &generated, &status, &deferrable, &deferred, &validated, &column, &position, &nullable); err != nil {
+ if err := rows.Scan(&name, &kind, &condition, &generated, &status, &deferrable, &deferred, &validated, &rely, &indexOwner, &indexName, &column, &position, &nullable); err != nil {
return nil, err
}
if skipped[name] {
@@ -2949,12 +3023,44 @@ ORDER BY ac.CONSTRAINT_NAME, acc.POSITION`, []any{schema, table})
InitiallyDeferred: deferred.Valid && deferred.String == "DEFERRED",
Enabled: status.Valid && status.String == "ENABLED",
Valid: validated.Valid && validated.String == "VALIDATED",
+ OracleMetadata: &oracleConstraintMetadata{
+ MetadataComplete: kind != "" && status.Valid && validated.Valid && deferrable.Valid && deferred.Valid &&
+ (kind != "C" || condition.Valid),
+ Owner: schema,
+ ConstraintType: stringPointer(kind),
+ Status: nullableStringPointer(status),
+ Validated: nullableStringPointer(validated),
+ Deferrable: nullableStringPointer(deferrable),
+ Deferred: nullableStringPointer(deferred),
+ Rely: nullableStringPointer(rely),
+ IndexOwner: nullableStringPointer(indexOwner),
+ IndexName: nullableStringPointer(indexName),
+ },
+ }
+ if kind == "U" {
+ if status.Valid && status.String == "DISABLED" && !indexOwner.Valid && !indexName.Valid {
+ item.OracleMetadata.Index = nil
+ item.OracleMetadata.IndexSharing = nil
+ } else {
+ item.OracleMetadata.Index, item.OracleMetadata.IndexSharing = s.oracleUniqueIndexMetadata(schema, table, indexOwner, indexName)
+ if item.OracleMetadata.Index == nil || !item.OracleMetadata.Index.MetadataComplete || item.OracleMetadata.IndexSharing == nil {
+ item.OracleMetadata.MetadataComplete = false
+ }
+ }
}
byName[name] = item
order = append(order, name)
}
if column.Valid && column.String != "" {
+ if !position.Valid || position.Int64 != int64(len(item.Columns)+1) {
+ item.OracleMetadata.MetadataComplete = false
+ }
item.Columns = append(item.Columns, column.String)
+ } else if position.Valid {
+ item.OracleMetadata.MetadataComplete = false
+ }
+ if item.OracleMetadata.IndexOwner == nil != (item.OracleMetadata.IndexName == nil) {
+ item.OracleMetadata.MetadataComplete = false
}
}
if err := rows.Err(); err != nil {
@@ -2967,6 +3073,80 @@ ORDER BY ac.CONSTRAINT_NAME, acc.POSITION`, []any{schema, table})
return emptyIfNil(result), nil
}
+func nullableStringPointer(value sql.NullString) *string {
+ if !value.Valid {
+ return nil
+ }
+ result := value.String
+ return &result
+}
+
+func (s *server) oracleUniqueIndexMetadata(tableOwner, tableName string, indexOwner, indexName sql.NullString) (*oracleConstraintIndexMetadata, *string) {
+ if !indexOwner.Valid || !indexName.Valid || indexOwner.String == "" || indexName.String == "" {
+ return nil, nil
+ }
+ rows, err := s.queryRows(`
+SELECT i.OWNER, i.TABLE_OWNER, i.TABLE_NAME, i.INDEX_TYPE, i.UNIQUENESS,
+ i.STATUS, i.PARTITIONED, i.VISIBILITY, i.SECONDARY,
+ ic.COLUMN_NAME, ic.DESCEND, ie.COLUMN_EXPRESSION, ic.COLUMN_POSITION
+FROM ALL_INDEXES i
+JOIN ALL_IND_COLUMNS ic ON ic.INDEX_OWNER = i.OWNER AND ic.INDEX_NAME = i.INDEX_NAME
+LEFT JOIN ALL_IND_EXPRESSIONS ie ON ie.INDEX_OWNER = ic.INDEX_OWNER AND ie.INDEX_NAME = ic.INDEX_NAME
+ AND ie.TABLE_OWNER = ic.TABLE_OWNER AND ie.TABLE_NAME = ic.TABLE_NAME AND ie.COLUMN_POSITION = ic.COLUMN_POSITION
+WHERE i.OWNER = :1 AND i.INDEX_NAME = :2 AND i.TABLE_OWNER = :3 AND i.TABLE_NAME = :4
+ORDER BY ic.COLUMN_POSITION`, []any{indexOwner.String, indexName.String, tableOwner, tableName})
+ if err != nil {
+ return &oracleConstraintIndexMetadata{}, nil
+ }
+ defer s.closeRows(rows)
+ metadata := &oracleConstraintIndexMetadata{
+ Owner: indexOwner.String, TableOwner: tableOwner, TableName: tableName,
+ Columns: []string{}, Directions: []string{}, KeyIsExpression: []bool{}, IncludedColumns: []string{},
+ }
+ var sharing *string
+ for rows.Next() {
+ var owner, actualTableOwner, actualTable, indexType, uniqueness, status, partitioned, visibility sql.NullString
+ var secondary, column, descend, expression sql.NullString
+ var position sql.NullInt64
+ if err := rows.Scan(&owner, &actualTableOwner, &actualTable, &indexType, &uniqueness, &status, &partitioned, &visibility, &secondary, &column, &descend, &expression, &position); err != nil {
+ return metadata, nil
+ }
+ if !owner.Valid || !actualTableOwner.Valid || !actualTable.Valid || !indexType.Valid || !uniqueness.Valid || !status.Valid || !partitioned.Valid || (partitioned.String != "YES" && partitioned.String != "NO") || !visibility.Valid || !position.Valid || position.Int64 != int64(len(metadata.Columns)+1) || !descend.Valid || (descend.String != "ASC" && descend.String != "DESC") || (!column.Valid && !expression.Valid) {
+ return metadata, nil
+ }
+ metadata.Owner, metadata.TableOwner, metadata.TableName = owner.String, actualTableOwner.String, actualTable.String
+ metadata.IndexType, metadata.Uniqueness, metadata.Status = indexType.String, uniqueness.String, status.String
+ metadata.Visibility, metadata.Secondary = visibility.String, nullableStringPointer(secondary)
+ metadata.Partitioned = partitioned.String == "YES"
+ metadata.Columns = append(metadata.Columns, column.String)
+ metadata.Directions = append(metadata.Directions, descend.String)
+ metadata.KeyIsExpression = append(metadata.KeyIsExpression, expression.Valid && strings.TrimSpace(expression.String) != "")
+ }
+ if err := rows.Err(); err != nil || len(metadata.Columns) == 0 || len(metadata.Directions) != len(metadata.Columns) {
+ return metadata, nil
+ }
+ metadata.MetadataComplete = true
+ sharingRows, err := s.queryRows(`
+SELECT COUNT(*) FROM ALL_CONSTRAINTS
+WHERE OWNER = :1 AND TABLE_NAME = :2 AND INDEX_OWNER = :3 AND INDEX_NAME = :4
+ AND CONSTRAINT_TYPE IN ('P', 'U')`, []any{tableOwner, tableName, indexOwner.String, indexName.String})
+ if err != nil {
+ return metadata, nil
+ }
+ defer s.closeRows(sharingRows)
+ if sharingRows.Next() {
+ var count int64
+ if err := sharingRows.Scan(&count); err == nil && count == 1 {
+ value := "exclusive"
+ sharing = &value
+ } else if err == nil && count > 1 {
+ value := "shared"
+ sharing = &value
+ }
+ }
+ return metadata, sharing
+}
+
func (s *server) listTriggers(schema, table string) ([]triggerInfo, error) {
schema, err := s.normalizeSchema(schema)
if err != nil {
@@ -3678,6 +3858,12 @@ func oracleColumnTypeDDL(column columnInfo) string {
if strings.Contains(dataType, "(") {
return dataType
}
+ if dataType == "RAW" {
+ if column.DataLength != nil && *column.DataLength > 0 {
+ return fmt.Sprintf("RAW(%d)", *column.DataLength)
+ }
+ return dataType
+ }
if isOracleCharacterType(dataType) && column.CharacterMaximumLength != nil && *column.CharacterMaximumLength > 0 {
if unit := oracleCharacterLengthUnit(dataType, column.CharacterLengthUnit); unit != "" {
return fmt.Sprintf("%s(%d %s)", dataType, *column.CharacterMaximumLength, unit)
diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.go
index 354cb17be8..0b20a9824b 100644
--- a/agents/drivers/oracle-go/main_test.go
+++ b/agents/drivers/oracle-go/main_test.go
@@ -547,9 +547,9 @@ func TestGetTableDDLFallbackPreservesQuotedColumnNames(t *testing.T) {
args: []driver.Value{schema, table},
columns: []string{
"COLUMN_NAME", "DATA_TYPE", "NULLABLE", "DATA_DEFAULT", "IS_PRIMARY_KEY",
- "COMMENTS", "DATA_PRECISION", "DATA_SCALE", "CHAR_LENGTH", "CHAR_USED",
+ "COMMENTS", "DATA_PRECISION", "DATA_SCALE", "DATA_LENGTH", "CHAR_LENGTH", "CHAR_USED",
},
- rows: [][]driver.Value{{"FlowId", "VARCHAR2", "N", nil, int64(1), nil, nil, nil, int64(50), "C"}},
+ rows: [][]driver.Value{{"FlowId", "VARCHAR2", "N", nil, int64(1), nil, nil, nil, nil, int64(50), "C"}},
},
})
s := newServer()
@@ -876,14 +876,14 @@ func TestListIndexesSeparatesQuotedCloneTableNamesByCase(t *testing.T) {
{
queryContains: "FROM ALL_INDEXES",
args: []driver.Value{schema, "ORDERS_COPY"},
- columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "COLUMN_POSITION"},
- rows: [][]driver.Value{{"ORDERS_COPY_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", int64(1)}},
+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},
+ rows: [][]driver.Value{{"ORDERS_COPY_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1)}},
},
{
queryContains: "FROM ALL_INDEXES",
args: []driver.Value{schema, "ORDERS_copy"},
- columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "COLUMN_POSITION"},
- rows: [][]driver.Value{{"ORDERS_copy_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", int64(1)}},
+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},
+ rows: [][]driver.Value{{"ORDERS_copy_IDX1", "STATUS", "NONUNIQUE", int64(0), "NORMAL", "NO", "VISIBLE", "ASC", nil, int64(1)}},
},
})
s := newServer()
@@ -908,6 +908,84 @@ func TestListIndexesSeparatesQuotedCloneTableNamesByCase(t *testing.T) {
}
}
+func TestListIndexesExposesExpressionDirectionAndVisibilityMetadata(t *testing.T) {
+ const schema = "APP"
+ const table = "EVENTS"
+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{
+ queryContains: "FROM ALL_INDEXES",
+ args: []driver.Value{schema, table},
+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},
+ rows: [][]driver.Value{
+ {"IX_EVENT_EXPR", "SYS_NC00001$", "NONUNIQUE", int64(0), "FUNCTION-BASED NORMAL", "NO", "INVISIBLE", "DESC", `LOWER("EVENT_NAME")`, int64(1)},
+ {"IX_EVENT_EXPR", "EVENT_TS", "NONUNIQUE", int64(0), "FUNCTION-BASED NORMAL", "NO", "INVISIBLE", "ASC", nil, int64(2)},
+ },
+ }})
+ s := newServer()
+ s.db = db
+
+ resp, shutdown := s.handleLine(`{"jsonrpc":"2.0","id":1,"method":"list_indexes","params":{"schema":"APP","table":"EVENTS"}}`)
+ if shutdown {
+ t.Fatal("list_indexes unexpectedly shut down the agent")
+ }
+ if resp.Error != nil {
+ t.Fatalf("list_indexes RPC failed: %s", resp.Error.Message)
+ }
+ indexes, ok := resp.Result.([]indexInfo)
+ if !ok || len(indexes) != 1 {
+ t.Fatalf("list_indexes RPC result = %#v, want one index", resp.Result)
+ }
+ payload, err := json.Marshal(indexes[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got map[string]any
+ if err := json.Unmarshal(payload, &got); err != nil {
+ t.Fatal(err)
+ }
+ for key, want := range map[string]any{
+ "columns": []any{`LOWER("EVENT_NAME")`, "EVENT_TS"},
+ "key_is_expression": []any{true, false},
+ "key_directions": []any{"DESC", "ASC"},
+ "visibility": "INVISIBLE",
+ "key_metadata_complete": true,
+ } {
+ if !reflect.DeepEqual(got[key], want) {
+ t.Errorf("listIndexes JSON field %q = %#v, want %#v (payload %s)", key, got[key], want, payload)
+ }
+ }
+}
+
+func TestListIndexesMarksUnsupportedShapesIncompleteThroughRPC(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ indexType string
+ partitioned string
+ }{
+ {name: "partitioned", indexType: "NORMAL", partitioned: "YES"},
+ {name: "bitmap", indexType: "FUNCTION-BASED BITMAP", partitioned: "NO"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{
+ queryContains: "FROM ALL_INDEXES",
+ args: []driver.Value{"APP", "EVENTS"},
+ columns: []string{"INDEX_NAME", "COLUMN_NAME", "UNIQUENESS", "IS_PRIMARY", "INDEX_TYPE", "PARTITIONED", "VISIBILITY", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},
+ rows: [][]driver.Value{{"IX_EVENT", "EVENT_TS", "NONUNIQUE", int64(0), test.indexType, test.partitioned, "VISIBLE", "ASC", nil, int64(1)}},
+ }})
+ s := newServer()
+ s.db = db
+
+ resp, shutdown := s.handleLine(`{"jsonrpc":"2.0","id":1,"method":"list_indexes","params":{"schema":"APP","table":"EVENTS"}}`)
+ if shutdown || resp.Error != nil {
+ t.Fatalf("list_indexes RPC failed: shutdown=%v error=%v", shutdown, resp.Error)
+ }
+ indexes, ok := resp.Result.([]indexInfo)
+ if !ok || len(indexes) != 1 || indexes[0].KeyMetadataComplete {
+ t.Fatalf("list_indexes returned unsupported shape as complete: %#v", resp.Result)
+ }
+ })
+ }
+}
+
func TestGetTableCommentPreservesQuotedObjectName(t *testing.T) {
const schema = "HR"
const table = "OrderDetails"
@@ -1005,12 +1083,12 @@ func TestListConstraintsGroupsMultiColumnPrimaryKeyAndMapsTypes(t *testing.T) {
{
queryContains: "FROM ALL_CONSTRAINTS ac",
args: []driver.Value{schema, table},
- columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "COLUMN_NAME", "POSITION", "NULLABLE"},
+ columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "RELY", "INDEX_OWNER", "INDEX_NAME", "COLUMN_NAME", "POSITION", "NULLABLE"},
rows: [][]driver.Value{
- {"PK_ORDERS", "P", nil, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", "TENANT_ID", int64(1), "N"},
- {"PK_ORDERS", "P", nil, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", "ORDER_ID", int64(2), "N"},
- {"UQ_ORDERS_CODE", "U", nil, "USER NAME", "ENABLED", "DEFERRABLE", "DEFERRED", "VALIDATED", "ORDER_CODE", int64(1), "Y"},
- {"CK_ORDERS_AMOUNT", "C", "AMOUNT > 0", "USER NAME", "DISABLED", "NOT DEFERRABLE", "IMMEDIATE", "NOT VALIDATED", nil, nil, nil},
+ {"PK_ORDERS", "P", nil, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, "TENANT_ID", int64(1), "N"},
+ {"PK_ORDERS", "P", nil, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, "ORDER_ID", int64(2), "N"},
+ {"UQ_ORDERS_CODE", "U", nil, "USER NAME", "ENABLED", "DEFERRABLE", "DEFERRED", "VALIDATED", nil, nil, nil, "ORDER_CODE", int64(1), "Y"},
+ {"CK_ORDERS_AMOUNT", "C", "AMOUNT > 0", "USER NAME", "DISABLED", "NOT DEFERRABLE", "IMMEDIATE", "NOT VALIDATED", nil, nil, nil, nil, nil, nil},
},
},
})
@@ -1021,6 +1099,9 @@ func TestListConstraintsGroupsMultiColumnPrimaryKeyAndMapsTypes(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ for i := range got {
+ got[i].OracleMetadata = nil // These assertions preserve the legacy display contract.
+ }
want := []constraintInfo{
{Name: "PK_ORDERS", ConstraintType: "PRIMARY KEY", Definition: "", Columns: []string{"TENANT_ID", "ORDER_ID"}, RefColumns: []string{}, Enabled: true, Valid: true},
{Name: "UQ_ORDERS_CODE", ConstraintType: "UNIQUE", Definition: "", Columns: []string{"ORDER_CODE"}, RefColumns: []string{}, Deferrable: true, InitiallyDeferred: true, Enabled: true, Valid: true},
@@ -1034,6 +1115,106 @@ func TestListConstraintsGroupsMultiColumnPrimaryKeyAndMapsTypes(t *testing.T) {
}
}
+func TestListConstraintsReturnsExactUniqueIndexMetadata(t *testing.T) {
+ const schema = "HR"
+ const table = "USERS"
+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{
+ {
+ queryContains: "FROM ALL_CONSTRAINTS ac",
+ args: []driver.Value{schema, table},
+ columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "RELY", "INDEX_OWNER", "INDEX_NAME", "COLUMN_NAME", "POSITION", "NULLABLE"},
+ rows: [][]driver.Value{{"UQ_USERS_EMAIL", "U", nil, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, schema, "UQ_USERS_EMAIL", "EMAIL", int64(1), "Y"}},
+ },
+ {
+ queryContains: "FROM ALL_INDEXES i",
+ args: []driver.Value{schema, "UQ_USERS_EMAIL", schema, table},
+ columns: []string{"OWNER", "TABLE_OWNER", "TABLE_NAME", "INDEX_TYPE", "UNIQUENESS", "STATUS", "PARTITIONED", "VISIBILITY", "SECONDARY", "COLUMN_NAME", "DESCEND", "COLUMN_EXPRESSION", "COLUMN_POSITION"},
+ rows: [][]driver.Value{{schema, schema, table, "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", nil, "EMAIL", "ASC", nil, int64(1)}},
+ },
+ {
+ queryContains: "SELECT COUNT(*) FROM ALL_CONSTRAINTS",
+ args: []driver.Value{schema, table, schema, "UQ_USERS_EMAIL"},
+ columns: []string{"COUNT(*)"},
+ rows: [][]driver.Value{{int64(1)}},
+ },
+ })
+ s := newServer()
+ s.db = db
+
+ got, err := s.listConstraints(schema, table)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 1 || got[0].OracleMetadata == nil {
+ t.Fatalf("listConstraints() = %#v, want one item with Oracle metadata", got)
+ }
+ metadata := got[0].OracleMetadata
+ if !metadata.MetadataComplete || metadata.Rely != nil || metadata.IndexSharing == nil || *metadata.IndexSharing != "exclusive" {
+ t.Fatalf("constraint metadata = %#v, want complete metadata with NULL RELY and exclusive index", metadata)
+ }
+ if metadata.Index == nil || !metadata.Index.MetadataComplete || metadata.Index.Secondary != nil ||
+ !reflect.DeepEqual(metadata.Index.Columns, []string{"EMAIL"}) ||
+ !reflect.DeepEqual(metadata.Index.Directions, []string{"ASC"}) ||
+ !reflect.DeepEqual(metadata.Index.KeyIsExpression, []bool{false}) {
+ t.Fatalf("index metadata = %#v, want exact ordinary index shape", metadata.Index)
+ }
+ if scripted.next != len(scripted.steps) {
+ t.Fatalf("expected %d queries, got %d", len(scripted.steps), scripted.next)
+ }
+}
+
+func TestListConstraintsDisabledUniqueWithoutIndexMaintainsCompleteMetadata(t *testing.T) {
+ const schema = "HR"
+ const table = "USERS"
+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{
+ {
+ queryContains: "FROM ALL_CONSTRAINTS ac",
+ args: []driver.Value{schema, table},
+ columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "RELY", "INDEX_OWNER", "INDEX_NAME", "COLUMN_NAME", "POSITION", "NULLABLE"},
+ rows: [][]driver.Value{
+ {"UQ_DISABLED_NO_IDX", "U", nil, "USER NAME", "DISABLED", "NOT DEFERRABLE", "IMMEDIATE", "NOT VALIDATED", nil, nil, nil, "EMAIL", int64(1), "Y"},
+ {"UQ_ENABLED_NO_IDX", "U", nil, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, "PHONE", int64(1), "Y"},
+ {"UQ_DISABLED_ONE_NULL", "U", nil, "USER NAME", "DISABLED", "NOT DEFERRABLE", "IMMEDIATE", "NOT VALIDATED", nil, schema, nil, "ADDRESS", int64(1), "Y"},
+ {"UQ_DISABLED_EMPTY_NAME", "U", nil, "USER NAME", "DISABLED", "NOT DEFERRABLE", "IMMEDIATE", "NOT VALIDATED", nil, schema, "", "CITY", int64(1), "Y"},
+ {"UQ_UNKNOWN_STATUS", "U", nil, "USER NAME", "UNKNOWN", "NOT DEFERRABLE", "IMMEDIATE", "NOT VALIDATED", nil, nil, nil, "ZIP", int64(1), "Y"},
+ },
+ },
+ })
+ s := newServer()
+ s.db = db
+
+ got, err := s.listConstraints(schema, table)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 5 {
+ t.Fatalf("listConstraints() returned %d items, want 5", len(got))
+ }
+ // Case 1: DISABLED + double SQL NULL -> MetadataComplete == true
+ if meta := got[0].OracleMetadata; meta == nil || !meta.MetadataComplete || meta.Index != nil || meta.IndexSharing != nil {
+ t.Fatalf("UQ_DISABLED_NO_IDX metadata = %#v, want MetadataComplete == true and nil Index/IndexSharing", meta)
+ }
+ // Case 2: ENABLED + double SQL NULL -> MetadataComplete == false (ENABLED UNIQUE must have index)
+ if meta := got[1].OracleMetadata; meta == nil || meta.MetadataComplete {
+ t.Fatalf("UQ_ENABLED_NO_IDX metadata = %#v, want MetadataComplete == false for ENABLED without index", meta)
+ }
+ // Case 3: DISABLED + single null (IndexName is nil, IndexOwner is not) -> MetadataComplete == false
+ if meta := got[2].OracleMetadata; meta == nil || meta.MetadataComplete {
+ t.Fatalf("UQ_DISABLED_ONE_NULL metadata = %#v, want MetadataComplete == false for single null index", meta)
+ }
+ // Case 4: DISABLED + empty string -> MetadataComplete == false
+ if meta := got[3].OracleMetadata; meta == nil || meta.MetadataComplete {
+ t.Fatalf("UQ_DISABLED_EMPTY_NAME metadata = %#v, want MetadataComplete == false for empty string index name", meta)
+ }
+ // Case 5: UNKNOWN status -> MetadataComplete == false
+ if meta := got[4].OracleMetadata; meta == nil || meta.MetadataComplete {
+ t.Fatalf("UQ_UNKNOWN_STATUS metadata = %#v, want MetadataComplete == false for unknown status", meta)
+ }
+ if scripted.next != len(scripted.steps) {
+ t.Fatalf("expected %d queries, got %d", len(scripted.steps), scripted.next)
+ }
+}
+
func TestListConstraintsExcludesGeneratedNotNullChecksButKeepsRealChecks(t *testing.T) {
const schema = "HR"
const table = "ORDERS"
@@ -1041,12 +1222,12 @@ func TestListConstraintsExcludesGeneratedNotNullChecksButKeepsRealChecks(t *test
{
queryContains: "FROM ALL_CONSTRAINTS ac",
args: []driver.Value{schema, table},
- columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "COLUMN_NAME", "POSITION", "NULLABLE"},
+ columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "RELY", "INDEX_OWNER", "INDEX_NAME", "COLUMN_NAME", "POSITION", "NULLABLE"},
rows: [][]driver.Value{
- {"SYS_C008648", "C", `"ORDER_CODE" IS NOT NULL`, "GENERATED NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", "ORDER_CODE", int64(1), "N"},
- {"SYS_C008649", "C", `"OPTIONAL_CODE" IS NOT NULL`, "GENERATED NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", "OPTIONAL_CODE", int64(1), "Y"},
- {"CK_REQUIRED_CODE", "C", `"REQUIRED_CODE" IS NOT NULL`, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", "REQUIRED_CODE", int64(1), "N"},
- {"CK_ORDERS_AMOUNT", "C", "AMOUNT > 0", "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil},
+ {"SYS_C008648", "C", `"ORDER_CODE" IS NOT NULL`, "GENERATED NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, "ORDER_CODE", int64(1), "N"},
+ {"SYS_C008649", "C", `"OPTIONAL_CODE" IS NOT NULL`, "GENERATED NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, "OPTIONAL_CODE", int64(1), "Y"},
+ {"CK_REQUIRED_CODE", "C", `"REQUIRED_CODE" IS NOT NULL`, "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, "REQUIRED_CODE", int64(1), "N"},
+ {"CK_ORDERS_AMOUNT", "C", "AMOUNT > 0", "USER NAME", "ENABLED", "NOT DEFERRABLE", "IMMEDIATE", "VALIDATED", nil, nil, nil, nil, nil, nil},
},
},
})
@@ -1057,6 +1238,9 @@ func TestListConstraintsExcludesGeneratedNotNullChecksButKeepsRealChecks(t *test
if err != nil {
t.Fatal(err)
}
+ for i := range got {
+ got[i].OracleMetadata = nil // These assertions preserve the legacy display contract.
+ }
want := []constraintInfo{
{Name: "SYS_C008649", ConstraintType: "CHECK", Definition: `"OPTIONAL_CODE" IS NOT NULL`, Columns: []string{"OPTIONAL_CODE"}, RefColumns: []string{}, Enabled: true, Valid: true},
{Name: "CK_REQUIRED_CODE", ConstraintType: "CHECK", Definition: `"REQUIRED_CODE" IS NOT NULL`, Columns: []string{"REQUIRED_CODE"}, RefColumns: []string{}, Enabled: true, Valid: true},
@@ -1077,7 +1261,7 @@ func TestListConstraintsPreservesQuotedMixedCaseSchema(t *testing.T) {
{
queryContains: "FROM ALL_CONSTRAINTS ac",
args: []driver.Value{schema, table},
- columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "COLUMN_NAME", "POSITION", "NULLABLE"},
+ columns: []string{"CONSTRAINT_NAME", "CONSTRAINT_TYPE", "SEARCH_CONDITION", "GENERATED", "STATUS", "DEFERRABLE", "DEFERRED", "VALIDATED", "RELY", "INDEX_OWNER", "INDEX_NAME", "COLUMN_NAME", "POSITION", "NULLABLE"},
rows: [][]driver.Value{},
},
})
@@ -1311,6 +1495,8 @@ func protocolContract(t *testing.T) struct {
func TestOracleColumnTypeDDL(t *testing.T) {
charLen := 64
+ rawLen := 16
+ zeroLength := 0
precision := 10
scale := 2
zeroScale := 0
@@ -1326,6 +1512,10 @@ func TestOracleColumnTypeDDL(t *testing.T) {
{name: "varchar", column: columnInfo{DataType: "VARCHAR2", CharacterMaximumLength: &charLen}, want: "VARCHAR2(64)"},
{name: "varchar byte semantics", column: columnInfo{DataType: "VARCHAR2", CharacterMaximumLength: &charLen, CharacterLengthUnit: &byteUnit}, want: "VARCHAR2(64 BYTE)"},
{name: "varchar char semantics", column: columnInfo{DataType: "VARCHAR2", CharacterMaximumLength: &charLen, CharacterLengthUnit: &charUnit}, want: "VARCHAR2(64 CHAR)"},
+ {name: "raw length", column: columnInfo{DataType: "RAW", DataLength: &rawLen}, want: "RAW(16)"},
+ {name: "raw unknown length", column: columnInfo{DataType: "RAW"}, want: "RAW"},
+ {name: "raw non-positive length", column: columnInfo{DataType: "RAW", DataLength: &zeroLength}, want: "RAW"},
+ {name: "raw explicit parameters", column: columnInfo{DataType: "RAW(8)", DataLength: &rawLen}, want: "RAW(8)"},
{name: "national character type ignores unit", column: columnInfo{DataType: "NVARCHAR2", CharacterMaximumLength: &charLen, CharacterLengthUnit: &charUnit}, want: "NVARCHAR2(64)"},
{name: "number scale", column: columnInfo{DataType: "NUMBER", NumericPrecision: &precision, NumericScale: &scale}, want: "NUMBER(10,2)"},
{name: "number zero scale", column: columnInfo{DataType: "NUMBER", NumericPrecision: &precision, NumericScale: &zeroScale}, want: "NUMBER(10)"},
@@ -1351,6 +1541,38 @@ func TestOracleColumnTypeDDL(t *testing.T) {
}
}
+func TestGetColumnsRPCFormatsRawLengthFromDataLength(t *testing.T) {
+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{
+ queryContains: "c.DATA_LENGTH",
+ args: []driver.Value{"APP", "BINARY_DATA"},
+ columns: []string{"COLUMN_NAME", "DATA_TYPE", "NULLABLE", "DATA_DEFAULT", "IS_PRIMARY_KEY", "COMMENTS", "DATA_PRECISION", "DATA_SCALE", "DATA_LENGTH", "CHAR_LENGTH", "CHAR_USED"},
+ rows: [][]driver.Value{{"PAYLOAD", "RAW", "Y", nil, int64(0), nil, nil, nil, int64(16), int64(0), nil}},
+ }})
+ s := newServer()
+ s.db = db
+
+ resp, shutdown := s.handleLine(`{"jsonrpc":"2.0","id":1,"method":"get_columns","params":{"schema":"APP","table":"BINARY_DATA"}}`)
+ if shutdown {
+ t.Fatal("get_columns unexpectedly shut down the agent")
+ }
+ if resp.Error != nil {
+ t.Fatalf("get_columns RPC failed: %s", resp.Error.Message)
+ }
+ columns, ok := resp.Result.([]columnInfo)
+ if !ok || len(columns) != 1 {
+ t.Fatalf("get_columns RPC result = %#v, want one column", resp.Result)
+ }
+ if columns[0].DataType != "RAW(16)" {
+ t.Fatalf("get_columns data_type = %q, want RAW(16)", columns[0].DataType)
+ }
+ if columns[0].CharacterMaximumLength != nil && *columns[0].CharacterMaximumLength != 0 {
+ t.Fatalf("RAW character maximum length = %v, want null or zero", *columns[0].CharacterMaximumLength)
+ }
+ if scripted.next != len(scripted.steps) {
+ t.Fatalf("expected %d queries, got %d", len(scripted.steps), scripted.next)
+ }
+}
+
func TestBuildDSNUsesConnectionStringWhenProvided(t *testing.T) {
dsn := buildDSN(connectParams{ConnectionString: "oracle://scott:[email protected]:1521/ORCLPDB1"})
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.infiniteScroll.spec.ts b/apps/desktop/src/components/redis/RedisKeyBrowser.infiniteScroll.spec.ts
index 96b7740d22..9eefe94006 100644
--- a/apps/desktop/src/components/redis/RedisKeyBrowser.infiniteScroll.spec.ts
+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.infiniteScroll.spec.ts
@@ -485,9 +485,7 @@ describe("RedisKeyBrowser infinite scroll auto-continue (issue #6022)", () => {
mocks.redisScanKeysBatch.mockResolvedValueOnce({ cursor: 0, keys, total_keys: keys.length });
const host = mountBrowser();
await settleThoroughly();
- await new Promise((resolve) => setTimeout(resolve, 20));
- await settleThoroughly();
- expect(host.querySelector('[role="button"]')).not.toBeNull();
+ await vi.waitFor(() => expect(host.querySelector('[role="button"]')).not.toBeNull());
const frames: FrameRequestCallback[] = [];
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
frames.push(callback);
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
index 7a910169e6..307681e5b1 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
+++ b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
@@ -206,6 +206,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 1,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.ts
index 13d4cde15b..9b0fe70582 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.ts
+++ b/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.ts
@@ -7,6 +7,7 @@ import TableStructureEditor from "./TableStructureEditor.vue";
import { useConnectionStore } from "@/stores/connectionStore";
import type { ConnectionConfig } from "@/types/database";
import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+import type { ObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";
import { TooltipProvider } from "@/components/ui/tooltip";
import LightTooltip from "@/components/ui/LightTooltip.vue";
@@ -18,15 +19,32 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/backend/api")>()),
...backend,
checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ getColumns: vi.fn().mockResolvedValue([]),
listIndexes: vi.fn().mockResolvedValue([]),
listConstraints: vi.fn().mockResolvedValue([]),
listForeignKeys: vi.fn().mockResolvedValue([]),
listTriggers: vi.fn().mockResolvedValue([]),
+ getTableComment: vi.fn().mockResolvedValue(""),
+ getTablePartitioning: vi.fn().mockResolvedValue(null),
getTableOwner: vi.fn().mockResolvedValue("APP"),
getTablePartitionStatus: vi.fn().mockResolvedValue(null),
listPlugins: vi.fn().mockResolvedValue([]),
loadSchemaCache: vi.fn().mockResolvedValue(null),
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ loadObjectDdl: vi.fn().mockResolvedValue(""),
+ invalidateObjectDdl: vi.fn().mockResolvedValue(undefined),
+ invalidateObjectMetadataCache: vi.fn().mockResolvedValue(undefined),
+ invalidateTableMetadataCache: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("@/lib/metadata/objectMetadataCache", () => ({
+ invalidateObjectMetadataCache: vi.fn().mockResolvedValue(undefined),
+ invalidateTableMetadataCache: vi.fn().mockResolvedValue(undefined),
+ loadObjectMetadataFacet: vi.fn().mockImplementation(async (_req, facet) => ({
+ value: facet === "columns" ? [{ name: "C", data_type: "NCLOB", is_nullable: true, column_default: null, comment: "original comment", is_primary_key: false, extra: null }] : facet === "comment" ? "original comment" : [],
+ cacheStatus: "remote",
+ })),
}));
let app: App | undefined;
@@ -50,10 +68,10 @@ it("filters rejected JDBC recommendations without replacing an existing nonrecom
dataType: "NCLOB",
isNullable: true,
defaultValue: "",
- comment: "original comment",
+ comment: "original column comment",
isPrimaryKey: false,
extra: {},
- original: { name: "C", data_type: "NCLOB", is_nullable: true, column_default: null, comment: "original comment", is_primary_key: false, extra: null },
+ original: { name: "C", data_type: "NCLOB", is_nullable: true, column_default: null, comment: "original column comment", is_primary_key: false, extra: null },
originalPosition: 0,
markedForDrop: false,
};
@@ -64,9 +82,20 @@ it("filters rejected JDBC recommendations without replacing an existing nonrecom
database: "APP",
schema: "APP",
tableName: "T",
- draft: { initialized: true, activeTab: "columns" as const, newTableName: "", tableComment: "", originalTableComment: "", columns: [column], indexes: [], foreignKeys: [], triggers: [] },
+ draft: {
+ initialized: true,
+ activeTab: "columns" as const,
+ newTableName: "",
+ tableComment: "original table comment",
+ originalTableComment: "original table comment",
+ columns: [column],
+ indexes: [],
+ foreignKeys: [],
+ triggers: [],
+ loadedMetadataFacets: ["columns", "indexes", "foreign-keys", "constraints", "triggers", "partitions", "comment"] as ObjectMetadataFacet[],
+ },
};
- app = createApp({ render: () => h(TooltipProvider, {}, { default: () => h(TableStructureEditor, editorProps) }) });
+ app = createApp({ render: () => h(TooltipProvider, {}, { default: () => h(TableStructureEditor, editorProps as any) }) });
app.component("LightTooltip", LightTooltip);
app.use(pinia);
app.use(i18n);
@@ -82,9 +111,9 @@ it("filters rejected JDBC recommendations without replacing an existing nonrecom
expect(choices).toContain("NUMBER");
for (const rejected of ["NCLOB", "Long", "LONG RAW", "BFILE", "boolean", "VECTOR(3, FLOAT32)"]) expect(choices).not.toContain(rejected);
picker!.click();
- const comment = Array.from(root.querySelectorAll("input")).find((input) => input.value === "original comment");
+ const comment = Array.from(root.querySelectorAll<HTMLInputElement>("tbody input")).find((input) => input.value === "original column comment");
expect(comment).toBeDefined();
comment!.value = "changed comment";
comment!.dispatchEvent(new Event("input", { bubbles: true }));
- await vi.waitFor(() => expect(backend.buildTableStructureChangeSql).toHaveBeenLastCalledWith(expect.objectContaining({ columns: [expect.objectContaining({ dataType: "NCLOB", comment: "changed comment", original: expect.objectContaining({ data_type: "NCLOB" }) })] })));
+ await vi.waitFor(() => expect(backend.buildTableStructureChangeSql).toHaveBeenLastCalledWith(expect.objectContaining({ columns: [expect.objectContaining({ dataType: "NCLOB", comment: "changed comment", original: expect.objectContaining({ data_type: "NCLOB" }) })] })), { timeout: 3000 });
});
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts
index 34c9664c43..6b1e571960 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts
+++ b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -214,6 +214,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index 0daa2cbd34..b2d8631312 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -7,6 +7,12 @@ import { getColumnDefaultValuePresets } from "@/lib/table/columnDefaultPresets";
import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
import StructureIndexColumnPicker from "./StructureIndexColumnPicker.vue";
+import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
+import { executeOceanbasePrimaryKeyPlan, readOceanbasePrimaryKeySnapshot, prepareOraclePrimaryKeyChange, OceanbasePrimaryKeyValidationError, type ExistingPrimaryKeyChange, type OceanbasePrimaryKeyPlan, type PrimaryKeyTarget } from "@/lib/database/oceanbasePrimaryKey";
+import { executeOracleForeignKeyCreatePlan, executeOracleForeignKeyPlan, prepareOracleForeignKeyCreatePlan, prepareOracleForeignKeyPlan, readOracleForeignKeyDefinitions, type OracleForeignKeyCreatePlan, type OracleForeignKeyPlan } from "@/lib/database/oracleForeignKeys";
+import { executeOracleConstraintPlan, oracleConstraintDefinitionFromInfo, prepareOracleConstraintPlan, type OracleConstraintPlan, type OracleConstraintTarget } from "@/lib/database/oracleConstraints";
+import { executeOracleIndexPlan, mergeOracleIndexDraftsAfterRefresh, oracleIndexSnapshotMatchesLoaded, oracleIndexSnapshotMatchesLoadedColumns, prepareOracleIndexPlan, type OracleIndexDefinition, type OracleIndexLoadBaseline, type OracleIndexPlan } from "@/lib/database/oracleIndexes";
+import { readOracleIndexSnapshot } from "@/lib/database/oracleConstraints";
import { computed, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, shallowRef, watch } from "vue";
import { uuid } from "@/lib/common/utils";
@@ -60,6 +66,7 @@ import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomC
import EditorSearchPanel from "@/components/editor/EditorSearchPanel.vue";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useConnectionStore } from "@/stores/connectionStore";
+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import { productionContextForDatabase } from "@/lib/database/productionSafety";
import { useQueryStore } from "@/stores/queryStore";
@@ -97,6 +104,8 @@ import {
type EditableStructureForeignKey,
type EditableStructureIndex,
type EditableStructureTrigger,
+ type OracleConstraintChange,
+ type OracleConstraintDefinition,
type TablePartitionBoundDraft,
type TablePartitionOperation,
type TablePartitionOperationKind,
@@ -652,6 +661,9 @@ const pendingStatements = ref<string[]>([]);
const warnings = ref<string[]>([]);
const sqliteSchemaRevision = ref<string>();
const foreignKeys = ref<EditableStructureForeignKey[]>([]);
+const foreignKeyDefinitionBusy = ref(false);
+const foreignKeyReferenceColumns = ref<Record<string, ColumnInfo[]>>({});
+const foreignKeyReferenceListPrefix = `oracle-fk-columns-${uuid()}`;
const constraints = ref<ConstraintInfo[]>([]);
const constraintsLoaded = ref(false);
// Structured PostgreSQL partitioning view (partitioned parent, its descendant
@@ -981,7 +993,7 @@ function columnChanged(column: EditableStructureColumn, index: number): boolean
}
function indexChanged(index: EditableStructureIndex): boolean {
- if (!index.original || index.markedForDrop) return true;
+ if (!index.original || index.oracleOriginalMissing || index.markedForDrop) return true;
const original = index.original;
return (
index.name !== original.name ||
@@ -997,6 +1009,18 @@ function indexChanged(index: EditableStructureIndex): boolean {
function foreignKeyChanged(foreignKey: EditableStructureForeignKey): boolean {
if (!foreignKey.original || foreignKey.markedForDrop) return true;
+ if (foreignKey.oracleOriginal) {
+ const original = foreignKey.oracleOriginal;
+ return (
+ foreignKey.name !== original.name ||
+ JSON.stringify(foreignKey.columns) !== JSON.stringify(original.columns) ||
+ foreignKey.refSchema !== original.refSchema ||
+ foreignKey.refTable !== original.refTable ||
+ JSON.stringify(foreignKey.refColumns) !== JSON.stringify(original.refColumns) ||
+ (foreignKey.onDelete || "NO ACTION") !== original.onDelete ||
+ JSON.stringify(foreignKey.oracleState) !== JSON.stringify(original.state)
+ );
+ }
const original = foreignKey.original;
return (
foreignKey.name !== original.name ||
@@ -1009,6 +1033,24 @@ function foreignKeyChanged(foreignKey: EditableStructureForeignKey): boolean {
);
}
+function oracleForeignKeyChanges() {
+ return foreignKeys.value.filter(foreignKeyChanged).map((foreignKey) => {
+ const original = foreignKey.oracleOriginal ?? null;
+ const target = foreignKey.markedForDrop
+ ? null
+ : {
+ name: foreignKey.name,
+ columns: [...(foreignKey.columns ?? [])],
+ refSchema: foreignKey.refSchema,
+ refTable: foreignKey.refTable,
+ refColumns: [...(foreignKey.refColumns ?? [])],
+ onDelete: (foreignKey.onDelete || "NO ACTION") as "NO ACTION" | "CASCADE" | "SET NULL",
+ state: { ...(foreignKey.oracleState ?? { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false }) },
+ };
+ return { original, target };
+ });
+}
+
function triggerChanged(trigger: EditableStructureTrigger): boolean {
if (!trigger.original || trigger.markedForDrop) return true;
const original = trigger.original;
@@ -1997,6 +2039,248 @@ const tableOwnerRolesLoading = ref(false);
const tableOwnerRolesLoadError = ref("");
const supportsTableOwner = computed(() => !isCreateMode.value && databaseType.value === "postgres");
const primaryKeyName = ref("");
+const existingPrimaryKeyDraft = ref<ExistingPrimaryKeyChange>();
+const existingPrimaryKeyPlan = shallowRef<OceanbasePrimaryKeyPlan>();
+const existingPrimaryKeySession = ref<{ revision: number; configFingerprint: string }>();
+const existingOracleForeignKeyPlan = shallowRef<OracleForeignKeyPlan>();
+const existingOracleForeignKeySession = ref<{ revision: number; configFingerprint: string }>();
+const newOracleForeignKeyPlan = shallowRef<OracleForeignKeyCreatePlan>();
+const newOracleForeignKeySession = ref<{ revision: number; configFingerprint: string; draftFingerprint: string }>();
+const oracleForeignKeyBusy = ref(false);
+const oracleConstraintDraft = ref<OracleConstraintChange>();
+const oracleConstraintPlan = shallowRef<OracleConstraintPlan>();
+const oracleConstraintSession = ref<{ revision: number; configFingerprint: string; draftFingerprint: string }>();
+const oracleConstraintBusy = ref(false);
+const oracleIndexPlan = shallowRef<OracleIndexPlan>();
+const oracleIndexBusy = ref(false);
+const oracleIndexEpoch = ref(0);
+const oracleIndexReady = shallowRef<OracleIndexLoadBaseline>();
+const oracleIndexRefreshGuard = ref<{ target: string; afterRequestId: number; completedCreates: OracleIndexDefinition[] }>();
+const oracleIndexConfirmationScope = `structure-oracle-index:${uuid()}`;
+const oracleConstraintConfirmationScope = `structure-oracle-constraint:${uuid()}`;
+const oracleConstraintChanged = computed(() => !!oracleConstraintDraft.value && JSON.stringify(oracleConstraintDraft.value.original) !== JSON.stringify(oracleConstraintDraft.value.target));
+const primaryKeyNewColumn = ref("");
+const primaryKeyBusy = ref(false);
+const primaryKeyResultOpen = ref(false);
+const primaryKeyResultMessage = ref("");
+const primaryKeyResultDetails = ref("");
+const primaryKeyResultTitle = ref("oceanbasePrimaryKey.resultTitle");
+const oracleForeignKeyCreateRecovery = ref<TableStructureEditorDraft["oracleForeignKeyCreateRecovery"]>();
+let primaryKeyUnmounted = false;
+const primaryKeyConfirmationScope = `structure-primary-key:${uuid()}`;
+const oracleForeignKeyConfirmationScope = `structure-oracle-foreign-key:${uuid()}`;
+onBeforeUnmount(() => {
+ primaryKeyUnmounted = true;
+ if (primaryKeyBusy.value) productionSafetyStore.cancelScope(primaryKeyConfirmationScope);
+ if (saving.value) productionSafetyStore.cancelScope(oracleForeignKeyConfirmationScope);
+ if (saving.value) productionSafetyStore.cancelScope(oracleConstraintConfirmationScope);
+ if (saving.value) productionSafetyStore.cancelScope(oracleIndexConfirmationScope);
+});
+watch(
+ () => [props.connectionId, props.database, props.schema, props.tableName, props.catalog],
+ () => {
+ invalidateOracleIndexReady();
+ if (primaryKeyBusy.value) productionSafetyStore.cancelScope(primaryKeyConfirmationScope);
+ if (saving.value) productionSafetyStore.cancelScope(oracleForeignKeyConfirmationScope);
+ if (saving.value) productionSafetyStore.cancelScope(oracleConstraintConfirmationScope);
+ if (saving.value) productionSafetyStore.cancelScope(oracleIndexConfirmationScope);
+ existingPrimaryKeyDraft.value = undefined;
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ existingOracleForeignKeyPlan.value = undefined;
+ existingOracleForeignKeySession.value = undefined;
+ newOracleForeignKeyPlan.value = undefined;
+ newOracleForeignKeySession.value = undefined;
+ oracleConstraintDraft.value = undefined;
+ oracleConstraintPlan.value = undefined;
+ oracleConstraintSession.value = undefined;
+ oracleIndexPlan.value = undefined;
+ if (primaryKeyBusy.value) saving.value = false;
+ },
+);
+watch(
+ () => [databaseType.value, props.connectionId ? store.connectionStateRevision(props.connectionId) : -1, props.connectionId && store.getConfig(props.connectionId) ? connectionConfigFingerprint(store.getConfig(props.connectionId)!) : ""],
+ () => invalidateOracleIndexReady(),
+);
+const canEditExistingPrimaryKey = computed(() => !isCreateMode.value && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle"));
+const isOracleConstraintEditor = canEditExistingPrimaryKey;
+const existingPrimaryKeyChanged = computed(() => !!existingPrimaryKeyDraft.value && JSON.stringify(existingPrimaryKeyDraft.value.columns) !== JSON.stringify(existingPrimaryKeyDraft.value.originalColumns));
+const primaryKeyAvailableColumns = computed(() => columns.value.filter((column) => column.original && !column.markedForDrop && !existingPrimaryKeyDraft.value?.columns.includes(column.name)));
+const currentPrimaryKeyIndex = computed(() => {
+ const plan = existingPrimaryKeyPlan.value;
+ if (!plan || JSON.stringify(plan.draft ?? plan.change) !== JSON.stringify(existingPrimaryKeyDraft.value) || JSON.stringify(plan.target) !== JSON.stringify(primaryKeyTarget())) return undefined;
+ return plan.change.oracleIndex;
+});
+
+function primaryKeyTarget(): PrimaryKeyTarget {
+ return { connectionId: props.connectionId, database: props.database, schema: metadataSchema.value, tableName: props.tableName, catalog: props.catalog, databaseType: databaseType.value === "oracle" ? "oracle" : "oceanbase-oracle" };
+}
+
+function oracleConstraintTarget(): OracleConstraintTarget {
+ return { ...primaryKeyTarget(), schema: metadataSchema.value, databaseType: databaseType.value === "oracle" ? "oracle" : "oceanbase-oracle" };
+}
+
+function oracleIndexTargetIdentity(target: OracleConstraintTarget): string {
+ return JSON.stringify({ connectionId: target.connectionId, database: target.database, schema: target.schema, tableName: target.tableName, catalog: target.catalog });
+}
+
+function invalidateOracleIndexReady() {
+ oracleIndexEpoch.value += 1;
+ oracleIndexReady.value = undefined;
+}
+
+function oracleIndexLoadIsCurrent(requestId: number, targetIdentity: string, revision: number | undefined, configFingerprint: string) {
+ const connectionId = props.connectionId;
+ const config = connectionId ? store.getConfig(connectionId) : undefined;
+ return (
+ requestId === structureLoadRequestId &&
+ targetIdentity === oracleIndexTargetIdentity(oracleConstraintTarget()) &&
+ (revision === undefined || (store.connectionStateRevision(connectionId!) === revision && store.isCurrentConnectionStateRevision(connectionId!, revision))) &&
+ (revision === undefined || (config ? connectionConfigFingerprint(config) : "") === configFingerprint)
+ );
+}
+
+async function editOracleConstraint(info: ConstraintInfo) {
+ if (!isOracleConstraintEditor.value || saving.value || oracleConstraintBusy.value || existingPrimaryKeyChanged.value || hasPendingStructureChanges(false, false)) return;
+ const target = oracleConstraintTarget();
+ const identity = JSON.stringify(target);
+ try {
+ await loadStructure(true, { columns: false, indexes: true, constraints: true, foreignKeys: false, triggers: false, partitions: false, tableComment: false }, true, { forceMetadata: true, blockSecondaryMetadata: true, preserveDraft: true });
+ if (primaryKeyUnmounted || identity !== JSON.stringify(oracleConstraintTarget())) return;
+ const current = constraints.value.find((item) => item.name === info.name && item.constraint_type === info.constraint_type);
+ if (!current) throw new Error("Constraint metadata changed. Refresh the table definition.");
+ const original = oracleConstraintDefinitionFromInfo(current, target);
+ oracleConstraintDraft.value = { original, target: cloneDraftValue(original), ...(original.kind === "unique" ? { indexPolicy: target.databaseType === "oracle" ? ("keep" as const) : ("none" as const) } : {}) };
+ } catch (error) {
+ if (identity === JSON.stringify(oracleConstraintTarget())) errorMessage.value = error instanceof Error ? error.message : String(error);
+ }
+}
+
+function deleteOracleConstraint(info: ConstraintInfo) {
+ if (!isOracleConstraintEditor.value || saving.value || oracleConstraintBusy.value || oracleConstraintDraft.value) return;
+ try {
+ const target = oracleConstraintTarget();
+ const original = oracleConstraintDefinitionFromInfo(info, target);
+ oracleConstraintDraft.value = { original, target: null, ...(original.kind === "unique" ? { indexPolicy: target.databaseType === "oracle" ? ("keep" as const) : ("none" as const) } : {}) };
+ } catch (error) {
+ errorMessage.value = error instanceof Error ? error.message : String(error);
+ }
+}
+
+function addOracleConstraint(kind: "check" | "unique") {
+ if (!isOracleConstraintEditor.value || saving.value || oracleConstraintBusy.value || hasPendingStructureChanges()) return;
+ const prefix = kind === "check" ? "DBX_CHECK_" : "DBX_UNIQUE_";
+ let suffix = 1;
+ while (constraints.value.some((item) => item.name === `${prefix}${suffix}`)) suffix += 1;
+ const name = `${prefix}${suffix}`;
+ const state = { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false };
+ const definition: OracleConstraintDefinition =
+ kind === "check"
+ ? { kind, definition: { name, expression: "", state } }
+ : {
+ kind,
+ definition: {
+ name,
+ columns: [],
+ state,
+ relyRaw: "NULL",
+ index: {
+ owner: metadataSchema.value,
+ name: "",
+ tableOwner: metadataSchema.value,
+ tableName: props.tableName,
+ sharing: "exclusive",
+ metadataComplete: false,
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: "N",
+ columns: [],
+ directions: [],
+ keyIsExpression: [],
+ includedColumns: [],
+ newNameAvailable: false,
+ },
+ },
+ };
+ oracleConstraintDraft.value = { original: null, target: definition, ...(kind === "unique" && databaseType.value === "oceanbase-oracle" ? { indexPolicy: "none" as const } : {}) };
+}
+
+function cancelOracleConstraintEdit() {
+ oracleConstraintDraft.value = undefined;
+ oracleConstraintPlan.value = undefined;
+ oracleConstraintSession.value = undefined;
+ oracleIndexPlan.value = undefined;
+ pendingStatements.value = [];
+ warnings.value = [];
+ syncDraftToParent();
+}
+
+function addOracleUniqueColumn(name: string) {
+ const definition = oracleConstraintDraft.value?.target?.kind === "unique" ? oracleConstraintDraft.value.target.definition : undefined;
+ if (definition && name && !definition.columns.includes(name)) definition.columns.push(name);
+}
+
+function canOpenPairedOracleConstraint(index: EditableStructureIndex): boolean {
+ return isOracleConstraintEditor.value && index.isUnique && !!index.original;
+}
+
+async function editOracleUniqueConstraintForIndex(index: EditableStructureIndex) {
+ if (!canOpenPairedOracleConstraint(index)) return;
+ const target = oracleConstraintTarget();
+ const identity = JSON.stringify(target);
+ try {
+ const fresh = await api.listConstraints(target.connectionId, target.database, target.schema, target.tableName, target.catalog);
+ if (primaryKeyUnmounted || identity !== JSON.stringify(oracleConstraintTarget())) return;
+ const constraint = fresh.find((item) => item.constraint_type === "UNIQUE" && item.oracle_metadata?.metadataComplete && item.oracle_metadata.owner === target.schema && item.oracle_metadata.indexOwner === target.schema && item.oracle_metadata.indexName === index.original?.name);
+ if (!constraint) throw new Error("This unique index has no uniquely paired constraint metadata.");
+ activeTab.value = "constraints";
+ await editOracleConstraint(constraint);
+ } catch (error) {
+ if (identity === JSON.stringify(oracleConstraintTarget())) errorMessage.value = error instanceof Error ? error.message : String(error);
+ }
+}
+
+function moveOracleUniqueColumn(index: number, direction: number) {
+ const columns = oracleConstraintDraft.value?.target?.kind === "unique" ? oracleConstraintDraft.value.target.definition.columns : undefined;
+ if (!columns || index + direction < 0 || index + direction >= columns.length) return;
+ const [column] = columns.splice(index, 1);
+ columns.splice(index + direction, 0, column!);
+}
+
+function primaryKeyError(error: unknown): string {
+ return error instanceof OceanbasePrimaryKeyValidationError ? t(`oceanbasePrimaryKey.${error.key}`, error.values) : error instanceof Error ? error.message : String(error);
+}
+
+async function editExistingPrimaryKey(constraint: ConstraintInfo, remove = false) {
+ if (!canEditExistingPrimaryKey.value || saving.value || primaryKeyBusy.value) return;
+ const target = JSON.stringify(primaryKeyTarget());
+ await loadStructure(true, { columns: true, indexes: true, constraints: true, foreignKeys: false, triggers: false, partitions: false, tableComment: false }, true, { blockSecondaryMetadata: true, preserveDraft: true });
+ if (primaryKeyUnmounted || target !== JSON.stringify(primaryKeyTarget())) return;
+ const current = constraints.value.find((item) => item.name === constraint.name && item.constraint_type === "PRIMARY KEY");
+ if (!current || !current.columns.length) {
+ errorMessage.value = t("oceanbasePrimaryKey.incompleteMetadata");
+ return;
+ }
+ existingPrimaryKeyDraft.value = { name: current.name, originalColumns: [...current.columns], columns: remove ? [] : [...current.columns] };
+ if (databaseType.value === "oracle") existingPrimaryKeyDraft.value.oracleIndex = { policy: "keep", owner: metadataSchema.value, name: "" };
+ primaryKeyNewColumn.value = "";
+}
+
+function moveExistingPrimaryKeyColumn(index: number, direction: number) {
+ const draft = existingPrimaryKeyDraft.value;
+ if (!draft || primaryKeyBusy.value || index + direction < 0 || index + direction >= draft.columns.length) return;
+ const [name] = draft.columns.splice(index, 1);
+ draft.columns.splice(index + direction, 0, name!);
+}
+
+function addExistingPrimaryKeyColumn() {
+ if (primaryKeyBusy.value || !primaryKeyAvailableColumns.value.some((column) => column.name === primaryKeyNewColumn.value)) return;
+ existingPrimaryKeyDraft.value?.columns.push(primaryKeyNewColumn.value);
+ primaryKeyNewColumn.value = "";
+}
// Mirrors Rust `supports_named_primary_key`: engines that persist a user-supplied
// PK constraint name. Other dialects ignore the symbol, so the field is hidden.
const canNamePrimaryKey = computed(() => {
@@ -2388,6 +2672,9 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {
indexes: cloneDraftValue(indexes.value),
foreignKeys: cloneDraftValue(foreignKeys.value),
constraints: cloneDraftValue(constraints.value),
+ existingPrimaryKey: existingPrimaryKeyDraft.value ? cloneDraftValue(existingPrimaryKeyDraft.value) : undefined,
+ oracleConstraintChange: oracleConstraintDraft.value ? cloneDraftValue(oracleConstraintDraft.value) : undefined,
+ oracleForeignKeyCreateRecovery: oracleForeignKeyCreateRecovery.value ? cloneDraftValue(oracleForeignKeyCreateRecovery.value) : undefined,
constraintsLoaded: constraintsLoaded.value,
triggers: cloneDraftValue(triggers.value),
triggersLoaded: triggersLoaded.value,
@@ -2436,6 +2723,7 @@ function syncDraftToParent() {
}
function restoreDraft(draft: TableStructureEditorDraft) {
+ invalidateOracleIndexReady();
lastSyncedDraft = draft;
restoringDraft = true;
draftHydrated = false;
@@ -2481,6 +2769,15 @@ function restoreDraft(draft: TableStructureEditorDraft) {
normalizeConcurrentIndexDraftsForCurrentAvailability();
foreignKeys.value = cloneDraftValue(draft.foreignKeys || []);
constraints.value = cloneDraftValue(draft.constraints || []);
+ existingPrimaryKeyDraft.value = draft.existingPrimaryKey ? cloneDraftValue(draft.existingPrimaryKey) : undefined;
+ oracleConstraintDraft.value = draft.oracleConstraintChange ? cloneDraftValue(draft.oracleConstraintChange) : undefined;
+ oracleForeignKeyCreateRecovery.value = draft.oracleForeignKeyCreateRecovery ? cloneDraftValue(draft.oracleForeignKeyCreateRecovery) : undefined;
+ if (oracleForeignKeyCreateRecovery.value) {
+ primaryKeyResultTitle.value = "oracleForeignKey.resultTitle";
+ primaryKeyResultMessage.value = `${metadataSchema.value}.${oracleForeignKeyCreateRecovery.value.tableName}: ${t("oracleForeignKey.createdTablePartial")}`;
+ primaryKeyResultDetails.value = oracleForeignKeyCreateRecovery.value.details;
+ primaryKeyResultOpen.value = true;
+ }
// Drafts created before constraint loading existed have no saved facet.
constraintsLoaded.value = draft.constraintsLoaded ?? false;
triggers.value = cloneDraftValue(draft.triggers || []);
@@ -2556,7 +2853,9 @@ function markDraftHydratedAndSync() {
syncDraftToParent();
}
-function hasPendingStructureChanges(): boolean {
+function hasPendingStructureChanges(includeExistingPrimaryKey = true, includeOracleConstraint = true): boolean {
+ if (includeExistingPrimaryKey && existingPrimaryKeyChanged.value) return true;
+ if (includeOracleConstraint && oracleConstraintChanged.value) return true;
if (isCreateMode.value) {
return (
!!newTableName.value.trim() ||
@@ -2598,6 +2897,14 @@ function clearSqlPreviewState() {
pendingStatements.value = [];
warnings.value = [];
sqliteSchemaRevision.value = undefined;
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ existingOracleForeignKeyPlan.value = undefined;
+ existingOracleForeignKeySession.value = undefined;
+ newOracleForeignKeyPlan.value = undefined;
+ newOracleForeignKeySession.value = undefined;
+ oracleConstraintPlan.value = undefined;
+ oracleConstraintSession.value = undefined;
}
function dataTypeOptionsCacheKey(connectionId: string, database: string) {
@@ -2763,6 +3070,8 @@ function structureChangeOptions(): BuildTableStructureChangeSqlOptions {
foreignTable: isForeignTable.value,
isGaussdbMMode: connection.value?.driver_profile?.toLowerCase() === "gaussdb-m",
primaryKeyName: willCreateNewPrimaryKey.value ? primaryKeyName.value.trim() || undefined : undefined,
+ primaryKeyChange: existingPrimaryKeyChanged.value ? cloneDraftValue(existingPrimaryKeyDraft.value) : undefined,
+ oracleConstraintChanges: oracleConstraintChanged.value && oracleConstraintDraft.value ? [cloneDraftValue(oracleConstraintDraft.value)] : undefined,
};
}
@@ -2782,6 +3091,14 @@ function partitionSqlOptions(): TablePartitionSqlOptions {
async function refreshSqlPreview() {
const requestId = ++sqlPreviewRequestId;
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ oracleConstraintPlan.value = undefined;
+ oracleConstraintSession.value = undefined;
+ existingOracleForeignKeyPlan.value = undefined;
+ existingOracleForeignKeySession.value = undefined;
+ newOracleForeignKeyPlan.value = undefined;
+ newOracleForeignKeySession.value = undefined;
if (concurrentAvailabilityInvalidated.value) {
// Availability gap in effect: never regenerate SQL here — doing so would
// turn a lost Concurrent request into a silent blocking CREATE INDEX. Keep
@@ -2823,6 +3140,147 @@ async function refreshSqlPreview() {
sqlPreviewPending.value = false;
return;
}
+ if (existingPrimaryKeyChanged.value) {
+ sqlPreviewLoading.value = true;
+ try {
+ if (!canEditExistingPrimaryKey.value || hasPendingStructureChanges(false)) throw new OceanbasePrimaryKeyValidationError("mixedDraft");
+ const target = primaryKeyTarget();
+ const connectionRevision = store.connectionStateRevision(target.connectionId);
+ const currentConfig = store.getConfig(target.connectionId);
+ const configFingerprint = currentConfig ? connectionConfigFingerprint(currentConfig) : "";
+ let change = cloneDraftValue(existingPrimaryKeyDraft.value!);
+ const draft = cloneDraftValue(change);
+ let snapshot: string;
+ if (target.databaseType === "oracle") {
+ const prepared = await prepareOraclePrimaryKeyChange(target, change);
+ change = prepared.change;
+ snapshot = prepared.snapshot;
+ } else {
+ snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ }
+ if (requestId !== sqlPreviewRequestId) return;
+ const result = await api.buildTableStructureChangeSql({ ...structureChangeOptions(), primaryKeyChange: change });
+ if (requestId !== sqlPreviewRequestId) return;
+ const latestConfig = store.getConfig(target.connectionId);
+ if (store.connectionStateRevision(target.connectionId) !== connectionRevision || !store.isCurrentConnectionStateRevision(target.connectionId, connectionRevision) || (latestConfig ? connectionConfigFingerprint(latestConfig) : "") !== configFingerprint) {
+ throw new Error(t("oceanbasePrimaryKey.refreshRequired"));
+ }
+ if (result.warnings.length) throw new Error(result.warnings.join("\n"));
+ if (result.statements.length !== (change.columns.length ? 2 : 1)) throw new OceanbasePrimaryKeyValidationError("incompletePlan");
+ existingPrimaryKeyPlan.value = { target, change, draft, snapshot, statements: [...result.statements] };
+ existingPrimaryKeySession.value = { revision: connectionRevision, configFingerprint };
+ pendingStatements.value = [...result.statements];
+ warnings.value = [];
+ } catch (error) {
+ if (requestId !== sqlPreviewRequestId) return;
+ pendingStatements.value = [];
+ warnings.value = [primaryKeyError(error)];
+ } finally {
+ if (requestId === sqlPreviewRequestId) {
+ sqlPreviewLoading.value = false;
+ sqlPreviewPending.value = false;
+ }
+ }
+ return;
+ }
+ if (oracleConstraintChanged.value && oracleConstraintDraft.value) {
+ sqlPreviewLoading.value = true;
+ const target = primaryKeyTarget() as OracleConstraintTarget;
+ const revision = store.connectionStateRevision(target.connectionId);
+ const config = store.getConfig(target.connectionId);
+ const fingerprint = config ? connectionConfigFingerprint(config) : "";
+ const connectionCurrent = () => {
+ const currentConfig = store.getConfig(target.connectionId);
+ return store.connectionStateRevision(target.connectionId) === revision && store.isCurrentConnectionStateRevision(target.connectionId, revision) && (currentConfig ? connectionConfigFingerprint(currentConfig) : "") === fingerprint;
+ };
+ const draftFingerprint = JSON.stringify(oracleConstraintDraft.value);
+ try {
+ if (!isOracleConstraintEditor.value || isCreateMode.value || existingPrimaryKeyChanged.value || hasPendingStructureChanges(false, false)) throw new Error("Apply CHECK/UNIQUE changes separately from other table structure drafts.");
+ const plan = await prepareOracleConstraintPlan(target, structureChangeOptions(), cloneDraftValue(oracleConstraintDraft.value), connectionCurrent);
+ if (requestId !== sqlPreviewRequestId || JSON.stringify(target) !== JSON.stringify(primaryKeyTarget()) || draftFingerprint !== JSON.stringify(oracleConstraintDraft.value)) return;
+ const currentConfig = store.getConfig(target.connectionId);
+ if (store.connectionStateRevision(target.connectionId) !== revision || (currentConfig ? connectionConfigFingerprint(currentConfig) : "") !== fingerprint) throw new Error("Connection changed while preparing the constraint plan. Refresh and preview again.");
+ oracleConstraintPlan.value = plan;
+ oracleConstraintSession.value = { revision, configFingerprint: fingerprint, draftFingerprint };
+ pendingStatements.value = [...plan.statements];
+ warnings.value = [];
+ } catch (error) {
+ if (requestId !== sqlPreviewRequestId) return;
+ pendingStatements.value = [];
+ warnings.value = [error instanceof Error ? error.message : String(error)];
+ } finally {
+ if (requestId === sqlPreviewRequestId) {
+ sqlPreviewLoading.value = false;
+ sqlPreviewPending.value = false;
+ }
+ }
+ return;
+ }
+ const foreignKeyChanges = isOracleForeignKeyEditor.value ? oracleForeignKeyChanges() : [];
+ if (isCreateMode.value && foreignKeyChanges.length) {
+ sqlPreviewLoading.value = true;
+ const target = { ...primaryKeyTarget(), schema: metadataSchema.value, tableName: newTableName.value.trim(), databaseType: databaseType.value === "oracle" ? ("oracle" as const) : ("oceanbase-oracle" as const) };
+ const connectionRevision = store.connectionStateRevision(target.connectionId);
+ const connectionConfig = store.getConfig(target.connectionId);
+ const configFingerprint = connectionConfig ? connectionConfigFingerprint(connectionConfig) : "";
+ const connectionCurrent = () => {
+ const currentConfig = store.getConfig(target.connectionId);
+ return store.connectionStateRevision(target.connectionId) === connectionRevision && store.isCurrentConnectionStateRevision(target.connectionId, connectionRevision) && (currentConfig ? connectionConfigFingerprint(currentConfig) : "") === configFingerprint;
+ };
+ try {
+ const options = { ...structureChangeOptions(), oracleForeignKeyChanges: foreignKeyChanges };
+ const partitioning = createPartitioningEnabled.value ? { kind: createPartitioningKind.value, columns: createPartitioningColumns.value, expression: createPartitioningExpression.value } : undefined;
+ const plan = await prepareOracleForeignKeyCreatePlan(target, options, foreignKeyChanges, partitioning, connectionCurrent);
+ if (requestId !== sqlPreviewRequestId || JSON.stringify(target) !== JSON.stringify({ ...primaryKeyTarget(), schema: metadataSchema.value, tableName: newTableName.value.trim(), databaseType: target.databaseType })) return;
+ const currentConfig = store.getConfig(target.connectionId);
+ if (store.connectionStateRevision(target.connectionId) !== connectionRevision || (currentConfig ? connectionConfigFingerprint(currentConfig) : "") !== configFingerprint) throw new Error(t("oracleForeignKey.refreshRequired"));
+ newOracleForeignKeyPlan.value = plan;
+ newOracleForeignKeySession.value = { revision: connectionRevision, configFingerprint, draftFingerprint: JSON.stringify({ options: plan.options, changes: plan.changes, partitioning: plan.partitioning }) };
+ pendingStatements.value = [...plan.statements];
+ warnings.value = [];
+ } catch (error) {
+ if (requestId !== sqlPreviewRequestId) return;
+ pendingStatements.value = [];
+ warnings.value = [error instanceof Error ? error.message : String(error)];
+ } finally {
+ if (requestId === sqlPreviewRequestId) {
+ sqlPreviewLoading.value = false;
+ sqlPreviewPending.value = false;
+ }
+ }
+ return;
+ }
+ if (foreignKeyChanges.length) {
+ sqlPreviewLoading.value = true;
+ const target = { ...primaryKeyTarget(), schema: metadataSchema.value, tableName: props.tableName || "", databaseType: databaseType.value === "oracle" ? ("oracle" as const) : ("oceanbase-oracle" as const) };
+ const connectionRevision = store.connectionStateRevision(target.connectionId);
+ const connectionConfig = store.getConfig(target.connectionId);
+ const configFingerprint = connectionConfig ? connectionConfigFingerprint(connectionConfig) : "";
+ const connectionCurrent = () => {
+ const currentConfig = store.getConfig(target.connectionId);
+ return store.connectionStateRevision(target.connectionId) === connectionRevision && store.isCurrentConnectionStateRevision(target.connectionId, connectionRevision) && (currentConfig ? connectionConfigFingerprint(currentConfig) : "") === configFingerprint;
+ };
+ try {
+ const plan = await prepareOracleForeignKeyPlan(target, structureChangeOptions(), foreignKeyChanges, connectionCurrent);
+ if (requestId !== sqlPreviewRequestId || JSON.stringify(target) !== JSON.stringify(primaryKeyTarget())) return;
+ const currentConfig = store.getConfig(target.connectionId);
+ if (store.connectionStateRevision(target.connectionId) !== connectionRevision || (currentConfig ? connectionConfigFingerprint(currentConfig) : "") !== configFingerprint) throw new Error(t("oracleForeignKey.refreshRequired"));
+ existingOracleForeignKeyPlan.value = plan;
+ existingOracleForeignKeySession.value = { revision: connectionRevision, configFingerprint };
+ pendingStatements.value = [...plan.statements];
+ warnings.value = [];
+ } catch (error) {
+ if (requestId !== sqlPreviewRequestId) return;
+ pendingStatements.value = [];
+ warnings.value = [error instanceof Error ? error.message : String(error)];
+ } finally {
+ if (requestId === sqlPreviewRequestId) {
+ sqlPreviewLoading.value = false;
+ sqlPreviewPending.value = false;
+ }
+ }
+ return;
+ }
const indexWarnings = indexes.value
.filter((index) => !index.markedForDrop && needsIndexColumnValidation(index))
.flatMap((index) => {
@@ -2914,6 +3372,9 @@ const canApply = computed(
() =>
!loading.value &&
!saving.value &&
+ !primaryKeyBusy.value &&
+ !oracleForeignKeyBusy.value &&
+ !oracleConstraintBusy.value &&
(databaseType.value !== "starrocks" || !starrocksStatusBusy.value) &&
!postSaveRefreshing.value &&
!secondaryMetadataLoading.value &&
@@ -2923,6 +3384,7 @@ const canApply = computed(
pendingStatements.value.length > 0 &&
warnings.value.length === 0 &&
!concurrentAvailabilityInvalidated.value &&
+ !(isCreateMode.value && oracleForeignKeyCreateRecovery.value?.uncertainSteps.includes("CREATE")) &&
(!hasSqliteTypeChange.value || !!sqliteSchemaRevision.value) &&
!!props.connectionId &&
(isCreateMode.value ? !!newTableName.value.trim() : !!props.tableName),
@@ -2934,6 +3396,7 @@ function clearDraft() {
}
function resetState() {
+ invalidateOracleIndexReady();
loading.value = false;
saving.value = false;
postSaveRefreshing.value = false;
@@ -2960,6 +3423,17 @@ function resetState() {
sqliteSchemaRevision.value = undefined;
foreignKeys.value = [];
constraints.value = [];
+ existingPrimaryKeyDraft.value = undefined;
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ existingOracleForeignKeyPlan.value = undefined;
+ existingOracleForeignKeySession.value = undefined;
+ newOracleForeignKeyPlan.value = undefined;
+ newOracleForeignKeySession.value = undefined;
+ oracleConstraintDraft.value = undefined;
+ oracleConstraintPlan.value = undefined;
+ oracleConstraintSession.value = undefined;
+ primaryKeyNewColumn.value = "";
constraintsLoaded.value = false;
partitioning.value = null;
triggers.value = [];
@@ -3031,6 +3505,7 @@ async function reloadStructureFromDatabase() {
starrocksAlterContext.value = undefined;
starrocksSortColumns.value = undefined;
const refreshDdl = activeTab.value === "ddl";
+ const preserveOracleIndexDraft = oracleIndexRefreshGuard.value?.target === oracleIndexTargetIdentity(oracleConstraintTarget());
const metadataMatch = { connectionId: props.connectionId, database: props.database, schema: metadataSchema.value, tableName: props.tableName };
invalidateTableMetadataCache(metadataMatch);
await invalidateObjectDdl(ddlRequest());
@@ -3043,7 +3518,11 @@ async function reloadStructureFromDatabase() {
await Promise.all([fetchDdl(true), loadVisibleTableComment(true), loadTableOwner(true), loadTableOwnerRoles(), loadMysqlTableEngine(true)]);
markDraftHydratedAndSync();
} else {
- await Promise.all([loadStructure(false, visibleTableStructureRefreshScope(activeTab.value), true, { blockSecondaryMetadata: true, forceDdl: true, forceMetadata: true }), loadTableOwner(true), loadTableOwnerRoles(), loadMysqlTableEngine(true)]);
+ await Promise.all([loadStructure(false, visibleTableStructureRefreshScope(activeTab.value), true, { blockSecondaryMetadata: true, forceDdl: true, forceMetadata: true, preserveDraft: preserveOracleIndexDraft }), loadTableOwner(true), loadTableOwnerRoles(), loadMysqlTableEngine(true)]);
+ if (preserveOracleIndexDraft) {
+ markDraftHydratedAndSync();
+ await refreshSqlPreview();
+ }
}
}
@@ -3244,8 +3723,15 @@ async function loadStructure(
const schema = metadataSchema.value;
const tableName = props.tableName;
if (!connectionId || !database || !tableName) return;
- const effectiveScope = withRequiredPostgresPrimaryKeyMetadata(scope);
+ const oracleIndexContext = !isCreateMode.value && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");
+ const needsOracleIndexBaseline = oracleIndexContext && scope.indexes;
+ const effectiveScope = withRequiredPostgresPrimaryKeyMetadata(needsOracleIndexBaseline ? { ...scope, columns: true, indexes: true } : scope);
+ if (oracleIndexContext && (scope.columns || scope.indexes)) invalidateOracleIndexReady();
+ let loadEpoch = oracleIndexEpoch.value;
const requestId = ++structureLoadRequestId;
+ const loadTargetIdentity = oracleIndexTargetIdentity(oracleConstraintTarget());
+ let loadConnectionRevision: number | undefined;
+ let loadConfigFingerprint = "";
if (!silent) loading.value = true;
setSecondaryMetadataLoading(effectiveScope, true);
errorMessage.value = "";
@@ -3258,9 +3744,14 @@ async function loadStructure(
let appliedColumnsSignature: string | undefined;
try {
await store.ensureConnected(connectionId);
+ loadConnectionRevision = store.connectionStateRevision(connectionId);
+ const loadConnection = store.getConfig(connectionId);
+ loadConfigFingerprint = loadConnection ? connectionConfigFingerprint(loadConnection) : "";
+ loadEpoch = oracleIndexEpoch.value;
+ if (requestId !== structureLoadRequestId || loadTargetIdentity !== oracleIndexTargetIdentity(oracleConstraintTarget())) return;
const metadataRequest = ddlRequest();
- const forceMetadata = options.forceMetadata === true;
+ const forceMetadata = options.forceMetadata === true || needsOracleIndexBaseline;
const partitionStatusPromise =
tableMetadataCapabilities.value.partitions && !isCreateMode.value
? api
@@ -3312,8 +3803,10 @@ async function loadStructure(
return result.value;
})
: Promise.resolve(undefined);
+ const secondaryMetadataResultsPromise = Promise.allSettled([indexesPromise, foreignKeysPromise, constraintsPromise, triggersPromise, partitioningPromise]);
let nextColumns = await columnsPromise;
+ if (!oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) return;
if (nextColumns) {
if (databaseType.value === "manticoresearch" && tableMetadataCapabilities.value.ddl) {
try {
@@ -3325,13 +3818,17 @@ async function loadStructure(
/* ignore — Manticore column properties can still come from SHOW COLUMNS when available */
}
}
+ if (!oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) return;
// Load live charset/collation metadata from the MySQL server so the column
// editor shows the correct options for the server version.
void loadCharsetMetadata();
void loadMysqlTableDefaultCollation();
- const nextColumnDrafts = createColumnDrafts(nextColumns, databaseType.value);
- const hydratedColumnDrafts = supportsCharacterLengthUnits.value && options.characterLengthUnitsAfterSave ? restoreCharacterLengthUnitsAfterSave(databaseType.value, nextColumnDrafts, options.characterLengthUnitsAfterSave) : nextColumnDrafts;
- columns.value = applyStoredLocalColumnOrder(hydratedColumnDrafts);
+ const retainOracleColumns = oracleIndexContext && options.preserveDraft === true && !scope.columns;
+ if (!retainOracleColumns) {
+ const nextColumnDrafts = createColumnDrafts(nextColumns, databaseType.value);
+ const hydratedColumnDrafts = supportsCharacterLengthUnits.value && options.characterLengthUnitsAfterSave ? restoreCharacterLengthUnitsAfterSave(databaseType.value, nextColumnDrafts, options.characterLengthUnitsAfterSave) : nextColumnDrafts;
+ columns.value = applyStoredLocalColumnOrder(hydratedColumnDrafts);
+ }
appliedColumnsSignature = JSON.stringify(nextColumns);
loadedMetadataFacets.add("columns");
if (!options.preserveDraft) clearColumnSelection();
@@ -3364,8 +3861,8 @@ async function loadStructure(
}
}
const applySecondaryMetadata = async () => {
- const [indexesResult, foreignKeysResult, constraintsResult, triggersResult, partitioningResult] = await Promise.allSettled([indexesPromise, foreignKeysPromise, constraintsPromise, triggersPromise, partitioningPromise]);
- if (requestId !== structureLoadRequestId) return;
+ const [indexesResult, foreignKeysResult, constraintsResult, triggersResult, partitioningResult] = await secondaryMetadataResultsPromise;
+ if (!oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) return;
type SecondaryMetadataResult = { facet: ObjectMetadataFacet; result: PromiseSettledResult<unknown> };
const secondaryResults: SecondaryMetadataResult[] = [
@@ -3390,11 +3887,39 @@ async function loadStructure(
const nextTriggers = triggersResult.status === "fulfilled" ? triggersResult.value : undefined;
if (nextIndexes) {
// An empty lazy load changes no draft data and should not trigger another save.
- if (nextIndexes.length || indexes.value.length) indexes.value = createIndexDrafts(nextIndexes);
+ const indexRefreshGuard = oracleIndexRefreshGuard.value;
+ if (options.preserveDraft && indexRefreshGuard?.target === JSON.stringify({ connectionId, database, schema, tableName, catalog })) {
+ indexes.value = mergeOracleIndexDraftsAfterRefresh(indexes.value, nextIndexes, indexRefreshGuard.completedCreates);
+ } else if (nextIndexes.length || indexes.value.length) {
+ indexes.value = createIndexDrafts(nextIndexes);
+ }
+ if (oracleIndexRefreshGuard.value?.target === JSON.stringify({ connectionId, database, schema, tableName, catalog }) && requestId > oracleIndexRefreshGuard.value.afterRequestId) {
+ oracleIndexRefreshGuard.value = undefined;
+ }
loadedMetadataFacets.add("indexes");
}
if (nextForeignKeys) {
- foreignKeys.value = createForeignKeyDrafts(nextForeignKeys);
+ foreignKeys.value = createForeignKeyDrafts(nextForeignKeys, databaseType.value);
+ const recovery = oracleForeignKeyCreateRecovery.value;
+ if (recovery?.tableExists && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle")) {
+ const pending = recovery.remaining
+ .filter((definition) => !foreignKeys.value.some((foreignKey) => foreignKey.name === definition.name))
+ .map((definition) => ({
+ id: `oracle-create-recovery:${definition.name}`,
+ name: definition.name,
+ column: definition.columns[0] || "",
+ refSchema: definition.refSchema,
+ refTable: definition.refTable,
+ refColumn: definition.refColumns[0] || "",
+ columns: [...definition.columns],
+ refColumns: [...definition.refColumns],
+ oracleState: { ...definition.state },
+ onUpdate: "NO ACTION",
+ onDelete: definition.onDelete,
+ markedForDrop: false,
+ }));
+ foreignKeys.value.push(...pending);
+ }
loadedMetadataFacets.add("foreign-keys");
}
if (nextConstraints) {
@@ -3426,11 +3951,36 @@ async function loadStructure(
console.warn("[DBX][structure-editor:secondary-metadata-failed]", error);
})
.finally(() => {
- if (requestId === structureLoadRequestId) setSecondaryMetadataLoading(effectiveScope, false);
+ if (oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) setSecondaryMetadataLoading(effectiveScope, false);
});
- if (options.blockSecondaryMetadata) {
+ if (options.blockSecondaryMetadata || needsOracleIndexBaseline) {
await secondaryMetadataPromise;
}
+ if (needsOracleIndexBaseline && !secondaryMetadataErrors.value.indexes && oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint) && oracleIndexEpoch.value === loadEpoch) {
+ try {
+ const target = oracleConstraintTarget();
+ const snapshot = await readOracleIndexSnapshot(target);
+ if (oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint) && oracleIndexEpoch.value === loadEpoch) {
+ const loadedColumns = columns.value.flatMap((column) => (column.original ? [column.original] : []));
+ if (oracleIndexSnapshotMatchesLoaded(snapshot, target, indexes.value) && oracleIndexSnapshotMatchesLoadedColumns(snapshot, loadedColumns)) {
+ oracleIndexReady.value = {
+ snapshot,
+ epoch: loadEpoch,
+ targetIdentity: loadTargetIdentity,
+ requestId,
+ connectionRevision: loadConnectionRevision!,
+ configFingerprint: loadConfigFingerprint,
+ columnsFingerprint: JSON.stringify(columns.value),
+ indexesFingerprint: JSON.stringify(snapshot.indexes),
+ };
+ }
+ }
+ } catch (error) {
+ if (oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) {
+ secondaryMetadataErrors.value.indexes = error instanceof Error ? error.message : String(error);
+ }
+ }
+ }
loadedSuccessfully = true;
// Cache-served structure metadata can be stale when another session rebuilt
// the table (#8816): the cache is only invalidated by in-app mutations.
@@ -3441,17 +3991,20 @@ async function loadStructure(
void revalidateCachedStructureMetadata(requestId, { columns: columnsServedFromCache, tableComment: commentServedFromCache }, appliedColumnsSignature);
}
} catch (e: any) {
- if (showErrors) {
- errorMessage.value = e?.message || String(e);
- } else {
- console.warn("[DBX][structure-editor:refresh-failed]", e);
+ if (oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) {
+ if (showErrors) {
+ errorMessage.value = e?.message || String(e);
+ } else {
+ console.warn("[DBX][structure-editor:refresh-failed]", e);
+ }
}
+ return { error: e?.message || String(e) };
} finally {
if (!secondaryMetadataScheduled && requestId === structureLoadRequestId) {
setSecondaryMetadataLoading(effectiveScope, false);
}
- if (!silent) loading.value = false;
- if (!options.preserveDraft && loadedSuccessfully && requestId === structureLoadRequestId) {
+ if (!silent && requestId === structureLoadRequestId) loading.value = false;
+ if (!options.preserveDraft && loadedSuccessfully && oracleIndexLoadIsCurrent(requestId, loadTargetIdentity, loadConnectionRevision, loadConfigFingerprint)) {
markDraftHydratedAndSync();
}
}
@@ -3468,22 +4021,41 @@ async function revalidateCachedStructureMetadata(loadRequestId: number, scope: {
const schema = metadataSchema.value;
const tableName = props.tableName;
if (!connectionId || !database || !tableName) return;
+ if (scope.columns && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle")) invalidateOracleIndexReady();
const revalidationId = ++structureMetadataRevalidationId;
const metadataRequest = { connectionId, database, schema, tableName, catalog, queryTimeoutSecs: store.getConfig(connectionId)?.query_timeout_secs };
+ let revalidationConnectionRevision: number | undefined;
+ let revalidationConfigFingerprint = "";
+ const isCurrent = () =>
+ revalidationId === structureMetadataRevalidationId &&
+ loadRequestId === structureLoadRequestId &&
+ connectionId === props.connectionId &&
+ database === props.database &&
+ schema === metadataSchema.value &&
+ tableName === props.tableName &&
+ (catalog || "") === (props.catalog || "") &&
+ (revalidationConnectionRevision === undefined ||
+ (store.connectionStateRevision(connectionId) === revalidationConnectionRevision &&
+ store.isCurrentConnectionStateRevision(connectionId, revalidationConnectionRevision) &&
+ (store.getConfig(connectionId) ? connectionConfigFingerprint(store.getConfig(connectionId)!) : "") === revalidationConfigFingerprint));
try {
await store.ensureConnected(connectionId);
+ revalidationConnectionRevision = store.connectionStateRevision(connectionId);
+ const revalidationConfig = store.getConfig(connectionId);
+ revalidationConfigFingerprint = revalidationConfig ? connectionConfigFingerprint(revalidationConfig) : "";
// Force alone only clears this facet's own key; the web backend keeps its
// own backend-columns/backend-comment entries under the same table prefix
// and would serve them to the forced re-fetch. Drop the whole table scope
// first, the same thing an explicit "Refresh Structure" does.
await invalidateObjectMetadataCache({ connectionId, database, schema, tableName });
+ if (!isCurrent()) return;
const columnsPromise = scope.columns ? loadObjectMetadataFacet(metadataRequest, "columns", () => api.getColumns(connectionId, database, schema, tableName, catalog), { force: true }) : Promise.resolve(undefined);
const commentPromise = scope.tableComment ? loadCachedTableComment(metadataRequest, true) : Promise.resolve(undefined);
// allSettled so a failing comment re-fetch cannot swallow a valid columns
// fix (and vice versa); each failure is logged on its own.
const [columnsResult, commentResult] = await Promise.allSettled([columnsPromise, commentPromise] as const);
// A newer load or revalidation supersedes this one.
- if (revalidationId !== structureMetadataRevalidationId || loadRequestId !== structureLoadRequestId) return;
+ if (!isCurrent()) return;
if (columnsResult.status === "rejected") console.warn("[DBX][structure-editor:columns-metadata-revalidation-failed]", columnsResult.reason);
if (commentResult.status === "rejected") console.warn("[DBX][structure-editor:comment-metadata-revalidation-failed]", commentResult.reason);
@@ -3502,7 +4074,7 @@ async function revalidateCachedStructureMetadata(loadRequestId: number, scope: {
}
if (applied) syncDraftToParent();
} catch (e) {
- console.warn("[DBX][structure-editor:metadata-revalidation-failed]", e);
+ if (isCurrent()) console.warn("[DBX][structure-editor:metadata-revalidation-failed]", e);
}
}
@@ -5091,7 +5663,8 @@ function canDropIndex(index: EditableStructureIndex): boolean {
return !!index.original && !index.isPrimary && structureCapabilities.value.dropIndex;
}
-const canEditForeignKeys = computed(() => structureCapabilities.value.foreignKey);
+const isOracleForeignKeyEditor = computed(() => databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");
+const canEditForeignKeys = computed(() => (isOracleForeignKeyEditor.value ? true : structureCapabilities.value.foreignKey));
const canEditTriggers = computed(() => structureDialect.value === "mysql" || structureDialect.value === "oracle" || structureDialect.value === "sqlserver");
const isOracleTriggerEditor = computed(() => structureDialect.value === "oracle");
const isSqlServerTriggerEditor = computed(() => structureDialect.value === "sqlserver");
@@ -5122,6 +5695,7 @@ function addForeignKey() {
refSchema: "",
refTable: "",
refColumn: "",
+ ...(isOracleForeignKeyEditor.value ? { columns: [""], refColumns: [""], oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } } : {}),
onUpdate: "",
onDelete: "",
markedForDrop: false,
@@ -5134,13 +5708,121 @@ function removeNewForeignKey(foreignKey: EditableStructureForeignKey) {
function toggleDropForeignKey(foreignKey: EditableStructureForeignKey) {
if (foreignKeysLoading.value || !foreignKey.original) return;
+ if (isOracleForeignKeyEditor.value && (!foreignKey.oracleOriginal || foreignKeyDefinitionBusy.value || saving.value)) return;
foreignKey.markedForDrop = !foreignKey.markedForDrop;
}
function canEditForeignKeyDraft(foreignKey: EditableStructureForeignKey): boolean {
+ if (isOracleForeignKeyEditor.value) return !foreignKeysLoading.value && !foreignKeyDefinitionBusy.value && !saving.value && !foreignKey.markedForDrop && (!foreignKey.original || !!foreignKey.oracleOriginal);
return !foreignKeysLoading.value && canEditForeignKeys.value && !foreignKey.markedForDrop;
}
+async function editOracleForeignKey(foreignKey: EditableStructureForeignKey) {
+ if (!isOracleForeignKeyEditor.value || foreignKeyDefinitionBusy.value || saving.value || foreignKeysLoading.value || !foreignKey.original) return;
+ const target = { ...primaryKeyTarget(), databaseType: databaseType.value === "oracle" ? ("oracle" as const) : ("oceanbase-oracle" as const) };
+ const identity = JSON.stringify(target);
+ foreignKeyDefinitionBusy.value = true;
+ try {
+ const definitions = await readOracleForeignKeyDefinitions(target);
+ if (primaryKeyUnmounted || identity !== JSON.stringify(primaryKeyTarget()) || !foreignKeys.value.includes(foreignKey)) return;
+ const definition = definitions.find((key) => key.name === foreignKey.original!.name);
+ if (!definition) throw new Error(t("oceanbasePrimaryKey.incompleteMetadata"));
+ foreignKey.name = definition.name;
+ foreignKey.columns = [...definition.columns];
+ foreignKey.refColumns = [...definition.refColumns];
+ foreignKey.column = definition.columns.join(", ");
+ foreignKey.refColumn = definition.refColumns.join(", ");
+ foreignKey.refSchema = definition.refSchema;
+ foreignKey.refTable = definition.refTable;
+ foreignKey.onDelete = definition.onDelete;
+ foreignKey.onUpdate = "";
+ foreignKey.oracleState = { ...definition.state };
+ foreignKey.oracleOriginal = cloneDraftValue(definition);
+ foreignKey.original = { ...foreignKey.original, name: definition.name, column: foreignKey.column, ref_column: foreignKey.refColumn, ref_schema: definition.refSchema, ref_table: definition.refTable, on_delete: definition.onDelete, on_update: "" };
+ void loadOracleForeignKeyReferenceColumns(foreignKey);
+ } catch (error) {
+ if (!primaryKeyUnmounted && identity === JSON.stringify(primaryKeyTarget()) && foreignKeys.value.includes(foreignKey)) errorMessage.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ foreignKeyDefinitionBusy.value = false;
+ }
+}
+
+function syncForeignKeyPairText(foreignKey: EditableStructureForeignKey) {
+ foreignKey.column = foreignKey.columns?.join(", ") ?? "";
+ foreignKey.refColumn = foreignKey.refColumns?.join(", ") ?? "";
+}
+
+function foreignKeyReferenceListId(foreignKey: EditableStructureForeignKey) {
+ return `${foreignKeyReferenceListPrefix}-${foreignKey.id.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
+}
+
+function setOracleForeignKeyPair(foreignKey: EditableStructureForeignKey, position: number, value: unknown, local: boolean) {
+ if (!canEditForeignKeyDraft(foreignKey)) return;
+ const list = local ? foreignKey.columns : foreignKey.refColumns;
+ if (!list || position < 0 || position >= list.length) return;
+ list[position] = String(value ?? "");
+ syncForeignKeyPairText(foreignKey);
+}
+
+function moveOracleForeignKeyPair(foreignKey: EditableStructureForeignKey, position: number, direction: number) {
+ if (!canEditForeignKeyDraft(foreignKey) || !foreignKey.columns || !foreignKey.refColumns || position + direction < 0 || position + direction >= foreignKey.columns.length) return;
+ for (const list of [foreignKey.columns, foreignKey.refColumns]) {
+ const [name] = list.splice(position, 1);
+ list.splice(position + direction, 0, name!);
+ }
+ syncForeignKeyPairText(foreignKey);
+}
+
+function addOracleForeignKeyPair(foreignKey: EditableStructureForeignKey) {
+ if (!canEditForeignKeyDraft(foreignKey)) return;
+ foreignKey.columns?.push("");
+ foreignKey.refColumns?.push("");
+ syncForeignKeyPairText(foreignKey);
+}
+
+function removeOracleForeignKeyPair(foreignKey: EditableStructureForeignKey, position: number) {
+ if (!canEditForeignKeyDraft(foreignKey)) return;
+ foreignKey.columns?.splice(position, 1);
+ foreignKey.refColumns?.splice(position, 1);
+ syncForeignKeyPairText(foreignKey);
+}
+
+function setOracleForeignKeyTarget(foreignKey: EditableStructureForeignKey, value: unknown, schema: boolean) {
+ if (!canEditForeignKeyDraft(foreignKey)) return;
+ const next = String(value ?? "");
+ if (next === (schema ? foreignKey.refSchema : foreignKey.refTable)) return;
+ if (schema) foreignKey.refSchema = next;
+ else foreignKey.refTable = next;
+ foreignKey.refColumns = foreignKey.columns?.map(() => "");
+ foreignKeyReferenceColumns.value[foreignKey.id] = [];
+ syncForeignKeyPairText(foreignKey);
+ void loadOracleForeignKeyReferenceColumns(foreignKey);
+}
+
+async function loadOracleForeignKeyReferenceColumns(foreignKey: EditableStructureForeignKey) {
+ const target = primaryKeyTarget();
+ const parent = { schema: foreignKey.refSchema, table: foreignKey.refTable };
+ if (!parent.schema || !parent.table) return;
+ const current = () => !primaryKeyUnmounted && JSON.stringify(target) === JSON.stringify(primaryKeyTarget()) && foreignKeys.value.includes(foreignKey) && foreignKey.refSchema === parent.schema && foreignKey.refTable === parent.table;
+ try {
+ const choices = await api.getColumns(target.connectionId, target.database, parent.schema, parent.table, target.catalog);
+ if (current()) foreignKeyReferenceColumns.value[foreignKey.id] = choices;
+ } catch {
+ // Parent columns can be invisible under column-level REFERENCES grants.
+ // Keep exact-name entry available; write preflight decides admissibility.
+ if (current()) foreignKeyReferenceColumns.value[foreignKey.id] = [];
+ }
+}
+
+function setOracleForeignKeyState(foreignKey: EditableStructureForeignKey, key: "enabled" | "validated" | "deferrable" | "initiallyDeferred" | "rely", value: boolean) {
+ if (!canEditForeignKeyDraft(foreignKey) || !foreignKey.oracleState) return;
+ if ((key === "deferrable" || key === "initiallyDeferred") && databaseType.value !== "oracle") return;
+ if (key === "initiallyDeferred" && value && !foreignKey.oracleState.deferrable) return;
+ foreignKey.oracleState[key] = value;
+ if (!foreignKey.oracleState.deferrable) foreignKey.oracleState.initiallyDeferred = false;
+ if (foreignKey.oracleState.validated) foreignKey.oracleState.rely = false;
+}
+
function addTrigger() {
if (!canEditTriggers.value || triggersLoading.value) return;
activeTab.value = "triggers";
@@ -5247,8 +5929,722 @@ function toggleSqlPreviewCollapsed() {
safeLocalStorageSet(STRUCTURE_SQL_PREVIEW_COLLAPSED_STORAGE_KEY, String(sqlPreviewCollapsed.value));
}
+async function applyExistingPrimaryKey(): Promise<boolean> {
+ if (primaryKeyBusy.value || !existingPrimaryKeyPlan.value) return false;
+ const plan = cloneDraftValue(existingPrimaryKeyPlan.value);
+ const plannedSession = existingPrimaryKeySession.value;
+ if (!plannedSession) return false;
+ const identity = JSON.stringify(plan.target);
+ const draft = JSON.stringify(plan.draft ?? plan.change);
+ const connectionAtStart = store.getConfig(plan.target.connectionId);
+ const sameTarget = () => !primaryKeyUnmounted && identity === JSON.stringify(primaryKeyTarget());
+ const connectionCurrent = () =>
+ store.connectionStateRevision(plan.target.connectionId) === plannedSession.revision &&
+ store.isCurrentConnectionStateRevision(plan.target.connectionId, plannedSession.revision) &&
+ (store.getConfig(plan.target.connectionId) ? connectionConfigFingerprint(store.getConfig(plan.target.connectionId)!) : "") === plannedSession.configFingerprint;
+ const canStart = () => sameTarget() && connectionCurrent() && draft === JSON.stringify(existingPrimaryKeyDraft.value) && !hasPendingStructureChanges(false) && !ddlDirty.value;
+ if (!canStart()) {
+ if (sameTarget() && !connectionCurrent()) {
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ pendingStatements.value = [];
+ warnings.value = [t("oceanbasePrimaryKey.refreshRequired")];
+ }
+ return false;
+ }
+ primaryKeyBusy.value = true;
+ saving.value = true;
+ const startedAt = Date.now();
+ try {
+ const protection = productionContextForDatabase(connectionAtStart, plan.target.database);
+ if (protection.active) {
+ const accepted = await productionSafetyStore.requestConfirmation({
+ sql: plan.statements.join("\n"),
+ connectionName: connectionAtStart?.name,
+ database: plan.target.database,
+ productionDatabases: protection.databases,
+ source: t("production.sourceStructure"),
+ scopeId: primaryKeyConfirmationScope,
+ });
+ if (!accepted || !canStart()) {
+ if (sameTarget() && !connectionCurrent()) {
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ pendingStatements.value = [];
+ warnings.value = [t("oceanbasePrimaryKey.refreshRequired")];
+ }
+ return false;
+ }
+ }
+ const timeout = queryTimeoutSecsForConnection(connectionAtStart, settingsStore.editorSettings.globalQueryTimeoutSecs);
+ const result = await executeOceanbasePrimaryKeyPlan(plan, timeout, { canStart, connectionCurrent });
+ if (!result) {
+ if (sameTarget() && !connectionCurrent()) {
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ pendingStatements.value = [];
+ warnings.value = [t("oceanbasePrimaryKey.refreshRequired")];
+ }
+ return false;
+ }
+ const completed = result.steps.every((step) => step.state === "committed");
+ let details = result.steps.map((step, index) => `${index + 1}. ${t(`oceanbasePrimaryKey.${step.state}`)}\n${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n\n");
+ if (result.indexStates?.length) details += `\n\n${result.indexStates.map((index) => `${index.name}: ${t(`oceanbasePrimaryKey.${index.state}`)}`).join("\n")}`;
+ for (const step of result.steps.filter((item) => item.state !== "notExecuted")) {
+ try {
+ await historyStore.add({
+ connection_id: plan.target.connectionId,
+ connection_name: connectionAtStart?.name || "",
+ database: plan.target.database,
+ sql: step.sql,
+ execution_time_ms: Date.now() - startedAt,
+ success: step.state === "committed",
+ error: step.state === "committed" ? undefined : `${t(`oceanbasePrimaryKey.${step.state}`)}: ${step.error || ""}`,
+ activity_kind: "schema_change",
+ operation: "ALTER TABLE",
+ target: plan.target.tableName,
+ });
+ } catch (error) {
+ console.warn("[DBX][structure-history:save-failed]", error);
+ }
+ }
+ if (connectionCurrent()) {
+ try {
+ invalidateTableMetadataCache(plan.target);
+ await invalidateObjectMetadataCache(plan.target);
+ await invalidateObjectDdl(plan.target);
+ } catch (error) {
+ result.readbackError = [result.readbackError, primaryKeyError(error)].filter(Boolean).join("\n");
+ }
+ }
+ if (sameTarget()) {
+ existingPrimaryKeyPlan.value = undefined;
+ existingPrimaryKeySession.value = undefined;
+ pendingStatements.value = [];
+ if (completed && !result.readbackError && connectionCurrent()) {
+ existingPrimaryKeyDraft.value = undefined;
+ loadedMetadataFacets.clear();
+ ddlFetched.value = false;
+ rawDdlContent.value = "";
+ const refresh = await loadStructure(true, { columns: true, indexes: true, constraints: true, foreignKeys: false, triggers: false, partitions: false, tableComment: false }, true, { forceMetadata: true, blockSecondaryMetadata: true });
+ if (refresh?.error) result.readbackError = refresh.error;
+ if (sameTarget()) {
+ const refreshErrors = [errorMessage.value, ...Object.values(secondaryMetadataErrors.value)].filter(Boolean);
+ if (refreshErrors.length) result.readbackError = refreshErrors.join("\n");
+ emit("saved", false);
+ }
+ } else {
+ warnings.value = [t("oceanbasePrimaryKey.refreshRequired")];
+ }
+ syncDraftToParent();
+ }
+ const succeeded = completed && !result.readbackError && connectionCurrent();
+ if (succeeded) {
+ toast(t("structureEditor.saved"), 2500);
+ if (!result.recoverySql) return true;
+ }
+ if (result.readbackError) details += `\n\n${t("oceanbasePrimaryKey.readbackFailed")}: ${result.readbackError === "definitionChanged" ? t("oceanbasePrimaryKey.definitionChanged") : result.readbackError}`;
+ if (result.recoverySql) details += `\n\n${t("oceanbasePrimaryKey.recoveryNotice")}\n${result.recoverySql}`;
+ primaryKeyResultTitle.value = "oceanbasePrimaryKey.resultTitle";
+ primaryKeyResultMessage.value = `${plan.target.schema}.${plan.target.tableName}: ${t(succeeded ? "structureEditor.saved" : "oceanbasePrimaryKey.executionFailed")}`;
+ primaryKeyResultDetails.value = details;
+ if (!primaryKeyUnmounted) primaryKeyResultOpen.value = true;
+ else toast(primaryKeyResultMessage.value, 10000);
+ return succeeded;
+ } catch (error) {
+ if (sameTarget()) errorMessage.value = primaryKeyError(error);
+ return false;
+ } finally {
+ primaryKeyBusy.value = false;
+ saving.value = false;
+ }
+}
+
+async function applyOracleForeignKeyPlan(): Promise<boolean> {
+ if (oracleForeignKeyBusy.value || !existingOracleForeignKeyPlan.value) return false;
+ const plan = cloneDraftValue(existingOracleForeignKeyPlan.value);
+ const plannedSession = existingOracleForeignKeySession.value;
+ if (!plannedSession) return false;
+ const identity = JSON.stringify(plan.target);
+ const changes = JSON.stringify(oracleForeignKeyChanges());
+ const connectionAtStart = store.getConfig(plan.target.connectionId);
+ const sameTarget = () => !primaryKeyUnmounted && identity === JSON.stringify(primaryKeyTarget());
+ const connectionCurrent = () =>
+ store.connectionStateRevision(plan.target.connectionId) === plannedSession.revision &&
+ store.isCurrentConnectionStateRevision(plan.target.connectionId, plannedSession.revision) &&
+ (store.getConfig(plan.target.connectionId) ? connectionConfigFingerprint(store.getConfig(plan.target.connectionId)!) : "") === plannedSession.configFingerprint;
+ const noOtherDrafts = () => {
+ const scope = captureStructureRefreshScope();
+ return !scope.columns && !scope.indexes && !scope.triggers && !scope.tableComment && !partitionOperations.value.length && !existingPrimaryKeyChanged.value && !ddlDirty.value;
+ };
+ const canStart = () => sameTarget() && changes === JSON.stringify(oracleForeignKeyChanges()) && noOtherDrafts();
+ const stillCurrent = () => canStart() && connectionCurrent();
+ if (!stillCurrent()) return false;
+ oracleForeignKeyBusy.value = true;
+ saving.value = true;
+ const startedAt = Date.now();
+ let refreshError = "";
+ try {
+ const protection = productionContextForDatabase(connectionAtStart, plan.target.database);
+ if (protection.active) {
+ const accepted = await productionSafetyStore.requestConfirmation({
+ sql: plan.statements.join("\n"),
+ connectionName: connectionAtStart?.name,
+ database: plan.target.database,
+ productionDatabases: protection.databases,
+ source: t("production.sourceStructure"),
+ scopeId: oracleForeignKeyConfirmationScope,
+ });
+ if (!accepted || !stillCurrent()) return false;
+ }
+ const timeout = queryTimeoutSecsForConnection(connectionAtStart, settingsStore.editorSettings.globalQueryTimeoutSecs);
+ const result = await executeOracleForeignKeyPlan(plan, timeout, { canStart, connectionCurrent });
+ if (!result) return false;
+ const completed = result.steps.every((step) => step.state === "committed");
+ let details = result.steps.map((step, index) => `${index + 1}. ${t(`oceanbasePrimaryKey.${step.state}`)}\n${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n\n");
+ if (result.recoverySql?.length) details += `\n\n${t("oracleForeignKey.recoveryNotice")}\n${result.recoverySql.join("\n")}`;
+ for (const step of result.steps.filter((item) => item.state !== "notExecuted")) {
+ try {
+ await historyStore.add({
+ connection_id: plan.target.connectionId,
+ connection_name: connectionAtStart?.name || "",
+ database: plan.target.database,
+ sql: step.sql,
+ execution_time_ms: Date.now() - startedAt,
+ success: step.state === "committed",
+ error: step.state === "committed" ? undefined : `${t(`oceanbasePrimaryKey.${step.state}`)}: ${step.error || ""}`,
+ activity_kind: "schema_change",
+ operation: "ALTER TABLE",
+ target: plan.target.tableName,
+ });
+ } catch (error) {
+ console.warn("[DBX][structure-history:save-failed]", error);
+ }
+ }
+ if (!sameTarget() || !connectionCurrent()) return false;
+ if (result.steps.some((step) => step.state !== "notExecuted")) {
+ try {
+ const affected = new Map([[JSON.stringify([plan.target.schema, plan.target.tableName]), { ...plan.target }]]);
+ for (const change of plan.changes) {
+ for (const definition of [change.original, change.target]) {
+ if (definition) affected.set(JSON.stringify([definition.refSchema, definition.refTable]), { ...plan.target, schema: definition.refSchema, tableName: definition.refTable });
+ }
+ }
+ for (const object of affected.values()) {
+ invalidateTableMetadataCache(object);
+ await invalidateObjectMetadataCache(object);
+ if (!sameTarget() || !connectionCurrent()) return false;
+ await invalidateObjectDdl(object);
+ if (!sameTarget() || !connectionCurrent()) return false;
+ }
+ } catch (error) {
+ refreshError = error instanceof Error ? error.message : String(error);
+ }
+ }
+ if (sameTarget() && connectionCurrent()) {
+ existingOracleForeignKeyPlan.value = undefined;
+ existingOracleForeignKeySession.value = undefined;
+ pendingStatements.value = [];
+ if (completed && !result.readbackError && !refreshError) {
+ oracleForeignKeyCreateRecovery.value = undefined;
+ loadedMetadataFacets.clear();
+ ddlFetched.value = false;
+ rawDdlContent.value = "";
+ const refresh = await loadStructure(true, { columns: false, indexes: false, constraints: false, foreignKeys: true, triggers: false, partitions: false, tableComment: false }, true, { forceMetadata: true, blockSecondaryMetadata: true });
+ if (!sameTarget() || !connectionCurrent()) return false;
+ if (refresh?.error) refreshError = refresh.error;
+ if (!refreshError && sameTarget()) emit("saved", false);
+ syncDraftToParent();
+ } else {
+ warnings.value = [t("oracleForeignKey.refreshRequired")];
+ }
+ syncDraftToParent();
+ }
+ if (!sameTarget() || !connectionCurrent()) return false;
+ const readbackError = [result.readbackError, refreshError].filter(Boolean).join("\n");
+ const succeeded = completed && !readbackError;
+ if (succeeded) toast(t("structureEditor.saved"), 2500);
+ if (readbackError) details += `\n\n${t("oracleForeignKey.readbackFailed")}: ${readbackError}`;
+ if (!succeeded || result.recoverySql?.length) {
+ primaryKeyResultTitle.value = "oracleForeignKey.resultTitle";
+ primaryKeyResultMessage.value = `${plan.target.schema}.${plan.target.tableName}: ${t(succeeded ? "structureEditor.saved" : "oracleForeignKey.executionFailed")}`;
+ primaryKeyResultDetails.value = details;
+ if (!primaryKeyUnmounted) primaryKeyResultOpen.value = true;
+ else toast(primaryKeyResultMessage.value, 10000);
+ }
+ return succeeded;
+ } catch (error) {
+ if (sameTarget() && connectionCurrent()) errorMessage.value = error instanceof Error ? error.message : String(error);
+ return false;
+ } finally {
+ oracleForeignKeyBusy.value = false;
+ saving.value = false;
+ }
+}
+
+async function applyOracleConstraintPlan(): Promise<boolean> {
+ if (oracleConstraintBusy.value || !oracleConstraintPlan.value || !oracleConstraintSession.value || !oracleConstraintDraft.value) return false;
+ const plan = cloneDraftValue(oracleConstraintPlan.value);
+ const session = oracleConstraintSession.value;
+ const draft = JSON.stringify(oracleConstraintDraft.value);
+ const connection = store.getConfig(plan.target.connectionId);
+ const sameTarget = () => !primaryKeyUnmounted && JSON.stringify(oracleConstraintTarget()) === JSON.stringify(plan.target);
+ const connectionCurrent = () =>
+ store.connectionStateRevision(plan.target.connectionId) === session.revision &&
+ store.isCurrentConnectionStateRevision(plan.target.connectionId, session.revision) &&
+ (store.getConfig(plan.target.connectionId) ? connectionConfigFingerprint(store.getConfig(plan.target.connectionId)!) : "") === session.configFingerprint;
+ const canStart = () => sameTarget() && draft === JSON.stringify(oracleConstraintDraft.value) && !hasPendingStructureChanges(false, false) && !ddlDirty.value;
+ const stillCurrent = () => canStart() && connectionCurrent();
+ if (!stillCurrent() || session.draftFingerprint !== draft) return false;
+ oracleConstraintBusy.value = true;
+ saving.value = true;
+ const startedAt = Date.now();
+ try {
+ const protection = productionContextForDatabase(connection, plan.target.database);
+ if (protection.active) {
+ const accepted = await productionSafetyStore.requestConfirmation({
+ sql: plan.statements.join("\n"),
+ connectionName: connection?.name,
+ database: plan.target.database,
+ productionDatabases: protection.databases,
+ source: t("production.sourceStructure"),
+ scopeId: oracleConstraintConfirmationScope,
+ });
+ if (!accepted || !stillCurrent()) return false;
+ }
+ const timeout = queryTimeoutSecsForConnection(connection, settingsStore.editorSettings.globalQueryTimeoutSecs);
+ const result = await executeOracleConstraintPlan(plan, timeout, { canStart, connectionCurrent });
+ if (!result) return false;
+ const completed = result.steps.length > 0 && result.steps.every((step) => step.state === "committed") && !result.readbackError;
+ for (const step of result.steps.filter((item) => item.state !== "notExecuted")) {
+ try {
+ await historyStore.add({
+ connection_id: plan.target.connectionId,
+ connection_name: connection?.name || "",
+ database: plan.target.database,
+ sql: step.sql,
+ execution_time_ms: Date.now() - startedAt,
+ success: step.state === "committed",
+ error: step.state === "committed" ? undefined : `${step.state}: ${step.error || ""}`,
+ activity_kind: "schema_change",
+ operation: "ALTER TABLE",
+ target: plan.target.tableName,
+ });
+ } catch (error) {
+ console.warn("[DBX][structure-history:save-failed]", error);
+ }
+ }
+ if (!sameTarget() || !connectionCurrent()) return false;
+ if (result.steps.some((step) => step.state !== "notExecuted")) {
+ invalidateTableMetadataCache(plan.target);
+ await invalidateObjectMetadataCache(plan.target);
+ if (!sameTarget() || !connectionCurrent()) return false;
+ await invalidateObjectDdl(plan.target);
+ if (!sameTarget() || !connectionCurrent()) return false;
+ loadedMetadataFacets.clear();
+ }
+ if (sameTarget() && connectionCurrent()) {
+ oracleConstraintPlan.value = undefined;
+ oracleConstraintSession.value = undefined;
+ pendingStatements.value = [];
+ if (completed) {
+ const refresh = await loadStructure(true, { columns: false, indexes: true, constraints: true, foreignKeys: false, triggers: false, partitions: false, tableComment: false }, true, { forceMetadata: true, blockSecondaryMetadata: true, preserveDraft: true });
+ if (!sameTarget() || !connectionCurrent()) return false;
+ if (refresh?.error) result.readbackError = refresh.error;
+ oracleConstraintDraft.value = undefined;
+ if (!result.readbackError) {
+ syncDraftToParent();
+ emit("saved", false);
+ toast(t("structureEditor.saved"), 2500);
+ }
+ }
+ }
+ if (!completed || result.readbackError) {
+ primaryKeyResultTitle.value = "oracleStructureResult.resultTitle";
+ primaryKeyResultMessage.value = `${plan.target.schema}.${plan.target.tableName}: ${result.readbackError || t("oracleStructureResult.executionFailed")}`;
+ primaryKeyResultDetails.value = result.steps.map((step, index) => `${index + 1}. ${step.state}\n${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n\n");
+ if (result.recoverySql) primaryKeyResultDetails.value += `\n\n${t("oracleStructureResult.recoveryNotice")}\n${result.recoverySql}`;
+ if (!primaryKeyUnmounted) primaryKeyResultOpen.value = true;
+ }
+ return completed && !result.readbackError;
+ } catch (error) {
+ if (sameTarget() && connectionCurrent()) errorMessage.value = error instanceof Error ? error.message : String(error);
+ return false;
+ } finally {
+ oracleConstraintBusy.value = false;
+ saving.value = false;
+ }
+}
+
+function oracleIndexOnlyChange(): boolean {
+ if (isCreateMode.value || ddlDirty.value || oracleConstraintChanged.value || existingPrimaryKeyChanged.value) return false;
+ const scope = captureStructureRefreshScope();
+ if (!scope.indexes || scope.columns || scope.foreignKeys || scope.triggers || scope.tableComment || partitionOperations.value.length) return false;
+ return pendingStatements.value.length > 0 && pendingStatements.value.every((sql) => /^\s*(?:CREATE\s+(?:UNIQUE\s+)?INDEX|DROP\s+INDEX)\b/i.test(sql));
+}
+
+async function applyOracleIndexPlan(): Promise<boolean> {
+ const target = oracleConstraintTarget();
+ const statements = [...pendingStatements.value];
+ const draftFingerprint = JSON.stringify(indexes.value);
+ const columnsFingerprint = JSON.stringify(columns.value);
+ const baseline = oracleIndexReady.value;
+ const connectionAtStart = store.getConfig(target.connectionId);
+ const revision = store.connectionStateRevision(target.connectionId);
+ const configFingerprint = connectionAtStart ? connectionConfigFingerprint(connectionAtStart) : "";
+ if (!baseline || baseline.epoch !== oracleIndexEpoch.value || baseline.targetIdentity !== oracleIndexTargetIdentity(target) || baseline.connectionRevision !== revision || baseline.configFingerprint !== configFingerprint || baseline.columnsFingerprint !== columnsFingerprint) {
+ errorMessage.value = "Index metadata is not ready for a safe save. Refresh the complete table structure and preview again.";
+ return false;
+ }
+ const saveSessionCurrent = () =>
+ !primaryKeyUnmounted &&
+ JSON.stringify(target) === JSON.stringify(oracleConstraintTarget()) &&
+ JSON.stringify(statements) === JSON.stringify(pendingStatements.value) &&
+ draftFingerprint === JSON.stringify(indexes.value) &&
+ columnsFingerprint === JSON.stringify(columns.value) &&
+ oracleIndexOnlyChange() &&
+ store.connectionStateRevision(target.connectionId) === revision &&
+ store.isCurrentConnectionStateRevision(target.connectionId, revision) &&
+ (store.getConfig(target.connectionId) ? connectionConfigFingerprint(store.getConfig(target.connectionId)!) : "") === configFingerprint;
+ const stillCurrent = () => saveSessionCurrent() && oracleIndexReady.value === baseline && oracleIndexEpoch.value === baseline.epoch;
+ if (oracleIndexBusy.value || !oracleIndexOnlyChange() || !stillCurrent()) return false;
+ oracleIndexBusy.value = true;
+ saving.value = true;
+ const startedAt = Date.now();
+ try {
+ const plan = await prepareOracleIndexPlan(target, statements, cloneDraftValue(indexes.value), {
+ baseline,
+ columnsFingerprint,
+ indexesFingerprint: baseline.indexesFingerprint,
+ });
+ if (!stillCurrent()) return false;
+ oracleIndexPlan.value = plan;
+ const protection = productionContextForDatabase(connectionAtStart, target.database);
+ if (protection.active) {
+ const accepted = await productionSafetyStore.requestConfirmation({
+ sql: statements.join("\n"),
+ connectionName: connectionAtStart?.name,
+ database: target.database,
+ productionDatabases: protection.databases,
+ source: t("production.sourceStructure"),
+ scopeId: oracleIndexConfirmationScope,
+ });
+ if (!accepted || !stillCurrent()) return false;
+ }
+ const timeout = queryTimeoutSecsForConnection(connectionAtStart, settingsStore.editorSettings.globalQueryTimeoutSecs);
+ const result = await executeOracleIndexPlan(plan, timeout, stillCurrent);
+ if (!result) return false;
+ const attemptedSteps = result.steps.some((step) => step.state !== "notExecuted");
+ if (attemptedSteps) invalidateOracleIndexReady();
+ for (const step of result.steps.filter((item) => item.state !== "notExecuted")) {
+ try {
+ await historyStore.add({
+ connection_id: target.connectionId,
+ connection_name: connectionAtStart?.name || "",
+ database: target.database,
+ sql: step.sql,
+ execution_time_ms: Date.now() - startedAt,
+ success: step.state === "committed",
+ error: step.state === "committed" ? undefined : `${step.state}: ${step.error || ""}`,
+ activity_kind: "schema_change",
+ operation: step.sql.startsWith("CREATE") ? "CREATE INDEX" : "DROP INDEX",
+ target: target.tableName,
+ });
+ } catch (error) {
+ console.warn("[DBX][structure-history:save-failed]", error);
+ }
+ }
+ if (result.steps.some((step) => step.state !== "notExecuted")) {
+ const completedCreates = plan.mutations.flatMap((mutation, index) => {
+ if (mutation.operation !== "CREATE" || result.steps[index]?.state !== "committed") return [];
+ const created = mutation.expectedAfter.find((item) => item.name === mutation.name);
+ return created ? [created] : [];
+ });
+ oracleIndexRefreshGuard.value = { target: oracleIndexTargetIdentity(target), afterRequestId: structureLoadRequestId, completedCreates };
+ invalidateTableMetadataCache(target);
+ await invalidateObjectMetadataCache(target);
+ await invalidateObjectDdl(target);
+ loadedMetadataFacets.clear();
+ }
+ const complete = result.steps.length > 0 && result.steps.every((step) => step.state === "committed") && !result.readbackError;
+ if (saveSessionCurrent()) {
+ // Never leave a DROP in the Apply queue after partial or unknown execution.
+ pendingStatements.value = [];
+ oracleIndexPlan.value = undefined;
+ if (complete) {
+ const columnsBeforeReadback = cloneDraftValue(columns.value);
+ const indexesBeforeReadback = cloneDraftValue(indexes.value);
+ const expectedReadbackRequestId = structureLoadRequestId + 1;
+ const refresh = await loadStructure(true, { columns: false, indexes: true, constraints: false, foreignKeys: false, triggers: false, partitions: false, tableComment: true }, true, { forceMetadata: true, blockSecondaryMetadata: true });
+ if (!refresh?.error && !oracleIndexReady.value && secondaryMetadataLoading.value) {
+ await new Promise<void>((resolve) => {
+ const stop = watch(secondaryMetadataLoading, (loading) => {
+ if (!loading) {
+ stop();
+ resolve();
+ }
+ });
+ if (!secondaryMetadataLoading.value) {
+ stop();
+ resolve();
+ }
+ });
+ }
+ const readback = oracleIndexReady.value;
+ const currentConfig = store.getConfig(target.connectionId);
+ const contextStillCurrent = !primaryKeyUnmounted && JSON.stringify(target) === JSON.stringify(oracleConstraintTarget()) && store.connectionStateRevision(target.connectionId) === revision && (currentConfig ? connectionConfigFingerprint(currentConfig) : "") === configFingerprint;
+ const readbackReady =
+ !!readback &&
+ contextStillCurrent &&
+ !refresh?.error &&
+ !secondaryMetadataErrors.value.indexes &&
+ !errorMessage.value &&
+ readback.requestId === structureLoadRequestId &&
+ readback.requestId >= expectedReadbackRequestId &&
+ readback.epoch === oracleIndexEpoch.value &&
+ readback.targetIdentity === oracleIndexTargetIdentity(target) &&
+ readback.connectionRevision === store.connectionStateRevision(target.connectionId) &&
+ readback.configFingerprint === (currentConfig ? connectionConfigFingerprint(currentConfig) : "");
+ if (readbackReady) {
+ emit("saved", false);
+ } else {
+ if (structureLoadRequestId === expectedReadbackRequestId && contextStillCurrent) {
+ columns.value = columnsBeforeReadback;
+ indexes.value = indexesBeforeReadback;
+ }
+ result.readbackError = refresh?.error || secondaryMetadataErrors.value.indexes || errorMessage.value || "Index refresh did not publish a current complete baseline after DDL.";
+ }
+ }
+ }
+ if ((!complete || result.readbackError) && !primaryKeyUnmounted) {
+ primaryKeyResultTitle.value = "oracleStructureResult.resultTitle";
+ primaryKeyResultMessage.value = `${target.schema}.${target.tableName}: ${t("oracleStructureResult.executionFailed")}`;
+ primaryKeyResultDetails.value = result.steps.map((step, index) => `${index + 1}. ${step.state}\n${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n\n");
+ if (result.readbackError) primaryKeyResultDetails.value += `\n\n${t("oracleStructureResult.readbackFailed")}: ${result.readbackError}`;
+ if (!primaryKeyUnmounted) primaryKeyResultOpen.value = true;
+ }
+ return complete && !result.readbackError;
+ } catch (error) {
+ if (saveSessionCurrent()) {
+ pendingStatements.value = [];
+ oracleIndexPlan.value = undefined;
+ errorMessage.value = error instanceof Error ? error.message : String(error);
+ }
+ return false;
+ } finally {
+ oracleIndexBusy.value = false;
+ saving.value = false;
+ }
+}
+
+async function applyOracleForeignKeyCreatePlan(): Promise<boolean> {
+ if (oracleForeignKeyBusy.value || !newOracleForeignKeyPlan.value || !newOracleForeignKeySession.value) return false;
+ const plan = cloneDraftValue(newOracleForeignKeyPlan.value);
+ const plannedSession = newOracleForeignKeySession.value;
+ const identity = JSON.stringify(plan.target);
+ const changes = JSON.stringify(oracleForeignKeyChanges());
+ const connectionAtStart = store.getConfig(plan.target.connectionId);
+ const sameTarget = () => !primaryKeyUnmounted && identity === JSON.stringify({ ...primaryKeyTarget(), schema: metadataSchema.value, tableName: newTableName.value.trim(), databaseType: plan.target.databaseType });
+ const connectionCurrent = () =>
+ store.connectionStateRevision(plan.target.connectionId) === plannedSession.revision &&
+ store.isCurrentConnectionStateRevision(plan.target.connectionId, plannedSession.revision) &&
+ (store.getConfig(plan.target.connectionId) ? connectionConfigFingerprint(store.getConfig(plan.target.connectionId)!) : "") === plannedSession.configFingerprint;
+ const currentOptions = () => ({ ...structureChangeOptions(), schema: metadataSchema.value, tableName: newTableName.value.trim(), foreignKeys: [], oracleForeignKeyChanges: oracleForeignKeyChanges() });
+ const currentPartitioning = () => (createPartitioningEnabled.value ? { kind: createPartitioningKind.value, columns: createPartitioningColumns.value, expression: createPartitioningExpression.value } : undefined);
+ const canStart = () => sameTarget() && changes === JSON.stringify(oracleForeignKeyChanges()) && JSON.stringify({ options: currentOptions(), changes: oracleForeignKeyChanges(), partitioning: currentPartitioning() }) === plannedSession.draftFingerprint && isCreateMode.value;
+ const stillCurrent = () => canStart() && connectionCurrent();
+ if (!stillCurrent()) return false;
+ oracleForeignKeyBusy.value = true;
+ saving.value = true;
+ const startedAt = Date.now();
+ try {
+ const protection = productionContextForDatabase(connectionAtStart, plan.target.database);
+ if (protection.active) {
+ const accepted = await productionSafetyStore.requestConfirmation({
+ sql: plan.statements.join("\n"),
+ connectionName: connectionAtStart?.name,
+ database: plan.target.database,
+ productionDatabases: protection.databases,
+ source: t("production.sourceStructure"),
+ scopeId: oracleForeignKeyConfirmationScope,
+ });
+ if (!accepted || !stillCurrent()) return false;
+ }
+ const timeout = queryTimeoutSecsForConnection(connectionAtStart, settingsStore.editorSettings.globalQueryTimeoutSecs);
+ const result = await executeOracleForeignKeyCreatePlan(plan, timeout, { canStart, connectionCurrent });
+ if (!result) return false;
+ for (const step of result.steps.filter((item) => item.state !== "notExecuted")) {
+ try {
+ await historyStore.add({
+ connection_id: plan.target.connectionId,
+ connection_name: connectionAtStart?.name || "",
+ database: plan.target.database,
+ sql: step.sql,
+ execution_time_ms: Date.now() - startedAt,
+ success: step.state === "committed",
+ error: step.state === "committed" ? undefined : `${t(`oceanbasePrimaryKey.${step.state}`)}: ${step.error || ""}`,
+ activity_kind: "schema_change",
+ operation: step.sql.startsWith("CREATE ") ? "CREATE TABLE" : "ALTER TABLE",
+ target: plan.target.tableName,
+ });
+ } catch (error) {
+ console.warn("[DBX][structure-history:save-failed]", error);
+ }
+ }
+ if (!connectionCurrent()) return false;
+ const created = result.steps[0]?.state === "committed" || result.tableExists === true;
+ const issues = [
+ ...result.steps.filter((step) => step.state === "rejected" || step.state === "unknown").map((step) => `${step.state}: ${step.error || step.sql}`),
+ ...(result.readbackError ? [result.readbackError] : []),
+ ...(result.steps.some((step) => step.state === "notExecuted") ? [t("oracleForeignKey.executionFailed")] : []),
+ ];
+ if (created) {
+ const stepDetails = result.steps.map((step, index) => `${index + 1}. ${t(`oceanbasePrimaryKey.${step.state}`)}: ${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n");
+ const details = [
+ t("oracleForeignKey.createdTablePartial"),
+ `${plan.target.schema}.${foldCreatedTableName(plan.target.tableName, plan.target.databaseType)}`,
+ stepDetails,
+ ...(result.readbackError ? [`${t("oracleForeignKey.readbackFailed")}: ${result.readbackError}`] : []),
+ ...(issues.length ? [t("oracleForeignKey.createRecoveryNotice")] : []),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+ const createdName = foldCreatedTableName(plan.target.tableName, plan.target.databaseType);
+ for (const object of [{ ...plan.target, tableName: createdName }, ...plan.changes.map((change) => ({ ...plan.target, schema: change.target!.refSchema, tableName: change.target!.refTable }))]) {
+ invalidateTableMetadataCache(object);
+ await invalidateObjectMetadataCache(object);
+ await invalidateObjectDdl(object);
+ }
+ if (!sameTarget()) {
+ toast(`${t("oracleForeignKey.executionFailed")}\n${details}`, 10000);
+ return false;
+ }
+ if (!connectionCurrent()) return false;
+ newOracleForeignKeyPlan.value = undefined;
+ newOracleForeignKeySession.value = undefined;
+ pendingStatements.value = [];
+ warnings.value = [];
+ const fkSteps = result.steps.filter((step) => step.sql.includes("FOREIGN KEY"));
+ const sameDefinition = (actual: NonNullable<(typeof plan.changes)[number]["target"]>, expected: NonNullable<(typeof plan.changes)[number]["target"]>) => {
+ const fold = (name: string) => (plan.target.databaseType === "oracle" ? foldCreatedTableName(name, plan.target.databaseType) : name);
+ const selfReference = fold(expected.refSchema) === fold(plan.target.schema) && fold(expected.refTable) === fold(plan.target.tableName);
+ return (
+ JSON.stringify(actual) ===
+ JSON.stringify({
+ ...expected,
+ name: fold(expected.name),
+ columns: expected.columns.map(fold),
+ ...(selfReference ? { refSchema: fold(expected.refSchema), refTable: fold(expected.refTable), refColumns: expected.refColumns.map(fold) } : {}),
+ })
+ );
+ };
+ const remaining = plan.changes.flatMap((change, index) => {
+ const step = fkSteps[index];
+ const target = change.target!;
+ const exists = result.readbackDefinitions?.some((definition) => sameDefinition(definition, target));
+ if (exists || (step?.state !== "rejected" && step?.state !== "notExecuted")) return [];
+ const fold = (name: string) => foldCreatedTableName(name, plan.target.databaseType);
+ const selfReference = fold(target.refSchema) === fold(plan.target.schema) && fold(target.refTable) === fold(plan.target.tableName);
+ return [
+ {
+ ...target,
+ name: fold(target.name),
+ columns: target.columns.map(fold),
+ ...(selfReference ? { refSchema: fold(target.refSchema), refTable: fold(target.refTable), refColumns: target.refColumns.map(fold) } : {}),
+ },
+ ];
+ });
+ const uncertainSteps = result.steps.filter((step) => step.state === "unknown").map((step) => (step.sql.startsWith("CREATE TABLE") ? "CREATE" : step.sql));
+ if (issues.length) {
+ const recovery = { tableName: createdName, tableExists: true, details, remaining, uncertainSteps };
+ oracleForeignKeyCreateRecovery.value = recovery;
+ const recoveryDraft = {
+ ...createCurrentDraft(),
+ dirty: remaining.length > 0,
+ activeTab: "foreignKeys" as TableStructureEditorDraft["activeTab"],
+ newTableName: "",
+ tableComment: tableComment.value,
+ originalTableComment: tableComment.value,
+ columns: [],
+ indexes: [],
+ foreignKeys: [],
+ constraints: [],
+ constraintsLoaded: false,
+ triggers: [],
+ triggersLoaded: false,
+ partitionOperations: [],
+ createPartitioningEnabled: false,
+ createPartitioningColumns: [],
+ createPartitioningExpression: "",
+ loadedMetadataFacets: [],
+ existingPrimaryKey: undefined,
+ oracleConstraintChange: undefined,
+ oracleForeignKeyCreateRecovery: recovery,
+ ddlDraft: null,
+ } satisfies TableStructureEditorDraft;
+ emitDraftToParent(recoveryDraft);
+ emit("saved", false, createdName);
+ primaryKeyResultDetails.value = details;
+ primaryKeyResultTitle.value = "oracleForeignKey.resultTitle";
+ primaryKeyResultMessage.value = `${plan.target.schema}.${createdName}: ${t("oracleForeignKey.createdTablePartial")}`;
+ if (!primaryKeyUnmounted) primaryKeyResultOpen.value = true;
+ else toast(`${primaryKeyResultMessage.value}\n${details}`, 10000);
+ return false;
+ }
+ primaryKeyResultDetails.value = details;
+ oracleForeignKeyCreateRecovery.value = undefined;
+ clearDraft();
+ emit("saved", tableComment.value !== originalTableComment.value, createdName);
+ toast(t("structureEditor.created"), 2500);
+ return issues.length === 0;
+ }
+ if (sameTarget() && connectionCurrent()) {
+ errorMessage.value = issues.join("\n") || t("oracleForeignKey.executionFailed");
+ newOracleForeignKeyPlan.value = undefined;
+ newOracleForeignKeySession.value = undefined;
+ pendingStatements.value = [];
+ if (result.steps[0]?.state === "unknown") {
+ const recovery = {
+ tableName: foldCreatedTableName(plan.target.tableName, plan.target.databaseType),
+ tableExists: false,
+ details: [...issues, ...result.steps.map((step) => `${step.state}: ${step.sql}${step.error ? `\n${step.error}` : ""}`)].join("\n\n"),
+ remaining: [],
+ uncertainSteps: ["CREATE"],
+ };
+ oracleForeignKeyCreateRecovery.value = recovery;
+ emitDraftToParent({ ...createCurrentDraft(), oracleForeignKeyCreateRecovery: recovery });
+ primaryKeyResultTitle.value = "oracleForeignKey.resultTitle";
+ primaryKeyResultMessage.value = `${plan.target.schema}.${recovery.tableName}: ${t("oracleForeignKey.readbackFailed")}`;
+ primaryKeyResultDetails.value = recovery.details;
+ primaryKeyResultOpen.value = true;
+ }
+ }
+ return false;
+ } catch (error) {
+ if (sameTarget() && connectionCurrent()) errorMessage.value = error instanceof Error ? error.message : String(error);
+ return false;
+ } finally {
+ oracleForeignKeyBusy.value = false;
+ saving.value = false;
+ }
+}
+
async function applyChanges() {
if (!canApply.value || !props.connectionId || !props.database) return false;
+ if (oracleIndexRefreshGuard.value?.target === oracleIndexTargetIdentity(oracleConstraintTarget())) {
+ errorMessage.value = "Index execution may have changed the database. Refresh index metadata before applying again.";
+ return false;
+ }
+ const oracleIndexMutation = !isCreateMode.value && (databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle") && indexes.value.some(indexChanged);
+ if (oracleIndexMutation && !oracleIndexOnlyChange()) {
+ errorMessage.value = t("oracleIndex.mixedDraft");
+ return false;
+ }
+ if (existingPrimaryKeyChanged.value) return applyExistingPrimaryKey();
+ if (oracleConstraintPlan.value) return applyOracleConstraintPlan();
+ if (oracleIndexMutation) return applyOracleIndexPlan();
+ if (newOracleForeignKeyPlan.value) return applyOracleForeignKeyCreatePlan();
+ if (existingOracleForeignKeyPlan.value) return applyOracleForeignKeyPlan();
// Layer B runtime guard: a stale `concurrently: true` whose availability is
// no longer enabled must never be executed — reject the save with an
// explicit error even if normalization was skipped (race / non-UI caller).
@@ -5778,6 +7174,8 @@ watch(
mysqlTableDefaultCollation,
tableOwner,
ddlDraft,
+ existingPrimaryKeyDraft,
+ oracleConstraintDraft,
columns,
indexes,
foreignKeys,
@@ -5903,6 +7301,15 @@ watch(
<template>
<div ref="rootRef" class="flex h-full min-h-0 flex-col gap-2 overflow-hidden p-[var(--structure-shell-padding)] text-[length:var(--structure-font-size)]" :data-structure-density="localStructureDensity" :style="structureDensityStyle">
+ <DangerConfirmDialog v-model:open="primaryKeyResultOpen" :title="t(primaryKeyResultTitle)" :message="primaryKeyResultMessage" :confirm-label="t('common.close')">
+ <template #options>
+ <details class="rounded border p-2 text-xs">
+ <summary class="cursor-pointer">{{ t("oceanbasePrimaryKey.details") }}</summary>
+ <Button variant="ghost" size="sm" @click="copyColumnNamesText(primaryKeyResultDetails)">{{ t("dangerDialog.copyFullText") }}</Button>
+ <pre data-native-clipboard class="max-h-72 overflow-auto whitespace-pre-wrap break-all">{{ primaryKeyResultDetails }}</pre>
+ </details>
+ </template>
+ </DangerConfirmDialog>
<StarRocksLayoutCopyDialog
v-if="!isCreateMode && databaseType === 'starrocks' && props.tableName"
v-model:open="starrocksLayoutCopyOpen"
@@ -5948,7 +7355,7 @@ watch(
<div class="flex shrink-0 items-center gap-2">
<label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.comment") }}</label>
- <Input v-model="tableComment" :placeholder="t('structureEditor.tableCommentPlaceholder')" :class="[structureControlClass, 'max-w-[320px]']" :disabled="isTableCommentDisabled" />
+ <Input v-model="tableComment" :placeholder="t('structureEditor.tableCommentPlaceholder')" :class="[structureControlClass, 'max-w-[320px]']" :disabled="isTableCommentDisabled" data-table-comment-input />
<Tooltip v-if="isTableCommentDisabled">
<TooltipTrigger as-child>
<Info :class="[structureIconClass, 'shrink-0 text-muted-foreground']" />
@@ -6161,6 +7568,10 @@ watch(
<Plus :class="structureIconClass" />
{{ t("structureEditor.addForeignKey") }}
</Button>
+ <template v-if="activeTab === 'constraints' && isOracleConstraintEditor">
+ <Button size="sm" :class="structureToolbarButtonClass" :disabled="saving || oracleConstraintBusy || !!oracleConstraintDraft" @click="addOracleConstraint('check')"><Plus :class="structureIconClass" />{{ t("structureEditor.addCheckConstraint") }}</Button>
+ <Button size="sm" :class="structureToolbarButtonClass" :disabled="saving || oracleConstraintBusy || !!oracleConstraintDraft" @click="addOracleConstraint('unique')"><Plus :class="structureIconClass" />{{ t("structureEditor.addUniqueConstraint") }}</Button>
+ </template>
<Button v-if="activeTab === 'triggers'" size="sm" :class="structureToolbarButtonClass" :disabled="!canEditTriggers || triggersLoading" @click="addTrigger">
<Plus :class="structureIconClass" />
{{ t("structureEditor.addTrigger") }}
@@ -6771,6 +8182,16 @@ watch(
data-index-name-input
@update:model-value="(value: string | number) => onIndexNameInput(index, value)"
/>
+ <Button
+ v-if="canOpenPairedOracleConstraint(index)"
+ variant="ghost"
+ size="icon"
+ :disabled="saving || oracleConstraintBusy || !!oracleConstraintDraft"
+ :aria-label="`Edit unique constraint ${index.name}`"
+ :data-paired-unique-constraint="index.name"
+ @click="editOracleUniqueConstraintForIndex(index)"
+ >{{ t("common.edit") }}</Button
+ >
<LightTooltip v-if="!index.isPrimary" :text="t('structureEditor.regenerateIndexName')" side="top" nowrap>
<Button
type="button"
@@ -6895,12 +8316,15 @@ watch(
<div v-for="fk in foreignKeys" :key="fk.id" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]" :class="fk.markedForDrop ? 'bg-destructive/5 opacity-60' : ''">
<div class="grid grid-cols-[minmax(110px,1fr)_minmax(110px,1fr)_minmax(110px,1fr)_minmax(90px,0.8fr)_minmax(90px,0.8fr)_auto] gap-1.5">
<Input v-model="fk.name" :class="structureControlClass" :placeholder="t('structureEditor.foreignKeyName')" :disabled="!canEditForeignKeyDraft(fk)" />
- <Input v-model="fk.column" :class="structureControlClass" :placeholder="t('structureEditor.columnName')" :disabled="!canEditForeignKeyDraft(fk)" />
- <Input v-model="fk.refTable" :class="structureControlClass" :placeholder="t('structureEditor.referencedTable')" :disabled="!canEditForeignKeyDraft(fk)" />
- <Input v-model="fk.refColumn" :class="structureControlClass" :placeholder="t('structureEditor.referencedColumn')" :disabled="!canEditForeignKeyDraft(fk)" />
- <Input v-model="fk.refSchema" :class="structureControlClass" :placeholder="t('structureEditor.referencedSchema')" :disabled="!canEditForeignKeyDraft(fk)" />
+ <Input v-if="!isOracleForeignKeyEditor" v-model="fk.column" :class="structureControlClass" :placeholder="t('structureEditor.columnName')" :disabled="!canEditForeignKeyDraft(fk)" />
+ <Input v-if="!isOracleForeignKeyEditor" v-model="fk.refTable" :class="structureControlClass" :placeholder="t('structureEditor.referencedTable')" :disabled="!canEditForeignKeyDraft(fk)" />
+ <Input v-else :model-value="fk.refTable" :class="structureControlClass" :placeholder="t('structureEditor.referencedTable')" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(value) => setOracleForeignKeyTarget(fk, value, false)" />
+ <Input v-if="!isOracleForeignKeyEditor" v-model="fk.refColumn" :class="structureControlClass" :placeholder="t('structureEditor.referencedColumn')" :disabled="!canEditForeignKeyDraft(fk)" />
+ <Input v-if="!isOracleForeignKeyEditor" v-model="fk.refSchema" :class="structureControlClass" :placeholder="t('structureEditor.referencedSchema')" :disabled="!canEditForeignKeyDraft(fk)" />
+ <Input v-else :model-value="fk.refSchema" :class="structureControlClass" :placeholder="t('structureEditor.referencedSchema')" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(value) => setOracleForeignKeyTarget(fk, value, true)" />
<div class="flex items-center justify-end gap-1">
- <Button v-if="fk.original" variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="toggleDropForeignKey(fk)">
+ <Button v-if="isOracleForeignKeyEditor && fk.original && !fk.oracleOriginal" data-oracle-foreign-key-edit variant="ghost" size="sm" :disabled="foreignKeyDefinitionBusy || foreignKeysLoading || saving" @click="editOracleForeignKey(fk)">{{ t("common.edit") }}</Button>
+ <Button v-if="fk.original" variant="ghost" size="sm" :class="structureToolbarButtonClass" :disabled="isOracleForeignKeyEditor && (!fk.oracleOriginal || foreignKeyDefinitionBusy || saving)" @click="toggleDropForeignKey(fk)">
<Trash2 :class="structureIconClass" />
{{ fk.markedForDrop ? t("structureEditor.restore") : t("structureEditor.drop") }}
</Button>
@@ -6910,16 +8334,83 @@ watch(
</Button>
</div>
</div>
+ <div v-if="isOracleForeignKeyEditor" class="mt-1.5 space-y-1">
+ <div v-for="(column, position) in fk.columns" :key="position" data-oracle-foreign-key-pair class="flex items-center gap-1">
+ <Select :model-value="column || undefined" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(value) => setOracleForeignKeyPair(fk, position, value, true)">
+ <SelectTrigger class="min-w-0 flex-1"><SelectValue :placeholder="t('structureEditor.columnName')" /></SelectTrigger>
+ <SelectContent
+ ><SelectItem v-for="source in columns.filter((item) => !item.markedForDrop)" :key="source.id" :value="source.name">{{ source.name }}</SelectItem></SelectContent
+ >
+ </Select>
+ <Input
+ :model-value="fk.refColumns?.[position] ?? ''"
+ :list="foreignKeyReferenceListId(fk)"
+ data-oracle-foreign-key-reference
+ :placeholder="t('structureEditor.referencedColumn')"
+ :disabled="!canEditForeignKeyDraft(fk)"
+ @update:model-value="(value) => setOracleForeignKeyPair(fk, position, value, false)"
+ />
+ <Button variant="ghost" size="icon-xs" data-oracle-foreign-key-up :title="t('oceanbasePrimaryKey.moveUp')" :disabled="!canEditForeignKeyDraft(fk) || position === 0" @click="moveOracleForeignKeyPair(fk, position, -1)"><ChevronUp class="h-4 w-4" /></Button>
+ <Button variant="ghost" size="icon-xs" data-oracle-foreign-key-down :title="t('oceanbasePrimaryKey.moveDown')" :disabled="!canEditForeignKeyDraft(fk) || position === (fk.columns?.length ?? 0) - 1" @click="moveOracleForeignKeyPair(fk, position, 1)"
+ ><ChevronDown class="h-4 w-4"
+ /></Button>
+ <Button variant="ghost" size="icon-xs" :title="t('common.delete')" :disabled="!canEditForeignKeyDraft(fk)" @click="removeOracleForeignKeyPair(fk, position)"><X class="h-4 w-4" /></Button>
+ </div>
+ <Button variant="outline" size="sm" :disabled="!canEditForeignKeyDraft(fk)" @click="addOracleForeignKeyPair(fk)">{{ t("structureEditor.addColumn") }}</Button>
+ <datalist :id="foreignKeyReferenceListId(fk)"><option v-for="choice in foreignKeyReferenceColumns[fk.id] ?? []" :key="choice.name" :value="choice.name" /></datalist>
+ <div v-if="fk.oracleState" class="flex flex-wrap gap-3" data-oracle-foreign-key-state>
+ <label class="flex items-center gap-1"
+ ><input type="checkbox" data-oracle-foreign-key-enabled :class="structureCheckboxClass" :checked="fk.oracleState.enabled" :disabled="!canEditForeignKeyDraft(fk)" @change="setOracleForeignKeyState(fk, 'enabled', ($event.target as HTMLInputElement).checked)" />{{
+ t("grid.tableInfoConstraintEnabled")
+ }}</label
+ >
+ <label class="flex items-center gap-1"
+ ><input type="checkbox" data-oracle-foreign-key-validated :class="structureCheckboxClass" :checked="fk.oracleState.validated" :disabled="!canEditForeignKeyDraft(fk)" @change="setOracleForeignKeyState(fk, 'validated', ($event.target as HTMLInputElement).checked)" />{{
+ t("grid.tableInfoConstraintValidated")
+ }}</label
+ >
+ <label class="flex items-center gap-1"
+ ><input
+ type="checkbox"
+ data-oracle-foreign-key-deferrable
+ :class="structureCheckboxClass"
+ :checked="fk.oracleState.deferrable"
+ :disabled="!canEditForeignKeyDraft(fk) || databaseType !== 'oracle'"
+ @change="setOracleForeignKeyState(fk, 'deferrable', ($event.target as HTMLInputElement).checked)"
+ />DEFERRABLE</label
+ >
+ <label class="flex items-center gap-1"
+ ><input
+ type="checkbox"
+ data-oracle-foreign-key-deferred
+ :class="structureCheckboxClass"
+ :checked="fk.oracleState.initiallyDeferred"
+ :disabled="!canEditForeignKeyDraft(fk) || databaseType !== 'oracle' || !fk.oracleState.deferrable"
+ @change="setOracleForeignKeyState(fk, 'initiallyDeferred', ($event.target as HTMLInputElement).checked)"
+ />INITIALLY DEFERRED</label
+ >
+ <label class="flex items-center gap-1"
+ ><input
+ type="checkbox"
+ data-oracle-foreign-key-rely
+ :class="structureCheckboxClass"
+ :checked="fk.oracleState.rely"
+ :disabled="!canEditForeignKeyDraft(fk) || fk.oracleState.validated"
+ @change="setOracleForeignKeyState(fk, 'rely', ($event.target as HTMLInputElement).checked)"
+ />RELY</label
+ >
+ </div>
+ </div>
<div class="mt-1.5 grid grid-cols-[minmax(110px,0.5fr)_minmax(110px,0.5fr)_1fr] gap-1.5">
<Select :model-value="fk.onDelete || '__default'" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(v: any) => (fk.onDelete = String(v === '__default' ? '' : (v ?? '')))">
<SelectTrigger class="h-[var(--structure-control-height)] rounded-[6px] px-[var(--structure-control-px)] text-[length:var(--structure-font-size)] focus-visible:border-ring/50 focus-visible:ring-1 focus-visible:ring-ring/25">
<SelectValue :placeholder="t('structureEditor.onDelete')" />
</SelectTrigger>
<SelectContent>
- <SelectItem v-for="action in foreignKeyActionOptions" :key="`delete-${action || 'default'}`" :value="action || '__default'">{{ action || t("structureEditor.defaultAction") }}</SelectItem>
+ <SelectItem v-for="action in isOracleForeignKeyEditor ? ['', 'CASCADE', 'SET NULL', 'NO ACTION'] : foreignKeyActionOptions" :key="`delete-${action || 'default'}`" :value="action || '__default'">{{ action || t("structureEditor.defaultAction") }}</SelectItem>
</SelectContent>
</Select>
- <Select :model-value="fk.onUpdate || '__default'" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(v: any) => (fk.onUpdate = String(v === '__default' ? '' : (v ?? '')))">
+ <Select v-if="!isOracleForeignKeyEditor" :model-value="fk.onUpdate || '__default'" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(v: any) => (fk.onUpdate = String(v === '__default' ? '' : (v ?? '')))">
<SelectTrigger class="h-[var(--structure-control-height)] rounded-[6px] px-[var(--structure-control-px)] text-[length:var(--structure-font-size)] focus-visible:border-ring/50 focus-visible:ring-1 focus-visible:ring-ring/25">
<SelectValue :placeholder="t('structureEditor.onUpdate')" />
</SelectTrigger>
@@ -6951,18 +8442,159 @@ watch(
{{ t("structureEditor.emptyReadonly") }}
</div>
<div v-else class="space-y-1.5">
- <div v-for="constraint in constraintsForTab" :key="constraint.name" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]" :class="constraint.enabled === false ? 'opacity-60' : ''">
+ <div
+ v-for="constraint in constraintsForTab"
+ :key="constraint.name"
+ class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]"
+ :class="constraint.enabled === false && existingPrimaryKeyDraft?.name !== constraint.name ? 'opacity-60' : ''"
+ >
<div class="flex flex-wrap items-center gap-1.5">
<span class="font-mono font-medium">{{ constraint.name }}</span>
<Badge variant="outline" class="shrink-0">{{ constraint.constraint_type }}</Badge>
<Badge variant="outline" class="shrink-0 text-muted-foreground">{{ t(constraint.enabled === true ? "grid.tableInfoConstraintEnabled" : constraint.enabled === false ? "structureEditor.constraintDisabled" : "grid.tableInfoConstraintEnabledUnknown") }}</Badge>
<Badge variant="outline" class="shrink-0 text-muted-foreground">{{ t(constraint.valid === true ? "grid.tableInfoConstraintValidated" : constraint.valid === false ? "structureEditor.constraintNotValidated" : "grid.tableInfoConstraintValidationUnknown") }}</Badge>
+ <template v-if="canEditExistingPrimaryKey && constraint.constraint_type === 'PRIMARY KEY'">
+ <Button variant="ghost" size="sm" :disabled="loading || saving || primaryKeyBusy" @click="editExistingPrimaryKey(constraint)">{{ t("common.edit") }}</Button>
+ <Button variant="ghost" size="sm" :disabled="loading || saving || primaryKeyBusy" @click="editExistingPrimaryKey(constraint, true)">{{ t("common.delete") }}</Button>
+ </template>
+ <template v-if="isOracleConstraintEditor && ['CHECK', 'UNIQUE'].includes(constraint.constraint_type)">
+ <Button variant="ghost" size="sm" :disabled="loading || saving || oracleConstraintBusy || !!oracleConstraintDraft" :aria-label="`Edit constraint ${constraint.name}`" :data-constraint-edit="constraint.name" @click="editOracleConstraint(constraint)">{{ t("common.edit") }}</Button>
+ <Button variant="ghost" size="sm" :disabled="loading || saving || oracleConstraintBusy || !!oracleConstraintDraft" :aria-label="`Delete constraint ${constraint.name}`" :data-constraint-delete="constraint.name" @click="deleteOracleConstraint(constraint)">{{
+ t("common.delete")
+ }}</Button>
+ </template>
+ </div>
+ <div v-if="oracleConstraintDraft?.original?.definition.name === constraint.name" class="mt-2 space-y-2" data-oracle-constraint-editor :data-constraint-editor="constraint.name">
+ <template v-if="oracleConstraintDraft.target?.kind === 'check'">
+ <Input v-model="oracleConstraintDraft.target.definition.name" :placeholder="t('structureEditor.constraintName')" :disabled="oracleConstraintBusy" />
+ <textarea v-model="oracleConstraintDraft.target.definition.expression" :placeholder="t('structureEditor.checkExpression')" :disabled="oracleConstraintBusy" class="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-sm" />
+ <div class="flex flex-wrap gap-3 text-sm">
+ <label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.enabled" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintEnabled") }}</label
+ ><label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.validated" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintValidated") }}</label>
+ </div>
+ </template>
+ <template v-else-if="oracleConstraintDraft.target?.kind === 'unique'">
+ <Input v-model="oracleConstraintDraft.target.definition.name" :placeholder="t('structureEditor.constraintName')" :disabled="oracleConstraintBusy" />
+ <div v-if="databaseType === 'oracle'" class="space-y-1 rounded border p-2" data-oracle-unique-index-policy>
+ <span>{{ t("oceanbasePrimaryKey.indexPolicy") }}</span>
+ <p v-if="oracleConstraintDraft.original?.kind === 'unique'" class="break-all font-mono text-xs">
+ {{ oracleConstraintDraft.original.definition.index.name ? `${oracleConstraintDraft.original.definition.index.owner}.${oracleConstraintDraft.original.definition.index.name}` : t("oceanbasePrimaryKey.noIndex") }}
+ </p>
+ <Select v-model="oracleConstraintDraft.indexPolicy" :disabled="oracleConstraintBusy">
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="keep">{{ t("oceanbasePrimaryKey.keepIndex") }}</SelectItem>
+ <SelectItem value="drop">{{ t("oceanbasePrimaryKey.dropIndex") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <p v-if="oracleConstraintDraft.indexPolicy === 'keep'" class="text-xs text-muted-foreground">{{ t("oceanbasePrimaryKey.preserveState") }}</p>
+ </div>
+ <div v-for="(name, position) in oracleConstraintDraft.target.definition.columns" :key="`${name}-${position}`" class="flex items-center gap-1">
+ <span class="min-w-0 flex-1 truncate font-mono">{{ position + 1 }}. {{ name }}</span>
+ <Button variant="ghost" size="icon-xs" :title="t('oceanbasePrimaryKey.moveUp')" :disabled="oracleConstraintBusy || position === 0" @click="moveOracleUniqueColumn(position, -1)"><ChevronUp class="h-4 w-4" /></Button>
+ <Button variant="ghost" size="icon-xs" :title="t('oceanbasePrimaryKey.moveDown')" :disabled="oracleConstraintBusy || position === oracleConstraintDraft.target.definition.columns.length - 1" @click="moveOracleUniqueColumn(position, 1)"><ChevronDown class="h-4 w-4" /></Button>
+ <Button variant="ghost" size="icon-xs" :title="t('common.delete')" :disabled="oracleConstraintBusy" @click="oracleConstraintDraft.target.definition.columns.splice(position, 1)"><X class="h-4 w-4" /></Button>
+ </div>
+ <Select :disabled="oracleConstraintBusy" @update:model-value="(value: any) => addOracleUniqueColumn(String(value || ''))">
+ <SelectTrigger><SelectValue :placeholder="t('structureEditor.addColumn')" /></SelectTrigger>
+ <SelectContent
+ ><SelectItem v-for="column in columns.filter((item) => !item.markedForDrop && oracleConstraintDraft?.target?.kind === 'unique' && !oracleConstraintDraft.target.definition.columns.includes(item.name))" :key="column.id" :value="column.name">{{
+ column.name
+ }}</SelectItem></SelectContent
+ >
+ </Select>
+ <div class="flex flex-wrap gap-3 text-sm">
+ <label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.enabled" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintEnabled") }}</label
+ ><label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.validated" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintValidated") }}</label>
+ </div>
+ </template>
+ <div class="flex gap-2">
+ <Button size="sm" variant="ghost" :disabled="oracleConstraintBusy" @click="cancelOracleConstraintEdit">{{ t("common.cancel") }}</Button>
+ <span v-if="oracleConstraintPlan" class="text-xs text-muted-foreground">{{ t("structureEditor.previewReady") }}</span>
+ </div>
+ <p v-for="notice in oracleConstraintPlan?.notices" :key="notice" class="rounded border border-amber-500/30 bg-amber-500/10 p-2 text-xs">{{ t(notice) }}</p>
+ </div>
+ <div v-if="existingPrimaryKeyDraft?.name === constraint.name" class="mt-2 space-y-2" data-existing-primary-key-editor>
+ <div v-for="(name, position) in existingPrimaryKeyDraft.columns" :key="name" class="flex items-center gap-1">
+ <span class="min-w-0 flex-1 truncate font-mono">{{ position + 1 }}. {{ name }}</span>
+ <Button variant="ghost" size="icon-xs" :title="t('oceanbasePrimaryKey.moveUp')" :disabled="primaryKeyBusy || position === 0" @click="moveExistingPrimaryKeyColumn(position, -1)"><ChevronUp class="h-4 w-4" /></Button>
+ <Button variant="ghost" size="icon-xs" :title="t('oceanbasePrimaryKey.moveDown')" :disabled="primaryKeyBusy || position === existingPrimaryKeyDraft.columns.length - 1" @click="moveExistingPrimaryKeyColumn(position, 1)"><ChevronDown class="h-4 w-4" /></Button>
+ <Button variant="ghost" size="icon-xs" :title="t('common.delete')" :disabled="primaryKeyBusy" @click="existingPrimaryKeyDraft.columns.splice(position, 1)"><X class="h-4 w-4" /></Button>
+ </div>
+ <p v-if="!existingPrimaryKeyDraft.columns.length" class="text-destructive">{{ t("oceanbasePrimaryKey.removeKey") }}</p>
+ <div class="flex items-center gap-2">
+ <Select v-model="primaryKeyNewColumn" :disabled="primaryKeyBusy || !primaryKeyAvailableColumns.length">
+ <SelectTrigger class="h-7 min-w-0 flex-1"><SelectValue :placeholder="t('structureEditor.addColumn')" /></SelectTrigger>
+ <SelectContent
+ ><SelectItem v-for="column in primaryKeyAvailableColumns" :key="column.id" :value="column.name">{{ column.name }}</SelectItem></SelectContent
+ >
+ </Select>
+ <Button variant="outline" size="sm" :disabled="primaryKeyBusy || !primaryKeyNewColumn" @click="addExistingPrimaryKeyColumn">{{ t("structureEditor.addColumn") }}</Button>
+ <Button variant="ghost" size="sm" :disabled="primaryKeyBusy" @click="existingPrimaryKeyDraft = undefined">{{ t("common.cancel") }}</Button>
+ </div>
+ <div v-if="existingPrimaryKeyDraft.oracleIndex" class="space-y-1">
+ <span>{{ t("oceanbasePrimaryKey.indexPolicy") }}</span>
+ <p v-if="currentPrimaryKeyIndex?.policy === 'none'" data-primary-key-index-identity class="text-xs">{{ t("oceanbasePrimaryKey.noIndex") }}</p>
+ <p v-else-if="currentPrimaryKeyIndex" data-primary-key-index-identity class="break-all font-mono text-xs">{{ currentPrimaryKeyIndex.owner }}.{{ currentPrimaryKeyIndex.name }}</p>
+ <Select v-if="currentPrimaryKeyIndex?.policy !== 'none'" v-model="existingPrimaryKeyDraft.oracleIndex.policy" :disabled="primaryKeyBusy">
+ <SelectTrigger :aria-label="t('oceanbasePrimaryKey.indexPolicy')"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="keep">{{ t("oceanbasePrimaryKey.keepIndex") }}</SelectItem>
+ <SelectItem value="drop">{{ t("oceanbasePrimaryKey.dropIndex") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <p class="text-xs text-muted-foreground">{{ t("oceanbasePrimaryKey.preserveState") }}</p>
+ </div>
+ <p v-if="existingPrimaryKeyChanged" class="rounded border border-amber-500/30 bg-amber-500/10 p-2 text-xs">
+ {{ t(currentPrimaryKeyIndex?.policy === "none" ? "oceanbasePrimaryKey.noIndexImpact" : existingPrimaryKeyDraft.oracleIndex ? "oceanbasePrimaryKey.oracleImpact" : "oceanbasePrimaryKey.impact") }}
+ </p>
</div>
<div v-if="constraint.columns.length" class="mt-1 truncate font-mono text-muted-foreground">{{ constraint.columns.join(", ") }}</div>
<div v-if="constraint.ref_table" class="mt-1 truncate font-mono text-muted-foreground">-> {{ constraint.ref_schema ? `${constraint.ref_schema}.` : "" }}{{ constraint.ref_table }}{{ constraint.ref_columns.length ? `(${constraint.ref_columns.join(", ")})` : "" }}</div>
<div v-if="constraint.definition" class="mt-1 whitespace-pre-wrap break-words font-mono text-muted-foreground">{{ constraint.definition }}</div>
</div>
</div>
+ <div v-if="oracleConstraintDraft && !oracleConstraintDraft.original" class="mt-2 rounded-md border p-3" data-oracle-constraint-editor data-constraint-editor="new">
+ <template v-if="oracleConstraintDraft.target?.kind === 'check'">
+ <Input v-model="oracleConstraintDraft.target.definition.name" :placeholder="t('structureEditor.constraintName')" :disabled="oracleConstraintBusy" />
+ <textarea v-model="oracleConstraintDraft.target.definition.expression" :placeholder="t('structureEditor.checkExpression')" :disabled="oracleConstraintBusy" class="mt-2 min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-sm" />
+ <div class="flex flex-wrap gap-3 text-sm">
+ <label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.enabled" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintEnabled") }}</label
+ ><label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.validated" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintValidated") }}</label>
+ </div>
+ </template>
+ <template v-else-if="oracleConstraintDraft.target?.kind === 'unique'">
+ <Input v-model="oracleConstraintDraft.target.definition.name" :placeholder="t('structureEditor.constraintName')" :disabled="oracleConstraintBusy" />
+ <div v-if="databaseType === 'oracle'" class="space-y-1 rounded border p-2" data-oracle-unique-index-policy>
+ <span>{{ t("oceanbasePrimaryKey.indexPolicy") }}</span>
+ <Select v-model="oracleConstraintDraft.indexPolicy" :disabled="oracleConstraintBusy">
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="keep">{{ t("oceanbasePrimaryKey.keepIndex") }}</SelectItem>
+ <SelectItem value="drop">{{ t("oceanbasePrimaryKey.dropIndex") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div v-for="(name, position) in oracleConstraintDraft.target.definition.columns" :key="`${name}-${position}`" class="flex items-center gap-1">
+ <span class="min-w-0 flex-1 truncate font-mono">{{ position + 1 }}. {{ name }}</span>
+ <Button variant="ghost" size="icon-xs" :disabled="oracleConstraintBusy" @click="oracleConstraintDraft.target.kind === 'unique' && oracleConstraintDraft.target.definition.columns.splice(position, 1)"><X class="h-4 w-4" /></Button>
+ </div>
+ <Select :disabled="oracleConstraintBusy" @update:model-value="(value: any) => addOracleUniqueColumn(String(value || ''))"
+ ><SelectTrigger><SelectValue :placeholder="t('structureEditor.addColumn')" /></SelectTrigger
+ ><SelectContent
+ ><SelectItem v-for="column in columns.filter((item) => !item.markedForDrop && oracleConstraintDraft?.target?.kind === 'unique' && !oracleConstraintDraft.target.definition.columns.includes(item.name))" :key="column.id" :value="column.name">{{
+ column.name
+ }}</SelectItem></SelectContent
+ ></Select
+ >
+ <div class="flex flex-wrap gap-3 text-sm">
+ <label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.enabled" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintEnabled") }}</label
+ ><label class="flex items-center gap-1"><input v-model="oracleConstraintDraft.target.definition.state.validated" type="checkbox" :disabled="oracleConstraintBusy" />{{ t("grid.tableInfoConstraintValidated") }}</label>
+ </div>
+ </template>
+ <Button variant="ghost" size="sm" :disabled="oracleConstraintBusy" @click="cancelOracleConstraintEdit">{{ t("common.cancel") }}</Button>
+ <p v-for="notice in oracleConstraintPlan?.notices" :key="notice" class="rounded border border-amber-500/30 bg-amber-500/10 p-2 text-xs">{{ t(notice) }}</p>
+ </div>
</TabsContent>
<TabsContent ref="triggersScrollerRef" v-if="tableMetadataCapabilities.triggers" value="triggers" class="col-start-1 row-start-2 structure-card-scroller m-0 min-h-0 flex-1 overflow-auto p-[var(--structure-cell-px)]" @scroll.passive="onStructureContentScroll('triggers', $event)">
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts
index 0da5c195f8..b84314af70 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -205,6 +205,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts
index 424b760364..7ca66f7487 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -205,6 +205,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts
index cfc1d712de..2f54ff6654 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts
@@ -221,6 +221,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts
index ab1a26b05e..0f11a2deb4 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts
@@ -18,9 +18,13 @@ const mocks = vi.hoisted(() => ({
name: "Oracle",
db_type: "oracle",
driver_label: "Oracle",
+ database: "APP",
+ production_databases: [] as string[],
database_info: { productVersion: "3.5.0" },
},
ensureConnected: vi.fn(),
+ connectionStateRevision: vi.fn(() => 1),
+ isCurrentConnectionStateRevision: vi.fn(() => true),
executeQuery: vi.fn(),
executeBatch: vi.fn(),
listDataTypes: vi.fn(),
@@ -38,6 +42,7 @@ const mocks = vi.hoisted(() => ({
loadObjectMetadataFacet: vi.fn(),
invalidateObjectMetadataCache: vi.fn(),
invalidateTableMetadataCache: vi.fn(),
+ requestConfirmation: vi.fn(),
toast: vi.fn(),
}));
@@ -241,6 +246,18 @@ vi.mock("@/components/ui/select", async () => {
});
return { Select: Div, SelectContent: Div, SelectItem: Div, SelectTrigger: Div, SelectValue: Div };
});
+vi.mock("@/components/editor/DangerConfirmDialog.vue", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ default: defineComponent({
+ props: { open: Boolean, title: String, message: String },
+ setup:
+ (props, { slots }) =>
+ () =>
+ props.open ? h("div", { role: "alertdialog" }, [h("h2", props.title), h("p", props.message), slots.options?.()]) : null,
+ }),
+ };
+});
vi.mock("@/components/editor/EditorSearchPanel.vue", async () => {
const { defineComponent, h } = await import("vue");
return {
@@ -256,9 +273,11 @@ vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
+ connectionStateRevision: mocks.connectionStateRevision,
+ isCurrentConnectionStateRevision: mocks.isCurrentConnectionStateRevision,
}),
}));
-vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: vi.fn() }) }));
+vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: mocks.requestConfirmation }) }));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({ tableStructureRefreshVersion: () => 0 }) }));
vi.mock("@/stores/historyStore", () => ({ useHistoryStore: () => ({ add: vi.fn() }) }));
vi.mock("@/stores/settingsStore", () => ({
@@ -369,8 +388,10 @@ async function createTableAndCaptureSaved(dbType: string, newTableName: string):
beforeEach(() => {
vi.clearAllMocks();
+ mocks.connection.production_databases = [];
mocks.renderColumnRows = false;
mocks.ensureConnected.mockResolvedValue(undefined);
+ mocks.requestConfirmation.mockResolvedValue(true);
mocks.executeQuery.mockResolvedValue({ columns: [], rows: [] });
mocks.executeBatch.mockResolvedValue({ rowsAffected: 0 });
mocks.listDataTypes.mockResolvedValue([]);
@@ -414,6 +435,534 @@ describe("TableStructureEditor created-table name write-back", () => {
const saved = await createTableAndCaptureSaved("oracle", "my table");
expect(saved.createdTableName).toBe("my table");
});
+
+ it("preflights and executes an Oracle self-reference through the ordered create plan", async () => {
+ mocks.connection.db_type = "oracle";
+ mocks.connection.production_databases = ["APP"];
+ mocks.buildCreateTableSql.mockResolvedValue({
+ statements: ['CREATE TABLE "APP".MyTable (id number NOT NULL, parent_id number, CONSTRAINT PK_NEW PRIMARY KEY (id));', 'ALTER TABLE "APP".MyTable ADD CONSTRAINT fk_new FOREIGN KEY (parent_id) REFERENCES "APP".MyTable (id) NORELY ENABLE VALIDATE;'],
+ warnings: [],
+ });
+ const ddl = 'ALTER TABLE "APP"."MYTABLE" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."MYTABLE" ("ID") ENABLE VALIDATE;';
+ mocks.executeQuery.mockImplementation(async (_id, _database, sql: string) => ({
+ columns: [],
+ rows: sql.includes("SELECT USER, SYS_CONTEXT")
+ ? [["APP", "APP"]]
+ : sql.includes("SYS.ALL_OBJECTS")
+ ? [["APP", "MYTABLE", 802]]
+ : sql.includes("SYS.ALL_TAB_COLS")
+ ? [
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]
+ : sql.includes("SYS.ALL_TABLES")
+ ? [["APP", "MYTABLE"]]
+ : sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")
+ ? [["FK_NEW", "MYTABLE"]]
+ : sql.includes("SYS.ALL_CONSTRAINTS")
+ ? [["FK_NEW", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"]]
+ : sql.includes("DBMS_METADATA.GET_DDL")
+ ? [[ddl]]
+ : [],
+ execution_time_ms: 0,
+ rows_affected: 0,
+ }));
+ let savedName: string | undefined;
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "APP",
+ schema: "APP",
+ tableName: "",
+ draft: {
+ dirty: true,
+ activeTab: "foreignKeys",
+ newTableName: "MyTable",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [
+ { id: "new:id", name: "id", dataType: "number", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false },
+ { id: "new:parent", name: "parent_id", dataType: "number", isNullable: true, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false },
+ ],
+ indexes: [],
+ foreignKeys: [
+ {
+ id: "new:fk",
+ name: "fk_new",
+ column: "parent_id",
+ columns: ["parent_id"],
+ refSchema: "APP",
+ refTable: "MyTable",
+ refColumn: "id",
+ refColumns: ["id"],
+ onUpdate: "",
+ onDelete: "NO ACTION",
+ oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false },
+ markedForDrop: false,
+ },
+ ],
+ triggers: [],
+ initialized: true,
+ },
+ onSaved: (_commentChanged: boolean, createdName?: string) => {
+ savedName = createdName;
+ },
+ });
+ mountedApps.push(app);
+ const editor = app.mount(root) as unknown as { applyChanges: () => Promise<boolean> };
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalled());
+ mocks.requestConfirmation.mockResolvedValueOnce(false);
+ expect(await editor.applyChanges()).toBe(false);
+ expect(mocks.executeQuery.mock.calls.some((call) => /^(CREATE TABLE|ALTER TABLE)\b/i.test(String(call[2])))).toBe(false);
+ expect(mocks.requestConfirmation).toHaveBeenCalledTimes(1);
+ await vi.waitFor(async () => expect(await editor.applyChanges()).toBe(true), { timeout: 3000 });
+ expect(mocks.executeBatch).not.toHaveBeenCalled();
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(1);
+ expect(savedName).toBe("MYTABLE");
+ });
+
+ it("shows partial new-table foreign-key results and never replays committed DDL", async () => {
+ mocks.connection.db_type = "oracle";
+ mocks.buildCreateTableSql.mockResolvedValue({
+ statements: [
+ 'CREATE TABLE "APP".MyTable (id number NOT NULL, parent_id number, CONSTRAINT PK_NEW PRIMARY KEY (id));',
+ 'ALTER TABLE "APP".MyTable ADD CONSTRAINT fk_first FOREIGN KEY (parent_id) REFERENCES "APP".MyTable (id) NORELY ENABLE VALIDATE;',
+ 'ALTER TABLE "APP".MyTable ADD CONSTRAINT fk_second FOREIGN KEY (parent_id) REFERENCES "APP".MyTable (id) NORELY ENABLE VALIDATE;',
+ ],
+ warnings: [],
+ });
+ const writes: string[] = [];
+ let secondForeignKeyAttempts = 0;
+ mocks.executeQuery.mockImplementation(async (_id, _database, sql: string) => {
+ if (/^(CREATE TABLE|ALTER TABLE)\b/i.test(sql)) {
+ writes.push(sql);
+ if (sql.toUpperCase().includes("FK_SECOND") && secondForeignKeyAttempts++ === 0) return { columns: [], rows: [], execution_error: true, error: { detail: "Second foreign key rejected" } };
+ }
+ const ddl = sql.includes("FK_SECOND")
+ ? 'ALTER TABLE "APP"."MYTABLE" ADD CONSTRAINT "FK_SECOND" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."MYTABLE" ("ID") ENABLE VALIDATE;'
+ : 'ALTER TABLE "APP"."MYTABLE" ADD CONSTRAINT "FK_FIRST" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."MYTABLE" ("ID") ENABLE VALIDATE;';
+ return {
+ columns: [],
+ rows: sql.includes("SELECT USER, SYS_CONTEXT")
+ ? [["APP", "APP"]]
+ : sql.includes("SYS.ALL_OBJECTS")
+ ? [["APP", "MYTABLE", 802]]
+ : sql.includes("SYS.ALL_TAB_COLS")
+ ? [
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]
+ : sql.includes("SYS.ALL_TABLES")
+ ? [["APP", "MYTABLE"]]
+ : sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")
+ ? secondForeignKeyAttempts > 1
+ ? [
+ ["FK_FIRST", "MYTABLE"],
+ ["FK_SECOND", "MYTABLE"],
+ ]
+ : [["FK_FIRST", "MYTABLE"]]
+ : sql.includes("SYS.ALL_CONSTRAINTS")
+ ? secondForeignKeyAttempts > 1
+ ? [
+ ["FK_FIRST", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"],
+ ["FK_SECOND", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"],
+ ]
+ : [["FK_FIRST", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"]]
+ : sql.includes("DBMS_METADATA.GET_DDL")
+ ? [[ddl]]
+ : [],
+ execution_time_ms: 0,
+ rows_affected: 0,
+ };
+ });
+ let savedName: string | undefined;
+ let savedDraft: import("@/types/database").TableStructureEditorDraft | undefined;
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "APP",
+ schema: "APP",
+ tableName: "",
+ draft: {
+ dirty: true,
+ activeTab: "foreignKeys",
+ newTableName: "MyTable",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [
+ { id: "new:id", name: "id", dataType: "number", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false },
+ { id: "new:parent", name: "parent_id", dataType: "number", isNullable: true, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false },
+ ],
+ indexes: [],
+ foreignKeys: ["first", "second"].map((name) => ({
+ id: `new:fk_${name}`,
+ name: `fk_${name}`,
+ column: "parent_id",
+ columns: ["parent_id"],
+ refSchema: "APP",
+ refTable: "MyTable",
+ refColumn: "id",
+ refColumns: ["id"],
+ onUpdate: "",
+ onDelete: "NO ACTION",
+ oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false },
+ markedForDrop: false,
+ })),
+ triggers: [],
+ initialized: true,
+ },
+ onSaved: (_commentChanged: boolean, createdName?: string) => {
+ savedName = createdName;
+ },
+ "onUpdate:draft": (draft: import("@/types/database").TableStructureEditorDraft | undefined) => {
+ savedDraft = draft;
+ },
+ });
+ mountedApps.push(app);
+ const editor = app.mount(root) as unknown as { applyChanges: () => Promise<boolean> };
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalled());
+ const applyButton = Array.from(root.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("structureEditor.apply"))!;
+ await vi.waitFor(() => expect(applyButton.disabled).toBe(false), { timeout: 3000 });
+
+ expect(await editor.applyChanges()).toBe(false);
+ await vi.waitFor(() => expect(savedName).toBe("MYTABLE"));
+ expect(root.textContent).toContain("oracleForeignKey.createdTablePartial");
+ expect(root.textContent).toContain("oceanbasePrimaryKey.committed");
+ expect(root.textContent).toContain("oceanbasePrimaryKey.rejected");
+ expect(root.textContent).toContain("Second foreign key rejected");
+ expect(savedDraft?.oracleForeignKeyCreateRecovery).toMatchObject({
+ tableName: "MYTABLE",
+ tableExists: true,
+ remaining: [{ name: "FK_SECOND", columns: ["PARENT_ID"], refSchema: "APP", refTable: "MYTABLE", refColumns: ["ID"] }],
+ });
+ expect(savedDraft?.columns).toEqual([]);
+ expect(writes).toHaveLength(3);
+ expect(writes.filter((sql) => sql.startsWith("CREATE TABLE"))).toHaveLength(1);
+ expect(writes.filter((sql) => sql.includes("fk_first"))).toHaveLength(1);
+ expect(writes.filter((sql) => sql.includes("fk_second"))).toHaveLength(1);
+ expect(await editor.applyChanges()).toBe(false);
+ expect(writes).toHaveLength(3);
+
+ const resumedRoot = document.createElement("div");
+ document.body.append(resumedRoot);
+ mocks.buildTableStructureChangeSql.mockResolvedValue({ statements: ['ALTER TABLE "APP"."MYTABLE" ADD CONSTRAINT "FK_SECOND" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."MYTABLE" ("ID") ENABLE VALIDATE;'], warnings: [] });
+ const resumedApp = createApp(TableStructureEditor, { connectionId: mocks.connection.id, database: "APP", schema: "APP", tableName: "MYTABLE", draft: savedDraft });
+ mountedApps.push(resumedApp);
+ const resumedEditor = resumedApp.mount(resumedRoot) as unknown as { applyChanges: () => Promise<boolean> };
+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("SYS.ALL_OBJECTS"))).toBe(true));
+ await vi.waitFor(() => expect(resumedRoot.textContent).not.toContain("structureEditor.loading"));
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenCalled();
+ const resumedApplyButton = Array.from(resumedRoot.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("structureEditor.apply"))!;
+ await vi.waitFor(() => expect(resumedApplyButton.disabled).toBe(false), { timeout: 3000 });
+ const sourceSnapshotsBeforeApply = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("SYS.ALL_OBJECTS")).length;
+ await vi.waitFor(async () => expect(await resumedEditor.applyChanges()).toBe(true), { timeout: 3000 });
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("SYS.ALL_OBJECTS")).length).toBeGreaterThan(sourceSnapshotsBeforeApply);
+ expect(resumedRoot.textContent).not.toContain("oracleForeignKey.invalid");
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tableName: "MYTABLE",
+ oracleForeignKeyChanges: [expect.objectContaining({ original: null, target: expect.objectContaining({ name: "FK_SECOND", columns: ["PARENT_ID"], refSchema: "APP", refTable: "MYTABLE", refColumns: ["ID"] }) })],
+ }),
+ );
+ expect(writes.filter((sql) => sql.startsWith("CREATE TABLE"))).toHaveLength(1);
+ expect(writes.filter((sql) => sql.toUpperCase().includes("FK_FIRST"))).toHaveLength(1);
+ expect(writes.filter((sql) => sql.toUpperCase().includes("FK_SECOND"))).toHaveLength(2);
+ });
+
+ it("blocks retry after an unknown CREATE response until the table is manually verified", async () => {
+ mocks.connection.db_type = "oracle";
+ const create = 'CREATE TABLE "APP".MyTable (id number NOT NULL, CONSTRAINT PK_NEW PRIMARY KEY (id));';
+ mocks.buildCreateTableSql.mockResolvedValue({
+ statements: [create, 'ALTER TABLE "APP".MyTable ADD CONSTRAINT fk_self FOREIGN KEY (id) REFERENCES "APP".MyTable (id) NORELY ENABLE VALIDATE;'],
+ warnings: [],
+ });
+ mocks.executeQuery.mockImplementation(async (_id, _database, sql: string) => {
+ if (sql.startsWith("CREATE TABLE")) throw new Error("Connection lost after request");
+ return {
+ columns: [],
+ rows: sql.includes("SELECT USER, SYS_CONTEXT") ? [["APP", "APP"]] : sql.includes("SYS.ALL_TABLES") ? [] : [],
+ execution_time_ms: 0,
+ rows_affected: 0,
+ };
+ });
+ let savedDraft: import("@/types/database").TableStructureEditorDraft | undefined;
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "APP",
+ schema: "APP",
+ tableName: "",
+ draft: {
+ dirty: true,
+ activeTab: "foreignKeys",
+ newTableName: "MyTable",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [{ id: "new:id", name: "id", dataType: "number", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false }],
+ indexes: [],
+ foreignKeys: [
+ {
+ id: "new:fk",
+ name: "fk_self",
+ column: "id",
+ columns: ["id"],
+ refSchema: "APP",
+ refTable: "MyTable",
+ refColumn: "id",
+ refColumns: ["id"],
+ onUpdate: "",
+ onDelete: "NO ACTION",
+ oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false },
+ markedForDrop: false,
+ },
+ ],
+ triggers: [],
+ initialized: true,
+ },
+ "onUpdate:draft": (draft: import("@/types/database").TableStructureEditorDraft | undefined) => {
+ savedDraft = draft;
+ },
+ });
+ mountedApps.push(app);
+ const editor = app.mount(root) as unknown as { applyChanges: () => Promise<boolean> };
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalled());
+ const applyButton = Array.from(root.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("structureEditor.apply"))!;
+ await vi.waitFor(() => expect(applyButton.disabled).toBe(false), { timeout: 3000 });
+ expect(await editor.applyChanges()).toBe(false);
+ await vi.waitFor(() => expect(savedDraft?.oracleForeignKeyCreateRecovery?.uncertainSteps).toContain("CREATE"));
+ await vi.waitFor(() => expect(applyButton.disabled).toBe(true));
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ expect(await editor.applyChanges()).toBe(false);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ });
+
+ it("does not emit saved when the connection changes after CREATE commits", async () => {
+ mocks.connection.db_type = "oracle";
+ let revision = 1;
+ mocks.connectionStateRevision.mockImplementation(() => revision);
+ mocks.buildCreateTableSql.mockResolvedValue({
+ statements: ['CREATE TABLE "APP".MyTable (id number NOT NULL, parent_id number, CONSTRAINT PK_NEW PRIMARY KEY (id));', 'ALTER TABLE "APP".MyTable ADD CONSTRAINT fk_new FOREIGN KEY (parent_id) REFERENCES "APP".MyTable (id) NORELY ENABLE VALIDATE;'],
+ warnings: [],
+ });
+ mocks.executeQuery.mockImplementation(async (_id, _database, sql: string) => {
+ if (sql.startsWith("CREATE TABLE")) revision = 2;
+ return {
+ columns: [],
+ rows: sql.includes("SELECT USER, SYS_CONTEXT")
+ ? [["APP", "APP"]]
+ : sql.includes("SYS.ALL_OBJECTS")
+ ? [["APP", "MYTABLE", 802]]
+ : sql.includes("SYS.ALL_TAB_COLS")
+ ? [
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]
+ : sql.includes("SYS.ALL_TABLES")
+ ? [["APP", "MYTABLE"]]
+ : sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")
+ ? [["FK_NEW", "MYTABLE"]]
+ : sql.includes("SYS.ALL_CONSTRAINTS")
+ ? [["FK_NEW", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"]]
+ : sql.includes("DBMS_METADATA.GET_DDL")
+ ? [['ALTER TABLE "APP"."MYTABLE" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."MYTABLE" ("ID") ENABLE VALIDATE;']]
+ : [],
+ execution_time_ms: 0,
+ rows_affected: 0,
+ };
+ });
+ let saved = false;
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "APP",
+ schema: "APP",
+ tableName: "",
+ draft: {
+ dirty: true,
+ activeTab: "foreignKeys",
+ newTableName: "MyTable",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [
+ { id: "new:id", name: "id", dataType: "number", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false },
+ { id: "new:parent", name: "parent_id", dataType: "number", isNullable: true, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false },
+ ],
+ indexes: [],
+ foreignKeys: [
+ {
+ id: "new:fk",
+ name: "fk_new",
+ column: "parent_id",
+ columns: ["parent_id"],
+ refSchema: "APP",
+ refTable: "MyTable",
+ refColumn: "id",
+ refColumns: ["id"],
+ onUpdate: "",
+ onDelete: "NO ACTION",
+ oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false },
+ markedForDrop: false,
+ },
+ ],
+ triggers: [],
+ initialized: true,
+ },
+ onSaved: () => {
+ saved = true;
+ },
+ });
+ mountedApps.push(app);
+ const editor = app.mount(root) as unknown as { applyChanges: () => Promise<boolean> };
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalled());
+ await vi.waitFor(
+ async () => {
+ await editor.applyChanges();
+ expect(revision).toBe(2);
+ },
+ { timeout: 3000 },
+ );
+ expect(revision).toBe(2);
+ expect(saved).toBe(false);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(0);
+ });
+
+ it("preserves a new CREATE plan when the previous target returns late", async () => {
+ mocks.connection.db_type = "oracle";
+ mocks.buildCreateTableSql.mockImplementation(async (options: { tableName: string }) => ({
+ statements: [`CREATE TABLE "APP".${options.tableName} (id number NOT NULL, parent_id number, CONSTRAINT PK_NEW PRIMARY KEY (id));`, `ALTER TABLE "APP".${options.tableName} ADD CONSTRAINT fk_new FOREIGN KEY (parent_id) REFERENCES "PARENT_OWNER".PARENT (id) NORELY ENABLE VALIDATE;`],
+ warnings: [],
+ }));
+
+ let releaseOldCreate!: () => void;
+ let signalOldCreateStarted!: () => void;
+ let metadataTableName = "MYTABLE";
+ const oldCreateStarted = new Promise<void>((resolve) => {
+ signalOldCreateStarted = resolve;
+ });
+ const oldCreateGate = new Promise<void>((resolve) => {
+ releaseOldCreate = resolve;
+ });
+ mocks.executeQuery.mockImplementation(async (_id, _database, sql: string) => {
+ if (sql.startsWith('CREATE TABLE "APP".MyTable')) {
+ signalOldCreateStarted();
+ await oldCreateGate;
+ }
+ return {
+ columns: [],
+ rows: sql.includes("SELECT USER, SYS_CONTEXT")
+ ? [["APP", "APP"]]
+ : sql.includes("SYS.ALL_OBJECTS") && sql.includes("PARENT_OWNER")
+ ? [["PARENT_OWNER", "PARENT", 900]]
+ : sql.includes("SYS.ALL_OBJECTS")
+ ? [["APP", "MYTABLE", 802]]
+ : sql.includes("SYS.ALL_TAB_COLS") && sql.includes("PARENT_OWNER")
+ ? [["ID", "NUMBER"]]
+ : sql.includes("SYS.ALL_TAB_COLS")
+ ? [
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]
+ : sql.includes("SYS.ALL_TABLES")
+ ? [["APP", sql.match(/TABLE_NAME = '([^']+)'/)?.[1] ?? "MYTABLE"]]
+ : sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")
+ ? [["FK_NEW", "MYTABLE"]]
+ : sql.includes("c.CONSTRAINT_TYPE IN ('P', 'U')")
+ ? [["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "ID", 1]]
+ : sql.includes("SYS.ALL_CONSTRAINTS")
+ ? [["FK_NEW", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "PARENT_OWNER", "PK_PARENT", "NO ACTION"]]
+ : sql.includes("SYS.ALL_TAB_PRIVS")
+ ? [["REFERENCES"]]
+ : sql.includes("SYS.ALL_COL_PRIVS") || sql.includes("SESSION_PRIVS")
+ ? []
+ : sql.includes("DBMS_METADATA.GET_DDL")
+ ? [[`ALTER TABLE "APP"."${metadataTableName}" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("PARENT_ID") REFERENCES "PARENT_OWNER"."PARENT" ("ID") ENABLE VALIDATE;`]]
+ : [],
+ execution_time_ms: 0,
+ rows_affected: 0,
+ };
+ });
+
+ let savedName: string | undefined;
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "APP",
+ schema: "APP",
+ tableName: "",
+ draft: {
+ dirty: true,
+ activeTab: "foreignKeys",
+ newTableName: "MyTable",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [
+ { id: "new:id", name: "id", dataType: "number", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false },
+ { id: "new:parent", name: "parent_id", dataType: "number", isNullable: true, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false },
+ ],
+ indexes: [],
+ foreignKeys: [
+ {
+ id: "new:fk",
+ name: "fk_new",
+ column: "parent_id",
+ columns: ["parent_id"],
+ refSchema: "PARENT_OWNER",
+ refTable: "PARENT",
+ refColumn: "ID",
+ refColumns: ["ID"],
+ onUpdate: "",
+ onDelete: "NO ACTION",
+ oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false },
+ markedForDrop: false,
+ },
+ ],
+ triggers: [],
+ initialized: true,
+ },
+ onSaved: (_commentChanged: boolean, createdName?: string) => {
+ savedName = createdName;
+ },
+ });
+ mountedApps.push(app);
+ const editor = app.mount(root) as unknown as { applyChanges: () => Promise<boolean> };
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalled());
+ const applyButton = Array.from(root.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("structureEditor.apply"))!;
+ await vi.waitFor(() => expect(applyButton.disabled, `${root.textContent}\n${JSON.stringify(mocks.toast.mock.calls)}\n${JSON.stringify(mocks.executeQuery.mock.calls.map((call) => call[2]))}`).toBe(false));
+
+ const oldApply = editor.applyChanges();
+ await vi.waitFor(
+ () =>
+ expect(
+ mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith('CREATE TABLE "APP".MyTable')),
+ `${JSON.stringify(mocks.toast.mock.calls)}\n${JSON.stringify(mocks.executeQuery.mock.calls.map((call) => call[2]))}`,
+ ).toBe(true),
+ { timeout: 3000 },
+ );
+ await oldCreateStarted;
+ const tableName = root.querySelector<HTMLInputElement>('input[placeholder="contextMenu.duplicateNamePlaceholder"]')!;
+ tableName.value = "NextTable";
+ tableName.dispatchEvent(new Event("input", { bubbles: true }));
+ metadataTableName = "NEXTTABLE";
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalledWith(expect.objectContaining({ tableName: "NextTable" })));
+
+ releaseOldCreate();
+ expect(await oldApply).toBe(false);
+ await settle();
+
+ await vi.waitFor(() => expect(applyButton.disabled).toBe(false), { timeout: 3000 });
+ expect(await editor.applyChanges()).toBe(true);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith('CREATE TABLE "APP".MyTable'))).toHaveLength(1);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith('CREATE TABLE "APP".NextTable'))).toHaveLength(1);
+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith('ALTER TABLE "APP".MyTable'))).toHaveLength(0);
+ expect(savedName).toBe("NEXTTABLE");
+ });
});
describe("StarRocks create layout integration", () => {
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts
index 89ac9c36d2..d91dcd1a35 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { EditorView } from "@codemirror/view";
@@ -263,6 +263,8 @@ vi.mock("@/components/editor/EditorSearchPanel.vue", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts
index 150edfe929..a4ff65396d 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, reactive, ref, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -172,6 +172,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts
index 0920f0df20..b913f3dd88 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { EditorView } from "@codemirror/view";
@@ -253,6 +253,8 @@ vi.mock("@/components/editor/EditorSearchPanel.vue", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts
index c37f6697be..50529e5781 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts
@@ -233,6 +233,8 @@ vi.mock("@/components/editor/EditorSearchPanel.vue", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
@@ -269,6 +271,24 @@ vi.mock("@/lib/backend/api", () => ({
getTablePartitionStatus: mocks.getTablePartitionStatus,
getTableOwner: mocks.getTableOwner,
}));
+vi.mock("@/lib/database/oracleConstraints", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/database/oracleConstraints")>();
+ return {
+ ...actual,
+ readOracleIndexSnapshot: vi.fn(async (target) => ({
+ user: target.schema || "TEST",
+ currentSchema: target.schema || "TEST",
+ database: target.database,
+ databaseName: "ORCL",
+ objectId: "1",
+ columns: [],
+ userColumns: [],
+ columnReadMode: "strict-base" as const,
+ indexes: [],
+ indexNames: [],
+ })),
+ };
+});
import TableStructureEditor from "@/components/structure/TableStructureEditor.vue";
import { createColumnDrafts, createIndexDrafts } from "@/lib/table/tableStructureEditorState";
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts
index a79dcec7fc..262cf30ff8 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -206,6 +206,8 @@ vi.mock("@/components/ui/select", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oceanbasePrimaryKey.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oceanbasePrimaryKey.spec.ts
new file mode 100644
index 0000000000..8db050a6e0
--- /dev/null
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oceanbasePrimaryKey.spec.ts
@@ -0,0 +1,532 @@
+// @vitest-environment happy-dom
+import { createApp, h, nextTick, ref, type App } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import TableStructureEditor from "../TableStructureEditor.vue";
+import i18n from "@/i18n";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import LightTooltip from "@/components/ui/LightTooltip.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
+import type { ConnectionConfig, ConstraintInfo } from "@/types/database";
+import * as api from "@/lib/backend/api";
+import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";
+
+vi.mock("@/lib/backend/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),
+ listPlugins: vi.fn().mockResolvedValue([]),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ listDataTypes: vi.fn().mockResolvedValue([]),
+ getColumns: vi.fn(),
+ listConstraints: vi.fn(),
+ listIndexes: vi.fn().mockResolvedValue([]),
+ listForeignKeys: vi.fn().mockResolvedValue([]),
+ listTriggers: vi.fn().mockResolvedValue([]),
+ getTableComment: vi.fn().mockResolvedValue(""),
+ getTablePartitioning: vi.fn().mockResolvedValue(null),
+ buildTableStructureChangeSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),
+ saveHistory: vi.fn().mockResolvedValue(undefined),
+ disconnectDb: vi.fn().mockResolvedValue(undefined),
+ executeQuery: vi.fn().mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 }),
+}));
+
+const connection = { id: "ob-existing-pk", name: "OB fixture", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", host: "fixture", port: 2881, username: "APP", database: "APP" } as ConnectionConfig;
+let app: App | undefined;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ i18n.global.locale.value = "en";
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown) => {
+ throw new Error(`Unexpected HTTP request: ${input}`);
+ }),
+ );
+});
+
+afterEach(() => {
+ app?.unmount();
+ app = undefined;
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+async function mountExistingKey(columns: string[], databaseType = "oceanbase-oracle", disabled = false, isProduction = false) {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const store = useConnectionStore();
+ store.connections = [{ ...connection, db_type: databaseType, driver_profile: databaseType, is_production: isProduction } as ConnectionConfig];
+ store.connectedIds.add(connection.id);
+ vi.mocked(api.getColumns).mockResolvedValue(["ID", "V"].map((name) => ({ name, data_type: "NUMBER", is_nullable: false, is_primary_key: columns.includes(name), column_default: null })));
+ vi.mocked(api.listConstraints).mockResolvedValue([{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns, definition: "", ref_columns: [], enabled: !disabled, valid: !disabled, deferrable: false, initially_deferred: false } as ConstraintInfo]);
+ const container = document.createElement("div");
+ document.body.append(container);
+ await invalidateObjectMetadataCache({ connectionId: connection.id });
+ const editor = ref<InstanceType<typeof TableStructureEditor>>();
+ const context = ref({ connectionId: connection.id, database: "APP", schema: "APP", tableName: `SOURCE_${columns.join("_")}`, initialTab: "constraints" as const });
+ const drafts: unknown[] = [];
+ app = createApp({ render: () => h(TooltipProvider, {}, { default: () => h(TableStructureEditor, { ...context.value, ref: editor, "onUpdate:draft": (draft) => drafts.push(draft) }) }) });
+ app.use(pinia);
+ app.use(i18n);
+ app.component("LightTooltip", LightTooltip);
+ app.mount(container);
+ if (["oceanbase-oracle", "oracle"].includes(databaseType)) await vi.waitFor(() => expect(container.textContent).toContain("PK_SOURCE"));
+ else await vi.waitFor(() => expect(api.getColumns).toHaveBeenCalled());
+ await nextTick();
+ return { container, editor, context, drafts };
+}
+
+async function prepareReorderedKey(rejectAdd = false, remove = false, databaseType = "oceanbase-oracle", disabled = false, isProduction = false, openOnly = false) {
+ const mounted = await mountExistingKey(["ID", "V"], databaseType, disabled, isProduction);
+ const oracle = databaseType === "oracle";
+ const tableName = "SOURCE_ID_V";
+ let keyColumns = ["ID", "V"];
+ vi.mocked(api.getColumns).mockImplementation(async () => ["ID", "V"].map((name) => ({ name, data_type: "NUMBER", is_nullable: false, is_primary_key: keyColumns.includes(name), column_default: null })));
+ vi.mocked(api.listConstraints).mockImplementation(async () => (keyColumns.length ? [{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: [...keyColumns], definition: "", ref_columns: [], enabled: !disabled, valid: !disabled, deferrable: false, initially_deferred: false }] : []));
+ vi.mocked(api.listIndexes).mockImplementation(async () => (!disabled && (keyColumns.length || oracle) ? [{ name: "PK_SOURCE", columns: oracle ? ["ID", "V"] : [...keyColumns], is_primary: !!keyColumns.length, is_unique: true, index_type: "NORMAL" }] : []));
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (options) => ({
+ statements: options.primaryKeyChange
+ ? [
+ `ALTER TABLE "APP"."${tableName}" DROP CONSTRAINT "PK_SOURCE"${oracle && !disabled ? " KEEP INDEX" : ""};`,
+ ...(options.primaryKeyChange.columns.length ? [`ALTER TABLE "APP"."${tableName}" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("V", "ID")${disabled ? " NOT DEFERRABLE INITIALLY IMMEDIATE NORELY DISABLE NOVALIDATE" : oracle ? ' USING INDEX "APP"."PK_SOURCE"' : ""};`] : []),
+ ]
+ : [],
+ warnings: [],
+ }));
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _database, sql) => {
+ const result = (rows: unknown[][] = []) => ({ columns: [], rows, affected_rows: 0, execution_time_ms: 0 });
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "APP"]]);
+ if (sql.includes("SYS.ALL_OBJECTS")) {
+ const tableName = /OBJECT_NAME = '([^']+)'/.exec(sql)?.[1] ?? "SOURCE_ID_V";
+ return result([["APP", tableName, 77]]);
+ }
+ if (sql.startsWith("SELECT RELY ")) return result([[null]]);
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result();
+ if (sql.includes(" DROP CONSTRAINT ")) {
+ keyColumns = [];
+ return result();
+ }
+ if (sql.includes(" ADD CONSTRAINT ")) {
+ if (rejectAdd) return { ...result(), execution_error: true, error: { detail: "ORA-00001: duplicate key" } };
+ keyColumns = ["V", "ID"];
+ return result();
+ }
+ if (sql.includes("R_CONSTRAINT_NAME")) return result();
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["ID", 1, "ASC"],
+ ["V", 2, "ASC"],
+ ]);
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["APP", "PK_SOURCE", "NORMAL", "UNIQUE", "VALID", "VISIBLE", "NO", ...(sql.includes("PARTITIONED, TABLE_OWNER") ? ["APP", tableName] : [])]]);
+ if (sql.includes("SYS.ALL_CONS_COLUMNS"))
+ return result([
+ ["ID", 1],
+ ["V", 2],
+ ]);
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["ID", "N", "NO"],
+ ["V", "N", "NO"],
+ ]);
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]);
+ if (sql.startsWith("SELECT OWNER, TABLE_NAME")) return result([["APP", tableName, "PK_SOURCE", "P"]]);
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["PK_SOURCE", disabled ? "DISABLED" : "ENABLED", disabled ? "NOT VALIDATED" : "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", disabled ? null : "APP", disabled ? null : "PK_SOURCE"]]);
+ if (sql.startsWith("SELECT COUNT(*)")) return result([[0]]);
+ throw new Error(`Unexpected query: ${sql}`);
+ });
+ Array.from(mounted.container.querySelectorAll("button"))
+ .find((button) => button.textContent?.trim() === i18n.global.t(remove ? "common.delete" : "common.edit"))!
+ .click();
+ await vi.waitFor(() => expect(mounted.container.querySelector("[data-existing-primary-key-editor]")).not.toBeNull());
+ if (openOnly) return mounted;
+ if (!remove) (mounted.container.querySelector(`[data-existing-primary-key-editor] button[title="${i18n.global.t("oceanbasePrimaryKey.moveDown")}"]`) as HTMLButtonElement).click();
+ await vi.waitFor(() => {
+ const apply = Array.from(mounted.container.querySelectorAll("button")).find((button) => button.textContent?.trim() === i18n.global.t("structureEditor.apply"));
+ expect(apply?.disabled).toBe(false);
+ });
+ return mounted;
+}
+
+describe("OceanBase existing primary key in the structure editor", () => {
+ it("previews and saves a disabled Oracle key without offering a nonexistent index policy", async () => {
+ const { editor, drafts, container } = await prepareReorderedKey(false, false, "oracle", true);
+ expect(container.querySelector("[data-primary-key-index-identity]")?.textContent).toBe(i18n.global.t("oceanbasePrimaryKey.noIndex"));
+ expect(container.querySelector("[data-existing-primary-key-editor]")?.parentElement?.classList.contains("opacity-60")).toBe(false);
+ expect(container.textContent).not.toContain(i18n.global.t("oceanbasePrimaryKey.oracleImpact"));
+ expect(container.querySelector(`[aria-label="${i18n.global.t("oceanbasePrimaryKey.indexPolicy")}"]`)).toBeNull();
+ expect(container.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.preserveState"));
+ expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].primaryKeyChange).toMatchObject({ oracleIndex: { policy: "none", name: "" }, oracleState: { enabled: false, validated: false, deferrable: false, initiallyDeferred: false, rely: false } });
+ await expect(editor.value!.applyChanges()).resolves.toBe(true);
+ expect(drafts.at(-1)).toMatchObject({ dirty: false, existingPrimaryKey: undefined });
+ expect(
+ vi
+ .mocked(api.executeQuery)
+ .mock.calls.filter((call) => call[2].startsWith("ALTER "))
+ .map((call) => call[2]),
+ ).toEqual(['ALTER TABLE "APP"."SOURCE_ID_V" DROP CONSTRAINT "PK_SOURCE"', 'ALTER TABLE "APP"."SOURCE_ID_V" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("V", "ID") NOT DEFERRABLE INITIALLY IMMEDIATE NORELY DISABLE NOVALIDATE']);
+ });
+ it("offers the existing primary key editor for native Oracle", async () => {
+ const { container } = await mountExistingKey(["ID", "V"], "oracle");
+ const name = Array.from(container.querySelectorAll("span")).find((node) => node.textContent === "PK_SOURCE")!;
+ const card = name.parentElement!.parentElement!;
+ const edit = Array.from(card.querySelectorAll("button")).find((button) => button.textContent?.trim() === i18n.global.t("common.edit"));
+ expect(edit, "Native Oracle must expose the existing primary key editor").toBeDefined();
+ edit!.click();
+ await vi.waitFor(() => expect(container.querySelector("[data-existing-primary-key-editor]")).not.toBeNull());
+ expect(api.executeQuery).toHaveBeenCalled();
+ expect(api.executeQuery.mock.calls.filter(([, , sql]) => /^(?:ALTER|CREATE|DROP)\b/i.test(sql.trim()))).toHaveLength(0);
+ });
+
+ it.each([{ columns: ["ID"] }, { columns: ["V", "ID"] }])("offers editing for the existing ordered key $columns in its constraint card", async ({ columns }) => {
+ const { container } = await mountExistingKey(columns);
+ const name = Array.from(container.querySelectorAll("span")).find((node) => node.textContent === "PK_SOURCE")!;
+ const card = name.parentElement!.parentElement!;
+ expect(card.textContent).toContain(columns.join(", "));
+ const edit = Array.from(card.querySelectorAll("button")).find((button) => button.textContent?.trim() === i18n.global.t("common.edit"));
+ expect(edit, "Existing primary keys must be editable from their current constraint card").toBeDefined();
+ expect(edit!.disabled).toBe(false);
+ expect(api.executeQuery).not.toHaveBeenCalled();
+ });
+
+ it.each(["saphana", "mysql"])("does not expose the Oracle-family key editor for %s", async (databaseType) => {
+ const { container } = await mountExistingKey(["ID"], databaseType);
+ const name = Array.from(container.querySelectorAll("span")).find((node) => node.textContent === "PK_SOURCE");
+ if (name) {
+ const card = name.parentElement!.parentElement!;
+ expect(Array.from(card.querySelectorAll("button")).some((button) => button.textContent?.trim() === i18n.global.t("common.edit"))).toBe(false);
+ }
+ expect(container.querySelector("[data-existing-primary-key-editor]")).toBeNull();
+ });
+
+ it("keeps an ordered primary key draft in the existing unsaved-change contract", async () => {
+ const { container, drafts } = await mountExistingKey(["ID", "V"]);
+ const edit = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.trim() === i18n.global.t("common.edit"))!;
+ edit.click();
+ await vi.waitFor(() => expect(container.querySelector("[data-existing-primary-key-editor]")).not.toBeNull());
+ const down = container.querySelector(`[data-existing-primary-key-editor] button[title="${i18n.global.t("oceanbasePrimaryKey.moveDown")}"]`) as HTMLButtonElement;
+ down.click();
+ await nextTick();
+ await vi.waitFor(() => expect(drafts.at(-1)).toMatchObject({ dirty: true, existingPrimaryKey: { name: "PK_SOURCE", originalColumns: ["ID", "V"], columns: ["V", "ID"] } }));
+ expect(api.executeQuery.mock.calls.filter(([, , sql]) => /^(?:ALTER|CREATE|DROP)\b/i.test(sql.trim()))).toHaveLength(0);
+ });
+
+ it("previews and applies the ordered key through the existing save entry", async () => {
+ const { editor, drafts, container } = await prepareReorderedKey();
+ expect(container.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.impact"));
+ expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].primaryKeyChange).toEqual({ name: "PK_SOURCE", originalColumns: ["ID", "V"], columns: ["V", "ID"] });
+ await expect(editor.value!.applyChanges()).resolves.toBe(true);
+ expect(
+ vi
+ .mocked(api.executeQuery)
+ .mock.calls.filter((call) => call[2].startsWith("ALTER "))
+ .map((call) => call.slice(0, 2)),
+ ).toEqual([
+ [connection.id, "APP"],
+ [connection.id, "APP"],
+ ]);
+ expect(vi.mocked(api.saveHistory).mock.calls).toHaveLength(2);
+ expect(drafts.at(-1)).toMatchObject({ dirty: false, existingPrimaryKey: undefined });
+ });
+
+ it("previews and saves native Oracle with an explicit retained index through the same entry", async () => {
+ const { editor, drafts, container } = await prepareReorderedKey(false, false, "oracle");
+ expect(container.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.oracleImpact"));
+ expect(container.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.keepIndex"));
+ expect(container.querySelector("[data-primary-key-index-identity]")?.textContent).toBe("APP.PK_SOURCE");
+ expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].primaryKeyChange).toEqual({
+ name: "PK_SOURCE",
+ originalColumns: ["ID", "V"],
+ columns: ["V", "ID"],
+ oracleIndex: { policy: "keep", owner: "APP", name: "PK_SOURCE" },
+ oracleState: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false },
+ });
+ await expect(editor.value!.applyChanges()).resolves.toBe(true);
+ expect(
+ vi
+ .mocked(api.executeQuery)
+ .mock.calls.filter((call) => call[2].startsWith("ALTER "))
+ .map((call) => call[2]),
+ ).toEqual(['ALTER TABLE "APP"."SOURCE_ID_V" DROP CONSTRAINT "PK_SOURCE" KEEP INDEX', 'ALTER TABLE "APP"."SOURCE_ID_V" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("V", "ID") USING INDEX "APP"."PK_SOURCE"']);
+ expect(drafts.at(-1)).toMatchObject({ dirty: false, existingPrimaryKey: undefined });
+ });
+
+ it("hides the verified Oracle index identity when the draft no longer matches its plan", async () => {
+ const { container } = await prepareReorderedKey(false, false, "oracle");
+ expect(container.querySelector("[data-primary-key-index-identity]")).not.toBeNull();
+ (container.querySelector(`[data-existing-primary-key-editor] button[title="${i18n.global.t("oceanbasePrimaryKey.moveDown")}"]`) as HTMLButtonElement).click();
+ await nextTick();
+ expect(container.querySelector("[data-primary-key-index-identity]")).toBeNull();
+ });
+
+ it("shows the committed DROP and rejected ADD together with manual recovery", async () => {
+ const { editor } = await prepareReorderedKey(true);
+ await expect(editor.value!.applyChanges()).resolves.toBe(false);
+ await nextTick();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog?.textContent).toContain("ORA-00001");
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.committed"));
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.rejected"));
+ expect(dialog?.textContent).toContain('PRIMARY KEY ("ID", "V")');
+ expect(dialog?.querySelector("details")?.open).toBe(false);
+ });
+
+ it("deletes an existing key from its constraint card and reloads the keyless table", async () => {
+ const { editor, container, drafts } = await prepareReorderedKey(false, true);
+ expect(container.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.removeKey"));
+ expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].primaryKeyChange).toEqual({ name: "PK_SOURCE", originalColumns: ["ID", "V"], columns: [] });
+ await expect(editor.value!.applyChanges()).resolves.toBe(true);
+ const statements = vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "));
+ expect(statements.map((call) => call[2])).toEqual(['ALTER TABLE "APP"."SOURCE_ID_V" DROP CONSTRAINT "PK_SOURCE"']);
+ expect(container.textContent).not.toContain("PK_SOURCE");
+ expect(drafts.at(-1)).toMatchObject({ dirty: false, existingPrimaryKey: undefined });
+ expect(api.saveHistory).toHaveBeenCalledTimes(1);
+ await nextTick();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog?.textContent).toContain(i18n.global.t("structureEditor.saved"));
+ expect(dialog?.textContent).not.toContain(i18n.global.t("oceanbasePrimaryKey.executionFailed"));
+ expect(dialog?.textContent).toContain('ALTER TABLE "APP"."SOURCE_ID_V" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("ID", "V");');
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.recoveryNotice"));
+ expect(dialog?.querySelector("details")?.open).toBe(false);
+ });
+
+ it("reports editor refresh failure after committed DDL without losing the execution result", async () => {
+ const { editor } = await prepareReorderedKey();
+ const readColumns = vi.mocked(api.getColumns).getMockImplementation()!;
+ let postDdlReads = 0;
+ vi.mocked(api.getColumns).mockImplementation(async (...args) => {
+ const added = vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].includes(" ADD CONSTRAINT "));
+ if (added && ++postDdlReads === 2) throw new Error("column refresh unavailable");
+ return readColumns(...args);
+ });
+ const saved = await editor.value!.applyChanges();
+ expect(postDdlReads).toBe(2);
+ expect(saved).toBe(false);
+ await nextTick();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog?.textContent).toContain("column refresh unavailable");
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.committed"));
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "))).toHaveLength(2);
+ });
+
+ it.each(["cancel", "switch", "unmount"])("does not execute DDL after production confirmation %s", async (action) => {
+ const { editor, context } = await prepareReorderedKey(false, false, "oceanbase-oracle", false, true);
+ const pending = editor.value!.applyChanges();
+ const safety = useProductionSafetyStore();
+ await vi.waitFor(() => expect(safety.pending).toBeDefined());
+ if (action === "cancel") safety.cancel();
+ if (action === "switch") {
+ context.value = { ...context.value, tableName: "OTHER" };
+ await nextTick();
+ }
+ if (action === "unmount") {
+ app!.unmount();
+ app = undefined;
+ }
+ await expect(pending).resolves.toBe(false);
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].startsWith("ALTER "))).toBe(false);
+ expect(safety.pending).toBeUndefined();
+ });
+
+ it("keeps an in-flight DDL sequence and its history on the captured table after switching", async () => {
+ const { editor, context, drafts } = await prepareReorderedKey();
+ const execute = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let releaseDrop!: () => void;
+ const dropGate = new Promise<void>((resolve) => {
+ releaseDrop = resolve;
+ });
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].includes(" DROP CONSTRAINT ")) await dropGate;
+ return execute(...args);
+ });
+ const pending = editor.value!.applyChanges();
+ await vi.waitFor(() => expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].includes(" DROP CONSTRAINT "))).toBe(true));
+ context.value = { ...context.value, tableName: "OTHER" };
+ await nextTick();
+ releaseDrop();
+ await expect(pending).resolves.toBe(true);
+ const statements = vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "));
+ expect(statements).toHaveLength(2);
+ expect(statements.every((call) => call[2].includes('"APP"."SOURCE_ID_V"'))).toBe(true);
+ expect(vi.mocked(api.saveHistory).mock.calls).toHaveLength(2);
+ expect(JSON.stringify(vi.mocked(api.saveHistory).mock.calls)).not.toContain('"target":"OTHER"');
+ expect(drafts.at(-1)).toMatchObject({ dirty: false, existingPrimaryKey: undefined });
+ });
+
+ it("discards late primary key preview if connection state revision changes while query is pending", async () => {
+ let releaseBuild!: () => void;
+ let buildStarted!: () => void;
+ const buildStartedPromise = new Promise<void>((resolve) => {
+ buildStarted = resolve;
+ });
+ const buildGate = new Promise<void>((resolve) => {
+ releaseBuild = resolve;
+ });
+ const { container, editor } = await prepareReorderedKey(false, false, "oceanbase-oracle", false, false, true);
+ const store = useConnectionStore();
+ const originalBuild = vi.mocked(api.buildTableStructureChangeSql).getMockImplementation()!;
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (...args) => {
+ buildStarted();
+ await buildGate;
+ return originalBuild(...args);
+ });
+
+ // Trigger preview computation by clicking moveDown
+ (container.querySelector(`[data-existing-primary-key-editor] button[title="${i18n.global.t("oceanbasePrimaryKey.moveDown")}"]`) as HTMLButtonElement).click();
+ await buildStartedPromise;
+
+ // While query is pending, bump connection state revision
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+
+ releaseBuild();
+ await vi.waitFor(() => expect(container.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.refreshRequired")));
+ expect(await editor.value!.applyChanges()).toBe(false);
+ });
+
+ it.each(["after-preview", "during-confirmation", "during-preflight-snapshot"])("issues zero DDL when connection state changes %s", async (phase) => {
+ const { editor } = await prepareReorderedKey(false, false, "oceanbase-oracle", false, phase === "during-confirmation");
+ const store = useConnectionStore();
+
+ if (phase === "after-preview") {
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+ await expect(editor.value!.applyChanges()).resolves.toBe(false);
+ } else if (phase === "during-confirmation") {
+ const pending = editor.value!.applyChanges();
+ const safety = useProductionSafetyStore();
+ await vi.waitFor(() => expect(safety.pending).toBeDefined());
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+ safety.confirm();
+ await expect(pending).resolves.toBe(false);
+ } else if (phase === "during-preflight-snapshot") {
+ let releaseSnapshot!: () => void;
+ const snapshotGate = new Promise<void>((resolve) => {
+ releaseSnapshot = resolve;
+ });
+ const originalExecute = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let intercepted = false;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (!intercepted && args[2].includes("FROM SYS.ALL_CONSTRAINTS WHERE OWNER = 'APP' AND TABLE_NAME = 'SOURCE_ID_V' AND CONSTRAINT_TYPE = 'P'")) {
+ intercepted = true;
+ await snapshotGate;
+ }
+ return originalExecute(...args);
+ });
+ const pending = editor.value!.applyChanges();
+ await vi.waitFor(() => expect(intercepted).toBe(true));
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+ releaseSnapshot();
+ await expect(pending).resolves.toBe(false);
+ }
+
+ const statements = vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "));
+ expect(statements).toHaveLength(0);
+ });
+
+ it("marks in-flight DROP as unknown, skips ADD, and omits recovery SQL when connection is disconnected/reconfigured while DROP is pending", async () => {
+ const { editor } = await prepareReorderedKey();
+ const store = useConnectionStore();
+ const execute = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let releaseDrop!: () => void;
+ const dropGate = new Promise<void>((resolve) => {
+ releaseDrop = resolve;
+ });
+
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].includes(" DROP CONSTRAINT ")) {
+ await dropGate;
+ }
+ return execute(...args);
+ });
+
+ const pending = editor.value!.applyChanges();
+ await vi.waitFor(() => expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].includes(" DROP CONSTRAINT "))).toBe(true));
+
+ // While DROP is pending in database, connection disconnects / bumps revision
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+
+ releaseDrop();
+ await expect(pending).resolves.toBe(false);
+
+ const statements = vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "));
+ expect(statements).toHaveLength(1);
+ expect(statements[0]![2]).toContain("DROP CONSTRAINT");
+
+ await nextTick();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.unknown"));
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.notExecuted"));
+ expect(dialog?.textContent).not.toContain(i18n.global.t("oceanbasePrimaryKey.recoveryNotice"));
+ expect(dialog?.textContent).not.toContain(i18n.global.t("structureEditor.saved"));
+ });
+
+ it("keeps DROP committed and skips ADD when connection becomes invalid after DROP returns", async () => {
+ const { editor } = await prepareReorderedKey();
+ const store = useConnectionStore();
+ const execute = vi.mocked(api.executeQuery).getMockImplementation()!;
+
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ const res = await execute(...args);
+ if (args[2].includes(" DROP CONSTRAINT ")) {
+ setTimeout(async () => {
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+ }, 0);
+ }
+ return res;
+ });
+
+ await expect(editor.value!.applyChanges()).resolves.toBe(false);
+
+ const statements = vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "));
+ expect(statements).toHaveLength(1);
+ expect(statements[0]![2]).toContain("DROP CONSTRAINT");
+
+ await nextTick();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.committed"));
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.notExecuted"));
+ expect(dialog?.textContent).not.toContain(i18n.global.t("oceanbasePrimaryKey.recoveryNotice"));
+ });
+
+ it("fails save and rejects readback if connection changes during post-DDL readback", async () => {
+ const { editor } = await prepareReorderedKey();
+ const store = useConnectionStore();
+ const readConstraints = vi.mocked(api.listConstraints).getMockImplementation()!;
+
+ let ddlComplete = false;
+ vi.mocked(api.listConstraints).mockImplementation(async (...args) => {
+ if (ddlComplete) {
+ await store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ store.connectedIds.add(connection.id);
+ }
+ return readConstraints(...args);
+ });
+
+ const originalExecute = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ const res = await originalExecute(...args);
+ if (args[2].includes(" ADD CONSTRAINT ")) {
+ ddlComplete = true;
+ }
+ return res;
+ });
+
+ await expect(editor.value!.applyChanges()).resolves.toBe(false);
+
+ const statements = vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "));
+ expect(statements).toHaveLength(2);
+
+ await nextTick();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog?.textContent).toContain(i18n.global.t("oceanbasePrimaryKey.readbackFailed"));
+ expect(dialog?.textContent).not.toContain(i18n.global.t("structureEditor.saved"));
+ });
+});
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.ts
new file mode 100644
index 0000000000..6ff931486a
--- /dev/null
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleConstraints.spec.ts
@@ -0,0 +1,996 @@
+// @vitest-environment happy-dom
+import { createApp, h, nextTick, type App } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import TableStructureEditor from "../TableStructureEditor.vue";
+import i18n from "@/i18n";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import LightTooltip from "@/components/ui/LightTooltip.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
+import type { ConnectionConfig, ConstraintInfo, IndexInfo } from "@/types/database";
+import type { TableStructureEditorDraft } from "@/types/database";
+import * as api from "@/lib/backend/api";
+import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";
+
+vi.mock("@/lib/backend/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),
+ listPlugins: vi.fn().mockResolvedValue([]),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ listDataTypes: vi.fn().mockResolvedValue([]),
+ getColumns: vi.fn(),
+ listConstraints: vi.fn(),
+ listIndexes: vi.fn(),
+ listForeignKeys: vi.fn().mockResolvedValue([]),
+ listTriggers: vi.fn().mockResolvedValue([]),
+ getTableComment: vi.fn().mockResolvedValue(""),
+ getTablePartitionStatus: vi.fn().mockResolvedValue({ isPartitionedParent: false, isPartition: false, isForeign: false }),
+ getTablePartitioning: vi.fn().mockResolvedValue(null),
+ buildTableStructureChangeSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),
+ saveHistory: vi.fn().mockResolvedValue(undefined),
+ saveOpenTabsState: vi.fn().mockResolvedValue(undefined),
+ disconnectDb: vi.fn().mockResolvedValue(undefined),
+ executeQuery: vi.fn().mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 }),
+}));
+
+const connection = { id: "ob-constraint-edit", name: "OB constraint fixture", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", host: "fixture", port: 2881, username: "APP", database: "APP" } as ConnectionConfig;
+let app: App | undefined;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(api.buildTableStructureChangeSql).mockReset().mockResolvedValue({ statements: [], warnings: [] });
+ connection.db_type = "oceanbase-oracle";
+ connection.driver_profile = "oceanbase-oracle";
+ connection.is_production = false;
+ i18n.global.locale.value = "en";
+});
+
+afterEach(() => {
+ app?.unmount();
+ app = undefined;
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+
+async function mountConstraintEditor(
+ initialTab: "constraints" | "indexes" | "columns" = "constraints",
+ indexes: IndexInfo[] = [{ name: "UQ_EMAIL", columns: ["EMAIL"], is_primary: false, is_unique: true, index_type: "NORMAL" }],
+ expose?: (instance: { applyChanges: () => Promise<boolean> }) => void,
+ draft?: TableStructureEditorDraft,
+ indexCatalogConfigured = false,
+ loadedColumns?: Array<{ name: string; data_type: string; is_nullable: boolean; is_primary_key: boolean; column_default: string | null; character_maximum_length?: number }>,
+ beforeMount: (() => void) | undefined = undefined,
+ events: { drafts?: unknown[]; saved?: unknown[] } = {},
+) {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const store = useConnectionStore();
+ store.connections = [connection];
+ store.connectedIds.add(connection.id);
+ vi.mocked(api.getColumns).mockResolvedValue(
+ loadedColumns ?? [
+ { name: "EMAIL", data_type: "VARCHAR2(120 BYTE)", character_maximum_length: 120, is_nullable: true, is_primary_key: false, column_default: null },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ],
+ );
+ vi.mocked(api.listConstraints).mockResolvedValue([
+ {
+ name: "CK_AGE",
+ constraint_type: "CHECK",
+ columns: [],
+ definition: '"AGE" >= 0',
+ ref_columns: [],
+ enabled: true,
+ valid: true,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: { metadataComplete: true, owner: "APP", constraintType: "C", status: "ENABLED", validated: "VALIDATED", deferrable: "NOT DEFERRABLE", deferred: "IMMEDIATE", rely: null, indexOwner: null, indexName: null, indexSharing: null, index: null },
+ },
+ {
+ name: "UQ_EMAIL",
+ constraint_type: "UNIQUE",
+ columns: ["EMAIL"],
+ definition: "",
+ ref_columns: [],
+ enabled: true,
+ valid: true,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: {
+ metadataComplete: true,
+ owner: "APP",
+ constraintType: "U",
+ status: "ENABLED",
+ validated: "VALIDATED",
+ deferrable: "NOT DEFERRABLE",
+ deferred: "IMMEDIATE",
+ rely: null,
+ indexOwner: "APP",
+ indexName: "UQ_EMAIL",
+ indexSharing: "exclusive",
+ index: {
+ metadataComplete: true,
+ owner: "APP",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: ["EMAIL"],
+ directions: ["ASC"],
+ keyIsExpression: [false],
+ includedColumns: [],
+ },
+ },
+ },
+ ] as ConstraintInfo[]);
+ if (!indexCatalogConfigured) {
+ if (connection.db_type === "oracle" || connection.db_type === "oceanbase-oracle") configureOracleIndexCatalog();
+ vi.mocked(api.listIndexes).mockResolvedValue(indexes);
+ }
+ beforeMount?.();
+ const container = document.createElement("div");
+ document.body.append(container);
+ await invalidateObjectMetadataCache({ connectionId: connection.id });
+ app = createApp({
+ render: () =>
+ h(
+ TooltipProvider,
+ {},
+ { default: () => h(TableStructureEditor, { connectionId: connection.id, database: "APP", schema: "APP", tableName: "CONTACTS", initialTab, ref: expose, draft, "onUpdate:draft": (value: unknown) => events.drafts?.push(value), onSaved: (...args: unknown[]) => events.saved?.push(args) }) },
+ ),
+ });
+ app.use(pinia);
+ app.use(i18n);
+ app.component("LightTooltip", LightTooltip);
+ app.mount(container);
+ await vi.waitFor(() =>
+ expect(initialTab === "constraints" ? container.textContent.includes("CK_AGE") : initialTab === "indexes" ? container.querySelector("[data-index-name-input]") : initialTab === "columns" ? container.querySelector("[data-column-row-index='0']") : false, container.textContent).toBeTruthy(),
+ );
+ await nextTick();
+ return container;
+}
+
+type OracleIndexCatalogItem = { name: string; columns: string[]; unique: boolean; indexType: string; partitioned: string; visibility: string; directions: string[]; expressions: Array<string | null> };
+
+function configureOracleIndexCatalog(
+ failCreate: boolean | string = false,
+ initial: OracleIndexCatalogItem | OracleIndexCatalogItem[] = { name: "IX_EMAIL", columns: ["EMAIL"], unique: false, indexType: "NORMAL", partitioned: "NO", visibility: "VISIBLE", directions: ["ASC"], expressions: [null] },
+ indexSnapshotGate?: Promise<void>,
+ onIndexSnapshotStart?: () => void,
+) {
+ const initialIndexes = Array.isArray(initial) ? initial : [initial];
+ let catalog = [...initialIndexes];
+ let lastDroppedIndex = initialIndexes[0]!;
+ let rejectCreate = failCreate;
+ let activeIndexSnapshotGate = indexSnapshotGate;
+ const ddl: string[] = [];
+ vi.mocked(api.listIndexes).mockImplementation(async () =>
+ catalog.map(
+ (index) =>
+ ({
+ name: index.name,
+ columns: [...index.columns],
+ is_primary: false,
+ is_unique: index.unique,
+ index_type: index.indexType,
+ key_metadata_complete: true,
+ key_is_expression: index.expressions.map((expression) => expression !== null),
+ key_directions: [...index.directions],
+ visibility: index.visibility,
+ constraint_backed: false,
+ }) as IndexInfo,
+ ),
+ );
+ vi.mocked(api.executeQuery).mockImplementation(async (_connectionId, _database, sql) => {
+ if (/^\s*DROP INDEX/i.test(sql)) {
+ ddl.push(sql);
+ const name = /^\s*DROP INDEX\s+(?:"(?:APP)"\.)?"((?:""|[^"])*)"/i.exec(sql)?.[1]?.replace(/""/g, '"');
+ const dropped = catalog.find((index) => index.name === name);
+ if (dropped) lastDroppedIndex = dropped;
+ catalog = catalog.filter((index) => index.name !== name);
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 } as never;
+ }
+ if (/^\s*CREATE INDEX/i.test(sql)) {
+ ddl.push(sql);
+ const name = /^\s*CREATE\s+INDEX\s+"((?:""|[^"])*)"/i.exec(sql)?.[1]?.replace(/""/g, '"');
+ const rejected = rejectCreate === true || (typeof rejectCreate === "string" && rejectCreate === name);
+ if (!rejected && name) catalog.push({ ...lastDroppedIndex, name });
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1, execution_error: rejected, error: rejected ? { detail: "CREATE rejected" } : undefined } as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return { columns: [], rows: [["APP", "APP", "ORCL"]], affected_rows: 0, execution_time_ms: 1 } as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return { columns: [], rows: [["APP", "CONTACTS", 77]], affected_rows: 0, execution_time_ms: 1 } as never;
+ if (sql.includes("SYS.ALL_TABLES")) return { columns: [], rows: [[null, "N"]], affected_rows: 0, execution_time_ms: 1 } as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 } as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) {
+ const rows = sql.includes("USER_GENERATED")
+ ? [
+ ["EMAIL", "VARCHAR2", 120, null, null, "Y", "B", 120, "YES", "NO"],
+ ["AGE", "NUMBER", 22, null, null, "Y", null, null, "YES", "NO"],
+ ...catalog.flatMap((index) => index.expressions.flatMap((expression, position) => (expression === null ? [] : [[`SYS_NC${position + 1}$`, "VARCHAR2", 120, null, null, "Y", "B", 120, "NO", "YES"]]))),
+ ]
+ : [
+ ["EMAIL", "VARCHAR2", 120, null, null, "Y"],
+ ["AGE", "NUMBER", 22, null, null, "Y"],
+ ];
+ return { columns: [], rows, affected_rows: 0, execution_time_ms: 1 } as never;
+ }
+ if (sql.includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES"))
+ return {
+ columns: [],
+ rows: catalog
+ .map((index) => index.name)
+ .sort()
+ .map((name) => [name]),
+ affected_rows: 0,
+ execution_time_ms: 1,
+ } as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS")) {
+ onIndexSnapshotStart?.();
+ if (activeIndexSnapshotGate) await activeIndexSnapshotGate;
+ return {
+ columns: [],
+ rows: [...catalog]
+ .sort((left, right) => left.name.localeCompare(right.name))
+ .flatMap((index) =>
+ index.columns.map((column, position) => [
+ "APP",
+ index.name,
+ "APP",
+ "CONTACTS",
+ index.indexType,
+ index.unique ? "UNIQUE" : "NONUNIQUE",
+ "VALID",
+ index.partitioned === "YES" ? "YES" : "NO",
+ index.visibility,
+ "N",
+ index.expressions[position] === null ? column : `SYS_NC${position + 1}$`,
+ index.directions[position],
+ index.expressions[position],
+ ]),
+ ),
+ affected_rows: 0,
+ execution_time_ms: 1,
+ } as never;
+ }
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 } as never;
+ throw new Error(`Unhandled Oracle index fixture query: ${sql}`);
+ });
+ return {
+ ddl,
+ setCatalog: (value: typeof catalog) => (catalog = value),
+ setRejectCreate: (value: boolean | string) => (rejectCreate = value),
+ setIndexSnapshotGate: (value: Promise<void> | undefined, onStart?: () => void) => {
+ activeIndexSnapshotGate = value;
+ onIndexSnapshotStart = onStart;
+ },
+ };
+}
+
+describe("Oracle CHECK and UNIQUE entry points", () => {
+ it("opens a delete draft without executing SQL", async () => {
+ const container = await mountConstraintEditor();
+ const deleteCheck = container.querySelector<HTMLButtonElement>('[data-constraint-delete="CK_AGE"]');
+ expect(deleteCheck).toBeTruthy();
+ const queryCount = vi.mocked(api.executeQuery).mock.calls.length;
+ deleteCheck!.click();
+ await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="CK_AGE"]')).toBeTruthy());
+ expect(vi.mocked(api.executeQuery).mock.calls.length).toBe(queryCount);
+ });
+
+ it("opens a new CHECK draft from the constraints toolbar", async () => {
+ const container = await mountConstraintEditor();
+ const addCheck = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Add CHECK Constraint"));
+ expect(addCheck).toBeTruthy();
+ addCheck!.click();
+ await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="new"]')).toBeTruthy());
+ });
+
+ it("opens a new UNIQUE draft from the constraints toolbar", async () => {
+ const container = await mountConstraintEditor();
+ const addUnique = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Add UNIQUE Constraint"));
+ expect(addUnique).toBeTruthy();
+ addUnique!.click();
+ await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="new"]')).toBeTruthy());
+ });
+
+ it("opens the CHECK editor from its constraint card", async () => {
+ const container = await mountConstraintEditor();
+ const checkEdit = container.querySelector<HTMLButtonElement>('[aria-label="Edit constraint CK_AGE"]');
+ expect(checkEdit).toBeTruthy();
+ checkEdit!.click();
+ await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="CK_AGE"]')).toBeTruthy());
+ });
+
+ it.each(["history", "refresh", "same-session"] as const)("handles CHECK results correctly when the connection is %s", async (pendingAt) => {
+ let dropped = false;
+ let componentRefreshStarted = false;
+ let historySaved = false;
+ let releaseHistory!: () => void;
+ let releaseRefresh!: () => void;
+ let refreshStarted!: () => void;
+ const refreshStartedPromise = new Promise<void>((resolve) => (refreshStarted = resolve));
+ const check = {
+ name: "CK_AGE",
+ constraint_type: "CHECK",
+ columns: [],
+ definition: '"AGE" >= 0',
+ ref_columns: [],
+ enabled: true,
+ valid: true,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: { metadataComplete: true, owner: "APP", constraintType: "C", status: "ENABLED", validated: "VALIDATED", deferrable: "NOT DEFERRABLE", deferred: "IMMEDIATE", rely: null, indexOwner: null, indexName: null, indexSharing: null, index: null },
+ } as ConstraintInfo;
+ const beforeMount = () => {
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (options) => ({ statements: options.oracleConstraintChanges?.length ? ['ALTER TABLE "APP"."CONTACTS" DROP CONSTRAINT "CK_AGE";'] : [], warnings: [] }) as never);
+ vi.mocked(api.getColumns).mockImplementation(async () => {
+ if (dropped && pendingAt === "refresh") {
+ componentRefreshStarted = true;
+ }
+ return [
+ { name: "EMAIL", data_type: "VARCHAR2(120 BYTE)", character_maximum_length: 120, is_nullable: true, is_primary_key: false, column_default: null },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ];
+ });
+ vi.mocked(api.listConstraints).mockImplementation(async () => {
+ if (dropped) {
+ if (pendingAt === "refresh" && componentRefreshStarted) {
+ refreshStarted();
+ return new Promise((resolve) => {
+ releaseRefresh = () => resolve([] as never);
+ });
+ }
+ return [];
+ }
+ return [check];
+ });
+ vi.mocked(api.saveHistory).mockImplementation(async () => {
+ if (pendingAt === "history") await new Promise<void>((resolve) => (releaseHistory = resolve));
+ historySaved = true;
+ });
+ const baseExecute = vi.mocked(api.executeQuery).getMockImplementation();
+ vi.mocked(api.executeQuery).mockImplementation(async (connectionId, database, sql, schema, bindValues, options) => {
+ if (sql.startsWith("ALTER TABLE") && sql.includes('DROP CONSTRAINT "CK_AGE"')) {
+ dropped = true;
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 } as never;
+ }
+ return baseExecute!(connectionId, database, sql, schema, bindValues, options);
+ });
+ };
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ const drafts: unknown[] = [];
+ const saved: unknown[] = [];
+ const container = await mountConstraintEditor("constraints", undefined, (instance) => (editor = instance), undefined, false, undefined, beforeMount, { drafts, saved });
+ const store = useConnectionStore();
+ const deleteCheck = container.querySelector<HTMLButtonElement>('[data-constraint-delete="CK_AGE"]');
+ expect(deleteCheck).toBeTruthy();
+ deleteCheck!.click();
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.some(([options]) => options.oracleConstraintChanges?.length)).toBe(true));
+ const draftUpdatesBeforeSave = drafts.length;
+
+ const pendingSave = editor!.applyChanges();
+ if (pendingAt === "history") await vi.waitFor(() => expect(api.saveHistory).toHaveBeenCalled());
+ else if (pendingAt === "refresh") {
+ await refreshStartedPromise;
+ expect(historySaved).toBe(true);
+ }
+ if (pendingAt !== "same-session") {
+ const disconnecting = store.disconnect(connection.id, { skipTabHandling: true, markClosedByUser: false });
+ if (pendingAt === "history") releaseHistory();
+ else releaseRefresh();
+ await disconnecting;
+ }
+ const outcome = await pendingSave;
+
+ if (pendingAt === "same-session") {
+ expect(outcome).toBe(true);
+ expect(saved).toEqual([[false]]);
+ expect(drafts.length).toBeGreaterThan(draftUpdatesBeforeSave);
+ expect(container.querySelector('[data-constraint-delete="CK_AGE"]')).toBeNull();
+ } else {
+ expect(outcome).toBe(false);
+ expect(saved).toEqual([]);
+ expect(drafts).toHaveLength(draftUpdatesBeforeSave);
+ }
+ });
+
+ it("opens the UNIQUE editor from its constraint card", async () => {
+ const container = await mountConstraintEditor();
+ const uniqueEdit = container.querySelector<HTMLButtonElement>('[aria-label="Edit constraint UQ_EMAIL"]');
+ expect(uniqueEdit).toBeTruthy();
+ uniqueEdit!.click();
+ await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="UQ_EMAIL"]')).toBeTruthy());
+ });
+
+ it("opens the same UNIQUE draft from its paired index entry", async () => {
+ const container = await mountConstraintEditor("indexes");
+ await vi.waitFor(() => expect(container.querySelector("[data-index-name-input]")).toBeTruthy());
+
+ const editConstraint = container.querySelector<HTMLButtonElement>('[data-paired-unique-constraint="UQ_EMAIL"]');
+ expect(editConstraint).toBeTruthy();
+ editConstraint!.click();
+ await vi.waitFor(() => expect(container.querySelector('[data-constraint-editor="UQ_EMAIL"]')).toBeTruthy());
+ });
+
+ it("passes loaded Oracle key metadata through the index rebuild preview", async () => {
+ connection.db_type = "oracle";
+ connection.driver_profile = "oracle";
+ const container = await mountConstraintEditor("indexes", [
+ {
+ name: "IX_EVENT_EXPR",
+ columns: ["LOWER(EVENT_NAME)", "EVENT_TS"],
+ is_primary: false,
+ is_unique: false,
+ index_type: "FUNCTION-BASED NORMAL",
+ key_is_expression: [true, false],
+ key_directions: ["DESC", "ASC"],
+ visibility: "INVISIBLE",
+ key_metadata_complete: true,
+ } as unknown as IndexInfo,
+ ]);
+ const input = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;
+ input.value = "IX_EVENT_EXPR_RENAMED";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+
+ await vi.waitFor(() => {
+ const options = vi.mocked(api.buildTableStructureChangeSql).mock.calls.map(([value]) => value);
+ expect(options.some((value) => value.indexes?.[0]?.name === "IX_EVENT_EXPR_RENAMED")).toBe(true);
+ });
+ const options = vi
+ .mocked(api.buildTableStructureChangeSql)
+ .mock.calls.map(([value]) => value)
+ .find((value) => value.indexes?.[0]?.name === "IX_EVENT_EXPR_RENAMED")!;
+ expect(options.indexes?.[0]?.original).toMatchObject({
+ key_is_expression: [true, false],
+ key_directions: ["DESC", "ASC"],
+ visibility: "INVISIBLE",
+ });
+ });
+});
+
+describe("Oracle independent index execution", () => {
+ const loadedIndex = {
+ name: "IX_EMAIL",
+ columns: ["EMAIL"],
+ is_primary: false,
+ is_unique: false,
+ index_type: "NORMAL",
+ key_metadata_complete: true,
+ key_is_expression: [false],
+ key_directions: ["ASC"],
+ visibility: "VISIBLE",
+ constraint_backed: false,
+ } as IndexInfo;
+
+ async function prepareRename(
+ failCreate = false,
+ index: IndexInfo = loadedIndex,
+ initialCatalog = { name: "IX_EMAIL", columns: ["EMAIL"], unique: false, indexType: "NORMAL", partitioned: "NO", visibility: "VISIBLE", directions: ["ASC"], expressions: [null] as Array<string | null> },
+ expose?: (instance: { applyChanges: () => Promise<boolean> }) => void,
+ initialTab: "constraints" | "indexes" | "columns" = "indexes",
+ draft?: TableStructureEditorDraft,
+ loadedColumns?: Array<{ name: string; data_type: string; is_nullable: boolean; is_primary_key: boolean; column_default: string | null; character_maximum_length?: number }>,
+ indexSnapshotGate?: Promise<void>,
+ onIndexSnapshotStart?: () => void,
+ ) {
+ connection.db_type = "oracle";
+ connection.driver_profile = "oracle";
+ const fixture = configureOracleIndexCatalog(failCreate, initialCatalog, indexSnapshotGate, onIndexSnapshotStart);
+ const container = await mountConstraintEditor(initialTab, [index], expose, draft, true, loadedColumns);
+ configureIndexRenamePreview();
+ const input = container.querySelector<HTMLInputElement>("[data-index-name-input]");
+ if (input) {
+ input.value = "IX_EMAIL_RENAMED";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ if (input) await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.length).toBeGreaterThan(0));
+ return { container, fixture };
+ }
+
+ function configureIndexRenamePreview() {
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (options) => {
+ const draft = options.indexes?.[0];
+ const targetName = draft?.name || "IX_EMAIL_RENAMED";
+ const original = draft?.original;
+ const keys = (draft?.columns || ["EMAIL"])
+ .map((column) => {
+ const originalPosition = original?.columns.indexOf(column) ?? -1;
+ const expression = originalPosition >= 0 && original?.key_is_expression?.[originalPosition] ? column : `"${column}"`;
+ const direction = originalPosition >= 0 ? original?.key_directions?.[originalPosition] || "ASC" : "ASC";
+ return `${expression} ${direction}`;
+ })
+ .join(", ");
+ const visibility = original?.visibility === "INVISIBLE" ? " INVISIBLE" : "";
+ const create = `CREATE ${draft?.isUnique ? "UNIQUE " : ""}INDEX "${targetName}" ON "APP"."CONTACTS" (${keys})${visibility};`;
+ return {
+ statements: original && !draft?.oracleOriginalMissing ? [`DROP INDEX "APP"."${original.name}";`, create] : [create],
+ warnings: [],
+ } as never;
+ });
+ }
+
+ it("compares the loaded original before the first DDL", async () => {
+ const { container, fixture } = await prepareRename();
+ fixture.setCatalog([{ name: "IX_EMAIL", columns: ["AGE"], unique: false, indexType: "NORMAL", partitioned: "NO", visibility: "VISIBLE", directions: ["ASC"], expressions: [null] }]);
+
+ const apply = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Apply"))!;
+ apply.click();
+
+ await vi.waitFor(() => expect(container.textContent).toContain("Index metadata changed"));
+ expect(fixture.ddl).toEqual([]);
+ });
+
+ it("does not publish a ready baseline when loaded columns disagree with the dictionary snapshot", async () => {
+ connection.is_production = true;
+ const { container, fixture } = await prepareRename(false, loadedIndex, undefined, undefined, "indexes", undefined, [
+ { name: "EMAIL", data_type: "VARCHAR2(121 BYTE)", character_maximum_length: 121, is_nullable: true, is_primary_key: false, column_default: null },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ]);
+ await vi.waitFor(() => expect(vi.mocked(api.executeQuery).mock.calls.some(([, , sql]) => sql.includes("SYS.ALL_IND_COLUMNS"))).toBe(true));
+
+ const apply = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Apply"))!;
+ apply.click();
+
+ await vi.waitFor(() => expect(container.textContent).toContain("not ready for a safe save"));
+ expect(useProductionSafetyStore().pending).toBeUndefined();
+ expect(fixture.ddl).toEqual([]);
+ });
+
+ it("blocks an index rebuild mixed with a column change", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ const originalColumn = { name: "EMAIL", data_type: "VARCHAR2(120)", is_nullable: true, is_primary_key: false, column_default: null };
+ const columnDraft = { id: "EMAIL", name: "EMAIL", dataType: "VARCHAR2(120)", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, original: originalColumn, markedForDrop: false };
+ const indexDraft = { id: "IX_EMAIL", name: "IX_EMAIL_RENAMED", columns: ["EMAIL"], isUnique: false, isPrimary: false, filter: "", indexType: "NORMAL", includedColumns: [], comment: "", original: loadedIndex, markedForDrop: false };
+ const draft = {
+ dirty: true,
+ activeTab: "columns",
+ newTableName: "",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [columnDraft],
+ indexes: [indexDraft],
+ foreignKeys: [],
+ triggers: [],
+ loadedMetadataFacets: ["columns", "indexes"],
+ initialized: true,
+ } as unknown as TableStructureEditorDraft;
+ const container = await mountConstraintEditor(
+ "columns",
+ [loadedIndex],
+ (instance) => {
+ editor = instance;
+ },
+ draft,
+ );
+ const fixture = configureOracleIndexCatalog();
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: ['ALTER TABLE "CONTACTS" MODIFY "EMAIL" NOT NULL;', 'DROP INDEX "IX_EMAIL";', 'CREATE INDEX "IX_EMAIL_RENAMED" ON "APP"."CONTACTS" ("EMAIL" ASC);'], warnings: [] } as never);
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.length).toBeGreaterThan(0));
+
+ expect(await editor!.applyChanges()).toBe(false);
+ expect(container.textContent).toContain("Apply Oracle-family index changes separately");
+ expect(fixture.ddl).toEqual([]);
+ });
+
+ it("does not replay DROP after CREATE rejection until refreshed", async () => {
+ const { container, fixture } = await prepareRename(true);
+ const apply = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Apply"))!;
+ apply.click();
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(2));
+ await vi.waitFor(() => expect(document.body.textContent).toContain("CREATE rejected"));
+
+ const refresh = container.querySelector<HTMLButtonElement>("[data-refresh-structure-shortcut]")!;
+ refresh.click();
+ await vi.waitFor(() => expect(vi.mocked(api.listIndexes).mock.calls.length).toBeGreaterThan(1));
+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED"));
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.some(([options]) => options.indexes?.some((index) => index.name === "IX_EMAIL_RENAMED" && index.oracleOriginalMissing && index.original?.name === "IX_EMAIL"))).toBe(true));
+ fixture.setRejectCreate(false);
+ apply.click();
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(3));
+ expect(fixture.ddl[2]).toMatch(/^CREATE INDEX/);
+ });
+
+ it("recreates a missing index when the user restores its original definition", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ const { container, fixture } = await prepareRename(true, loadedIndex, undefined, (instance) => {
+ editor = instance;
+ });
+ const apply = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Apply"))!;
+ apply.click();
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(2));
+
+ const close = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === "Close");
+ close?.click();
+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
+ await nextTick();
+ expect(Array.from(container.querySelectorAll<HTMLElement>("[role=tab]")).find((tab) => tab.getAttribute("aria-selected") === "true")?.textContent).toContain("Indexes");
+ const refresh = container.querySelector<HTMLButtonElement>("[data-refresh-structure-shortcut]")!;
+ expect(refresh.disabled).toBe(false);
+ refresh.click();
+ await vi.waitFor(() => expect(vi.mocked(api.listIndexes).mock.calls.length).toBeGreaterThan(1));
+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED"));
+ const input = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;
+ const buildCallsBeforeRenameBack = vi.mocked(api.buildTableStructureChangeSql).mock.calls.length;
+ input.value = "IX_EMAIL";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.length).toBeGreaterThan(buildCallsBeforeRenameBack));
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.at(-1)?.[0].indexes?.[0]).toMatchObject({ name: "IX_EMAIL", oracleOriginalMissing: true }));
+ await vi.waitFor(() => expect(container.textContent).toContain('CREATE INDEX "IX_EMAIL"'));
+ fixture.setRejectCreate(false);
+
+ const indexReadsBeforeRestore = vi.mocked(api.listIndexes).mock.calls.length;
+ const restored = await editor!.applyChanges();
+ expect(restored).toBe(true);
+ expect(vi.mocked(api.listIndexes).mock.calls.length).toBe(indexReadsBeforeRestore + 1);
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(3));
+ expect(fixture.ddl[2]).toMatch(/^CREATE INDEX "IX_EMAIL"/);
+ });
+
+ it("retains function-key and INVISIBLE metadata after a partial rename and refresh", async () => {
+ const functionIndex = {
+ ...loadedIndex,
+ columns: ["LOWER(EMAIL)"],
+ index_type: "FUNCTION-BASED NORMAL",
+ key_is_expression: [true],
+ key_directions: ["ASC"],
+ visibility: "INVISIBLE",
+ } as IndexInfo;
+ const initialCatalog = {
+ name: "IX_EMAIL",
+ columns: ["LOWER(EMAIL)"],
+ unique: false,
+ indexType: "FUNCTION-BASED NORMAL",
+ partitioned: "NO",
+ visibility: "INVISIBLE",
+ directions: ["ASC"],
+ expressions: ["LOWER(EMAIL)"],
+ };
+ const { container, fixture } = await prepareRename(true, functionIndex, initialCatalog);
+ const apply = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Apply"))!;
+ apply.click();
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(2));
+
+ const close = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === "Close");
+ close?.click();
+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
+ await nextTick();
+ expect(Array.from(container.querySelectorAll<HTMLElement>("[role=tab]")).find((tab) => tab.getAttribute("aria-selected") === "true")?.textContent).toContain("Indexes");
+ const refresh = container.querySelector<HTMLButtonElement>("[data-refresh-structure-shortcut]")!;
+ expect(refresh.disabled).toBe(false);
+ refresh.click();
+ await vi.waitFor(() => expect(vi.mocked(api.listIndexes).mock.calls.length).toBeGreaterThan(1));
+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED"));
+ const retryDraft = vi
+ .mocked(api.buildTableStructureChangeSql)
+ .mock.calls.map(([options]) => options.indexes?.[0])
+ .find((index) => index?.oracleOriginalMissing);
+ expect(retryDraft?.original).toMatchObject({ key_is_expression: [true], key_directions: ["ASC"], visibility: "INVISIBLE" });
+
+ fixture.setRejectCreate(false);
+ apply.click();
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(3));
+ expect(fixture.ddl[2]).toContain("LOWER(EMAIL) ASC");
+ expect(fixture.ddl[2]).toContain("INVISIBLE");
+ expect(fixture.ddl[2]).not.toMatch(/^DROP INDEX/);
+ });
+
+ it("rejects a column type change made while production confirmation is pending", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ connection.is_production = true;
+ const { container, fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {
+ editor = instance;
+ });
+ const pending = editor!.applyChanges();
+ const safety = useProductionSafetyStore();
+ await vi.waitFor(() => expect(safety.pending, container.textContent).toBeDefined());
+ const columnsTab = Array.from(container.querySelectorAll<HTMLElement>("[role=tab]")).find((tab) => tab.textContent?.includes("Columns"));
+ expect(columnsTab).toBeTruthy();
+ container.querySelector<HTMLElement>('[role=tab][aria-selected="true"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));
+ await vi.waitFor(() => expect(columnsTab!.getAttribute("aria-selected")).toBe("true"));
+ await vi.waitFor(() => expect(container.querySelector("[data-column-row-index='0']")).toBeTruthy());
+ const typeTrigger = container.querySelector<HTMLElement>("[data-column-row-index='0'] .dbx-searchable-select-trigger");
+ expect(typeTrigger).toBeTruthy();
+ typeTrigger!.click();
+ await vi.waitFor(() => expect(document.querySelector(".dbx-searchable-select-list")).toBeTruthy());
+ const searchInput = document.querySelector<HTMLInputElement>(".dbx-searchable-select-list")?.parentElement?.querySelector("input");
+ expect(searchInput).toBeTruthy();
+ const setInputValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ setInputValue?.call(searchInput, "VARCHAR2(40 CHAR)");
+ searchInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ const customOption = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.title === "VARCHAR2(40 CHAR)");
+ expect(customOption).toBeTruthy();
+ customOption!.click();
+ await nextTick();
+ expect(container.querySelector<HTMLInputElement>("[data-column-row-index='0'] input")?.value).toBe("EMAIL");
+ expect(Array.from(container.querySelectorAll<HTMLInputElement>("[data-column-row-index='0'] input")).map((input) => input.value)).toContain("40");
+ expect(container.querySelector("[data-column-row-index='0']")?.textContent).toContain("CHAR");
+ safety.confirm();
+ await expect(pending).resolves.toBe(false);
+ expect(fixture.ddl).toEqual([]);
+ });
+
+ it("retains a dirty column draft when the Indexes tab lazily refreshes metadata", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ const { container, fixture } = await prepareRename(
+ false,
+ loadedIndex,
+ undefined,
+ (instance) => {
+ editor = instance;
+ },
+ "columns",
+ );
+ const typeTrigger = container.querySelector<HTMLElement>("[data-column-row-index='0'] .dbx-searchable-select-trigger")!;
+ typeTrigger.click();
+ await vi.waitFor(() => expect(document.querySelector(".dbx-searchable-select-list")).toBeTruthy());
+ const searchInput = document.querySelector(".dbx-searchable-select-list")!.parentElement!.querySelector<HTMLInputElement>("input")!;
+ const setInputValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ setInputValue?.call(searchInput, "VARCHAR2(40 CHAR)");
+ searchInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ Array.from(document.querySelectorAll<HTMLButtonElement>("button"))
+ .find((button) => button.title === "VARCHAR2(40 CHAR)")!
+ .click();
+ await nextTick();
+ const indexesTab = Array.from(container.querySelectorAll<HTMLElement>("[role=tab]")).find((tab) => tab.textContent?.includes("Indexes"))!;
+ container.querySelector<HTMLElement>("[role=tab][aria-selected=true]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
+ await vi.waitFor(() => expect(indexesTab.getAttribute("aria-selected")).toBe("true"));
+ await vi.waitFor(() => expect(container.querySelector("[data-index-name-input]")).toBeTruthy());
+ container.querySelector<HTMLElement>("[role=tab][aria-selected=true]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));
+ await vi.waitFor(() => expect(Array.from(container.querySelectorAll<HTMLInputElement>("[data-column-row-index='0'] input")).map((input) => input.value)).toContain("40"));
+ container.querySelector<HTMLElement>("[role=tab][aria-selected=true]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
+ await vi.waitFor(() => expect(indexesTab.getAttribute("aria-selected")).toBe("true"));
+ const indexName = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;
+ indexName.value = "IX_EMAIL_RENAMED";
+ indexName.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.some(([options]) => options.indexes?.[0]?.name === "IX_EMAIL_RENAMED")).toBe(true));
+ expect(await editor!.applyChanges()).toBe(false);
+ expect(fixture.ddl).toEqual([]);
+ });
+
+ it("invalidates confirmation eligibility while a columns-only refresh is pending", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ connection.is_production = true;
+ const { container, fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {
+ editor = instance;
+ });
+ container.querySelector<HTMLElement>("[role=tab][aria-selected=true]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));
+ await vi.waitFor(() => expect(container.querySelector("[data-column-row-index='0']")).toBeTruthy());
+ let releaseColumns!: () => void;
+ const columnsGate = new Promise<void>((resolve) => {
+ releaseColumns = resolve;
+ });
+ vi.mocked(api.getColumns).mockImplementationOnce(async () => {
+ await columnsGate;
+ return [
+ { name: "EMAIL", data_type: "VARCHAR2(120 BYTE)", character_maximum_length: 120, is_nullable: true, is_primary_key: false, column_default: null },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ] as never;
+ });
+ useQueryStore().invalidateTableStructure(connection.id, "APP", "APP", "CONTACTS");
+ await vi.waitFor(() => expect(releaseColumns).toBeTypeOf("function"));
+
+ expect(await editor!.applyChanges()).toBe(false);
+ expect(useProductionSafetyStore().pending).toBeUndefined();
+ expect(fixture.ddl).toEqual([]);
+ releaseColumns();
+ });
+
+ it("blocks Apply until the index snapshot request finishes, then allows the same draft", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ let snapshotStarted!: () => void;
+ let releaseSnapshot!: () => void;
+ const snapshotStartedPromise = new Promise<void>((resolve) => {
+ snapshotStarted = resolve;
+ });
+ const snapshotGate = new Promise<void>((resolve) => {
+ releaseSnapshot = resolve;
+ });
+ connection.db_type = "oracle";
+ connection.driver_profile = "oracle";
+ connection.is_production = true;
+ const fixture = configureOracleIndexCatalog(false, undefined, snapshotGate, snapshotStarted);
+ const container = await mountConstraintEditor(
+ "constraints",
+ undefined,
+ (instance) => {
+ editor = instance;
+ },
+ undefined,
+ true,
+ );
+ configureIndexRenamePreview();
+ await vi.waitFor(() => expect(container.querySelector<HTMLButtonElement>("[data-refresh-structure-shortcut]")?.disabled).toBe(false));
+ const indexesTab = Array.from(container.querySelectorAll<HTMLElement>("[role=tab]")).find((tab) => tab.textContent?.includes("Indexes"));
+ expect(indexesTab).toBeTruthy();
+ container.querySelector<HTMLElement>('[role=tab][aria-selected="true"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));
+ await vi.waitFor(() => expect(Array.from(container.querySelectorAll<HTMLElement>("[role=tab]")).find((tab) => tab.getAttribute("aria-selected") === "true")?.textContent).toContain("Foreign Keys"));
+ container.querySelector<HTMLElement>('[role=tab][aria-selected="true"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }));
+ await vi.waitFor(() => expect(indexesTab!.getAttribute("aria-selected")).toBe("true"));
+ await Promise.race([snapshotStartedPromise, new Promise<void>((_, reject) => setTimeout(() => reject(new Error(`index snapshot did not start after lazy tab load; listIndexes=${vi.mocked(api.listIndexes).mock.calls.length}`)), 1500))]);
+ expect(container.querySelector("[data-index-name-input]")).toBeTruthy();
+ const indexName = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;
+ const previewsBeforeEdit = vi.mocked(api.buildTableStructureChangeSql).mock.calls.length;
+ indexName.value = "IX_EMAIL_RENAMED";
+ indexName.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() =>
+ expect(
+ vi
+ .mocked(api.buildTableStructureChangeSql)
+ .mock.calls.slice(previewsBeforeEdit)
+ .some(([options]) => options.indexes?.[0]?.name === "IX_EMAIL_RENAMED"),
+ ).toBe(true),
+ );
+ await vi.waitFor(() => expect(Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Apply Changes"))?.disabled).toBe(false));
+ expect(await editor!.applyChanges()).toBe(false);
+ expect(useProductionSafetyStore().pending).toBeUndefined();
+ expect(fixture.ddl).toEqual([]);
+ expect(container.textContent).toContain("Index metadata is not ready for a safe save");
+ releaseSnapshot();
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ const safety = useProductionSafetyStore();
+ const applying = editor!.applyChanges();
+ const applyResult = await Promise.race([applying.then((result) => ({ result })), new Promise<{ timeout: true }>((resolve) => setTimeout(() => resolve({ timeout: true }), 5000))]);
+ expect(safety.pending, `post-release apply outcome=${JSON.stringify(applyResult)}; message=${container.textContent}`).toBeDefined();
+ safety.confirm();
+ await expect(applying).resolves.toBe(true);
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(2));
+ expect(container.textContent).not.toContain("Index metadata is not ready for a safe save");
+ });
+
+ it("does not replace a dirty restored column draft during background cache revalidation", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ let revalidationStarted!: () => void;
+ let releaseRevalidation!: () => void;
+ const started = new Promise<void>((resolve) => {
+ revalidationStarted = resolve;
+ });
+ const gate = new Promise<void>((resolve) => {
+ releaseRevalidation = resolve;
+ });
+ const originalColumn = { name: "EMAIL", data_type: "VARCHAR2(120 BYTE)", character_maximum_length: 120, is_nullable: true, is_primary_key: false, column_default: null };
+ const draft = {
+ dirty: false,
+ activeTab: "columns",
+ newTableName: "",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [{ id: "EMAIL", name: "EMAIL", dataType: "VARCHAR2(120 BYTE)", isNullable: true, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, original: originalColumn, markedForDrop: false }],
+ indexes: [{ id: "IX_EMAIL", name: "IX_EMAIL", columns: ["EMAIL"], isUnique: false, isPrimary: false, filter: "", indexType: "NORMAL", includedColumns: [], comment: "", original: loadedIndex, markedForDrop: false }],
+ foreignKeys: [],
+ triggers: [],
+ loadedMetadataFacets: ["columns", "indexes", "comment"],
+ initialized: true,
+ } as unknown as TableStructureEditorDraft;
+ const fixture = configureOracleIndexCatalog();
+ const container = await mountConstraintEditor(
+ "columns",
+ [loadedIndex],
+ (instance) => {
+ editor = instance;
+ },
+ draft,
+ true,
+ undefined,
+ () => {
+ vi.mocked(api.getColumns).mockImplementationOnce(async () => {
+ revalidationStarted();
+ await gate;
+ return [
+ { ...originalColumn, data_type: "VARCHAR2(80 BYTE)", character_maximum_length: 80 },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ] as never;
+ });
+ },
+ );
+ await started;
+ const typeTrigger = container.querySelector<HTMLElement>("[data-column-row-index='0'] .dbx-searchable-select-trigger")!;
+ typeTrigger.click();
+ await vi.waitFor(() => expect(document.querySelector(".dbx-searchable-select-list")).toBeTruthy());
+ const searchInput = document.querySelector(".dbx-searchable-select-list")!.parentElement!.querySelector<HTMLInputElement>("input")!;
+ const setInputValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
+ setInputValue?.call(searchInput, "VARCHAR2(40 CHAR)");
+ searchInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ Array.from(document.querySelectorAll<HTMLButtonElement>("button"))
+ .find((button) => button.title === "VARCHAR2(40 CHAR)")!
+ .click();
+ await nextTick();
+ releaseRevalidation();
+ await vi.waitFor(() => expect(vi.mocked(api.saveSchemaCache).mock.calls.length).toBeGreaterThan(0));
+ expect(Array.from(container.querySelectorAll<HTMLInputElement>("[data-column-row-index='0'] input")).map((input) => input.value)).toContain("40");
+
+ expect(await editor!.applyChanges()).toBe(false);
+ expect(fixture.ddl).toEqual([]);
+ });
+
+ it("ignores a late failed column request after a newer refresh publishes its baseline", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ connection.is_production = true;
+ const { container, fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {
+ editor = instance;
+ });
+ const queryStore = useQueryStore();
+ let newerSnapshotStarted!: () => void;
+ const newerSnapshotStartedPromise = new Promise<void>((resolve) => {
+ newerSnapshotStarted = resolve;
+ });
+ fixture.setIndexSnapshotGate(undefined, newerSnapshotStarted);
+ let rejectOldColumns!: (error: Error) => void;
+ let oldColumnsStarted!: () => void;
+ const oldStarted = new Promise<void>((resolve) => {
+ oldColumnsStarted = resolve;
+ });
+ vi.mocked(api.getColumns).mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectOldColumns = reject;
+ oldColumnsStarted();
+ }) as never,
+ );
+ const callsBeforeOld = vi.mocked(api.getColumns).mock.calls.length;
+ queryStore.invalidateTableStructure(connection.id, "APP", "APP", "CONTACTS");
+ await oldStarted;
+ await invalidateObjectMetadataCache({ connectionId: connection.id, database: "APP", schema: "APP", tableName: "CONTACTS" });
+ vi.mocked(api.getColumns).mockResolvedValueOnce([
+ { name: "EMAIL", data_type: "VARCHAR2(120 BYTE)", character_maximum_length: 120, is_nullable: true, is_primary_key: false, column_default: null },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ]);
+ queryStore.invalidateTableStructure(connection.id, "APP", "APP", "CONTACTS");
+ await vi.waitFor(() => expect(vi.mocked(api.getColumns).mock.calls.length).toBeGreaterThan(callsBeforeOld + 1));
+ await newerSnapshotStartedPromise;
+ await vi.waitFor(() => expect(Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("Add Index"))?.disabled).toBe(false));
+ await vi.waitFor(() => expect(container.querySelector<HTMLButtonElement>("[data-refresh-structure-shortcut]")?.disabled).toBe(false));
+
+ const indexName = container.querySelector<HTMLInputElement>("[data-index-name-input]")!;
+ const previewsBeforeEdit = vi.mocked(api.buildTableStructureChangeSql).mock.calls.length;
+ indexName.value = "IX_EMAIL_RENAMED";
+ indexName.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() =>
+ expect(
+ vi
+ .mocked(api.buildTableStructureChangeSql)
+ .mock.calls.slice(previewsBeforeEdit)
+ .some(([options]) => options.indexes?.[0]?.name === "IX_EMAIL_RENAMED"),
+ ).toBe(true),
+ );
+ const applying = editor!.applyChanges();
+ const safety = useProductionSafetyStore();
+ await vi.waitFor(() => expect(safety.pending).toBeDefined());
+
+ rejectOldColumns(new Error("stale columns request failed"));
+ await nextTick();
+ expect(container.textContent).not.toContain("stale columns request failed");
+ expect(safety.pending).toBeDefined();
+ safety.confirm();
+ await expect(applying).resolves.toBe(true);
+ await vi.waitFor(() => expect(fixture.ddl).toHaveLength(2));
+ expect(fixture.ddl).toHaveLength(2);
+ expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED");
+ });
+
+ it("returns false and preserves the index draft when post-DDL column readback mismatches", async () => {
+ let editor: { applyChanges: () => Promise<boolean> } | undefined;
+ const { container, fixture } = await prepareRename(false, loadedIndex, undefined, (instance) => {
+ editor = instance;
+ });
+ vi.mocked(api.getColumns).mockResolvedValueOnce([
+ { name: "EMAIL", data_type: "VARCHAR2(121 BYTE)", character_maximum_length: 121, is_nullable: true, is_primary_key: false, column_default: null },
+ { name: "AGE", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },
+ ]);
+
+ expect(await editor!.applyChanges()).toBe(false);
+ expect(fixture.ddl).toHaveLength(2);
+ expect(container.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("IX_EMAIL_RENAMED");
+ expect(document.body.textContent).toContain("committed");
+ expect(document.body.textContent).toContain("Readback failed or did not match the intended result");
+ });
+});
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.ts
new file mode 100644
index 0000000000..9c10af9769
--- /dev/null
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.ts
@@ -0,0 +1,327 @@
+// @vitest-environment happy-dom
+import { createApp, h, ref, type App } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import TableStructureEditor from "../TableStructureEditor.vue";
+import i18n from "@/i18n";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import LightTooltip from "@/components/ui/LightTooltip.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";
+import type { ConnectionConfig } from "@/types/database";
+import * as api from "@/lib/backend/api";
+
+vi.mock("@/lib/backend/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),
+ listPlugins: vi.fn().mockResolvedValue([]),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ listDataTypes: vi.fn().mockResolvedValue([]),
+ getColumns: vi.fn(async (_id, _database, _schema, table) => (table === "SOURCE" ? ["A", "B"] : ["ID", "V"]).map((name) => ({ name, data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null }))),
+ listConstraints: vi.fn().mockResolvedValue([]),
+ listIndexes: vi.fn().mockResolvedValue([]),
+ listForeignKeys: vi.fn().mockResolvedValue([
+ { name: "FK_SOURCE", column: "A", ref_schema: "PARENT_OWNER", ref_table: "PARENT", ref_column: "ID", on_delete: "CASCADE", on_update: null },
+ { name: "FK_SOURCE", column: "B", ref_schema: "PARENT_OWNER", ref_table: "PARENT", ref_column: "V", on_delete: "CASCADE", on_update: null },
+ ]),
+ listTriggers: vi.fn().mockResolvedValue([]),
+ getTableComment: vi.fn().mockResolvedValue(""),
+ getTablePartitioning: vi.fn().mockResolvedValue(null),
+ buildTableStructureChangeSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),
+ buildCreateTableSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),
+ saveHistory: vi.fn().mockResolvedValue(undefined),
+ disconnectDb: vi.fn().mockResolvedValue(undefined),
+ executeQuery: vi.fn(async (_id, _database, sql: string) => ({
+ columns: [],
+ rows: sql.includes("SELECT USER")
+ ? [["APP"]]
+ : sql.includes("SYS.ALL_TABLES")
+ ? [["APP", "SOURCE"]]
+ : sql.includes("SYS.ALL_CONSTRAINTS") || sql.includes("SYS.USER_CONSTRAINTS")
+ ? [["FK_SOURCE", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "PARENT_OWNER", "PK_PARENT", "CASCADE"]]
+ : [['ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "FK_SOURCE" FOREIGN KEY ("A", "B") REFERENCES "PARENT_OWNER"."PARENT" ("ID", "V") ON DELETE CASCADE ENABLE VALIDATE']],
+ execution_time_ms: 0,
+ rows_affected: 0,
+ })),
+}));
+
+let app: App | undefined;
+beforeEach(() => {
+ vi.clearAllMocks();
+ i18n.global.locale.value = "en";
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new Error("Unexpected HTTP request");
+ }),
+ );
+});
+afterEach(() => {
+ app?.unmount();
+ app = undefined;
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe("Oracle family foreign key editing entry", () => {
+ it.each([
+ { databaseType: "oracle", readable: true },
+ { databaseType: "oceanbase-oracle", readable: true },
+ { databaseType: "oracle", readable: false },
+ { databaseType: "oceanbase-oracle", readable: false },
+ ])("activates $databaseType editing only after definition verification (readable=$readable)", async ({ databaseType, readable }) => {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const store = useConnectionStore();
+ const id = `foreign-key-${databaseType}`;
+ store.connections = [{ id, name: "Foreign key fixture", db_type: databaseType, driver_profile: databaseType, host: "fixture", port: 2881, username: "APP", database: "APP" } as ConnectionConfig];
+ store.connectedIds.add(id);
+ await invalidateObjectMetadataCache({ connectionId: id });
+ const container = document.createElement("div");
+ document.body.append(container);
+ app = createApp({ render: () => h(TooltipProvider, {}, { default: () => h(TableStructureEditor, { connectionId: id, database: "APP", schema: "APP", tableName: "SOURCE", initialTab: "foreignKeys" }) }) });
+ app.use(pinia);
+ app.use(i18n);
+ app.component("LightTooltip", LightTooltip);
+ app.mount(container);
+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>('input[placeholder="' + i18n.global.t("structureEditor.foreignKeyName") + '"]')?.value).toBe("FK_SOURCE"));
+ const name = container.querySelector<HTMLInputElement>('input[placeholder="' + i18n.global.t("structureEditor.foreignKeyName") + '"]')!;
+ expect(container.textContent).toContain("PARENT_OWNER.PARENT");
+ expect(name.disabled).toBe(true);
+ const edit = container.querySelector<HTMLButtonElement>("[data-oracle-foreign-key-edit]");
+ expect(edit).not.toBeNull();
+ if (!readable) vi.mocked(api.executeQuery).mockRejectedValueOnce(new Error("Metadata access denied"));
+ edit!.click();
+ if (!readable) {
+ await vi.waitFor(() => expect(edit!.disabled).toBe(false));
+ expect(name.disabled).toBe(true);
+ expect(container.querySelector("[data-oracle-foreign-key-state]")).toBeNull();
+ expect(api.executeQuery).toHaveBeenCalledTimes(1);
+ return;
+ }
+ await vi.waitFor(() => expect(name.disabled).toBe(false));
+ expect(api.executeQuery).toHaveBeenCalledTimes(databaseType === "oracle" ? 3 : 4);
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ const enabled = container.querySelector<HTMLInputElement>("[data-oracle-foreign-key-enabled]")!;
+ const validated = container.querySelector<HTMLInputElement>("[data-oracle-foreign-key-validated]")!;
+ const deferrable = container.querySelector<HTMLInputElement>("[data-oracle-foreign-key-deferrable]")!;
+ expect(enabled.checked).toBe(true);
+ expect(validated.checked).toBe(true);
+ expect(deferrable.disabled).toBe(databaseType !== "oracle");
+ enabled.checked = false;
+ enabled.dispatchEvent(new Event("change", { bubbles: true }));
+ await vi.waitFor(() => expect(enabled.checked).toBe(false));
+ if (databaseType === "oracle") {
+ deferrable.checked = true;
+ deferrable.dispatchEvent(new Event("change", { bubbles: true }));
+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("[data-oracle-foreign-key-deferred]")!.disabled).toBe(false));
+ }
+ const referenceInputs = () => Array.from(container.querySelectorAll<HTMLInputElement>("[data-oracle-foreign-key-reference]"));
+ expect(referenceInputs().map((input) => input.value)).toEqual(["ID", "V"]);
+ container.querySelector<HTMLButtonElement>("[data-oracle-foreign-key-down]")!.click();
+ await vi.waitFor(() => expect(referenceInputs().map((input) => input.value)).toEqual(["V", "ID"]));
+ const rows = container.querySelectorAll("[data-oracle-foreign-key-pair]");
+ expect(rows[0]!.textContent).toContain("B");
+ expect(rows[1]!.textContent).toContain("A");
+ const parentTable = container.querySelector<HTMLInputElement>('input[placeholder="' + i18n.global.t("structureEditor.referencedTable") + '"]')!;
+ parentTable.value = "OtherParent";
+ parentTable.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(referenceInputs().map((input) => input.value)).toEqual(["", ""]));
+ });
+
+ it("does not publish a created-table result into a reconnected session", async () => {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const store = useConnectionStore();
+ const id = "foreign-key-create-generation";
+ store.connections = [{ id, name: "Create fixture", db_type: "oracle", driver_profile: "oracle", host: "fixture", port: 1521, username: "APP", database: "APP" } as ConnectionConfig];
+ store.connectedIds.add(id);
+ const createSql = 'CREATE TABLE "APP"."NEW_TABLE" ("ID" NUMBER PRIMARY KEY)';
+ const addSql = 'ALTER TABLE "APP"."NEW_TABLE" ADD CONSTRAINT "FK_SELF" FOREIGN KEY ("ID") REFERENCES "APP"."NEW_TABLE" ("ID") ENABLE VALIDATE';
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements: [`${createSql};`, `${addSql};`], warnings: [] } as never);
+ const result = (rows: unknown[][] = []) => ({ columns: [], rows, execution_time_ms: 0, rows_affected: 0 });
+ let finishAdd!: (value: ReturnType<typeof result>) => void;
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql.startsWith(createSql)) return result([]) as never;
+ if (sql.startsWith(addSql))
+ return new Promise((resolve) => {
+ finishAdd = resolve as typeof finishAdd;
+ }) as never;
+ throw new Error(`Unexpected query during create: ${sql}`);
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const drafts: unknown[] = [];
+ const saved: unknown[] = [];
+ const editor = ref<{ applyChanges: () => Promise<boolean> }>();
+ app = createApp({
+ render: () =>
+ h(
+ TooltipProvider,
+ {},
+ {
+ default: () =>
+ h(TableStructureEditor, {
+ connectionId: id,
+ database: "APP",
+ schema: "APP",
+ tableName: "",
+ initialTab: "foreignKeys",
+ draft: {
+ dirty: true,
+ activeTab: "foreignKeys",
+ newTableName: "NEW_TABLE",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [{ id: "new:id", name: "ID", dataType: "NUMBER", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false }],
+ indexes: [],
+ foreignKeys: [{ id: "new:fk", name: "FK_SELF", column: "ID", columns: ["ID"], refSchema: "APP", refTable: "NEW_TABLE", refColumn: "ID", refColumns: ["ID"], onUpdate: "", onDelete: "NO ACTION" }],
+ triggers: [],
+ initialized: true,
+ },
+ ref: editor,
+ "onUpdate:draft": (draft: unknown) => drafts.push(draft),
+ onSaved: (...args: unknown[]) => saved.push(args),
+ }),
+ },
+ ),
+ });
+ app.use(pinia);
+ app.use(i18n);
+ app.component("LightTooltip", LightTooltip);
+ app.mount(container);
+ await vi.waitFor(() => expect(api.buildCreateTableSql).toHaveBeenCalled());
+ const applyButton = () => Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.trim() === i18n.global.t("structureEditor.apply"));
+ await vi.waitFor(() => expect(applyButton()?.disabled).toBe(false));
+ const draftUpdatesBeforeSave = drafts.length;
+
+ const pendingSave = editor.value!.applyChanges();
+ await vi.waitFor(() => expect(finishAdd).toBeTypeOf("function"));
+ await store.disconnect(id, { skipTabHandling: true, markClosedByUser: false });
+ finishAdd(result([]));
+ await pendingSave;
+
+ expect(saved).toEqual([]);
+ expect(drafts).toHaveLength(draftUpdatesBeforeSave);
+ expect(api.executeQuery.mock.calls.slice(-2).map((call) => String(call[2]).startsWith("CREATE TABLE") || String(call[2]).startsWith("ALTER TABLE"))).toEqual([true, true]);
+ });
+
+ it.each(["history", "refresh"] as const)("keeps an existing foreign-key result out of a disconnected generation while %s is pending", async (pendingAt) => {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const store = useConnectionStore();
+ const id = "foreign-key-existing-generation";
+ store.connections = [{ id, name: "Foreign key fixture", db_type: "oracle", driver_profile: "oracle", host: "fixture", port: 1521, username: "APP", database: "APP" } as ConnectionConfig];
+ store.connectedIds.add(id);
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(
+ async (options) =>
+ ({
+ statements: options.oracleForeignKeyChanges?.length ? ['ALTER TABLE "APP"."SOURCE" DISABLE CONSTRAINT "FK_SOURCE";'] : [],
+ warnings: [],
+ }) as never,
+ );
+ const result = (rows: unknown[][] = []) => ({ columns: [], rows, execution_time_ms: 0, rows_affected: 0, execution_error: false, truncated: false, has_more: false });
+ let fkEnabled = "ENABLED";
+ let releaseRefresh!: () => void;
+ let refreshStarted!: () => void;
+ const refreshStartedPromise = new Promise<void>((resolve) => (refreshStarted = resolve));
+ vi.mocked(api.listForeignKeys).mockImplementation(async () => {
+ if (fkEnabled === "DISABLED" && pendingAt === "refresh") {
+ refreshStarted();
+ return new Promise(
+ (resolve) =>
+ (releaseRefresh = () =>
+ resolve([
+ { name: "FK_SOURCE", column: "A", ref_schema: "PARENT_OWNER", ref_table: "PARENT", ref_column: "ID", on_delete: "CASCADE", on_update: null },
+ { name: "FK_SOURCE", column: "B", ref_schema: "PARENT_OWNER", ref_table: "PARENT", ref_column: "V", on_delete: "CASCADE", on_update: null },
+ ] as never)),
+ );
+ }
+ return [
+ { name: "FK_SOURCE", column: "A", ref_schema: "PARENT_OWNER", ref_table: "PARENT", ref_column: "ID", on_delete: "CASCADE", on_update: null },
+ { name: "FK_SOURCE", column: "B", ref_schema: "PARENT_OWNER", ref_table: "PARENT", ref_column: "V", on_delete: "CASCADE", on_update: null },
+ ] as never;
+ });
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) {
+ fkEnabled = "DISABLED";
+ return result() as never;
+ }
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([["APP", "SOURCE"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("PARENT_OWNER") ? [["PARENT_OWNER", "PARENT", 99]] : [["APP", "SOURCE", 77]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result(
+ sql.includes("PARENT_OWNER")
+ ? [["ID", "NUMBER"]]
+ : [
+ ["A", "NUMBER", 22, null, null, "Y"],
+ ["B", "NUMBER", 22, null, null, "Y"],
+ ],
+ ) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS") || sql.includes("SESSION_PRIVS")) return result() as never;
+ if (sql.includes("SYS.ALL_CONS_COLUMNS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "ID", 1]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([["FK_SOURCE", "SOURCE"]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["FK_SOURCE", fkEnabled, "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "PARENT_OWNER", "PK_PARENT", "CASCADE"]]) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[`ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "FK_SOURCE" FOREIGN KEY ("A", "B") REFERENCES "PARENT_OWNER"."PARENT" ("ID", "V") ON DELETE CASCADE ${fkEnabled === "ENABLED" ? "ENABLE" : "DISABLE"} VALIDATE`]]) as never;
+ throw new Error(`Unexpected query during existing foreign-key update: ${sql}`);
+ });
+ let releaseHistory!: () => void;
+ vi.mocked(api.saveHistory).mockImplementation(() => (pendingAt === "history" ? (new Promise<void>((resolve) => (releaseHistory = resolve)) as never) : (Promise.resolve() as never)));
+ const container = document.createElement("div");
+ document.body.append(container);
+ const drafts: unknown[] = [];
+ const saved: unknown[] = [];
+ const editor = ref<{ applyChanges: () => Promise<boolean> }>();
+ app = createApp({
+ render: () =>
+ h(
+ TooltipProvider,
+ {},
+ {
+ default: () =>
+ h(TableStructureEditor, {
+ connectionId: id,
+ database: "APP",
+ schema: "APP",
+ tableName: "SOURCE",
+ initialTab: "foreignKeys",
+ ref: editor,
+ "onUpdate:draft": (draft: unknown) => drafts.push(draft),
+ onSaved: (...args: unknown[]) => saved.push(args),
+ }),
+ },
+ ),
+ });
+ app.use(pinia);
+ app.use(i18n);
+ app.component("LightTooltip", LightTooltip);
+ app.mount(container);
+ const edit = () => container.querySelector<HTMLButtonElement>("[data-oracle-foreign-key-edit]");
+ await vi.waitFor(() => expect(edit()).not.toBeNull());
+ edit()!.click();
+ const enabled = () => container.querySelector<HTMLInputElement>("[data-oracle-foreign-key-enabled]");
+ await vi.waitFor(() => expect(enabled()?.disabled).toBe(false));
+ enabled()!.checked = false;
+ enabled()!.dispatchEvent(new Event("change", { bubbles: true }));
+ await vi.waitFor(() => expect(vi.mocked(api.buildTableStructureChangeSql).mock.calls.some(([options]) => options.oracleForeignKeyChanges?.length)).toBe(true));
+ const draftUpdatesBeforeSave = drafts.length;
+
+ const pendingSave = editor.value!.applyChanges();
+ if (pendingAt === "history") await vi.waitFor(() => expect(api.saveHistory).toHaveBeenCalled());
+ else await refreshStartedPromise;
+ await store.disconnect(id, { skipTabHandling: true, markClosedByUser: false });
+ if (pendingAt === "history") releaseHistory();
+ else releaseRefresh();
+ await pendingSave;
+
+ expect(saved).toEqual([]);
+ expect(drafts).toHaveLength(draftUpdatesBeforeSave);
+ expect(api.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER TABLE"))).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts
index 34901fc86b..f81695a9fb 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts
@@ -1,4 +1,4 @@
-// @vitest-environment happy-dom
+// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -275,6 +275,8 @@ vi.mock("@/components/editor/EditorSearchPanel.vue", async () => {
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
+ connectionStateRevision: () => 0,
+ isCurrentConnectionStateRevision: () => true,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index e601872551..aed2dcb290 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -62,6 +62,7 @@ const consul = {
export default withEnglishFallback({
sidebarMenu,
+ oracleIndex: { mixedDraft: "Oracle indeks dəyişikliklərini digər cədvəl quruluşu dəyişikliklərindən ayrıca tətbiq edin." },
pluginPlatform: {
dataAccessConsent: '"{name}" "{connection}" bağlantısındakı məlumatları oxumaq istəyir. Bu bağlantı açıq olduqca plagin, Plagin Mərkəzində girişi ləğv edənə qədər orada yalnız oxuma sorğuları icra edə bilər. İcazə verilsin?',
dataAccessConsentTitle: "Məlumat girişi sorğusu",
@@ -4678,6 +4679,11 @@ export default withEnglishFallback({
searchIndexes: "İndeks axtar",
nextIndexMatch: "Növbəti uyğun indeksə keç",
addIndex: "İndeks əlavə et",
+ addCheckConstraint: "CHECK məhdudiyyəti əlavə et",
+ addUniqueConstraint: "UNIQUE məhdudiyyəti əlavə et",
+ constraintName: "Məhdudiyyətin adı",
+ checkExpression: "CHECK ifadəsi",
+ pairedIndexImpact: "OceanBase Oracle UNIQUE məhdudiyyətini və uyğun indeksini vahid obyekt kimi idarə edir. Bu məhdudiyyətin silinməsi və ya yenidən yaradılması uyğun indeksi də silə bilər.",
addForeignKey: "Xarici açar əlavə et",
addTrigger: "Tətikləyici əlavə et",
columnName: "Sütun",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index abb8dc4a71..59a54022a4 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -127,7 +127,63 @@ export default {
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "Foreign key operation result",
+ executionFailed: "The foreign key operation did not complete cleanly. Check each statement and the database state.",
+ createdTablePartial: "The table was created, but some foreign-key steps did not complete.",
+ createRecoveryNotice: "The table and successful foreign keys remain. Refresh and inspect the current definitions before handling unfinished foreign keys separately.",
+ readbackFailed: "Foreign key readback failed or did not match the intended result",
+ recoveryNotice: "Manual recovery candidate only. Recheck the referenced key, permissions, data and name before running it.",
+ refreshRequired: "Check the foreign key state and refresh before another attempt.",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "Replacement commits DROP and ADD separately; ADD may fail and leave no primary key. Review the SQL and original constraint state, and restore manually if needed.",
+ noIndex: "No associated supporting index",
+ preserveState: "Replacement preserves the original enabled, validated, and deferred state; it does not automatically enable or validate the key.",
+ indexPolicy: "Supporting index",
+ keepIndex: "Keep the original index",
+ dropIndex: "Drop the original index",
+ oracleImpact: "Keeping the index preserves its uniqueness rules. Dropping it removes its physical settings. Replacement commits DROP and ADD separately; ADD may fail and leave no primary key. Review the SQL and restore manually if needed.",
+ indexPresent: "Present; definition matches",
+ indexAbsent: "Absent",
+ indexChanged: "Definition changed",
+ indexUnknown: "State unknown",
+ incompleteMetadata: "Required metadata is incomplete. Refresh the table definition.",
+ duplicateColumns: "Primary key columns must not repeat.",
+ unsupportedTable: "This table type does not support this primary key operation.",
+ unsupportedState: "This primary key state is not supported.",
+ unsupportedIndex: "The supporting index has unsupported or unknown properties.",
+ definitionChanged: "The table definition changed. Refresh and preview again.",
+ virtualColumn: "Virtual or unknown column definitions cannot be used here.",
+ referenced: "Referenced by: {names}. Remove or change these references first.",
+ sharedIndex: "The supporting index is shared by another constraint.",
+ nullValues: "The selected columns contain NULL values.",
+ duplicateValues: "The selected columns contain duplicate keys.",
+ mixedDraft: "Apply other table changes separately from this primary key change.",
+ incompletePlan: "The SQL plan is incomplete. Refresh before saving.",
+ refreshRequired: "Check the database state and refresh before another attempt.",
+ readbackFailed: "Database readback failed or did not match the intended result",
+ recoveryNotice: "Manual recovery candidate only. Recheck data, names and indexes before running it. Tablespace, compression and storage properties are not restored.",
+ executionFailed: "The operation did not complete cleanly. Check each statement and the database state.",
+ resultTitle: "Primary key operation result",
+ details: "Statement results and manual recovery",
+ moveUp: "Move up",
+ moveDown: "Move down",
+ removeKey: "The primary key will be removed.",
+ impact: "Saving drops the key and its supporting index first. Rebuilding leaves a window without a primary key and may fail, leaving the table without one. Manual recovery restores only the logical key, not all physical properties.",
+ committed: "Committed",
+ rejected: "Rejected",
+ unknown: "Outcome unknown",
+ notExecuted: "Not executed",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Apply Oracle-family index changes separately from other table structure changes." },
+ oracleStructureResult: {
+ resultTitle: "Operation result",
+ executionFailed: "The operation did not complete cleanly. Check each statement and the database state.",
+ readbackFailed: "Readback failed or did not match the intended result",
+ recoveryNotice: "Manual recovery candidate only. Recheck data, names and indexes before running it.",
+ },
modelGeneration: {
title: "Generate model",
editTemplate: "Edit template",
@@ -5816,6 +5872,11 @@ export default {
fulltextIndexColumns: "Full-text indexes require CHAR, VARCHAR, or TEXT columns.",
spatialIndexColumn: "A spatial index requires a single geometry column.",
spatialIndexNullable: "MySQL spatial index columns must be NOT NULL.",
+ addCheckConstraint: "Add CHECK Constraint",
+ addUniqueConstraint: "Add UNIQUE Constraint",
+ constraintName: "Constraint name",
+ checkExpression: "CHECK expression",
+ pairedIndexImpact: "OceanBase Oracle treats a UNIQUE constraint and its paired index as one object. Dropping or rebuilding this constraint may also remove the paired index.",
addForeignKey: "Add Foreign Key",
addTrigger: "Add Trigger",
columnName: "Column",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index bcd8014c4e..60a3cdca34 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -129,7 +129,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "Resultado de la operación de clave externa",
+ executionFailed: "La operación de clave externa no se completó correctamente. Revise cada instrucción y el estado de la base de datos.",
+ createdTablePartial: "La tabla se creó, pero algunos pasos de clave externa no se completaron.",
+ createRecoveryNotice: "La tabla y las claves externas creadas correctamente se conservan. Actualice y revise las definiciones antes de tratar por separado las claves pendientes.",
+ readbackFailed: "La lectura de la clave externa falló o no coincide con el resultado esperado",
+ recoveryNotice: "Solo es una propuesta de recuperación manual. Antes de ejecutarla, vuelva a comprobar la clave referenciada, los permisos, los datos y el nombre.",
+ refreshRequired: "Compruebe el estado de la clave externa y actualícelo antes de volver a intentarlo.",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "DROP y ADD se confirman por separado; si ADD falla, puede no quedar clave primaria. Revise el SQL y el estado original de la restricción y restaure manualmente si es necesario.",
+ noIndex: "No hay un índice de soporte asociado",
+ preserveState: "El reemplazo conserva los estados originales de activación, validación y aplazamiento; no activa ni valida la clave automáticamente.",
+ indexPolicy: "Índice de soporte",
+ keepIndex: "Conservar el índice original",
+ dropIndex: "Eliminar el índice original",
+ oracleImpact: "Conservar el índice mantiene su unicidad. Eliminarlo pierde sus propiedades físicas. DROP y ADD se confirman por separado; si ADD falla, puede no quedar clave primaria. Revise el SQL y restaure manualmente si es necesario.",
+ indexPresent: "Existe y coincide la definición",
+ indexAbsent: "No existe",
+ indexChanged: "Definición modificada",
+ indexUnknown: "Estado desconocido",
+ incompleteMetadata: "Los metadatos necesarios están incompletos. Actualice la definición de la tabla.",
+ duplicateColumns: "Las columnas de la clave primaria no pueden repetirse.",
+ unsupportedTable: "Este tipo de tabla no admite esta operación de clave primaria.",
+ unsupportedState: "El estado actual de la clave primaria no es compatible.",
+ unsupportedIndex: "El índice de soporte tiene propiedades desconocidas o no compatibles.",
+ definitionChanged: "La definición de la tabla cambió. Actualice y vuelva a previsualizar.",
+ virtualColumn: "No se pueden usar columnas virtuales o de definición desconocida.",
+ referenced: "Referencias: {names}. Modifíquelas o elimínelas primero.",
+ sharedIndex: "Otra restricción comparte el índice de soporte.",
+ nullValues: "Las columnas seleccionadas contienen valores NULL.",
+ duplicateValues: "Las columnas seleccionadas contienen claves duplicadas.",
+ mixedDraft: "Aplique los demás cambios de tabla por separado de este cambio de clave primaria.",
+ incompletePlan: "El plan SQL está incompleto. Actualice antes de guardar.",
+ refreshRequired: "Compruebe el estado de la base de datos y actualice antes de reintentar.",
+ readbackFailed: "La lectura posterior falló o no coincide con el resultado previsto",
+ recoveryNotice: "Solo es una propuesta de recuperación manual. Revise datos, nombres e índices antes de ejecutarla. No restaura propiedades de tablespace, compresión ni almacenamiento.",
+ executionFailed: "La operación no terminó correctamente. Revise cada sentencia y el estado de la base de datos.",
+ resultTitle: "Resultado de la operación de clave primaria",
+ details: "Resultados y recuperación manual",
+ moveUp: "Subir",
+ moveDown: "Bajar",
+ removeKey: "Se eliminará la clave primaria.",
+ impact: "Al guardar se eliminan primero la clave y su índice de soporte. Durante la reconstrucción no hay clave primaria; si falla la creación, la tabla puede quedar sin ella. La recuperación manual solo restaura la clave lógica, no todas las propiedades físicas.",
+ committed: "Confirmada",
+ rejected: "Rechazada",
+ unknown: "Resultado desconocido",
+ notExecuted: "No ejecutada",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Aplica los cambios de índices Oracle por separado de los demás cambios de estructura de tabla." },
+ oracleStructureResult: {
+ resultTitle: "Resultado de la operación",
+ executionFailed: "La operación no se completó por completo. Revisa cada sentencia y el estado de la base de datos.",
+ readbackFailed: "La lectura de vuelta falló o no coincide con el resultado previsto",
+ recoveryNotice: "Solo es una propuesta de recuperación manual. Vuelve a comprobar datos, nombres e índices antes de ejecutarla.",
+ },
modelGeneration: {
title: "Generar modelo",
editTemplate: "Editar plantilla",
@@ -5175,6 +5231,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "Los índices de texto completo requieren columnas CHAR, VARCHAR o TEXT.",
spatialIndexColumn: "Un índice espacial requiere una sola columna de tipo geométrico.",
spatialIndexNullable: "Las columnas de índices espaciales de MySQL deben ser NOT NULL.",
+ addCheckConstraint: "Agregar restricción CHECK",
+ addUniqueConstraint: "Agregar restricción UNIQUE",
+ constraintName: "Nombre de la restricción",
+ checkExpression: "Expresión CHECK",
+ pairedIndexImpact: "OceanBase Oracle administra la restricción UNIQUE y su índice asociado como un solo objeto. Al eliminar o reconstruir la restricción, también podría eliminarse el índice.",
addForeignKey: "Agregar clave foránea",
addTrigger: "Agregar disparador",
columnName: "Columna",
@@ -6653,6 +6714,14 @@ export default withEnglishFallback({
tableNameCaseLower: "Convertir a minúsculas",
tableNameCaseUpper: "Convertir a mayúsculas",
batchSize: "Tamaño de lote",
+ operationTimeout: "Tiempo de espera de la operación (segundos)",
+ operationTimeoutInherit: "Heredar de las conexiones",
+ operationTimeoutCustom: "Personalizado",
+ operationTimeoutUnlimited: "Sin límite",
+ operationTimeoutSeconds: "{seconds} segundos",
+ operationTimeoutInheritedHint: "Conexión de origen: {source}; conexión de destino: {target}. La transferencia completa no tiene un límite de duración.",
+ operationTimeoutCustomHint: "Las operaciones individuales en el origen y el destino usan un tiempo de espera de {seconds} segundos; en las lecturas en flujo se mide como tiempo sin actividad. La transferencia completa no tiene un límite de duración.",
+ operationTimeoutCustomUnlimitedHint: "Las operaciones de base de datos de esta transferencia no tienen límite de tiempo; la tarea aún se puede cancelar manualmente.",
modeRebuild: "Reconstruir estructura y datos (RENAME + CREATE + INSERT)",
modeKeepExisting: "Conservar tablas existentes",
modeRebuildStructure: "Reconstruir estructura (RENAME + CREATE)",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index db81593ef8..b6214f701c 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8,6 +8,7 @@ import { meilisearchManagementId } from "./meilisearchManagement";
export default withEnglishFallback({
sidebarMenu,
+ oracleIndex: { mixedDraft: "Terapkan perubahan indeks Oracle secara terpisah dari perubahan struktur tabel lainnya." },
cellTransform: {
title: "Pratinjau konversi",
description: "Konversi nilai saat ini untuk dilihat atau disalin. Nilai sumber dan draf editor tidak berubah.",
@@ -5331,6 +5332,11 @@ export default withEnglishFallback({
searchIndexes: "Cari indeks",
nextIndexMatch: "Ke indeks cocok berikutnya",
addIndex: "Tambah Indeks",
+ addCheckConstraint: "Tambah constraint CHECK",
+ addUniqueConstraint: "Tambah constraint UNIQUE",
+ constraintName: "Nama constraint",
+ checkExpression: "Ekspresi CHECK",
+ pairedIndexImpact: "OceanBase Oracle mengelola constraint UNIQUE dan indeks pasangannya sebagai satu objek. Menghapus atau membangun ulang constraint ini juga dapat menghapus indeks pasangannya.",
addForeignKey: "Tambah Kunci Asing",
addTrigger: "Tambah Trigger",
columnName: "Kolom",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index a97b53ac88..18bdcb468d 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -127,7 +127,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "Risultato dell'operazione sulla chiave esterna",
+ executionFailed: "L'operazione sulla chiave esterna non è stata completata correttamente. Controllare ogni istruzione e lo stato del database.",
+ createdTablePartial: "La tabella è stata creata, ma alcuni passaggi delle chiavi esterne non sono stati completati.",
+ createRecoveryNotice: "La tabella e le chiavi esterne create correttamente vengono mantenute. Aggiornare e controllare le definizioni prima di gestire separatamente le chiavi non completate.",
+ readbackFailed: "La rilettura della chiave esterna non è riuscita o non corrisponde al risultato previsto",
+ recoveryNotice: "Solo una proposta di ripristino manuale. Prima di eseguirla, ricontrollare la chiave referenziata, i permessi, i dati e il nome.",
+ refreshRequired: "Controllare lo stato della chiave esterna e aggiornare prima di riprovare.",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "DROP e ADD vengono confermati separatamente; se ADD fallisce, la chiave primaria può essere assente. Verificare SQL e stato originale del vincolo e ripristinare manualmente se necessario.",
+ noIndex: "Nessun indice di supporto associato",
+ preserveState: "La sostituzione mantiene gli stati originali di abilitazione, convalida e differimento; non abilita né convalida automaticamente la chiave.",
+ indexPolicy: "Indice di supporto",
+ keepIndex: "Mantieni l'indice originale",
+ dropIndex: "Elimina l'indice originale",
+ oracleImpact: "Mantenere l'indice conserva la sua unicità. Eliminarlo perde le proprietà fisiche. DROP e ADD vengono confermati separatamente; se ADD fallisce, la chiave primaria può essere assente. Verificare SQL e ripristinare manualmente se necessario.",
+ indexPresent: "Presente, definizione corrispondente",
+ indexAbsent: "Assente",
+ indexChanged: "Definizione modificata",
+ indexUnknown: "Stato sconosciuto",
+ incompleteMetadata: "I metadati necessari sono incompleti. Aggiornare la definizione della tabella.",
+ duplicateColumns: "Le colonne della chiave primaria non possono ripetersi.",
+ unsupportedTable: "Questo tipo di tabella non supporta questa operazione sulla chiave primaria.",
+ unsupportedState: "Lo stato attuale della chiave primaria non è supportato.",
+ unsupportedIndex: "L'indice di supporto ha proprietà sconosciute o non supportate.",
+ definitionChanged: "La definizione della tabella è cambiata. Aggiornare e riaprire l'anteprima.",
+ virtualColumn: "Non è possibile usare colonne virtuali o con definizione sconosciuta.",
+ referenced: "Riferimenti: {names}. Modificarli o rimuoverli prima.",
+ sharedIndex: "L'indice di supporto è condiviso da un altro vincolo.",
+ nullValues: "Le colonne selezionate contengono valori NULL.",
+ duplicateValues: "Le colonne selezionate contengono chiavi duplicate.",
+ mixedDraft: "Applicare le altre modifiche alla tabella separatamente dalla modifica della chiave primaria.",
+ incompletePlan: "Il piano SQL è incompleto. Aggiornare prima di salvare.",
+ refreshRequired: "Controllare lo stato del database e aggiornare prima di riprovare.",
+ readbackFailed: "La rilettura del database è fallita o non corrisponde al risultato previsto",
+ recoveryNotice: "Solo una proposta di ripristino manuale. Ricontrollare dati, nomi e indici prima di eseguirla. Non ripristina tablespace, compressione o proprietà di archiviazione.",
+ executionFailed: "L'operazione non è stata completata correttamente. Controllare ogni istruzione e lo stato del database.",
+ resultTitle: "Risultato dell'operazione sulla chiave primaria",
+ details: "Risultati delle istruzioni e ripristino manuale",
+ moveUp: "Sposta su",
+ moveDown: "Sposta giù",
+ removeKey: "La chiave primaria verrà eliminata.",
+ impact: "Il salvataggio elimina prima la chiave e il relativo indice. Durante la ricostruzione la tabella non ha chiave primaria; se la creazione fallisce, può rimanerne priva. Il ripristino manuale ricrea solo la chiave logica, non tutte le proprietà fisiche.",
+ committed: "Confermata",
+ rejected: "Rifiutata",
+ unknown: "Esito sconosciuto",
+ notExecuted: "Non eseguita",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Applica le modifiche agli indici Oracle separatamente dalle altre modifiche alla struttura della tabella." },
+ oracleStructureResult: {
+ resultTitle: "Risultato dell'operazione",
+ executionFailed: "L'operazione non è stata completata completamente. Controlla ogni istruzione e lo stato del database.",
+ readbackFailed: "La rilettura non è riuscita o non corrisponde al risultato previsto",
+ recoveryNotice: "È solo una proposta di ripristino manuale. Ricontrolla dati, nomi e indici prima di eseguirla.",
+ },
modelGeneration: {
title: "Genera modello",
editTemplate: "Modifica modello",
@@ -4995,6 +5051,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "Gli indici full-text richiedono colonne CHAR, VARCHAR o TEXT.",
spatialIndexColumn: "Un indice spaziale richiede una sola colonna di tipo geometrico.",
spatialIndexNullable: "Le colonne degli indici spaziali MySQL devono essere NOT NULL.",
+ addCheckConstraint: "Aggiungi vincolo CHECK",
+ addUniqueConstraint: "Aggiungi vincolo UNIQUE",
+ constraintName: "Nome del vincolo",
+ checkExpression: "Espressione CHECK",
+ pairedIndexImpact: "OceanBase Oracle gestisce il vincolo UNIQUE e il relativo indice come un unico oggetto. L'eliminazione o la ricostruzione del vincolo può eliminare anche l'indice associato.",
addForeignKey: "Aggiungi Chiave Esterna",
addTrigger: "Aggiungi Trigger",
columnName: "Colonna",
@@ -6470,6 +6531,14 @@ export default withEnglishFallback({
tableNameCaseLower: "Converti in minuscolo",
tableNameCaseUpper: "Converti in maiuscolo",
batchSize: "Dimensione lotto",
+ operationTimeout: "Timeout operazione (secondi)",
+ operationTimeoutInherit: "Eredita dalle connessioni",
+ operationTimeoutCustom: "Personalizzato",
+ operationTimeoutUnlimited: "Illimitato",
+ operationTimeoutSeconds: "{seconds} secondi",
+ operationTimeoutInheritedHint: "Connessione di origine: {source}; connessione di destinazione: {target}. La durata complessiva del trasferimento non è limitata.",
+ operationTimeoutCustomHint: "Le singole operazioni sull'origine e sulla destinazione usano un timeout di {seconds} secondi; per le letture in streaming viene considerato il tempo di inattività. La durata complessiva del trasferimento non è limitata.",
+ operationTimeoutCustomUnlimitedHint: "Le operazioni sul database di questo trasferimento non hanno limiti di durata; l'attività può comunque essere annullata manualmente.",
modeRebuild: "Ricostruisci struttura e dati (RENAME + CREATE + INSERT)",
modeKeepExisting: "Mantieni tabelle esistenti",
modeRebuildStructure: "Ricostruisci struttura (RENAME + CREATE)",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index c572241419..935214585c 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -128,7 +128,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "外部キー操作の結果",
+ executionFailed: "外部キー操作が正常に完了しませんでした。各ステートメントとデータベースの状態を確認してください。",
+ createdTablePartial: "テーブルは作成されましたが、一部の外部キー処理が完了していません。",
+ createRecoveryNotice: "テーブルと正常に作成された外部キーは残ります。未完了の外部キーを個別に処理する前に、更新して定義を確認してください。",
+ readbackFailed: "外部キーの再読み込みに失敗したか、結果が期待値と一致しません",
+ recoveryNotice: "手動復旧用の候補です。実行前に参照キー、権限、データ、名前を再確認してください。",
+ refreshRequired: "再試行する前に外部キーの状態を確認し、更新してください。",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "DROP と ADD は個別にコミットされ、ADD の失敗後は主キーがない場合があります。SQL と元の制約状態を確認し、必要に応じて手動で復元してください。",
+ noIndex: "関連付けられた索引はありません",
+ preserveState: "置換では元の有効化・検証・遅延状態を保持します。主キーを自動で有効化または検証しません。",
+ indexPolicy: "制約を支えるインデックス",
+ keepIndex: "元のインデックスを保持",
+ dropIndex: "元のインデックスを削除",
+ oracleImpact: "保持すると元の一意性制約が残ります。削除すると物理属性が失われます。DROP と ADD は個別にコミットされ、ADD の失敗後は主キーがない場合があります。SQL を確認し、必要に応じて手動で復元してください。",
+ indexPresent: "存在し、定義が一致",
+ indexAbsent: "存在しません",
+ indexChanged: "定義が変更されています",
+ indexUnknown: "状態不明",
+ incompleteMetadata: "必要なメタデータが不完全です。テーブル定義を更新してください。",
+ duplicateColumns: "主キー列は重複できません。",
+ unsupportedTable: "このテーブル種別ではこの主キー操作を実行できません。",
+ unsupportedState: "現在の主キー状態はサポートされていません。",
+ unsupportedIndex: "関連インデックスに未対応または不明な属性があります。",
+ definitionChanged: "テーブル定義が変更されました。更新して再度プレビューしてください。",
+ virtualColumn: "仮想列または定義が不明な列は使用できません。",
+ referenced: "参照があります:{names}。先に参照を変更または削除してください。",
+ sharedIndex: "関連インデックスは別の制約でも使用されています。",
+ nullValues: "選択した列に NULL 値があります。",
+ duplicateValues: "選択した列に重複するキー値があります。",
+ mixedDraft: "他のテーブル変更と主キー変更は別々に適用してください。",
+ incompletePlan: "SQL 計画が不完全です。更新してから保存してください。",
+ refreshRequired: "再試行前にデータベースの状態を確認して更新してください。",
+ readbackFailed: "データベースの再読込に失敗したか、結果が期待と異なります",
+ recoveryNotice: "手動復旧用の候補です。実行前にデータ、名前、インデックスを再確認してください。表領域、圧縮、ストレージ属性は復元されません。",
+ executionFailed: "操作が完全には完了しませんでした。各文の結果とデータベースの状態を確認してください。",
+ resultTitle: "主キー操作の結果",
+ details: "各文の結果と手動復旧",
+ moveUp: "上へ",
+ moveDown: "下へ",
+ removeKey: "この主キーを削除します。",
+ impact: "保存時に主キーと関連インデックスを先に削除します。再作成中は主キーがなくなり、追加が失敗するとその状態が残ります。手動復旧では論理的な主キーのみを再作成し、すべての物理属性は復元しません。",
+ committed: "コミット済み",
+ rejected: "拒否",
+ unknown: "結果不明",
+ notExecuted: "未実行",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Oracle 系インデックスの変更は、他のテーブル構造の変更と分けて適用してください。" },
+ oracleStructureResult: {
+ resultTitle: "操作結果",
+ executionFailed: "操作が完全には完了しませんでした。各ステートメントとデータベースの状態を確認してください。",
+ readbackFailed: "読み戻しに失敗したか、想定した結果と一致しません",
+ recoveryNotice: "以下は手動復旧の候補にすぎません。実行前にデータ、名前、インデックスを再確認してください。",
+ },
modelGeneration: {
title: "モデルを生成",
editTemplate: "テンプレートを編集",
@@ -5057,6 +5113,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "全文インデックスには CHAR、VARCHAR、TEXT 型の列が必要です。",
spatialIndexColumn: "空間インデックスには幾何型の列を 1 つだけ指定してください。",
spatialIndexNullable: "MySQL の空間インデックスの列は NOT NULL である必要があります。",
+ addCheckConstraint: "CHECK 制約を追加",
+ addUniqueConstraint: "UNIQUE 制約を追加",
+ constraintName: "制約名",
+ checkExpression: "CHECK 式",
+ pairedIndexImpact: "OceanBase Oracle では UNIQUE 制約と対応する索引は一体として管理されます。この制約を削除または再作成すると、対応する索引も削除される場合があります。",
addForeignKey: "外部キーを追加",
addTrigger: "トリガーを追加",
columnName: "列",
@@ -6490,6 +6551,14 @@ export default withEnglishFallback({
tableNameCaseLower: "小文字に変換",
tableNameCaseUpper: "大文字に変換",
batchSize: "バッチサイズ",
+ operationTimeout: "操作タイムアウト(秒)",
+ operationTimeoutInherit: "接続設定を継承",
+ operationTimeoutCustom: "カスタム",
+ operationTimeoutUnlimited: "無制限",
+ operationTimeoutSeconds: "{seconds} 秒",
+ operationTimeoutInheritedHint: "ソース接続: {source}、ターゲット接続: {target}。転送全体の所要時間に上限はありません。",
+ operationTimeoutCustomHint: "ソースとターゲットの各操作に {seconds} 秒のタイムアウトを適用します。ストリーミング読み取りでは無進行時間として扱われます。転送全体の所要時間に上限はありません。",
+ operationTimeoutCustomUnlimitedHint: "この転送のデータベース操作に時間制限はありません。タスクは手動でキャンセルできます。",
modeRebuild: "構造とデータを再構築 (RENAME + CREATE + INSERT)",
modeKeepExisting: "既存テーブルを保持",
modeRebuildStructure: "構造を再構築 (RENAME + CREATE)",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 9f9ee9cd86..dc827462ad 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -126,7 +126,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "외래 키 작업 결과",
+ executionFailed: "외래 키 작업이 완전히 완료되지 않았습니다. 각 문과 데이터베이스 상태를 확인하세요.",
+ createdTablePartial: "테이블은 생성되었지만 일부 외래 키 단계가 완료되지 않았습니다.",
+ createRecoveryNotice: "테이블과 성공적으로 생성된 외래 키는 유지됩니다. 완료되지 않은 외래 키를 별도로 처리하기 전에 새로 고쳐 정의를 확인하세요.",
+ readbackFailed: "외래 키 재조회에 실패했거나 결과가 예상과 다릅니다",
+ recoveryNotice: "수동 복구용 후보입니다. 실행 전에 참조 키, 권한, 데이터와 이름을 다시 확인하세요.",
+ refreshRequired: "다시 시도하기 전에 외래 키 상태를 확인하고 새로 고치세요.",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "DROP과 ADD는 각각 커밋되며 ADD 실패 후 기본 키가 없을 수 있습니다. SQL과 기존 제약 조건 상태를 확인하고 필요하면 수동 복구하세요.",
+ noIndex: "연결된 지원 인덱스가 없습니다",
+ preserveState: "교체 시 기존 활성화, 검증 및 지연 상태를 유지하며 키를 자동으로 활성화하거나 검증하지 않습니다.",
+ indexPolicy: "지원 인덱스",
+ keepIndex: "기존 인덱스 유지",
+ dropIndex: "기존 인덱스 삭제",
+ oracleImpact: "유지하면 기존 고유성 제한이 남습니다. 삭제하면 물리 속성이 사라집니다. DROP과 ADD는 각각 커밋되며 ADD 실패 후 기본 키가 없을 수 있습니다. SQL을 확인하고 필요하면 수동 복구하세요.",
+ indexPresent: "존재하며 정의 일치",
+ indexAbsent: "없음",
+ indexChanged: "정의 변경됨",
+ indexUnknown: "상태 알 수 없음",
+ incompleteMetadata: "필수 메타데이터가 불완전합니다. 테이블 정의를 새로 고치세요.",
+ duplicateColumns: "기본 키 열은 중복될 수 없습니다.",
+ unsupportedTable: "이 테이블 유형은 해당 기본 키 작업을 지원하지 않습니다.",
+ unsupportedState: "현재 기본 키 상태는 지원되지 않습니다.",
+ unsupportedIndex: "지원 인덱스에 지원되지 않거나 알 수 없는 속성이 있습니다.",
+ definitionChanged: "테이블 정의가 변경되었습니다. 새로 고친 후 다시 미리 보세요.",
+ virtualColumn: "가상 열이나 정의를 알 수 없는 열은 사용할 수 없습니다.",
+ referenced: "참조가 있습니다: {names}. 먼저 참조를 변경하거나 제거하세요.",
+ sharedIndex: "지원 인덱스를 다른 제약 조건도 사용하고 있습니다.",
+ nullValues: "선택한 열에 NULL 값이 있습니다.",
+ duplicateValues: "선택한 열에 중복 키 값이 있습니다.",
+ mixedDraft: "다른 테이블 변경 사항과 기본 키 변경을 따로 적용하세요.",
+ incompletePlan: "SQL 계획이 불완전합니다. 저장 전에 새로 고치세요.",
+ refreshRequired: "다시 시도하기 전에 데이터베이스 상태를 확인하고 새로 고치세요.",
+ readbackFailed: "데이터베이스 재조회에 실패했거나 결과가 예상과 다릅니다",
+ recoveryNotice: "수동 복구용 후보입니다. 실행 전에 데이터, 이름, 인덱스를 다시 확인하세요. 테이블스페이스, 압축 및 저장소 속성은 복원되지 않습니다.",
+ executionFailed: "작업이 완전히 완료되지 않았습니다. 각 명령의 결과와 데이터베이스 상태를 확인하세요.",
+ resultTitle: "기본 키 작업 결과",
+ details: "명령별 결과 및 수동 복구",
+ moveUp: "위로",
+ moveDown: "아래로",
+ removeKey: "이 기본 키가 삭제됩니다.",
+ impact: "저장하면 기본 키와 지원 인덱스가 먼저 삭제됩니다. 재생성 중에는 기본 키가 없으며 추가에 실패하면 그 상태가 유지될 수 있습니다. 수동 복구는 논리적 기본 키만 재생성하며 모든 물리적 속성을 복원하지 않습니다.",
+ committed: "커밋됨",
+ rejected: "거부됨",
+ unknown: "결과 알 수 없음",
+ notExecuted: "실행되지 않음",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Oracle 계열 인덱스 변경은 다른 테이블 구조 변경과 분리해 적용하세요." },
+ oracleStructureResult: {
+ resultTitle: "작업 결과",
+ executionFailed: "작업이 완전히 완료되지 않았습니다. 각 문과 데이터베이스 상태를 확인하세요.",
+ readbackFailed: "다시 읽기에 실패했거나 예상한 결과와 일치하지 않습니다",
+ recoveryNotice: "다음은 수동 복구 후보일 뿐입니다. 실행 전에 데이터, 이름, 인덱스를 다시 확인하세요.",
+ },
modelGeneration: {
title: "모델 생성",
editTemplate: "템플릿 편집",
@@ -4937,6 +4993,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "전문 인덱스에는 CHAR, VARCHAR 또는 TEXT 컬럼이 필요합니다.",
spatialIndexColumn: "공간 인덱스에는 기하 형식의 컬럼 하나만 지정해야 합니다.",
spatialIndexNullable: "MySQL 공간 인덱스 컬럼은 NOT NULL이어야 합니다.",
+ addCheckConstraint: "CHECK 제약 조건 추가",
+ addUniqueConstraint: "UNIQUE 제약 조건 추가",
+ constraintName: "제약 조건 이름",
+ checkExpression: "CHECK 표현식",
+ pairedIndexImpact: "OceanBase Oracle은 UNIQUE 제약 조건과 연결된 인덱스를 하나의 객체로 관리합니다. 이 제약 조건을 삭제하거나 다시 만들면 연결된 인덱스도 삭제될 수 있습니다.",
addForeignKey: "외래 키 추가",
addTrigger: "트리거 추가",
columnName: "컬럼",
@@ -6270,6 +6331,14 @@ export default withEnglishFallback({
tableNameCaseLower: "소문자",
tableNameCaseUpper: "대문자",
batchSize: "배치 크기",
+ operationTimeout: "작업 시간 제한(초)",
+ operationTimeoutInherit: "연결 설정 상속",
+ operationTimeoutCustom: "사용자 지정",
+ operationTimeoutUnlimited: "제한 없음",
+ operationTimeoutSeconds: "{seconds}초",
+ operationTimeoutInheritedHint: "소스 연결: {source}; 대상 연결: {target}. 전체 전송 시간에는 제한이 없습니다.",
+ operationTimeoutCustomHint: "소스와 대상의 개별 작업에 {seconds}초 시간 제한을 적용합니다. 스트리밍 읽기에서는 진행이 없는 시간으로 계산하며, 전체 전송 시간에는 제한이 없습니다.",
+ operationTimeoutCustomUnlimitedHint: "이 전송의 데이터베이스 작업에는 시간 제한이 없습니다. 작업은 계속 수동으로 취소할 수 있습니다.",
modeRebuild: "구조 및 데이터 재구축 (RENAME + CREATE + INSERT)",
modeKeepExisting: "기존 테이블 유지",
modeRebuildStructure: "구조 재구축 (RENAME + CREATE)",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index fdd2d459f8..92d33090a1 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -128,7 +128,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "Resultado da operação de chave estrangeira",
+ executionFailed: "A operação de chave estrangeira não foi concluída corretamente. Confira cada instrução e o estado do banco de dados.",
+ createdTablePartial: "A tabela foi criada, mas algumas etapas de chave estrangeira não foram concluídas.",
+ createRecoveryNotice: "A tabela e as chaves estrangeiras criadas com sucesso foram mantidas. Atualize e confira as definições antes de tratar separadamente as chaves pendentes.",
+ readbackFailed: "A releitura da chave estrangeira falhou ou não corresponde ao resultado esperado",
+ recoveryNotice: "Apenas uma proposta de recuperação manual. Confira novamente a chave referenciada, as permissões, os dados e o nome antes de executar.",
+ refreshRequired: "Confira o estado da chave estrangeira e atualize antes de tentar novamente.",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "DROP e ADD são confirmados separadamente; se ADD falhar, a chave primária poderá ficar ausente. Confira o SQL e o estado original da restrição e restaure manualmente se necessário.",
+ noIndex: "Nenhum índice de suporte associado",
+ preserveState: "A substituição preserva os estados originais de ativação, validação e adiamento; não ativa nem valida a chave automaticamente.",
+ indexPolicy: "Índice de suporte",
+ keepIndex: "Manter o índice original",
+ dropIndex: "Excluir o índice original",
+ oracleImpact: "Manter o índice preserva sua unicidade. Excluí-lo perde suas propriedades físicas. DROP e ADD são confirmados separadamente; se ADD falhar, a chave primária poderá ficar ausente. Confira o SQL e restaure manualmente se necessário.",
+ indexPresent: "Presente, definição correspondente",
+ indexAbsent: "Ausente",
+ indexChanged: "Definição alterada",
+ indexUnknown: "Estado desconhecido",
+ incompleteMetadata: "Os metadados necessários estão incompletos. Atualize a definição da tabela.",
+ duplicateColumns: "As colunas da chave primária não podem se repetir.",
+ unsupportedTable: "Este tipo de tabela não oferece suporte a esta operação de chave primária.",
+ unsupportedState: "O estado atual da chave primária não é compatível.",
+ unsupportedIndex: "O índice de suporte tem propriedades desconhecidas ou incompatíveis.",
+ definitionChanged: "A definição da tabela mudou. Atualize e visualize novamente.",
+ virtualColumn: "Não é possível usar colunas virtuais ou com definição desconhecida.",
+ referenced: "Referências: {names}. Altere ou remova essas referências primeiro.",
+ sharedIndex: "Outra restrição compartilha o índice de suporte.",
+ nullValues: "As colunas selecionadas contêm valores NULL.",
+ duplicateValues: "As colunas selecionadas contêm chaves duplicadas.",
+ mixedDraft: "Aplique as outras alterações da tabela separadamente da alteração da chave primária.",
+ incompletePlan: "O plano SQL está incompleto. Atualize antes de salvar.",
+ refreshRequired: "Confira o estado do banco de dados e atualize antes de tentar novamente.",
+ readbackFailed: "A releitura do banco de dados falhou ou não corresponde ao resultado esperado",
+ recoveryNotice: "Apenas uma proposta de recuperação manual. Confira dados, nomes e índices antes de executar. Não restaura tablespace, compressão ou propriedades de armazenamento.",
+ executionFailed: "A operação não foi concluída corretamente. Confira cada instrução e o estado do banco de dados.",
+ resultTitle: "Resultado da operação de chave primária",
+ details: "Resultados das instruções e recuperação manual",
+ moveUp: "Mover para cima",
+ moveDown: "Mover para baixo",
+ removeKey: "A chave primária será removida.",
+ impact: "Ao salvar, a chave e seu índice de suporte são removidos primeiro. Durante a reconstrução não há chave primária; se a criação falhar, a tabela poderá continuar sem ela. A recuperação manual restaura apenas a chave lógica, não todas as propriedades físicas.",
+ committed: "Confirmada",
+ rejected: "Rejeitada",
+ unknown: "Resultado desconhecido",
+ notExecuted: "Não executada",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Aplique as alterações de índices Oracle separadamente das demais alterações na estrutura da tabela." },
+ oracleStructureResult: {
+ resultTitle: "Resultado da operação",
+ executionFailed: "A operação não foi concluída por completo. Verifique cada instrução e o estado do banco de dados.",
+ readbackFailed: "A releitura falhou ou não correspondeu ao resultado esperado",
+ recoveryNotice: "É apenas uma sugestão de recuperação manual. Verifique novamente dados, nomes e índices antes de executá-la.",
+ },
modelGeneration: {
title: "Gerar modelo",
editTemplate: "Editar modelo",
@@ -4995,6 +5051,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "Índices de texto completo exigem colunas CHAR, VARCHAR ou TEXT.",
spatialIndexColumn: "Um índice espacial exige uma única coluna de tipo geométrico.",
spatialIndexNullable: "As colunas de índices espaciais do MySQL devem ser NOT NULL.",
+ addCheckConstraint: "Adicionar restrição CHECK",
+ addUniqueConstraint: "Adicionar restrição UNIQUE",
+ constraintName: "Nome da restrição",
+ checkExpression: "Expressão CHECK",
+ pairedIndexImpact: "O OceanBase Oracle gerencia a restrição UNIQUE e seu índice associado como um único objeto. Excluir ou recriar a restrição também pode excluir o índice associado.",
addForeignKey: "Adicionar chave estrangeira",
addTrigger: "Adicionar trigger",
columnName: "Coluna",
@@ -6470,6 +6531,14 @@ export default withEnglishFallback({
tableNameCaseLower: "Converter para minúsculas",
tableNameCaseUpper: "Converter para maiúsculas",
batchSize: "Tamanho do lote",
+ operationTimeout: "Tempo limite da operação (segundos)",
+ operationTimeoutInherit: "Herdar das conexões",
+ operationTimeoutCustom: "Personalizado",
+ operationTimeoutUnlimited: "Sem limite",
+ operationTimeoutSeconds: "{seconds} segundos",
+ operationTimeoutInheritedHint: "Conexão de origem: {source}; conexão de destino: {target}. A transferência completa não tem limite de duração.",
+ operationTimeoutCustomHint: "As operações individuais na origem e no destino usam um tempo limite de {seconds} segundos; leituras em fluxo consideram o tempo sem atividade. A transferência completa não tem limite de duração.",
+ operationTimeoutCustomUnlimitedHint: "As operações de banco de dados desta transferência não têm limite de tempo; a tarefa ainda pode ser cancelada manualmente.",
modeRebuild: "Reconstruir estrutura e dados (RENAME + CREATE + INSERT)",
modeKeepExisting: "Manter tabelas existentes",
modeRebuildStructure: "Reconstruir estrutura (RENAME + CREATE)",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 0f715417e7..94872defe5 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -70,7 +70,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "Результат операции с внешним ключом",
+ executionFailed: "Операция с внешним ключом завершена не полностью. Проверьте результат каждого оператора и состояние базы данных.",
+ createdTablePartial: "Таблица создана, но часть операций с внешними ключами не завершена.",
+ createRecoveryNotice: "Таблица и успешно созданные внешние ключи сохранены. Обновите данные и проверьте определения, прежде чем отдельно обрабатывать незавершенные ключи.",
+ readbackFailed: "Не удалось повторно прочитать внешний ключ или результат отличается от ожидаемого",
+ recoveryNotice: "Только кандидат для ручного восстановления. Перед выполнением перепроверьте ссылочный ключ, права, данные и имя.",
+ refreshRequired: "Перед повторной попыткой проверьте состояние внешнего ключа и обновите данные.",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "DROP и ADD фиксируются отдельно; после сбоя ADD первичный ключ может отсутствовать. Проверьте SQL и исходное состояние ограничения и при необходимости восстановите вручную.",
+ noIndex: "Связанный опорный индекс отсутствует",
+ preserveState: "Замена сохраняет исходные состояния включения, проверки и отсрочки; ключ не включается и не проверяется автоматически.",
+ indexPolicy: "Опорный индекс",
+ keepIndex: "Сохранить исходный индекс",
+ dropIndex: "Удалить исходный индекс",
+ oracleImpact: "При сохранении индекса его уникальность продолжает действовать. При удалении теряются физические параметры. DROP и ADD фиксируются отдельно; после сбоя ADD первичный ключ может отсутствовать. Проверьте SQL и при необходимости восстановите вручную.",
+ indexPresent: "Существует, определение совпадает",
+ indexAbsent: "Отсутствует",
+ indexChanged: "Определение изменено",
+ indexUnknown: "Состояние неизвестно",
+ incompleteMetadata: "Обязательные метаданные неполны. Обновите определение таблицы.",
+ duplicateColumns: "Столбцы первичного ключа не должны повторяться.",
+ unsupportedTable: "Этот тип таблицы не поддерживает данную операцию с первичным ключом.",
+ unsupportedState: "Текущее состояние первичного ключа не поддерживается.",
+ unsupportedIndex: "У поддерживающего индекса есть неизвестные или неподдерживаемые свойства.",
+ definitionChanged: "Определение таблицы изменилось. Обновите его и повторите просмотр.",
+ virtualColumn: "Виртуальные столбцы и столбцы с неизвестным определением использовать нельзя.",
+ referenced: "Есть ссылки: {names}. Сначала измените или удалите их.",
+ sharedIndex: "Поддерживающий индекс используется другим ограничением.",
+ nullValues: "Выбранные столбцы содержат NULL.",
+ duplicateValues: "Выбранные столбцы содержат повторяющиеся значения ключа.",
+ mixedDraft: "Примените остальные изменения таблицы отдельно от изменения первичного ключа.",
+ incompletePlan: "План SQL неполон. Обновите данные перед сохранением.",
+ refreshRequired: "Перед повторной попыткой проверьте состояние базы данных и обновите данные.",
+ readbackFailed: "Повторное чтение базы данных не удалось или результат отличается от ожидаемого",
+ recoveryNotice: "Только кандидат для ручного восстановления. Перед выполнением перепроверьте данные, имена и индексы. Табличное пространство, сжатие и параметры хранения не восстанавливаются.",
+ executionFailed: "Операция завершена не полностью. Проверьте результат каждого оператора и состояние базы данных.",
+ resultTitle: "Результат операции с первичным ключом",
+ details: "Результаты операторов и ручное восстановление",
+ moveUp: "Вверх",
+ moveDown: "Вниз",
+ removeKey: "Первичный ключ будет удалён.",
+ impact: "При сохранении сначала удаляются ключ и его индекс. Во время пересоздания первичного ключа нет; если добавление завершится ошибкой, таблица может остаться без него. Ручное восстановление воссоздаёт только логический ключ, а не все физические свойства.",
+ committed: "Зафиксировано",
+ rejected: "Отклонено",
+ unknown: "Результат неизвестен",
+ notExecuted: "Не выполнено",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "Применяйте изменения индексов Oracle отдельно от других изменений структуры таблицы." },
+ oracleStructureResult: {
+ resultTitle: "Результат операции",
+ executionFailed: "Операция завершилась не полностью. Проверьте каждый оператор и состояние базы данных.",
+ readbackFailed: "Обратное чтение не удалось или не совпало с ожидаемым результатом",
+ recoveryNotice: "Это лишь вариант ручного восстановления. Перед выполнением повторно проверьте данные, имена и индексы.",
+ },
modelGeneration: {
title: "Создать модель",
editTemplate: "Изменить шаблон",
@@ -5462,6 +5518,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "Для полнотекстовых индексов требуются столбцы CHAR, VARCHAR или TEXT.",
spatialIndexColumn: "Пространственный индекс должен содержать один столбец геометрического типа.",
spatialIndexNullable: "Столбцы пространственных индексов MySQL должны иметь ограничение NOT NULL.",
+ addCheckConstraint: "Добавить ограничение CHECK",
+ addUniqueConstraint: "Добавить ограничение UNIQUE",
+ constraintName: "Имя ограничения",
+ checkExpression: "Выражение CHECK",
+ pairedIndexImpact: "OceanBase Oracle управляет ограничением UNIQUE и связанным индексом как единым объектом. Удаление или пересоздание ограничения может также удалить индекс.",
addForeignKey: "Добавить внешний ключ",
addTrigger: "Добавить триггер",
columnName: "Столбец",
@@ -7703,6 +7764,14 @@ export default withEnglishFallback({
tableNameCaseLower: "Нижний регистр",
tableNameCaseUpper: "Верхний регистр",
batchSize: "Размер пакета",
+ operationTimeout: "Тайм-аут операции (секунды)",
+ operationTimeoutInherit: "Наследовать настройки подключений",
+ operationTimeoutCustom: "Пользовательский",
+ operationTimeoutUnlimited: "Без ограничений",
+ operationTimeoutSeconds: "{seconds} с",
+ operationTimeoutInheritedHint: "Подключение источника: {source}; подключение назначения: {target}. Для всей задачи переноса нет ограничения по общей длительности.",
+ operationTimeoutCustomHint: "Для отдельных операций на источнике и назначении установлен тайм-аут {seconds} с; для потокового чтения учитывается время без прогресса. Общая длительность переноса не ограничена.",
+ operationTimeoutCustomUnlimitedHint: "Операции с базой данных в этом переносе не ограничены по времени; задачу по-прежнему можно отменить вручную.",
modeRebuild: "Перестроить структуру и данные (RENAME + CREATE + INSERT)",
modeKeepExisting: "Оставить существующие таблицы",
modeRebuildStructure: "Перестроить структуру (RENAME + CREATE)",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 204d7bdd10..c5374a53a1 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -49,6 +49,55 @@ const damengDump = {
};
export default withEnglishFallback({
+ oracleForeignKey: {
+ resultTitle: "ผลลัพธ์การดำเนินการ Foreign Key",
+ executionFailed: "การดำเนินการ Foreign Key ไม่ได้เสร็จสมบูรณ์ กรุณาตรวจสอบผลลัพธ์แต่ละรายการและสถานะฐานข้อมูล",
+ createdTablePartial: "สร้างตารางแล้ว แต่ขั้นตอน Foreign Key บางรายการยังไม่เสร็จสมบูรณ์",
+ createRecoveryNotice: "ตารางและ Foreign Key ที่สำเร็จแล้วจะยังคงอยู่ กรุณารีเฟรชและตรวจสอบคำจำกัดความปัจจุบันก่อนจัดการ Foreign Key ที่ค้างอยู่แยกต่างหาก",
+ readbackFailed: "การอ่าน Foreign Key กลับล้มเหลวหรือไม่ตรงกับผลลัพธ์ที่ต้องการ",
+ recoveryNotice: "ต่อไปนี้เป็นเพียงตัวเลือกสำหรับกู้คืนด้วยตนเองเท่านั้น ก่อนดำเนินการต้องตรวจสอบ Key ที่อ้างอิง สิทธิ์ ข้อมูล และชื่ออีกครั้ง",
+ refreshRequired: "กรุณาตรวจสอบสถานะ Foreign Key และรีเฟรชก่อนลองอีกครั้ง",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "การแทนที่ commits DROP และ ADD แยกกัน หาก ADD ล้มเหลวอาจไม่มี Primary Key กรุณาตรวจสอบ SQL และสถานะ Constraint เดิม และกู้คืนด้วยตนเองหากจำเป็น",
+ noIndex: "ไม่มี Index ที่รองรับซึ่งเชื่อมโยงอยู่",
+ preserveState: "การแทนที่จะรักษาสถานะ enabled, validated และ deferred เดิมไว้ จะไม่เปิดใช้งานหรือ validate โดยอัตโนมัติ",
+ indexPolicy: "Index ที่รองรับ",
+ keepIndex: "เก็บ Index เดิมไว้",
+ dropIndex: "ลบ Index เดิม",
+ oracleImpact: "การเก็บ Index ไว้จะรักษากฎ uniqueness ไว้ การลบ Index จะสูญเสียคุณสมบัติทางกายภาพ การแทนที่ commits DROP และ ADD แยกกัน หาก ADD ล้มเหลวอาจไม่มี Primary Key กรุณาตรวจสอบ SQL และกู้คืนด้วยตนเองหากจำเป็น",
+ indexPresent: "มีอยู่ คำจำกัดความตรงกัน",
+ indexAbsent: "ไม่มีอยู่",
+ indexChanged: "คำจำกัดความเปลี่ยนไป",
+ indexUnknown: "ไม่ทราบสถานะ",
+ incompleteMetadata: "Metadata ที่จำเป็นไม่ครบถ้วน กรุณารีเฟรชคำจำกัดความตาราง",
+ duplicateColumns: "คอลัมน์ Primary Key ซ้ำกันไม่ได้",
+ unsupportedTable: "ตารางประเภทนี้ไม่รองรับการดำเนินการ Primary Key นี้",
+ unsupportedState: "สถานะ Primary Key ปัจจุบันไม่อยู่ในขอบเขตที่รองรับ",
+ unsupportedIndex: "Index ที่รองรับมีคุณสมบัติที่ไม่รองรับหรือไม่ทราบ",
+ definitionChanged: "คำจำกัดความตารางเปลี่ยนไป กรุณารีเฟรชและดูตัวอย่างใหม่",
+ virtualColumn: "การดำเนินการนี้ใช้คอลัมน์ virtual หรือคอลัมน์ที่คำจำกัดความไม่ทราบไม่ได้",
+ referenced: "มีการอ้างอิง: {names} กรุณาจัดการการอ้างอิงเหล่านี้ก่อน",
+ sharedIndex: "Index ที่รองรับถูกใช้โดย Constraint อื่นด้วย",
+ nullValues: "คอลัมน์ที่เลือกมีค่า NULL",
+ duplicateValues: "คอลัมน์ที่เลือกมีค่าคีย์ซ้ำกัน",
+ mixedDraft: "กรุณาแยกการแก้ไขโครงสร้างตารางอื่นออกจากการแก้ไข Primary Key นี้",
+ incompletePlan: "แผน SQL ไม่ครบถ้วน กรุณารีเฟรชก่อนบันทึก",
+ refreshRequired: "กรุณาตรวจสอบสถานะฐานข้อมูลและรีเฟรชก่อนลองอีกครั้ง",
+ readbackFailed: "การอ่านฐานข้อมูลกลับล้มเหลวหรือไม่ตรงกับผลลัพธ์ที่ต้องการ",
+ recoveryNotice: "ต่อไปนี้เป็นเพียงตัวเลือกสำหรับกู้คืนด้วยตนเองเท่านั้น ก่อนดำเนินการต้องตรวจสอบข้อมูล ชื่อ และ Index อีกครั้ง จะไม่กู้คืนคุณสมบัติทางกายภาพ เช่น tablespace, compression และ storage",
+ executionFailed: "การดำเนินการไม่เสร็จสมบูรณ์ กรุณาตรวจสอบผลลัพธ์แต่ละรายการและสถานะฐานข้อมูล",
+ resultTitle: "ผลลัพธ์การดำเนินการ Primary Key",
+ details: "ผลลัพธ์แต่ละรายการและการกู้คืนด้วยตนเอง",
+ moveUp: "เลื่อนขึ้น",
+ moveDown: "เลื่อนลง",
+ removeKey: "Primary Key นี้จะถูกลบ",
+ impact: "การบันทึกจะลบ Primary Key และ Index ที่รองรับก่อน ในระหว่างการสร้างใหม่จะมีช่วงที่ไม่มี Primary Key และหากเพิ่มล้มเหลวตารางอาจไม่มี Primary Key การกู้คืนด้วยตนเองจะสร้างเฉพาะ Primary Key เชิงตรรกะ ไม่ได้กู้คืนคุณสมบัติทางกายภาพทั้งหมด",
+ committed: "คอมมิตแล้ว",
+ rejected: "ถูกปฏิเสธอย่างชัดเจน",
+ unknown: "ไม่ทราบผลลัพธ์",
+ notExecuted: "ยังไม่ได้ดำเนินการ",
+ },
sidebarMenu: {
customize: "ปรับแต่งเมนูแบบจัดกลุ่ม…",
customizeTitle: "ปรับแต่งเมนู {scope}",
@@ -98,6 +147,13 @@ export default withEnglishFallback({
view: "View",
},
},
+ oracleIndex: { mixedDraft: "กรุณาแยกการแก้ไข Index ของตระกูล Oracle ออกจากการแก้ไขโครงสร้างตารางอื่น" },
+ oracleStructureResult: {
+ resultTitle: "ผลลัพธ์การดำเนินการ",
+ executionFailed: "การดำเนินการไม่เสร็จสมบูรณ์ กรุณาตรวจสอบผลลัพธ์แต่ละรายการและสถานะฐานข้อมูล",
+ readbackFailed: "การอ่านกลับล้มเหลวหรือไม่ตรงกับผลลัพธ์ที่ต้องการ",
+ recoveryNotice: "ต่อไปนี้เป็นเพียงตัวเลือกสำหรับกู้คืนด้วยตนเองเท่านั้น ก่อนดำเนินการต้องตรวจสอบข้อมูล ชื่อ และ Index อีกครั้ง",
+ },
modelGeneration: {
title: "สร้างโมเดล",
editTemplate: "แก้ไขเทมเพลต",
@@ -5792,6 +5848,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "Full-text Index ต้องใช้ Column CHAR, VARCHAR หรือ TEXT",
spatialIndexColumn: "Spatial Index ต้องใช้ Column Geometry เดียว",
spatialIndexNullable: "Column Spatial Index ของ MySQL ต้องเป็น NOT NULL",
+ addCheckConstraint: "เพิ่ม CHECK Constraint",
+ addUniqueConstraint: "เพิ่ม UNIQUE Constraint",
+ constraintName: "ชื่อ Constraint",
+ checkExpression: "นิพจน์ CHECK",
+ pairedIndexImpact: "OceanBase Oracle จัดการ UNIQUE Constraint และ Index ที่จับคู่เป็นวัตถุเดียวกัน การลบหรือสร้าง Constraint นี้ใหม่จึงอาจลบ Index ที่จับคู่ไปด้วย",
addForeignKey: "เพิ่ม Foreign Key",
addTrigger: "เพิ่ม Trigger",
columnName: "คอลัมน์",
@@ -8094,6 +8155,14 @@ export default withEnglishFallback({
tableNameCaseLower: "ตัวพิมพ์เล็ก",
tableNameCaseUpper: "ตัวพิมพ์ใหญ่",
batchSize: "ขนาด Batch",
+ operationTimeout: "Timeout การทำงาน (วินาที)",
+ operationTimeoutInherit: "สืบทอดจากการเชื่อมต่อ",
+ operationTimeoutCustom: "กำหนดเอง",
+ operationTimeoutUnlimited: "ไม่จำกัด",
+ operationTimeoutSeconds: "{seconds} วินาที",
+ operationTimeoutInheritedHint: "การเชื่อมต่อต้นทาง: {source}; การเชื่อมต่อปลายทาง: {target} งานถ่ายโอนทั้งหมดไม่มีการจำกัดระยะเวลารวม",
+ operationTimeoutCustomHint: "การทำงานแต่ละครั้งที่ต้นทางและปลายทางใช้ Timeout {seconds} วินาที; การอ่านแบบสตรีมจะนับตามช่วงเวลาที่ไม่มีความคืบหน้า งานถ่ายโอนทั้งหมดไม่มีการจำกัดระยะเวลารวม",
+ operationTimeoutCustomUnlimitedHint: "การทำงานฐานข้อมูลในงานถ่ายโอนนี้ไม่มีการจำกัดเวลา แต่ยังสามารถยกเลิกงานด้วยตนเองได้",
tableFilterSection: "ตัวกรองแยกตาม Table",
tableFilterSectionHint: "ว่าง = Table ทั้งหมด",
tableFilterSet: "ตั้งตัวกรอง",
@@ -10063,6 +10132,8 @@ export default withEnglishFallback({
redisScanPageSize: "จำนวน Redis Scan",
redisScanPageSizeDescription: "จำนวน Key ที่ขอต่อหน้า Redis SCAN เมื่อเรียกดู Key",
redisScanPageSizeOption: "Keys {count} รายการ",
+ redisValuePreviewLimit: "ขีดจำกัดการแสดงตัวอย่างค่า",
+ redisValuePreviewLimitDescription: "ขนาดสูงสุดของค่า String และ Bitmap ที่โหลดใน Editor ค่าเริ่มต้น 64 KiB ตั้งค่าได้ 1–65536 KiB (64 MiB) หากเกินขีดจำกัดสามารถดาวน์โหลดค่าทั้งหมดได้ เมื่อเปลี่ยน รายละเอียดที่เปิดอยู่และไม่มีการแก้ไขที่ยังไม่บันทึกจะรีเฟรช",
redisDatabaseDisplayLimit: "ขีดจำกัดรายการฐานข้อมูลใน Sidebar",
redisDatabaseDisplayLimitDescription: 'จำนวนฐานข้อมูลสูงสุดที่แสดงพร้อมกันใน Sidebar ส่วนที่เหลือแสดงได้ด้วย "โหลดเพิ่ม"',
redisDatabaseDisplayLimitOption: "ฐานข้อมูล {count} รายการ",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 37e5035850..994747ed6f 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -62,6 +62,7 @@ const consul = {
export default withEnglishFallback({
sidebarMenu,
+ oracleIndex: { mixedDraft: "Oracle indeks değişikliklerini diğer tablo yapısı değişikliklerinden ayrı uygulayın." },
pluginPlatform: {
dataAccessConsent: '"{name}", "{connection}" bağlantısındaki verileri okumak istiyor. Bu bağlantı açık olduğu sürece eklenti, Eklenti Merkezi\'nden erişimi iptal edene kadar bağlantıda salt okunur sorgular çalıştırabilir. İzin verilsin mi?',
dataAccessConsentTitle: "Veri Erişim İsteği",
@@ -4580,6 +4581,11 @@ export default withEnglishFallback({
searchIndexes: "Dizin ara",
nextIndexMatch: "Sonraki eşleşen dizine git",
addIndex: "Dizin Ekle",
+ addCheckConstraint: "CHECK kısıtlaması ekle",
+ addUniqueConstraint: "UNIQUE kısıtlaması ekle",
+ constraintName: "Kısıtlama adı",
+ checkExpression: "CHECK ifadesi",
+ pairedIndexImpact: "OceanBase Oracle, UNIQUE kısıtlamasını ve eşleşen dizinini tek nesne olarak yönetir. Bu kısıtlamayı silmek veya yeniden oluşturmak eşleşen dizini de silebilir.",
addForeignKey: "Yabancı Anahtar Ekle",
addTrigger: "Tetikleyici Ekle",
columnName: "Sütun",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 2bb5c7b98b..b0f3f6dca6 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -72,7 +72,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "外键操作结果",
+ executionFailed: "外键操作未完整完成,请核对逐条结果和数据库状态。",
+ createdTablePartial: "表已创建,但部分外键步骤未完成。",
+ createRecoveryNotice: "表和已成功执行的外键会保留。刷新并核对当前定义后,再单独处理未完成的外键。",
+ readbackFailed: "外键读回失败或与预期结果不一致",
+ recoveryNotice: "以下仅为人工恢复候选。执行前须重新检查引用键、权限、数据和名称。",
+ refreshRequired: "再次尝试前,请核对外键状态并刷新。",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "替换的 DROP 与 ADD 分别提交,ADD 失败后可能没有主键。请核对 SQL 和原约束状态,必要时人工恢复。",
+ noIndex: "没有关联的支撑索引",
+ preserveState: "替换保留原主键的启用、验证和延迟状态,不会自动启用或验证。",
+ indexPolicy: "支撑索引",
+ keepIndex: "保留原索引",
+ dropIndex: "删除原索引",
+ oracleImpact: "保留索引后,原索引的唯一性限制仍生效;删除索引会丢失其物理属性。替换的 DROP 与 ADD 分别提交,ADD 失败后可能没有主键。请核对 SQL,必要时人工恢复。",
+ indexPresent: "存在,定义一致",
+ indexAbsent: "不存在",
+ indexChanged: "定义已变化",
+ indexUnknown: "状态未知",
+ incompleteMetadata: "必要元数据不完整,请刷新表定义。",
+ duplicateColumns: "主键列不能重复。",
+ unsupportedTable: "此表类型不支持本次主键操作。",
+ unsupportedState: "当前主键状态不在支持范围内。",
+ unsupportedIndex: "支撑索引包含不支持或未知的属性。",
+ definitionChanged: "表定义已变化,请刷新后重新预览。",
+ virtualColumn: "此操作不能使用虚拟列或定义未知的列。",
+ referenced: "存在引用:{names}。请先处理这些引用。",
+ sharedIndex: "支撑索引还被其他约束使用。",
+ nullValues: "所选列包含空值。",
+ duplicateValues: "所选列包含重复键值。",
+ mixedDraft: "请将其他表结构修改与本次主键修改分开应用。",
+ incompletePlan: "SQL 计划不完整,请刷新后再保存。",
+ refreshRequired: "再次尝试前,请核对数据库状态并刷新。",
+ readbackFailed: "数据库读回失败或与预期结果不一致",
+ recoveryNotice: "以下仅为人工恢复候选。执行前须重新检查数据、名称和索引;不会恢复表空间、压缩和存储等物理属性。",
+ executionFailed: "操作未完整完成,请核对逐条结果和数据库状态。",
+ resultTitle: "主键操作结果",
+ details: "逐条结果与人工恢复",
+ moveUp: "上移",
+ moveDown: "下移",
+ removeKey: "将删除此主键。",
+ impact: "保存会先删除主键及其支撑索引。重建期间存在无主键窗口,新增失败后表可能保持无主键状态。人工恢复仅重建逻辑主键,不恢复全部物理属性。",
+ committed: "已提交",
+ rejected: "明确拒绝",
+ unknown: "结果未知",
+ notExecuted: "未执行",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "请将 Oracle 系索引修改与其他表结构修改分开应用。" },
+ oracleStructureResult: {
+ resultTitle: "操作结果",
+ executionFailed: "操作未完整完成,请核对逐条结果和数据库状态。",
+ readbackFailed: "读回失败或与预期结果不一致",
+ recoveryNotice: "以下仅为人工恢复候选。执行前须重新检查数据、名称和索引。",
+ },
modelGeneration: {
title: "生成模型",
editTemplate: "编辑模板",
@@ -5805,6 +5861,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "全文索引仅支持 CHAR、VARCHAR 和 TEXT 类字段。",
spatialIndexColumn: "空间索引只能包含一个几何类型字段。",
spatialIndexNullable: "MySQL 空间索引字段必须设为不可为空。",
+ addCheckConstraint: "新增 CHECK 约束",
+ addUniqueConstraint: "新增 UNIQUE 约束",
+ constraintName: "约束名称",
+ checkExpression: "CHECK 表达式",
+ pairedIndexImpact: "OceanBase Oracle 将 UNIQUE 约束及其配对索引作为同一对象管理。删除或重建此约束时,配对索引也可能一并删除。",
addForeignKey: "新增外键",
addTrigger: "新增触发器",
columnName: "字段名",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 57d92ccfdd..56ccd97ade 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -128,7 +128,63 @@ export default withEnglishFallback({
},
oceanbaseCloneDialog,
+ oracleForeignKey: {
+ resultTitle: "外鍵操作結果",
+ executionFailed: "外鍵操作未完整完成,請核對逐條結果和資料庫狀態。",
+ createdTablePartial: "資料表已建立,但部分外鍵步驟未完成。",
+ createRecoveryNotice: "資料表與已成功執行的外鍵會保留。重新整理並核對目前定義後,再個別處理未完成的外鍵。",
+ readbackFailed: "外鍵讀回失敗或與預期結果不一致",
+ recoveryNotice: "以下僅為手動還原候選。執行前須重新檢查參照鍵、權限、資料和名稱。",
+ refreshRequired: "再次嘗試前,請核對外鍵狀態並重新整理。",
+ },
+ oceanbasePrimaryKey: {
+ noIndexImpact: "替換的 DROP 與 ADD 分別提交,ADD 失敗後可能沒有主鍵。請核對 SQL 和原約束狀態,必要時手動還原。",
+ noIndex: "沒有關聯的支撐索引",
+ preserveState: "替換保留原主鍵的啟用、驗證和延遲狀態,不會自動啟用或驗證。",
+ indexPolicy: "支撐索引",
+ keepIndex: "保留原索引",
+ dropIndex: "刪除原索引",
+ oracleImpact: "保留索引後,原索引的唯一性限制仍生效;刪除索引會遺失其實體屬性。替換的 DROP 與 ADD 分別提交,ADD 失敗後可能沒有主鍵。請核對 SQL,必要時手動還原。",
+ indexPresent: "存在,定義一致",
+ indexAbsent: "不存在",
+ indexChanged: "定義已變更",
+ indexUnknown: "狀態未知",
+ incompleteMetadata: "必要中繼資料不完整,請重新整理資料表定義。",
+ duplicateColumns: "主鍵欄位不能重複。",
+ unsupportedTable: "此資料表類型不支援這項主鍵操作。",
+ unsupportedState: "目前主鍵狀態不在支援範圍內。",
+ unsupportedIndex: "支援索引包含不支援或未知的屬性。",
+ definitionChanged: "資料表定義已變更,請重新整理後再次預覽。",
+ virtualColumn: "此操作不能使用虛擬欄位或定義未知的欄位。",
+ referenced: "存在參照:{names}。請先處理這些參照。",
+ sharedIndex: "支援索引也被其他約束使用。",
+ nullValues: "所選欄位包含 NULL 值。",
+ duplicateValues: "所選欄位包含重複鍵值。",
+ mixedDraft: "請將其他資料表結構修改與這次主鍵修改分開套用。",
+ incompletePlan: "SQL 計畫不完整,請重新整理後再儲存。",
+ refreshRequired: "再次嘗試前,請核對資料庫狀態並重新整理。",
+ readbackFailed: "資料庫回讀失敗或與預期結果不符",
+ recoveryNotice: "以下僅為手動復原候選。執行前須重新檢查資料、名稱和索引;不會還原表空間、壓縮及儲存等實體屬性。",
+ executionFailed: "操作未完整完成,請核對各陳述式結果及資料庫狀態。",
+ resultTitle: "主鍵操作結果",
+ details: "各陳述式結果與手動復原",
+ moveUp: "上移",
+ moveDown: "下移",
+ removeKey: "將刪除此主鍵。",
+ impact: "儲存會先刪除主鍵及其支援索引。重建期間沒有主鍵,新增失敗後資料表可能仍無主鍵。手動復原僅重建邏輯主鍵,不還原全部實體屬性。",
+ committed: "已提交",
+ rejected: "已明確拒絕",
+ unknown: "結果未知",
+ notExecuted: "未執行",
+ },
sidebarMenu,
+ oracleIndex: { mixedDraft: "請將 Oracle 系索引修改與其他資料表結構修改分開套用。" },
+ oracleStructureResult: {
+ resultTitle: "操作結果",
+ executionFailed: "操作未完整完成,請核對逐條結果和資料庫狀態。",
+ readbackFailed: "讀回失敗或與預期結果不一致",
+ recoveryNotice: "以下僅為人工復原候選。執行前須重新檢查資料、名稱和索引。",
+ },
modelGeneration: {
title: "產生模型",
editTemplate: "編輯範本",
@@ -4742,6 +4798,11 @@ export default withEnglishFallback({
fulltextIndexColumns: "全文索引僅支援 CHAR、VARCHAR 和 TEXT 類型的欄位。",
spatialIndexColumn: "空間索引只能包含一個幾何類型欄位。",
spatialIndexNullable: "MySQL 空間索引欄位必須設為不可為空。",
+ addCheckConstraint: "新增 CHECK 約束",
+ addUniqueConstraint: "新增 UNIQUE 約束",
+ constraintName: "約束名稱",
+ checkExpression: "CHECK 運算式",
+ pairedIndexImpact: "OceanBase Oracle 將 UNIQUE 約束及其配對索引視為同一物件。刪除或重建此約束時,配對索引也可能一併刪除。",
addForeignKey: "新增外鍵",
addTrigger: "新增觸發器",
columnName: "欄位",
@@ -5797,6 +5858,14 @@ export default withEnglishFallback({
modeOverwrite: "覆蓋 (TRUNCATE + INSERT)",
modeUpsert: "更新插入 (按主鍵 INSERT 或 UPDATE)",
batchSize: "每批筆數",
+ operationTimeout: "操作逾時(秒)",
+ operationTimeoutInherit: "沿用連線設定",
+ operationTimeoutCustom: "自訂",
+ operationTimeoutUnlimited: "不限",
+ operationTimeoutSeconds: "{seconds} 秒",
+ operationTimeoutInheritedHint: "來源連線:{source};目標連線:{target}。整個傳輸工作沒有總時長限制。",
+ operationTimeoutCustomHint: "來源端和目標端的單次操作使用 {seconds} 秒逾時;串流讀取依無進度時間計算,整個傳輸工作沒有總時長限制。",
+ operationTimeoutCustomUnlimitedHint: "此傳輸中的資料庫操作不限制時長;仍可手動取消工作。",
modeRebuild: "重建結構和資料 (RENAME + CREATE + INSERT)",
modeKeepExisting: "保留既有表",
modeRebuildStructure: "重建結構 (RENAME + CREATE)",
diff --git a/apps/desktop/src/lib/__tests__/database/oceanbasePrimaryKey.spec.ts b/apps/desktop/src/lib/__tests__/database/oceanbasePrimaryKey.spec.ts
new file mode 100644
index 0000000000..c03eec063e
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/database/oceanbasePrimaryKey.spec.ts
@@ -0,0 +1,537 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import * as api from "@/lib/backend/api";
+import { executeOceanbasePrimaryKeyPlan, readOceanbasePrimaryKeySnapshot, prepareOraclePrimaryKeyChange } from "@/lib/database/oceanbasePrimaryKey";
+
+vi.mock("@/lib/backend/api", () => ({ executeQuery: vi.fn(), getColumns: vi.fn(), listConstraints: vi.fn(), listIndexes: vi.fn() }));
+
+const target = { connectionId: "ob", database: "APP", schema: "APP", tableName: "SOURCE" };
+const change = { name: "PK_SOURCE", originalColumns: ["ID"], columns: ["V"] };
+const rows = {
+ key: [["PK_SOURCE", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", "APP", "PK_SOURCE"]],
+ keyColumns: [["ID", 1]],
+ table: [[null, "N"]],
+ columns: [
+ ["ID", "N", "NO"],
+ ["V", "N", "NO"],
+ ],
+ references: [],
+ index: [["APP", "PK_SOURCE", "NORMAL", "UNIQUE", "VALID", "VISIBLE", "NO"]],
+ indexColumns: [["ID", 1, "ASC"]],
+ indexUsers: [["APP", "SOURCE", "PK_SOURCE", "P"]],
+ nulls: [[0]],
+ duplicates: [[0]],
+};
+let fixture: Record<keyof typeof rows, unknown[][]>;
+let truncated = false;
+let capturedObjectId: unknown = 77;
+let capturedIdentity: unknown[][] = [["APP", "APP", "ORCL"]];
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ truncated = false;
+ capturedObjectId = 77;
+ capturedIdentity = [["APP", "APP", "ORCL"]];
+ fixture = structuredClone(rows);
+ vi.mocked(api.getColumns).mockResolvedValue(["ID", "V"].map((name) => ({ name, data_type: "NUMBER", is_nullable: false, is_primary_key: name === "ID", column_default: null })));
+ vi.mocked(api.listConstraints).mockResolvedValue([{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled: true, valid: true, deferrable: false, initially_deferred: false }]);
+ vi.mocked(api.listIndexes).mockResolvedValue([{ name: "PK_SOURCE", columns: ["ID"], is_unique: true, is_primary: true, index_type: "NORMAL" }]);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _database, sql) => {
+ expect(sql).toMatch(/^SELECT /);
+ if (sql.includes("SYS_CONTEXT")) return { columns: [], rows: capturedIdentity, affected_rows: 0, execution_time_ms: 0 };
+ if (sql.includes("SYS.ALL_OBJECTS")) return { columns: [], rows: Array.isArray(capturedObjectId) ? capturedObjectId : [["APP", "SOURCE", capturedObjectId]], affected_rows: 0, execution_time_ms: 0 };
+ if (sql.startsWith("SELECT RELY ")) return { columns: [], rows: [[null]], affected_rows: 0, execution_time_ms: 0 };
+ if (sql.startsWith("SELECT INDEX_NAME FROM SYS.ALL_INDEXES")) {
+ const name = /INDEX_NAME = '([^']+)'/.exec(sql)?.[1];
+ return { columns: [], rows: name && fixture.index.some((row) => row[1] === name) ? [[name]] : [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ if (sql.startsWith("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS")) {
+ const name = /CONSTRAINT_NAME = '([^']+)'/.exec(sql)?.[1];
+ return { columns: [], rows: name && fixture.key.some((row) => row[0] === name) ? [[name]] : [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
+ const selected = sql.includes("R_CONSTRAINT_NAME")
+ ? fixture.references
+ : sql.includes("SYS.ALL_IND_COLUMNS")
+ ? fixture.indexColumns
+ : sql.includes("SYS.ALL_INDEXES")
+ ? fixture.index
+ : sql.includes("SYS.ALL_CONS_COLUMNS")
+ ? fixture.keyColumns
+ : sql.includes("SYS.ALL_TAB_COLS")
+ ? fixture.columns
+ : sql.includes("SYS.ALL_TABLES")
+ ? fixture.table
+ : sql.startsWith("SELECT OWNER, TABLE_NAME")
+ ? fixture.indexUsers
+ : sql.includes("SYS.ALL_CONSTRAINTS")
+ ? fixture.key
+ : sql.includes("GROUP BY")
+ ? fixture.duplicates
+ : sql.includes("IS NULL")
+ ? fixture.nulls
+ : undefined;
+ if (!selected) throw new Error(`Unexpected query: ${sql}`);
+ return { columns: [], rows: selected, affected_rows: 0, execution_time_ms: 0, truncated };
+ });
+});
+
+describe("OceanBase existing primary key preflight", () => {
+ it("reads the original key and supporting index, then checks target values without returning business values", async () => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ expect(JSON.parse(snapshot).indexProperties).toEqual(fixture.index);
+ expect(api.executeQuery).toHaveBeenCalledWith("ob", "APP", expect.stringContaining('GROUP BY "V"'), "APP", undefined, { maxRows: 10001, catalog: undefined });
+ expect(api.executeQuery).toHaveBeenCalledWith("ob", "APP", expect.stringContaining("R_OWNER = 'APP'"), "APP", undefined, expect.anything());
+ });
+
+ it.each(["ENABLED", "DISABLED"])("rejects a cross-owner %s reference", async (state) => {
+ fixture.references = [["CHILD_OWNER", "CHILD", "FK_PARENT", state]];
+ await expect(readOceanbasePrimaryKeySnapshot(target, change)).rejects.toMatchObject({ key: "referenced", values: { names: "CHILD_OWNER.CHILD.FK_PARENT" } });
+ });
+
+ it.each([
+ ["table", [["IOT", "N"]], "unsupportedTable"],
+ ["key", [["PK_SOURCE", "DISABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", "APP", "PK_SOURCE"]], "unsupportedState"],
+ ["keyColumns", [["V", 1]], "definitionChanged"],
+ [
+ "columns",
+ [
+ ["ID", "N", "NO"],
+ ["V", "N", "YES"],
+ ],
+ "virtualColumn",
+ ],
+ ["columns", [["ID", "N", "NO"]], "incompleteMetadata"],
+ ["index", [["APP", "PK_SOURCE", "NORMAL", "UNIQUE", "VALID", "INVISIBLE", "NO"]], "unsupportedIndex"],
+ ["indexColumns", [["ID", 1, "DESC"]], "unsupportedIndex"],
+ [
+ "indexUsers",
+ [
+ ["APP", "SOURCE", "PK_SOURCE", "P"],
+ ["APP", "SOURCE", "UQ_OTHER", "U"],
+ ],
+ "sharedIndex",
+ ],
+ ["nulls", [[1]], "nullValues"],
+ ["duplicates", [[1]], "duplicateValues"],
+ ["nulls", [], "incompleteMetadata"],
+ ] as const)("rejects invalid %s metadata or data (%s)", async (key, value, expected) => {
+ fixture[key] = value.map((row) => [...row]);
+ await expect(readOceanbasePrimaryKeySnapshot(target, change)).rejects.toMatchObject({ key: expected });
+ });
+
+ it("rejects truncated query results", async () => {
+ truncated = true;
+ await expect(readOceanbasePrimaryKeySnapshot(target, change)).rejects.toMatchObject({ key: "incompleteMetadata" });
+ });
+
+ it("preserves metadata read failures", async () => {
+ vi.mocked(api.listIndexes).mockRejectedValue(new Error("permission denied"));
+ await expect(readOceanbasePrimaryKeySnapshot(target, change)).rejects.toThrow("permission denied");
+ });
+
+ it("checks all dependencies but skips new-key data checks for deletion", async () => {
+ await readOceanbasePrimaryKeySnapshot(target, { ...change, columns: [] });
+ expect(api.executeQuery.mock.calls.some((call) => call[2].includes("GROUP BY"))).toBe(false);
+ expect(api.executeQuery.mock.calls.some((call) => call[2].includes("R_CONSTRAINT_NAME"))).toBe(true);
+ });
+});
+
+describe("Native Oracle primary key index policy", () => {
+ const oracleTarget = { ...target, databaseType: "oracle" as const };
+
+ it("requires complete session and object identity and blocks session drift before DDL", async () => {
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => (String(args[2]).includes("SYS_CONTEXT") ? (Promise.resolve({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 }) as never) : read(...args)));
+ await expect(readOceanbasePrimaryKeySnapshot(oracleTarget, { ...change, columns: [] })).rejects.toMatchObject({ key: "incompleteMetadata" });
+ expect(api.executeQuery.mock.calls.some((call) => String(call[2]).includes("SYS.ALL_OBJECTS") && String(call[2]).includes("OBJECT_NAME = 'SOURCE'"))).toBe(true);
+
+ vi.mocked(api.executeQuery).mockImplementation(read);
+ const deletion = { ...change, columns: [] };
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, deletion);
+ capturedIdentity = [["OTHER_USER", "APP", "ORCL"]];
+ await expect(executeOceanbasePrimaryKeyPlan({ target: oracleTarget, ...prepared, statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE" KEEP INDEX;'] }, 60, () => true)).rejects.toMatchObject({ key: "definitionChanged" });
+ expect(api.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER TABLE"))).toBe(false);
+ });
+
+ it.each([
+ ["missing session identity", "session", []],
+ [
+ "multiple session identities",
+ "session",
+ [
+ ["APP", "APP", "ORCL"],
+ ["APP", "APP", "ORCL"],
+ ],
+ ],
+ ["missing object identity", "object", null],
+ [
+ "multiple object identities",
+ "object",
+ [
+ ["APP", "SOURCE", 77],
+ ["APP", "SOURCE", 78],
+ ],
+ ],
+ ["invalid object identity", "object", "not-an-id"],
+ ] as const)("rejects %s before returning a snapshot", async (_label, identityKind, value) => {
+ if (identityKind === "session") capturedIdentity = value as unknown[][];
+ else capturedObjectId = value;
+
+ await expect(readOceanbasePrimaryKeySnapshot(oracleTarget, { ...change, columns: [] })).rejects.toMatchObject({ key: "incompleteMetadata" });
+ });
+
+ it("refuses execution when the captured table object is replaced with the same PK metadata", async () => {
+ let objectId: number = 77;
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ if (String(args[2]).startsWith("ALTER TABLE")) return Promise.resolve({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 }) as never;
+ if (String(args[2]).includes("SYS.ALL_OBJECTS")) return Promise.resolve({ columns: [], rows: [["APP", "SOURCE", objectId]], affected_rows: 0, execution_time_ms: 0 }) as never;
+ return read(...args);
+ });
+ const deletion = { ...change, columns: [] };
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, deletion);
+ objectId = 78;
+
+ await expect(executeOceanbasePrimaryKeyPlan({ target: oracleTarget, ...prepared, statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE" KEEP INDEX;'] }, 60, () => true)).rejects.toMatchObject({ key: "definitionChanged" });
+
+ expect(vi.mocked(api.executeQuery).mock.calls.some((args) => String(args[2]).startsWith("ALTER TABLE"))).toBe(false);
+ });
+
+ it("refuses OceanBase execution when the captured table object is replaced", async () => {
+ let objectId = 77;
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => (String(args[2]).includes("SYS.ALL_OBJECTS") ? (Promise.resolve({ columns: [], rows: [["APP", "SOURCE", objectId]], affected_rows: 0, execution_time_ms: 0 }) as never) : read(...args)));
+ const deletion = { ...change, columns: [] };
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, deletion);
+ objectId = 78;
+
+ await expect(executeOceanbasePrimaryKeyPlan({ target, change: deletion, snapshot, statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE";'] }, 60, () => true)).rejects.toMatchObject({ key: "definitionChanged" });
+
+ expect(vi.mocked(api.executeQuery).mock.calls.some((args) => String(args[2]).startsWith("ALTER TABLE"))).toBe(false);
+ });
+
+ it.each(["external", "unreadable"])("blocks %s table metadata before any DDL", async (mode) => {
+ const originalQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ if (args[2].includes("SYS.ALL_EXTERNAL_TABLES")) {
+ if (mode === "unreadable") return Promise.reject(new Error("external metadata denied"));
+ return Promise.resolve({ columns: [], rows: [["SOURCE"]], affected_rows: 0, execution_time_ms: 0 });
+ }
+ return originalQuery(...args);
+ });
+ await expect(executeOceanbasePrimaryKeyPlan({ target: oracleTarget, change: { ...change, columns: [] }, snapshot: "", statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE";'] }, 60, () => true)).rejects.toThrow(
+ mode === "external" ? "unsupportedTable" : "external metadata denied",
+ );
+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ });
+
+ it("ignores meaningless RELY changes on a validated key but invalidates a NOVALIDATE plan", async () => {
+ let rely: unknown = null;
+ const originalQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => (args[2].startsWith("SELECT RELY ") ? Promise.resolve({ columns: [], rows: [[rely]], affected_rows: 0, execution_time_ms: 0 }) : originalQuery(...args)));
+ const deletion = { ...change, columns: [] };
+ const validated = await prepareOraclePrimaryKeyChange(oracleTarget, deletion);
+ rely = "RELY";
+ await expect(readOceanbasePrimaryKeySnapshot(oracleTarget, validated.change)).resolves.toBe(validated.snapshot);
+ fixture.key[0]![2] = "NOT VALIDATED";
+ vi.mocked(api.listConstraints).mockResolvedValue([{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled: true, valid: false, deferrable: false, initially_deferred: false }]);
+ const unvalidated = await prepareOraclePrimaryKeyChange(oracleTarget, deletion);
+ rely = null;
+ await expect(executeOceanbasePrimaryKeyPlan({ target: oracleTarget, ...unvalidated, statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE";'] }, 60, () => true)).rejects.toMatchObject({ key: "definitionChanged" });
+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ });
+
+ it.each(["disabled-none", "disabled-keep", "deferred-keep"])("preserves %s state in deletion readback and manual recovery", async (mode) => {
+ const enabled = mode === "deferred-keep";
+ const indexed = mode !== "disabled-none";
+ fixture.key = [["PK_SOURCE", enabled ? "ENABLED" : "DISABLED", "NOT VALIDATED", enabled ? "DEFERRABLE" : "NOT DEFERRABLE", enabled ? "DEFERRED" : "IMMEDIATE", indexed ? "APP" : null, indexed ? "PK_SOURCE" : null]];
+ fixture.index[0]![3] = "NONUNIQUE";
+ const constraint = { name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled, valid: false, deferrable: enabled, initially_deferred: enabled };
+ vi.mocked(api.listConstraints).mockResolvedValue([constraint]);
+ // Same-named independent index must remain untouched for a key with no index association.
+ vi.mocked(api.listIndexes).mockResolvedValue([{ name: "PK_SOURCE", columns: ["ID"], is_primary: indexed, is_unique: false, index_type: "NORMAL" }]);
+ const originalQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ const sql = args[2];
+ const result = (rows: unknown[][] = []) => Promise.resolve({ columns: [], rows, affected_rows: 0, execution_time_ms: 0 });
+ if (sql.startsWith("SELECT RELY ")) return result([["RELY"]]);
+ if (sql.startsWith("ALTER ")) {
+ vi.mocked(api.listConstraints).mockResolvedValue([]);
+ return result();
+ }
+ if (sql.includes("PARTITIONED, TABLE_OWNER")) return result(fixture.index.map((row) => [...row, "APP", "SOURCE"]));
+ return originalQuery(...args);
+ });
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, { ...change, columns: [] });
+ const statements = [`ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE"${indexed ? " KEEP INDEX" : ""};`];
+ const result = await executeOceanbasePrimaryKeyPlan({ target: oracleTarget, ...prepared, statements }, 60, () => true);
+ expect(result?.readbackError).toBeUndefined();
+ expect(result?.steps.map((step) => step.state)).toEqual(["committed"]);
+ expect(result?.recoverySql).toBe(`ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("ID") ${enabled ? "DEFERRABLE INITIALLY DEFERRED" : "NOT DEFERRABLE INITIALLY IMMEDIATE"} RELY${enabled ? ' USING INDEX "APP"."PK_SOURCE"' : ""} ${enabled ? "ENABLE" : "DISABLE"} NOVALIDATE;`);
+ expect(result?.indexStates).toEqual(indexed ? [{ name: "APP.PK_SOURCE", state: "indexPresent" }] : []);
+ if (!indexed) expect(api.executeQuery.mock.calls.some((call) => call[2].includes("SYS.ALL_INDEXES") || call[2].includes("SYS.ALL_IND_COLUMNS"))).toBe(false);
+ });
+
+ it("captures a disabled unvalidated Oracle key without inventing a supporting index", async () => {
+ fixture.key = [["PK_SOURCE", "DISABLED", "NOT VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, null]];
+ fixture.index = [];
+ fixture.indexColumns = [];
+ fixture.indexUsers = [];
+ vi.mocked(api.listIndexes).mockResolvedValue([]);
+ vi.mocked(api.listConstraints).mockResolvedValue([{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled: false, valid: false, deferrable: false, initially_deferred: false }]);
+ const originalQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => (args[2].startsWith("SELECT RELY ") ? Promise.resolve({ columns: [], rows: [["RELY"]], affected_rows: 0, execution_time_ms: 0 }) : originalQuery(...args)));
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, { ...change, columns: [] });
+ expect(prepared.change).toMatchObject({ oracleState: { enabled: false, validated: false, deferrable: false, initiallyDeferred: false, rely: true }, oracleIndex: { policy: "none", owner: "APP", name: "" } });
+ expect(api.executeQuery.mock.calls.some((call) => !call[2].startsWith("SELECT "))).toBe(false);
+ });
+
+ it("captures a deferred Oracle primary key backed by a nonunique index", async () => {
+ fixture.key[0]![3] = "DEFERRABLE";
+ fixture.key[0]![4] = "DEFERRED";
+ fixture.index[0]![3] = "NONUNIQUE";
+ vi.mocked(api.listIndexes).mockResolvedValue([{ name: "PK_SOURCE", columns: ["ID"], is_unique: false, is_primary: true, index_type: "NORMAL" }]);
+ vi.mocked(api.listConstraints).mockResolvedValue([{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled: true, valid: true, deferrable: true, initially_deferred: true }]);
+ const originalQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => (args[2].startsWith("SELECT RELY ") ? Promise.resolve({ columns: [], rows: [[null]], affected_rows: 0, execution_time_ms: 0 }) : originalQuery(...args)));
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, { ...change, columns: [] });
+ expect(prepared.change).toMatchObject({ oracleState: { enabled: true, validated: true, deferrable: true, initiallyDeferred: true, rely: false }, oracleIndex: { policy: "keep", owner: "APP", name: "PK_SOURCE" } });
+ });
+
+ it("does not report success when replacement loses the captured validation state", async () => {
+ fixture.key[0]![2] = "NOT VALIDATED";
+ const sourceConstraint = { name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled: true, valid: false, deferrable: false, initially_deferred: false };
+ vi.mocked(api.listConstraints).mockResolvedValue([sourceConstraint]);
+ let applied = false;
+ let newIndex = "";
+ const originalQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ const sql = args[2];
+ const result = (rows: unknown[][] = []) => Promise.resolve({ columns: [], rows, affected_rows: 0, execution_time_ms: 0 });
+ if (sql.startsWith("SELECT INDEX_NAME FROM SYS.ALL_INDEXES")) return result();
+ if (sql.includes(" DROP CONSTRAINT ")) {
+ vi.mocked(api.listConstraints).mockResolvedValue([]);
+ return result();
+ }
+ if (sql.includes(" ADD CONSTRAINT ")) {
+ applied = true;
+ vi.mocked(api.listConstraints).mockResolvedValue([{ ...sourceConstraint, columns: ["V"], valid: true }]);
+ return result();
+ }
+ if (applied && sql.startsWith("SELECT CONSTRAINT_NAME, STATUS")) return result([["PK_SOURCE", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", "APP", newIndex]]);
+ if (applied && sql.includes("PARTITIONED, TABLE_OWNER")) return result(sql.includes(`INDEX_NAME = '${newIndex}'`) ? [["APP", newIndex, "NORMAL", "NONUNIQUE", "VALID", "VISIBLE", "NO", "APP", "SOURCE"]] : fixture.index.map((row) => [...row, "APP", "SOURCE"]));
+ if (applied && sql.includes("SYS.ALL_IND_COLUMNS") && sql.includes(`INDEX_NAME = '${newIndex}'`)) return result([["V", 1, "ASC"]]);
+ return originalQuery(...args);
+ });
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, change);
+ newIndex = prepared.change.oracleIndex!.newName!;
+ const result = await executeOceanbasePrimaryKeyPlan(
+ {
+ target: oracleTarget,
+ ...prepared,
+ statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE" KEEP INDEX;', `ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("V") NOT DEFERRABLE INITIALLY IMMEDIATE NORELY USING INDEX (CREATE INDEX "APP"."${newIndex}" ON "APP"."SOURCE" ("V")) ENABLE NOVALIDATE;`],
+ },
+ 60,
+ () => true,
+ );
+ expect(result?.steps.map((step) => step.state)).toEqual(["committed", "committed"]);
+ expect(result?.indexStates?.map((index) => index.state)).toEqual(["indexPresent", "indexPresent"]);
+ expect(result?.readbackError).toBe("definitionChanged");
+ });
+
+ it("rejects a new index name taken after preview before executing DDL", async () => {
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].startsWith("SELECT INDEX_NAME")) return { columns: [], rows: [["SOURCE_V_IDX"]], affected_rows: 0, execution_time_ms: 0 };
+ return read(...args);
+ });
+ const verifiedChange = { ...change, oracleIndex: { policy: "keep" as const, owner: "APP", name: "PK_SOURCE", newName: "SOURCE_V_IDX" } };
+ await expect(readOceanbasePrimaryKeySnapshot(oracleTarget, verifiedChange)).rejects.toMatchObject({ key: "definitionChanged" });
+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ });
+
+ it("stops when the database rejects DROP for an invisible or concurrent reference", async () => {
+ const deletion = { ...change, columns: [], oracleIndex: { policy: "keep" as const, owner: "APP", name: "PK_SOURCE" } };
+ const snapshot = await readOceanbasePrimaryKeySnapshot(oracleTarget, deletion);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].startsWith("ALTER ")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0, execution_error: true, error: { detail: "ORA-02273: referenced by foreign keys" } };
+ if (args[2].includes("PARTITIONED, TABLE_OWNER")) return { columns: [], rows: fixture.index.map((row) => [...row, "APP", "SOURCE"]), affected_rows: 0, execution_time_ms: 0 };
+ return read(...args);
+ });
+ const result = await executeOceanbasePrimaryKeyPlan({ target: oracleTarget, change: deletion, snapshot, statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE" KEEP INDEX;'] }, 30, () => true);
+ expect(result?.steps[0]?.state).toBe("rejected");
+ expect(result?.recoverySql).toBeUndefined();
+ expect(result?.indexStates).toEqual([{ name: "APP.PK_SOURCE", state: "indexPresent" }]);
+ expect(api.executeQuery.mock.calls.filter((call) => call[2].startsWith("ALTER "))).toHaveLength(1);
+ });
+
+ it("allocates the new index name in the owner's namespace without changing the draft", async () => {
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].startsWith("SELECT INDEX_NAME FROM SYS.ALL_INDEXES")) {
+ const name = /INDEX_NAME = '([^']+)'/.exec(args[2])?.[1];
+ return { columns: [], rows: name === "SOURCE_V_IDX" ? [[name]] : [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ if (args[2].startsWith("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
+ return read(...args);
+ });
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, change);
+ expect(prepared.change.oracleIndex).toEqual({ policy: "keep", owner: "APP", name: "PK_SOURCE", newName: "SOURCE_V_IDX_2" });
+ expect(change).not.toHaveProperty("oracleIndex");
+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ });
+
+ it("allows editing a reordered key backed by the original index order", async () => {
+ fixture.keyColumns = [
+ ["V", 1],
+ ["ID", 2],
+ ];
+ fixture.indexColumns = [
+ ["ID", 1, "ASC"],
+ ["V", 2, "ASC"],
+ ];
+ vi.mocked(api.getColumns).mockResolvedValue(["ID", "V"].map((name) => ({ name, data_type: "NUMBER", is_nullable: false, is_primary_key: true })));
+ vi.mocked(api.listConstraints).mockResolvedValue([{ name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["V", "ID"], definition: "", ref_columns: [], enabled: true, valid: true, deferrable: false, initially_deferred: false }]);
+ vi.mocked(api.listIndexes).mockResolvedValue([{ name: "PK_SOURCE", columns: ["ID", "V"], is_unique: true, is_primary: true, index_type: "NORMAL" }]);
+ const draft = { name: "PK_SOURCE", originalColumns: ["V", "ID"], columns: ["ID", "V"] };
+ const prepared = await prepareOraclePrimaryKeyChange(oracleTarget, draft);
+ expect(prepared.change.oracleIndex).toEqual({ policy: "keep", owner: "APP", name: "PK_SOURCE" });
+ await expect(readOceanbasePrimaryKeySnapshot(oracleTarget, { ...prepared.change, columns: [] })).resolves.toBe(prepared.snapshot);
+ await expect(readOceanbasePrimaryKeySnapshot(target, draft)).rejects.toMatchObject({ key: "unsupportedIndex" });
+ });
+
+ it.each(["keep", "drop"] as const)("reads index state and supplies recovery after successful deletion with %s", async (policy) => {
+ const deletion = { ...change, columns: [], oracleIndex: { policy, owner: "APP", name: "PK_SOURCE" } };
+ const snapshot = await readOceanbasePrimaryKeySnapshot(oracleTarget, deletion);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let dropped = false;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ const sql = args[2];
+ if (sql.startsWith("ALTER ")) {
+ dropped = true;
+ vi.mocked(api.listConstraints).mockResolvedValue([]);
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ if (dropped && sql.includes("SYS.ALL_INDEXES")) return { columns: [], rows: policy === "keep" ? fixture.index.map((row) => [...row, "APP", "SOURCE"]) : [], affected_rows: 0, execution_time_ms: 0 };
+ if (dropped && sql.includes("SYS.ALL_IND_COLUMNS")) return { columns: [], rows: policy === "keep" ? fixture.indexColumns : [], affected_rows: 0, execution_time_ms: 0 };
+ return read(...args);
+ });
+ const result = await executeOceanbasePrimaryKeyPlan({ target: oracleTarget, change: deletion, snapshot, statements: [`ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE" ${policy.toUpperCase()} INDEX;`] }, 30, () => true);
+ expect(result?.steps[0]?.state).toBe("committed");
+ expect(result?.readbackError).toBeUndefined();
+ expect(result?.indexStates).toEqual([{ name: "APP.PK_SOURCE", state: policy === "keep" ? "indexPresent" : "indexAbsent" }]);
+ expect(result?.recoverySql).toBe(`ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("ID")${policy === "keep" ? ' USING INDEX "APP"."PK_SOURCE"' : ""};`);
+ expect(api.executeQuery.mock.calls.filter((call) => call[2].startsWith("ALTER "))).toHaveLength(1);
+ });
+
+ it("does not recommend reusing an index whose definition changed after DROP", async () => {
+ const deletion = { ...change, columns: [], oracleIndex: { policy: "keep" as const, owner: "APP", name: "PK_SOURCE" } };
+ const snapshot = await readOceanbasePrimaryKeySnapshot(oracleTarget, deletion);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let dropped = false;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].startsWith("ALTER ")) {
+ dropped = true;
+ vi.mocked(api.listConstraints).mockResolvedValue([]);
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ if (dropped && args[2].includes("SYS.ALL_INDEXES")) return { columns: [], rows: fixture.index.map((row) => [...row, "APP", "SOURCE"]), affected_rows: 0, execution_time_ms: 0 };
+ if (dropped && args[2].includes("SYS.ALL_IND_COLUMNS")) return { columns: [], rows: [["V", 1, "ASC"]], affected_rows: 0, execution_time_ms: 0 };
+ return read(...args);
+ });
+ const result = await executeOceanbasePrimaryKeyPlan({ target: oracleTarget, change: deletion, snapshot, statements: ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE" KEEP INDEX;'] }, 30, () => true);
+ expect(result?.readbackError).toBe("definitionChanged");
+ expect(result?.indexStates?.[0]?.state).toBe("indexChanged");
+ expect(result?.recoverySql).not.toContain("USING INDEX");
+ expect(result?.recoverySql?.split("\n").every((line) => line.startsWith("-- "))).toBe(true);
+ });
+});
+
+describe("OceanBase primary key independent DDL execution", () => {
+ const statements = ['ALTER TABLE "APP"."SOURCE" DROP CONSTRAINT "PK_SOURCE";', 'ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("V");'];
+
+ it("provides manual recovery after a successful intentional key deletion without executing it", async () => {
+ const deletion = { ...change, columns: [] };
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, deletion);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].includes(" DROP CONSTRAINT ")) {
+ vi.mocked(api.listConstraints).mockResolvedValue([]);
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ return read(...args);
+ });
+ const result = await executeOceanbasePrimaryKeyPlan({ target, change: deletion, snapshot, statements: statements.slice(0, 1) }, 30, () => true);
+ expect(result?.steps.map((step) => step.state)).toEqual(["committed"]);
+ expect(result?.readbackError).toBeUndefined();
+ expect(result?.recoverySql).toBe('ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "PK_SOURCE" PRIMARY KEY ("ID");');
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "))).toHaveLength(1);
+ });
+
+ it.each(["rejected", "unknown"] as const)("keeps a committed DROP when ADD has a %s outcome", async (outcome) => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].includes(" DROP CONSTRAINT ")) {
+ vi.mocked(api.listConstraints).mockResolvedValue([]);
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
+ }
+ if (args[2].includes(" ADD CONSTRAINT ")) {
+ if (outcome === "unknown") throw new Error("connection lost");
+ return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0, execution_error: true, error: { detail: "duplicate key" } };
+ }
+ return read(...args);
+ });
+ const result = await executeOceanbasePrimaryKeyPlan({ target, change, snapshot, statements }, 30, () => true);
+ expect(result?.steps.map((step) => step.state)).toEqual(["committed", outcome]);
+ expect(result?.recoverySql).toContain('PRIMARY KEY ("ID")');
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "))).toHaveLength(2);
+ });
+
+ it("does not execute ADD after DROP is rejected and does not suggest restoring an intact key", async () => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => (args[2].startsWith("ALTER ") ? { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0, execution_error: true, error: { detail: "ORA-02266" } } : read(...args)));
+ const result = await executeOceanbasePrimaryKeyPlan({ target, change, snapshot, statements }, 30, () => true);
+ expect(result?.steps.map((step) => step.state)).toEqual(["rejected", "notExecuted"]);
+ expect(result?.recoverySql).toBeUndefined();
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].startsWith("ALTER "))).toHaveLength(1);
+ });
+
+ it("preserves unknown execution when the original-target readback also fails", async () => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (args[2].startsWith("ALTER ")) {
+ vi.mocked(api.listConstraints).mockRejectedValue(new Error("readback unavailable"));
+ throw new Error("timeout");
+ }
+ return read(...args);
+ });
+ const result = await executeOceanbasePrimaryKeyPlan({ target, change, snapshot, statements }, 30, () => true);
+ expect(result?.steps.map((step) => step.state)).toEqual(["unknown", "notExecuted"]);
+ expect(result?.readbackError).toBe("readback unavailable");
+ expect(result?.recoverySql).toBeUndefined();
+ });
+
+ it("rejects a reference added after preview before sending DDL", async () => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ fixture.references = [["OTHER", "CHILD", "FK_NEW", "DISABLED"]];
+ await expect(executeOceanbasePrimaryKeyPlan({ target, change, snapshot, statements }, 30, () => true)).rejects.toMatchObject({ key: "referenced" });
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].startsWith("ALTER "))).toBe(false);
+ });
+
+ it("rejects a column definition changed after preview before dropping the original key", async () => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ vi.mocked(api.getColumns).mockResolvedValue(["ID", "V"].map((name) => ({ name, data_type: name === "V" ? "VARCHAR2(40)" : "NUMBER", is_nullable: false, is_primary_key: name === "ID", column_default: null })));
+ await expect(executeOceanbasePrimaryKeyPlan({ target, change, snapshot, statements }, 30, () => true)).rejects.toMatchObject({ key: "definitionChanged" });
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].startsWith("ALTER "))).toBe(false);
+ });
+
+ it("cancels before DDL when the editor target or draft changed during revalidation", async () => {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, change);
+ await expect(executeOceanbasePrimaryKeyPlan({ target, change, snapshot, statements }, 30, () => false)).resolves.toBeUndefined();
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].startsWith("ALTER "))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/database/__tests__/oracleConstraints.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleConstraints.spec.ts
new file mode 100644
index 0000000000..d8ad0630f9
--- /dev/null
+++ b/apps/desktop/src/lib/database/__tests__/oracleConstraints.spec.ts
@@ -0,0 +1,704 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import * as api from "@/lib/backend/api";
+import { executeOracleConstraintPlan, oracleConstraintDefinitionFromInfo, OracleConstraintMetadataError, prepareOracleConstraintPlan } from "../oracleConstraints";
+import type { ConstraintInfo } from "@/types/database";
+import type { OracleConstraintChange } from "@/lib/table/tableStructureEditorSql";
+
+vi.mock("@/lib/backend/api", () => ({ executeQuery: vi.fn(), listConstraints: vi.fn(), buildTableStructureChangeSql: vi.fn() }));
+
+const target = { connectionId: "fixture", database: "APP", schema: "APP", tableName: "CONTACTS", databaseType: "oracle" as const };
+const state = { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false };
+const uniqueInfo: ConstraintInfo = {
+ name: "UQ_PAIR",
+ constraint_type: "UNIQUE",
+ columns: ["A", "B"],
+ definition: "",
+ ref_columns: [],
+ enabled: true,
+ valid: true,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: {
+ metadataComplete: true,
+ owner: "APP",
+ constraintType: "U",
+ status: "ENABLED",
+ validated: "VALIDATED",
+ deferrable: "NOT DEFERRABLE",
+ deferred: "IMMEDIATE",
+ rely: null,
+ indexOwner: "APP",
+ indexName: "UQ_PAIR",
+ indexSharing: "exclusive",
+ index: {
+ metadataComplete: true,
+ owner: "APP",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: "N",
+ columns: ["A", "B"],
+ directions: ["ASC", "ASC"],
+ keyIsExpression: [false, false],
+ includedColumns: [],
+ },
+ },
+};
+const result = (rows: unknown[][]) => ({ execution_error: false, truncated: false, has_more: false, rows, error: undefined });
+
+function makeChange(): OracleConstraintChange {
+ const original = {
+ kind: "unique" as const,
+ definition: {
+ name: "UQ_PAIR",
+ columns: ["A", "B"],
+ state,
+ relyRaw: "NULL",
+ index: {
+ owner: "APP",
+ name: "UQ_PAIR",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ sharing: "exclusive",
+ metadataComplete: true,
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: "N",
+ columns: ["A", "B"],
+ directions: ["ASC", "ASC"],
+ keyIsExpression: [false, false],
+ includedColumns: [],
+ newNameAvailable: false,
+ },
+ },
+ };
+ return { original, target: { kind: "unique", definition: { ...original.definition, columns: ["B", "A"] } } };
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(api.listConstraints).mockResolvedValue([uniqueInfo]);
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: ['ALTER TABLE "APP"."CONTACTS" DROP CONSTRAINT "UQ_PAIR" KEEP INDEX;', 'ALTER TABLE "APP"."CONTACTS" ADD CONSTRAINT "UQ_PAIR" UNIQUE ("B", "A") USING INDEX "APP"."UQ_PAIR";'], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("R_CONSTRAINT_NAME")) return result([]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS")) return result(sql.includes("'UQ_PAIR'") ? [["UQ_PAIR"]] : []) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result(sql.includes("'UQ_PAIR'") ? [["UQ_PAIR"]] : []) as never;
+ return result([]) as never;
+ });
+});
+
+describe("Oracle CHECK/UNIQUE constraint preflight", () => {
+ it("checks duplicate composite keys including partial NULL keys and excludes all-NULL keys", async () => {
+ const change = makeChange();
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ expect(plan.statements).toHaveLength(2);
+ const duplicateScan = vi
+ .mocked(api.executeQuery)
+ .mock.calls.map((call) => String(call[2]))
+ .find((sql) => sql.includes("GROUP BY"));
+ expect(duplicateScan).toContain('WHERE "B" IS NOT NULL OR "A" IS NOT NULL');
+ expect(duplicateScan).toContain('GROUP BY "B", "A" HAVING COUNT(*) > 1');
+ });
+
+ it("stops before returning a plan when duplicate target keys are found", async () => {
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("R_CONSTRAINT_NAME")) return result([]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["UQ_PAIR"]]) as never;
+ if (sql.includes("GROUP BY")) return result([[1]]) as never;
+ return result([]) as never;
+ });
+ await expect(prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange())).rejects.toMatchObject({ reason: "invalidData" } satisfies Partial<OracleConstraintMetadataError>);
+ });
+
+ it("fails closed when constraint metadata is incomplete", async () => {
+ vi.mocked(api.listConstraints).mockResolvedValue([{ ...uniqueInfo, oracle_metadata: { ...uniqueInfo.oracle_metadata!, metadataComplete: false } }] as ConstraintInfo[]);
+ await expect(prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange())).rejects.toMatchObject({ reason: "incomplete" });
+ expect(api.buildTableStructureChangeSql).not.toHaveBeenCalled();
+ });
+
+ it("allows an OceanBase UNIQUE creation without requiring a pre-existing paired index", async () => {
+ const oceanbaseTarget = { ...target, databaseType: "oceanbase-oracle" as const };
+ vi.mocked(api.listConstraints).mockResolvedValue([{ ...uniqueInfo, oracle_metadata: { ...uniqueInfo.oracle_metadata!, index: { ...uniqueInfo.oracle_metadata!.index!, secondary: null } } }] as ConstraintInfo[]);
+ const change: OracleConstraintChange = {
+ original: null,
+ target: {
+ kind: "unique",
+ definition: {
+ name: "UQ_NEW",
+ columns: ["A", "B"],
+ state,
+ index: {
+ owner: "APP",
+ name: "",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ sharing: "exclusive",
+ metadataComplete: false,
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: ["A", "B"],
+ directions: ["ASC", "ASC"],
+ keyIsExpression: [false, false],
+ includedColumns: [],
+ newNameAvailable: false,
+ },
+ },
+ },
+ indexPolicy: "none",
+ };
+ const plan = await prepareOracleConstraintPlan(oceanbaseTarget, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ expect(plan.change.target?.kind).toBe("unique");
+ expect(plan.change.target?.kind === "unique" && plan.change.target.definition.index.metadataComplete).toBe(false);
+ expect(plan.statements).toHaveLength(2);
+ });
+
+ it("reads back an Oracle UNIQUE and its generated supporting-index name", async () => {
+ let ddlApplied = false;
+ let generatedIndexName = "";
+ const createdInfo = (): ConstraintInfo => ({
+ ...uniqueInfo,
+ name: "UQ_NEW",
+ columns: ["A"],
+ oracle_metadata: {
+ ...uniqueInfo.oracle_metadata!,
+ indexName: generatedIndexName,
+ index: { ...uniqueInfo.oracle_metadata!.index!, columns: ["A"], directions: ["ASC"], keyIsExpression: [false] },
+ },
+ });
+ vi.mocked(api.listConstraints).mockImplementation(async () => (ddlApplied ? [createdInfo()] : [uniqueInfo]));
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: ['ALTER TABLE "APP"."CONTACTS" ADD CONSTRAINT "UQ_NEW" UNIQUE ("A");'], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) {
+ ddlApplied = true;
+ return result([]) as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS")) return result([]) as never;
+ if (sql.includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES") && sql.includes("INDEX_NAME =")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([[ddlApplied ? "UQ_NEW" : "UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([[ddlApplied ? generatedIndexName : "UQ_PAIR"]]) as never;
+ return result([]) as never;
+ });
+ const change: OracleConstraintChange = {
+ original: null,
+ target: {
+ kind: "unique",
+ definition: {
+ name: "UQ_NEW",
+ columns: ["A"],
+ state,
+ index: {
+ owner: "APP",
+ name: "",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ sharing: "exclusive",
+ metadataComplete: false,
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: "N",
+ columns: ["A"],
+ directions: ["ASC"],
+ keyIsExpression: [false],
+ includedColumns: [],
+ newNameAvailable: false,
+ },
+ },
+ },
+ };
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ generatedIndexName = plan.change.target?.kind === "unique" ? plan.change.target.definition.index.newName! : "";
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => true);
+ expect(generatedIndexName).toBeTruthy();
+ expect(outcome?.steps.map((step) => step.state)).toEqual(["committed"]);
+ expect(outcome?.readbackError).toBeUndefined();
+ });
+
+ it("plans an enabled NOVALIDATE UNIQUE with a new nonunique supporting index", async () => {
+ const base = makeChange().target!;
+ const change: OracleConstraintChange = {
+ original: null,
+ target: {
+ kind: "unique",
+ definition: {
+ ...base.definition,
+ name: "UQ_NOVALIDATE",
+ state: { ...state, validated: false },
+ index: { ...base.definition.index, name: "", metadataComplete: false, uniqueness: "UNIQUE", newName: undefined, newNameAvailable: false },
+ },
+ },
+ };
+
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change);
+
+ expect(plan.change.target?.kind === "unique" && plan.change.target.definition.index).toMatchObject({ uniqueness: "NONUNIQUE", newNameAvailable: true });
+ expect(api.buildTableStructureChangeSql).toHaveBeenCalledWith(
+ expect.objectContaining({ oracleConstraintChanges: [expect.objectContaining({ target: expect.objectContaining({ definition: expect.objectContaining({ state: { ...state, validated: false }, index: expect.objectContaining({ uniqueness: "NONUNIQUE" }) }) }) })] }),
+ );
+ });
+
+ it("does not rename a frozen support-index candidate when it becomes occupied", async () => {
+ const change = makeChange();
+ change.indexPolicy = "drop";
+ let occupied = "";
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ const sql = String(args[2]);
+ const indexName = /INDEX_NAME = '([^']+)'/.exec(sql)?.[1];
+ if (sql.includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES") && indexName) return Promise.resolve(result(indexName === occupied ? [[indexName]] : [])) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS") && /CONSTRAINT_NAME =/.test(sql)) return Promise.resolve(result([])) as never;
+ return read(...args);
+ });
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ occupied = plan.change.target?.kind === "unique" ? plan.change.target.definition.index.newName! : "";
+
+ await expect(executeOracleConstraintPlan(plan, 0, () => true)).rejects.toMatchObject({ reason: "changed" });
+
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => String(call[2]).startsWith("ALTER TABLE"))).toBe(false);
+ });
+
+ it("reads back a new OceanBase UNIQUE constraint as a paired object", async () => {
+ let ddlApplied = false;
+ const oceanbaseTarget = { ...target, databaseType: "oceanbase-oracle" as const };
+ const createdInfo: ConstraintInfo = {
+ ...uniqueInfo,
+ name: "UQ_NEW",
+ columns: ["A"],
+ oracle_metadata: { ...uniqueInfo.oracle_metadata!, indexName: "UQ_NEW", index: { ...uniqueInfo.oracle_metadata!.index!, secondary: null, columns: ["A"], directions: ["ASC"], keyIsExpression: [false] } },
+ };
+ vi.mocked(api.listConstraints).mockImplementation(async () => (ddlApplied ? [createdInfo] : [{ ...uniqueInfo, oracle_metadata: { ...uniqueInfo.oracle_metadata!, index: { ...uniqueInfo.oracle_metadata!.index!, secondary: null } } }]));
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: ['ALTER TABLE "APP"."CONTACTS" ADD CONSTRAINT "UQ_NEW" UNIQUE ("A");'], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) {
+ ddlApplied = true;
+ return result([]) as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS")) return result([["APP", "UQ_NEW", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([[ddlApplied ? "UQ_NEW" : "UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["UQ_NEW"]]) as never;
+ return result([]) as never;
+ });
+ const change: OracleConstraintChange = {
+ original: null,
+ target: {
+ kind: "unique",
+ definition: {
+ name: "UQ_NEW",
+ columns: ["A"],
+ state,
+ index: {
+ owner: "APP",
+ name: "",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ sharing: "exclusive",
+ metadataComplete: false,
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: ["A"],
+ directions: ["ASC"],
+ keyIsExpression: [false],
+ includedColumns: [],
+ newNameAvailable: false,
+ },
+ },
+ },
+ indexPolicy: "none",
+ };
+ const plan = await prepareOracleConstraintPlan(oceanbaseTarget, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => true);
+ expect(outcome?.steps.map((step) => step.state)).toEqual(["committed"]);
+ expect(outcome?.readbackError).toBeUndefined();
+ });
+
+ it.each([
+ { identity: "table object id", objectId: 78, databaseName: "ORCL" },
+ { identity: "database name", objectId: 77, databaseName: "OTHER" },
+ ])("stops after one DDL when the $identity changes mid-plan", async ({ objectId, databaseName }) => {
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange());
+ let ddlStarted = false;
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) {
+ ddlStarted = true;
+ return result([]) as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", ddlStarted ? databaseName : "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", ddlStarted ? objectId : 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("R_CONSTRAINT_NAME")) return result([]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["UQ_PAIR"]]) as never;
+ return result([]) as never;
+ });
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => true);
+ expect(outcome?.steps.map((step) => step.state)).toEqual(["committed", "notExecuted"]);
+ expect(outcome?.readbackError).toContain("identity changed");
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(1);
+ });
+
+ it("records a rejected DDL and never sends later statements", async () => {
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange());
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) return { ...result([]), execution_error: true, error: { detail: "database rejected" } } as never;
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("R_CONSTRAINT_NAME")) return result([]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["UQ_PAIR"]]) as never;
+ return result([]) as never;
+ });
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => true);
+ expect(outcome?.steps.map((step) => step.state)).toEqual(["rejected", "notExecuted"]);
+ expect(outcome?.steps[0]?.error).toContain("database rejected");
+ expect(outcome?.steps[0]?.error).toContain("Original definition remains after readback.");
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(1);
+ });
+
+ it.each(["rejection", "throw"] as const)("does not read CHECK metadata after a stale DDL %s", async (mode) => {
+ const checkInfo: ConstraintInfo = {
+ name: "CK_AGE",
+ constraint_type: "CHECK",
+ columns: [],
+ definition: "AGE > 0",
+ ref_columns: [],
+ enabled: true,
+ valid: true,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: { ...uniqueInfo.oracle_metadata!, constraintType: "C", indexOwner: null, indexName: null, indexSharing: null, index: null },
+ };
+ vi.mocked(api.listConstraints).mockResolvedValue([checkInfo]);
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: ['ALTER TABLE "APP"."CONTACTS" DROP CONSTRAINT "CK_AGE";', 'ALTER TABLE "APP"."CONTACTS" ADD CONSTRAINT "CK_AGE" CHECK (AGE >= 0);'], warnings: [] } as never);
+ const change = {
+ original: { kind: "check" as const, definition: { name: "CK_AGE", expression: "AGE > 0", state } },
+ target: { kind: "check" as const, definition: { name: "CK_AGE", expression: "AGE >= 0", state } },
+ } satisfies OracleConstraintChange;
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ const base = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let current = true;
+ let metadataReadAfterStale = false;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ const sql = String(args[2]);
+ if (sql.startsWith("ALTER TABLE")) {
+ current = false;
+ if (mode === "throw") throw new Error("connection lost");
+ return { ...result([]), execution_error: true, error: { detail: "constraint rejected" } } as never;
+ }
+ if (!current && sql.includes("SYS_CONTEXT")) metadataReadAfterStale = true;
+ return base(...args);
+ });
+
+ await executeOracleConstraintPlan(plan, 0, () => current);
+
+ expect(metadataReadAfterStale).toBe(false);
+ });
+
+ it("does not read metadata when execution starts on a stale generation", async () => {
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange());
+ vi.mocked(api.executeQuery).mockClear();
+ vi.mocked(api.listConstraints).mockClear();
+
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => false);
+
+ expect(outcome).toBeUndefined();
+ expect(api.executeQuery).not.toHaveBeenCalled();
+ expect(api.listConstraints).not.toHaveBeenCalled();
+ });
+
+ it("stops bounded support-index name allocation after repeated owner conflicts", async () => {
+ const change = makeChange();
+ change.indexPolicy = "drop";
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS")) return result([["APP", "OLD_INDEX", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("R_CONSTRAINT_NAME") || sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES") && sql.includes("INDEX_NAME =")) return result([["occupied"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS") && sql.includes("CONSTRAINT_NAME =")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["OLD_INDEX"]]) as never;
+ return result([]) as never;
+ });
+
+ await expect(prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change)).rejects.toMatchObject({ reason: "changed" });
+
+ expect(api.executeQuery.mock.calls.filter((call) => String(call[2]).includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES") && String(call[2]).includes("INDEX_NAME =")).length).toBe(64);
+ expect(api.buildTableStructureChangeSql).not.toHaveBeenCalled();
+ });
+
+ it("reports an in-flight DDL outcome as unknown after its generation changes", async () => {
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange());
+ const base = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let finish!: (value: ReturnType<typeof result>) => void;
+ let current = true;
+ vi.mocked(api.executeQuery).mockImplementation((...args) =>
+ String(args[2]).startsWith("ALTER TABLE")
+ ? (new Promise((resolve) => {
+ finish = resolve as typeof finish;
+ }) as never)
+ : base(...args),
+ );
+ const pending = executeOracleConstraintPlan(plan, 0, () => current);
+ while (!finish) await new Promise((resolve) => setTimeout(resolve, 0));
+ current = false;
+ finish(result([]));
+
+ const outcome = await pending;
+
+ expect(outcome?.steps[0]?.state).toBe("unknown");
+ });
+
+ it.each(["execution_error", "throw"] as const)("builds a manual recovery candidate after DROP commits and ADD returns %s", async (mode) => {
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange());
+ let dropped = false;
+ vi.mocked(api.listConstraints).mockImplementation(async () => (dropped ? [] : [uniqueInfo]));
+ let recoveryBuilt = false;
+ let applyBuildCalls = 0;
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async () => {
+ if (++applyBuildCalls === 1) return { statements: plan.statements, warnings: [] } as never;
+ recoveryBuilt = true;
+ return { statements: ["ALTER TABLE recovery ADD constraint"], warnings: [] } as never;
+ });
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) {
+ if (sql.includes("DROP CONSTRAINT")) {
+ dropped = true;
+ return result([]) as never;
+ }
+ if (mode === "throw") throw new Error("ADD response lost");
+ return { ...result([]), execution_error: true, error: { detail: "ADD rejected" } } as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return dropped
+ ? (result([]) as never)
+ : (result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never);
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("R_CONSTRAINT_NAME")) return result([]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS")) return result([]) as never;
+ if (sql.includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES") && sql.includes("INDEX_NAME =")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result(dropped ? [] : [["UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["UQ_PAIR"]]) as never;
+ return result([]) as never;
+ });
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => true);
+ expect(outcome?.steps.map((step) => step.state)).toEqual(mode === "throw" ? ["committed", "unknown"] : ["committed", "rejected"]);
+ expect(recoveryBuilt).toBe(true);
+ });
+
+ it("does not send the next DDL when the fixed connection generation changes", async () => {
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, makeChange());
+ let current = true;
+ const read = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ if (String(args[2]).startsWith("ALTER TABLE")) {
+ current = false;
+ return Promise.resolve(result([])) as never;
+ }
+ return read(...args);
+ });
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => current);
+ expect(outcome?.steps.map((step) => step.state)).toEqual(["unknown", "notExecuted"]);
+ expect(outcome?.readbackError).toContain("Connection or target changed");
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(1);
+ });
+
+ it("accepts a CHECK expression readback with equivalent Oracle whitespace normalization", async () => {
+ let ddlApplied = false;
+ const checkInfo: ConstraintInfo = {
+ name: "CK_POSITIVE",
+ constraint_type: "CHECK",
+ columns: [],
+ definition: '"A">=1',
+ ref_columns: [],
+ enabled: true,
+ valid: true,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: { metadataComplete: true, owner: "APP", constraintType: "C", status: "ENABLED", validated: "VALIDATED", deferrable: "NOT DEFERRABLE", deferred: "IMMEDIATE", rely: null, indexOwner: null, indexName: null, indexSharing: null, index: null },
+ };
+ vi.mocked(api.listConstraints).mockImplementation(async () => (ddlApplied ? [checkInfo] : []));
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: ['ALTER TABLE "APP"."CONTACTS" ADD CONSTRAINT "CK_POSITIVE" CHECK ("A" >= 1);'], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (sql.startsWith("ALTER TABLE")) {
+ ddlApplied = true;
+ return result([]) as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "A", "ASC", null],
+ ["APP", "UQ_PAIR", "APP", "CONTACTS", "NORMAL", "UNIQUE", "VALID", "NO", "VISIBLE", "N", "B", "ASC", null],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["A", "NUMBER", 22, null, 0, "Y"],
+ ["B", "NUMBER", 22, null, 0, "Y"],
+ ]) as never;
+ if (sql.includes("INDEX_NAME IS NOT NULL")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([[ddlApplied ? "CK_POSITIVE" : "UQ_PAIR", "CONTACTS"]]) as never;
+ if (sql.includes("SYS.ALL_INDEXES")) return result([["UQ_PAIR"]]) as never;
+ return result([]) as never;
+ });
+ const change: OracleConstraintChange = { original: null, target: { kind: "check", definition: { name: "CK_POSITIVE", expression: '"A" >= 1', state } } };
+ const plan = await prepareOracleConstraintPlan(target, { tableName: target.tableName, columns: [], indexes: [] }, change);
+ const outcome = await executeOracleConstraintPlan(plan, 0, () => true);
+ expect(outcome?.steps.map((step) => step.state)).toEqual(["committed"]);
+ expect(outcome?.readbackError).toBeUndefined();
+ });
+
+ it("converts disabled UNIQUE constraint with SQL NULL index into no-index definition", () => {
+ const disabledInfo: ConstraintInfo = {
+ name: "UQ_DISABLED_NO_IDX",
+ constraint_type: "UNIQUE",
+ columns: ["EMAIL"],
+ definition: "",
+ ref_columns: [],
+ enabled: false,
+ valid: false,
+ deferrable: false,
+ initially_deferred: false,
+ oracle_metadata: {
+ metadataComplete: true,
+ owner: "APP",
+ constraintType: "U",
+ status: "DISABLED",
+ validated: "NOT VALIDATED",
+ deferrable: "NOT DEFERRABLE",
+ deferred: "IMMEDIATE",
+ rely: null,
+ indexOwner: null,
+ indexName: null,
+ indexSharing: null,
+ index: null,
+ },
+ };
+ const definition = oracleConstraintDefinitionFromInfo(disabledInfo, target);
+ expect(definition.kind).toBe("unique");
+ if (definition.kind === "unique") {
+ expect(definition.definition.name).toBe("UQ_DISABLED_NO_IDX");
+ expect(definition.definition.state.enabled).toBe(false);
+ expect(definition.definition.index.name).toBe("");
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/database/__tests__/oracleForeignKeys.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleForeignKeys.spec.ts
new file mode 100644
index 0000000000..ef22eac05e
--- /dev/null
+++ b/apps/desktop/src/lib/database/__tests__/oracleForeignKeys.spec.ts
@@ -0,0 +1,868 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import * as api from "@/lib/backend/api";
+import {
+ parseOracleForeignKeyDdl,
+ readOracleForeignKeyDefinitions,
+ readOracleForeignKeyConstraintNames,
+ readOracleForeignKeySourceSnapshot,
+ validateOracleForeignKeySourceChanges,
+ readOracleForeignKeyReferenceSnapshot,
+ validateOracleForeignKeyReference,
+ compareOracleForeignKeyColumnTypes,
+ checkOracleForeignKeyData,
+ prepareOracleForeignKeyPlan,
+ executeOracleForeignKeyPlan,
+ prepareOracleForeignKeyCreatePlan,
+ executeOracleForeignKeyCreatePlan,
+ type OracleForeignKeyTarget,
+ type OracleForeignKeySourceSnapshot,
+} from "../oracleForeignKeys";
+
+vi.mock("@/lib/backend/api", () => ({ executeQuery: vi.fn(), buildTableStructureChangeSql: vi.fn(), buildCreateTableSql: vi.fn() }));
+const target: OracleForeignKeyTarget = { connectionId: "fixture", database: "APP", schema: "App Owner", tableName: "Child,Table", databaseType: "oracle" };
+const state = { enabled: false, validated: false, deferrable: true, initiallyDeferred: true, rely: true };
+const ddl = `ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK""name" FOREIGN KEY ("B", " A,quoted ") REFERENCES "Parent Owner"."Parent,Table" ("V", "ID""quoted") ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED RELY DISABLE NOVALIDATE;`;
+const row = ['FK"name', "DISABLED", "NOT VALIDATED", "DEFERRABLE", "DEFERRED", "RELY", "Parent Owner", "PK_PARENT", "SET NULL"];
+const result = (rows: unknown[][]) => ({ columns: [], rows, execution_time_ms: 0, rows_affected: 0 });
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => result(sql.includes("SYS.ALL_TABLES") ? [[target.schema, target.tableName]] : sql.includes("SYS.ALL_CONSTRAINTS") ? [row] : [[ddl]]) as never);
+});
+
+describe("Oracle foreign key definition reads", () => {
+ it.each([
+ { user: "Other Owner", owner: "App Owner", view: "SYS.ALL_CONSTRAINTS" },
+ { user: "app", owner: "APP", view: "SYS.ALL_CONSTRAINTS" },
+ { user: "App Owner", owner: "App Owner", view: "SYS.USER_CONSTRAINTS" },
+ ])("selects the name namespace from exact USER=$user, owner=$owner", async ({ user, owner, view }) => {
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => result(sql.includes("SELECT USER") ? [[user]] : [["FK_NAME", "SOURCE"]]) as never);
+ await expect(readOracleForeignKeyConstraintNames({ ...target, schema: owner, databaseType: "oceanbase-oracle" })).resolves.toEqual([{ name: "FK_NAME", table: "SOURCE" }]);
+ expect(vi.mocked(api.executeQuery).mock.calls[1]![2]).toContain(view);
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => !call[2].includes("CURRENT_SCHEMA"))).toBe(true);
+ });
+
+ it.each([{ users: [] }, { users: [[""]] }, { users: [[null]] }, { users: [["APP"], ["OTHER"]] }])("rejects invalid USER metadata without falling back ($users)", async ({ users }) => {
+ vi.mocked(api.executeQuery).mockResolvedValue(result(users) as never);
+ await expect(readOracleForeignKeyConstraintNames({ ...target, databaseType: "oceanbase-oracle" })).rejects.toThrow();
+ expect(api.executeQuery).toHaveBeenCalledTimes(1);
+ });
+ it("reads an OB owner key hidden from ALL under column-level REFERENCES", async () => {
+ const ownedTarget = { ...target, databaseType: "oceanbase-oracle" as const };
+ const ownRow = [row[0], "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, ...row.slice(6)];
+ const ownDdl = ddl.replace("DEFERRABLE INITIALLY DEFERRED RELY DISABLE NOVALIDATE;", "ENABLE;");
+ vi.mocked(api.executeQuery).mockImplementation(
+ async (_id, _db, sql) => result(sql.includes("SYS.ALL_TABLES") ? [[target.schema, target.tableName]] : sql.includes("SELECT USER") ? [[target.schema]] : sql.includes("SYS.USER_CONSTRAINTS") ? [ownRow] : sql.includes("SYS.ALL_CONSTRAINTS") ? [] : [[ownDdl]]) as never,
+ );
+ await expect(readOracleForeignKeyDefinitions(ownedTarget)).resolves.toHaveLength(1);
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => call[2].includes("SYS.USER_CONSTRAINTS"))).toBe(true);
+ });
+ it("preserves real reverse composite pairs, quoted identities and every state", async () => {
+ const keys = await readOracleForeignKeyDefinitions(target);
+ expect(keys).toEqual([{ name: 'FK"name', columns: ["B", " A,quoted "], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ["V", 'ID"quoted'], onDelete: "SET NULL", state }]);
+ expect(api.executeQuery).toHaveBeenCalledTimes(3);
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ });
+
+ it("stops a segmented definition read when its generation changes after the first DDL fetch", async () => {
+ let current = true;
+ const secondRow = [...row];
+ secondRow[0] = "FK_SECOND";
+ const secondDdl = ddl.replace('"FK""name"', '"FK_SECOND"');
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SYS.ALL_TABLES")) return result([[target.schema, target.tableName]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([row, secondRow]) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) {
+ current = false;
+ return result([[sql.includes("FK_SECOND") ? secondDdl : ddl]]) as never;
+ }
+ return result([]) as never;
+ });
+
+ await expect(readOracleForeignKeyDefinitions(target, () => current)).rejects.toThrow();
+
+ expect(api.executeQuery.mock.calls.filter((call) => String(call[2]).includes("DBMS_METADATA.GET_DDL"))).toHaveLength(1);
+ });
+
+ it.each([
+ ddl + " DROP TABLE X",
+ ddl.replace("DISABLE", "DISABLE ENABLE"),
+ ddl.replace('"App Owner"', '"Other Owner"'),
+ ddl.replace('"Parent Owner"', '"Other Parent"'),
+ ddl.replace("SET NULL", "CASCADE"),
+ ddl.replace("NOVALIDATE", "VALIDATE"),
+ ddl.replace('"B", " A,quoted "', '"B", "B"'),
+ ddl.replace('"V", "ID""quoted"', '"V"'),
+ ddl.slice(0, 45),
+ ])("rejects unsupported, incomplete or inconsistent DDL", (input) => {
+ expect(() => parseOracleForeignKeyDdl(input, target, 'FK"name', "Parent Owner", "SET NULL", state)).toThrow();
+ });
+
+ it("does not guess unknown constraint status", async () => {
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => result(sql.includes("SYS.ALL_TABLES") ? [[target.schema, target.tableName]] : [[row[0], "UNKNOWN", ...row.slice(2)]]) as never);
+ await expect(readOracleForeignKeyDefinitions(target)).rejects.toThrow();
+ expect(api.executeQuery).toHaveBeenCalledTimes(2);
+ });
+
+ it("distinguishes visible empty table from missing metadata", async () => {
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => result(sql.includes("SYS.ALL_TABLES") ? [[target.schema, target.tableName]] : []) as never);
+ await expect(readOracleForeignKeyDefinitions(target)).resolves.toEqual([]);
+ vi.mocked(api.executeQuery).mockResolvedValue(result([]) as never);
+ await expect(readOracleForeignKeyDefinitions(target)).rejects.toThrow();
+ });
+
+ it("never returns a partial set after a second definition read fails", async () => {
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SYS.ALL_TABLES")) return result([[target.schema, target.tableName]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([row, ["FK_SECOND", ...row.slice(1)]]) as never;
+ if (sql.includes("FK_SECOND")) throw new Error("Metadata access denied");
+ return result([[ddl]]) as never;
+ });
+ await expect(readOracleForeignKeyDefinitions(target)).rejects.toThrow("Metadata access denied");
+ });
+
+ it("keeps every read bound to the captured target during a switch", async () => {
+ let release!: (value: ReturnType<typeof result>) => void;
+ vi.mocked(api.executeQuery).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve as typeof release;
+ }) as never,
+ );
+ const mutableTarget = { ...target };
+ const read = readOracleForeignKeyDefinitions(mutableTarget);
+ mutableTarget.connectionId = "other-connection";
+ mutableTarget.schema = "OTHER";
+ mutableTarget.tableName = "OTHER_TABLE";
+ release(result([[target.schema, target.tableName]]));
+ await expect(read).resolves.toHaveLength(1);
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => call[0] === target.connectionId && call[3] === target.schema)).toBe(true);
+ });
+});
+
+describe("Oracle foreign key source preflight", () => {
+ function sourceFixture(objectId: unknown = 516042) {
+ vi.mocked(api.executeQuery).mockImplementation(
+ async (_id, _db, sql) =>
+ result(
+ sql.includes("SYS_CONTEXT")
+ ? [["READER", target.schema]]
+ : sql.includes("SYS.ALL_OBJECTS")
+ ? [[target.schema, target.tableName, objectId]]
+ : sql.includes("SYS.ALL_TAB_COLS")
+ ? [
+ ["B", "NUMBER", 22, null, null, "Y"],
+ [" A,quoted ", "NUMBER", 22, 10, 0, "N"],
+ ]
+ : sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")
+ ? [
+ [row[0], target.tableName],
+ ["TAKEN", "OtherTable"],
+ ]
+ : sql.includes("SYS.ALL_TABLES")
+ ? [[target.schema, target.tableName]]
+ : sql.includes("SYS.ALL_CONSTRAINTS")
+ ? [row]
+ : [[ddl]],
+ ) as never,
+ );
+ }
+
+ it("captures physical object identity, column definitions and namespace without DDL", async () => {
+ sourceFixture();
+ const snapshot = await readOracleForeignKeySourceSnapshot(target);
+ expect(snapshot.objectId).toBe("516042");
+ expect(snapshot.user).toBe("READER");
+ expect(snapshot.columns[1]).toMatchObject({ name: " A,quoted ", precision: "10", scale: "0", nullable: false });
+ expect(snapshot.names).toContainEqual({ name: "TAKEN", table: "OtherTable" });
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ const original = snapshot.definitions[0]!;
+ expect(() => validateOracleForeignKeySourceChanges(snapshot, target, [{ original, target: { ...original, name: "FK_NEW" } }])).not.toThrow();
+ });
+
+ it.each([null, 0, Number.MAX_SAFE_INTEGER + 1, "unknown"])("rejects unusable source object id %s", async (objectId) => {
+ sourceFixture(objectId);
+ await expect(readOracleForeignKeySourceSnapshot(target)).rejects.toThrow();
+ });
+
+ it("refuses stale originals, occupied names, absent columns and duplicate pairs before writes", async () => {
+ sourceFixture();
+ const snapshot = await readOracleForeignKeySourceSnapshot(target);
+ const original = snapshot.definitions[0]!;
+ for (const change of [
+ { original: { ...original, onDelete: "CASCADE" as const }, target: original },
+ { original, target: { ...original, name: "TAKEN" } },
+ { original, target: { ...original, columns: ["MISSING", " A,quoted "] } },
+ { original, target: { ...original, refColumns: ["V", "V"] } },
+ ])
+ expect(() => validateOracleForeignKeySourceChanges(snapshot, target, [change])).toThrow();
+ });
+});
+
+describe("Oracle foreign key parent preflight", () => {
+ const definition = parseOracleForeignKeyDdl(ddl, target, 'FK"name', "Parent Owner", "SET NULL", state);
+ const source: OracleForeignKeySourceSnapshot = {
+ user: "READER",
+ currentSchema: target.schema,
+ objectId: "1",
+ columns: [
+ { name: "B", dataType: "NUMBER", length: "22", precision: null, scale: null, nullable: true },
+ { name: " A,quoted ", dataType: "NUMBER", length: "22", precision: null, scale: null, nullable: true },
+ ],
+ definitions: [definition],
+ referenceKeys: [{ name: definition.name, owner: definition.refSchema, constraint: "PK_PARENT" }],
+ names: [],
+ };
+ function parentFixture(columnOnly = false) {
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SESSION_PRIVS")) throw new Error("View unavailable");
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([[definition.refSchema, definition.refTable, 24]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS"))
+ return result([
+ ["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", 'ID"quoted', 1],
+ ["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "V", 2],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ['ID"quoted', "NUMBER"],
+ ["V", "NUMBER"],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result(columnOnly ? [] : [["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS"))
+ return result(
+ columnOnly
+ ? [
+ ['ID"quoted', "REFERENCES"],
+ ["V", "REFERENCES"],
+ ]
+ : [],
+ ) as never;
+ throw new Error("Unexpected query");
+ });
+ }
+
+ it.each([false, true])("accepts table/column REFERENCES without demanding SELECT (columnOnly=%s)", async (columnOnly) => {
+ parentFixture(columnOnly);
+ const parent = await readOracleForeignKeyReferenceSnapshot(target, source.user, definition);
+ expect(parent.references).toBe("present");
+ expect(() => validateOracleForeignKeyReference(parent, source, definition, true)).not.toThrow();
+ expect(parent.keys?.[0]?.columns).toEqual(['ID"quoted', "V"]);
+ expect(definition.refColumns).toEqual(["V", 'ID"quoted']);
+ });
+
+ it("preserves unknown parent visibility for single ADD but blocks a destructive replacement", async () => {
+ vi.mocked(api.executeQuery).mockResolvedValue(result([]) as never);
+ const parent = await readOracleForeignKeyReferenceSnapshot(target, source.user, definition);
+ expect(parent.objectId).toBeNull();
+ expect(parent.keys).toBeNull();
+ expect(() => validateOracleForeignKeyReference(parent, source, definition, false)).not.toThrow();
+ expect(() => validateOracleForeignKeyReference(parent, source, definition, true)).toThrow();
+ });
+
+ it("rejects enabled child against a known disabled parent and certain type mismatch", async () => {
+ parentFixture();
+ const parent = await readOracleForeignKeyReferenceSnapshot(target, source.user, definition);
+ const enabled = { ...definition, state: { ...state, enabled: true } };
+ const disabledParent = { ...parent, keys: parent.keys!.map((key) => ({ ...key, enabled: false })) };
+ expect(() => validateOracleForeignKeyReference(disabledParent, source, enabled, false)).toThrow();
+ expect(() => validateOracleForeignKeyReference(parent, { ...source, columns: source.columns.map((column) => ({ ...column, dataType: "VARCHAR2" })) }, definition, true)).toThrow();
+ });
+
+ it("rejects DATE to NUMBER foreign key replacement and enforces type matrix", async () => {
+ parentFixture();
+ const parent = await readOracleForeignKeyReferenceSnapshot(target, source.user, definition);
+ const dateSource: OracleForeignKeySourceSnapshot = {
+ ...source,
+ columns: source.columns.map((column) => ({ ...column, dataType: "DATE" })),
+ };
+ expect(() => validateOracleForeignKeyReference(parent, dateSource, definition, true)).toThrow();
+ });
+
+ it("evaluates canonical Oracle foreign key column type compatibility matrix", () => {
+ // Compatible same-type / normalized parameters
+ expect(compareOracleForeignKeyColumnTypes("NUMBER(10,2)", "NUMBER(5)")).toBe("compatible");
+ expect(compareOracleForeignKeyColumnTypes("VARCHAR2(100 BYTE)", "VARCHAR2(200 CHAR)")).toBe("compatible");
+ expect(compareOracleForeignKeyColumnTypes("TIMESTAMP(3)", "TIMESTAMP(6)")).toBe("compatible");
+ expect(compareOracleForeignKeyColumnTypes("RAW(16)", "RAW(32)")).toBe("compatible");
+
+ // Oracle NUMBER vs FLOAT and VARCHAR vs VARCHAR2
+ expect(compareOracleForeignKeyColumnTypes("FLOAT(126)", "NUMBER(38)", "oracle")).toBe("compatible");
+ expect(compareOracleForeignKeyColumnTypes("FLOAT(126)", "NUMBER(38)", "oceanbase-oracle")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("VARCHAR(50)", "VARCHAR2(50)", "oracle")).toBe("compatible");
+ expect(compareOracleForeignKeyColumnTypes("VARCHAR(50)", "VARCHAR2(50)", "oceanbase-oracle")).toBe("unknown");
+
+ // Incompatible types
+ expect(compareOracleForeignKeyColumnTypes("DATE", "NUMBER")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("DATE", "TIMESTAMP")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("CHAR", "NCHAR")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("VARCHAR2", "NVARCHAR2")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("BINARY_FLOAT", "BINARY_DOUBLE")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("BINARY_FLOAT", "NUMBER")).toBe("incompatible");
+ expect(compareOracleForeignKeyColumnTypes("TIMESTAMP", "TIMESTAMP WITH LOCAL TIME ZONE")).toBe("incompatible");
+
+ // Unknown types
+ expect(compareOracleForeignKeyColumnTypes("CUSTOM_TYPE", "NUMBER")).toBe("unknown");
+ expect(compareOracleForeignKeyColumnTypes("NUMBER", "CLOB")).toBe("unknown");
+ expect(compareOracleForeignKeyColumnTypes("VARCHAR2(100) INVALID_SUFFIX", "VARCHAR2(100)")).toBe("unknown");
+ });
+});
+
+describe("Oracle foreign key data preflight", () => {
+ const original = parseOracleForeignKeyDdl(ddl, target, 'FK"name', "Parent Owner", "SET NULL", state);
+ const validated = { ...original, state: { ...state, validated: true, rely: false } };
+
+ it("checks only fully nonnull composite rows and returns no business values", async () => {
+ vi.mocked(api.executeQuery).mockResolvedValue(result([]) as never);
+ await expect(checkOracleForeignKeyData(target, { original: null, target: validated }, false)).resolves.toEqual({ checked: true });
+ const sql = vi.mocked(api.executeQuery).mock.calls[0]![2];
+ expect(sql).toContain('SELECT 1 FROM "App Owner"."Child,Table"');
+ expect(sql).toContain('fk_child."B" IS NOT NULL AND fk_child." A,quoted " IS NOT NULL');
+ expect(sql).toContain('fk_parent."V" = fk_child."B" AND fk_parent."ID""quoted" = fk_child." A,quoted "');
+ expect(sql).toContain("ROWNUM <= 1");
+ });
+
+ it("does not scan NOVALIDATE or pure rename", async () => {
+ await expect(checkOracleForeignKeyData(target, { original: null, target: original }, false)).resolves.toEqual({ checked: false });
+ await expect(checkOracleForeignKeyData(target, { original: validated, target: { ...validated, name: "FK_NEW" } }, false)).resolves.toEqual({ checked: false });
+ expect(api.executeQuery).not.toHaveBeenCalled();
+ });
+
+ it("allows database validation of atomic ADD without SELECT but refuses deletion first", async () => {
+ vi.mocked(api.executeQuery).mockRejectedValue(new Error("SELECT access denied"));
+ await expect(checkOracleForeignKeyData(target, { original: null, target: validated }, false)).resolves.toEqual({ checked: false });
+ await expect(checkOracleForeignKeyData(target, { original, target: validated }, true)).rejects.toMatchObject({ reason: "referenceDataUnreadable" });
+ });
+
+ it("rejects confirmed orphan data before any DDL", async () => {
+ vi.mocked(api.executeQuery).mockResolvedValue(result([[1]]) as never);
+ await expect(checkOracleForeignKeyData(target, { original: null, target: validated }, false)).rejects.toMatchObject({ reason: "referenceDataInvalid" });
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);
+ });
+
+ it("checks existing data when enabling a previously disabled validated key", async () => {
+ vi.mocked(api.executeQuery).mockResolvedValue(result([[1]]) as never);
+ await expect(checkOracleForeignKeyData(target, { original: validated, target: { ...validated, state: { ...validated.state, enabled: true } } }, false)).rejects.toMatchObject({ reason: "referenceDataInvalid" });
+ });
+});
+
+describe("Oracle foreign key plan", () => {
+ it("builds a complete static plan only after source, parent, permission and data checks", async () => {
+ const created = { name: "FK_NEW", columns: ["B"], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ['ID"quoted'], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const change = { original: null, target: created };
+ const statement = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("ID""quoted") ENABLE VALIDATE;';
+ const statements = [statement, 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_SECOND" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("ID""quoted") ENABLE VALIDATE;'];
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async () => ({ statements, warnings: [] }) as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER,")) return result([["READER", target.schema]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OWNER = 'App Owner'") ? [[target.schema, target.tableName, 516042]] : [["Parent Owner", "Parent,Table", 24]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[target.schema, target.tableName]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", 'ID"quoted', 1]]) as never;
+ if (sql.includes("SESSION_PRIVS")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result(sql.includes("OWNER = 'App Owner'") ? [["B", "NUMBER", 22, null, null, "Y"]] : [['ID"quoted', "NUMBER"]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS")) return result([]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oracle" as const, schema: target.schema, tableName: target.tableName, columns: [], indexes: [], foreignKeys: [] };
+ const plan = await prepareOracleForeignKeyPlan(target, options, [change]);
+ expect(plan.statements).toEqual(statements);
+ expect(plan.groups).toEqual([{ change, statements, replacement: false }]);
+ expect(plan.unverified).toEqual([]);
+ expect(JSON.parse(plan.snapshot).source.objectId).toBe("516042");
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => !call[2].startsWith("SELECT "))).toBe(false);
+
+ const readQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation(async (...args) => {
+ if (String(args[2]).startsWith("ALTER TABLE")) throw new Error("Response lost");
+ return readQuery(...args) as never;
+ });
+ const execution = await executeOracleForeignKeyPlan(plan, 30, () => true);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["unknown", "notExecuted"]);
+ expect(execution?.readbackError).toBeTruthy();
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(1);
+ });
+
+ it("reports an in-flight DDL outcome as unknown after the generation changes", async () => {
+ const created = { name: "FK_NEW", columns: ["B"], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ['ID"quoted'], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const change = { original: null, target: created };
+ const statement = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("ID""quoted") ENABLE VALIDATE;';
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: [statement], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER,")) return result([["READER", target.schema]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OWNER = 'App Owner'") ? [[target.schema, target.tableName, 516042]] : [["Parent Owner", "Parent,Table", 24]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[target.schema, target.tableName]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", 'ID"quoted', 1]]) as never;
+ if (sql.includes("SESSION_PRIVS")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result(sql.includes("OWNER = 'App Owner'") ? [["B", "NUMBER", 22, null, null, "Y"]] : [['ID"quoted', "NUMBER"]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS")) return result([]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oracle" as const, schema: target.schema, tableName: target.tableName, columns: [], indexes: [], foreignKeys: [] };
+ const plan = await prepareOracleForeignKeyPlan(target, options, [change]);
+ const base = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let finish!: (value: ReturnType<typeof result>) => void;
+ let current = true;
+ vi.mocked(api.executeQuery).mockImplementation((...args) =>
+ String(args[2]).startsWith("ALTER TABLE")
+ ? (new Promise((resolve) => {
+ finish = resolve as typeof finish;
+ }) as never)
+ : base(...args),
+ );
+ const pending = executeOracleForeignKeyPlan(plan, 30, () => current);
+ while (!finish) await new Promise((resolve) => setTimeout(resolve, 0));
+ current = false;
+ finish(result([]));
+
+ const outcome = await pending;
+
+ expect(outcome?.steps[0]?.state).toBe("unknown");
+ expect(outcome?.readbackError).toContain("readback is unknown");
+ });
+
+ it("keeps a resolved DDL committed when only the UI target changes in flight", async () => {
+ const created = { name: "FK_NEW", columns: ["B"], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ['ID"quoted'], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const statement = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("ID""quoted") ENABLE VALIDATE;';
+ vi.mocked(api.buildTableStructureChangeSql).mockResolvedValue({ statements: [statement], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER,")) return result([["READER", target.schema]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OWNER = 'App Owner'") ? [[target.schema, target.tableName, 516042]] : [["Parent Owner", "Parent,Table", 24]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[target.schema, target.tableName]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", 'ID"quoted', 1]]) as never;
+ if (sql.includes("SESSION_PRIVS")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result(sql.includes("OWNER = 'App Owner'") ? [["B", "NUMBER", 22, null, null, "Y"]] : [['ID"quoted', "NUMBER"]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS")) return result([]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oracle" as const, schema: target.schema, tableName: target.tableName, columns: [], indexes: [], foreignKeys: [] };
+ const plan = await prepareOracleForeignKeyPlan(target, options, [{ original: null, target: created }]);
+ const base = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let finish!: (value: ReturnType<typeof result>) => void;
+ let canStart = true;
+ vi.mocked(api.executeQuery).mockImplementation((...args) =>
+ String(args[2]).startsWith("ALTER TABLE")
+ ? (new Promise((resolve) => {
+ finish = resolve as typeof finish;
+ }) as never)
+ : base(...args),
+ );
+ const pending = executeOracleForeignKeyPlan(plan, 30, { canStart: () => canStart, connectionCurrent: () => true });
+ while (!finish) await new Promise((resolve) => setTimeout(resolve, 0));
+ canStart = false;
+ finish(result([]));
+
+ const outcome = await pending;
+
+ expect(outcome?.steps[0]?.state).toBe("committed");
+ expect(outcome?.steps[0]?.error).toBeUndefined();
+ });
+
+ it("offers only an unoccupied original ADD after a confirmed replacement DROP and rejected ADD", async () => {
+ const obTarget: OracleForeignKeyTarget = { ...target, databaseType: "oceanbase-oracle" };
+ const original = { name: "FK_OLD", columns: ["B"], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ["V"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const changed = { ...original, name: "FK_NEW" };
+ const drop = 'ALTER TABLE "App Owner"."Child,Table" DROP CONSTRAINT "FK_OLD";';
+ const add = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ const restore = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_OLD" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ const originalDdl = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_OLD" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ let exists = true;
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (options) => {
+ const change = options.oracleForeignKeyChanges?.[0];
+ return { statements: !change ? [drop, add] : change.original && change.target ? [drop, add] : [restore], warnings: [] } as never;
+ });
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.startsWith("ALTER TABLE") && sql.includes("DROP CONSTRAINT")) {
+ exists = false;
+ return result([]) as never;
+ }
+ if (sql.startsWith("ALTER TABLE") && sql.includes('"FK_NEW"')) return { ...result([]), execution_error: true, error: { detail: "Unique key already exists" } } as never;
+ if (sql === "SELECT USER FROM DUAL") return result([[obTarget.schema]]) as never;
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([[obTarget.schema, obTarget.schema]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[obTarget.schema, obTarget.tableName]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OWNER = 'App Owner'") ? (exists ? [[obTarget.schema, obTarget.tableName, 7]] : [[obTarget.schema, obTarget.tableName, 7]]) : [["Parent Owner", "Parent,Table", 24]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result(sql.includes("OWNER = 'App Owner'") ? [["B", "NUMBER", 22, null, null, "Y"]] : [["V", "NUMBER"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result(exists ? [["FK_OLD", obTarget.tableName]] : []) as never;
+ if (sql.includes("JOIN SYS.ALL_CONS_COLUMNS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "V", 1]]) as never;
+ if (sql.includes("SYS.USER_CONSTRAINTS")) return result(exists ? [["FK_OLD", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "Parent Owner", "PK_PARENT", "NO ACTION"]] : []) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[originalDdl]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS") || sql.includes("SESSION_PRIVS")) return result([]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oceanbase-oracle" as const, schema: obTarget.schema, tableName: obTarget.tableName, columns: [], indexes: [], foreignKeys: [] };
+ const plan = await prepareOracleForeignKeyPlan(obTarget, options, [{ original, target: changed }]);
+ const execution = await executeOracleForeignKeyPlan(plan, 30, () => true);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["committed", "rejected"]);
+ expect(execution?.recoverySql).toEqual([restore]);
+ });
+
+ it("generates manual recovery candidate after unconfirmed DROP when authoritative readback confirms missing", async () => {
+ const obTarget: OracleForeignKeyTarget = { ...target, databaseType: "oceanbase-oracle" };
+ const original = { name: "FK_OLD", columns: ["B"], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ["V"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const changed = { ...original, name: "FK_NEW" };
+ const drop = 'ALTER TABLE "App Owner"."Child,Table" DROP CONSTRAINT "FK_OLD";';
+ const add = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ const restore = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_OLD" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ const originalDdl = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_OLD" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ let exists = true;
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (options) => {
+ const change = options.oracleForeignKeyChanges?.[0];
+ return { statements: !change ? [drop, add] : change.original && change.target ? [drop, add] : [restore], warnings: [] } as never;
+ });
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.startsWith("ALTER TABLE") && sql.includes("DROP CONSTRAINT")) {
+ exists = false;
+ throw new Error("Connection reset by peer");
+ }
+ if (sql === "SELECT USER FROM DUAL") return result([[obTarget.schema]]) as never;
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([[obTarget.schema, obTarget.schema]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[obTarget.schema, obTarget.tableName]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OWNER = 'App Owner'") ? [[obTarget.schema, obTarget.tableName, 7]] : [["Parent Owner", "Parent,Table", 24]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result(sql.includes("OWNER = 'App Owner'") ? [["B", "NUMBER", 22, null, null, "Y"]] : [["V", "NUMBER"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result(exists ? [["FK_OLD", obTarget.tableName]] : []) as never;
+ if (sql.includes("JOIN SYS.ALL_CONS_COLUMNS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "V", 1]]) as never;
+ if (sql.includes("SYS.USER_CONSTRAINTS")) return result(exists ? [["FK_OLD", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "Parent Owner", "PK_PARENT", "NO ACTION"]] : []) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[originalDdl]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS") || sql.includes("SESSION_PRIVS")) return result([]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oceanbase-oracle" as const, schema: obTarget.schema, tableName: obTarget.tableName, columns: [], indexes: [], foreignKeys: [] };
+ const plan = await prepareOracleForeignKeyPlan(obTarget, options, [{ original, target: changed }]);
+ const execution = await executeOracleForeignKeyPlan(plan, 30, () => true);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["unknown", "notExecuted"]);
+ expect(execution?.recoverySql).toEqual([restore]);
+ });
+
+ it.each([
+ ["original still exists", { exists: true, objectId: 7, nameOccupied: false, colType: "NUMBER", stillCurrent: true }],
+ ["objectId changed", { exists: false, objectId: 999, nameOccupied: false, colType: "NUMBER", stillCurrent: true }],
+ ["name occupied", { exists: false, objectId: 7, nameOccupied: true, colType: "NUMBER", stillCurrent: true }],
+ ["column drifted", { exists: false, objectId: 7, nameOccupied: false, colType: "VARCHAR2", stillCurrent: true }],
+ ["stillCurrent false", { exists: false, objectId: 7, nameOccupied: false, colType: "NUMBER", stillCurrent: false }],
+ ])("withholds manual recovery when %s", async (_label, config) => {
+ const obTarget: OracleForeignKeyTarget = { ...target, databaseType: "oceanbase-oracle" };
+ const original = { name: "FK_OLD", columns: ["B"], refSchema: "Parent Owner", refTable: "Parent,Table", refColumns: ["V"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const changed = { ...original, name: "FK_NEW" };
+ const drop = 'ALTER TABLE "App Owner"."Child,Table" DROP CONSTRAINT "FK_OLD";';
+ const add = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ const restore = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_OLD" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ const originalDdl = 'ALTER TABLE "App Owner"."Child,Table" ADD CONSTRAINT "FK_OLD" FOREIGN KEY ("B") REFERENCES "Parent Owner"."Parent,Table" ("V") ENABLE VALIDATE;';
+ let dropAttempted = false;
+ vi.mocked(api.buildTableStructureChangeSql).mockImplementation(async (options) => {
+ const change = options.oracleForeignKeyChanges?.[0];
+ return { statements: !change ? [drop, add] : change.original && change.target ? [drop, add] : [restore], warnings: [] } as never;
+ });
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.startsWith("ALTER TABLE") && sql.includes("DROP CONSTRAINT")) {
+ dropAttempted = true;
+ throw new Error("Connection reset by peer");
+ }
+ if (sql === "SELECT USER FROM DUAL") return result([[obTarget.schema]]) as never;
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([[obTarget.schema, obTarget.schema]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[obTarget.schema, obTarget.tableName]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OWNER = 'App Owner'") ? [[obTarget.schema, obTarget.tableName, dropAttempted ? config.objectId : 7]] : [["Parent Owner", "Parent,Table", 24]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result(sql.includes("OWNER = 'App Owner'") ? [["B", dropAttempted ? config.colType : "NUMBER", 22, null, null, "Y"]] : [["V", "NUMBER"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) {
+ if (!dropAttempted) return result([["FK_OLD", obTarget.tableName]]) as never;
+ if (config.nameOccupied) return result([["FK_OLD", obTarget.tableName]]) as never;
+ return result(config.exists ? [["FK_OLD", obTarget.tableName]] : []) as never;
+ }
+ if (sql.includes("JOIN SYS.ALL_CONS_COLUMNS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "V", 1]]) as never;
+ if (sql.includes("SYS.USER_CONSTRAINTS")) return result(!dropAttempted || config.exists ? [["FK_OLD", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "Parent Owner", "PK_PARENT", "NO ACTION"]] : []) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[originalDdl]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.includes("SYS.ALL_COL_PRIVS") || sql.includes("SESSION_PRIVS")) return result([]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oceanbase-oracle" as const, schema: obTarget.schema, tableName: obTarget.tableName, columns: [], indexes: [], foreignKeys: [] };
+ const plan = await prepareOracleForeignKeyPlan(obTarget, options, [{ original, target: changed }]);
+ let stale = false;
+ const readQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ if (config.stillCurrent === false && dropAttempted && String(args[2]).includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) {
+ stale = true;
+ return Promise.resolve(result([])) as never;
+ }
+ return readQuery(...args);
+ });
+ const execution = await executeOracleForeignKeyPlan(plan, 30, () => !stale);
+ expect(execution?.recoverySql).toBeUndefined();
+ });
+});
+
+describe("Oracle foreign keys in new table plans", () => {
+ it("rejects a self-reference to a non-key column before returning CREATE SQL", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "NewTable" };
+ const invalidDefinition = { name: "FK_BAD", columns: ["ID"], refSchema: "APP", refTable: "NewTable", refColumns: ["PARENT_ID"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements: ["CREATE TABLE APP.NEWTABLE (ID NUMBER)", "ALTER TABLE APP.NEWTABLE ADD CONSTRAINT FK_BAD FOREIGN KEY (ID) REFERENCES APP.NEWTABLE (PARENT_ID)"], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockResolvedValue(result([["APP", "APP"]]) as never);
+ await expect(
+ prepareOracleForeignKeyCreatePlan(
+ createTarget,
+ {
+ databaseType: "oracle",
+ schema: "APP",
+ tableName: "NewTable",
+ columns: [
+ { id: "id", name: "ID", dataType: "NUMBER", isNullable: false, isPrimaryKey: true },
+ { id: "pid", name: "PARENT_ID", dataType: "NUMBER", isNullable: true, isPrimaryKey: false },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ },
+ [{ original: null, target: invalidDefinition }],
+ ),
+ ).rejects.toThrow();
+ expect(vi.mocked(api.executeQuery).mock.calls.every((call) => String(call[2]).startsWith("SELECT "))).toBe(true);
+ });
+
+ it("preflights self-reference before CREATE and executes each statement once", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "NewTable" };
+ const definition = { name: "FK_NEW", columns: ["PARENT_ID"], refSchema: "APP", refTable: "NewTable", refColumns: ["ID"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const statements = ['CREATE TABLE "APP".NewTable (ID NUMBER NOT NULL, PARENT_ID NUMBER, CONSTRAINT PK_NEW PRIMARY KEY (ID));', 'ALTER TABLE "APP".NewTable ADD CONSTRAINT fk_new FOREIGN KEY (PARENT_ID) REFERENCES "APP".NewTable (ID) NORELY ENABLE VALIDATE;'];
+ const ddl = 'ALTER TABLE "APP"."NEWTABLE" ADD CONSTRAINT "FK_NEW" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."NEWTABLE" ("ID") ENABLE VALIDATE;';
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements, warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql.startsWith("CREATE TABLE") || sql.startsWith("ALTER TABLE")) return result([]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "NEWTABLE", 802]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([["APP", "NEWTABLE"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([["FK_NEW", "NEWTABLE"]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["FK_NEW", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"]]) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[ddl]]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = {
+ databaseType: "oracle" as const,
+ schema: createTarget.schema,
+ tableName: createTarget.tableName,
+ columns: [
+ { id: "id", name: "ID", dataType: "NUMBER", isNullable: false, isPrimaryKey: true },
+ { id: "pid", name: "PARENT_ID", dataType: "NUMBER", isNullable: true, isPrimaryKey: false },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ primaryKeyName: "PK_NEW",
+ };
+ const changes = [{ original: null, target: definition }];
+ const plan = await prepareOracleForeignKeyCreatePlan(createTarget, options, changes);
+ expect(plan.statements).toEqual(statements);
+ expect(vi.mocked(api.executeQuery).mock.calls.some((call) => String(call[2]).startsWith("CREATE TABLE"))).toBe(false);
+ const execution = await executeOracleForeignKeyCreatePlan(plan, 30, () => true);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["committed", "committed"]);
+ expect(execution?.readbackError).toBeUndefined();
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("ALTER TABLE"))).toHaveLength(1);
+
+ vi.mocked(api.executeQuery).mockClear();
+ await expect(executeOracleForeignKeyCreatePlan(plan, 30, () => false)).resolves.toBeUndefined();
+ expect(api.executeQuery).not.toHaveBeenCalled();
+ vi.mocked(api.executeQuery).mockClear();
+ const readQuery = vi.mocked(api.executeQuery).getMockImplementation()!;
+ let current = true;
+ let finish!: (value: ReturnType<typeof result>) => void;
+ let readAfterStale = false;
+ vi.mocked(api.executeQuery).mockImplementation((...args) => {
+ const sql = String(args[2]);
+ if (sql.startsWith("CREATE TABLE"))
+ return new Promise((resolve) => {
+ finish = resolve as typeof finish;
+ }) as never;
+ if (!current) readAfterStale = true;
+ return readQuery(...args) as never;
+ });
+ const pendingLateCreate = executeOracleForeignKeyCreatePlan(plan, 30, () => current);
+ while (!finish) await new Promise((resolve) => setTimeout(resolve, 0));
+ current = false;
+ finish(result([]));
+ const lateCreate = await pendingLateCreate;
+ expect(lateCreate?.steps.map((step) => step.state)).toEqual(["unknown", "notExecuted"]);
+ expect(lateCreate?.tableExists).toBeUndefined();
+ expect(readAfterStale).toBe(false);
+ expect(api.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ });
+
+ it("matches Oracle self-reference readback after identifier folding", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "child" };
+ const definition = { name: "fk_self", columns: ["parent_id"], refSchema: "app", refTable: "CHILD", refColumns: ["id"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const statements = ['CREATE TABLE "APP".child (id NUMBER PRIMARY KEY, parent_id NUMBER)', 'ALTER TABLE "APP".child ADD CONSTRAINT fk_self FOREIGN KEY (parent_id) REFERENCES "app".CHILD (id)'];
+ const ddl = 'ALTER TABLE "APP"."CHILD" ADD CONSTRAINT "FK_SELF" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."CHILD" ("ID") ENABLE VALIDATE;';
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements, warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql.startsWith("CREATE TABLE") || sql.startsWith("ALTER TABLE")) return result([]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CHILD", 802]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([["APP", "CHILD"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([["FK_SELF", "CHILD"]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["FK_SELF", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"]]) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[ddl]]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = {
+ databaseType: "oracle" as const,
+ schema: "APP",
+ tableName: "child",
+ columns: [
+ { id: "id", name: "id", dataType: "NUMBER", isNullable: false, isPrimaryKey: true },
+ { id: "pid", name: "parent_id", dataType: "NUMBER", isNullable: true, isPrimaryKey: false },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ primaryKeyName: "PK_NEW",
+ };
+ const plan = await prepareOracleForeignKeyCreatePlan(createTarget, options, [{ original: null, target: definition }]);
+ const executed = await executeOracleForeignKeyCreatePlan(plan, 30, () => true);
+ expect(executed?.steps.map((step) => step.state)).toEqual(["committed", "committed"]);
+ expect(executed?.readbackError).toBeUndefined();
+ });
+
+ it("accepts a reverse-ordered self reference to the new composite primary key", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "NewTable" };
+ const definition = { name: "FK_SELF", columns: ["X", "Y"], refSchema: "APP", refTable: "NewTable", refColumns: ["B", "A"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements: ['CREATE TABLE "APP".NewTable (A NUMBER, B NUMBER, X NUMBER, Y NUMBER, PRIMARY KEY (A, B))', 'ALTER TABLE "APP".NewTable ADD CONSTRAINT FK_SELF FOREIGN KEY (X, Y) REFERENCES "APP".NewTable (B, A)'], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockResolvedValue(result([["APP", "APP"]]) as never);
+ const options = {
+ databaseType: "oracle" as const,
+ schema: "APP",
+ tableName: "NewTable",
+ columns: [
+ { id: "a", name: "A", dataType: "NUMBER", isNullable: false, isPrimaryKey: true },
+ { id: "b", name: "B", dataType: "NUMBER", isNullable: false, isPrimaryKey: true },
+ { id: "x", name: "X", dataType: "NUMBER", isNullable: true, isPrimaryKey: false },
+ { id: "y", name: "Y", dataType: "NUMBER", isNullable: true, isPrimaryKey: false },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ primaryKeyName: "PK_NEW",
+ };
+ await expect(prepareOracleForeignKeyCreatePlan(createTarget, options, [{ original: null, target: definition }])).resolves.toMatchObject({ references: [{ objectId: "new-table" }] });
+ });
+
+ it("does not fold a mixed-case external parent during new-table readback", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "NewTable" };
+ const external = { name: "FK_PARENT", columns: ["ID"], refSchema: "APP", refTable: "Parent", refColumns: ["ID"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const statements = ['CREATE TABLE "APP".NewTable (ID NUMBER PRIMARY KEY)', 'ALTER TABLE "APP".NewTable ADD CONSTRAINT FK_PARENT FOREIGN KEY (ID) REFERENCES "App"."Parent" ("id")'];
+ const ddl = 'ALTER TABLE "APP"."NEWTABLE" ADD CONSTRAINT "FK_PARENT" FOREIGN KEY ("ID") REFERENCES "App"."PARENT" ("id") ENABLE VALIDATE;';
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements, warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql.startsWith("CREATE TABLE") || sql.startsWith("ALTER TABLE")) return result([]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result(sql.includes("OBJECT_NAME = 'NEWTABLE'") ? [["APP", "NEWTABLE", 802]] : [["APP", "Parent", 903]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) return result([["ID", "NUMBER", 22, null, null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([["APP", "NEWTABLE"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([["FK_PARENT", "NEWTABLE"]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS") && sql.includes("CONSTRAINT_TYPE = 'R'")) return result([["FK_PARENT", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "App", "PK_PARENT", "NO ACTION"]]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["PK_PARENT", "P", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "ID", 1]]) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[ddl]]) as never;
+ if (sql.includes("SYS.ALL_TAB_PRIVS") || sql.includes("SYS.ALL_COL_PRIVS") || sql.includes("SESSION_PRIVS")) return result([["REFERENCES"]]) as never;
+ if (sql.startsWith("SELECT 1 FROM")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oracle" as const, schema: "APP", tableName: "NewTable", columns: [{ id: "id", name: "ID", dataType: "NUMBER", isNullable: false, isPrimaryKey: true }], indexes: [], foreignKeys: [], primaryKeyName: "PK_NEW" };
+ const plan = await prepareOracleForeignKeyCreatePlan(createTarget, options, [{ original: null, target: external }]);
+ const executed = await executeOracleForeignKeyCreatePlan(plan, 30, () => true);
+ expect(executed?.readbackError).toContain("differs from the submitted plan");
+ expect(executed?.steps.map((step) => step.state)).toEqual(["committed", "committed"]);
+ });
+
+ it("reads back the target after an unknown CREATE response without retrying it", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "NewTable" };
+ const definition = { name: "FK_SELF", columns: ["ID"], refSchema: "APP", refTable: "NewTable", refColumns: ["ID"], onDelete: "NO ACTION" as const, state: { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false } };
+ const create = 'CREATE TABLE "APP".NewTable (ID NUMBER PRIMARY KEY)';
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements: [create, 'ALTER TABLE "APP".NewTable ADD CONSTRAINT FK_SELF FOREIGN KEY (ID) REFERENCES "APP".NewTable (ID)'], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql === create) throw new Error("Connection lost after request");
+ if (sql.includes("SYS.ALL_TABLES")) return result([["APP", "NEWTABLE"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME")) return result([]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = { databaseType: "oracle" as const, schema: "APP", tableName: "NewTable", columns: [{ id: "id", name: "ID", dataType: "NUMBER", isNullable: false, isPrimaryKey: true }], indexes: [], foreignKeys: [], primaryKeyName: "PK_NEW" };
+ const plan = await prepareOracleForeignKeyCreatePlan(createTarget, options, [{ original: null, target: definition }]);
+ const execution = await executeOracleForeignKeyCreatePlan(plan, 30, () => true);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["unknown", "notExecuted"]);
+ expect(execution?.readbackError).toBeUndefined();
+ expect(execution?.tableExists).toBe(true);
+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);
+ });
+
+ it("stops after a later FK fails and reports the committed partial create", async () => {
+ const createTarget = { ...target, schema: "APP", tableName: "NewTable" };
+ const state = { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false };
+ const first = { name: "FK_FIRST", columns: ["PARENT_ID"], refSchema: "APP", refTable: "NewTable", refColumns: ["ID"], onDelete: "NO ACTION" as const, state };
+ const second = { ...first, name: "FK_SECOND" };
+ const create = 'CREATE TABLE "APP".NewTable (ID NUMBER NOT NULL, PARENT_ID NUMBER, CONSTRAINT PK_NEW PRIMARY KEY (ID));';
+ const addFirst = 'ALTER TABLE "APP".NewTable ADD CONSTRAINT fk_first FOREIGN KEY (PARENT_ID) REFERENCES "APP".NewTable (ID) NORELY ENABLE VALIDATE;';
+ const addSecond = 'ALTER TABLE "APP".NewTable ADD CONSTRAINT fk_second FOREIGN KEY (PARENT_ID) REFERENCES "APP".NewTable (ID) NORELY ENABLE VALIDATE;';
+ const ddl = 'ALTER TABLE "APP"."NEWTABLE" ADD CONSTRAINT "FK_FIRST" FOREIGN KEY ("PARENT_ID") REFERENCES "APP"."NEWTABLE" ("ID") ENABLE VALIDATE;';
+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements: [create, addFirst, addSecond], warnings: [] } as never);
+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {
+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;
+ if (sql === addSecond.replace(/;$/, "")) return { ...result([]), execution_error: true, error: { detail: "Second foreign key rejected" } } as never;
+ if (sql.startsWith("CREATE TABLE") || sql === addFirst.replace(/;$/, "")) return result([]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "NEWTABLE", 802]]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS"))
+ return result([
+ ["ID", "NUMBER", 22, null, null, "N"],
+ ["PARENT_ID", "NUMBER", 22, null, null, "Y"],
+ ]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([["APP", "NEWTABLE"]]) as never;
+ if (sql.includes("SELECT CONSTRAINT_NAME, TABLE_NAME"))
+ return result([
+ ["FK_FIRST", "NEWTABLE"],
+ ["FK_SECOND", "NEWTABLE"],
+ ]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["FK_FIRST", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_NEW", "NO ACTION"]]) as never;
+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[ddl]]) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ const options = {
+ databaseType: "oracle" as const,
+ schema: createTarget.schema,
+ tableName: createTarget.tableName,
+ columns: [
+ { id: "id", name: "ID", dataType: "NUMBER", isNullable: false, isPrimaryKey: true },
+ { id: "pid", name: "PARENT_ID", dataType: "NUMBER", isNullable: true, isPrimaryKey: false },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ primaryKeyName: "PK_NEW",
+ };
+ const changes = [
+ { original: null, target: first },
+ { original: null, target: second },
+ ];
+ const plan = await prepareOracleForeignKeyCreatePlan(createTarget, options, changes);
+ const execution = await executeOracleForeignKeyCreatePlan(plan, 30, () => true);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["committed", "committed", "rejected"]);
+ expect(execution?.readbackError).toBeUndefined();
+ const writes = vi
+ .mocked(api.executeQuery)
+ .mock.calls.map((call) => String(call[2]))
+ .filter((sql) => sql.startsWith("CREATE TABLE") || sql.startsWith("ALTER TABLE"));
+ expect(writes).toEqual([create.replace(/;$/, ""), addFirst.replace(/;$/, ""), addSecond.replace(/;$/, "")]);
+ });
+});
diff --git a/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.ts
new file mode 100644
index 0000000000..f57c42a3d5
--- /dev/null
+++ b/apps/desktop/src/lib/database/__tests__/oracleIndexes.spec.ts
@@ -0,0 +1,551 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import * as api from "@/lib/backend/api";
+import { executeOracleIndexPlan, mergeOracleIndexDraftsAfterRefresh, oracleIndexSnapshotMatchesLoadedColumns, prepareOracleIndexPlan } from "../oracleIndexes";
+import { readOracleConstraintSnapshot, readOracleIndexSnapshot } from "../oracleConstraints";
+
+vi.mock("@/lib/backend/api", () => ({ executeQuery: vi.fn(), listConstraints: vi.fn() }));
+
+const target = { connectionId: "fixture", database: "APP", schema: "APP", tableName: "CONTACTS", databaseType: "oracle" as const };
+const result = (rows: unknown[][], execution_error = false) => ({ execution_error, truncated: false, has_more: false, rows, error: execution_error ? { detail: "rejected" } : undefined });
+const drafts = [
+ {
+ id: "old",
+ name: "IX_OLD",
+ columns: ["EMAIL"],
+ isUnique: false,
+ isPrimary: false,
+ filter: "",
+ indexType: "NORMAL",
+ includedColumns: [],
+ comment: "",
+ original: { name: "IX_OLD", columns: ["EMAIL"], is_unique: false, is_primary: false, index_type: "NORMAL", key_metadata_complete: true, key_is_expression: [false], key_directions: ["ASC"], visibility: "VISIBLE", constraint_backed: false },
+ markedForDrop: true,
+ },
+ { id: "new", name: "IX_NEW", columns: ["EMAIL"], isUnique: false, isPrimary: false, filter: "", indexType: "NORMAL", includedColumns: [], comment: "", markedForDrop: false },
+];
+
+describe("Oracle index plans", () => {
+ let indexNames: string[];
+ let supportedIndexes: Set<string>;
+ let otherOwnerIndexNames: string[];
+ let indexNamesReads: number;
+ let ddl: string[];
+ let rejectCreate: boolean;
+ let indexColumns: unknown[][];
+ let unrelatedOwnerIndexRows: unknown[][];
+ let sharedIndexUsers: unknown[][];
+ let functionIndexName: string | undefined;
+ let failEnhancedColumns: boolean;
+ let enhancedFailureRows: unknown[][] = [];
+ let columnFlags = new Map<string, [string | null, string | null, string | null, string | null]>();
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ indexNames = ["IX_OLD"];
+ supportedIndexes = new Set();
+ otherOwnerIndexNames = [];
+ indexNamesReads = 0;
+ ddl = [];
+ rejectCreate = true;
+ indexColumns = [["EMAIL", "VARCHAR2", 100, null, null, "Y"]];
+ unrelatedOwnerIndexRows = [];
+ sharedIndexUsers = [];
+ functionIndexName = undefined;
+ failEnhancedColumns = false;
+ enhancedFailureRows = [];
+ columnFlags = new Map();
+ vi.mocked(api.executeQuery).mockImplementation(async (_connection, _database, sql) => {
+ if (/^\s*(?:DROP|CREATE)\s+INDEX/i.test(sql)) {
+ ddl.push(sql);
+ if (/^\s*DROP/i.test(sql)) {
+ const dropped = /DROP\s+INDEX\s+(?:"[^"]+"\.)?"?([^"\s;]+)"?/i.exec(sql)?.[1];
+ indexNames = indexNames.filter((name) => name !== dropped);
+ if (dropped === functionIndexName) {
+ indexColumns = indexColumns.filter((row) => row[0] !== "SYS_NC00001$");
+ functionIndexName = undefined;
+ }
+ }
+ const rejected = /^\s*CREATE/i.test(sql) && rejectCreate;
+ if (!rejected && /^\s*CREATE/i.test(sql)) {
+ const name = /CREATE\s+(?:UNIQUE\s+)?INDEX\s+"([^"]+)"/i.exec(sql)?.[1];
+ if (name) indexNames.push(name);
+ if (sql.includes("LOWER(EMAIL)")) {
+ functionIndexName = name;
+ indexColumns = [...indexColumns, ["SYS_NC00001$", "VARCHAR2", 100, null, null, "Y"]];
+ }
+ }
+ return result([], rejected) as never;
+ }
+ if (sql.includes("SYS_CONTEXT")) return result([["APP", "APP", "ORCL"]]) as never;
+ if (sql.includes("SYS.ALL_OBJECTS")) return result([["APP", "CONTACTS", 77]]) as never;
+ if (sql.includes("SYS.ALL_TABLES")) return result([[null, "N"]]) as never;
+ if (sql.includes("SYS.ALL_EXTERNAL_TABLES")) return result([]) as never;
+ if (sql.includes("SYS.ALL_TAB_COLS")) {
+ if (sql.includes("USER_GENERATED") && failEnhancedColumns) return result(enhancedFailureRows, true) as never;
+ const rows = sql.includes("USER_GENERATED")
+ ? indexColumns.map((row) => [...row, ...(columnFlags.get(String(row[0])) ?? ["B", ["VARCHAR2", "CHAR", "NVARCHAR2", "NCHAR"].includes(String(row[1])) ? String(row[2]) : null, row[0] === "SYS_NC00001$" ? "NO" : "YES", row[0] === "SYS_NC00001$" ? "YES" : "NO"])])
+ : indexColumns;
+ return result(rows) as never;
+ }
+ if (sql.includes("SELECT INDEX_NAME FROM SYS.ALL_INDEXES")) {
+ indexNamesReads += 1;
+ if (indexNamesReads === 5) supportedIndexes.add("IX_SECOND");
+ const requested = [...sql.matchAll(/'([^']+)'/g)].map((match) => match[1]!);
+ const names = sql.includes("AND 1 = 0") ? [] : [...indexNames, ...otherOwnerIndexNames].filter((name) => requested.includes(name));
+ return result(names.sort().map((name) => [name])) as never;
+ }
+ if (sql.includes("SYS.ALL_IND_COLUMNS"))
+ return result([
+ ...indexNames.map((name) => ["APP", name, "APP", "CONTACTS", name === functionIndexName ? "FUNCTION-BASED NORMAL" : "NORMAL", "NONUNIQUE", "VALID", "NO", "VISIBLE", "N", name === functionIndexName ? "SYS_NC00001$" : "EMAIL", "ASC", name === functionIndexName ? "LOWER(EMAIL)" : null]),
+ ...unrelatedOwnerIndexRows.filter((row) => row[3] === "CONTACTS"),
+ ]) as never;
+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([...supportedIndexes].map((name) => ["APP", name, "APP", "CONTACTS", `UQ_${name}`]).concat(sharedIndexUsers)) as never;
+ throw new Error(`Unexpected SQL: ${sql}`);
+ });
+ });
+
+ it("reads target indexes when unrelated indexes exceed the owner-wide row limit", async () => {
+ unrelatedOwnerIndexRows = Array.from({ length: 10_000 }, (_, i) => ["APP", `IX_OTHER_${i}`, "APP", `TABLE_${i}`, "NORMAL", "NONUNIQUE", "VALID", "NO", "VISIBLE", "N", "EMAIL", "ASC", null]);
+
+ const snapshot = await readOracleIndexSnapshot(target);
+
+ expect(snapshot.indexes.map((index) => index.name)).toEqual(["IX_OLD"]);
+ });
+
+ it("reads a target snapshot when unrelated owner index names exceed the row limit", async () => {
+ otherOwnerIndexNames = Array.from({ length: 10_000 }, (_, i) => `IX_OTHER_${i}`);
+
+ const snapshot = await readOracleIndexSnapshot(target);
+
+ expect(snapshot.indexes.map((index) => index.name)).toEqual(["IX_OLD"]);
+ });
+
+ it("preserves same-named indexes from different owners and rejects ambiguous drafts", async () => {
+ unrelatedOwnerIndexRows = [["OTHER", "IX_OLD", "APP", "CONTACTS", "NORMAL", "NONUNIQUE", "VALID", "NO", "VISIBLE", "N", "PHONE", "DESC", null]];
+ sharedIndexUsers = [["OTHER", "IX_OLD", "OTHER", "OTHER_TABLE", "PK_OTHER"]];
+
+ const fullSnapshot = await readOracleConstraintSnapshot(target, undefined, true);
+ const indexSnapshot = await readOracleIndexSnapshot(target);
+ await expect(prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" ("EMAIL");'], drafts as never)).rejects.toThrow("Index metadata changed");
+
+ expect(fullSnapshot.indexes.map(({ owner, name, columns, directions, constraints }) => ({ owner, name, columns, directions, constraints }))).toEqual([
+ { owner: "APP", name: "IX_OLD", columns: ["EMAIL"], directions: ["ASC"], constraints: [] },
+ { owner: "OTHER", name: "IX_OLD", columns: ["PHONE"], directions: ["DESC"], constraints: [{ owner: "OTHER", tableName: "OTHER_TABLE", name: "PK_OTHER" }] },
+ ]);
+ expect(indexSnapshot.indexes.map(({ owner, name, columns, directions }) => ({ owner, name, columns, directions }))).toEqual([
+ { owner: "APP", name: "IX_OLD", columns: ["EMAIL"], directions: ["ASC"] },
+ { owner: "OTHER", name: "IX_OLD", columns: ["PHONE"], directions: ["DESC"] },
+ ]);
+ expect(ddl).toEqual([]);
+ });
+
+ it("does not invalidate a target plan when an unrelated owner index name changes", async () => {
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" ("EMAIL");'], drafts as never);
+ otherOwnerIndexNames = ["IX_OTHER_ADDED_AFTER_PREVIEW"];
+
+ const outcome = await executeOracleIndexPlan(plan, 10, () => true);
+
+ expect(outcome?.steps[0]?.state).toBe("committed");
+ });
+
+ it("stops after a rejected CREATE and reads back the completed DROP", async () => {
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" ("EMAIL");'], drafts as never);
+
+ const result = await executeOracleIndexPlan(plan, 10, () => true);
+
+ expect(ddl).toHaveLength(2);
+ expect(result?.steps.map((step) => step.state)).toEqual(["committed", "rejected"]);
+ expect(result?.steps[1]?.error).toContain("Readback index names: none");
+ expect(result?.steps[2]).toBeUndefined();
+ });
+
+ it("refuses stale index metadata before executing DDL", async () => {
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" ("EMAIL");'], drafts as never);
+ indexNames = ["IX_CHANGED"];
+
+ await expect(executeOracleIndexPlan(plan, 10, () => true)).rejects.toThrow("Index metadata changed");
+
+ expect(ddl).toHaveLength(0);
+ });
+
+ it("requires generated SQL identity to match the structured draft target", async () => {
+ await expect(prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OTHER";'], drafts as never)).rejects.toThrow("Index metadata changed");
+
+ expect(ddl).toHaveLength(0);
+ });
+
+ it("rejects a target index name already used by another table in the owner", async () => {
+ otherOwnerIndexNames = ["IX_NEW"];
+
+ await expect(prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" ("EMAIL");'], drafts as never)).rejects.toThrow("Index metadata changed");
+
+ expect(ddl).toHaveLength(0);
+ });
+
+ it("preserves a shared index relation owned by a different table constraint", async () => {
+ sharedIndexUsers = [["APP", "IX_OLD", "OTHER", "OTHER_TABLE", "UQ_SHARED"]];
+
+ await expect(prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";'], [drafts[0]!] as never)).rejects.toThrow("Index metadata changed");
+
+ expect(api.executeQuery.mock.calls.some((call) => String(call[2]).includes("c.INDEX_OWNER, c.INDEX_NAME"))).toBe(true);
+ expect(api.executeQuery.mock.calls.some((call) => String(call[2]).includes("ORDER BY c.INDEX_OWNER, c.INDEX_NAME, c.OWNER, c.TABLE_NAME, c.CONSTRAINT_NAME"))).toBe(true);
+ });
+
+ it("plans a CREATE when a missing index draft is restored to its original definition", async () => {
+ indexNames = [];
+ const recoverableDraft = { ...drafts[0]!, name: "IX_OLD", oracleOriginalMissing: true, markedForDrop: false };
+
+ const plan = await prepareOracleIndexPlan(target, ['CREATE INDEX "IX_OLD" ON "APP"."CONTACTS" ("EMAIL");'], [recoverableDraft] as never);
+
+ expect(plan.mutations).toHaveLength(1);
+ expect(plan.mutations[0]?.operation).toBe("CREATE");
+ });
+
+ it("does not drop an index when its missing recovery draft is discarded", async () => {
+ indexNames = [];
+ const discardedDraft = { ...drafts[0]!, oracleOriginalMissing: true, markedForDrop: true };
+
+ const plan = await prepareOracleIndexPlan(target, [], [discardedDraft] as never);
+
+ expect(plan.statements).toEqual([]);
+ expect(plan.mutations).toEqual([]);
+ });
+
+ it("keeps only incomplete renames as missing drafts after a partial refresh", () => {
+ const originalA = { ...drafts[0]!.original, name: "IX_A", columns: ["EMAIL"] };
+ const originalB = { ...drafts[0]!.original, name: "IX_B", columns: ["AGE"] };
+ const draftA = { ...drafts[0]!, id: "a", name: "IX_A_NEW", original: originalA, markedForDrop: false };
+ const draftB = { ...drafts[0]!, id: "b", name: "IX_B_NEW", original: originalB, columns: ["AGE"], markedForDrop: false };
+ const actualA = { ...originalA, name: "IX_A_NEW", is_primary: false };
+ const completedA = {
+ owner: "APP",
+ name: "IX_A_NEW",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ indexType: "NORMAL",
+ uniqueness: "NONUNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: ["EMAIL"],
+ directions: ["ASC"],
+ keyIsExpression: [false],
+ includedColumns: [],
+ constraints: [],
+ };
+
+ const merged = mergeOracleIndexDraftsAfterRefresh([draftA, draftB] as never, [actualA] as never, [completedA]);
+
+ expect(merged).toHaveLength(2);
+ expect(merged[0]).toMatchObject({ name: "IX_A_NEW", original: { name: "IX_A_NEW" }, indexType: "NORMAL" });
+ expect(merged[0]?.oracleOriginalMissing).toBeUndefined();
+ expect(merged[1]).toMatchObject({ name: "IX_B_NEW", original: { name: "IX_B" }, oracleOriginalMissing: true });
+ });
+
+ it("preserves a delete mark added after a completed rename before refresh", () => {
+ const originalA = { ...drafts[0]!.original, name: "IX_A" };
+ const originalB = { ...drafts[0]!.original, name: "IX_B", columns: ["AGE"] };
+ const draftA = { ...drafts[0]!, id: "a", name: "IX_A_NEW", original: originalA, markedForDrop: true };
+ const draftB = { ...drafts[0]!, id: "b", name: "IX_B_NEW", original: originalB, columns: ["AGE"], markedForDrop: false };
+ const actualA = { ...originalA, name: "IX_A_NEW", is_primary: false };
+ const completedA = {
+ owner: "APP",
+ name: "IX_A_NEW",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ indexType: "NORMAL",
+ uniqueness: "NONUNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: ["EMAIL"],
+ directions: ["ASC"],
+ keyIsExpression: [false],
+ includedColumns: [],
+ constraints: [],
+ };
+
+ const merged = mergeOracleIndexDraftsAfterRefresh([draftA, draftB] as never, [actualA] as never, [completedA]);
+
+ expect(merged).toHaveLength(2);
+ expect(merged[0]).toMatchObject({ name: "IX_A_NEW", original: { name: "IX_A_NEW" }, markedForDrop: true });
+ expect(merged[1]).toMatchObject({ name: "IX_B_NEW", original: { name: "IX_B" }, oracleOriginalMissing: true });
+ });
+
+ it("preserves edits made after a completed rename before refresh", () => {
+ const originalA = { ...drafts[0]!.original, name: "IX_A" };
+ const originalB = { ...drafts[0]!.original, name: "IX_B", columns: ["AGE"] };
+ const draftA = { ...drafts[0]!, id: "a", name: "IX_A_NEW", original: originalA, columns: ["AGE"], markedForDrop: false };
+ const draftB = { ...drafts[0]!, id: "b", name: "IX_B_NEW", original: originalB, columns: ["AGE"], markedForDrop: false };
+ const actualA = { ...originalA, name: "IX_A_NEW", columns: ["EMAIL"], is_primary: false };
+ const completedA = {
+ owner: "APP",
+ name: "IX_A_NEW",
+ tableOwner: "APP",
+ tableName: "CONTACTS",
+ indexType: "NORMAL",
+ uniqueness: "NONUNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: ["EMAIL"],
+ directions: ["ASC"],
+ keyIsExpression: [false],
+ includedColumns: [],
+ constraints: [],
+ };
+
+ const merged = mergeOracleIndexDraftsAfterRefresh([draftA, draftB] as never, [actualA] as never, [completedA]);
+
+ expect(merged).toHaveLength(2);
+ expect(merged[0]).toMatchObject({ name: "IX_A_NEW", columns: ["AGE"], original: { name: "IX_A_NEW", columns: ["EMAIL"] }, indexType: "NORMAL" });
+ expect(merged[1]).toMatchObject({ name: "IX_B_NEW", original: { name: "IX_B" }, oracleOriginalMissing: true });
+ });
+
+ it("plans only the missing CREATE while retaining original function and visibility metadata", async () => {
+ indexNames = [];
+ const recoverableDraft = {
+ ...drafts[0]!,
+ name: "IX_NEW",
+ columns: ["LOWER(EMAIL)"],
+ indexType: "FUNCTION-BASED NORMAL",
+ original: {
+ ...drafts[0]!.original,
+ columns: ["LOWER(EMAIL)"],
+ key_is_expression: [true],
+ key_directions: ["ASC"],
+ index_type: "FUNCTION-BASED NORMAL",
+ visibility: "INVISIBLE",
+ },
+ oracleOriginalMissing: true,
+ markedForDrop: false,
+ };
+
+ const plan = await prepareOracleIndexPlan(target, ['CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" (LOWER(EMAIL) ASC) INVISIBLE;'], [recoverableDraft] as never);
+
+ expect(plan.mutations).toHaveLength(1);
+ expect(plan.mutations[0]?.operation).toBe("CREATE");
+ expect(plan.mutations[0]?.expectedAfter[0]).toMatchObject({ keyIsExpression: [true], directions: ["ASC"], visibility: "INVISIBLE" });
+ });
+
+ it("reads through the confirmed internal column created by a function index", async () => {
+ indexNames = [];
+ rejectCreate = false;
+ const recoverableDraft = {
+ ...drafts[0]!,
+ name: "IX_NEW",
+ columns: ["LOWER(EMAIL)"],
+ indexType: "FUNCTION-BASED NORMAL",
+ original: {
+ ...drafts[0]!.original,
+ columns: ["LOWER(EMAIL)"],
+ key_is_expression: [true],
+ key_directions: ["ASC"],
+ index_type: "FUNCTION-BASED NORMAL",
+ },
+ oracleOriginalMissing: true,
+ markedForDrop: false,
+ };
+ const plan = await prepareOracleIndexPlan(target, ['CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" (LOWER(EMAIL) ASC);'], [recoverableDraft] as never);
+
+ const execution = await executeOracleIndexPlan(plan, 10, () => true);
+
+ expect(ddl).toHaveLength(1);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["committed"]);
+ expect(execution?.readbackError).toBeUndefined();
+ });
+
+ it("checks internal-column projection after a function-index DROP and CREATE chain", async () => {
+ indexNames = ["IX_OLD"];
+ functionIndexName = "IX_OLD";
+ indexColumns = [
+ ["EMAIL", "VARCHAR2", 100, null, null, "Y"],
+ ["SYS_NC00001$", "VARCHAR2", 100, null, null, "Y"],
+ ];
+ rejectCreate = false;
+ const functionDraft = {
+ id: "rename-function",
+ name: "IX_NEW",
+ columns: ["LOWER(EMAIL)"],
+ isUnique: false,
+ isPrimary: false,
+ filter: "",
+ indexType: "FUNCTION-BASED NORMAL",
+ includedColumns: [],
+ comment: "",
+ markedForDrop: false,
+ original: { name: "IX_OLD", columns: ["LOWER(EMAIL)"], is_unique: false, is_primary: false, index_type: "FUNCTION-BASED NORMAL", key_metadata_complete: true, key_is_expression: [true], key_directions: ["ASC"], visibility: "VISIBLE", constraint_backed: false },
+ };
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" (LOWER(EMAIL) ASC);'], [functionDraft] as never);
+
+ const execution = await executeOracleIndexPlan(plan, 10, () => true);
+
+ expect(ddl).toHaveLength(2);
+ expect(execution?.steps.map((step) => step.state)).toEqual(["committed", "committed"]);
+ expect(execution?.readbackError).toBeUndefined();
+ });
+
+ it("executes later CREATE steps for multiple changed indexes", async () => {
+ rejectCreate = false;
+ const extraDraft = { ...drafts[1]!, id: "extra", name: "IX_EXTRA" };
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'CREATE INDEX "IX_NEW" ON "APP"."CONTACTS" ("EMAIL");', 'CREATE INDEX "IX_EXTRA" ON "APP"."CONTACTS" ("EMAIL");'], [drafts[0]!, drafts[1]!, extraDraft] as never);
+
+ const execution = await executeOracleIndexPlan(plan, 10, () => true);
+
+ expect(ddl).toHaveLength(3);
+ expect(indexNames).toEqual(["IX_NEW", "IX_EXTRA"]);
+ expect(
+ execution?.steps.map((step) => step.state),
+ JSON.stringify(execution),
+ ).toEqual(["committed", "committed", "committed"]);
+ expect(execution?.readbackError).toBeUndefined();
+ });
+
+ it("keeps internal-column projection conservative for unknown flags and NO+NO", async () => {
+ indexColumns = [
+ ["EMAIL", "VARCHAR2", 100, null, null, "Y"],
+ ["SYS_NC00001$", "VARCHAR2", 100, null, null, "Y"],
+ ["SYS_NC00002$", "VARCHAR2", 100, null, null, "Y"],
+ ];
+ columnFlags.set("SYS_NC00001$", ["B", "100", "NO", "YES"]);
+ columnFlags.set("SYS_NC00002$", ["B", "100", "NO", "NO"]);
+
+ const snapshot = await readOracleIndexSnapshot(target);
+
+ expect(snapshot.columns.map((column) => column.name)).toEqual(["EMAIL", "SYS_NC00001$", "SYS_NC00002$"]);
+ expect(snapshot.userColumns.map((column) => column.name)).toEqual(["EMAIL", "SYS_NC00002$"]);
+ columnFlags.set("SYS_NC00002$", ["unknown", "100", "NO", null]);
+ const unknown = await readOracleIndexSnapshot(target);
+ expect(unknown.userColumns.map((column) => column.name)).toContain("SYS_NC00002$");
+ });
+
+ it("retains YES+YES hidden columns and user-named SYS_NC columns", async () => {
+ indexColumns = [
+ ["EMAIL", "VARCHAR2", 100, null, null, "Y"],
+ ["SYS_NC_USER", "VARCHAR2", 100, null, null, "Y"],
+ ["SYS_NC00003$", "VARCHAR2", 100, null, null, "Y"],
+ ];
+ columnFlags.set("SYS_NC_USER", ["B", "100", "YES", "YES"]);
+ columnFlags.set("SYS_NC00003$", ["B", "100", "YES", "YES"]);
+
+ const snapshot = await readOracleIndexSnapshot(target);
+
+ expect(snapshot.userColumns.map((column) => column.name)).toEqual(["EMAIL", "SYS_NC_USER", "SYS_NC00003$"]);
+ });
+
+ it("falls back to a complete strict-base read without claiming charset detection", async () => {
+ failEnhancedColumns = true;
+ enhancedFailureRows = [["EMAIL", "WRONG_TYPE", 999, 1, 2, "N", "C", 999, "NO", "YES"]];
+
+ const snapshot = await readOracleIndexSnapshot(target);
+
+ expect(snapshot.columnReadMode).toBe("strict-base");
+ expect(snapshot.columns).toEqual([{ name: "EMAIL", dataType: "VARCHAR2", length: "100", precision: null, scale: null, nullable: true }]);
+ expect(snapshot.userColumns).toEqual(snapshot.columns);
+ });
+
+ it("refuses an enhanced-to-strict mode change during execution before DDL", async () => {
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";'], [drafts[0]!] as never);
+ failEnhancedColumns = true;
+
+ await expect(executeOracleIndexPlan(plan, 10, () => true)).rejects.toThrow("Index metadata changed");
+
+ expect(ddl).toHaveLength(0);
+ });
+
+ it("rejects a live column semantic change from the fixed load baseline before DDL", async () => {
+ const baseline = await readOracleIndexSnapshot(target);
+ const context = {
+ baseline: { snapshot: baseline, epoch: 1, targetIdentity: "target", requestId: 1, connectionRevision: 1, configFingerprint: "config", columnsFingerprint: "columns", indexesFingerprint: "indexes" },
+ columnsFingerprint: "columns",
+ indexesFingerprint: "indexes",
+ };
+ columnFlags.set("EMAIL", ["C", "100", "YES", "NO"]);
+
+ await expect(prepareOracleIndexPlan(target, [], [], context)).rejects.toThrow("Index metadata changed");
+
+ expect(ddl).toHaveLength(0);
+ });
+
+ it("matches loaded column definitions against complete enhanced semantics", async () => {
+ const snapshot = await readOracleIndexSnapshot(target);
+ const loaded = [{ name: "EMAIL", data_type: "VARCHAR2(100 BYTE)", is_nullable: true, numeric_precision: null, numeric_scale: null, character_maximum_length: 100 }];
+
+ expect(oracleIndexSnapshotMatchesLoadedColumns(snapshot, loaded)).toBe(true);
+ expect(oracleIndexSnapshotMatchesLoadedColumns(snapshot, [{ ...loaded[0]!, data_type: "VARCHAR2(100 CHAR)" }])).toBe(false);
+ });
+
+ it("strict-base loading still matches known precision and byte length fields", async () => {
+ failEnhancedColumns = true;
+ indexColumns = [
+ ["AMOUNT", "NUMBER", null, 10, 0, "N"],
+ ["RATE", "FLOAT", null, 126, null, "Y"],
+ ["PAYLOAD", "RAW", 8, null, null, "Y"],
+ ];
+ const snapshot = await readOracleIndexSnapshot(target);
+ const loaded = [
+ { name: "AMOUNT", data_type: "NUMBER(5)", is_nullable: false, numeric_precision: 5, numeric_scale: 0, character_maximum_length: null },
+ { name: "RATE", data_type: "FLOAT(20)", is_nullable: true, numeric_precision: 20, numeric_scale: null, character_maximum_length: null },
+ { name: "PAYLOAD", data_type: "RAW(4)", is_nullable: true, numeric_precision: null, numeric_scale: null, character_maximum_length: null },
+ ];
+
+ expect(oracleIndexSnapshotMatchesLoadedColumns(snapshot, loaded)).toBe(false);
+ expect(
+ oracleIndexSnapshotMatchesLoadedColumns(snapshot, [
+ { ...loaded[0]!, data_type: "NUMBER(10)", numeric_precision: 10 },
+ { ...loaded[1]!, data_type: "FLOAT(126)", numeric_precision: 126 },
+ { ...loaded[2]!, data_type: "RAW(8)" },
+ ]),
+ ).toBe(true);
+ expect(
+ oracleIndexSnapshotMatchesLoadedColumns(snapshot, [
+ { ...loaded[0]!, data_type: "NUMBER(5)", numeric_precision: 5 },
+ { ...loaded[1]!, data_type: "FLOAT(126)", numeric_precision: 126 },
+ { ...loaded[2]!, data_type: "RAW(8)" },
+ ]),
+ ).toBe(false);
+ expect(
+ oracleIndexSnapshotMatchesLoadedColumns(snapshot, [
+ { ...loaded[0]!, data_type: "NUMBER(10)", numeric_precision: 10 },
+ { ...loaded[1]!, data_type: "FLOAT(126)", numeric_precision: 126 },
+ { ...loaded[2]!, data_type: "RAW(4)" },
+ ]),
+ ).toBe(false);
+ expect(
+ oracleIndexSnapshotMatchesLoadedColumns(snapshot, [
+ { ...loaded[0]!, data_type: "NUMBER(10)", numeric_precision: 10 },
+ { ...loaded[1]!, data_type: "FLOAT(20)", numeric_precision: 20 },
+ { ...loaded[2]!, data_type: "RAW(8)" },
+ ]),
+ ).toBe(false);
+ });
+
+ it("matches OceanBase RAW length formatting from the actual agent contract", async () => {
+ indexColumns = [["PAYLOAD", "RAW", 8, null, null, "Y"]];
+ const snapshot = await readOracleIndexSnapshot(target);
+ const loaded = [{ name: "PAYLOAD", data_type: "RAW(8)", is_nullable: true, numeric_precision: null, numeric_scale: null, character_maximum_length: null }];
+
+ expect(oracleIndexSnapshotMatchesLoadedColumns(snapshot, loaded)).toBe(true);
+ expect(oracleIndexSnapshotMatchesLoadedColumns(snapshot, [{ ...loaded[0]!, data_type: "RAW(4)" }])).toBe(false);
+ });
+
+ it("stops before a later DROP when its constraint-support relation changes", async () => {
+ indexNames = ["IX_OLD", "IX_SECOND"];
+ const second = {
+ ...drafts[0]!,
+ id: "second",
+ name: "IX_SECOND",
+ original: { ...drafts[0]!.original, name: "IX_SECOND" },
+ };
+ const plan = await prepareOracleIndexPlan(target, ['DROP INDEX "APP"."IX_OLD";', 'DROP INDEX "APP"."IX_SECOND";'], [drafts[0]!, second] as never);
+
+ const result = await executeOracleIndexPlan(plan, 10, () => true);
+
+ expect(ddl).toEqual(['DROP INDEX "APP"."IX_OLD"']);
+ expect(result?.steps.map((step) => step.state)).toEqual(["committed", "notExecuted"]);
+ expect(result?.readbackError).toContain("support changed");
+ });
+});
diff --git a/apps/desktop/src/lib/database/oceanbasePrimaryKey.ts b/apps/desktop/src/lib/database/oceanbasePrimaryKey.ts
new file mode 100644
index 0000000000..56323e5594
--- /dev/null
+++ b/apps/desktop/src/lib/database/oceanbasePrimaryKey.ts
@@ -0,0 +1,411 @@
+import * as api from "@/lib/backend/api";
+import type { BuildTableStructureChangeSqlOptions } from "@/lib/table/tableStructureEditorSql";
+import { generateUniqueIndexName } from "@/lib/table/tableStructureEditorState";
+
+export interface PrimaryKeyTarget {
+ connectionId: string;
+ database: string;
+ schema: string;
+ tableName: string;
+ catalog?: string;
+ databaseType?: "oracle" | "oceanbase-oracle";
+}
+
+export type ExistingPrimaryKeyChange = NonNullable<BuildTableStructureChangeSqlOptions["primaryKeyChange"]>;
+
+export interface OceanbasePrimaryKeyPlan {
+ target: PrimaryKeyTarget;
+ change: ExistingPrimaryKeyChange;
+ draft?: ExistingPrimaryKeyChange;
+ snapshot: string;
+ statements: string[];
+}
+
+export type OceanbasePrimaryKeyGuards = {
+ canStart?: () => boolean;
+ connectionCurrent?: () => boolean;
+};
+
+export interface OceanbasePrimaryKeyResult {
+ steps: Array<{ sql: string; state: "committed" | "rejected" | "unknown" | "notExecuted"; error?: string }>;
+ readbackError?: string;
+ recoverySql?: string;
+ indexStates?: Array<{ name: string; state: "indexPresent" | "indexAbsent" | "indexChanged" | "indexUnknown" }>;
+}
+
+export class OceanbasePrimaryKeyValidationError extends Error {
+ constructor(
+ readonly key: string,
+ readonly values: Record<string, string> = {},
+ ) {
+ super(key);
+ }
+}
+
+const ident = (name: string) => `"${name.replace(/"/g, '""')}"`;
+const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
+const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
+const sameMembers = (a: string[], b: string[]) => same([...a].sort(), [...b].sort());
+const fail = (key: string): never => {
+ throw new OceanbasePrimaryKeyValidationError(key);
+};
+
+type OraclePrimaryKeyState = NonNullable<ExistingPrimaryKeyChange["oracleState"]>;
+
+function oraclePrimaryKeyState(key: unknown[], relyRows: unknown[][]): OraclePrimaryKeyState {
+ if (!["ENABLED", "DISABLED"].includes(String(key[1])) || !["VALIDATED", "NOT VALIDATED"].includes(String(key[2])) || !["DEFERRABLE", "NOT DEFERRABLE"].includes(String(key[3])) || !["IMMEDIATE", "DEFERRED"].includes(String(key[4]))) fail("incompleteMetadata");
+ if (relyRows.length !== 1 || relyRows[0]?.length !== 1) fail("incompleteMetadata");
+ const validated = key[2] === "VALIDATED";
+ if (!validated && relyRows[0]![0] !== null && relyRows[0]![0] !== "RELY") fail("incompleteMetadata");
+ const state = { enabled: key[1] === "ENABLED", validated, deferrable: key[3] === "DEFERRABLE", initiallyDeferred: key[4] === "DEFERRED", rely: !validated && relyRows[0]![0] === "RELY" };
+ if (!state.deferrable && state.initiallyDeferred) fail("unsupportedState");
+ return state;
+}
+
+const oracleStateBeforeIndex = (state: OraclePrimaryKeyState) => ` ${state.deferrable ? "DEFERRABLE" : "NOT DEFERRABLE"} INITIALLY ${state.initiallyDeferred ? "DEFERRED" : "IMMEDIATE"} ${state.rely ? "RELY" : "NORELY"}`;
+const oracleStateAfterIndex = (state: OraclePrimaryKeyState) => ` ${state.enabled ? "ENABLE" : "DISABLE"} ${state.validated ? "VALIDATE" : "NOVALIDATE"}`;
+
+async function queryPrimaryKey(target: PrimaryKeyTarget, sql: string) {
+ const result = await api.executeQuery(target.connectionId, target.database, sql, target.schema, undefined, { catalog: target.catalog, maxRows: 10001 });
+ if (result.execution_error) throw new Error(result.error?.detail || "Primary key metadata query failed");
+ if (result.truncated || result.has_more || result.rows.length >= 10001) fail("incompleteMetadata");
+ return result.rows;
+}
+
+async function readOracleIndex(target: PrimaryKeyTarget, owner: string, name: string) {
+ const [properties, columns] = await Promise.all([
+ queryPrimaryKey(target, `SELECT OWNER, INDEX_NAME, INDEX_TYPE, UNIQUENESS, STATUS, VISIBILITY, PARTITIONED, TABLE_OWNER, TABLE_NAME FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(owner)} AND INDEX_NAME = ${literal(name)}`),
+ queryPrimaryKey(target, `SELECT COLUMN_NAME, COLUMN_POSITION, DESCEND FROM SYS.ALL_IND_COLUMNS WHERE INDEX_OWNER = ${literal(owner)} AND INDEX_NAME = ${literal(name)} ORDER BY COLUMN_POSITION`),
+ ]);
+ return { properties, columns };
+}
+
+async function availableOracleIndexName(target: PrimaryKeyTarget, columns: string[]): Promise<string> {
+ const taken: string[] = [];
+ for (let attempt = 0; attempt < 64; attempt++) {
+ const candidate = generateUniqueIndexName(target.tableName, columns, taken, 30) || generateUniqueIndexName("DBX_PK", [], taken, 30);
+ if (!candidate) break;
+ const [indexes, constraints] = await Promise.all([
+ queryPrimaryKey(target, `SELECT INDEX_NAME FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(target.schema)} AND INDEX_NAME = ${literal(candidate)}`),
+ queryPrimaryKey(target, `SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS WHERE OWNER = ${literal(target.schema)} AND CONSTRAINT_NAME = ${literal(candidate)}`),
+ ]);
+ if (!indexes.length && !constraints.length) return candidate;
+ taken.push(candidate);
+ }
+ return fail("definitionChanged");
+}
+
+export async function prepareOraclePrimaryKeyChange(target: PrimaryKeyTarget, draft: ExistingPrimaryKeyChange) {
+ const snapshot = await readOceanbasePrimaryKeySnapshot(target, draft);
+ const original = JSON.parse(snapshot) as { keys: Array<Array<string | null>>; oracleState: OraclePrimaryKeyState };
+ const policy = draft.oracleIndex?.policy ?? "keep";
+ const name = original.keys[0]![6];
+ const oracleIndex: NonNullable<ExistingPrimaryKeyChange["oracleIndex"]> = { policy: name === null ? "none" : policy, owner: target.schema, name: name ?? "" };
+ if (original.oracleState.enabled && draft.columns.length && (policy === "drop" || !sameMembers(draft.originalColumns, draft.columns))) {
+ oracleIndex.newName = await availableOracleIndexName(target, draft.columns);
+ }
+ return { snapshot, change: { ...draft, oracleIndex, oracleState: original.oracleState } };
+}
+
+/** Reads the captured target afresh. No DDL is issued by this preflight. */
+export async function readOceanbasePrimaryKeySnapshot(target: PrimaryKeyTarget, change: ExistingPrimaryKeyChange): Promise<string> {
+ const oracle = target.databaseType === "oracle";
+ if (!target.schema || !target.tableName || !change.name || !change.originalColumns.length) fail("incompleteMetadata");
+ if (new Set(change.originalColumns).size !== change.originalColumns.length || new Set(change.columns).size !== change.columns.length) fail("duplicateColumns");
+ const query = (sql: string) => queryPrimaryKey(target, sql);
+ const where = `OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`;
+ const [identity, objects, columns, constraints, indexes, keys, keyColumns, tableFlags, columnFlags, references, relyRows, externalTables] = await Promise.all([
+ query("SELECT USER, SYS_CONTEXT('USERENV','CURRENT_SCHEMA'), SYS_CONTEXT('USERENV','DB_NAME') FROM DUAL"),
+ query(`SELECT OWNER, OBJECT_NAME, OBJECT_ID FROM SYS.ALL_OBJECTS WHERE OWNER = ${literal(target.schema)} AND OBJECT_NAME = ${literal(target.tableName)} AND OBJECT_TYPE = 'TABLE'`),
+ api.getColumns(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ api.listConstraints(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ api.listIndexes(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ query(`SELECT CONSTRAINT_NAME, STATUS, VALIDATED, DEFERRABLE, DEFERRED, INDEX_OWNER, INDEX_NAME FROM SYS.ALL_CONSTRAINTS WHERE ${where} AND CONSTRAINT_TYPE = 'P'`),
+ query(`SELECT COLUMN_NAME, POSITION FROM SYS.ALL_CONS_COLUMNS WHERE ${where} AND CONSTRAINT_NAME = ${literal(change.name)} ORDER BY POSITION`),
+ query(`SELECT IOT_TYPE, TEMPORARY FROM SYS.ALL_TABLES WHERE ${where}`),
+ query(`SELECT COLUMN_NAME, NULLABLE, VIRTUAL_COLUMN FROM SYS.ALL_TAB_COLS WHERE ${where} ORDER BY COLUMN_ID`),
+ query(`SELECT OWNER, TABLE_NAME, CONSTRAINT_NAME, STATUS FROM SYS.ALL_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'R' AND R_OWNER = ${literal(target.schema)} AND R_CONSTRAINT_NAME = ${literal(change.name)} ORDER BY OWNER, TABLE_NAME, CONSTRAINT_NAME`),
+ oracle ? query(`SELECT RELY FROM SYS.ALL_CONSTRAINTS WHERE ${where} AND CONSTRAINT_NAME = ${literal(change.name)} AND CONSTRAINT_TYPE = 'P'`) : Promise.resolve([]),
+ oracle ? query(`SELECT TABLE_NAME FROM SYS.ALL_EXTERNAL_TABLES WHERE ${where}`) : Promise.resolve([]),
+ ]);
+ if (identity.length !== 1 || identity[0]?.length !== 3 || identity[0].some((value) => typeof value !== "string" || !value)) fail("incompleteMetadata");
+ if (
+ objects.length !== 1 ||
+ objects[0]?.length !== 3 ||
+ objects[0][0] !== target.schema ||
+ objects[0][1] !== target.tableName ||
+ (typeof objects[0][2] !== "string" && typeof objects[0][2] !== "number") ||
+ !/^[1-9]\d*$/.test(String(objects[0][2])) ||
+ (typeof objects[0][2] === "number" && !Number.isSafeInteger(objects[0][2]))
+ )
+ fail("incompleteMetadata");
+ if (externalTables.length || tableFlags.length !== 1 || tableFlags[0]?.length !== 2 || tableFlags[0][0] !== null || tableFlags[0][1] !== "N") fail("unsupportedTable");
+ const key = keys[0];
+ if (keys.length !== 1 || key?.length !== 7 || key[0] !== change.name) fail("incompleteMetadata");
+ const state = oracle ? oraclePrimaryKeyState(key, relyRows) : undefined;
+ if (!oracle && !same(key.slice(1, 5), ["ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE"])) fail("unsupportedState");
+ if (change.oracleState && !same(change.oracleState, state)) fail("definitionChanged");
+ const noIndex = state?.enabled === false && key[5] === null && key[6] === null;
+ if (!noIndex && (key[5] !== target.schema || typeof key[6] !== "string" || !key[6])) fail("unsupportedIndex");
+ if (
+ !same(
+ keyColumns.map((row) => row[0]),
+ change.originalColumns,
+ ) ||
+ keyColumns.some((row, i) => row.length !== 2 || Number(row[1]) !== i + 1)
+ )
+ fail("definitionChanged");
+ const reported = constraints.filter((constraint) => constraint.constraint_type === "PRIMARY KEY");
+ if (
+ reported.length !== 1 ||
+ reported[0]?.name !== change.name ||
+ !same(reported[0]?.columns, change.originalColumns) ||
+ reported[0]?.enabled !== (key[1] === "ENABLED") ||
+ reported[0]?.valid !== (key[2] === "VALIDATED") ||
+ reported[0]?.deferrable !== (key[3] === "DEFERRABLE") ||
+ reported[0]?.initially_deferred !== (key[4] === "DEFERRED")
+ )
+ fail("incompleteMetadata");
+ const columnNames = new Set(columns.map((column) => column.name));
+ const markedNames = columns.filter((column) => column.is_primary_key).map((column) => column.name);
+ if (!columns.length || columnNames.size !== columns.length || markedNames.length !== change.originalColumns.length || change.originalColumns.some((name) => !markedNames.includes(name))) fail("incompleteMetadata");
+ for (const name of new Set([...change.originalColumns, ...change.columns])) {
+ const flags = columnFlags.filter((row) => row[0] === name);
+ if (!columnNames.has(name) || flags.length !== 1 || flags[0]?.length !== 3 || !["Y", "N"].includes(String(flags[0][1]))) fail("incompleteMetadata");
+ if (flags[0][2] !== "NO") fail("virtualColumn");
+ if (columns.find((column) => column.name === name)?.is_nullable !== (flags[0][1] === "Y")) fail("incompleteMetadata");
+ }
+ if (references.length) {
+ throw new OceanbasePrimaryKeyValidationError("referenced", { names: references.map((row) => `${String(row[0])}.${String(row[1])}.${String(row[2])}`).join(", ") });
+ }
+ const indexName = noIndex ? "" : (key[6] as string);
+ const [indexProperties, indexColumns, indexUsers] = noIndex
+ ? [[], [], []]
+ : await Promise.all([
+ query(`SELECT OWNER, INDEX_NAME, INDEX_TYPE, UNIQUENESS, STATUS, VISIBILITY, PARTITIONED FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(target.schema)} AND INDEX_NAME = ${literal(indexName)} AND TABLE_OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`),
+ query(`SELECT COLUMN_NAME, COLUMN_POSITION, DESCEND FROM SYS.ALL_IND_COLUMNS WHERE INDEX_OWNER = ${literal(target.schema)} AND INDEX_NAME = ${literal(indexName)} ORDER BY COLUMN_POSITION`),
+ query(`SELECT OWNER, TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE FROM SYS.ALL_CONSTRAINTS WHERE INDEX_OWNER = ${literal(target.schema)} AND INDEX_NAME = ${literal(indexName)} ORDER BY OWNER, TABLE_NAME, CONSTRAINT_NAME`),
+ ]);
+ if (!noIndex) {
+ const uniqueness = indexProperties[0]?.[3];
+ if (!(oracle ? ["UNIQUE", "NONUNIQUE"].includes(String(uniqueness)) : uniqueness === "UNIQUE") || (state?.deferrable && uniqueness !== "NONUNIQUE") || !same(indexProperties, [[target.schema, indexName, "NORMAL", uniqueness, "VALID", "VISIBLE", "NO"]])) fail("unsupportedIndex");
+ if (
+ !(oracle
+ ? sameMembers(
+ indexColumns.map((row) => String(row[0])),
+ change.originalColumns,
+ )
+ : same(
+ indexColumns.map((row) => row[0]),
+ change.originalColumns,
+ )) ||
+ indexColumns.some((row, i) => row.length !== 3 || Number(row[1]) !== i + 1 || row[2] !== "ASC")
+ )
+ fail("unsupportedIndex");
+ if (!same(indexUsers, [[target.schema, target.tableName, change.name, "P"]])) fail("sharedIndex");
+ const reportedIndexes = indexes.filter((index) => index.name === indexName);
+ if (
+ reportedIndexes.length !== 1 ||
+ !same(
+ reportedIndexes[0]?.columns,
+ indexColumns.map((row) => row[0]),
+ ) ||
+ reportedIndexes[0]?.is_unique !== (uniqueness === "UNIQUE") ||
+ reportedIndexes[0]?.is_primary !== true ||
+ reportedIndexes[0]?.index_type !== "NORMAL"
+ )
+ fail("incompleteMetadata");
+ }
+ if (oracle && change.oracleIndex && (change.oracleIndex.name || change.oracleIndex.policy === "none")) {
+ const index = change.oracleIndex;
+ if (index.owner !== target.schema || index.name !== indexName || !(noIndex ? index.policy === "none" : ["keep", "drop"].includes(index.policy))) fail("definitionChanged");
+ if (index.newName) {
+ const conflict = await query(`SELECT INDEX_NAME FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(index.owner)} AND INDEX_NAME = ${literal(index.newName)}`);
+ if (conflict.length) fail("definitionChanged");
+ }
+ }
+ if (change.columns.length) {
+ const table = `${ident(target.schema)}.${ident(target.tableName)}`;
+ const [nulls, duplicates] = await Promise.all([
+ query(`SELECT COUNT(*) FROM ${table} WHERE (${change.columns.map((name) => `${ident(name)} IS NULL`).join(" OR ")}) AND ROWNUM <= 1`),
+ query(`SELECT COUNT(*) FROM (SELECT 1 FROM ${table} GROUP BY ${change.columns.map(ident).join(", ")} HAVING COUNT(*) > 1) WHERE ROWNUM <= 1`),
+ ]);
+ for (const [rows, error] of [
+ [nulls, "nullValues"],
+ [duplicates, "duplicateValues"],
+ ] as const) {
+ if (rows.length !== 1 || rows[0]?.length !== 1 || ![0, 1, "0", "1"].includes(rows[0][0] as number | string)) fail("incompleteMetadata");
+ if (Number(rows[0][0]) !== 0) fail(error);
+ }
+ }
+ return JSON.stringify({
+ user: identity[0]![0],
+ currentSchema: identity[0]![1],
+ database: target.database,
+ databaseName: identity[0]![2],
+ objectId: String(objects[0]![2]),
+ columns,
+ keys,
+ keyColumns,
+ tableFlags,
+ columnFlags,
+ indexProperties,
+ indexColumns,
+ indexUsers,
+ ...(oracle ? { oracleState: state, externalTables } : {}),
+ });
+}
+
+/** Rechecks the original target and stops at the first failed independent DDL. */
+export async function executeOceanbasePrimaryKeyPlan(plan: OceanbasePrimaryKeyPlan, timeoutSecs: number, stillCurrent: (() => boolean) | OceanbasePrimaryKeyGuards): Promise<OceanbasePrimaryKeyResult | undefined> {
+ const canStart = typeof stillCurrent === "function" ? stillCurrent : (stillCurrent?.canStart ?? (() => true));
+ const connectionCurrent = typeof stillCurrent === "function" ? stillCurrent : (stillCurrent?.connectionCurrent ?? (() => true));
+ if (!canStart() || !connectionCurrent()) return undefined;
+ const { target, change } = plan;
+ const current = await readOceanbasePrimaryKeySnapshot(target, change);
+ if (!canStart() || !connectionCurrent()) return undefined;
+ if (current !== plan.snapshot) fail("definitionChanged");
+ if (!canStart() || !connectionCurrent()) return undefined;
+ const steps: OceanbasePrimaryKeyResult["steps"] = plan.statements.map((sql) => ({ sql, state: "notExecuted" }));
+ for (let i = 0; i < steps.length; i++) {
+ const step = steps[i]!;
+ if (i === 0) {
+ if (!canStart() || !connectionCurrent()) return undefined;
+ } else {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ if (!connectionCurrent()) break;
+ }
+ try {
+ const result = await api.executeQuery(target.connectionId, target.database, step.sql.replace(/;\s*$/, ""), target.schema, undefined, { catalog: target.catalog, timeoutSecs });
+ if (!connectionCurrent()) {
+ step.state = "unknown";
+ step.error = "Connection changed during execution";
+ break;
+ }
+ if (result.execution_error) {
+ step.state = "rejected";
+ step.error = result.error?.detail || "Primary key statement rejected";
+ break;
+ }
+ step.state = "committed";
+ } catch (error) {
+ step.state = "unknown";
+ step.error = error instanceof Error ? error.message : String(error);
+ break;
+ }
+ }
+ if (steps.every((step) => step.state === "notExecuted")) {
+ return undefined;
+ }
+ const result: OceanbasePrimaryKeyResult = { steps };
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ try {
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ const [, constraints] = await Promise.all([
+ api.getColumns(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ api.listConstraints(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ api.listIndexes(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ ]);
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ const keys = constraints.filter((constraint) => constraint.constraint_type === "PRIMARY KEY");
+ if (steps.every((step) => step.state === "committed")) {
+ if (change.columns.length ? keys.length !== 1 || keys[0]?.name !== change.name || !same(keys[0]?.columns, change.columns) : keys.length !== 0) {
+ result.readbackError = "definitionChanged";
+ }
+ if (target.databaseType === "oracle" && change.columns.length && change.oracleState) {
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ const where = `OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)} AND CONSTRAINT_TYPE = 'P'`;
+ const [currentKeys, relyRows] = await Promise.all([
+ queryPrimaryKey(target, `SELECT CONSTRAINT_NAME, STATUS, VALIDATED, DEFERRABLE, DEFERRED, INDEX_OWNER, INDEX_NAME FROM SYS.ALL_CONSTRAINTS WHERE ${where}`),
+ queryPrimaryKey(target, `SELECT RELY FROM SYS.ALL_CONSTRAINTS WHERE ${where} AND CONSTRAINT_NAME = ${literal(change.name)}`),
+ ]);
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ if (currentKeys.length !== 1 || currentKeys[0]?.length !== 7 || currentKeys[0][0] !== change.name) fail("incompleteMetadata");
+ const state = oraclePrimaryKeyState(currentKeys[0], relyRows);
+ if (
+ !same(state, change.oracleState) ||
+ keys[0]?.enabled !== state.enabled ||
+ keys[0]?.valid !== state.validated ||
+ keys[0]?.deferrable !== state.deferrable ||
+ keys[0]?.initially_deferred !== state.initiallyDeferred ||
+ (state.enabled && (currentKeys[0][5] !== change.oracleIndex?.owner || currentKeys[0][6] !== (change.oracleIndex?.newName ?? change.oracleIndex?.name)))
+ )
+ result.readbackError = "definitionChanged";
+ }
+ }
+ let recoveryIndex = "";
+ let recoveryVerified = true;
+ if (target.databaseType === "oracle" && change.oracleIndex) {
+ const original = JSON.parse(plan.snapshot) as { indexProperties: unknown[][]; indexColumns: unknown[][] };
+ const index = change.oracleIndex;
+ result.indexStates = [];
+ for (const name of [index.name, ...(index.newName ? [index.newName] : [])].filter(Boolean)) {
+ try {
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ const currentIndex = await readOracleIndex(target, index.owner, name);
+ if (!connectionCurrent()) {
+ result.readbackError = "Connection changed during execution; readback is unverifiable.";
+ return result;
+ }
+ const absent = currentIndex.properties.length === 0 && currentIndex.columns.length === 0;
+ const isOriginal = name === index.name;
+ const expectedProperties = isOriginal
+ ? original.indexProperties.map((row) => [...row, target.schema, target.tableName])
+ : [[index.owner, name, "NORMAL", change.oracleState && (change.oracleState.deferrable || !change.oracleState.validated) ? "NONUNIQUE" : "UNIQUE", "VALID", "VISIBLE", "NO", target.schema, target.tableName]];
+ const expectedColumns = isOriginal ? original.indexColumns : change.columns.map((column, i) => [column, i + 1, "ASC"]);
+ const normalizedColumns = currentIndex.columns.map((row) => [row[0], Number(row[1]), row[2]]);
+ const matches =
+ same(currentIndex.properties, expectedProperties) &&
+ same(
+ normalizedColumns,
+ expectedColumns.map((row) => [row[0], Number(row[1]), row[2]]),
+ );
+ result.indexStates.push({ name: `${index.owner}.${name}`, state: absent ? "indexAbsent" : matches ? "indexPresent" : "indexChanged" });
+ if (isOriginal) {
+ recoveryVerified = absent || matches;
+ if (matches && change.oracleState?.enabled !== false) recoveryIndex = ` USING INDEX ${ident(index.owner)}.${ident(name)}`;
+ }
+ if (steps.every((step) => step.state === "committed")) {
+ const shouldExist = !isOriginal || index.policy === "keep";
+ if (shouldExist ? !matches : !absent) result.readbackError = "definitionChanged";
+ }
+ } catch (error) {
+ result.indexStates.push({ name: `${index.owner}.${name}`, state: "indexUnknown" });
+ result.readbackError = error instanceof Error ? error.message : String(error);
+ recoveryVerified = false;
+ }
+ }
+ }
+ if (connectionCurrent() && steps[0]?.state === "committed" && keys.length === 0) {
+ const state = change.oracleState;
+ const sql = `ALTER TABLE ${ident(target.schema)}.${ident(target.tableName)} ADD CONSTRAINT ${ident(change.name)} PRIMARY KEY (${change.originalColumns.map(ident).join(", ")})${state ? oracleStateBeforeIndex(state) : ""}${recoveryIndex}${state ? oracleStateAfterIndex(state) : ""};`;
+ result.recoverySql = recoveryVerified
+ ? sql
+ : `-- VERIFY ORIGINAL INDEX DEFINITION BEFORE RECOVERY\n${sql
+ .split(/\r?\n/)
+ .map((line) => `-- ${line}`)
+ .join("\n")}`;
+ }
+ } catch (error) {
+ result.readbackError = error instanceof Error ? error.message : String(error);
+ }
+ return result;
+}
diff --git a/apps/desktop/src/lib/database/oracleConstraints.ts b/apps/desktop/src/lib/database/oracleConstraints.ts
new file mode 100644
index 0000000000..3b09cfe235
--- /dev/null
+++ b/apps/desktop/src/lib/database/oracleConstraints.ts
@@ -0,0 +1,800 @@
+import * as api from "@/lib/backend/api";
+import type { ConstraintInfo, OracleConstraintMetadata } from "@/types/database";
+import type { BuildTableStructureChangeSqlOptions, OracleCheckConstraint, OracleConstraintChange, OracleConstraintDefinition, OracleUniqueConstraint, OracleForeignKeyState } from "@/lib/table/tableStructureEditorSql";
+import { generateUniqueIndexName } from "@/lib/table/tableStructureEditorState";
+
+export interface OracleConstraintTarget {
+ connectionId: string;
+ database: string;
+ schema: string;
+ tableName: string;
+ catalog?: string;
+ databaseType: "oracle" | "oceanbase-oracle";
+}
+
+export interface OracleConstraintSnapshot {
+ user: string;
+ currentSchema: string;
+ database: string;
+ databaseName: string;
+ objectId: string;
+ columns: Array<{ name: string; dataType: string; length: string | null; precision: string | null; scale: string | null; nullable: boolean; charUsed?: string | null; charLength?: string | null; userGenerated?: string | null; hiddenColumn?: string | null }>;
+ indexColumnReadMode?: "enhanced" | "strict-base";
+ constraints: OracleConstraintDefinition[];
+ names: Array<{ name: string; table: string }>;
+ indexNames: string[];
+ indexes: Array<{
+ owner: string;
+ name: string;
+ tableOwner: string;
+ tableName: string;
+ indexType: string;
+ uniqueness: string;
+ status: string;
+ partitioned: boolean;
+ visibility: string;
+ secondary: string | null;
+ columns: string[];
+ directions: string[];
+ keyIsExpression: boolean[];
+ includedColumns: string[];
+ constraints: Array<{ owner: string; tableName: string; name: string }>;
+ }>;
+ references: Array<{ owner: string; table: string; name: string; status: string; validated: string }>;
+}
+
+export interface OracleConstraintPlan {
+ target: OracleConstraintTarget;
+ options: BuildTableStructureChangeSqlOptions;
+ change: OracleConstraintChange;
+ snapshot: OracleConstraintSnapshot;
+ snapshotFingerprint: string;
+ statements: string[];
+ notices: string[];
+}
+
+export interface OracleConstraintExecutionResult {
+ steps: Array<{ sql: string; state: "committed" | "rejected" | "unknown" | "notExecuted"; error?: string }>;
+ readbackError?: string;
+ recoverySql?: string;
+}
+
+export interface OracleIndexSnapshot {
+ user: string;
+ currentSchema: string;
+ database: string;
+ databaseName: string;
+ objectId: string;
+ columns: OracleConstraintSnapshot["columns"];
+ userColumns: OracleConstraintSnapshot["columns"];
+ columnReadMode: "enhanced" | "strict-base";
+ indexes: OracleConstraintSnapshot["indexes"];
+ indexNames: string[];
+}
+
+export class OracleConstraintMetadataError extends Error {
+ constructor(readonly reason: "incomplete" | "changed" | "invalidData" | "unreadableData") {
+ super(reason === "invalidData" ? "Existing rows violate the target constraint." : reason === "unreadableData" ? "Existing rows could not be verified before rebuilding the constraint." : "Constraint metadata is incomplete, unsupported, or changed. Refresh the table definition.");
+ }
+}
+
+function invalid(reason: OracleConstraintMetadataError["reason"] = "incomplete"): never {
+ throw new OracleConstraintMetadataError(reason);
+}
+
+const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
+const ident = (value: string) => `"${value.replace(/"/g, '""')}"`;
+
+async function query(target: OracleConstraintTarget, sql: string, stillCurrent: () => boolean = () => true): Promise<unknown[][]> {
+ if (!stillCurrent()) invalid("changed");
+ const result = await api.executeQuery(target.connectionId, target.database, sql, target.schema, undefined, { catalog: target.catalog, maxRows: 10001 });
+ if (!stillCurrent()) invalid("changed");
+ if (result.execution_error || result.truncated || result.has_more || result.rows.length >= 10001) invalid();
+ return result.rows;
+}
+
+function stateFromMetadata(metadata: OracleConstraintMetadata): OracleForeignKeyState {
+ const { status, validated, deferrable, deferred, rely } = metadata;
+ if (
+ !status ||
+ !["ENABLED", "DISABLED"].includes(status) ||
+ !validated ||
+ !["VALIDATED", "NOT VALIDATED"].includes(validated) ||
+ !deferrable ||
+ !["DEFERRABLE", "NOT DEFERRABLE"].includes(deferrable) ||
+ !deferred ||
+ !["DEFERRED", "IMMEDIATE"].includes(deferred) ||
+ (rely !== null && !["RELY", "NORELY"].includes(rely))
+ )
+ invalid();
+ const result = { enabled: status === "ENABLED", validated: validated === "VALIDATED", deferrable: deferrable === "DEFERRABLE", initiallyDeferred: deferred === "DEFERRED", rely: rely === "RELY" };
+ if (result.initiallyDeferred && !result.deferrable) invalid();
+ return result;
+}
+
+export function oracleConstraintDefinitionFromInfo(info: ConstraintInfo, target?: OracleConstraintTarget): OracleConstraintDefinition {
+ const metadata = info.oracle_metadata;
+ if (!metadata?.metadataComplete || metadata.owner === "" || !metadata.constraintType) invalid();
+ if (target && metadata.owner !== target.schema) invalid("changed");
+ const state = stateFromMetadata(metadata);
+ if (metadata.constraintType === "C" && info.constraint_type === "CHECK" && info.definition.trim()) {
+ const definition: OracleCheckConstraint = { name: info.name, expression: info.definition, state };
+ return { kind: "check", definition };
+ }
+ if (metadata.constraintType === "U" && info.constraint_type === "UNIQUE" && info.columns.length) {
+ const index = metadata.index;
+ if (!metadata.indexName && !metadata.indexOwner && !metadata.indexSharing && !index) {
+ if (state.enabled || (target && info.oracle_metadata?.metadataComplete !== true)) invalid();
+ return {
+ kind: "unique",
+ definition: {
+ name: info.name,
+ columns: [...info.columns],
+ state,
+ relyRaw: metadata.rely ?? "NULL",
+ index: {
+ owner: target?.schema ?? metadata.owner,
+ name: "",
+ tableOwner: target?.schema ?? metadata.owner,
+ tableName: target?.tableName ?? "",
+ sharing: "exclusive",
+ metadataComplete: true,
+ indexType: "NORMAL",
+ uniqueness: "NONUNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: [...info.columns],
+ directions: info.columns.map(() => "ASC"),
+ keyIsExpression: info.columns.map(() => false),
+ includedColumns: [],
+ newNameAvailable: false,
+ },
+ },
+ };
+ }
+ if (!metadata.indexName || !metadata.indexOwner || !metadata.indexSharing || !index) invalid();
+ if (!index.metadataComplete || index.owner !== metadata.indexOwner || index.tableOwner !== metadata.owner || (target && (index.tableOwner !== target.schema || index.tableName !== target.tableName))) invalid();
+ const definition: OracleUniqueConstraint = {
+ name: info.name,
+ columns: [...info.columns],
+ state,
+ relyRaw: metadata.rely ?? "NULL",
+ index: {
+ owner: index.owner,
+ name: metadata.indexName,
+ tableOwner: index.tableOwner,
+ tableName: index.tableName,
+ sharing: metadata.indexSharing,
+ metadataComplete: index.metadataComplete,
+ indexType: index.indexType,
+ uniqueness: index.uniqueness,
+ status: index.status,
+ partitioned: index.partitioned,
+ visibility: index.visibility,
+ secondary: index.secondary,
+ columns: [...index.columns],
+ directions: [...index.directions],
+ keyIsExpression: [...index.keyIsExpression],
+ includedColumns: [...index.includedColumns],
+ newNameAvailable: false,
+ },
+ };
+ return { kind: "unique", definition };
+ }
+ invalid();
+}
+
+function sortedJson(value: unknown): string {
+ return JSON.stringify(value);
+}
+
+function expressionTokens(expression: string): string[] {
+ const tokens: string[] = [];
+ for (let i = 0; i < expression.length;) {
+ const ch = expression[i]!;
+ if (/\s/.test(ch)) {
+ i++;
+ continue;
+ }
+ if (expression.startsWith("--", i)) {
+ const newline = expression.indexOf("\n", i + 2);
+ i = newline < 0 ? expression.length : newline + 1;
+ continue;
+ }
+ if (expression.startsWith("/*", i)) {
+ const end = expression.indexOf("*/", i + 2);
+ if (end < 0) return [];
+ i = end + 2;
+ continue;
+ }
+ if (ch === "'" || ch === '"') {
+ const quote = ch;
+ let value = ch;
+ i++;
+ let closed = false;
+ while (i < expression.length) {
+ value += expression[i]!;
+ if (expression[i] === quote) {
+ if (expression[i + 1] === quote) {
+ value += expression[i + 1]!;
+ i += 2;
+ continue;
+ }
+ i++;
+ closed = true;
+ break;
+ }
+ i++;
+ }
+ if (!closed) return [];
+ tokens.push(value);
+ continue;
+ }
+ if (/[A-Za-z0-9_$#]/.test(ch)) {
+ let word = ch;
+ i++;
+ while (i < expression.length && /[A-Za-z0-9_$#]/.test(expression[i]!)) word += expression[i++]!;
+ tokens.push(word.toUpperCase());
+ continue;
+ }
+ const pair = expression.slice(i, i + 2);
+ if (["<=", ">=", "<>", "!=", "||", ":=", "**"].includes(pair)) {
+ tokens.push(pair);
+ i += 2;
+ continue;
+ }
+ tokens.push(ch);
+ i++;
+ }
+ return tokens;
+}
+
+/** Reads the table/session/constraint/index/reference state required before a CHECK/UNIQUE write. */
+export async function readOracleIndexSnapshot(target: OracleConstraintTarget, stillCurrent: () => boolean = () => true, ownerNames: string[] = []): Promise<OracleIndexSnapshot> {
+ const snapshot = await readOracleConstraintSnapshot(target, undefined, true, stillCurrent, ownerNames);
+ const columns = [...snapshot.columns].sort((left, right) => left.name.localeCompare(right.name));
+ const userColumns = snapshot.indexColumnReadMode === "enhanced" ? columns.filter((column) => !(column.userGenerated === "NO" && column.hiddenColumn === "YES")) : columns;
+ return {
+ user: snapshot.user,
+ currentSchema: snapshot.currentSchema,
+ database: snapshot.database,
+ databaseName: snapshot.databaseName,
+ objectId: snapshot.objectId,
+ columns,
+ userColumns,
+ columnReadMode: snapshot.indexColumnReadMode ?? "strict-base",
+ indexes: snapshot.indexes.filter((index) => index.tableOwner === target.schema && index.tableName === target.tableName),
+ indexNames: snapshot.indexNames,
+ };
+}
+
+export async function readOracleConstraintSnapshot(target: OracleConstraintTarget, change?: OracleConstraintChange, indexesOnly = false, stillCurrent: () => boolean = () => true, requestedIndexNames: string[] = []): Promise<OracleConstraintSnapshot> {
+ if (!stillCurrent()) invalid("changed");
+ target = { ...target };
+ if (change) change = JSON.parse(JSON.stringify(change)) as OracleConstraintChange;
+ const baseColumnsSql = `SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE FROM SYS.ALL_TAB_COLS WHERE OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)} ORDER BY COLUMN_NAME`;
+ const enhancedColumnsSql = `SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE, CHAR_USED, CHAR_LENGTH, USER_GENERATED, HIDDEN_COLUMN FROM SYS.ALL_TAB_COLS WHERE OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`;
+ let indexColumnReadMode: OracleConstraintSnapshot["indexColumnReadMode"];
+ const columnsQuery = indexesOnly
+ ? (async () => {
+ try {
+ const rows = await query(target, enhancedColumnsSql, stillCurrent);
+ indexColumnReadMode = "enhanced";
+ return rows;
+ } catch {
+ const rows = await query(target, baseColumnsSql, stillCurrent);
+ indexColumnReadMode = "strict-base";
+ return rows;
+ }
+ })()
+ : query(target, `SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE FROM SYS.ALL_TAB_COLS WHERE OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)} ORDER BY COLUMN_ID`, stillCurrent);
+ const wantedConstraintNames = [...new Set([change?.original?.definition.name, change?.target?.definition.name].filter((name): name is string => !!name))];
+ const wantedIndexNames = [
+ ...new Set([...requestedIndexNames, ...(change?.original?.kind === "unique" ? [change.original.definition.index.name] : []), ...(change?.target?.kind === "unique" ? [change.target.definition.index.name, change.target.definition.index.newName || ""] : [])].filter(Boolean)),
+ ];
+ const inList = (column: string, names: string[]) => (names.length ? ` AND ${column} IN (${names.map(literal).join(", ")})` : " AND 1 = 0");
+ const sharedUsageNamesSql = `SELECT c.INDEX_OWNER, c.INDEX_NAME, c.OWNER, c.TABLE_NAME, c.CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS c WHERE c.CONSTRAINT_TYPE IN ('P', 'U') AND c.INDEX_NAME IS NOT NULL AND EXISTS (SELECT 1 FROM SYS.ALL_INDEXES i WHERE i.OWNER = c.INDEX_OWNER AND i.INDEX_NAME = c.INDEX_NAME AND i.TABLE_OWNER = ${literal(target.schema)} AND i.TABLE_NAME = ${literal(target.tableName)}) ORDER BY c.INDEX_OWNER, c.INDEX_NAME, c.OWNER, c.TABLE_NAME, c.CONSTRAINT_NAME`;
+ const [identity, objects, tableShapes, externalTables, columns, infos, names, indexNames, indexDetails, indexUsage] = await Promise.all([
+ query(target, "SELECT USER, SYS_CONTEXT('USERENV','CURRENT_SCHEMA'), SYS_CONTEXT('USERENV','DB_NAME') FROM DUAL", stillCurrent),
+ query(target, `SELECT OWNER, OBJECT_NAME, OBJECT_ID FROM SYS.ALL_OBJECTS WHERE OWNER = ${literal(target.schema)} AND OBJECT_NAME = ${literal(target.tableName)} AND OBJECT_TYPE = 'TABLE'`, stillCurrent),
+ query(target, `SELECT IOT_TYPE, TEMPORARY FROM SYS.ALL_TABLES WHERE OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`, stillCurrent),
+ query(target, `SELECT OWNER, TABLE_NAME FROM SYS.ALL_EXTERNAL_TABLES WHERE OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`, stillCurrent),
+ columnsQuery,
+ indexesOnly ? Promise.resolve([]) : api.listConstraints(target.connectionId, target.database, target.schema, target.tableName, target.catalog),
+ indexesOnly ? Promise.resolve([]) : query(target, `SELECT CONSTRAINT_NAME, TABLE_NAME FROM SYS.ALL_CONSTRAINTS WHERE OWNER = ${literal(target.schema)}${inList("CONSTRAINT_NAME", wantedConstraintNames)} ORDER BY CONSTRAINT_NAME`, stillCurrent),
+ query(target, `SELECT INDEX_NAME FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(target.schema)}${inList("INDEX_NAME", wantedIndexNames)} ORDER BY INDEX_NAME`, stillCurrent),
+ query(
+ target,
+ `SELECT i.OWNER, i.INDEX_NAME, i.TABLE_OWNER, i.TABLE_NAME, i.INDEX_TYPE, i.UNIQUENESS, i.STATUS, i.PARTITIONED, i.VISIBILITY, i.SECONDARY, ic.COLUMN_NAME, ic.DESCEND, ie.COLUMN_EXPRESSION FROM SYS.ALL_INDEXES i JOIN SYS.ALL_IND_COLUMNS ic ON ic.INDEX_OWNER = i.OWNER AND ic.INDEX_NAME = i.INDEX_NAME LEFT JOIN SYS.ALL_IND_EXPRESSIONS ie ON ie.INDEX_OWNER = ic.INDEX_OWNER AND ie.INDEX_NAME = ic.INDEX_NAME AND ie.TABLE_OWNER = ic.TABLE_OWNER AND ie.TABLE_NAME = ic.TABLE_NAME AND ie.COLUMN_POSITION = ic.COLUMN_POSITION WHERE i.TABLE_OWNER = ${literal(target.schema)} AND i.TABLE_NAME = ${literal(target.tableName)} ORDER BY i.OWNER, i.INDEX_NAME, ic.COLUMN_POSITION`,
+ stillCurrent,
+ ),
+ query(target, sharedUsageNamesSql, stillCurrent),
+ ]);
+ if (!stillCurrent()) invalid("changed");
+ if (identity.length !== 1 || identity[0]?.length !== 3 || identity[0].some((value) => typeof value !== "string" || !value)) invalid();
+ if (objects.length !== 1 || objects[0]?.length !== 3 || objects[0][0] !== target.schema || objects[0][1] !== target.tableName || !/^[1-9]\d*$/.test(String(objects[0][2]))) invalid();
+ if (tableShapes.length !== 1 || tableShapes[0]?.length !== 2 || (tableShapes[0][0] !== null && tableShapes[0][0] !== "") || tableShapes[0][1] !== "N") invalid();
+ if (externalTables.length !== 0) invalid();
+ if (typeof objects[0][2] === "number" && !Number.isSafeInteger(objects[0][2])) invalid();
+ const numeric = (value: unknown): string | null => {
+ if (value === null) return null;
+ if ((typeof value !== "string" && typeof value !== "number") || !/^-?\d+$/.test(String(value))) invalid();
+ return String(value);
+ };
+ if (!columns.length) invalid();
+ const seenColumns = new Set<string>();
+ const columnDefinitions = columns.map((row) => {
+ if (row.length < 6 || (!indexesOnly && row.length !== 6) || (indexColumnReadMode === "enhanced" && row.length > 10) || typeof row[0] !== "string" || !row[0] || seenColumns.has(row[0]) || typeof row[1] !== "string" || !row[1] || !["Y", "N"].includes(String(row[5]))) invalid();
+ seenColumns.add(row[0]);
+ const base = { name: row[0], dataType: row[1], length: numeric(row[2]), precision: numeric(row[3]), scale: numeric(row[4]), nullable: row[5] === "Y" };
+ if (indexColumnReadMode !== "enhanced") return base;
+ const optionalText = (index: number): string | null => {
+ const value = row[index];
+ if (value === undefined || value === null) return null;
+ if (typeof value !== "string") invalid();
+ return value;
+ };
+ return { ...base, charUsed: optionalText(6), charLength: numeric(row[7] ?? null), userGenerated: optionalText(8), hiddenColumn: optionalText(9) };
+ });
+ const editableInfos = indexesOnly ? [] : infos.filter((item) => item.constraint_type === "CHECK" || item.constraint_type === "UNIQUE");
+ const definitions = editableInfos.map((info) => oracleConstraintDefinitionFromInfo(info, target)).sort((a, b) => a.definition.name.localeCompare(b.definition.name));
+ if (!names.every((row) => row.length === 2 && typeof row[0] === "string" && !!row[0] && typeof row[1] === "string" && !!row[1])) invalid();
+ const nameRows = names.map((row) => ({ name: String(row[0]), table: String(row[1]) }));
+ if (!indexNames.every((row) => row.length === 1 && typeof row[0] === "string" && !!row[0])) invalid();
+ if (
+ indexDetails.some(
+ (row) => row.length !== 13 || row.slice(0, 9).some((value) => typeof value !== "string" || !value) || (row[9] !== null && typeof row[9] !== "string") || typeof row[10] !== "string" || !row[10] || !["ASC", "DESC"].includes(String(row[11])) || (row[12] !== null && typeof row[12] !== "string"),
+ )
+ )
+ invalid();
+ if (indexUsage.some((row) => row.length !== 5 || row.some((value) => typeof value !== "string" || !value))) invalid();
+ const references: OracleConstraintSnapshot["references"] = [];
+ if (!indexesOnly && change?.original?.kind === "unique") {
+ const original = change.original.definition;
+ const rows = await query(
+ target,
+ `SELECT OWNER, TABLE_NAME, CONSTRAINT_NAME, STATUS, VALIDATED FROM SYS.ALL_CONSTRAINTS WHERE R_OWNER = ${literal(target.schema)} AND R_CONSTRAINT_NAME = ${literal(original.name)} AND CONSTRAINT_TYPE = 'R' ORDER BY OWNER, TABLE_NAME, CONSTRAINT_NAME`,
+ stillCurrent,
+ );
+ for (const row of rows) {
+ if (row.length !== 5 || row.some((value) => typeof value !== "string" || !value)) invalid();
+ references.push({ owner: String(row[0]), table: String(row[1]), name: String(row[2]), status: String(row[3]), validated: String(row[4]) });
+ }
+ }
+ return {
+ user: String(identity[0]![0]),
+ currentSchema: String(identity[0]![1]),
+ database: target.database,
+ databaseName: String(identity[0]![2]),
+ objectId: String(objects[0]![2]),
+ columns: columnDefinitions,
+ ...(indexesOnly ? { indexColumnReadMode } : {}),
+ constraints: definitions,
+ names: nameRows,
+ indexNames: indexNames.map((row) => String(row[0])),
+ indexes: [...new Set(indexDetails.map((row) => `${String(row[0])}\u0000${String(row[1])}`))].sort().map((identity) => {
+ const [owner, name] = identity.split("\u0000");
+ const rows = indexDetails.filter((row) => row[0] === owner && row[1] === name);
+ const first = rows[0]!;
+ return {
+ owner: String(first[0]),
+ name: String(name),
+ tableOwner: String(first[2]),
+ tableName: String(first[3]),
+ indexType: String(first[4]),
+ uniqueness: String(first[5]),
+ status: String(first[6]),
+ partitioned: String(first[7]) === "YES",
+ visibility: String(first[8]),
+ secondary: first[9] === null ? null : String(first[9]),
+ columns: rows.map((row) => (typeof row[12] === "string" && row[12].trim() ? String(row[12]) : String(row[10]))),
+ directions: rows.map((row) => String(row[11])),
+ keyIsExpression: rows.map((row) => typeof row[12] === "string" && row[12].trim() !== ""),
+ includedColumns: [],
+ constraints: indexUsage.filter((use) => use[0] === first[0] && use[1] === name).map((use) => ({ owner: String(use[2]), tableName: String(use[3]), name: String(use[4]) })),
+ };
+ }),
+ references,
+ };
+}
+
+function validateChange(snapshot: OracleConstraintSnapshot, target: OracleConstraintTarget, change: OracleConstraintChange) {
+ if (!change.original && !change.target) invalid();
+ if (change.original) {
+ const actual = snapshot.constraints.find((item) => item.kind === change.original!.kind && item.definition.name === change.original!.definition.name);
+ if (!actual || sortedJson(actual) !== sortedJson(change.original)) invalid("changed");
+ }
+ if (change.target) {
+ const name = change.target.definition.name;
+ if (!name.trim() || (change.target.kind === "check" && !change.target.definition.expression.trim())) invalid();
+ if (change.target.kind === "unique") {
+ const columns = change.target.definition.columns;
+ if (!columns.length || new Set(columns).size !== columns.length || columns.some((column) => !snapshot.columns.some((item) => item.name === column))) invalid();
+ if (target.databaseType === "oceanbase-oracle" && (change.target.definition.state.deferrable || change.target.definition.state.initiallyDeferred || change.target.definition.state.rely)) invalid();
+ }
+ if (snapshot.names.some((item) => item.name === name && change.original?.definition.name !== name)) invalid("changed");
+ }
+}
+
+function sameIdentifierSet(left: string[], right: string[]) {
+ return left.length === right.length && left.every((name) => right.includes(name));
+}
+
+async function constraintRecoveryCandidate(plan: OracleConstraintPlan, snapshot: OracleConstraintSnapshot, stillCurrent: () => boolean): Promise<string | undefined> {
+ const original = plan.change.original;
+ if (
+ !original ||
+ !stillCurrent() ||
+ snapshot.objectId !== plan.snapshot.objectId ||
+ snapshot.user !== plan.snapshot.user ||
+ snapshot.currentSchema !== plan.snapshot.currentSchema ||
+ snapshot.databaseName !== plan.snapshot.databaseName ||
+ JSON.stringify(snapshot.columns) !== JSON.stringify(plan.snapshot.columns)
+ )
+ return undefined;
+ if (snapshot.constraints.some((item) => item.definition.name === original.definition.name)) return undefined;
+ let recovery = JSON.parse(JSON.stringify(original)) as OracleConstraintDefinition;
+ let indexPolicy: OracleConstraintChange["indexPolicy"] = "none";
+ if (recovery.kind === "unique" && plan.target.databaseType === "oracle") {
+ const oldIndex = recovery.definition.index;
+ const actualIndex = snapshot.indexes.find((index) => index.owner === oldIndex.owner && index.name === oldIndex.name);
+ const completeIndexStillMatches =
+ !!oldIndex.name &&
+ !!actualIndex &&
+ actualIndex.tableOwner === plan.target.schema &&
+ actualIndex.tableName === plan.target.tableName &&
+ actualIndex.indexType === oldIndex.indexType &&
+ actualIndex.uniqueness === oldIndex.uniqueness &&
+ actualIndex.status === oldIndex.status &&
+ actualIndex.partitioned === oldIndex.partitioned &&
+ actualIndex.visibility === oldIndex.visibility &&
+ actualIndex.secondary === oldIndex.secondary &&
+ (recovery.definition.state.deferrable ? actualIndex.uniqueness === "NONUNIQUE" : ["UNIQUE", "NONUNIQUE"].includes(actualIndex.uniqueness)) &&
+ sameIdentifierSet(actualIndex.columns, oldIndex.columns) &&
+ actualIndex.directions.join("\0") === oldIndex.directions.join("\0") &&
+ actualIndex.keyIsExpression.join("\0") === oldIndex.keyIsExpression.join("\0") &&
+ actualIndex.includedColumns.length === oldIndex.includedColumns.length &&
+ actualIndex.constraints.length === 0;
+ if (completeIndexStillMatches) {
+ recovery = { ...recovery, definition: { ...recovery.definition, index: { ...oldIndex } } };
+ indexPolicy = "keep";
+ recovery = { ...recovery, definition: { ...recovery.definition, index: { ...recovery.definition.index, sharing: "exclusive" } } };
+ } else {
+ const candidate = await availableUniqueIndexName(plan.target, plan.target.tableName, recovery.definition.columns, [...snapshot.indexNames, ...snapshot.names.map((item) => item.name)], stillCurrent);
+ if (!candidate) return undefined;
+ recovery = { ...recovery, definition: { ...recovery.definition, index: { ...oldIndex, name: "", newName: candidate, newNameAvailable: true } } };
+ }
+ if (!recovery.definition.state.enabled) recovery = { ...recovery, definition: { ...recovery.definition, index: { ...recovery.definition.index, name: "", newName: undefined, newNameAvailable: false } } };
+ } else if (recovery.kind === "unique") {
+ recovery = { ...recovery, definition: { ...recovery.definition, index: { ...recovery.definition.index, name: "", metadataComplete: false } } };
+ }
+ const recoveryOptions = { ...plan.options, oracleConstraintChanges: [{ original: null, target: recovery, indexPolicy }] };
+ const built = await api.buildTableStructureChangeSql(recoveryOptions);
+ if (!stillCurrent() || built.warnings.length || built.statements.length !== 1) return undefined;
+ return built.statements[0];
+}
+
+async function availableUniqueIndexName(target: OracleConstraintTarget, tableName: string, columns: string[], occupied: string[], stillCurrent: () => boolean): Promise<string | undefined> {
+ const taken = [...occupied];
+ for (let attempt = 0; attempt < 64; attempt++) {
+ const candidate = generateUniqueIndexName(tableName, columns, taken, 30) || generateUniqueIndexName("DBX_UQ", [], taken, 30);
+ if (!candidate) return undefined;
+ const [indexes, constraints] = await Promise.all([
+ query(target, `SELECT INDEX_NAME FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(target.schema)} AND INDEX_NAME = ${literal(candidate)}`, stillCurrent),
+ query(target, `SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS WHERE OWNER = ${literal(target.schema)} AND CONSTRAINT_NAME = ${literal(candidate)}`, stillCurrent),
+ ]);
+ if (!indexes.length && !constraints.length) return candidate;
+ taken.push(candidate);
+ }
+ return undefined;
+}
+
+async function prepareUniqueTargetIndex(snapshot: OracleConstraintSnapshot, target: OracleConstraintTarget, change: OracleConstraintChange, stillCurrent: () => boolean): Promise<OracleConstraintChange> {
+ if (change.target?.kind !== "unique") return change;
+ const next = JSON.parse(JSON.stringify(change)) as OracleConstraintChange;
+ const targetDefinition = next.target!.definition as OracleUniqueConstraint;
+ const original = next.original?.kind === "unique" ? next.original.definition : undefined;
+ const oldIndex = original?.index;
+ if (target.databaseType === "oceanbase-oracle") {
+ targetDefinition.index =
+ oldIndex && original
+ ? {
+ ...oldIndex,
+ owner: target.schema,
+ name: targetDefinition.name,
+ tableOwner: target.schema,
+ tableName: target.tableName,
+ columns: [...targetDefinition.columns],
+ directions: targetDefinition.columns.map(() => "ASC"),
+ keyIsExpression: targetDefinition.columns.map(() => false),
+ includedColumns: [],
+ }
+ : {
+ owner: target.schema,
+ name: "",
+ tableOwner: target.schema,
+ tableName: target.tableName,
+ sharing: "exclusive",
+ metadataComplete: false,
+ indexType: "NORMAL",
+ uniqueness: "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: null,
+ columns: [...targetDefinition.columns],
+ directions: targetDefinition.columns.map(() => "ASC"),
+ keyIsExpression: targetDefinition.columns.map(() => false),
+ includedColumns: [],
+ newNameAvailable: false,
+ };
+ return next;
+ }
+ if (!targetDefinition.state.enabled) {
+ targetDefinition.index = {
+ owner: target.schema,
+ name: "",
+ tableOwner: target.schema,
+ tableName: target.tableName,
+ sharing: "exclusive",
+ metadataComplete: true,
+ indexType: "NORMAL",
+ uniqueness: "NONUNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: "N",
+ columns: [...targetDefinition.columns],
+ directions: targetDefinition.columns.map(() => "ASC"),
+ keyIsExpression: targetDefinition.columns.map(() => false),
+ includedColumns: [],
+ newNameAvailable: false,
+ };
+ return next;
+ }
+ if (
+ oldIndex &&
+ !!oldIndex.name &&
+ oldIndex.metadataComplete &&
+ oldIndex.sharing === "exclusive" &&
+ sameIdentifierSet(oldIndex.columns, targetDefinition.columns) &&
+ change.indexPolicy !== "drop" &&
+ (targetDefinition.state.deferrable ? oldIndex.uniqueness === "NONUNIQUE" : ["UNIQUE", "NONUNIQUE"].includes(oldIndex.uniqueness))
+ ) {
+ targetDefinition.index = { ...oldIndex, columns: [...oldIndex.columns], directions: [...oldIndex.directions], keyIsExpression: [...oldIndex.keyIsExpression], includedColumns: [...oldIndex.includedColumns], newNameAvailable: false };
+ return next;
+ }
+ let candidate: string | undefined;
+ if (targetDefinition.index.newName && targetDefinition.index.newNameAvailable) {
+ const frozen = targetDefinition.index.newName;
+ const [indexes, constraints] = await Promise.all([
+ query(target, `SELECT INDEX_NAME FROM SYS.ALL_INDEXES WHERE OWNER = ${literal(target.schema)} AND INDEX_NAME = ${literal(frozen)}`, stillCurrent),
+ query(target, `SELECT CONSTRAINT_NAME FROM SYS.ALL_CONSTRAINTS WHERE OWNER = ${literal(target.schema)} AND CONSTRAINT_NAME = ${literal(frozen)}`, stillCurrent),
+ ]);
+ if (indexes.length || constraints.length) invalid("changed");
+ candidate = frozen;
+ } else {
+ candidate = await availableUniqueIndexName(target, target.tableName, targetDefinition.columns, [...snapshot.indexNames, ...snapshot.names.map((item) => item.name)], stillCurrent);
+ }
+ if (!candidate) invalid("changed");
+ targetDefinition.index = {
+ owner: target.schema,
+ name: "",
+ tableOwner: target.schema,
+ tableName: target.tableName,
+ sharing: "exclusive",
+ metadataComplete: false,
+ indexType: "NORMAL",
+ uniqueness: targetDefinition.state.deferrable || !targetDefinition.state.validated ? "NONUNIQUE" : "UNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: "VISIBLE",
+ secondary: "N",
+ columns: [...targetDefinition.columns],
+ directions: targetDefinition.columns.map(() => "ASC"),
+ keyIsExpression: targetDefinition.columns.map(() => false),
+ includedColumns: [],
+ newNameAvailable: true,
+ newName: candidate,
+ };
+ return next;
+}
+
+function readbackMatches(target: OracleConstraintTarget, actual: OracleConstraintDefinition | undefined, expected: OracleConstraintDefinition): boolean {
+ if (!actual || actual.kind !== expected.kind || actual.definition.name !== expected.definition.name || sortedJson(actual.definition.state) !== sortedJson(expected.definition.state)) return false;
+ if (expected.kind === "check" && actual.kind === "check") return sortedJson(expressionTokens(actual.definition.expression)) === sortedJson(expressionTokens(expected.definition.expression));
+ if (expected.kind !== "unique" || actual.kind !== "unique") return false;
+ if (sortedJson(actual.definition.columns) !== sortedJson(expected.definition.columns)) return false;
+ const index = actual.definition.index;
+ const expectedUniqueness = expected.definition.index.uniqueness;
+ if (!expected.definition.state.enabled && !expected.definition.index.name) return true;
+ if (
+ !index.metadataComplete ||
+ index.owner !== target.schema ||
+ index.tableOwner !== target.schema ||
+ index.tableName !== target.tableName ||
+ index.indexType !== "NORMAL" ||
+ index.uniqueness !== expectedUniqueness ||
+ index.status !== "VALID" ||
+ index.partitioned ||
+ index.visibility !== "VISIBLE" ||
+ index.columns.length !== expected.definition.columns.length ||
+ !sameIdentifierSet(index.columns, expected.definition.columns) ||
+ index.directions.length !== index.columns.length ||
+ index.directions.some((direction) => direction !== "ASC") ||
+ index.keyIsExpression.some(Boolean) ||
+ index.includedColumns.length
+ )
+ return false;
+ if (target.databaseType === "oceanbase-oracle") return !!index.name && index.secondary === null;
+ const expectedIndexName = expected.definition.index.newName || expected.definition.index.name;
+ return !!expectedIndexName && index.name === expectedIndexName;
+}
+
+async function checkCheckRows(target: OracleConstraintTarget, expression: string, stillCurrent: () => boolean) {
+ let rows: unknown[][];
+ try {
+ rows = await query(target, `SELECT 1 FROM ${ident(target.schema)}.${ident(target.tableName)} WHERE NOT (\n${expression}\n) AND ROWNUM <= 1`, stillCurrent);
+ } catch {
+ invalid("unreadableData");
+ }
+ if (rows!.some((row) => row.length !== 1 || (row[0] !== 1 && row[0] !== "1"))) invalid("unreadableData");
+ if (rows!.length) invalid("invalidData");
+}
+
+async function checkUniqueRows(target: OracleConstraintTarget, columns: string[], stillCurrent: () => boolean) {
+ const names = columns.map(ident);
+ const nonNull = names.map((name) => `${name} IS NOT NULL`).join(" OR ");
+ let rows: unknown[][];
+ try {
+ rows = await query(target, `SELECT 1 FROM (SELECT 1 FROM ${ident(target.schema)}.${ident(target.tableName)} WHERE ${nonNull} GROUP BY ${names.join(", ")} HAVING COUNT(*) > 1) WHERE ROWNUM <= 1`, stillCurrent);
+ } catch {
+ invalid("unreadableData");
+ }
+ if (rows!.some((row) => row.length !== 1 || (row[0] !== 1 && row[0] !== "1"))) invalid("unreadableData");
+ if (rows!.length) invalid("invalidData");
+}
+
+/** Builds one checked constraint change and its non-destructive data preflight. */
+export async function prepareOracleConstraintPlan(target: OracleConstraintTarget, options: BuildTableStructureChangeSqlOptions, change: OracleConstraintChange, stillCurrent: () => boolean = () => true): Promise<OracleConstraintPlan> {
+ target = { ...target };
+ change = JSON.parse(JSON.stringify(change)) as OracleConstraintChange;
+ options = { ...JSON.parse(JSON.stringify(options)), databaseType: target.databaseType, schema: target.schema, tableName: target.tableName, foreignKeys: [] };
+ const snapshot = await readOracleConstraintSnapshot(target, change, false, stillCurrent);
+ if (!stillCurrent()) invalid("changed");
+ validateChange(snapshot, target, change);
+ change = await prepareUniqueTargetIndex(snapshot, target, change, stillCurrent);
+ options.oracleConstraintChanges = [change];
+ const generated = await api.buildTableStructureChangeSql(options);
+ if (generated.warnings.length || !generated.statements.length) throw new Error(generated.warnings.join("\n") || "The constraint plan is empty.");
+ const hasDrop = generated.statements.some((statement) => /\bDROP\s+CONSTRAINT\b/i.test(statement));
+ const checkTarget = change.target?.kind === "check" ? change.target.definition : undefined;
+ const checkSource = change.original?.kind === "check" ? change.original.definition : undefined;
+ if (checkTarget && checkTarget.state.validated && checkSource && (checkSource.expression !== checkTarget.expression || hasDrop)) await checkCheckRows(target, checkTarget.expression, stillCurrent);
+ const uniqueTarget = change.target?.kind === "unique" ? change.target.definition : undefined;
+ const uniqueSource = change.original?.kind === "unique" ? change.original.definition : undefined;
+ if (uniqueSource && hasDrop && snapshot.references.length) invalid("changed");
+ if (uniqueTarget && uniqueSource && uniqueTarget.state.validated && hasDrop) {
+ await checkUniqueRows(target, uniqueTarget.columns, stillCurrent);
+ }
+ if (!stillCurrent()) invalid("changed");
+ const dropsConstraint = generated.statements.some((statement) => /\bDROP\s+CONSTRAINT\b/i.test(statement));
+ const notices = target.databaseType === "oceanbase-oracle" && change.original?.kind === "unique" && dropsConstraint ? ["oracleConstraint.pairedIndexImpact"] : [];
+ return { target, options, change, snapshot, snapshotFingerprint: JSON.stringify(snapshot), statements: [...generated.statements], notices };
+}
+
+/** Rechecks the fixed table identity before each DDL, stops on first failure, and never retries. */
+export async function executeOracleConstraintPlan(plan: OracleConstraintPlan, timeoutSecs: number, guards: (() => boolean) | { canStart?: () => boolean; connectionCurrent?: () => boolean }): Promise<OracleConstraintExecutionResult | undefined> {
+ const canStart = typeof guards === "function" ? guards : (guards.canStart ?? (() => true));
+ const connectionCurrent = typeof guards === "function" ? guards : (guards.connectionCurrent ?? (() => true));
+ if (!canStart() || !connectionCurrent()) return undefined;
+ const fresh = await prepareOracleConstraintPlan(plan.target, plan.options, plan.change, connectionCurrent);
+ if (!connectionCurrent()) return undefined;
+ if (!canStart()) return undefined;
+ if (fresh.snapshotFingerprint !== plan.snapshotFingerprint || JSON.stringify(fresh.statements) !== JSON.stringify(plan.statements)) invalid("changed");
+ const steps: OracleConstraintExecutionResult["steps"] = plan.statements.map((sql) => ({ sql, state: "notExecuted" }));
+ for (const step of steps) {
+ if (!canStart() || !connectionCurrent()) break;
+ try {
+ const result = await api.executeQuery(plan.target.connectionId, plan.target.database, step.sql.replace(/;\s*$/, ""), plan.target.schema, undefined, { catalog: plan.target.catalog, timeoutSecs });
+ if (!connectionCurrent()) {
+ step.state = "unknown";
+ step.error = "Connection or target changed during execution; outcome is unknown.";
+ return { steps, readbackError: "Connection or target changed during constraint DDL; readback is unknown." };
+ }
+ if (result.execution_error) {
+ step.state = "rejected";
+ step.error = result.error?.detail || "Constraint statement rejected";
+ try {
+ const actual = await readOracleConstraintSnapshot(plan.target, plan.change, false, connectionCurrent);
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during failure readback; actual state is unknown." };
+ if (actual.objectId !== plan.snapshot.objectId) return { steps, readbackError: "Target table was replaced after a rejected constraint statement." };
+ if (plan.change.target && actual.constraints.some((item) => readbackMatches(plan.target, item, plan.change.target!))) {
+ step.error += " Actual target definition is present after readback.";
+ } else if (plan.change.original && actual.constraints.some((item) => sortedJson(item) === sortedJson(plan.change.original))) {
+ step.error += " Original definition remains after readback.";
+ } else {
+ step.error += " Readback shows a partial or unexpected constraint state; inspect before recovery.";
+ }
+ const recoverySql = await constraintRecoveryCandidate(plan, actual, () => canStart() && connectionCurrent());
+ if (recoverySql) step.error += ` Manual recovery candidate: ${recoverySql}`;
+ } catch (readbackError) {
+ return { steps, readbackError: readbackError instanceof Error ? readbackError.message : String(readbackError) };
+ }
+ break;
+ }
+ step.state = "committed";
+ if (!canStart()) break;
+ } catch (error) {
+ step.state = "unknown";
+ step.error = error instanceof Error ? error.message : String(error);
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during unknown constraint outcome; readback is unknown." };
+ try {
+ const actual = await readOracleConstraintSnapshot(plan.target, plan.change, false, connectionCurrent);
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during unknown-outcome readback; actual state is unknown." };
+ if (actual.objectId !== plan.snapshot.objectId) return { steps, readbackError: "Target table was replaced after an unknown constraint outcome." };
+ if (plan.change.target && actual.constraints.some((item) => readbackMatches(plan.target, item, plan.change.target!))) {
+ step.error += " Actual target definition is present after readback.";
+ } else if (plan.change.original && actual.constraints.some((item) => sortedJson(item) === sortedJson(plan.change.original))) {
+ step.error += " Original definition remains after readback.";
+ } else {
+ step.error += " Readback shows a partial or unexpected constraint state; inspect before recovery.";
+ }
+ const recoverySql = await constraintRecoveryCandidate(plan, actual, () => canStart() && connectionCurrent());
+ if (recoverySql) step.error += ` Manual recovery candidate: ${recoverySql}`;
+ } catch (readbackError) {
+ return { steps, readbackError: readbackError instanceof Error ? readbackError.message : String(readbackError) };
+ }
+ break;
+ }
+ if (!canStart()) break;
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during execution; readback is unknown." };
+ try {
+ const current = await readOracleConstraintSnapshot(plan.target, plan.change, false, connectionCurrent);
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during readback; actual state is unknown." };
+ if (
+ current.user !== plan.snapshot.user ||
+ current.currentSchema !== plan.snapshot.currentSchema ||
+ current.database !== plan.snapshot.database ||
+ current.databaseName !== plan.snapshot.databaseName ||
+ current.objectId !== plan.snapshot.objectId ||
+ JSON.stringify(current.columns) !== JSON.stringify(plan.snapshot.columns)
+ ) {
+ return { steps, readbackError: "Target identity changed during constraint DDL; later statements stopped." };
+ }
+ } catch (error) {
+ return { steps, readbackError: error instanceof Error ? error.message : String(error) };
+ }
+ }
+ const outcome: OracleConstraintExecutionResult = { steps };
+ const oldUnique = plan.change.original?.kind === "unique" ? plan.change.original.definition : undefined;
+ const oldIndexName = oldUnique?.index.name;
+ const plannedIndexName = plan.change.target?.kind === "unique" ? plan.change.target.definition.index.newName || plan.change.target.definition.index.name : undefined;
+ const destructiveIndexChange =
+ !!oldIndexName && (plan.change.target === null || plan.change.target?.kind !== "unique" || plan.change.target.definition.columns.join("\0") !== oldUnique?.columns.join("\0") || plan.change.target.definition.state.deferrable !== oldUnique?.state.deferrable || plan.change.indexPolicy === "drop");
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed during execution; readback is unknown.";
+ return outcome;
+ }
+ if (steps.some((step) => step.state !== "notExecuted")) {
+ try {
+ const readback = await readOracleConstraintSnapshot(plan.target, plan.change, false, connectionCurrent);
+ if (!connectionCurrent()) outcome.readbackError = "Connection or target changed during readback; result is unknown.";
+ else if (readback.objectId !== plan.snapshot.objectId) outcome.readbackError = "Target table was replaced during constraint DDL.";
+ else if (steps.every((step) => step.state === "committed") && plan.change.target && !readback.constraints.some((item) => readbackMatches(plan.target, item, plan.change.target!))) outcome.readbackError = "Constraint readback differs from the submitted definition.";
+ else if (!plan.change.target && readback.constraints.some((item) => item.definition.name === plan.change.original?.definition.name)) outcome.readbackError = "Deleted constraint is still present after readback.";
+ else if (oldIndexName && plan.change.indexPolicy === "keep" && !readback.indexNames.includes(oldIndexName)) outcome.readbackError = "The selected KEEP INDEX supporting index is missing after readback.";
+ else if (oldIndexName && destructiveIndexChange && plan.target.databaseType === "oracle" && plan.change.indexPolicy !== "keep" && readback.indexNames.includes(oldIndexName) && plannedIndexName !== oldIndexName)
+ outcome.readbackError = "The replaced or dropped supporting index remains after readback.";
+ else if (plannedIndexName && plan.change.target?.kind === "unique" && plan.change.target.definition.state.enabled && plan.change.target.definition.index.newName && !readback.indexNames.includes(plannedIndexName))
+ outcome.readbackError = "The planned supporting index is missing after readback.";
+ if (oldUnique && !readback.constraints.some((item) => item.kind === "unique" && item.definition.name === oldUnique.name) && plan.change.target?.kind === "unique" && destructiveIndexChange && canStart())
+ outcome.recoverySql = await constraintRecoveryCandidate(plan, readback, () => canStart() && connectionCurrent());
+ } catch (error) {
+ outcome.readbackError = error instanceof Error ? error.message : String(error);
+ }
+ }
+ return outcome;
+}
diff --git a/apps/desktop/src/lib/database/oracleForeignKeys.ts b/apps/desktop/src/lib/database/oracleForeignKeys.ts
new file mode 100644
index 0000000000..1e657de805
--- /dev/null
+++ b/apps/desktop/src/lib/database/oracleForeignKeys.ts
@@ -0,0 +1,803 @@
+import * as api from "@/lib/backend/api";
+import type { BuildTableStructureChangeSqlOptions, OracleForeignKeyChange, OracleForeignKeyDefinition, OracleForeignKeyState, TablePartitionDefinition } from "@/lib/table/tableStructureEditorSql";
+import { foldCreatedTableName } from "@/lib/table/tableStructureEditorState";
+
+export interface OracleForeignKeyTarget {
+ connectionId: string;
+ database: string;
+ schema: string;
+ tableName: string;
+ catalog?: string;
+ databaseType: "oracle" | "oceanbase-oracle";
+}
+
+export class OracleForeignKeyMetadataError extends Error {
+ constructor() {
+ super("Foreign key metadata is incomplete, unsupported, or inconsistent. Refresh the table definition.");
+ }
+}
+
+function invalid(): never {
+ throw new OracleForeignKeyMetadataError();
+}
+const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
+
+/** Parses database-emitted REF_CONSTRAINT DDL. The returned text is never executed. */
+export function parseOracleForeignKeyDdl(ddl: string, target: OracleForeignKeyTarget, name: string, refOwner: string, deleteRule: string, state: OracleForeignKeyState): OracleForeignKeyDefinition {
+ let position = 0;
+ const whitespace = () => {
+ while (/\s/.test(ddl[position] ?? "") && position < ddl.length) position++;
+ };
+ const symbol = (value: string, required = true): boolean => {
+ whitespace();
+ if (ddl[position] !== value) {
+ if (required) invalid();
+ return false;
+ }
+ position++;
+ return true;
+ };
+ const word = (value: string, required = true): boolean => {
+ whitespace();
+ const end = position + value.length;
+ if (ddl.slice(position, end).toUpperCase() !== value || /[\w$#]/.test(ddl[end] ?? "")) {
+ if (required) invalid();
+ return false;
+ }
+ position = end;
+ return true;
+ };
+ const identifier = (): string => {
+ symbol('"');
+ let value = "";
+ while (position < ddl.length) {
+ const character = ddl[position++]!;
+ if (character !== '"') {
+ value += character;
+ continue;
+ }
+ if (ddl[position] === '"') {
+ position++;
+ value += '"';
+ continue;
+ }
+ return value || invalid();
+ }
+ return invalid();
+ };
+ const columns = (): string[] => {
+ symbol("(");
+ const values = [identifier()];
+ while (symbol(",", false)) values.push(identifier());
+ symbol(")");
+ if (new Set(values).size !== values.length) invalid();
+ return values;
+ };
+ word("ALTER");
+ word("TABLE");
+ const sourceOwner = identifier();
+ symbol(".");
+ const sourceTable = identifier();
+ word("ADD");
+ word("CONSTRAINT");
+ const constraint = identifier();
+ word("FOREIGN");
+ word("KEY");
+ const local = columns();
+ word("REFERENCES");
+ const refSchema = identifier();
+ symbol(".");
+ const refTable = identifier();
+ const references = columns();
+ let onDelete: OracleForeignKeyDefinition["onDelete"] = "NO ACTION";
+ if (word("ON", false)) {
+ word("DELETE");
+ if (word("CASCADE", false)) onDelete = "CASCADE";
+ else {
+ word("SET");
+ word("NULL");
+ onDelete = "SET NULL";
+ }
+ }
+ const observed: Partial<OracleForeignKeyState> = {};
+ const setState = (key: keyof OracleForeignKeyState, value: boolean) => {
+ if (key in observed) invalid();
+ observed[key] = value;
+ };
+ while (true) {
+ whitespace();
+ if (position === ddl.length) break;
+ if (symbol(";", false)) {
+ whitespace();
+ if (position !== ddl.length) invalid();
+ break;
+ }
+ if (word("ENABLE", false)) setState("enabled", true);
+ else if (word("DISABLE", false)) setState("enabled", false);
+ else if (word("VALIDATE", false)) setState("validated", true);
+ else if (word("NOVALIDATE", false)) setState("validated", false);
+ else if (word("RELY", false)) setState("rely", true);
+ else if (word("NORELY", false)) setState("rely", false);
+ else if (word("DEFERRABLE", false)) setState("deferrable", true);
+ else if (word("NOT", false)) {
+ word("DEFERRABLE");
+ setState("deferrable", false);
+ } else if (word("INITIALLY", false)) {
+ if (word("DEFERRED", false)) setState("initiallyDeferred", true);
+ else {
+ word("IMMEDIATE");
+ setState("initiallyDeferred", false);
+ }
+ } else invalid();
+ }
+ for (const key of Object.keys(observed) as Array<keyof OracleForeignKeyState>) {
+ if (key === "rely" && state.validated) continue;
+ if (observed[key] !== state[key]) invalid();
+ }
+ if (sourceOwner !== target.schema || sourceTable !== target.tableName || constraint !== name || refSchema !== refOwner || onDelete !== deleteRule || local.length !== references.length) invalid();
+ return { name, columns: local, refSchema, refTable, refColumns: references, onDelete, state: { ...state } };
+}
+
+async function query(target: OracleForeignKeyTarget, sql: string, stillCurrent: () => boolean = () => true): Promise<unknown[][]> {
+ if (!stillCurrent()) invalid();
+ const result = await api.executeQuery(target.connectionId, target.database, sql, target.schema, undefined, { catalog: target.catalog, maxRows: 10001 });
+ if (!stillCurrent()) invalid();
+ if (result.execution_error || result.truncated || result.has_more || result.rows.length >= 10001) invalid();
+ return result.rows;
+}
+
+async function sourceConstraintView(target: OracleForeignKeyTarget, stillCurrent: () => boolean = () => true) {
+ if (target.databaseType === "oceanbase-oracle") {
+ const users = await query(target, "SELECT USER FROM DUAL", stillCurrent);
+ if (users.length !== 1 || users[0]?.length !== 1 || typeof users[0][0] !== "string" || !users[0][0]) invalid();
+ if (users[0][0] === target.schema) return { view: "SYS.USER_CONSTRAINTS", owner: "" };
+ }
+ return { view: "SYS.ALL_CONSTRAINTS", owner: `OWNER = ${literal(target.schema)}` };
+}
+
+export async function readOracleForeignKeyConstraintNames(target: OracleForeignKeyTarget, selectedNames?: string[], stillCurrent: () => boolean = () => true): Promise<Array<{ name: string; table: string }>> {
+ target = { ...target };
+ if (selectedNames && !selectedNames.length) return [];
+ const source = await sourceConstraintView(target, stillCurrent);
+ const conditions = [source.owner, selectedNames ? `CONSTRAINT_NAME IN (${selectedNames.map(literal).join(", ")})` : ""].filter(Boolean);
+ const rows = await query(target, `SELECT CONSTRAINT_NAME, TABLE_NAME FROM ${source.view}${conditions.length ? ` WHERE ${conditions.join(" AND ")}` : ""} ORDER BY CONSTRAINT_NAME`, stillCurrent);
+ const names = new Set<string>();
+ return rows.map((row) => {
+ if (row.length !== 2 || typeof row[0] !== "string" || !row[0] || typeof row[1] !== "string" || !row[1] || names.has(row[0])) invalid();
+ names.add(row[0]);
+ return { name: row[0], table: row[1] };
+ });
+}
+
+async function readOracleForeignKeyMetadata(target: OracleForeignKeyTarget, selectedNames?: string[], stillCurrent: () => boolean = () => true) {
+ target = { ...target };
+ if (selectedNames && !selectedNames.length) return { definitions: [], referenceKeys: [] };
+ const tables = await query(target, `SELECT OWNER, TABLE_NAME FROM SYS.ALL_TABLES WHERE OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`, stillCurrent);
+ if (tables.length !== 1 || tables[0]?.length !== 2 || tables[0][0] !== target.schema || tables[0][1] !== target.tableName) invalid();
+ const source = await sourceConstraintView(target, stillCurrent);
+ const rows = await query(
+ target,
+ `SELECT CONSTRAINT_NAME, STATUS, VALIDATED, DEFERRABLE, DEFERRED, RELY, R_OWNER, R_CONSTRAINT_NAME, DELETE_RULE FROM ${source.view} WHERE ${source.owner ? `${source.owner} AND ` : ""}TABLE_NAME = ${literal(target.tableName)} AND CONSTRAINT_TYPE = 'R'${selectedNames ? ` AND CONSTRAINT_NAME IN (${selectedNames.map(literal).join(", ")})` : ""} ORDER BY CONSTRAINT_NAME`,
+ stillCurrent,
+ );
+ const names = new Set<string>();
+ const definitions: OracleForeignKeyDefinition[] = [];
+ const referenceKeys: Array<{ name: string; owner: string; constraint: string }> = [];
+ for (const row of rows) {
+ const [name, enabled, validated, deferrable, initially, rely, refOwner, refConstraint, action] = row;
+ if (
+ row.length !== 9 ||
+ typeof name !== "string" ||
+ !name ||
+ names.has(name) ||
+ typeof refOwner !== "string" ||
+ !refOwner ||
+ typeof refConstraint !== "string" ||
+ !refConstraint ||
+ !["ENABLED", "DISABLED"].includes(String(enabled)) ||
+ !["VALIDATED", "NOT VALIDATED"].includes(String(validated)) ||
+ !["DEFERRABLE", "NOT DEFERRABLE"].includes(String(deferrable)) ||
+ !["IMMEDIATE", "DEFERRED"].includes(String(initially)) ||
+ (rely !== null && rely !== "RELY") ||
+ !["NO ACTION", "CASCADE", "SET NULL"].includes(String(action))
+ )
+ invalid();
+ const state: OracleForeignKeyState = { enabled: enabled === "ENABLED", validated: validated === "VALIDATED", deferrable: deferrable === "DEFERRABLE", initiallyDeferred: initially === "DEFERRED", rely: validated !== "VALIDATED" && rely === "RELY" };
+ if ((!state.deferrable && state.initiallyDeferred) || (target.databaseType === "oceanbase-oracle" && state.deferrable)) invalid();
+ names.add(name);
+ const ddlRows = await query(target, `SELECT DBMS_METADATA.GET_DDL('REF_CONSTRAINT', ${literal(name)}, ${literal(target.schema)}) FROM DUAL`, stillCurrent);
+ if (ddlRows.length !== 1 || ddlRows[0]?.length !== 1 || typeof ddlRows[0][0] !== "string") invalid();
+ definitions.push(parseOracleForeignKeyDdl(ddlRows[0][0], target, name, refOwner, String(action), state));
+ referenceKeys.push({ name, owner: refOwner, constraint: refConstraint });
+ }
+ return { definitions, referenceKeys };
+}
+
+export async function readOracleForeignKeyDefinitions(target: OracleForeignKeyTarget, stillCurrent: () => boolean = () => true): Promise<OracleForeignKeyDefinition[]> {
+ return (await readOracleForeignKeyMetadata(target, undefined, stillCurrent)).definitions;
+}
+
+export interface OracleForeignKeySourceSnapshot {
+ user: string;
+ currentSchema: string;
+ objectId: string;
+ columns: Array<{ name: string; dataType: string; length: string | null; precision: string | null; scale: string | null; nullable: boolean }>;
+ definitions: OracleForeignKeyDefinition[];
+ referenceKeys: Array<{ name: string; owner: string; constraint: string }>;
+ names: Array<{ name: string; table: string }>;
+}
+
+/** Captures only metadata needed for a foreign key write, without issuing DDL. */
+export async function readOracleForeignKeySourceSnapshot(target: OracleForeignKeyTarget, changes?: OracleForeignKeyChange[], stillCurrent: () => boolean = () => true): Promise<OracleForeignKeySourceSnapshot> {
+ target = { ...target };
+ changes = changes ? (JSON.parse(JSON.stringify(changes)) as OracleForeignKeyChange[]) : undefined;
+ const originalNames = changes ? changes.flatMap((change) => (change.original ? [change.original.name] : [])) : undefined;
+ const selectedNames = changes ? [...new Set(changes.flatMap((change) => [change.original?.name, change.target?.name].filter((name): name is string => name !== undefined)))] : undefined;
+ const selectedColumns = changes ? new Set(changes.flatMap((change) => [...(change.original?.columns ?? []), ...(change.target?.columns ?? [])])) : undefined;
+ const where = `OWNER = ${literal(target.schema)} AND TABLE_NAME = ${literal(target.tableName)}`;
+ const [identity, objects, columns, metadata, names] = await Promise.all([
+ query(target, "SELECT USER, SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL", stillCurrent),
+ query(target, `SELECT OWNER, OBJECT_NAME, OBJECT_ID FROM SYS.ALL_OBJECTS WHERE OWNER = ${literal(target.schema)} AND OBJECT_NAME = ${literal(target.tableName)} AND OBJECT_TYPE = 'TABLE'`, stillCurrent),
+ query(target, `SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE FROM SYS.ALL_TAB_COLS WHERE ${where} ORDER BY COLUMN_ID`, stillCurrent),
+ readOracleForeignKeyMetadata(target, originalNames, stillCurrent),
+ readOracleForeignKeyConstraintNames(target, selectedNames, stillCurrent),
+ ]);
+ if (identity.length !== 1 || identity[0]?.length !== 2 || typeof identity[0][0] !== "string" || !identity[0][0] || typeof identity[0][1] !== "string" || !identity[0][1]) invalid();
+ if (objects.length !== 1 || objects[0]?.length !== 3 || objects[0][0] !== target.schema || objects[0][1] !== target.tableName || (typeof objects[0][2] !== "string" && typeof objects[0][2] !== "number") || !/^[1-9]\d*$/.test(String(objects[0][2]))) invalid();
+ if (typeof objects[0][2] === "number" && !Number.isSafeInteger(objects[0][2])) invalid();
+ if (!columns.length) invalid();
+ const columnNames = new Set<string>();
+ const numeric = (value: unknown): string | null => {
+ if (value === null) return null;
+ if ((typeof value !== "string" && typeof value !== "number") || !/^-?\d+$/.test(String(value))) invalid();
+ return String(value);
+ };
+ const columnDefinitions = columns.map((row) => {
+ if (row.length !== 6 || typeof row[0] !== "string" || !row[0] || columnNames.has(row[0]) || typeof row[1] !== "string" || !row[1] || !["Y", "N"].includes(String(row[5]))) invalid();
+ columnNames.add(row[0]);
+ return { name: row[0], dataType: row[1], length: numeric(row[2]), precision: numeric(row[3]), scale: numeric(row[4]), nullable: row[5] === "Y" };
+ });
+ return { user: identity[0][0], currentSchema: identity[0][1], objectId: String(objects[0][2]), columns: selectedColumns ? columnDefinitions.filter((column) => selectedColumns.has(column.name)) : columnDefinitions, definitions: metadata.definitions, referenceKeys: metadata.referenceKeys, names };
+}
+
+export function validateOracleForeignKeySourceChanges(snapshot: OracleForeignKeySourceSnapshot, target: OracleForeignKeyTarget, changes: OracleForeignKeyChange[]): void {
+ const definitionIdentity = (key: OracleForeignKeyDefinition) => JSON.stringify([key.name, key.columns, key.refSchema, key.refTable, key.refColumns, key.onDelete, key.state.enabled, key.state.validated, key.state.deferrable, key.state.initiallyDeferred, key.state.rely]);
+ const originalNames = new Set<string>();
+ const targetNames = new Set<string>();
+ for (const change of changes) {
+ if (!change.original && !change.target) invalid();
+ if (change.original) {
+ if (originalNames.has(change.original.name)) invalid();
+ originalNames.add(change.original.name);
+ const existing = snapshot.definitions.find((key) => key.name === change.original!.name);
+ if (!existing || definitionIdentity(existing) !== definitionIdentity(change.original)) invalid();
+ }
+ const definition = change.target;
+ if (!definition) continue;
+ if (
+ !definition.name ||
+ targetNames.has(definition.name) ||
+ !definition.refSchema ||
+ !definition.refTable ||
+ !definition.columns.length ||
+ definition.columns.length !== definition.refColumns.length ||
+ definition.columns.some((name) => !snapshot.columns.some((column) => column.name === name)) ||
+ definition.refColumns.some((name) => !name)
+ )
+ invalid();
+ targetNames.add(definition.name);
+ if (new Set(definition.columns).size !== definition.columns.length || new Set(definition.refColumns).size !== definition.refColumns.length) invalid();
+ if (
+ !["NO ACTION", "CASCADE", "SET NULL"].includes(definition.onDelete) ||
+ (!definition.state.deferrable && definition.state.initiallyDeferred) ||
+ (definition.state.validated && definition.state.rely) ||
+ (target.databaseType === "oceanbase-oracle" && (definition.state.deferrable || definition.state.initiallyDeferred))
+ )
+ invalid();
+ const occupied = snapshot.names.find((name) => name.name === definition.name);
+ if (occupied && (occupied.table !== target.tableName || change.original?.name !== definition.name)) invalid();
+ }
+}
+
+export interface OracleForeignKeyReferenceSnapshot {
+ owner: string;
+ table: string;
+ objectId: string | null;
+ keys: Array<{ name: string; kind: string; enabled: boolean; validated: boolean; deferrable: boolean; columns: string[] }> | null;
+ columns: Array<{ name: string; dataType: string }> | null;
+ references: "present" | "missing" | "unknown";
+}
+
+/** Missing dictionary visibility is recorded as unknown, never as a missing parent. */
+export async function readOracleForeignKeyReferenceSnapshot(target: OracleForeignKeyTarget, user: string, definition: OracleForeignKeyDefinition, stillCurrent: () => boolean = () => true): Promise<OracleForeignKeyReferenceSnapshot> {
+ target = { ...target };
+ definition = JSON.parse(JSON.stringify(definition)) as OracleForeignKeyDefinition;
+ const owner = literal(definition.refSchema),
+ table = literal(definition.refTable);
+ const sameOwner = definition.refSchema === user;
+ const grantee = `(GRANTEE = ${literal(user)} OR GRANTEE = 'PUBLIC')`;
+ const requests = await Promise.allSettled([
+ query(target, `SELECT OWNER, OBJECT_NAME, OBJECT_ID FROM SYS.ALL_OBJECTS WHERE OWNER = ${owner} AND OBJECT_NAME = ${table} AND OBJECT_TYPE = 'TABLE'`, stillCurrent),
+ query(
+ target,
+ `SELECT c.CONSTRAINT_NAME, c.CONSTRAINT_TYPE, c.STATUS, c.VALIDATED, c.DEFERRABLE, cc.COLUMN_NAME, cc.POSITION FROM SYS.ALL_CONSTRAINTS c JOIN SYS.ALL_CONS_COLUMNS cc ON cc.OWNER = c.OWNER AND cc.CONSTRAINT_NAME = c.CONSTRAINT_NAME WHERE c.OWNER = ${owner} AND c.TABLE_NAME = ${table} AND c.CONSTRAINT_TYPE IN ('P', 'U') ORDER BY c.CONSTRAINT_NAME, cc.POSITION`,
+ stillCurrent,
+ ),
+ query(target, `SELECT COLUMN_NAME, DATA_TYPE FROM SYS.ALL_TAB_COLS WHERE OWNER = ${owner} AND TABLE_NAME = ${table} ORDER BY COLUMN_ID`, stillCurrent),
+ sameOwner ? Promise.resolve([]) : query(target, `SELECT PRIVILEGE FROM SYS.ALL_TAB_PRIVS WHERE TABLE_SCHEMA = ${owner} AND TABLE_NAME = ${table} AND ${grantee} ORDER BY PRIVILEGE`, stillCurrent),
+ sameOwner ? Promise.resolve([]) : query(target, `SELECT COLUMN_NAME, PRIVILEGE FROM SYS.ALL_COL_PRIVS WHERE OWNER = ${owner} AND TABLE_NAME = ${table} AND ${grantee} ORDER BY COLUMN_NAME, PRIVILEGE`, stillCurrent),
+ sameOwner ? Promise.resolve([]) : query(target, "SELECT PRIVILEGE FROM SESSION_PRIVS ORDER BY PRIVILEGE", stillCurrent),
+ ]);
+ const rows = (index: number) => (requests[index]?.status === "fulfilled" ? requests[index].value : null);
+ const objects = rows(0);
+ let objectId: string | null = null;
+ if (
+ objects?.length === 1 &&
+ objects[0]?.length === 3 &&
+ objects[0][0] === definition.refSchema &&
+ objects[0][1] === definition.refTable &&
+ (typeof objects[0][2] === "string" || typeof objects[0][2] === "number") &&
+ /^[1-9]\d*$/.test(String(objects[0][2])) &&
+ (typeof objects[0][2] !== "number" || Number.isSafeInteger(objects[0][2]))
+ )
+ objectId = String(objects[0][2]);
+ const keyRows = rows(1);
+ let keys: OracleForeignKeyReferenceSnapshot["keys"] = null;
+ if (keyRows?.length) {
+ const groups = new Map<string, NonNullable<OracleForeignKeyReferenceSnapshot["keys"]>[number]>();
+ let valid = true;
+ for (const row of keyRows) {
+ if (
+ row.length !== 7 ||
+ typeof row[0] !== "string" ||
+ !row[0] ||
+ !["P", "U"].includes(String(row[1])) ||
+ !["ENABLED", "DISABLED"].includes(String(row[2])) ||
+ !["VALIDATED", "NOT VALIDATED"].includes(String(row[3])) ||
+ !["DEFERRABLE", "NOT DEFERRABLE"].includes(String(row[4])) ||
+ typeof row[5] !== "string" ||
+ !row[5]
+ ) {
+ valid = false;
+ break;
+ }
+ const key = groups.get(row[0]) ?? { name: row[0], kind: String(row[1]), enabled: row[2] === "ENABLED", validated: row[3] === "VALIDATED", deferrable: row[4] === "DEFERRABLE", columns: [] };
+ if (key.kind !== row[1] || key.enabled !== (row[2] === "ENABLED") || key.validated !== (row[3] === "VALIDATED") || key.deferrable !== (row[4] === "DEFERRABLE") || key.columns.includes(row[5]) || Number(row[6]) !== key.columns.length + 1) {
+ valid = false;
+ break;
+ }
+ key.columns.push(row[5]);
+ groups.set(key.name, key);
+ }
+ if (valid) keys = [...groups.values()];
+ }
+ const columnRows = rows(2);
+ let columns: OracleForeignKeyReferenceSnapshot["columns"] = null;
+ if (columnRows?.length && columnRows.every((row) => row.length === 2 && typeof row[0] === "string" && !!row[0] && typeof row[1] === "string" && !!row[1]) && new Set(columnRows.map((row) => row[0])).size === columnRows.length)
+ columns = columnRows.map((row) => ({ name: String(row[0]), dataType: String(row[1]) }));
+ const tableGrants = rows(3),
+ columnGrants = rows(4),
+ systemGrants = rows(5);
+ const tableReadable = tableGrants !== null && tableGrants.every((row) => row.length === 1 && typeof row[0] === "string");
+ const columnsReadable = columnGrants !== null && columnGrants.every((row) => row.length === 2 && typeof row[0] === "string" && typeof row[1] === "string");
+ const systemReadable = systemGrants !== null && systemGrants.every((row) => row.length === 1 && typeof row[0] === "string");
+ const referencesPresent =
+ sameOwner ||
+ (tableReadable && tableGrants.some((row) => row[0] === "REFERENCES")) ||
+ (columnsReadable && definition.refColumns.every((name) => columnGrants.some((row) => row[0] === name && row[1] === "REFERENCES"))) ||
+ (systemReadable && systemGrants.some((row) => row[0] === "REFERENCES ANY TABLE"));
+ return { owner: definition.refSchema, table: definition.refTable, objectId, keys, columns, references: referencesPresent ? "present" : tableReadable && columnsReadable && systemReadable ? "missing" : "unknown" };
+}
+
+export function parseOracleCanonicalType(raw: string, databaseType: "oracle" | "oceanbase-oracle" = "oracle"): string | null {
+ const text = raw.trim().toUpperCase();
+ // 1. NUMBER / FLOAT
+ if (/^NUMBER(?:\s*\(\s*\d+\s*(?:,\s*-?\d+\s*)?\))?$/.test(text)) return "NUMBER";
+ if (/^FLOAT(?:\s*\(\s*\d+\s*\))?$/.test(text)) {
+ return databaseType === "oracle" ? "NUMBER" : "FLOAT";
+ }
+ if (/^BINARY_FLOAT$/.test(text)) return "BINARY_FLOAT";
+ if (/^BINARY_DOUBLE$/.test(text)) return "BINARY_DOUBLE";
+ // 2. Character types
+ if (/^VARCHAR2(?:\s*\(\s*\d+\s*(?:BYTE|CHAR)?\s*\))?$/.test(text)) return "VARCHAR2";
+ if (/^VARCHAR(?:\s*\(\s*\d+\s*(?:BYTE|CHAR)?\s*\))?$/.test(text)) {
+ return databaseType === "oracle" ? "VARCHAR2" : null;
+ }
+ if (/^CHAR(?:\s*\(\s*\d+\s*(?:BYTE|CHAR)?\s*\))?$/.test(text)) return "CHAR";
+ if (/^NCHAR(?:\s*\(\s*\d+\s*\))?$/.test(text)) return "NCHAR";
+ if (/^NVARCHAR2(?:\s*\(\s*\d+\s*\))?$/.test(text)) return "NVARCHAR2";
+ // 3. DATE
+ if (/^DATE$/.test(text)) return "DATE";
+ // 4. RAW
+ if (/^RAW(?:\s*\(\s*\d+\s*\))?$/.test(text)) return "RAW";
+ // 5. TIMESTAMP
+ if (/^TIMESTAMP(?:\s*\(\s*\d+\s*\))?$/.test(text)) return "TIMESTAMP";
+ if (/^TIMESTAMP(?:\s*\(\s*\d+\s*\))?\s+WITH\s+LOCAL\s+TIME\s+ZONE$/.test(text)) return "TIMESTAMP_WITH_LOCAL_TIME_ZONE";
+
+ return null;
+}
+
+export function compareOracleForeignKeyColumnTypes(localRaw: string, parentRaw: string, databaseType: "oracle" | "oceanbase-oracle" = "oracle"): "compatible" | "incompatible" | "unknown" {
+ const localCanonical = parseOracleCanonicalType(localRaw, databaseType);
+ const parentCanonical = parseOracleCanonicalType(parentRaw, databaseType);
+ if (!localCanonical || !parentCanonical) return "unknown";
+ return localCanonical === parentCanonical ? "compatible" : "incompatible";
+}
+
+export function validateOracleForeignKeyReference(snapshot: OracleForeignKeyReferenceSnapshot, source: OracleForeignKeySourceSnapshot, definition: OracleForeignKeyDefinition, destructiveReplacement: boolean, databaseType: "oracle" | "oceanbase-oracle" = "oracle"): void {
+ if (snapshot.owner !== definition.refSchema || snapshot.table !== definition.refTable) invalid();
+ if (destructiveReplacement && (!snapshot.objectId || !snapshot.keys || !snapshot.columns || snapshot.references !== "present")) invalid();
+ if (snapshot.columns && definition.refColumns.some((name) => !snapshot.columns!.some((column) => column.name === name))) invalid();
+ if (snapshot.keys) {
+ const matching = snapshot.keys.filter((key) => key.columns.length === definition.refColumns.length && key.columns.every((name) => definition.refColumns.includes(name)));
+ if (!matching.length || (definition.state.enabled && !matching.some((key) => key.enabled))) invalid();
+ }
+ for (let index = 0; index < definition.columns.length; index++) {
+ const local = source.columns.find((column) => column.name === definition.columns[index])?.dataType;
+ const parent = snapshot.columns?.find((column) => column.name === definition.refColumns[index])?.dataType;
+ if (local && parent) {
+ const compatibility = compareOracleForeignKeyColumnTypes(local, parent, databaseType);
+ if (compatibility === "incompatible") invalid();
+ if (destructiveReplacement && compatibility === "unknown") invalid();
+ }
+ }
+}
+
+export class OracleForeignKeyPreflightError extends Error {
+ constructor(readonly reason: "referenceDataInvalid" | "referenceDataUnreadable") {
+ super(reason === "referenceDataInvalid" ? "Existing child rows do not match the referenced key." : "Existing rows could not be verified before replacing the foreign key.");
+ }
+}
+
+export async function checkOracleForeignKeyData(target: OracleForeignKeyTarget, change: OracleForeignKeyChange, destructiveReplacement: boolean, stillCurrent: () => boolean = () => true): Promise<{ checked: boolean }> {
+ target = { ...target };
+ change = JSON.parse(JSON.stringify(change)) as OracleForeignKeyChange;
+ const key = change.target;
+ if (!key || !key.state.validated || (change.original?.state.validated && !destructiveReplacement && (change.original.state.enabled || !key.state.enabled))) return { checked: false };
+ const ident = (name: string) => `"${name.replace(/"/g, '""')}"`;
+ const child = `${ident(target.schema)}.${ident(target.tableName)}`;
+ const parent = `${ident(key.refSchema)}.${ident(key.refTable)}`;
+ const nonnull = key.columns.map((name) => `fk_child.${ident(name)} IS NOT NULL`).join(" AND ");
+ const pairs = key.columns.map((name, index) => `fk_parent.${ident(key.refColumns[index]!)} = fk_child.${ident(name)}`).join(" AND ");
+ let rows: unknown[][];
+ try {
+ rows = await query(target, `SELECT 1 FROM ${child} fk_child WHERE ${nonnull} AND NOT EXISTS (SELECT 1 FROM ${parent} fk_parent WHERE ${pairs}) AND ROWNUM <= 1`, stillCurrent);
+ } catch {
+ if (destructiveReplacement) throw new OracleForeignKeyPreflightError("referenceDataUnreadable");
+ return { checked: false };
+ }
+ if (rows.length > 1 || rows.some((row) => row.length !== 1 || (row[0] !== 1 && row[0] !== "1"))) {
+ if (destructiveReplacement) throw new OracleForeignKeyPreflightError("referenceDataUnreadable");
+ return { checked: false };
+ }
+ if (rows.length) throw new OracleForeignKeyPreflightError("referenceDataInvalid");
+ return { checked: true };
+}
+
+export interface OracleForeignKeyPlan {
+ target: OracleForeignKeyTarget;
+ options: BuildTableStructureChangeSqlOptions;
+ changes: OracleForeignKeyChange[];
+ groups: Array<{ change: OracleForeignKeyChange; statements: string[]; replacement: boolean }>;
+ source: OracleForeignKeySourceSnapshot;
+ references: Array<{ columns: string[]; snapshot: OracleForeignKeyReferenceSnapshot }>;
+ snapshot: string;
+ statements: string[];
+ unverified: Array<"referenceDefinition" | "referencesPermission" | "existingData">;
+}
+
+export interface OracleForeignKeyExecutionResult {
+ steps: Array<{ sql: string; state: "committed" | "rejected" | "unknown" | "notExecuted"; error?: string }>;
+ readbackError?: string;
+ recoverySql?: string[];
+}
+
+export interface OracleForeignKeyCreatePlan {
+ target: OracleForeignKeyTarget;
+ options: BuildTableStructureChangeSqlOptions;
+ partitioning?: TablePartitionDefinition;
+ changes: OracleForeignKeyChange[];
+ statements: string[];
+ references: OracleForeignKeyReferenceSnapshot[];
+ session: { user: string; currentSchema: string };
+ snapshot: string;
+}
+
+export interface OracleForeignKeyCreateExecutionResult {
+ steps: Array<{ sql: string; state: "committed" | "rejected" | "unknown" | "notExecuted"; error?: string }>;
+ tableExists?: boolean;
+ readbackDefinitions?: OracleForeignKeyDefinition[];
+ readbackError?: string;
+}
+
+/** Preflights every new-table reference before any CREATE statement can run. */
+export async function prepareOracleForeignKeyCreatePlan(target: OracleForeignKeyTarget, options: BuildTableStructureChangeSqlOptions, changes: OracleForeignKeyChange[], partitioning?: TablePartitionDefinition, stillCurrent: () => boolean = () => true): Promise<OracleForeignKeyCreatePlan> {
+ target = { ...target };
+ changes = JSON.parse(JSON.stringify(changes)) as OracleForeignKeyChange[];
+ options = { ...JSON.parse(JSON.stringify(options)), databaseType: target.databaseType, schema: target.schema, tableName: target.tableName, foreignKeys: [], oracleForeignKeyChanges: changes };
+ if (changes.some((change) => change.original || !change.target)) invalid();
+ const generated = partitioning ? await api.buildCreatePartitionedTableSql({ options, partitioning }) : await api.buildCreateTableSql(options);
+ if (generated.warnings.length || !generated.statements.length) throw new Error(generated.warnings.join("\n") || "The create plan is empty.");
+ if (!/^CREATE\s+TABLE\b/i.test(generated.statements[0]!.trimStart())) invalid();
+ if (generated.statements.filter((statement) => statement.includes("FOREIGN KEY")).length !== changes.length) invalid();
+ const identity = await query(target, "SELECT USER, SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL", stillCurrent);
+ if (identity.length !== 1 || identity[0]?.length !== 2 || identity[0].some((value) => typeof value !== "string" || !value)) invalid();
+ const session = { user: identity[0]![0] as string, currentSchema: identity[0]![1] as string };
+ const source = {
+ user: session.user,
+ currentSchema: session.currentSchema,
+ objectId: "new-table",
+ columns: options.columns.filter((column) => !column.markedForDrop).map((column) => ({ name: column.name, dataType: column.dataType, length: null, precision: null, scale: null, nullable: column.isNullable })),
+ definitions: [],
+ referenceKeys: [],
+ names: [],
+ } satisfies OracleForeignKeySourceSnapshot;
+ const pkColumns = options.columns.filter((column) => !column.markedForDrop && column.isPrimaryKey).map((column) => column.name);
+ const references: OracleForeignKeyReferenceSnapshot[] = [];
+ for (const change of changes) {
+ const definition = change.target!;
+ if (definition.columns.some((name) => !source.columns.some((column) => column.name === name))) invalid();
+ const selfReference = foldCreatedTableName(definition.refSchema, target.databaseType) === foldCreatedTableName(target.schema, target.databaseType) && foldCreatedTableName(definition.refTable, target.databaseType) === foldCreatedTableName(target.tableName, target.databaseType);
+ if (selfReference) {
+ if (definition.refColumns.length !== pkColumns.length || definition.refColumns.some((column) => !pkColumns.includes(column))) invalid();
+ const snapshot: OracleForeignKeyReferenceSnapshot = {
+ owner: definition.refSchema,
+ table: definition.refTable,
+ objectId: "new-table",
+ keys: pkColumns.length ? [{ name: options.primaryKeyName || "PRIMARY_KEY", kind: "P", enabled: true, validated: true, deferrable: false, columns: pkColumns }] : [],
+ columns: source.columns.map(({ name, dataType }) => ({ name, dataType })),
+ references: "present",
+ };
+ validateOracleForeignKeyReference(snapshot, source, definition, false, target.databaseType);
+ references.push(snapshot);
+ continue;
+ }
+ const snapshot = await readOracleForeignKeyReferenceSnapshot(target, session.user, definition, stillCurrent);
+ validateOracleForeignKeyReference(snapshot, source, definition, false, target.databaseType);
+ references.push(snapshot);
+ }
+ return { target, options, partitioning, changes, statements: [...generated.statements], references, session, snapshot: JSON.stringify({ session, references }) };
+}
+
+/** Rechecks parent/session state, then executes CREATE and ordered FKs once each. */
+export async function executeOracleForeignKeyCreatePlan(plan: OracleForeignKeyCreatePlan, timeoutSecs: number, guards: (() => boolean) | { canStart?: () => boolean; connectionCurrent?: () => boolean }): Promise<OracleForeignKeyCreateExecutionResult | undefined> {
+ const canStart = typeof guards === "function" ? guards : (guards.canStart ?? (() => true));
+ const connectionCurrent = typeof guards === "function" ? guards : (guards.connectionCurrent ?? (() => true));
+ if (!canStart() || !connectionCurrent()) return undefined;
+ const fresh = await prepareOracleForeignKeyCreatePlan(plan.target, plan.options, plan.changes, plan.partitioning, connectionCurrent);
+ if (!connectionCurrent() || !canStart()) return undefined;
+ if (fresh.snapshot !== plan.snapshot || JSON.stringify(fresh.statements) !== JSON.stringify(plan.statements)) invalid();
+ const steps: OracleForeignKeyCreateExecutionResult["steps"] = plan.statements.map((sql) => ({ sql, state: "notExecuted" }));
+ for (const step of steps) {
+ if (!canStart() || !connectionCurrent()) break;
+ try {
+ const result = await api.executeQuery(plan.target.connectionId, plan.target.database, step.sql.replace(/;\s*$/, ""), plan.target.schema, undefined, { catalog: plan.target.catalog, timeoutSecs });
+ if (!connectionCurrent()) {
+ step.state = "unknown";
+ step.error = "Connection or target changed during execution; outcome is unknown.";
+ const outcome: OracleForeignKeyCreateExecutionResult = { steps, readbackError: "Connection or target changed during CREATE DDL; readback is unknown." };
+ return outcome;
+ }
+ if (result.execution_error) {
+ step.state = "rejected";
+ step.error = result.error?.detail || "Create statement rejected";
+ break;
+ }
+ step.state = "committed";
+ if (!canStart()) break;
+ } catch (error) {
+ step.state = "unknown";
+ step.error = error instanceof Error ? error.message : String(error);
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during CREATE DDL; readback is unknown." };
+ break;
+ }
+ }
+ const outcome: OracleForeignKeyCreateExecutionResult = { steps };
+ const createUnknown = steps[0]?.state === "unknown";
+ if (!steps.some((step) => step.state === "committed") && !createUnknown) return outcome;
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection, target, or draft changed before readback; the result remains unknown.";
+ return outcome;
+ }
+ try {
+ const readbackTarget = { ...plan.target, tableName: foldCreatedTableName(plan.target.tableName, plan.target.databaseType) };
+ const definitions = await readOracleForeignKeyDefinitions(readbackTarget, connectionCurrent);
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed during readback; the result remains unknown.";
+ return outcome;
+ }
+ outcome.tableExists = true;
+ outcome.readbackDefinitions = definitions;
+ if (!connectionCurrent()) outcome.readbackError = "Connection or target changed during readback; the result remains unknown.";
+ else
+ for (const [index, change] of plan.changes.entries()) {
+ const expected = change.target!;
+ const normalizeCreatedName = (name: string) => (plan.target.databaseType === "oracle" ? foldCreatedTableName(name, plan.target.databaseType) : name);
+ const actual = definitions.find((definition) => definition.name === normalizeCreatedName(expected.name));
+ const foreignKeyStep = steps.filter((step) => step.sql.includes("FOREIGN KEY"))[index];
+ const selfReference = normalizeCreatedName(expected.refSchema) === normalizeCreatedName(plan.target.schema) && normalizeCreatedName(expected.refTable) === normalizeCreatedName(plan.target.tableName);
+ const normalizeExpected = (definition: OracleForeignKeyDefinition) => ({
+ ...definition,
+ name: normalizeCreatedName(definition.name),
+ columns: definition.columns.map(normalizeCreatedName),
+ ...(selfReference ? { refSchema: normalizeCreatedName(definition.refSchema), refTable: normalizeCreatedName(definition.refTable), refColumns: definition.refColumns.map(normalizeCreatedName) } : {}),
+ });
+ if (foreignKeyStep?.state === "committed" && JSON.stringify(actual) !== JSON.stringify(normalizeExpected(expected))) {
+ outcome.readbackError = "Created foreign key definition differs from the submitted plan.";
+ break;
+ }
+ }
+ } catch (error) {
+ outcome.readbackError = error instanceof Error ? error.message : String(error);
+ }
+ return outcome;
+}
+
+/** Generates a complete preview and its preflight evidence. It never executes generated DDL. */
+export async function prepareOracleForeignKeyPlan(target: OracleForeignKeyTarget, options: BuildTableStructureChangeSqlOptions, changes: OracleForeignKeyChange[], stillCurrent: () => boolean = () => true): Promise<OracleForeignKeyPlan> {
+ target = { ...target };
+ changes = JSON.parse(JSON.stringify(changes)) as OracleForeignKeyChange[];
+ options = { ...JSON.parse(JSON.stringify(options)), databaseType: target.databaseType, schema: target.schema, tableName: target.tableName, foreignKeys: [], oracleForeignKeyChanges: changes };
+ const whole = await api.buildTableStructureChangeSql(options);
+ if (whole.warnings.length) throw new Error(whole.warnings.join("\n"));
+ const source = await readOracleForeignKeySourceSnapshot(target, changes, stillCurrent);
+ validateOracleForeignKeySourceChanges(source, target, changes);
+ const groups: OracleForeignKeyPlan["groups"] = [];
+ const references: OracleForeignKeyPlan["references"] = [];
+ const referenceIndices = new Map<string, number>();
+ const unverified = new Set<OracleForeignKeyPlan["unverified"][number]>();
+ const ident = (name: string) => `"${name.replace(/"/g, '""')}"`;
+ const reference = async (definition: OracleForeignKeyDefinition) => {
+ const identity = JSON.stringify([definition.refSchema, definition.refTable, definition.refColumns]);
+ const existing = referenceIndices.get(identity);
+ if (existing !== undefined) return references[existing]!.snapshot;
+ const snapshot = await readOracleForeignKeyReferenceSnapshot(target, source.user, definition, stillCurrent);
+ referenceIndices.set(identity, references.length);
+ references.push({
+ columns: [...definition.refColumns],
+ snapshot: {
+ ...snapshot,
+ columns: snapshot.columns?.filter((column) => definition.refColumns.includes(column.name)) ?? null,
+ keys: snapshot.keys?.filter((key) => key.columns.length === definition.refColumns.length && key.columns.every((column) => definition.refColumns.includes(column))) ?? null,
+ },
+ });
+ return snapshot;
+ };
+ for (const change of changes) {
+ const generated = await api.buildTableStructureChangeSql({ ...options, oracleForeignKeyChanges: [change] });
+ if (generated.warnings.length) throw new Error(generated.warnings.join("\n"));
+ const originalDrop = change.original ? `ALTER TABLE ${ident(target.schema)}.${ident(target.tableName)} DROP CONSTRAINT ${ident(change.original.name)};` : undefined;
+ const replacement = !!change.original && !!change.target && generated.statements[0] === originalDrop;
+ groups.push({ change, statements: generated.statements, replacement });
+ if (change.original) await reference(change.original);
+ if (!change.target || !generated.statements.length) continue;
+ const parent = await reference(change.target);
+ const needsQualification = !change.original || replacement || (!change.original.state.enabled && change.target.state.enabled) || (!change.original.state.validated && change.target.state.validated);
+ if (needsQualification) validateOracleForeignKeyReference(parent, source, change.target, replacement, target.databaseType);
+ if (needsQualification && (!parent.objectId || !parent.keys || !parent.columns)) unverified.add("referenceDefinition");
+ if (needsQualification && parent.references !== "present") unverified.add("referencesPermission");
+ const data = await checkOracleForeignKeyData(target, change, replacement, stillCurrent);
+ const needsData = change.target.state.validated && (!change.original || replacement || !change.original.state.validated || (!change.original.state.enabled && change.target.state.enabled));
+ if (needsData && !data.checked) unverified.add("existingData");
+ }
+ const statements = groups.flatMap((group) => group.statements);
+ if (JSON.stringify(statements) !== JSON.stringify(whole.statements)) invalid();
+ return { target, options, changes, groups, source, references, snapshot: JSON.stringify({ source, references }), statements, unverified: [...unverified] };
+}
+
+/** Rechecks the full preflight snapshot, applies one statement at a time, then reads the definitions back. */
+export async function executeOracleForeignKeyPlan(plan: OracleForeignKeyPlan, timeoutSecs: number, guards: (() => boolean) | { canStart?: () => boolean; connectionCurrent?: () => boolean }): Promise<OracleForeignKeyExecutionResult | undefined> {
+ const canStart = typeof guards === "function" ? guards : (guards.canStart ?? (() => true));
+ const connectionCurrent = typeof guards === "function" ? guards : (guards.connectionCurrent ?? (() => true));
+ if (!canStart() || !connectionCurrent()) return undefined;
+ const fresh = await prepareOracleForeignKeyPlan(plan.target, plan.options, plan.changes, connectionCurrent);
+ if (!connectionCurrent() || !canStart()) return undefined;
+ if (fresh.snapshot !== plan.snapshot || JSON.stringify(fresh.statements) !== JSON.stringify(plan.statements)) invalid();
+ if (!canStart() || !connectionCurrent()) return undefined;
+ const steps: OracleForeignKeyExecutionResult["steps"] = plan.statements.map((sql) => ({ sql, state: "notExecuted" }));
+ for (const step of steps) {
+ if (!canStart() || !connectionCurrent()) break;
+ try {
+ const result = await api.executeQuery(plan.target.connectionId, plan.target.database, step.sql.replace(/;\s*$/, ""), plan.target.schema, undefined, { catalog: plan.target.catalog, timeoutSecs });
+ if (!connectionCurrent()) {
+ step.state = "unknown";
+ step.error = "Connection or target changed during execution; outcome is unknown.";
+ return { steps, readbackError: "Connection or target changed during foreign key DDL; readback is unknown." };
+ }
+ if (result.execution_error) {
+ step.state = "rejected";
+ step.error = result.error?.detail || "Foreign key statement rejected";
+ break;
+ }
+ step.state = "committed";
+ if (!canStart()) break;
+ } catch (error) {
+ step.state = "unknown";
+ step.error = error instanceof Error ? error.message : String(error);
+ if (!connectionCurrent()) return { steps, readbackError: "Connection or target changed during foreign key DDL; readback is unknown." };
+ break;
+ }
+ }
+ const outcome: OracleForeignKeyExecutionResult = { steps };
+ const recoveryTargets: OracleForeignKeyDefinition[] = [];
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection, target, or draft changed during execution; readback is unknown.";
+ return outcome;
+ }
+ try {
+ const current = await readOracleForeignKeyDefinitions(plan.target, connectionCurrent);
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed during readback; the result remains unknown.";
+ return outcome;
+ }
+ for (const group of plan.groups) {
+ const { change, statements } = group;
+ if (!statements.length) continue;
+ const firstIndex = plan.statements.indexOf(statements[0]!);
+ const groupSteps = steps.slice(firstIndex, firstIndex + statements.length);
+ const complete = groupSteps.every((step) => step.state === "committed");
+ const original = change.original ? current.find((definition) => definition.name === change.original!.name) : undefined;
+ const target = change.target ? current.find((definition) => definition.name === change.target!.name) : undefined;
+ const matches = (actual: OracleForeignKeyDefinition | undefined, expected: OracleForeignKeyDefinition | null) => !!actual && !!expected && JSON.stringify(actual) === JSON.stringify(expected);
+ const dropped = !!change.original && (groupSteps[0]?.state === "committed" || groupSteps[0]?.state === "unknown") && (group.replacement || !change.target);
+ if (complete) {
+ if (change.target ? !matches(target, change.target) || (change.original && change.original.name !== change.target.name && original) : original) outcome.readbackError = "Foreign key definition differs from the completed statements.";
+ } else if (change.original && change.target) {
+ if (!matches(original, change.original) && !matches(target, change.target)) outcome.readbackError = "Foreign key definition matches neither the original nor target after a partial change.";
+ } else if (change.original) {
+ if (groupSteps[0]?.state === "committed" ? !!original : !matches(original, change.original)) outcome.readbackError = "Foreign key removal readback differs from its execution result.";
+ } else if (change.target) {
+ if (groupSteps[0]?.state === "committed" ? !matches(target, change.target) : !!target) outcome.readbackError = "Foreign key creation readback differs from its execution result.";
+ }
+ const needsRecovery = dropped && !original && !target && ((complete && !change.target) || groupSteps.some((step) => step.state === "rejected" || step.state === "unknown"));
+ if (needsRecovery) {
+ if (!canStart() || !connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed before recovery checks; the result remains unknown.";
+ return outcome;
+ }
+ const names = await readOracleForeignKeyConstraintNames(plan.target, [change.original!.name, ...(change.target && change.target.name !== change.original!.name ? [change.target.name] : [])], connectionCurrent);
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed during recovery checks; the result remains unknown.";
+ return outcome;
+ }
+ if (names.length) {
+ outcome.readbackError = "A foreign key name is occupied; manual recovery must be reviewed.";
+ continue;
+ }
+ const currentSource = await readOracleForeignKeySourceSnapshot(plan.target, plan.changes, connectionCurrent);
+ if (!connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed during source verification; the result remains unknown.";
+ return outcome;
+ }
+ const identityMatches = currentSource.user === plan.source.user && currentSource.currentSchema === plan.source.currentSchema && currentSource.objectId === plan.source.objectId;
+ const columnsMatch = change.original!.columns.every((colName) => {
+ const originalCol = plan.source.columns.find((c) => c.name === colName);
+ const currentCol = currentSource.columns.find((c) => c.name === colName);
+ return !!originalCol && !!currentCol && originalCol.dataType === currentCol.dataType && originalCol.length === currentCol.length && originalCol.precision === currentCol.precision && originalCol.scale === currentCol.scale && originalCol.nullable === currentCol.nullable;
+ });
+ if (identityMatches && columnsMatch) {
+ recoveryTargets.push(change.original!);
+ } else {
+ outcome.readbackError = "Table identity or column definitions changed; manual recovery candidate withheld.";
+ }
+ }
+ }
+ } catch (error) {
+ recoveryTargets.length = 0;
+ outcome.readbackError = error instanceof Error ? error.message : String(error);
+ }
+ if (recoveryTargets.length) {
+ if (!canStart() || !connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed before generating recovery statements; the result remains unknown.";
+ return outcome;
+ }
+ const recoveryChanges = recoveryTargets.map((original) => ({ original: null, target: original }));
+ const recovery = await api.buildTableStructureChangeSql({ ...plan.options, oracleForeignKeyChanges: recoveryChanges });
+ if (!canStart() || !connectionCurrent()) {
+ outcome.readbackError = "Connection or target changed during recovery statement generation; the result remains unknown.";
+ return outcome;
+ }
+ if (!recovery.warnings.length) outcome.recoverySql = recovery.statements;
+ }
+ return outcome;
+}
diff --git a/apps/desktop/src/lib/database/oracleIndexes.ts b/apps/desktop/src/lib/database/oracleIndexes.ts
new file mode 100644
index 0000000000..ae21e9202b
--- /dev/null
+++ b/apps/desktop/src/lib/database/oracleIndexes.ts
@@ -0,0 +1,439 @@
+import * as api from "@/lib/backend/api";
+import { readOracleIndexSnapshot, type OracleConstraintTarget, type OracleIndexSnapshot } from "@/lib/database/oracleConstraints";
+import type { EditableStructureIndex } from "@/lib/table/tableStructureEditorSql";
+import { createIndexDrafts } from "@/lib/table/tableStructureEditorState";
+import type { ColumnInfo, IndexInfo } from "@/types/database";
+
+export type OracleIndexDefinition = OracleIndexSnapshot["indexes"][number];
+type OracleIndexMutation = {
+ operation: "CREATE" | "DROP";
+ name: string;
+ expectedBefore: OracleIndexDefinition[];
+ expectedAfter: OracleIndexDefinition[];
+ expectedOwnerNamesBefore: string[];
+ expectedOwnerNamesAfter: string[];
+};
+
+export interface OracleIndexPlan {
+ target: OracleConstraintTarget;
+ snapshot: OracleIndexSnapshot;
+ statements: string[];
+ snapshotFingerprint: string;
+ mutations: OracleIndexMutation[];
+}
+
+export interface OracleIndexLoadBaseline {
+ snapshot: OracleIndexSnapshot;
+ epoch: number;
+ targetIdentity: string;
+ requestId: number;
+ connectionRevision: number;
+ configFingerprint: string;
+ columnsFingerprint: string;
+ indexesFingerprint: string;
+}
+
+export interface OracleIndexPrepareContext {
+ baseline: OracleIndexLoadBaseline;
+ columnsFingerprint: string;
+ indexesFingerprint: string;
+}
+
+export interface OracleIndexExecutionResult {
+ steps: Array<{ sql: string; state: "committed" | "rejected" | "unknown" | "notExecuted"; error?: string }>;
+ readbackError?: string;
+}
+
+function invalid(): never {
+ throw new Error("Index metadata changed, is incomplete, or is unsupported. Refresh the table definition and preview again.");
+}
+
+function parseIdentifierParts(text: string): string[] {
+ return [...text.matchAll(/"((?:""|[^"])*)"|([A-Za-z0-9_$#]+)/g)].map((part) => (part[1] === undefined ? part[2]!.toUpperCase() : part[1].replace(/""/g, '"')));
+}
+
+function sameTargetIdentity(left: OracleIndexSnapshot, right: OracleIndexSnapshot): boolean {
+ return (
+ left.user === right.user &&
+ left.currentSchema === right.currentSchema &&
+ left.database === right.database &&
+ left.databaseName === right.databaseName &&
+ left.objectId === right.objectId &&
+ left.columnReadMode === right.columnReadMode &&
+ JSON.stringify(left.userColumns) === JSON.stringify(right.userColumns)
+ );
+}
+
+function actualIndexMatchesLoaded(index: OracleIndexDefinition, original: IndexInfo, target: OracleConstraintTarget): boolean {
+ return (
+ index.owner === target.schema &&
+ index.tableOwner === target.schema &&
+ index.tableName === target.tableName &&
+ index.name === original.name &&
+ index.indexType === original.index_type &&
+ index.uniqueness === (original.is_unique ? "UNIQUE" : "NONUNIQUE") &&
+ JSON.stringify(index.columns) === JSON.stringify(original.columns) &&
+ JSON.stringify(index.directions) === JSON.stringify(original.key_directions) &&
+ JSON.stringify(index.keyIsExpression) === JSON.stringify(original.key_is_expression) &&
+ index.visibility === original.visibility
+ );
+}
+
+function assertOriginalsMatchLoaded(snapshot: OracleIndexSnapshot, target: OracleConstraintTarget, drafts: EditableStructureIndex[]) {
+ const originals = drafts.flatMap((draft) => (draft.original && !draft.oracleOriginalMissing ? [draft.original] : []));
+ if (originals.length !== snapshot.indexes.length) invalid();
+ for (const original of originals) {
+ const current = snapshot.indexes.find((index) => index.owner === target.schema && index.name === original.name);
+ if (!current || !actualIndexMatchesLoaded(current, original, target)) invalid();
+ }
+ for (const draft of drafts) {
+ if (draft.original && draft.oracleOriginalMissing && snapshot.indexNames.includes(draft.original.name)) invalid();
+ }
+}
+
+export function oracleIndexSnapshotMatchesLoaded(snapshot: OracleIndexSnapshot, target: OracleConstraintTarget, drafts: EditableStructureIndex[]): boolean {
+ try {
+ assertOriginalsMatchLoaded(snapshot, target, drafts);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function loadedColumnType(column: OracleIndexSnapshot["columns"][number]): string | undefined {
+ const base = column.dataType.toUpperCase();
+ if (["VARCHAR2", "CHAR"].includes(base)) {
+ if (column.charUsed === "B" && column.length !== null) return `${base}(${column.length} BYTE)`;
+ if (column.charUsed === "C" && column.charLength !== null) return `${base}(${column.charLength} CHAR)`;
+ const length = column.charLength ?? column.length;
+ return length === null ? base : `${base}(${length})`;
+ }
+ if (["NVARCHAR2", "NCHAR"].includes(base)) {
+ const length = column.charLength ?? column.length;
+ return length === null ? base : `${base}(${length})`;
+ }
+ if (base === "NUMBER") {
+ if (column.precision === null && column.scale !== null) return `${base}(*,${column.scale})`;
+ if (column.precision !== null && Number(column.precision) > 0) return column.scale !== null && Number(column.scale) !== 0 ? `${base}(${column.precision},${column.scale})` : `${base}(${column.precision})`;
+ return base;
+ }
+ if (base === "FLOAT" && column.precision !== null && Number(column.precision) > 0) return `${base}(${column.precision})`;
+ if (base === "RAW" && column.length !== null) return `${base}(${column.length})`;
+ return base;
+}
+
+export function oracleIndexSnapshotMatchesLoadedColumns(snapshot: OracleIndexSnapshot, loadedColumns: Pick<ColumnInfo, "name" | "data_type" | "is_nullable" | "numeric_precision" | "numeric_scale" | "character_maximum_length">[]): boolean {
+ const actual = [...loadedColumns].sort((left, right) => left.name.localeCompare(right.name));
+ const expected = [...snapshot.userColumns].sort((left, right) => left.name.localeCompare(right.name));
+ return (
+ actual.length === expected.length &&
+ actual.every((column, index) => {
+ const wanted = expected[index]!;
+ const wantedType = loadedColumnType(wanted);
+ const actualType = column.data_type.trim().toUpperCase();
+ const expectedBaseType = wanted.dataType.toUpperCase();
+ const sameType = snapshot.columnReadMode === "strict-base" ? (expectedBaseType.includes("(") ? actualType.startsWith(expectedBaseType) : actualType.replace(/\s*\([^)]*\)/, "") === expectedBaseType) : !!wantedType && actualType === wantedType;
+ const sameKnownNumber = (actualValue: number | null | undefined, expectedValue: string | null) => (expectedValue === null ? actualValue == null : actualValue != null && String(actualValue) === expectedValue);
+ const parameter = /^([A-Z0-9_$#]+)\((\d+)(?:\s+(BYTE|CHAR))?\)$/i.exec(actualType);
+ const sameKnownLength =
+ snapshot.columnReadMode === "enhanced"
+ ? wanted.charLength === null
+ ? column.character_maximum_length == null
+ : column.character_maximum_length != null && String(column.character_maximum_length) === wanted.charLength
+ : expectedBaseType === "RAW" || parameter?.[3] === "BYTE"
+ ? !!parameter && parameter[1]!.toUpperCase() === expectedBaseType && parameter[2] === wanted.length
+ : expectedBaseType === "VARCHAR2" || expectedBaseType === "CHAR" || expectedBaseType === "NVARCHAR2" || expectedBaseType === "NCHAR"
+ ? parameter?.[3] === "CHAR"
+ ? column.character_maximum_length != null && String(column.character_maximum_length) === parameter[2]
+ : !parameter || column.character_maximum_length == null || String(column.character_maximum_length) === parameter[2]
+ : true;
+ return sameType && sameKnownNumber(column.numeric_precision, wanted.precision) && sameKnownNumber(column.numeric_scale, wanted.scale) && sameKnownLength && column.name === wanted.name && column.is_nullable === wanted.nullable;
+ })
+ );
+}
+
+function validateMutationStatement(sql: string, mutation: { operation: "CREATE" | "DROP"; name: string }, target: OracleConstraintTarget): boolean {
+ const atom = '(?:"(?:""|[^"])*"|[A-Za-z0-9_$#]+)';
+ const qualified = `(${atom}(?:\\s*\\.\\s*${atom})?)`;
+ const match = new RegExp(`^\\s*(CREATE\\s+(?:UNIQUE\\s+)?(?:BITMAP\\s+)?INDEX|DROP\\s+INDEX)\\s+${qualified}`, "i").exec(sql);
+ if (!match || (/^CREATE/i.test(match[1]!) ? "CREATE" : "DROP") !== mutation.operation) return false;
+ const parts = parseIdentifierParts(match[2]!);
+ if (parts.length === 2 && parts[0] !== target.schema) return false;
+ if (parts[parts.length - 1] !== mutation.name) return false;
+ if (mutation.operation === "CREATE") {
+ const tableMatch = new RegExp(`\\bON\\s+${qualified}\\s*\\(`, "i").exec(sql);
+ if (!tableMatch) return false;
+ const table = parseIdentifierParts(tableMatch[1]!);
+ if (table.length === 2 ? table[0] !== target.schema || table[1] !== target.tableName : table[0] !== target.tableName) return false;
+ }
+ return true;
+}
+
+function draftChanged(draft: EditableStructureIndex): boolean {
+ const original = draft.original;
+ if (!original || draft.oracleOriginalMissing) return true;
+ return (
+ draft.name !== original.name ||
+ JSON.stringify(draft.columns) !== JSON.stringify(original.columns) ||
+ draft.isUnique !== original.is_unique ||
+ draft.indexType.trim().toUpperCase() !== (original.index_type ?? "").trim().toUpperCase() ||
+ JSON.stringify(draft.includedColumns) !== JSON.stringify(original.included_columns ?? []) ||
+ draft.filter !== (original.filter ?? "") ||
+ draft.comment !== (original.comment ?? "") ||
+ JSON.stringify(draft.columnOpclasses ?? []) !== JSON.stringify(original.column_opclasses ?? [])
+ );
+}
+
+function expectedMutations(drafts: EditableStructureIndex[]): Array<{ operation: "CREATE" | "DROP"; name: string; draft: EditableStructureIndex }> {
+ const mutations: Array<{ operation: "CREATE" | "DROP"; name: string; draft: EditableStructureIndex }> = [];
+ for (const draft of drafts) {
+ if (draft.markedForDrop) {
+ if (draft.original && !draft.oracleOriginalMissing) mutations.push({ operation: "DROP", name: draft.original.name, draft });
+ continue;
+ }
+ if (!draft.original) {
+ mutations.push({ operation: "CREATE", name: draft.name, draft });
+ continue;
+ }
+ if (draftChanged(draft)) {
+ if (!draft.oracleOriginalMissing) mutations.push({ operation: "DROP", name: draft.original.name, draft });
+ mutations.push({ operation: "CREATE", name: draft.name, draft });
+ }
+ }
+ return mutations;
+}
+
+function expectedCreatedIndex(draft: EditableStructureIndex, target: OracleConstraintTarget): OracleIndexDefinition {
+ const original = draft.original;
+ const originalPositions = new Map((original?.columns ?? []).map((column, position) => [column, position]));
+ const keyIsExpression = draft.columns.map((column) => {
+ const position = originalPositions.get(column);
+ if (position === undefined) return false;
+ const flag = original?.key_is_expression?.[position];
+ if (flag === undefined) invalid();
+ return flag;
+ });
+ const directions = draft.columns.map((column) => {
+ const position = originalPositions.get(column);
+ if (position === undefined) return "ASC";
+ const direction = original?.key_directions?.[position];
+ if (!direction) invalid();
+ return direction;
+ });
+ const indexType = (draft.indexType || original?.index_type || (keyIsExpression.some(Boolean) ? "FUNCTION-BASED NORMAL" : "NORMAL")).toUpperCase();
+ if (!draft.columns.length || !["NORMAL", "FUNCTION-BASED NORMAL"].includes(indexType) || (indexType === "NORMAL" && keyIsExpression.some(Boolean)) || (indexType === "FUNCTION-BASED NORMAL" && !keyIsExpression.some(Boolean))) invalid();
+ if (directions.some((direction) => !["ASC", "DESC"].includes(direction))) invalid();
+ if (target.databaseType === "oceanbase-oracle" && directions.some((direction) => direction === "DESC")) invalid();
+ return {
+ owner: target.schema,
+ name: draft.name,
+ tableOwner: target.schema,
+ tableName: target.tableName,
+ indexType,
+ uniqueness: draft.isUnique ? "UNIQUE" : "NONUNIQUE",
+ status: "VALID",
+ partitioned: false,
+ visibility: original?.visibility || "VISIBLE",
+ secondary: original?.constraint_backed ? "Y" : null,
+ columns: [...draft.columns],
+ directions,
+ keyIsExpression,
+ includedColumns: [],
+ constraints: [],
+ };
+}
+
+function completedCreateMatchesLoaded(index: IndexInfo, expected: OracleIndexDefinition): boolean {
+ return (
+ index.name === expected.name &&
+ index.is_unique === (expected.uniqueness === "UNIQUE") &&
+ !index.is_primary &&
+ index.index_type === expected.indexType &&
+ index.key_metadata_complete === true &&
+ JSON.stringify(index.columns) === JSON.stringify(expected.columns) &&
+ JSON.stringify(index.key_is_expression) === JSON.stringify(expected.keyIsExpression) &&
+ JSON.stringify(index.key_directions) === JSON.stringify(expected.directions) &&
+ index.visibility === expected.visibility &&
+ (index.constraint_backed ?? false) === (expected.secondary === "Y")
+ );
+}
+
+export function mergeOracleIndexDraftsAfterRefresh(drafts: EditableStructureIndex[], actualIndexes: IndexInfo[], completedCreates: OracleIndexDefinition[]): EditableStructureIndex[] {
+ const loadedByName = new Map(actualIndexes.map((index) => [index.name, index]));
+ const refreshedDrafts: EditableStructureIndex[] = [];
+ for (const draft of drafts) {
+ const current = loadedByName.get(draft.original?.name || draft.name);
+ if (current) {
+ loadedByName.delete(current.name);
+ refreshedDrafts.push({ ...draft, original: current, indexType: current.index_type ?? draft.indexType, oracleOriginalMissing: false, isPrimary: current.is_primary });
+ continue;
+ }
+ if (draft.original) {
+ const expected = completedCreates.find((index) => index.name === draft.name);
+ const actual = loadedByName.get(draft.name);
+ if (expected && actual && completedCreateMatchesLoaded(actual, expected)) {
+ loadedByName.delete(actual.name);
+ const committedDraft = { ...draft, original: actual, indexType: actual.index_type ?? draft.indexType, oracleOriginalMissing: false, isPrimary: actual.is_primary };
+ refreshedDrafts.push(draftMatchesCompletedCreate(committedDraft, expected) ? createIndexDrafts([actual])[0]! : committedDraft);
+ continue;
+ }
+ }
+ if (!draft.markedForDrop) refreshedDrafts.push({ ...draft, oracleOriginalMissing: !!draft.original, isPrimary: false });
+ }
+ return [...refreshedDrafts, ...createIndexDrafts([...loadedByName.values()])];
+}
+
+function draftMatchesCompletedCreate(draft: EditableStructureIndex, expected: OracleIndexDefinition): boolean {
+ return !draft.markedForDrop && draft.name === expected.name && draft.isUnique === (expected.uniqueness === "UNIQUE") && draft.indexType.trim().toUpperCase() === expected.indexType && JSON.stringify(draft.columns) === JSON.stringify(expected.columns);
+}
+
+function sameExpectedIndexes(actual: OracleIndexDefinition[], expected: OracleIndexDefinition[]): boolean {
+ if (actual.length !== expected.length) return false;
+ const orderedActual = [...actual].sort((a, b) => a.name.localeCompare(b.name));
+ const orderedExpected = [...expected].sort((a, b) => a.name.localeCompare(b.name));
+ return orderedActual.every((item, i) => {
+ const wanted = orderedExpected[i]!;
+ return (
+ item.owner === wanted.owner &&
+ item.name === wanted.name &&
+ item.tableOwner === wanted.tableOwner &&
+ item.tableName === wanted.tableName &&
+ item.indexType === wanted.indexType &&
+ item.uniqueness === wanted.uniqueness &&
+ item.status === wanted.status &&
+ item.partitioned === wanted.partitioned &&
+ item.visibility === wanted.visibility &&
+ (wanted.secondary === null ? item.secondary === null || item.secondary === "N" : item.secondary === wanted.secondary) &&
+ JSON.stringify(item.columns) === JSON.stringify(wanted.columns) &&
+ JSON.stringify(item.directions) === JSON.stringify(wanted.directions) &&
+ JSON.stringify(item.keyIsExpression) === JSON.stringify(wanted.keyIsExpression) &&
+ JSON.stringify(item.includedColumns) === JSON.stringify(wanted.includedColumns) &&
+ JSON.stringify(item.constraints) === JSON.stringify(wanted.constraints)
+ );
+ });
+}
+
+export async function prepareOracleIndexPlan(target: OracleConstraintTarget, statements: string[], drafts: EditableStructureIndex[], context?: OracleIndexPrepareContext): Promise<OracleIndexPlan> {
+ const mutationsRequested = expectedMutations(drafts);
+ const snapshot = await readOracleIndexSnapshot(
+ target,
+ () => true,
+ mutationsRequested.map((item) => item.name),
+ );
+ if (context) {
+ const { baseline } = context;
+ if (!baseline.targetIdentity || !baseline.configFingerprint || baseline.columnsFingerprint !== context.columnsFingerprint || baseline.indexesFingerprint !== context.indexesFingerprint || !sameTargetIdentity(baseline.snapshot, snapshot)) invalid();
+ }
+ assertOriginalsMatchLoaded(snapshot, target, drafts);
+ const planned = [...snapshot.indexes];
+ const plannedOwnerNames = new Set(snapshot.indexNames);
+ const mutations: OracleIndexMutation[] = [];
+ const targets = expectedMutations(drafts);
+ if (targets.length !== statements.length || statements.some((sql, index) => !targets[index] || !validateMutationStatement(sql, targets[index]!, target))) invalid();
+ for (const mutation of targets) {
+ const expectedBefore = [...planned];
+ const expectedOwnerNamesBefore = [...plannedOwnerNames].sort();
+ if (mutation.operation === "DROP") {
+ const current = planned.find((index) => index.name === mutation.name);
+ const draft = mutation.draft;
+ if (!current || !draft?.original || draft.isPrimary || draft.original.is_primary || draft.original.constraint_backed || current.constraints.length || current.partitioned || !["NORMAL", "FUNCTION-BASED NORMAL"].includes(current.indexType) || current.status !== "VALID") invalid();
+ if (!draft.original.key_metadata_complete || !actualIndexMatchesLoaded(current, draft.original, target)) invalid();
+ planned.splice(planned.indexOf(current), 1);
+ plannedOwnerNames.delete(mutation.name);
+ } else {
+ if (plannedOwnerNames.has(mutation.name)) invalid();
+ const draft = mutation.draft;
+ if (!draft || draft.isPrimary || draft.original?.is_primary || draft.original?.constraint_backed) invalid();
+ planned.push(expectedCreatedIndex(draft, target));
+ plannedOwnerNames.add(mutation.name);
+ }
+ mutations.push({
+ operation: mutation.operation,
+ name: mutation.name,
+ expectedBefore,
+ expectedAfter: [...planned],
+ expectedOwnerNamesBefore,
+ expectedOwnerNamesAfter: [...plannedOwnerNames].sort(),
+ });
+ }
+ return { target: { ...target }, snapshot, statements: [...statements], snapshotFingerprint: JSON.stringify(snapshot), mutations };
+}
+
+export async function executeOracleIndexPlan(plan: OracleIndexPlan, timeoutSecs: number, stillCurrent: () => boolean): Promise<OracleIndexExecutionResult | undefined> {
+ const requestedNames = [...new Set(plan.mutations.map((mutation) => mutation.name))];
+ const fresh = await readOracleIndexSnapshot(plan.target, stillCurrent, requestedNames);
+ if (!stillCurrent()) return undefined;
+ if (JSON.stringify(fresh) !== plan.snapshotFingerprint) invalid();
+ const originalIdentity = fresh;
+ const steps: OracleIndexExecutionResult["steps"] = plan.statements.map((sql) => ({ sql, state: "notExecuted" }));
+ for (const [index, step] of steps.entries()) {
+ if (!stillCurrent()) break;
+ const mutation = plan.mutations[index]!;
+ try {
+ const before = await readOracleIndexSnapshot(plan.target, stillCurrent, requestedNames);
+ if (!stillCurrent()) return { steps, readbackError: "Connection or target changed before index DDL; no further statements were run." };
+ if (!sameTargetIdentity(before, originalIdentity) || JSON.stringify(before.indexNames) !== JSON.stringify(mutation.expectedOwnerNamesBefore) || !sameExpectedIndexes(before.indexes, mutation.expectedBefore)) {
+ return { steps, readbackError: "Index metadata or constraint support changed before DDL; later statements stopped." };
+ }
+ } catch (error) {
+ return { steps, readbackError: error instanceof Error ? error.message : String(error) };
+ }
+ try {
+ const result = await api.executeQuery(plan.target.connectionId, plan.target.database, step.sql.replace(/;\s*$/, ""), plan.target.schema, undefined, { catalog: plan.target.catalog, timeoutSecs });
+ if (!stillCurrent()) {
+ step.state = "unknown";
+ step.error = "Connection or target changed during execution; outcome is unknown.";
+ return { steps, readbackError: "Connection or target changed during index DDL; readback is unknown." };
+ }
+ if (result.execution_error) {
+ step.state = "rejected";
+ step.error = result.error?.detail || "Index statement rejected";
+ } else {
+ step.state = "committed";
+ }
+ } catch (error) {
+ step.state = "unknown";
+ step.error = error instanceof Error ? error.message : String(error);
+ }
+ if (!stillCurrent()) {
+ step.state = "unknown";
+ step.error = `${step.error ? `${step.error}; ` : ""}Connection or target changed before readback; execution outcome is unknown.`;
+ return { steps, readbackError: "Connection or target changed during index DDL; readback is unknown." };
+ }
+ try {
+ const after = await readOracleIndexSnapshot(plan.target, stillCurrent, requestedNames);
+ if (!stillCurrent()) {
+ step.state = "unknown";
+ return { steps, readbackError: "Connection or target changed during index readback; actual state is unknown." };
+ }
+ if (!sameTargetIdentity(after, originalIdentity)) {
+ step.state = "unknown";
+ return { steps, readbackError: "Database identity, target table, or column definitions changed during index DDL." };
+ }
+ if (step.state !== "committed") {
+ if (JSON.stringify(after.indexNames) !== JSON.stringify(mutation.expectedOwnerNamesBefore) || !sameExpectedIndexes(after.indexes, mutation.expectedBefore)) {
+ step.state = "unknown";
+ step.error = `${step.error ? `${step.error}; ` : ""}Readback changed beyond the rejected/unknown statement's expected prior state.`;
+ break;
+ }
+ step.error = `${step.error ? `${step.error}; ` : ""}Readback index names: ${after.indexes.map((item) => item.name).join(", ") || "none"}.`;
+ break;
+ }
+ if (JSON.stringify(after.indexNames) !== JSON.stringify(mutation.expectedOwnerNamesAfter)) {
+ step.state = "unknown";
+ step.error = "Readback owner index names did not match the expected result.";
+ break;
+ }
+ if (!sameExpectedIndexes(after.indexes, mutation.expectedAfter)) {
+ step.state = "unknown";
+ step.error = `Readback did not match the expected ${mutation.operation} definition for ${mutation.name}.`;
+ break;
+ }
+ } catch (error) {
+ step.state = "unknown";
+ step.error = `${step.error ? `${step.error}; ` : ""}${error instanceof Error ? error.message : String(error)}`;
+ return { steps, readbackError: "Index DDL was attempted but immediate catalog readback failed; outcome is unknown." };
+ }
+ }
+ return { steps };
+}
diff --git a/apps/desktop/src/lib/table/__tests__/oracleForeignKeyDrafts.spec.ts b/apps/desktop/src/lib/table/__tests__/oracleForeignKeyDrafts.spec.ts
new file mode 100644
index 0000000000..3e03a915d5
--- /dev/null
+++ b/apps/desktop/src/lib/table/__tests__/oracleForeignKeyDrafts.spec.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { createForeignKeyDrafts } from "../tableStructureEditorState";
+import type { ForeignKeyInfo } from "@/types/database";
+
+const rows: ForeignKeyInfo[] = [
+ { name: "FK_SOURCE", column: "B,quoted", ref_schema: "Parent Owner", ref_table: "Parent,Table", ref_column: 'V"quoted', on_delete: "CASCADE", on_update: null },
+ { name: "FK_SOURCE", column: " A ", ref_schema: "Parent Owner", ref_table: "Parent,Table", ref_column: " ID ", on_delete: "CASCADE", on_update: null },
+];
+
+describe("Oracle ordered foreign key drafts", () => {
+ it.each(["oracle", "oceanbase-oracle"] as const)("preserves exact metadata pairs for %s", (engine) => {
+ const drafts = createForeignKeyDrafts(rows, engine);
+ expect(drafts).toHaveLength(1);
+ expect(drafts[0]?.columns).toEqual(["B,quoted", " A "]);
+ expect(drafts[0]?.refColumns).toEqual(['V"quoted', " ID "]);
+ });
+
+ it("rejects inconsistent rows of one Oracle constraint", () => {
+ expect(() => createForeignKeyDrafts([rows[0]!, { ...rows[1]!, ref_table: "Other" }], "oracle")).toThrow();
+ });
+
+ it("keeps the existing string contract for other engines", () => {
+ const drafts = createForeignKeyDrafts(rows);
+ expect(drafts[0]?.column).toBe("B,quoted, A ");
+ expect(drafts[0]?.columns).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/lib/table/tableStructureEditorSql.ts b/apps/desktop/src/lib/table/tableStructureEditorSql.ts
index 2b038d7fbf..762d37b4eb 100644
--- a/apps/desktop/src/lib/table/tableStructureEditorSql.ts
+++ b/apps/desktop/src/lib/table/tableStructureEditorSql.ts
@@ -58,6 +58,8 @@ export interface EditableStructureIndex {
/** Parallel to `columns`: operator class for each key column (PostgreSQL). `null` means default. */
columnOpclasses?: (string | null)[];
original?: IndexInfo;
+ /** Oracle-family recovery only: the original definition remains the metadata source, but its DROP already committed. */
+ oracleOriginalMissing?: boolean;
markedForDrop: boolean;
}
@@ -68,12 +70,82 @@ export interface EditableStructureForeignKey {
refSchema: string;
refTable: string;
refColumn: string;
+ /** Oracle-family pairs are never reconstructed from the display strings. */
+ columns?: string[];
+ refColumns?: string[];
+ oracleState?: OracleForeignKeyState;
+ oracleOriginal?: OracleForeignKeyDefinition;
onUpdate: string;
onDelete: string;
original?: ForeignKeyInfo;
markedForDrop: boolean;
}
+export interface OracleForeignKeyState {
+ enabled: boolean;
+ validated: boolean;
+ deferrable: boolean;
+ initiallyDeferred: boolean;
+ rely: boolean;
+}
+
+export interface OracleForeignKeyDefinition {
+ name: string;
+ columns: string[];
+ refSchema: string;
+ refTable: string;
+ refColumns: string[];
+ onDelete: "NO ACTION" | "CASCADE" | "SET NULL";
+ state: OracleForeignKeyState;
+}
+
+export interface OracleForeignKeyChange {
+ original: OracleForeignKeyDefinition | null;
+ target: OracleForeignKeyDefinition | null;
+}
+
+export type OracleConstraintChange = {
+ original: OracleConstraintDefinition | null;
+ target: OracleConstraintDefinition | null;
+ indexPolicy?: "keep" | "drop" | "none";
+};
+
+export type OracleConstraintDefinition = { kind: "check"; definition: OracleCheckConstraint } | { kind: "unique"; definition: OracleUniqueConstraint };
+
+export interface OracleCheckConstraint {
+ name: string;
+ expression: string;
+ state: OracleForeignKeyState;
+}
+
+export interface OracleUniqueConstraint {
+ name: string;
+ columns: string[];
+ state: OracleForeignKeyState;
+ /** Exact source dictionary value: NULL, RELY, or NORELY. */
+ relyRaw: string;
+ index: {
+ owner: string;
+ name: string;
+ tableOwner: string;
+ tableName: string;
+ sharing: string;
+ metadataComplete: boolean;
+ indexType: string;
+ uniqueness: string;
+ status: string;
+ partitioned: boolean;
+ visibility: string;
+ secondary: string | null;
+ columns: string[];
+ directions: string[];
+ keyIsExpression: boolean[];
+ includedColumns: string[];
+ newNameAvailable: boolean;
+ newName?: string;
+ };
+}
+
export interface EditableStructureTrigger {
id: string;
name: string;
@@ -122,6 +194,16 @@ export interface BuildTableStructureChangeSqlOptions {
* auto-name the constraint. Ignored when the draft only replaces an
* existing primary key (renaming is out of scope). */
primaryKeyName?: string;
+ oracleForeignKeyChanges?: OracleForeignKeyChange[];
+ oracleConstraintChanges?: OracleConstraintChange[];
+ /** Ordered change to an existing Oracle-family primary key; an empty target removes it. */
+ primaryKeyChange?: {
+ name: string;
+ originalColumns: string[];
+ columns: string[];
+ oracleIndex?: { policy: "keep" | "drop" | "none"; owner: string; name: string; newName?: string };
+ oracleState?: { enabled: boolean; validated: boolean; deferrable: boolean; initiallyDeferred: boolean; rely: boolean };
+ };
}
export interface TranswarpCreateTableOptions {
diff --git a/apps/desktop/src/lib/table/tableStructureEditorState.ts b/apps/desktop/src/lib/table/tableStructureEditorState.ts
index 6663e42057..89137f28b1 100644
--- a/apps/desktop/src/lib/table/tableStructureEditorState.ts
+++ b/apps/desktop/src/lib/table/tableStructureEditorState.ts
@@ -1307,7 +1307,18 @@ export function createIndexDrafts(indexes: IndexInfo[]): EditableStructureIndex[
}));
}
-export function createForeignKeyDrafts(foreignKeys: ForeignKeyInfo[]): EditableStructureForeignKey[] {
+export function createForeignKeyDrafts(foreignKeys: ForeignKeyInfo[], databaseType?: DatabaseType): EditableStructureForeignKey[] {
+ const oracle = databaseType === "oracle" || databaseType === "oceanbase-oracle";
+ if (oracle) {
+ const definitions = new Map<string, ForeignKeyInfo>();
+ for (const row of foreignKeys) {
+ const previous = definitions.get(row.name);
+ if (previous && (previous.ref_schema !== row.ref_schema || previous.ref_table !== row.ref_table || previous.on_delete !== row.on_delete || previous.on_update !== row.on_update)) {
+ throw new Error("Inconsistent foreign key metadata. Refresh the table definition.");
+ }
+ definitions.set(row.name, row);
+ }
+ }
const groups = new Map<string, ForeignKeyInfo[]>();
for (const foreignKey of foreignKeys) {
const key = [foreignKey.name, foreignKey.ref_schema ?? "", foreignKey.ref_table, foreignKey.on_update ?? "", foreignKey.on_delete ?? ""].join("\u0000");
@@ -1328,6 +1339,7 @@ export function createForeignKeyDrafts(foreignKeys: ForeignKeyInfo[]): EditableS
refSchema: first.ref_schema ?? "",
refTable: first.ref_table,
refColumn: original.ref_column,
+ ...(oracle ? { columns: group.map((row) => row.column), refColumns: group.map((row) => row.ref_column) } : {}),
onUpdate: first.on_update ?? "",
onDelete: first.on_delete ?? "",
original,
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 16aede5975..e282568a94 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -10565,6 +10565,8 @@ export const useConnectionStore = defineStore("connection", () => {
connectionGroupOptions,
selectedConnectionGroupId,
getConfig,
+ connectionStateRevision,
+ isCurrentConnectionStateRevision,
getEtcdAccessCapabilities,
ensureEtcdAccessCapabilities,
canWriteEtcdKey,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index d79cd86a7d..ccfa11cd36 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1226,6 +1226,12 @@ export interface IndexInfo {
comment?: string | null;
/** Parallel to `columns`: true at index i means columns[i] is a raw expression, not a plain column name. */
key_is_expression?: boolean[] | null;
+ /** Parallel to `columns`: Oracle-family key ordering (`ASC` or `DESC`). */
+ key_directions?: string[] | null;
+ /** Oracle-family index visibility (`VISIBLE` or `INVISIBLE`). */
+ visibility?: string | null;
+ /** True only when expression, direction and visibility metadata are aligned and complete. */
+ key_metadata_complete?: boolean;
/** Parallel to `columns`: operator class name for each key column (PostgreSQL), if non-default. */
column_opclasses?: (string | null)[] | null;
/**
@@ -1279,6 +1285,39 @@ export interface ConstraintInfo {
initially_deferred?: boolean | null;
enabled?: boolean | null;
valid?: boolean | null;
+ oracle_metadata?: OracleConstraintMetadata | null;
+}
+
+export interface OracleConstraintMetadata {
+ metadataComplete: boolean;
+ owner: string;
+ constraintType: string | null;
+ status: string | null;
+ validated: string | null;
+ deferrable: string | null;
+ deferred: string | null;
+ rely: string | null;
+ indexOwner: string | null;
+ indexName: string | null;
+ indexSharing: string | null;
+ index: OracleConstraintIndexMetadata | null;
+}
+
+export interface OracleConstraintIndexMetadata {
+ metadataComplete: boolean;
+ owner: string;
+ tableOwner: string;
+ tableName: string;
+ indexType: string;
+ uniqueness: string;
+ status: string;
+ partitioned: boolean;
+ visibility: string;
+ secondary: string | null;
+ columns: string[];
+ directions: string[];
+ keyIsExpression: boolean[];
+ includedColumns: string[];
}
export interface PartitionInfo {
@@ -1942,6 +1981,15 @@ export interface TableStructureEditorDraft {
indexes: import("@/lib/table/tableStructureEditorSql").EditableStructureIndex[];
foreignKeys: import("@/lib/table/tableStructureEditorSql").EditableStructureForeignKey[];
constraints?: ConstraintInfo[];
+ existingPrimaryKey?: NonNullable<import("@/lib/table/tableStructureEditorSql").BuildTableStructureChangeSqlOptions["primaryKeyChange"]>;
+ oracleConstraintChange?: import("@/lib/table/tableStructureEditorSql").OracleConstraintChange;
+ oracleForeignKeyCreateRecovery?: {
+ tableName: string;
+ tableExists: boolean;
+ details: string;
+ remaining: import("@/lib/table/tableStructureEditorSql").OracleForeignKeyDefinition[];
+ uncertainSteps: string[];
+ };
constraintsLoaded?: boolean;
triggers: import("@/lib/table/tableStructureEditorSql").EditableStructureTrigger[];
triggersLoaded?: boolean;
diff --git a/crates/dbx-core/assets/docs-export.css b/crates/dbx-core/assets/docs-export.css
index 6f49b30d5c..3b14158efa 100644
--- a/crates/dbx-core/assets/docs-export.css
+++ b/crates/dbx-core/assets/docs-export.css
@@ -1,3 +1,3 @@
@font-face{font-family:"Geist Variable";font-style:normal;font-display:swap;font-weight:100 900;src:url("data:font/woff2;base64,d09GMgABAAAAAHLYABQAAAABAQgAAHJiAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGoYFG4GfHhyHTD9IVkFSh1s/TVZBUjwGYD9TVEFUgTgAhRAvfhEICvZo3iMLhEIAMIGoaAE2AiQDiQAEIAWIGgeLSQwHGyLxFWxXY6CewOalNZfPMyrYrmbcDkTU+r1qNsKGjQMg3hwT/X9SUhlDE9iTFqA63e4PtWQjlBo5goYcMo0ZqbViQ0jvqjjmPNf7mgM3sj6o9UXp+5FQOzPJbOE3Jx5hd/ytpmpjm0pYR9BzruG68ZnXxBVYEMSHMTAwnWpYTZ0wG3f74drkjkO9/6wik1904hQkUpdYDWmJLZFY0pNBEcb7IndF19PSj1kEuE38iIQcX4SK1qgisnr6gFERPc4+OgJHpJCEZJaAxtzpl8/CAc8Rzfk/exe9hCSEEEII4fAAIZilNJgFLUVSVAJFvJRHwV/VaP29R8UpddoiNaXiVOXz+nnW8vzTuOd/7TP3wUxgI76kJCdlOHSryZ2cIZquptBglVCzlLbxtmnUViK7SXY3ySbepI23Th21In7G/T/8PXD3nBn2TjlRgXtD5X9y8/sLj1BKDapUxtT7bcyW//zF1njpmb9ZiFmfWWVarEkKASLEBdHC8/y9O39WtzE54I1pQBMnULgfMHXC/yed9r1BDQhtGTCKA5+y+w8Yu+u5KTKSj4v2ymuaz5wFYG/AcWQSNAC4Gc+jnNqMoTBjlTBQYlhwJCcyUAFAfd3JRQxiCQASnZhHqyFanw2SSW3yoCX0NbQNST3t3wtitjLDMjrC5AKDqIA84tpO+X06q19d3aKW2DLteMgws7s+RPtdEF0YdkmaA4IIKEPg+LL735x+fyVLjuNAgT8DDtDyE8VJ5/zdX+xoswDARzSdN21KaWKzLNlCv34uhbKnT9eI6JKKPh395+QWaAu0BXoHtIXfybyEh3836/8kJIGEQAIRQoAECxKklEmpQGl9rGsus5371L9E9JqP7HZnzdqZmk8LlCIJoX/k9iCCRPK2rIWh3PYL4J+AWGsmndQZSiFWlgOPgZDfTBA9mlsoDTKxz8xQv/38r2Up7Xf/esMojtKulKeklnaUQvEVkpgOEEUkKHYzvaO5v32jkPtSnpPkmC+vzpmFSM1ChCEkZmZqQ1ED6jKABowZGnBonv//5Ts7529ae2sUMo7ILxzFmpQ23KS7P9QiUaXLCBVnQXUjMR6jHCDqZv81T3ETF1IgRjKJJB6jsPi8Nst2/GZ9wAogFg0Avz5FhfaXZNmjGdM4u2Ovj9m5AFmWtePzAVIVIKiqtCnTXV2t97qtAh1g0Vb5e1PN9j8EYcVLSyr9y//yvwzHWjacAi9Url26i4tdgNhdENICJO8Wq7QAeeeF4gdFn0BS8hHgRVKekUNMdEofIH3zSZ2sZTgfpHMIoWhCyJ2L0k2fq9pFpXFRea4oO5eRnseb+MCsd5v0rcACzGRv+jFSDL5rR3UVmRIi8/WOe9fUUvNIKU12j6zTMTxCIATCUNraqc9r6/omVq3JfU/2LaGEQYYiEoJIENcL3e/m91MrGjK6RrIPCSoSZQkEqSUm9d3XvQOzYiqtAy27c6EL4OPV3wvhCgBLAZ8AzmKjCObOihAGadQMEAWeVGgw8LQnvyyX5FkeJYJ28yAgeri/vhBImAZti/nf7CJ/usjUXBR6sFgmIo65HKSrbQ4BKwHpaBFUHkZoocuC6HIR7791yCyoIEMB/BLgHMA+wHoIUIDAf9gqBByCQYDnn/XrBzD/O7gICECv+OSXH37/oxc+evGj73/+zW8/+S7Nt6adaVIcEx+U7pSelL/zy7u/PqQt6yn9Gv16/Q79PmPOWDSWjWtMN06aaXPeituIHbfn7AXnJudW53bnbuce5wkX2Q/3V/eUffvB6n58v7hfqtjHOxW5EqykKn2V/ip22DscHG5Vhaq3qla1GjZ5dC1Qk2tKLX1gO3rcQbj+ZWvailucozRIw7SfrtelQ7VRa8jMn4WzT9yE5t35SjPZzLZaEi/Iwl88tn2+T5fb7by+OWCaZMNsXY/r43dlQ+1sjtJRY7XFBSme08lAz4WnUReneIGXOMMFFljhyCK8gjyMhSQjmEbIU9AY6dIlzShlFtN87E/81J/5mU/FzUQrmAVZIISPrxB7yUZST5pJO+mG4zAN52EWFiFTllKqQqwTO/ahfXvSnPT76VC5AUU87a+nfHZt3pxPrrOsJLgEIcDFG7lwf2tccvQTuBYACKDzvG7ablGymjetVNpiyi2hbMcNBVFKqMABAATg70VLW0wZVxVWAlmAUF5kCADnUQEOHqWahWkqYG7/a8tRdlwUmQBWZ9ZXlID43IrcYhBflFmlBSsU8E4Z40S9e97iwlsrtCDreF0gubh4fx8QAIKGLg4FvSio1PWEALOnvaKu9ATayqQSofhoeBACBg15iBU0JAs2hAJXV9fgIWBYNwJheiOAUHhFAhVH1sydmDMy41JSr+zsJRlVf6gY0JA2lkFDCGCjSKFiq/nDeGjwYmALWEcAt6sWsHlgRNWqVvw98jV9EDt/t6dJ4t38UWbZvNuC7zRW2/yOyRe4u3cTvMM85eBusFEccQn2k0cMrF+2bUoEc0Q0Cw35AJgLWuBptqK8NQxQJ79YEpIozULEpYRlx2qsRXMKCGV3QHai2S0OIuvP79huwNbY9k24R9KWqqkMEM061+nLuWQQ+Rm4LD/yqVz8plpK2c6Z7My6LEnXwN+csfSmq6E/Tg+OOoqCRcRH5wXQj76iMnJzL3liryh+gbvj6VbX2GODvYalBhta1eus2XcVyYCpygCPfQYhdpwFmPobyf0m0Q5fQFD2zTkYvxXNiI3Q6YbYubiiP79YtvIZGNag1Yzfw25N44dILrWOE/tGy07v+I7wtizXnozyygvx+XZSeGAY+aRs0Ynvt7pxlYldax4X5FlrG9ti3nrGhgxcWjSWT2mo37fRC6+vHq3cNEk9rWHcOUZi63kT9BnlQEKXX/YbzbHSkOe8du6C6aWTzdruMYlJOzhSYteOXvh3LrehC91O2A2R54sy2nJASFgckLmLiZqYZHoE3M551aqGndjctE57MNyLwb1Fawgyk8FeSauiw2xI7LQqYOaw6Z1QRvjO43xSsKfTaX7INVZ2SiQVWHJy2iTsVALOnv/6TlGOyNy6hNlwLTD8Z9ycKHdGvXW/3b5E9MBzDHoV/OxCnfqhwdWAu359A+AywAnAXsBaq50rhdh2RcwWcvtzgVIXcoBSbLaysi1L6dmTBP/S85VPLebSYKs6Pdh8tH4QvB3sApaqm6yJIDhz8B/rPhVTBf+52l19taC8+esGK1ZEoSUvixIU5WYbbDIvQuRKw/9mq7csbalqSiGGo9NBI48FCUopaNIXEhoXw138VzY86FYMucw285OptCEtqlyLWwukwGQNP5O8LzB3y32AUdjLUjRZWp8ZW3M1fb/czl606sIua1m64BrEsuEoidz0rjJA6/IGmTQqxkk7fH3Gr5oz3YEwT9v+jOhj/q2133BJDQg0R9WGeBLX2G5AGRFtAoRoh4eXaZdFhSI8JbHRocrBuzirxt9kXBVQZgiWpkGf2mu0uvMCjh20D/ssaczOzCZ4VW+wD2fc9SKmUyGkqbP4YC6k2goCp+MzAo4Lt32RWJiAqP8DqEaho3qyn6Cb5TR6pUKILZNAaqj1XJA6yOmhUhwRMWT/hP2vjGHAR9fML4cNG0kSCOZtzH9sYwB+KPe/rvdAE5itjuNwyb+ubUQWFj7flxVrSSYVGN0t27wtF3uCy9FcHWW++jEY8Fb5lvXJbbqUDLX3/P46HusWhwuM1t7424JxnZFwTe4341jYJbKJe7VN+OQ4Jvvq8wSXRAucgEN/t2pvr1+CcroGRq7VSUKnMU+X6l7dL6xitWr7GYTKP6m5P7l5KF5dF+wOx9ewPAD9HCw2sOG4j2pvMdD6jhG7HHhaL2xagjYzwTotcqvkJ5hDAdUYnuVhr/Viuo/do6cRrmptPFKBNc+qbXqeJepuWNYf37sd/2RMAItyJmV62GDjqh0u1dTW4h60pdVyb+75Qcor8mV2FXn8faldbosJTJT5mEPQnen8qeMs7Fa6QfdjHgvg1ZbHNP/kLDhG+RVeN1Oo5629XL4z6JZrDcegt5o+kt+0Soh7jL5r+7snuE7qZQtVm8uXM5Yh6un2HIx5OILHs9/GYu3QG/4xyE6redq069CpS7cevY474aRThgwbc94Fl113x133PfTIE89MeOO9KX/52z/+9Z8ffgoKwhAOiO6NALH/0e4smmndCW4eEWojYu3EUAfR00n4ugium4j0EF29Up+TRF+LmCEiyGlCcZbQDRPPJuAsmYbzZBLeJTPwPpmHj+US/2IEvgJJwtdkAr4hSZglEzBHELhI4nCJIDAv450Wx2EdZAq2SAoae3cABn8/NmbzNmdTttNmbLftuDoLerDH7Al73o4VU/AReWkAeznOOzpOGVOudsJO2pJm8vvqQhLCOEAtNSsjFCALMYBEU7dN+t1EY0R0oU5vIHWXObUdi5iq5Jpy/yp/CP1kTiVMt1wNzk8JkaMAEsgkAkRAQ2p2MD0UIAcqQKKrQ7ffnHGIERzuOgX9IgW0juXZQhGNRwuKe+gic9yPXG8HnOveYhkz36GCHrPiUCqrrpXW1i4aGqTYfSSUUH9gBtKvyk+pu6yjTW3bG7mshTEtVemEZSuCOo0CAyrDMKI1/N1QvnRc0NB8USn7tLRhrnrOmL8lk0oK0dFBZ5TBRXOdn0+yBP95o+fIhLiAtksPzdS6ngKbOdKRcZmnXOdaHXcuF2j68D4nj1iMgyapoQOvujO41Gxdjk5O4mR/Z2Qn7khkO8bvbqTKZU156rI2+lxl+DILdOdJ+TftWubGm6e1rpd3FQhqjgGdgcRLpSlo5lPDkdaypvbK206RbLwXO2et96Qd0U+QuC8k6RqKkXFzVsToa/MioW4uDcF1nZgYhbCo9bcs11Glipm3bVy58p42vIziqHNqZLDuD6rbS5o5jwQkQm4R97iMCvIOBCzUGkxI4f0zRt+f8ESIvRjTkyn/+FGovyoydZ9vAx+OeFVm+H5A9diI46htvsJK/eRpygPEPKK2VGtvSKCjvOotlMsI1J0jozpfaZ37G19ya1wj+1xJjaafAJwT1kdVKsy6jg/J9kAXSjiDbr7BKFxz5jJpajawGoorCce5f2bOCq8YGNnbAz0q2c+rla3hEdQqXGU0tT3Ztwm1QHMsY051861utJY5Mnm17QovFnTmRVCHDp1RJciOzlVYyxbtRxB4RdI+K3R2DsmqhDepv0jNkvAK6Iww4BIujfT7HqtA99av+RBeN+odHZqnxW5gRwlL4xGqr22Z2eBpcp7jLcwAbDBGo+soapNJg++5l9mH5xLD4jbaaZGCUq+9pMp3G7YvlzeaOYKLgISPfISwRysrsj4F1z73hyxzNABOjYken+yiDj5YnurFBWI02F61pRuf0GAESga1QgdeC0upyUWMIrjhRw2QJZyXIfA0ptobkw/rYsYcX2kUjwEuzm0WBic6iuXz3vWYmBie0oALBc5RjNgLvhkIHwR7bDyeNDNekUmpWYvLAhzF+3hK6Lj2uGcmk3xxKqCuIYOBTYBL7VZljrMl8p7zOVk/xwVWEhKq7M0Rj5Tel6LwJDESWGES4DhXsC1+FVAbSaj3L5YiYuohdJalyYWRS07cIAEG9hnMZz2OxSHSaP87LZU6f9f0aGWMa4bwrVk1gxNBWeg9bmN+yLkthL/EiGh01n5HXZr4BUbVHpvtpDivtb40D//FHIqTYeDRZnMQs2xsKx7nYsQwhcExKWEnHDPejyPWp6HL1ei7nqQFVYuLNh4jInTm85tVr9X6xjq/rC/ZV2X0aPWQ/pbxUWr0ES8d4ODau2d9dcU17qmaBR141Z3ABZDgCKDrKT1LeEfCuxAfTjObB5+mlyZ45t8xkItazLxzb/7mdbGWjTFhm/WsT9cQ+njXJMje1a8GCE4F8FgAZkLFeG/6bBZjXhjq4qdrKnQuSk9eMdNKf9BtRfW/M5loPAgG7UicUls1J7OMDi+afUcjOJ0pedfOIz5S3DOXfKO1m4xk7N+4zZ6cdEYEtcBQOsFLXyiXmv5Nz0OGfbo5MUc4VnBQowsij+KnrMWkZNFkvOusfaHBKbpunmwXdJrLpkcGf9yXDles6xbjeQQF1hlurdgl/j+3OY8axbkuvTuld6G7c04VO2ZZ3cUF1Do6kWDT5iuhBNAxV6/u0jWtNXfocZqjcT3iPqyGWmJ54bpRFea3ZEQfkq0b9ybqq3dhZfBRriuhMcVKeLslCzR0ur93Vnrw4I1+snvs5del/7W/UR7bMaetU2x1BpB4/0n4mio8RmjjAKNWMebaC3kMvb9K6+vKnAufB296rlBc20KnBxosjW2IHn1F9Fy5oXtne4400lGrcODR2ncPGVgzqBU68NKskC18ZqlkDbR4odZ2CAfw6wi/1QB66Yd4wujb7PsJ1IzXORoe4ntOucz1Du8I3dJDnzVw6c4Z9tk7eub/tJWiozCOfK1gZ6SwfsX+a/vOuVI+AGIa81fNFK5VXodjdWtmPf2tUX+dhcq/zsQ08PW1oS14YKVBxi2toT20Od79BFjrq1eNpBLWQrqPeArURFYg42gE6sWvMB5de03hyvBfOj7/ls39qYeB8N/zcSvBzYMWhtZfn7o5598XqtJvt9DNqsr/kOiFKB19/eBQIgvg598LTeotJ9Hb/DVH9tpbC6QWe38Esgn0DOU/XpyT/oS8VKJX1SFExdaHcwcHUlK8T4t+fKtecx03pNvwPlO1BcamFzrvskWuTy93xz0rPJhe7ZEJa7xpG73/+iZTwWEzzO83mp035rQLOdOgj8JyaowooDWqzXCqGsyWUafJAsN1r53gcp1sM+p9klurkweeuivfY3eyfgQIgIeoCsENS7wxmClUglY2icpp6+Cg2joC/sMVBY11BVQ6LmNb6rfwKq/cs8zt2gH8rjpQzzOfZBU1dPW/5VrWxVrH3O89kOWZJ+qcc0qF87RL4rKrKqd9z6NLXHMJc6yPjWJTN4r/iFM80GJXBbThkmpLAzsdvRBGFUPFPVpvniab7M2SLcapxx5FaEnrZUCaZT3MQVRtNgvYWg0k18KL6P9HJECYaAgEhIUNp0MHwsGB4xJA9OnDCRlBJIyJSJlgIZlBzNnC2ZFD7NnDKSggDhzgHDnicOKGwZ0HNk+edHnxpsOHDyGlABSBAiFBomDU1PiiRcPEmAlJkkIgVSpEQ0PfLOmoMuTDFChAVagQUqQIplgxqhIlMKVKIVpaXGUq0VWpxlSjhp5a9ZgaNDDQaA6+Zs245moh1aqV2DzzOGjTxkW7ds46dJDr1MlOly5i3bo56dHDVq9eCsedwHPSKYaGDOE57TQjZ51laswYa+edZ+mCC2QuusjEJZeQLrvM3g03OLrjLp577jF3330WHnjA3EMPWXjkEYnHHjP2xBMSTz1l7JkJZt54w8p779mYMsXVX8GBgImFMNAwMdERCDpY2Hh06MBxcBjj0kMnIGBDnz6CkBGMhDEmKSkOEyaESGYw5mzgbNmis2NHSq6Jq/XoXs3EwY3BM39UIfuqGhgFzcWgiIURoBZFeqj4chNBGAQYMVzgZqSpYeYUNRExJ2HGnRsHCi6c2ZPQJy59J2QVuwW66Sr6WSYsWJajQ5YT0C+Z3CUTGskUyZQ1W3Jm32NBFAIBS3PJc/Lpl9ef1lEzNlu2/L0WFYokQviYCFw8uvj02FJwpJaqWKMz/yt2CeP+UBwe8G3MHzcCOfa/aWi7j8AoRr5AV2r7wdG8jJQ/PuqGiMnbywX1UYPgJESoMOEiRIoSLUOmLNly5MqTr0jJiNnMpo0jbiPiXQS3gXADAAAAALCycXuyAAd6084t/bMQBdCVSxPImfy/+o4SBP9vxzGOjcLxeRKpZEnKfBr3fkMeS/8/l8Y0DXNwOEUNMSJapbeBuTaGBPvrfNX8F/m+w1GFvvWGIBJStvslHC1we9zllP1+KZcOiQycKY7yI9pRcRHLf6/vxOz7aOjZYUzyxtTjlJECmJOzVi7+nTjz5tJyqDtLW1YKFcci5VUouKgwPxP64zCWgGYh8bWYS6pLKyD8sm4GgVfhwNc7/zJwMdFR4NGt2lyWTh6iMovRt+dXRuxpjsC77nnGZvultSrlL+Sdh4YNsELBgMBNtjVL0gbwh1CQRHgIz2EuewHfJJhXcdUPL1H05KtwQhwMx2B+OMrTkTABqjZ3vV44gRBzjGZD1xKrcaOqJVZN68fPBOw8dSsi+/O0zsEgv1oOaPj+FBogrBBwCB+ikLgLYZdX2AA4SMr57kZ/wGv7q1UPqILzwveeEYIiKUx/x4jt6PcjxlJnCpqQiWgsTIUsJxFTBPEEyWyiTBQXP9UCPVNCNLSKMxybrSMwzkVMKgsDOWlIUzsovbwHFWZRikzTE8Tq5GLULQhPoKWgAdlYSdbwVsywW5tA4xPbGkBJEg0zyR/jT7Ma5DyAHHdhufErrwpJI+75thxcNMb8EJP13tJLMDsiqPyhPPlzLg9y87iYwE1PZ6np8IfxCBscGsbK8uYIMWttiGj5xywAlwsgJqV/Bh/uAsqj0xYh1PJge9nCWUvEhjwm+Kz+mTLDQHREQzjY0pMolZMqFTQyaClUKlc/+DvPJDdbmSSFEqQplkC9Pld0GILjaqKa9yLZMGAeBhgFSH4ICTc3RSBQQh8SKWoABtzAWmUTDEEOtvrCQkxwvJKnUVmqGdoaAihyNL/nDGJBJwhMML9ZhFI0SeegVh1d8eI+S+drmUqJDXiG7oqaruSr/a6YppEp4ssQAp4LDrgWsA2w/A/+nvHNzLvAae7Nh+14xMJHDT+h62lHn9f/Dux8D65+CCOflfHncPSr/0v3ZxwBzwEC8JZdHTXRbe56zHt44Aj+9Phx51/df6NOD4/YRnVj2NjQueyFJVfMV/uvtV+zXgtcZ35QdUN6S3/LeAu/rRznjgvHpeO6O+DTsLtVd/l3hXc9d4P3Ku/p7ssfFH8FP3Q+an4UfeJ90v+08Dv2s2vPGp9xn41NMH+onmiccE5MPi/8uexl9UvpS/lL02vpa/1rw2vza+i1+3XP69E38AjOD8/GtHu1N3670fjWf+bNW82Hzc/++7D9uHO/89KF8Yv5/YmLN14Sq6XqyctTV45due7KXVfFg56DE9eI9DUNf6PUmLpx1e2+drk9pCf0Qf3+e+GPBh4ClpNRDgwGoG+e5T/32vxv8/0Xf6/S/ohuJ+vGjqN1sAsAPHxeftXaYA0wfwErM6g4HW5h0EcCpYLcBRXk7iQBXB5fvafgHF/G5GlwuyPu8jG75oiASBhCLuTjH///ArQtziGBlwFkYkYBNiOgtfZ8gOUIwHbYtbcXVCEA9I9mMeK+rwIkOU+hEmQoUacNAuBkckC6YirnNkxX/hzbEcsiIM9yG2Y76VbMTdJ150tWLCyydXG13XFBsFgDPaRCerlXYyulmr7STiFRSDjw0mynn+bIyficymhqoSqCU3Ambr5ZQIpJKWlGWpEupDcZSO5cNTNdvLp0wP/pwGaOvG20uzgSdxLgDWecokeKSMmFO5NeXVcY/yGc9InA/2fSkHn+j3kA/33fMQDfP97lnlRZsoGzbz6pYkeZc4AoAdd5agqADzFo9V4eCO92AbcmfeO0Z875MxR4Y8J1N4z5ywmXHXfeSaf85D8/nPUaQmDRwSWgT8iAhJQJkilzduwpOHDkxJ0HT1583HbBeI7BtWRQChQkRBi1aDFiJUmlMUuaDAWKFCuhVaZKtRq1Gtz01a1EYNAZ//N/k6Z88y5LvDfXo0ThQ67iUwA+tS+G/OKtkVzNHi0e22mHXYbRYCgYqOiY2PTw6OIzImJIjMOMNQuWbFj5h4wbZy5ceZMrpTKNL3/T+QkQLEq4CJFmipdghlDpcmTKkifbv3JVKjdbhTqF6tnKz1zE44GH7rjnvrsQYDEMIsBEdCEJctSXvvbyzWFnMeESO0WhCuw0RepFnzMUi492lhL6V8A5SrXOvnaeZBfCLtBM7RzYRVqoF4tdsgl1Z9F5cL65Rf1nDyw8F1h+JMCwEqhXAaDB+riX8HIz6UgSoaq86q6GxqUyATQaHhsLoGk6alKN1cjE1a2cukzw42JQ02px9aXmOnHy0evjUSUjqj52pav6VMUaFpIWr0O5HGXSUTP19KTUNW/is9SXsU6qkSSboV1kcHkiAgqi61MbEUY1JmNiyPPNsbG2WeXOTZJ/xo2goIleZCB0BVqtjrvZqsCl82v22TVlGu9yyCPII0vMYgfcrH337LZTKVImpwPRer2U+1XgI1dSmJ1CczXN4jivNxEhQj/2I54yfroPzYnNxm5na40dwxAw3iAFXs8ZwnJprelWCtPQH9M+s7lPcs+qalZJcnZRLgbpjEUSGbc52qXdlkmUabPZA21JpapONB7sksg+KnQf32eV4R8VX/veHaFDawevYZvzSQWExSavMyAAH/PAgGYvpdnPmRkS/KZOq0ZmSeXzLuggInw4JuKiv7nl34tZKZZR5MJv5OY/t6yWJH8XoBIuxX46dLNzeqZ9VRdUE37Kv96EhodUx6sFxi/MPqXYR96p1+K54zvWVzrrNPSy5zDWs1IcT5ApACPWgGUu32461R+iAl9qzbAOrfWVm4IpqzJ2KXTKr0YvMxObqPnzrFXNNYI83vp2aOQZQx4EEn72bVDlB6J8kISMZsrOiuW3XD2DseyYTg8vIyWpwlfxrO6yBI56hU5ymu8vH2UhDCD51v2TTyX7CVsDnTi4Vd1seWMtj4ppLvhAGu+/K8SWyXkWB/PIDLJ385M9jOsCaEDaAOlSe67WDiL3k6XofjdwGGeGsxq5zU3s+MYnrUTx+jH3JNjm33j9Fwa7YnBd4Z4qF59A/bK50uObRo3iz19umCA/Q5PkVojOdMyfnqL0sIRTDXrL4liNfLmhyD5S9dKM3yrsUbGRQUetYlsHnPApFwUtTEwYzbJ/DZjBzOmBNtGA7Mfk6GvPl10Q64EYgRCS5tiuyyZQ5HKnt/e5l3Pylkq1Pitwzbn4UD78IX0/VuSR8t3XwdE2MyRPHt9U5rPM4/cGw2z8Y8ivlHTmIWruSJL0rT/hVPb9mdPZo+VQkM1lJLKsbxhosyluIO+fiMKJfUd20ByUB62e+68hC5fr1Ur2Wq3vLG90nI/zstRLoJxJ2eJy8LGb5QHJ/zD2XPECErA3XxiZ3+0NIwkbltlZM/k7XcsQjecnUb2VVjLKR9gx5bnACGRoSRdoG5bVT2qIwJGSKXcfTdnmuPogxlR7seLDLPfV7z/fGh5kdVFlFtavaJz8ymNW5h37lVsDbAuZqNJZe2tnTa9yK70SNGt6eQleF9lPNFvbhOzjcZT+9O1WtX/ycSmhSJJikFmKyq3qfK9cftx7hayCwGO+w8AAptjDQBA1vNJxSkh56V8whCwDAsFOV96PglHmO/oX/nzRTwO1jMs/7IKLqd85J11Hd/14sitY0F1Hm1iG6irDu6Pu+5sS0XuVYt2qvxejAdSYnmX5Z3FfOfMv2cPUfe+LFYlu2Eq3k322+6BosLemdZwWvFryufuM0iMtFB89InssR301eXGVe6VuNeUua55CfXP6TJhQ7oEFy73dnDn/Uo3tO4MMrdZyjq26zCua4wup6/PGROa0kFAzPB+jGK1Mr+NcuIptUK2PxIWyQonKxTvvmT3nslPvm3pcaRGrVhGU6rtc7S3P8OmEBjyH3/A0YD++MkCn5Davzx1HZdpUrX9vrTMuc5rmT4L7IJ5KciK+78vYmwc31duK7WFkkJowROhC9BeRGzaXJfarVXNy+Zoz9goYSJ+Lix+NRRxMqHkSlkXfJ9yPoCGpTftLf01+lCIfhgX3u6vgQphBNhBq93bToX9astcbjc57axnt2anlUi8VDCSXKLY5FNWGCCuYU8p9vDtCe1mjAR+kLRKNTX/RWbPzzEnSt+yKR30TGyE6yUPCTHsLOVRi+AvQl8bAnRnclobOwT8LyhmPdxMTKYGa9I8fMLjV9WSSCDVnIB9LNPRsM/uLU+WaWCZ3nBipfZ2RJJnYWqsmDMJScpBNbcOA6i7JFMf3tMP2oLAX9+2T9O6dhGTMds87JpK4Dza8N6qRNv85fzmdL9p3yH414qIEzrYQqc5eYbLK/D+Vkq+ZR6tVjyssr01uaqqz1OAVymIYImnaJ+2ja7DCvdx6NDYp0+V8g+EtU+32dZPPKcE14+7qQspnPNt+8sNdmACFuaq6k6J5jvw04cER/59B9TLmC4XqTb9KiTQVDiTCRhWOPJk9/2gLks52cP0e17n4Szu3u8ur03ixnMZa5YSyyltT2+lASYoAuY00pm0m55HFwYCXPd0KI08NQ8a2rJZadc0f1nlamoVszs0snxGUl1/aHNJh0jixwlQfpD6pT3W+iFV6ZUStlqZC+OWONOdmKiCN1bO6OUf/HlGMoiE+8ozfxlfLdCLkQs6qTKtgJzmbgQ7DAoMzox63o8O6VXvZE22L/NTKuLk6sSLmDuiM44v34Dpz0wh7DEvUVZ3FGIMoRiAW7VDY5JyTRTWMuc2wWqeS3AgizXTroQ32otkQJ4aBXF5XFueRYnEW353E4ebC6zi9LRnHVCLuZ982iCcxUcA+spGBpQXsMyuWtmZhShrIdnvxtbrz2lwuhqz3h87fzu75mWVVy9a5Rb9Kw+azqOw5yfue0zneMPxjowE21YVZHa0D2nq1MUzpUIvuy706K8JfaTkVhUiB/pzhPHlO4afibeqqgzVVx8T8maKZf5tfXHlx7i7nuxud5Rvf4+wBwf2tqhmnBb8uPBQljS9MRoFg2ZnbCfaf9XH6X6mEI28ssvVeDcjQMaCZudK8IpIU8SwYV8aI5LqI7hXdY2e8o5hap1YTRmyG7iO8WoWaUrp/D4qZ8Z1B8vDoKHlkZ3J8zfZf9MvCjGJHdyCEZlDN6nBYsyqDoJ3prkJPmFHodIwuNwPNzFdbnx3c0b/r8Kbe+I0rVmzc1C1KjJcn+Qud+zkaF/11OGHri23vseBja+LWHEsDhczU9jh+pK/PcXRHRso3ZkB7CqEQoxAN+SPuFCla63J3rE47SFNELYnPfcsjyZoZj50+FYDHhCA6409+7vS+ZL/CLHPWHr+jgM2E00b1EAgNMECsLQCh9k7/O/tGt8dEyoQxQ6axa6BCxt/dc9MdSf33gNN3bEG1mKmJ7LNs3epavcGpvBtW3MTStKFh/8zqYDIFypnpXUHX4dFR15FdyemMKBq3+uGSKO3Fc4hqVTisWp1DcYwVjrO+inmgjJnd2ek4MjCIX/GVlqUm9dn0QRr/2Rhn/NWT8Hgqs37wSS+ZtctX017ZmhxOEllcusZLy1Zn7EAzc3+yXZxGdYkhGflEecETFIUgELXzngBV++mz7hgIhlO0+yw9Ntm2OJNxJr/df/K+WlCtY8mdlrwdCcfRbA4/ujM7k0Nz2NFcwvIYJAkMlmyuFJzJtEQdyTni5R5SuiZDbFaaUIOkQ07GBTQzRY4+mbYLFrfhllZ3EMJ1DKjsvYDuWV2h8R1WxT+gCMhgdMH4KyCa6VlisPYzbCFGqgOjOBqppQZiN/3gt6XL3eVdEqFNoVeHe6QYMaSF0nPNIUZYCGMcBewyypp+I0m8NFiR07eRMqMpPCQG5yse0Tz66xFIYnqmTOYJ9zv+mE/rDEATn6yamBRUgDNpD7L3s2lgBL4/ajcuJneRiU89Ptn9vZzdDzDfJF91573aMNCQ80v8XTrvRFOIgqvzvx/L+6tDz+hgM6gPLqsZot+Ph5iNNHjM8nQ5UJR0+ZknmwOMkEl14XTSnGJ8JBrO9I2kvyy9wqzAxQsXsGfEst3dfpLFxhQ4n2dt4x5rTN7cZGkHT1lk2m5TiyBn0+GTIsB0KKr6+aHgHKZjcSSQHhocqtk7YfQk2nnYIZTNQyT1xyoGRMa86bPWiH5Eu5ymtct6UczSY8YnJ1SzJp+mfBY5LD4bopVbx8L/Qy0ZTqdNZyBw4F+g8ol7Z5HOGfqHOF6usqYR1TKfTxR8cnAScfVEoq4cJLGI2AGjnh1EOwCrAO9HdMtpWresH8UNMaHOPR1grMfUSsydi0ahY5Ol21oQTesSYx2ggGVJIYplPh8p+sVjUQTagvfoGSdGhkNiLtlh7mgK6o1NAbOow+rJRSOeHvBJZ5Wkb1XXyGr91hXe+NwyLDZ/nZNa1nIwfnEBNmDQjZKUbiQ0g6mCIhPe5OOtWre1lMSoaMxFhTDMHfH58MwE0gIu/GNog3WI3U7jROP3LOWBs7gpDkSHNKkcg+WpAOPFNwyhTo3WL/BK5EgO0o46nJqRDASrg7I6mvqf0SOYFeFFqDsGYuewCVQosjpjHg8RAzEztM3uA/+31Ao1hJQf1vlog0uJqc0uF64HVCldCvKX4621N5osaL71czv+gVzPqx9+77t7jnlPXs8OTINB0QZ5Fh1ZCBaK8PSZcM3a8ELvFciMb/E7FiAXVjyNNLVpXCJeyOyjEbvKruIkG2CxgTbYJKSOk2QhHQYiwcaH+iTBDQIDoeCG1b7n0ZJKuJRvIJx4kVWADYgT+RTFGNaPYB+tW16wkxg1ISopVzGI3v+4Om/xS1qN3kCmXOIVTxRRVEQKrHV5a04z9n9uic52dqKuRQS3sgMQ1BJAWlvqRf3X0xRf40q4OqJCiopcGpI3+snOz1X+KlZYqgADq1VKRANLLsHXhqjBrOX0vNNrkLVOUI7YGNULX8pbTJx/28G/tSUAQb3CGRHNAwAxpfjsDSPzEdiollMyvvPxNhXgFWCJ9uyQF2CsOmd1/yNPv3UshBV5BXVCWy7cZQ2K2114gFF9QCvXRJprzeinLnaAJxRiwxSIuYYourvkUGIg7UF9fms+2B+WSL3K2Lq+KTNlJmmDWdjrZGnbyDajxaToOGFU2uzQNcC3o5B1Dp3Pvt0UiYvO4g44+C+Qsd6Yjza6lHaNyUbZ9HQptW6GaQ5ZwZ0hXc3DJ3ddwzaceMx6y46vOB6+28uPRye7aHzP/sEBDv9gvpqXmD678WxqYPZfixK7P97zMcjsxw31BxNNDX+fG/3d8RXu+p/Q715RgIwmRi34oeOTH8DB2kn5vVb7Ec1gRXNeQ/1Nm2/2ekJtsmNWZEXR9PwF+kUXC8obmhoTg19prWs5VZ6S/ZMlpV5wvVYdiVGUlAhXJE4qz2kWHJe7nBDYnpTS2xJE71/uff71UPcpicKZ/hUh9PDICHpkRdgfYMWiUf1wie/3RpP7tmjaVtOw0UCKWtEt+T8ZwfHifbie96PJFp0BeodoamKgRzX/5HMWltf+3xHhdy2whRgF2U3LRrGsTBk1KFsIGsG4cWkiy99CAzlzYtVgfiDIYJiDKkTkqr4hDumEXGpabfJIDCqr2ma1KgZDjPnkkkSvPStS+XSwh6KKS/3z01kChePjErDpkUIi8XX0bjAh+Ij/v3k08GA6+iXGEB5iLPPrEUeAdki5downl5ACRlS0Y0eCqZFx39rRcq6tz6gbtNlMg4sNoJ1JDdu129PB+ofNY70wGc9Gy/HQ3OOHfJJS+2c9WLaln2LLrD06bT9GmIaH9TavNRgkJRwbwm0XO7itNomE67AJwfODui+GLxMpj9A3iGB6ZEZxYwrsmc6JDrjT4oqkHCVlf8MjYbU6kJZaLBmpKqCGMed7ZZEl4ZTLAneOdzi9ZNSMGD14KOjFjUjUTERhm1ojs+hQxKqTaWxqUMANDvrLoPCcF67Lk2M7QB9SDWftFkuPQT+EE6bhIb0tNOxW7EmF6h4waXMGk1WCcYQ2mYTrtLVKJRYhxyGRcu0ID7Qy3aMh4+GREeOR0bDbQ0cbDo+OcEJur4/et6UnYf+wT9/+6e4Z+0AhvZE+V/x73CrsD+7xaT8iEjSwUqherf/DM7d9L1nWtzmLP13k7YItkMf2OW8tx2KSX90EVecfcN/N3nbPvR2JuXPhn97Bvr5YjO612SSuvD6rrq3dZkVF9tbwL5LFZpa4wMSi/3wPo/C9OHCubnuL77QeWMPCt/e+orT1PFQm1lWzpciloBU1axGDVKx8ecOTx8uHtHBQ63rykPRblT2f01Xf4Gmt0dTU19RUfb3IpLDscgTSaU23Osw4N+tcmlSUEZyGwy/KDl81flZ6K8PP7NXuBDu1Xla5+VKAy2rZwCELWurZzxmMvvvEe+OC5OmBaqPOoTY5LeCwVkXWucX/4kI2fdr4yamSSObmHwPJkKF2sbSXPK6ltHWrelgTFrBbG4xrFS0PGv64xnYwKwzGqx0W155QbG9xwyqVGu62BuONXMsHjopH2Uca3tUJzxl/5yqNfgMGHbHlWVBHmUqVQjGkUG6PAB5z2wvjcy8k0gfrG8BFO1hxh0nMIoB8MTNAcaBjrUx9JHVPgLi3mmndjDT/F/8rPiU9OM2BtzAs/0PnANVQrZCfy4zs/3C+PRcqp03Z9Z+xXFHEgBOOubYQgwGZ0n0aDErIVBG98KnRY0teV+S+lj1H3/TYEtX1bjnqmnj04WPnVpCOObnZHyd11r7RYnSwkTxYZ67SIpNK2LdCAqenzFN9fwnUC/dKkC2EsHAPeDfvjH0muuECy/Gu6X/tHOY6XA6sB0pHo5Q4oG9gwVLA7jbpIG/H3CGuEyCTXcTHszw8MP3e14973nU0f/pJ8fRPjMUgecBhNFbfeEF3lP198wgMI2Q47vS2Lv+2Kb7p2+V2Xufqi1QTxCxYoIg6IM8XeefNMxxReWCIPAIEj7wRMg8SyJWifT7vi7pCuuI8AXIWoaZC+ShoDCIGLkQvWA++dxBwSpe6FevBmo+Fs+rTtZGHWCB1ZLf+Mfy+Lf/Y2fGx9ar9Nmh1vGeOoQSgOll2hAoy5kcZ84MUF4DyJDPXKf7uwXO7MqVSoRxSKPQUfxYx68Hpfo+vPnEpwpImpabFsb7y+xi6WtkyrL3KeitFnEnELgA1qEXKB8qNo3+k/YcWZ0xHJ5YeghOLjwYifxigOpZ4UZXocPvzUxK/+hYd1S5wKxH5QMxsVuCi/Q/TohjzfYattHKyWqbpi3Va1mz0T3g2qTIz8u2BTnTtuoCYMlf+/KmFzk9ZkYKW3CJh+zuNkSK52AJwbmY8ERHVWPUQOnCF0eiK+t0KjM1FOjRImJQfekeS551bwB76B52Xdr6ZIg2kDKnKe+Zr2t7SIYV16sWBz3SG7HE2/zhX8MAWEEgtWbEmbDRqwjkx+tNMTAO6FBiZkKRITcF+xiqL2iySdFc2mtsJJlLs4QW4bffxm3fNHWRohGPQh3kqR9rHWGGTaBov/lVgAtvLXKWhVkc7/4FdSxtFrQo4ymlUdfS2NFXjpdy6fz1fKXzDagR+V+DcoM5Nqzc4Xer16fQGdaRr/S5Z73KqN6D1HFKXaSOJtpxeL4oqdotOl20jUoUU4hkduohC1mU0ymLwrZMSXIlF78r37RJYrL0nsLmPWkjOfeHziZiQYpQAGJ7XZAlxXJDQaEQhKSHYo1uw66NbuNkc1yoTOp2yO64xm7s0iNsPYqJL2wYLk1pzR2tj3a/ORhM6Jhp/TGZ8o0JwtcEFGDOrYqopU+USk7Kf7nRMHzvG9axTi7hxbXyeiMD51a0hAqG1vV1os/FbqZUvtBnWUhNYSzGH29jc3MjlsADv+/bnPvcfQWQgSkWPsukklSRv3Bhwk2X83hqH5UfwflS3jO4IX70+TqVqkzZdrY5rtaLodbWbfI2Fe3WIxxu6yrW+Ggc/fvVY08SGDbWN6ze01Qa5nayVanZK7TX/vgRJaCm+tB6jJvSWXoYlwEiKbARbLUGrxS1N7/tsPGVkeVzMt8q1qmBGYncOqM3JVUEGJoDsbDnkMEgXfUGY2Ev8FRltKyHVG4MDYvA0E+5VOhOCjW43f5Mr2auETWmNJVVsDjGYZh+lhUOO9jUed/uaEA4bA5EiS4RRgKL9PYZTt/DdC7AND4cfXoABT89ifcI0v6xmBO+eYSKNamUwLtM74mIZOZic83fUsY27+hzH4KtXng8/Emrr//8jATBzBzFDjOwlZghZ87fkiv97PCYeV4wR80lgff/tx93pwcFMbypnk2SAjgurtK6ulJXs2dCzVZj9O+Itt9FLuYtvr3sm9PbniLU84cybRfDRhBQkDvBBhr+Bs3reIC4UnCboYCD93y39H6rzGAW1LymiPba0lvv27t2b9cRH5DsC8Av0bBj/0y1gvXKyqZexp+unwqbAmdIAf9jn94cQ1Bfy+3xhxCDYqnTfKpAdoKf7wOkDyO6/ugUf7CONHkqFYkiUkhffsS9uX68fPunKRIYUCp5/kAfYpRLBhF8SG1zQ7gutikGrgJ0P0kBICq331lvx5ML7ewwOhw0Oi0ALPdNs/geJtwCzgE6TNcq7O6G7dLL0ixtQMstYhUU6ZmmuTF6D86s7iu6YhWVatpxvBK3D9kI7WOrSy14q5ZZWFf1rrbY1v1L8EtesDrTuDwfDYOOX4nUHzds/rBG/WKb3qvhExNyQ9x1P8noVrJpqtwceWCYncgSYe+NnOiQkWDf4cnOB84cNX72yiwCswgsIMCsE/Odg1p4NK9qzYHV7OmxYyoQ/Av3JdeAMt4QDbWkWTuJzFoBOqUfwimUz3NrBDwnXngVd7emwYAkTVgUN2hPg3p7181J7+s8bS5g/p0HJEgLNz5iaDA5mzLnrkq49C463p8OZtFdgwqUbe/S3wd18DvyWOCkSQzrRVulE/dKJDiZeK0dXE6VfOAJe0sPKTAv0fDqZsynYVwcWOJxICnL49ydhuu6V3teH1RS5PejlDrOB4goMMwqEDQXWCM8u/JHcYd6m5CcwnOEQXpTmcJJPZJgzQgTtI2hEeAjm663EtFJ2xlJh2Z6U6dLF+rKafDeTXqpRV5vUFtBxqnXoaUYdBtRZRHZ5l7gk5S9hoHYk8zWZNFrnatPe07X9sXDa/3Y6mtP5q9PVne7ZTs//ud4RN59lN/j/OZV75F65T+6XB+RBHMLzZiCv0nQCpj20l/bRfjpAB+kQBsxO+S136Y8YqJ3L8Ojk/P1ZIvfJSBoeOr4KYBbfhmO6sY4B8wnGTgMXZ4+QnEtFXAL4c2Z/2QNcX6LF7gnbHpJ522sG9Frkt7b21AigV/+pg89NfcYN80IHYhJBLNIhDnEF/zc99+59DI03sfimH3z5Et7tlMJvXY36gacB/o8A5M7qcbtbeLKRh97CO2rnjguw70/Jyox792UUDS/0VZxceE0jfcpCfvrB4+uCknek4OT5/GpA3ySXm3v0G3MMVKJcOE0jPTPjgR9RyKk4uVMuK52e/gayaxfknUWQcflgujEnp3B/9VMC2Nx2KnYL8t7JEYSdxvuoxoj59N9qfIqADXsAB/ArYh4IHww105ABhPGUjDwsE5r7eqxLlSgf1I7RKCWp5SW1JFJiTvm5HnlZP7njbxT2+zIbO46hBLk1o8mIHBfAw7s/C3AxS+vZPPbEpsSb6uwItmE4sYzYsYzlsCo4Z/zTZL0xw60IAF+njZcA1wWAQhBFNzgvQOITm8PleaezlKBiWfWWGXkHQQLaFdD8AOWNZSgEUVSZ0QCJTzThvPW3miCtU90K5M+MOfkm/10Wmi7OpIcZPf1ykHEw2z9lfQrRRauVx42btiPX73DMzguvb58jBmQmT997W4vMT1LIMuFNGJZXrtKnr1iJXBrhFmvMA0/Fi+p4qWbzxarZqnNksD9F3d+ntBjw/2/HRQDkBIBZrLkLkiBbhRYLjWTBZLPucoNHPGdF2WZE0eaBbM+hDAcPX6kyKb8K1co6UP31qYaNTTFqts2zhbTH28MhPZQPx7tF9+qFfapv6iv6tn6sPzZ9LGr1rM+2vo1+yP/52MEYO2aN9QIh/hesjt+JvwqPwoXk7cQriXcQM4k8Yod129/BSmTls6pZ8+zv27+w/2q/Zy9NWJMz9mfIH8VnJvGpOccTHc93vNbxbp0knTydKp3R6UXnPZwlaX3p99xfsv/OfjJTmKFm9FR0OUlPLXxl4a/mf5z/Z/7j/IMUk7LS75b8TnFmNr4acz9X+sVsm5kq+9/qq/n18u/2apzIxbg8V+ZOVNxYcW/FkxWvVvxK/Qf1n9f/XP9//bOFwkJ9QemAldMrHZWBymTlUOWyyk2VSys3VO6owqvKqpqrJFXmqtVVG6reVgdXZ6qfqqHWtNbsq1lbs7nmZM39mu+1tNqmWmktXOuuXVH7RO3/64LqvHXL6p6se1D3ru7vemZ9VT2/XlOP10fql9Y/XP+xwa/B3zDYsLRha8PhhvMNzxu+sUQsHsvI8rEmWDtZO1hjrOeNRONfFwUv6mua37SlmdIsah5u3tC8rHlr82ALvWWw5Tu2L/sAe5T9iP2Jw+LYOTHOUs6DnIOc71yC28Tdw93Lvcp9zv3Ko/CqeFJeiDfNO8+7wyf41XwvP8lfzF/F38Pv4/fzB/hn+Ff49/mv+N8EdDMYgtV5gAFUQLAI8EUDaq51CpAgAAQiAMRUv/RyxL+2cyUmwq7OhEJga3IHGnfsvT33Wcey8Xmu4CGd/pcHcHnx7P3RFm8rQIIVICAiAJw6gHcdKAhhZP8RfWd5kCO7sdZ3Hy2N0LH2d6elLFmBMErhHY8bLwRPfdS8i+xHnoIUHBlYU/XzR+66a4Y/LTMXbxm/A3+Xxi8UVuWVlXf3siYU2jIeeOB06gAIj7sQuhxY2LeAzfhrtzBPK90oH8mOrwm/Pf/mNfDkg//+7xGpBcel4zEzSh4INJdIAidIZTStoEUXoLegdDBCoA6UtZGBSsmJUtKMincx1cQhuog92ivQ07NFPnN9f2nY7nDixEScH0DPiygTI+sxC7fZp55aB1zTRqYBoWhWGVSMilFggQedo0WsbxyeS97SsoUBaSRve79mqZUFyw+5xnLG2Fl4Xl+44Nod7zwn6CC5uGrrrq5BxSjYL+d4SiQG5nCbocgSvtONxGD5Au5tqVf30oynjavM7D72SEYGmhFtWsj/oqo2W89tQr0iwfKXj7/GjoCfRENpEqdMkE53igMahKUwMBUl41iSMv1zvtfTLXsGdBcF7+oYMN84qLInVpJSov0DrNen9N8qC2yHfjy4Gbq9WVujlxGweVwYhZ4C1BYKgM9FXuD0QWGvy/+IC8uZvay3eP96cOS3WdpjrilwGQaLj+P6NZq8+zwyEor1ZsQemYFf8sPwlNIHmn+u4H91Aa/Ee2XAzuy6676VLvJ33GH/QEwByILq2i7ffux/N218U+cwXANXevv7LY+1ABrbI6rBr87VaxmVp5K27LbnVGq1H9/xBJUVK6wR3WpB8LjGvCPxOE2q2w820jkfh80d75KQZW1Uzp3ed3TREgH2WkrPiOUjsvPo0p29NB3RyOjt/EEmM2Epo3b8AQ4MEzL0bg2JU+lwE+qDEILPHJ9S0Fjg0ulTvN0SWlMgBCFeQcnHBe9saupcZVgPvLkZqGsYHZkIysQgTEyKRX6dEqyce3aZ1vrlNrOg+AXs3FCcmyt7lD+pO+CAm6a4jYC50JBZQHowihMKnzzq4EUp5F1ORLhYZyJmREJMSgC3Gh8CpR8XZR8ajRb4kgkSCXSNiqMcc+BRautJ5TNnPP82Kfd1FtnPUxB/6C+hvRNRutR/ouRIkZIO4TISVlbvUwYf+MyEI8xNLMHf3N/PBIoG/y4wDan66YQG89tHU/5f7jcL3M/QMXTY850PKIBLcsGagFKlVOf91M7e3kZAWCowCwPqk3XQj8PwIZAO6nEd+rr/5AVuaem9lYCkcvwiWFsrYnTTbX6v8ZNPOv/v3DGHTPba4ZulvYSTI6EfwIEH2QN5rnTPUncVCtDQ4FyA8dlF/u4zTx9Rl68HCuG7sau5suwyNI58PAnjUm/k7UxaiDWFFiyReUq2QueLFG2ys0qermigELINTKc2TQkhmInWfPA2bSeqFNGChnI38P0kRDCm/n3WopS3MjAKa62X8Ye/22t4O4NQ6YC3AqEfCzc3/1z0qOG1ezN97e5zyEgw1qUIcafepVagq+zkNny95mMEioRwq3RrheXEZNtUvGB+2+PR9QPuQ5kZEWVy0E6RlCy1OB+sug1NojsWCInp6xPiFwrLYibz7l62PM4FM9FDExa3NLlpHmzncuhS8tsVU/W7ElEz9g57IvGhzEwd9vGTg1DS+NWFW3pFQRXoMaKbArSMKaDjf/sxS8i+hq0pZ0TYMRov2AxtVu4N3Ucl/QVkpAyYfQ+kK4V12z8n+3Qlh5bqxbY5EgZiQANUu/qhp0Z9e+763uBsgLlazp/4uiTE1oH9sre3zBB5JVh8MmM575cgK2WBGSzbZ8PHmzU2Hky9xDVaLKbHduG8UVgebSZRlSus57r/HNh7vep5rOCxlRtkKabDNsxjm6JzrDAbfPOKSMaoSDo1uFm6uc1H63aykAti9ozjw+XERohXsvw8Mtmm2976gA8NZYPCEcVj3WxAijiySah+KvgwWmlk048JG1Y+NQhzIlhN5tCjciwRk0WbCoUCOTUwwrW6Ao0u49B9kcowKHn8mp4be4cGFKBkFAlmsaq49UNjr2DWefKdYVZY0fNIoA5syOMEDZa+CGMwinYK93VV3Pi1/Vyd5+i5Rd6MC8gqrHUjJ10qIaJtyVBuLStHaStsKYElpx0OntGOe+tdfWUFE4hyYByBDDNEWWl+APnmRsmvEVsHoelCCyNoyeq6FKP0YpVAgqscJCZEp03gfrhfMBw3jWMfbhVlX66EQwVoLJRMgMvRoLUrX31j0AkrMaiDSk2xdIFmgkN6kGvq6pEcc6m6wLyGwFF9lye9thHoqtvwKdpcldiW02yknZwoU06qOxLUgW3PGqHMyTv8aCsg7VRpyk2dtwZbqbEkVMTccmQc51ukYELTQ3tu1D8JXxNhsXwPOyAapq/Os+39mUztnPJdfmZ3/aoUDvl4ijpEsJfbARiKMBZIGzA/6OAvgILRe/aDcXLWYXxbMCFRmYoAqMc1Q0Qfr2341F+1qO6ZqGPGehXJ2xt2kpAA2z8TfUURWz/m16lW7u7DD6eEty3igvPHFceY1MEss8CKdCtTE3mXMxEp1jsRW2QJlERDg6CN/Dt43FIeFI+0//vAsPfIofuLQI9mbfUFfhOkaVMf+affP+us0gdT3lXgOvQvc/uXFm8uxYr7YNbNMvvXysqK94Ex4uwjItva9a7OE4L0WUxYn/hv77l7s8GLOuegwwE2+Bw6oA5Nu7v8uoXpDzvxDn6bXRPLgLnN0uLK4b+nYZce9ceEvuksVwkCaC3OPESHwj7QsXdnJgOiHNZhCtYlnkG5sa7B3PSerD+k3WExQoC4+En47LJmxLYfhgGE3Pk1X60CW+mG+Hzlt/GLd20CD0uP5J6UW3hPFwBvCxfH+UIcWYpECLLTnQuaqlvzeBhHl051v4Xc3Dsn4CEkCVzwIg228/C8FkdjD4dmk0DO1hCbI9t1OJyIKM1/vMBbmxMCPQlBE6fz6EMdubH/+siVg/76aDBwo1GPx6XK9kSdw8rSc+WFxqby0x8lBVZgJ8fBRFhK7t+C6B0xVERnr+zOyaDzzQrngvEP9fUKWOSJy7Dbz017xTYL1FYcwo9SqLuUCUkxvwnZVqLCaGczHddLFDJXYuE34ffcVWH4PedSQquN2LN8IR5Z8upIbErZnvaW+Q5VT5hIBoIUjfcqdtT0dbrT62u9HSCuPxl/vWpnt2DMSIKWqWLo2sL9fFgCFrebsQSGT9MNv9pgWZwfVrLaJuHwK+rVD4Ma1yq2PGwN3BtAA4OOV7Bm4WQheWhEbindEJkbdjfGOoPFNEKf9hmigS89pNbZxqG6y1Jugmg6GtJJ1kR7h+i4/VzcSl5duB7AZIqQXBNVPfiao52OCGdPZydyAMePBVCe54Wvu7lTGzBhXNRYPOOJlX7U6IDLaUHrx+VOS5owChMVu/drhWIRQQZTolVZ4EIE2YosE2ghkcUuUu7kzRgtTNM56TiZLkkuFDTgBS9EQLVWQHdv8IbCOae+6w/5fB7SBSE91e2LZLipTvqL1lYwYhWLdjzElM0SLFEYil/1oWlxAN2kYabIEgzBsLc1qWpfK6v2lXNRvXbJxo4L3qAUBr3IlmoGcIDjbKl3OrqXF/NgM15HabUWDbcUDzTyUUMpXJdKXK6vKiNJ3w3EYRrVL6X9GnAjGXOoVCxYmmx0LWStmAlnFcVrm4SAgf3lCrhx1SDvXOIxHg4jpOIXhEU+A8FLNWgShyoPCgaHyotpbhfNB2RwXKIDsFbWPAe2YmHHCdhWViRhbBjfQUVi3ZBubJHOSmQ4aUIpHUKUcanOZPEk73RKSYrO95NtINeaBoQb4HZmObeWxXZzyTZzY0UQQok5NF6w/EwSsBGSDkbYUaE5ETRJFJhrjUYnyoLaWuEE5t8VETgje90xYbFRVTZ9LSvb199qOq9F5/smqECAQzas6Ka/oWjHAhjn4LPO8SZuBjikX7CZ1AD6EIFBpNDYMSO9muk8I1cOiFPAF7/IrWz/gWd73Vl8RBNhzNueNxyXykUL88WvlMK+3O0PlG27de72u4Tm4i40tbQ122Fe8F4z1neFP7/SU90Il6qLj/tV9184WI2Vbwc40wBsjS0CPqHEjhCGzjAuj32AvMtr4Sj2QlgFuZMYiKBUKq/CA78DYN0E34qrVbhN08lDdf+AFCDITR44jngq8rJwIl6QNcgmxQH0YPMqEscJ67/WyALLS8WPzONhAMaU4PAkcUa90vRK7t5ENNptnVNHFvhJOqPqP427fQX+dKnzTxyAu4V3B3DctGmC4KuS0aatUCwhJeJROLe9CsctNVJc7re9AgX1gYEOBZVUFg8XrdFrb8U5I/OTCjCOaZnI5oyTwnsRFZID5drbegQ9TsV5w++IwUL7HGRND16Z2cHJrH+YyTBpit4xjf5OatJ7VcKaI0YLh6pEErcCdaZWISKUbq95XRJB9jhn4Yekz24dy2T7GtBtDu2cd1jEWek9zbdXl8joYquBDp+Xeb0TkWHGBt+y6EDDoU0rt8IQDNtwoK9wd7h1IwdITRMaraWKKGlx41WvnX8cX9jRvQCxvArfAFwiI9OwEa86FzIcbE7o/rtGQBjiUDt4WAt1l9pDXNB+9RhK+dgEAqjaoM0Bi8vT4CXwQcgTu9erNpqL4m3gOf0xn+uNqGV2PYSuKCGcUbAT5vnpwOu2C4Yy4fLoAuI7ZlRCeDBXIzajcou5hd3S79T3WTAJvY8MKepWRcRceTDbfTMaC8RD+CWCCKTFxeqY4Zpkv270UrEmk+RYKdSIs3qFwppsJFFkht614tmRBc6aJI3a1wSZkiwEroNb9KOr6U8TdaIi6I16uV5t6JZAEZolFsMOcDRenLf5nkoB52/VK9pIb9YZuRWpdmtG/mFvS1oEhzeGSfv223aPrquvOXGnE7Mi+sH+YrlYONJbBn1IrOhstozWCSw/NeFvBLjGVURY4VnKHxSUJbUqg+HGv1Q6X/YbVWlqWan01CTGIQU9MNoJJ/EyK0ui5m9wQSUcdBB78ofG1uttcne0uP3XCLO+ODRuGuvTIzNPgEHOEuoOE/pJ8umC/83BVvdU365vaFNgbbkD8tADg85k0rAgJTRj+Sw+NtU9J1U0MP8F01gzugdCm90Txa4X64p2wuOMJYf9ZQQTxqxGcRijXYtWP5qoPn2c6YhOYGOFAT9Noe5SLhSMuRAi7gwXRAPucRuiEDSuCNo8gFzegO/ACbiCO2f0xAFBcBZHc81leEeuYkSx2O60IFgd14pa/MJr1M8vMcu9ETbU3qOS18pFcCFuhG0kgEK7w52vq++FgkGvx4G7qh6GUd5g0Of313Te2kY7qYAt52ItM6XMh1I0k1EJUdERyQfRefTqAW10WWMASG1rTEGQKFpoj6YkiTh2e2apL0UZqRdkzhgI2w3P0UO7Al1Fnj8P3o9hMiw+lXJI1AW283l0ZpYMpUok8iX1/M4auu7YLTn8Kh+q2l5JHfe9KawV5EwTZnzV4+0twpufgkXZ5dM+0kdNWu2Z0gI4CVPc+c1MhuGcaEYld0rFF36V4flFt+l13WAKDV/CxbLGv6PrDGwVq4uXLmeTG1uFPrBeENdgfsu/DVPTbK8JiuoKnlmapuof8PnW29H9zcRYAGnInYCheNzSqeefOXhKK/XVYpcHrR76zRV1qAEIgzJDwegpokRSSrnMsBVDRRSr5iXnuMm1J+HBsPho9GHUHwnHgsFI0N9CkRMl+K7UD/VXszZX53wS3AF3co+dGZjxj3aVzmpCSmHabU/zWVosNOPG671Yk+JQFbnLy7yRhgkpO01WHoZZAl92a4LH7QhFXGED5UYi71vGTBlruuWxZnJs1CkZ+3ynheMsoUTQtLKYj9wxeEN3/HoT11PHIlA+VD50XTcXA15yGMIEV9JwJcKbl6lj+ZIoZI3H0oyZytOdMBCKyJyT1gNuglusJZOUojwVqHK+UGE52jl6ZBzZLRuv82mxC2v1ytTClQmZLo6uFJumZiG3HVUzTThX9upoCbc63TxmvrVcJ53HD929kurz+1MTq+QeDyFJXVGh8vUul63N7cSHjvEajfpSP/48jCKzzIvMcVnTyKg3JemgjfkSWsL1i/n/9jzxnHNcpUi2exS5zMkIMoYhyOACSWh/L+vNklgnwzlbQLnoDiudKemcygVBkjCqY/A9lckt4L2z5AdaDQnI5PoMoE+w0g76ylP8q1cZnwvsOPDqM8KprKNEOWvkpL8t+ztXF0T29fE2cWHDlxK+YBprUarZfZKvc3uQCI2Kp92nA4/AzkUcwBd214cKxWJ+FaJXcgAFzPseWPhtKbZ7GfY0OHMfWIr7DNS3q8ESThPqbwTB2bBvxjSA/+EkC2qK2Jowc1AmmhucCXDN0rr9QltHs1568MmWt/9chmjDt2DH1waD3x2eSYYMzWBe/kmeKW7nJ9VLUOTQgo9Bh8hS0BH8MzLyK7MH53k8CPqZzBDqS0SIDd69BRCF5JDyYH/P6ACt2k6z5cI+TgAZKHlsOMaZ94Vayt2S7Pe8HIfX9g7B7reTnRQCPHfFUsnvZ1Baz0+tQ+xyrg2BL1thuLYWKiSHV0ePadV9Bi7+5VXk/buhcDLIv1NX3cAWujIy3/O9JPZMQLoEArx1Ds5dge4HcydmYAsQIm428JELnHoyE5h7choLxG0bsA93Bv9cjWx7H34Hjy/6F9wH986KpipaQu3Qhe3q7hYcTWKW2IZUmVqtLlteDNaG2uS2EvlWbYupQY0kYZoyr1bj8gQrxfEGbBKBQY5G6YeIcS45zNV8veYcsPmCRomy4qV1GaW+GEllAKTa6Z4g7u3VtFzEL4sMw7rcUQ5FXsvmHRVoZbCI5FBOc20hpUxgqi2Wc2EwinMTsUJBEKCuaiTmOnDtkIfuSrrvR73KOlsSs2o7wNNZbXdjDUoaVzWUoHJkvySdIzstYMyURIm3Rz1iM5IJDvM2gYO6UmiogIwRBYE5TKBoow2HA/s6IFr0oAs0c2wXrpJzeC4C5R8Lfezj9V7ASjxfAleygAIMOlvzThexyIu2uoTkmUEbrDTFwm1GY0IdPB2gfyczOR2mNzR4ihM2o+iW6DQcyg7bilYiPYpYf59qRFe6r007epC/ukLoIIJiQMPkeFg92IlsuvktC9Z+XF/wgrc81lqpwqHOmUNgOS8Wq4dp5YMxxjNtO6Hf//wY6H9i//kdX9sjBNoKkzBZuatCn5DdKC0/5LApUUokRaE4g1nIZnX7yl4IBZfXN6mDitTG7qbmQfghi+Ko4zACWJC7e3sbu4YBh9V6Wcrc0Ubf3ZkbNVINaWWZ0ogztnRpCUG/cbkvl/T73FC5v73p/t4T1E4UGaLMmQL5+SFjuAPu4B5Llhy1g+nH5hVV2qXvF3orxaVwecgsrrhhVVeQE4bRfC63kJFx65DFOQjbQTxCm3hsqqM1G2Fd9sjCXFolwaUxmAyPjVGc35HUxbj9L6HhKp8OgNkGR53CtfRvxthqV3/Aw0jSbZOLKMCgkTGtquXjEKSdrX6Nkni2v7t5E16rM25kOw1rRcMLiwmuB7CIdUKBHJD6IRQd4okripRb9Wy1BWDPFwu8AvMetP76HhnwnX9p3rNbQb0Bt/8f5HAlupKPRW6RWu3g6rA/aF9+0pa38ATy2ML2sFJVsYNMp5HdhkNSmJJXVw94CiSjnNwATZ9KCoVlivcttrGw5k8WUbrTau9IG6P4sY2DlVjuKv+l+oc8OO35P0HLQb83hyt6GmyBDGqerhMSgbN9uKiX799nNvn2YyVtwwghIl1a1jRzj/NaczwbRNj9KTRNNf2Ga20ixkpklbObdVU04Y6ESUoiVHEbc+kAluHrRm2tS6YwlQ3NM+HXylIoudoiDDNRedSLMnAjLkzs5dDjZVJxfGLfJ8TGoP9a0aWem/1uyqLtHxyBIdqUCGYpPTYfmwi6mAj0fQmMLeA8bls0rS0ypdNSf83P23jMd4WWGr7xDX9rLX+BAXmlN9gqA5BBmlH7NOflT/lztKnVakCfiw9yvbdQOMX5kXZ8ojc0vnhW/HB44JpAADQb4SHmAcLf/+JIOQl4Gp4++rTCZIVGMMh9MLS0VpRdOKFpGZ4wdlO1y2EvoGZHfdvq7myYrlJ/ECxCC+DI4kxJGs+QrmLMQhw6BxRmolqvu1ocXJ7lHOfI7mlwAqTL0NPyIsQhnk/DgrLb+an0AOmm6a5BksKlXhN7n7k+jR1SL4Tb+RPJmRwgRaxpDWKlbbzLtjATWhbWUZRbB6+/ah+6kIOs9p2o8hgrpRNc9r403ArOVt2rBzfCN3y+Bbnvt9KpSMQVgyyxXJbZzFaNK9VKutfKNpkGfKas7qdMTpK4KyKSPhUF/S/qW5eqbpLCFwWxZXtrGkycBvVO5dNH0oPqj/uMSdeGKglNUTMuJYN6pHi8zJCLRV37YKyJa7SrYrqEHAzJlNjTkj0TkuJ7mJrwSbNGmqgP80NaDODTn45RNr9yiSvh9qC/3j0NrwL9jmhEbo4pTf3zlIPF4+XwYNPGm+g0YI2Fm8lNjpnIdMdbkVODk00Madn4Ij98/NB8ARMoBayxdDN/mqQcx3IIRTJCiFHp44gVd/dbhz0mdrIbQMk/z0zk1U+/YcqsGb5HD47Tf27p06MJIIB9PUBJpyAomQ6HQcUywY/VBi9WA1QsGMpYDlB3yfZKHUABfTAEuzrBQGA2xmhAj5EItGOUA5dj5KE+KjuB7UWFiPWtqICZCMTZ9RsFwTVwrVsf7MddqeoBAqPCmjtuQNtdI6PsoEwYfVtujbVWcxgRRqD9G01Mq5MGOH6rYOXYYOxEEYXnp3B84EFwet+bKuBDFV1Uo54eCfGUR6ltgwUsG0qOxAUatWYQ4HAZSnMeTVCia6IY4ZZwGJjAt32Qdf7udGG2nKKSWBn9Y6ObAg54pdPMQgE4Fx6QxdY6qI/opwRtePYsvqvscTYKpmojl/wHf30RWXD3Me1LcPGEchk8DX1QrKRpGw2bh3XaOBSogi0ipuqqnDN1BLYWUJzY7CITgjuQa4fdencvfv00BeyvueRjswPibIBFnFogHtj7TsepdTBgRJkQjSsYTFjrknDYddcQZNc52HPQXt1xEHijVoQIHw4+xB4VuzaE0nJ02YDuZmFMuG0D5nzHf7WZyTe1Axh6g/FK2cLXGEB3A82jZDllIAKtn5btydIfVchRIMmLDSHi0GLsSzZDjWCJQwQrT/lwMeU3djDfrrhwWmrqDJ1eMmlC0l4PvjNpRS0UVBUkjMvZsOSlSbIoZzwCr9UkDpu8baS0jzape3Aj3NjIEUrN4lLDhHSJxYAxwbleDqnnvsrCZeNlyxSPQlszMhE6mIKdIamiGtbLgqzzD/qXsbIqZRiGzu7wqMxYMfR9qUt2YdJ+yOMJeZ28VjCtabreiQbGwGa1VuaOAKORRLddVZHAtE0n1PGwmSfCD6NtuzgOYIpm0nHAgtuPkQbrHUeqTTgJ5D5Ih7ByATYKu5f3D8SQF9nOkoA/gPHLdzAMI7ztXEcwXzP6naZCRJWH7NC07X6ZEIO0Ba+FlAAxUW0KboPfiXKOQ0laNI5EFNAhRZDRRp+myl4EoWqFshqwfEsl7dEyuUIJs+BtmQy3vYYkFmxof3+1UiOebySOxcouxNAFwDUCWspoiuD5wnTSU2jH1qmGGZZxcFs6d1ipxbzB8X6CdWDMgzCtBMWtL7UuhwGF+aZnOy2ao6C1aKAUIKIp+VglXi5S61wwruXzqlo4QjojE8/rx7r7TGdsADZDn/Daej2XPXoQkiwaEEh9JxyOtzg97PYDBAh2ygGq7A2HBZWyrvIcxgwEjs4LxqknHLhFiW40gmW3b64o+pRcDojG6fqcKZezfIGQe5OgDe5zKPOUh+XxoqnbpnGZ+g1mOuhiq8738s6gY1td+tokHsxI0LJdFoB0xTtLHpeFhJttcxA2agihY75ZK6pSAjeq6jFJcLTE1q1ajPv9w1iZ6C3hfonFcqHkCty4xFHipqRkzITsuIGl9BFAmJB4ZwgwApiVHkh9jraqcDo+J0EoTXWeLbrdQsk4mQkCOMzaUWsLnlkzEQDiJxIjKHQX5EEorKuZISDE5gyizzyyzT899SSQT7836jSQhYVOM3eR0/1MAPX4OOmwkjFGRwveO1B+r72HZHQrMWj6tfOdMpSo2tt1YIz5+UdADrvyFK5AFWTDH5Z6j58OYHvyaNGmAkXfew4eC8j/dwwEENNxYeEkBzbhXRuWTObnGIAHcESt8xahobIY6UWB5Lb43AUOJ26wzw3jXVsd93WnTYsbfbiuSJQHgHmOiWJhZnnbGFFJH5Y2inYjj0Uf+KBd+O32+wiA00pE9vlO+WOCckQBY088Wcehi1ZcI4o59YcerVjMcjCvqOMa+w7lchVfB7uNepeLDoVCybjN+3ThisTR9TrNSdJx+uEzKRyDSTT18BxZshvNTmt7uXhskSrS8JKLE3l8O2MicRKDQzmFjziya9IPOSKPxXkkji1e3y/53MwtLnyY3Jgui4LM18lu1FsfuCtxpSZomP1u6loxq1MfF/bejAClSeM9PekIh8mDc+zrhyM0jPVWCoW524/XuYo1d9fVflyMBd6yOyWCOsznrE/b/VB+clBX8/ljx3h2Mu7sTUVetm3HK5xWJVvwlK9SH6LcjCiX0w3balY4T9w5/U2Pl6LDsfqGsP4F8Txs6p60Xq7CkSHyk6GokOW0Ws3tE7TR81dG8+obITemHz4T7Aat6HOwP3vR4OveS1CREUESxTfxVt9fXrrws+d/EyjCSvHSpehNwK7QlfJxXajqIYz0ClfFSeV1C4694W3HYsLi16eLA1WsAkC15CTM73NtzK/vfvrZbS1jQJqC7nBctRrOHumEK+X7Y9uh1enKvVYO2TVltrcwudbpPIY86MFYsRDcrMylD/F1XKwwX1SDgx2GQZ65GwCyKrNlwGCHhuy2uconLRf0ua/PDbdjLaB0h8cI+BPO7y5KI+BJ/K0SKneZwXpyiyPgKP7CrR2Xls+trJxDef7+++cLBxvgIuEPi1Byoamwu1LA+ltjnMqZbi/ML0Nngnd/Mj8FzmCuqHLYaepe5YSbYCoB60B1Hr4SyILYQw8eUw7kh+GWFqWnAZ50c7wxC4ARYKQ1693nmyU/otyyH9B3QECCi3iEtDw69b546xR+LE5ZoQXwP+MDhVx/rKsQ8QN3uQ2DZi1i9xTSzyIj+Kk4BB1go1pgJfHt/xwWyuoz/ji0w31N4AmAK+DKwpx3bV4sWWKjxC9TNAVXEEXhU5sdLHAyGOcgq6LPt6aobot5rHIZcmQNhVAbHJxewaLo3NtZ5X52R6km3Sgb7USjwyQkHFNXuvnUH5DN9LIDk7Y6mvJrazZWlnaYfT73+FOvW02JF0gFhaFyObBNsVm8hCBkXiyMsav4KX+pcriZ1dSsbhiVNxQf8EmihTHnCC3NSJHHcu+kGJ7nM0VZXRUZHIxQwpS6XWIoqyudOc37q/3Urzsejca7NzpDbE779NNDBReBFnhRJ7unH38iCYqyZEHXv8g3Q9sGR71xnE9fJS5sZZX6OcRuvtkDbGvUf54PAIHcHZiV7IC+thUp3378DIBJxhZO9E7barp6r/TOAl8tKgIB9gXhDfhroZYc43prO4UaDUsQQskisjNS5H8hBz9++Kab3i2cwl+K07J8Fck5tRSe9obdryRut3vfhX34Dfz1n84XS3Fg7ncvEl3/+on/tHQkZSA38rtH8EsH2jutbqNnH+E/gAEmE9C+DM5x1MLBJXA8/7Fm0HIJFZSTrXA8/EPwQWSX7EIm7je/qi0HAUuI39yQwlfeXZPbmT/fbQYz+x/p0N7Z2b0eqCoJQeWEaw1IEWYMvmlVr/AXnQEa6OsGZaj5h4Mu4C1urAexz8wZf6da3aloaXNxI6iVq/gWp1NbMtEQRBCnt3PKTlWK+K/ufgh/L8QSglghEU5bQ6nnZwK+q0gXwC9kN3tAek9rzgdwg7u+v6TsFE4DiTxE49GNab9Z6OoGakO4VxXYTR68wsDyytOorCehMS8IzXUVFkAzg+kPwHoZj38D/72PbLMLviSBNNcGx2gP6WEgqfy00m8C/XgqlUAU/KFMO/Ksz31afuqp6WxPMILDxYHVQEmDZTwZzF0YG7RFGiD8B/r3wXCrdl12FNsoAvqe8gStZHcmlU0mQjSwSk49oaxqLJ05glCaua10vldawbVIBJqnd9ZbBrVKFyagBAzPpkRUAKGJXASZDBWAKY5Xei0fCbJpRcsHyeFFl3Kch7e/U2zxF2pdqmUfogaukegXFe1QabtYXbs0R07v4FoohD4xQKFRA11dA0m7JGwckWT3reuSJQhZNVGWiSZjkk8K+OGKHrcgB+z9X0bgDrALQwx06UhciYZDPIVLdxf7jhoiuIXyu92T8d6oCIiJGmXKd1mrASUrmGaNhOq4Ls8bSihgFPEWzFvIJacpSkEIxtmcpxVXAtM2R/nZrNeoxeQ+A2JMrxNm3Qy8DL/mujPxUKoue52UkvSkjh80LOVHSJ3HyxQ2M/znaLyNUHMZk4TzNpE4PaFyvjAGKBIZGkmBAq+HJ6L4pq6WB6dPVk48/b7bjMZeGnyYFFvPkjE9LcmuIm5/+KqSd9n4OOsieEnakzAaRrfRkrSATrAS1ukFC2bp+EIUrDuJF4AOsLreSCRokpX/71fXmHSIN2KXtmIdFh5wehPMAdznh7sJYUSgsZyJonU8rh3zJGt9aluIhiE1Gq+H8LsfVl4Qkat7r68lxUF5wG7L6zWx3Tc2cKDYJpuFGLbxN2Yd0Xn9sw+2ftchaywxnl5DFPgZX237Nm8AW1V31xP5VE4KG+Enjh/+FP6Mv8pawNlOSRiUvaclHoOmUdzMBzABmpf5CcvMpuwiruxDZL/KM7x36hOPxE6TRHSYWG3uUnhD2oSQjCAEnYn38y+3zTKNGwlYQXvXtnB8uN0CUs1pKexln2dOS4KYc221rjiMpkOf6qq+HHiRL0x01ROyKXV32iFi2jXqGMje60YmvHoS2B2KTiZfMn3r3tAdDqQkAbnE1oUzPT1pErMvzL9JCyG3Ovzxxj4ZiLM2cMgwpMasdtuXf57Eh3kaOJEVeZnZbRsd1mupzR06/7qk+yqs8g5icUaFj1rzKNHhpSfG1dc636+TMDno17dBZABYRBJGJYowtUwCrCcEgRkGKPUGXb29XWHqIRwPMQRKPSvhRvnVFvX6SfXErw237QfFitTudpLdPlyMCzR0GmpJ4POhrBXU0sFdWwWCxTBEMSJ2XIRI0lSXqXQZ3mp/0nl+6vLAE0tDGc6Vg2LK6IebhUKMUMVeITdyMHofAYoXELCBcdl0ImmWRS3P88zSpQpE7PSirBf1MCyzHtFHMl+vv1o+TSnGBBGNIYRXk7mJ07TlF3ufNgdIKLOoK449J2TpMrHl3TLG036/CycDm88wwMy650wsh8NeS6Ykk1Lr3PTcBxdVg0EAztYBLlRHWSy0W/P6aS/n7FlCU8LSAU3SvsswniBFPDXrOyB3bshquAdhOqvAY4IFTlBsj7UmOtZosiJVBK7XpiiVzCjVzeyglpdabqIH1ZQPJDhWhGrS9CDiOwIAo7pbbwzkJF9112qEEhKyjdPfO+eggCOXwmfg+++ItM9TO60n+GdyyeRNvlnn+dPjEPpSHxDNpfgAPngZ5yENREdPRoFjyiqWa1iRqmz6Vt1RbEIGklcoZMMia40K67oYzhaIsCoGVbYPigwxLl28VoXQg4lSNB2QhjHz2JSWYuFh6I/F/AnXT3ZJtQVpYdffz9XasuazAE7JCXWc1v9Zgh1oLHpwQmrvJABm1DBmcDNN29fwK7gXjtUc+/+AT2JQBofkADNEJ3FaLg2TeKFL4QQcfcWm3L9MjdPhQ7eptyQii6KUTfEGsUYa063l3W85zq0aJcdTVdW03+xw2kmrpayDCJWaHVcr2C5Wjuo9OyZkmYHlOIJafs8J5D5EkNDxDiOsmn+m+1vBMe0ayvL8yv4+IcTly/aEum9MOzkJ4S8dXD1hau+W2e2EAdbaxlf1Z4+6YO77KdBR/Cb0MFrCJQSZ1VMnhIIPO1x3nNDLOsyCM2bv6rSlWWE4lmNcbKttzVJ/F5l1O1SV3rwGlssQfFy5MUUteo4jtXQcXsMj8ISPDdm9Qgetduyj7ZISyOVQZ/yjbcNIukG2VuNSWKWuWgarW+A6qPVazvbz6jVbqVvf3HM4iqGlHEkch7PUl5mcKgjRqExZqb7URUhke8ZJmZO3+7BW4LXV4kmS+M3sb6qj3VAhYzg/ikWhUjCuPd5GOVU+Meysbxb6nc1xvUaroSJllszzTCxdcT+NNvI6SjIRkXgySEZnt8BN1/UARzH6tYEY5T+qIDDiM08NlmDihSit+YfPpgSsRjyYUdB/TDSxeAXqaFJJN9gt5BoIRxghkMaVx4FN00ddDhOxFwwHQaBwDPuc7ffXR90RwGyyvUW8aG4X2u0lL7wVCoZMYyAEplFxT9+uk7lN6h0H0p89zhcFA05sPLuG1iH7t1UPVHhHKFHd0D4RpRtKUOAh6CxR5dvuViCZqRyU5iDIg/C4Fo9DlUvfI4y25/P8pu4VQIvBOiWua3oJniSTi/rirvjwzs7G2adTpbJsuMCuRpXCCfI7bfpa7eo4sxjsR5BcqnOYJIHeuDSfoHx7qWuEoP2hXNKrzNG34uTFdvGpcmXL40vHsdlchzDEN5azxpH4UTVy1vS72cXwF1fC39BuLEXxWk9a9VvaK4dzQfWwMjSnv6lNuZg+JgJIm3uU1lqW63zpyvfdr+Lu3cCGiJ4tFtyV5Ii2v5CR00QM9ZmlbUok4BcSEHiJB58u2D9HAx334GP+Ng0zMDedQS9GO77lAo58qwiG3yRauYSxs8ilW2I3d0eAqbRQ9Su5sjB+6IrrLHpKkgpgwZzOpqDZeq8h8vUd4sqVhjW4EgPKdR3dBH/dPsaumoYreXkBIPGk88/GQC8uKunrw661FEEZyNVkNKBym7fBnMaY6T8dZpNtgM3PW0XOAgIncVAUikZ5xYeU71mIRTcus7egZyUYY0IB8ZbsvSZ9sbBy+zzKl7hf917qvoQtuPFLzk1RcgMFYbxVtxCLc+/fvnKBufNJIPt7I4AxgPltGiHt6PSnpongfwNozbZhRbUT9jKQ/U6wGiygJA1A8xujoOQtTxQeP4DY0ZwXWN4wQ8LP4TxUjH2NGecydxLN8+iJbDvmh8+d64NHT0eVtsHCq3kjXV2nItTHOnienzIYlkU7GGN+HnNxHU8/KtFCTCqR1OUshIrIFdglKmpMx7O/6jiTMd1QW5h+S8hdmA+heSbbL68r/pnt1ilbgm1di376NKpYpJa2MqCoJOzgSXjI3bof+o0nM2oPU6oR4oUqUVj6yT1P9Lvn1ivPuwJ65e/eesc94jtuvenKJm76QPz3nZgWHQyKNBplqC8GOx3i+8Nw/DRiR3Vr77gBR3IlXK2LrsZEZ/kR8+NTbFDDILwOpoL5HHeDRgx7ggKJm8H4ERwPumAcBLvKw7q8beoYiJtIHjfOMGjuNJtWaA59frpgNfcn4qnglbgoZ/VF1J31auiyAykT9LX7dlx3qA9KS2y5yz/ua1mefxLv8RLENE+qwXg0rqNO07cvCVXKMeuQCVB44ZkWHZ8yBcSLklJi+Q75a64u/XHw5APqYbCPmR06xkUuBQyUh/TIqhdN7shDpQxqFuDMf7+EgjQgE66xdxkP5UsNfqqxTuT2Tm3x7Gl8sMEdVA8Q+fE5ffHJnwWaQn2SENuuuMkpqmY/FG0OHMle8WCTPzigjAiCEPSdpE7zu4rHJbXuCRaaUJ4kZJG01/OI9E4FNMzYU8Ie2mbNczMB3B2rOxB5yNlznrjeAeEI0B5ySKm3Ot7C5+M5TRtNnjazbWcmZalO5MDzDxs2dDXi+qY0CTgU/ZSMDZsCZn1XFsO6xFs3nYfaA/RBn3i0Z/m15FVmmvGxrKqKU6FhmJaF4yI6YllOEMQmDM9jsoUz1DbZCaeBmb6O6YrgE2sVNXSrHhdOCqufpHhfY/b2En8uSXS/dF0cDETiXlAQbLmjyBKP0b25Y58BPXER0pAuVFchSgQRIjgumlkNc2gFH50TS7Tym6KrtrR/0Q3umrxYNuyQVBLcii7KGoZt6nIhsazxhKXD6biGAbwT4eHYV0CbddBA4w0OdMIfqYYnXKImtbe8TtdZnmiiJU1bLBMlzQiwhMikZPVIWZQ/PbB6MzawBSsVUeDMsvlrQvJQ3j5Ot007xIx/twxD6zswno3mcDgxQ/Og3dv/O4FeuHtrlJPcaUeEGjL89RpB5H4mcvOaiPr9Lf0OdaVAanuPiiplXvcIxGG1374YmWzT2jSIqnFk+Ed7bfOyRny5BZ8H81f/cOAnMa4OLMUgA1/F4AONGP7ACjDVfSDazM2FMhCIiWYSQ8hw3/cYKNEVdOUWgQDfPWP51/jWU7n63yyOvwHgl2ceb19c+K/5b6XntDzHrJkBdBgABP31sOacVpX+e6hFVeMK5ycJWa3j0UfOevSi1S7hdup3NPVX7FsH0CglSK0JIIxTHnT+khRD+mkXA+UUTs0ggKxGU6jUBo6oXy/Wj9hLA1W2emD0w/gaxkb9eq/Go2Swax9Rzj2AoGG4VaXBLdX0eFCRSMoaebatBIknppo1QDxMi+FUll6UFWfLg4gxSY1QjNRjDw61FYXyU4GKmpgUSG2A/JllCfXHhXPtpJ0IVp5GFfNyFVGSzXjU9NGxqhphc7lJheFQhngo/C61A2XNROvWh/DIYmTZosvSB3FOi11VjLJyfZWPtCoQW8oGQWmQBURJKIQL5DCFY+IUYXVTp3Qh842R04lEGg6RZMsVwvK8JQ2pmxRZif7uWWRJPUTQOBMu6/E3mJXMOQ3fYYzcYO8S58mXxAbN6dLlLbc5o1gOyCOePYHdWz+e6FNkGeu1lC4ntuQq+nTrVWHfHT72ZLlpB9ptKhoYrpS1mFeO/UwX36X0kZch1olgDU4pi/2hvdDmcbunW483LUFWCepZ4tGUTY34jNaMJvuQu0mWKJnHAI1+yXI5ierTdYeQHb7sUwWyYpD4fr4kziVxdmUlFqx8JkV/tbmWc9hjfwL2Yzcer+72+aQ1TyGfIvCwFDkB/zWucIGA86nDk4YKGZuWf9WGZIFDAyYAb5U4VQhRPIXhFKZwjrmhKMQZBFX2gSbb1nC4R70JApgffyWAEW+ljyBWEEq+MoD0TYkgvFGGCN2oEVt7AjKquwmSwDaqjBHZraTw9CkTJFoVCUODMkUgT5nBl6DMkXJXFhDkyhIhIawk8V2sIQBXKFMqk1aYKt22RKFsIXK5smDt+Sdk1hQnI3kbpE5thUxwWXqYHGKkPApjcxxvO0sVIsrHliIKOU+rVupHSjhytvkKKMZ4rMf8CGrsEpugwJ7Uxs6ZcmXhrDH6y1Xy5sBllnM9nDe3aVU1VxNcebCi+PQK+eo2Ti6b6kbbCokRFaaw3JKcWg725MhxN+RDJexDaZwAkWacNUZmD5WZAPOd9SpWLiU5c5RWV+TKc66OsMExXlumqGCyL1r9VLfElK1CI00vaw/nUyi4dbUsCtkvxRYHNSut22RKJLGP29hrAzM+0vQGZ3+w8wG2O58ojMmyS7bdFrFkJYe1t2RynXPBRTZs2ZG75LIrrrIP3l+dn57H2TXX5btpsT32cvGRK7ee7PCtKAp8vHjzse9NW0yh56L0xaU2ChKsTIh3QpU3on22sH7ifPMdVWrUJh+qRYWBaD3guV7qxKnXqEmDTebYJ94nCWZI1G2mJM1a/GKuZClSaXxw1KzMhSGnk4D1+sIEvR75VPqz82FGJCEQC7GRzhZj/WtXV756CtRXqIEiDRVrpERjpZpIaqqZ5lpoqZXWHDfpT98j00Zb7ZRrr0IHHcHjpLMuuqKLy5jUDhRbmNnsrE46aPimx013ePY7wB8LW5oMvlSGjTjokAGH/aHfSadQEfHQUy+9McfUpUOvHr+aFx+VpHujzQn0TKPdChyffTGIZMrEUpm28sOIr9NVCQmLiGrRqk27mLgOnbokJFkgwHx3PXLPfY9TM2oOlBhJT6QLxgd7xGI5JJaJJfN7RP1DyX7a45hLtkllKpaUw/My8Yxom9R6543Fx5aeR/TJYGTuofT7jWXmDA2m756xyWzm7Z7uxffcvdYV354Jfo32TNk735xd7e12DfYMzny9+sJ2zwuWCmEWBGHmB4lAVgBhLwv7FwuwQ31pC5YCHBRAAhDcHAgAIKk95Y6RilXieKJYDGuiUk/Ge3JEFVFlVOWq5XtB4qbcklP32SR+z/ecmD4hC1n70ILKKLdyL4G95M4h0yd/JxCIrhvh4IA7C/c7mOtTjcaqnyj01bCUh+1qnSV3zm4du3P2bdjJP3guwdzukfexk+PD8yP2N5i98J4Qq7Gsav6xIo9fyA4kPKlkMxLuolJPGV8Gmj/W05+6m0telBsa6ttNYpBjC1NDY3tHXHVbkKr8ETJ1oVS0gv9gq+1iSywHTbIO9GwYeTXv/u5eynYA") format("woff2-variations")}
-.docs-group{--group-c:hsl(var(--h,220), 55%, 38%);--group-tint:hsl(var(--h,220), 55%, 94%)}.dark .docs-group{--group-c:hsl(var(--h,220), 50%, 72%);--group-tint:hsl(var(--h,220), 30%, 18%)}.docs-ground-light .docs-group{--group-c:hsl(var(--h,220), 55%, 38%);--group-tint:hsl(var(--h,220), 55%, 94%)}@supports (color:oklch(1 0 0)){.docs-group{--group-c:oklch(.55 .15 var(--h,220));--group-tint:oklch(.96 .03 var(--h,220))}.dark .docs-group{--group-c:oklch(.76 .13 var(--h,220));--group-tint:oklch(.28 .05 var(--h,220))}.docs-ground-light .docs-group{--group-c:oklch(.55 .15 var(--h,220));--group-tint:oklch(.96 .03 var(--h,220))}}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1}}}@layer theme{:root,:host{--color-amber-50:oklch(98.7% .022 95.277);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-900:oklch(41.4% .112 45.904);--color-amber-950:oklch(27.9% .077 45.635);--color-neutral-900:oklch(20.5% 0 0);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--font-weight-medium:500;--font-weight-semibold:600;--tracking-wide:.025em;--leading-relaxed:1.625;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:"Geist Variable", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;--default-mono-font-family:"Fira Code", "Cascadia Code", "Cascadia Mono", "JetBrains Mono", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", monospace}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.fixed{position:fixed}.inset-0{inset:calc(var(--spacing) * 0)}.z-50{z-index:50}.mx-1\.5{margin-inline:calc(var(--spacing) * 1.5)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.ml-1\.5{margin-left:calc(var(--spacing) * 1.5)}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.flex{display:flex}.grid{display:grid}.inline{display:inline}.table{display:table}.h-2{height:calc(var(--spacing) * 2)}.h-3{height:calc(var(--spacing) * 3)}.h-4{height:calc(var(--spacing) * 4)}.h-6{height:calc(var(--spacing) * 6)}.h-full{height:100%}.max-h-80{max-height:calc(var(--spacing) * 80)}.min-h-0{min-height:calc(var(--spacing) * 0)}.w-2{width:calc(var(--spacing) * 2)}.w-3{width:calc(var(--spacing) * 3)}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-14{width:calc(var(--spacing) * 14)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:calc(var(--spacing) * 0)}.flex-1{flex:1}.shrink-0{flex-shrink:0}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.cursor-text{cursor:text}.resize-y{resize:vertical}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:2147483647px}.rounded-md{border-radius:var(--dbx-radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-amber-300{border-color:var(--color-amber-300)}.border-border{border-color:var(--border)}.bg-amber-50{background-color:var(--color-amber-50)}.bg-background{background-color:var(--background)}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab, red, red)){.bg-black\/40{background-color:color-mix(in oklab, var(--color-black) 40%, transparent)}}.bg-muted,.bg-muted\/20{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/20{background-color:color-mix(in oklab, var(--muted) 20%, transparent)}}.bg-muted\/30{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/30{background-color:color-mix(in oklab, var(--muted) 30%, transparent)}}.bg-muted\/50{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/50{background-color:color-mix(in oklab, var(--muted) 50%, transparent)}}.bg-neutral-900{background-color:var(--color-neutral-900)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-card{fill:var(--card)}.fill-foreground{fill:var(--foreground)}.fill-muted-foreground{fill:var(--muted-foreground)}.stroke-border{stroke:var(--border)}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.pt-24{padding-top:calc(var(--spacing) * 24)}.pl-3{padding-left:calc(var(--spacing) * 3)}.text-center{text-align:center}.text-left{text-align:left}.align-top{vertical-align:top}.font-mono{font-family:Fira Code,Cascadia Code,Cascadia Mono,JetBrains Mono,PingFang SC,Hiragino Sans GB,Microsoft YaHei,monospace}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.text-amber-900{color:var(--color-amber-900)}.text-foreground{color:var(--foreground)}.text-muted-foreground{color:var(--muted-foreground)}.uppercase{text-transform:uppercase}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-ring{--tw-ring-color:var(--ring)}.ring-offset-2{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.ring-offset-background{--tw-ring-offset-color:var(--background)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\:scale-105:hover{--tw-scale-x:105%;--tw-scale-y:105%;--tw-scale-z:105%;scale:var(--tw-scale-x) var(--tw-scale-y)}.hover\:bg-muted\/30:hover{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/30:hover{background-color:color-mix(in oklab, var(--muted) 30%, transparent)}}.hover\:bg-muted\/40:hover{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/40:hover{background-color:color-mix(in oklab, var(--muted) 40%, transparent)}}}.focus\:border-ring:focus{border-color:var(--ring)}@media (width>=40rem){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (width>=64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}.dark\:border-amber-900\/40:is(.dark *){border-color:#7b330666}@supports (color:color-mix(in lab, red, red)){.dark\:border-amber-900\/40:is(.dark *){border-color:color-mix(in oklab, var(--color-amber-900) 40%, transparent)}}.dark\:bg-amber-950\/30:is(.dark *){background-color:#4619014d}@supports (color:color-mix(in lab, red, red)){.dark\:bg-amber-950\/30:is(.dark *){background-color:color-mix(in oklab, var(--color-amber-950) 30%, transparent)}}.dark\:text-amber-200:is(.dark *){color:var(--color-amber-200)}}:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--background:#fff;--foreground:#0a0a0a;--dbx-foreground-rgb:10, 10, 10;--card:#fff;--card-foreground:#0a0a0a;--popover:#fff;--popover-foreground:#0a0a0a;--primary:#171717;--dbx-primary-rgb:23, 23, 23;--primary-foreground:#fafafa;--secondary:#f5f5f5;--secondary-foreground:#171717;--muted:#f5f5f5;--muted-foreground:#737373;--accent:#f5f5f5;--accent-foreground:#171717;--destructive:#e7000b;--destructive-rgb:231, 0, 11;--border:#e5e5e5;--input:#e5e5e5;--ring:#a1a1a1;--chart-1:#d4d4d4;--chart-2:#737373;--chart-3:#525252;--chart-4:#404040;--chart-5:#262626;--radius:var(--dbx-radius-md);--dbx-radius-default:4px;--dbx-radius-sm:4px;--dbx-radius-md:4px;--dbx-radius-lg:6px;--dbx-radius-xl:6px;--dbx-radius-fixed-4:4px;--dbx-radius-fixed-5:5px;--dbx-radius-fixed-6:6px;--sidebar:#fafafa;--sidebar-foreground:#0a0a0a;--sidebar-primary:#171717;--sidebar-primary-foreground:#fafafa;--sidebar-accent:#f5f5f5;--sidebar-accent-foreground:#171717;--sidebar-border:#e5e5e5;--sidebar-ring:#a1a1a1;--success:#16a34a;--success-foreground:#f0fdf4;--success-bg:var(--success)}@supports (color:color-mix(in lab, red, red)){:root{--success-bg:color-mix(in srgb, var(--success) 12%, transparent)}}:root{--warning:#d97706;--dbx-warning-rgb:217, 119, 6;--warning-foreground:#fffbeb;--warning-bg:var(--warning)}@supports (color:color-mix(in lab, red, red)){:root{--warning-bg:color-mix(in srgb, var(--warning) 14%, transparent)}}:root{--info:#2563eb;--info-foreground:#eff6ff;--info-bg:var(--info)}@supports (color:color-mix(in lab, red, red)){:root{--info-bg:color-mix(in srgb, var(--info) 12%, transparent)}}:root{--dbx-chrome:#f5f5f5;--dbx-chrome-muted:#f0f0f0;--dbx-content:#fff;--dbx-editor-toolbar:#fafafa;--dbx-gutter:#f3f3f3;--dbx-sidebar-header:#fafafa;--dbx-window-top-border:#00000059;--dbx-viewport-height:100vh}.dark{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--background:#131416;--foreground:#d7d7db;--dbx-foreground-rgb:215, 215, 219;--card:#1b1b1e;--card-foreground:#d7d7db;--popover:#1e1e20;--popover-foreground:#dddde2;--primary:#d0d0d6;--dbx-primary-rgb:208, 208, 214;--primary-foreground:#131416;--secondary:#2a2a2d;--secondary-foreground:#d7d7db;--muted:#2a2a2d;--muted-foreground:#97989d;--accent:#2e2f33;--accent-foreground:#dddde2;--destructive:#f3625f;--destructive-rgb:243, 98, 95;--border:#6e6e7247;--input:#6e6e7257;--ring:#85868b;--chart-1:#d4d4d4;--chart-2:#737373;--chart-3:#525252;--chart-4:#404040;--chart-5:#262626;--sidebar:#19191c;--sidebar-foreground:#d0d0d5;--sidebar-primary:#d0d0d6;--sidebar-primary-foreground:#131416;--sidebar-accent:#2c2c30;--sidebar-accent-foreground:#dddde2;--sidebar-border:#6e6e7247;--sidebar-ring:#85868b;--success:#4ade80;--success-foreground:#141e18;--success-bg:var(--success)}@supports (color:color-mix(in lab, red, red)){.dark{--success-bg:color-mix(in srgb, var(--success) 16%, transparent)}}.dark{--warning:#fbbf24;--dbx-warning-rgb:251, 191, 36;--warning-foreground:#28200c;--warning-bg:var(--warning)}@supports (color:color-mix(in lab, red, red)){.dark{--warning-bg:color-mix(in srgb, var(--warning) 16%, transparent)}}.dark{--info:#60a5fa;--info-foreground:#121c2e;--info-bg:var(--info)}@supports (color:color-mix(in lab, red, red)){.dark{--info-bg:color-mix(in srgb, var(--info) 16%, transparent)}}.dark{--dbx-chrome:#1b1b1e;--dbx-chrome-muted:#202024;--dbx-content:#131416;--dbx-editor-toolbar:#19191c;--dbx-gutter:#171719;--dbx-sidebar-header:#19191c;--dbx-window-top-border:#ffffff2e}html,body,#app{height:100%}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}
+.docs-group{--group-c:hsl(var(--h,220), 55%, 38%);--group-tint:hsl(var(--h,220), 55%, 94%)}.dark .docs-group{--group-c:hsl(var(--h,220), 50%, 72%);--group-tint:hsl(var(--h,220), 30%, 18%)}.docs-ground-light .docs-group{--group-c:hsl(var(--h,220), 55%, 38%);--group-tint:hsl(var(--h,220), 55%, 94%)}@supports (color:oklch(1 0 0)){.docs-group{--group-c:oklch(.55 .15 var(--h,220));--group-tint:oklch(.96 .03 var(--h,220))}.dark .docs-group{--group-c:oklch(.76 .13 var(--h,220));--group-tint:oklch(.28 .05 var(--h,220))}.docs-ground-light .docs-group{--group-c:oklch(.55 .15 var(--h,220));--group-tint:oklch(.96 .03 var(--h,220))}}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1}}}@layer theme{:root,:host{--color-amber-50:oklch(98.7% .022 95.277);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-900:oklch(41.4% .112 45.904);--color-amber-950:oklch(27.9% .077 45.635);--color-neutral-900:oklch(20.5% 0 none);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--font-weight-medium:500;--font-weight-semibold:600;--tracking-wide:.025em;--leading-relaxed:1.625;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:"Geist Variable", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;--default-mono-font-family:"Fira Code", "Cascadia Code", "Cascadia Mono", "JetBrains Mono", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", monospace}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.fixed{position:fixed}.inset-0{inset:0}.z-50{z-index:50}.mx-1\.5{margin-inline:calc(var(--spacing) * 1.5)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.ml-1\.5{margin-left:calc(var(--spacing) * 1.5)}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.flex{display:flex}.grid{display:grid}.inline{display:inline}.table{display:table}.h-2{height:calc(var(--spacing) * 2)}.h-3{height:calc(var(--spacing) * 3)}.h-4{height:calc(var(--spacing) * 4)}.h-6{height:calc(var(--spacing) * 6)}.h-full{height:100%}.max-h-80{max-height:calc(var(--spacing) * 80)}.min-h-0{min-height:0}.w-2{width:calc(var(--spacing) * 2)}.w-3{width:calc(var(--spacing) * 3)}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-14{width:calc(var(--spacing) * 14)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:0}.flex-1{flex:1}.shrink-0{flex-shrink:0}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.cursor-text{cursor:text}.resize-y{resize:vertical}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:2147483647px}.rounded-md{border-radius:var(--dbx-radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-amber-300{border-color:var(--color-amber-300)}.border-border{border-color:var(--border)}.bg-amber-50{background-color:var(--color-amber-50)}.bg-background{background-color:var(--background)}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab, red, red)){.bg-black\/40{background-color:color-mix(in oklab, var(--color-black) 40%, transparent)}}.bg-muted,.bg-muted\/20{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/20{background-color:color-mix(in oklab, var(--muted) 20%, transparent)}}.bg-muted\/30{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/30{background-color:color-mix(in oklab, var(--muted) 30%, transparent)}}.bg-muted\/50{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/50{background-color:color-mix(in oklab, var(--muted) 50%, transparent)}}.bg-neutral-900{background-color:var(--color-neutral-900)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-card{fill:var(--card)}.fill-foreground{fill:var(--foreground)}.fill-muted-foreground{fill:var(--muted-foreground)}.stroke-border{stroke:var(--border)}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.pt-24{padding-top:calc(var(--spacing) * 24)}.pl-3{padding-left:calc(var(--spacing) * 3)}.text-center{text-align:center}.text-left{text-align:left}.align-top{vertical-align:top}.font-mono{font-family:Fira Code,Cascadia Code,Cascadia Mono,JetBrains Mono,PingFang SC,Hiragino Sans GB,Microsoft YaHei,monospace}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.text-amber-900{color:var(--color-amber-900)}.text-foreground{color:var(--foreground)}.text-muted-foreground{color:var(--muted-foreground)}.uppercase{text-transform:uppercase}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-ring{--tw-ring-color:var(--ring)}.ring-offset-2{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.ring-offset-background{--tw-ring-offset-color:var(--background)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\:scale-105:hover{--tw-scale-x:105%;--tw-scale-y:105%;--tw-scale-z:105%;scale:var(--tw-scale-x) var(--tw-scale-y)}.hover\:bg-muted\/30:hover{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/30:hover{background-color:color-mix(in oklab, var(--muted) 30%, transparent)}}.hover\:bg-muted\/40:hover{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/40:hover{background-color:color-mix(in oklab, var(--muted) 40%, transparent)}}}.focus\:border-ring:focus{border-color:var(--ring)}@media (width>=40rem){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (width>=64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}.dark\:border-amber-900\/40:is(.dark *){border-color:#7b330666}@supports (color:color-mix(in lab, red, red)){.dark\:border-amber-900\/40:is(.dark *){border-color:color-mix(in oklab, var(--color-amber-900) 40%, transparent)}}.dark\:bg-amber-950\/30:is(.dark *){background-color:#4619014d}@supports (color:color-mix(in lab, red, red)){.dark\:bg-amber-950\/30:is(.dark *){background-color:color-mix(in oklab, var(--color-amber-950) 30%, transparent)}}.dark\:text-amber-200:is(.dark *){color:var(--color-amber-200)}}:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--background:#fff;--foreground:#0a0a0a;--dbx-foreground-rgb:10, 10, 10;--card:#fff;--card-foreground:#0a0a0a;--popover:#fff;--popover-foreground:#0a0a0a;--primary:#171717;--dbx-primary-rgb:23, 23, 23;--primary-foreground:#fafafa;--secondary:#f5f5f5;--secondary-foreground:#171717;--muted:#f5f5f5;--muted-foreground:#737373;--accent:#f5f5f5;--accent-foreground:#171717;--destructive:#e7000b;--destructive-rgb:231, 0, 11;--border:#e5e5e5;--input:#e5e5e5;--ring:#a1a1a1;--chart-1:#d4d4d4;--chart-2:#737373;--chart-3:#525252;--chart-4:#404040;--chart-5:#262626;--radius:var(--dbx-radius-md);--dbx-radius-default:4px;--dbx-radius-sm:4px;--dbx-radius-md:4px;--dbx-radius-lg:6px;--dbx-radius-xl:6px;--dbx-radius-fixed-4:4px;--dbx-radius-fixed-5:5px;--dbx-radius-fixed-6:6px;--sidebar:#fafafa;--sidebar-foreground:#0a0a0a;--sidebar-primary:#171717;--sidebar-primary-foreground:#fafafa;--sidebar-accent:#f5f5f5;--sidebar-accent-foreground:#171717;--sidebar-border:#e5e5e5;--sidebar-ring:#a1a1a1;--success:#16a34a;--success-foreground:#f0fdf4;--success-bg:var(--success)}@supports (color:color-mix(in lab, red, red)){:root{--success-bg:color-mix(in srgb, var(--success) 12%, transparent)}}:root{--warning:#d97706;--dbx-warning-rgb:217, 119, 6;--warning-foreground:#fffbeb;--warning-bg:var(--warning)}@supports (color:color-mix(in lab, red, red)){:root{--warning-bg:color-mix(in srgb, var(--warning) 14%, transparent)}}:root{--info:#2563eb;--info-foreground:#eff6ff;--info-bg:var(--info)}@supports (color:color-mix(in lab, red, red)){:root{--info-bg:color-mix(in srgb, var(--info) 12%, transparent)}}:root{--dbx-chrome:#f5f5f5;--dbx-chrome-muted:#f0f0f0;--dbx-content:#fff;--dbx-editor-toolbar:#fafafa;--dbx-gutter:#f3f3f3;--dbx-sidebar-header:#fafafa;--dbx-window-top-border:#00000059;--dbx-viewport-height:100vh}.dark{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--background:#131416;--foreground:#d7d7db;--dbx-foreground-rgb:215, 215, 219;--card:#1b1b1e;--card-foreground:#d7d7db;--popover:#1e1e20;--popover-foreground:#dddde2;--primary:#d0d0d6;--dbx-primary-rgb:208, 208, 214;--primary-foreground:#131416;--secondary:#2a2a2d;--secondary-foreground:#d7d7db;--muted:#2a2a2d;--muted-foreground:#97989d;--accent:#2e2f33;--accent-foreground:#dddde2;--destructive:#f3625f;--destructive-rgb:243, 98, 95;--border:#6e6e7247;--input:#6e6e7257;--ring:#85868b;--chart-1:#d4d4d4;--chart-2:#737373;--chart-3:#525252;--chart-4:#404040;--chart-5:#262626;--sidebar:#19191c;--sidebar-foreground:#d0d0d5;--sidebar-primary:#d0d0d6;--sidebar-primary-foreground:#131416;--sidebar-accent:#2c2c30;--sidebar-accent-foreground:#dddde2;--sidebar-border:#6e6e7247;--sidebar-ring:#85868b;--success:#4ade80;--success-foreground:#141e18;--success-bg:var(--success)}@supports (color:color-mix(in lab, red, red)){.dark{--success-bg:color-mix(in srgb, var(--success) 16%, transparent)}}.dark{--warning:#fbbf24;--dbx-warning-rgb:251, 191, 36;--warning-foreground:#28200c;--warning-bg:var(--warning)}@supports (color:color-mix(in lab, red, red)){.dark{--warning-bg:color-mix(in srgb, var(--warning) 16%, transparent)}}.dark{--info:#60a5fa;--info-foreground:#121c2e;--info-bg:var(--info)}@supports (color:color-mix(in lab, red, red)){.dark{--info-bg:color-mix(in srgb, var(--info) 16%, transparent)}}.dark{--dbx-chrome:#1b1b1e;--dbx-chrome-muted:#202024;--dbx-content:#131416;--dbx-editor-toolbar:#19191c;--dbx-gutter:#171719;--dbx-sidebar-header:#19191c;--dbx-window-top-border:#ffffff2e}html,body,#app{height:100%}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}
/*$vite$:1*/
\ No newline at end of file
diff --git a/crates/dbx-core/assets/docs-export.js b/crates/dbx-core/assets/docs-export.js
index bb9ffccae2..b4e69c01b7 100644
--- a/crates/dbx-core/assets/docs-export.js
+++ b/crates/dbx-core/assets/docs-export.js
@@ -1,50 +1,52 @@
-(function(){function e(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var t={},n=[],r=()=>{},i=()=>!1,a=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),o=e=>e.startsWith(`onUpdate:`),s=Object.assign,c=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},l=Object.prototype.hasOwnProperty,u=(e,t)=>l.call(e,t),d=Array.isArray,f=e=>x(e)===`[object Map]`,p=e=>x(e)===`[object Set]`,m=e=>x(e)===`[object Date]`,h=e=>typeof e==`function`,g=e=>typeof e==`string`,_=e=>typeof e==`symbol`,v=e=>typeof e==`object`&&!!e,y=e=>(v(e)||h(e))&&h(e.then)&&h(e.catch),b=Object.prototype.toString,x=e=>b.call(e),ee=e=>x(e).slice(8,-1),S=e=>x(e)===`[object Object]`,te=e=>g(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=e(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},ie=/-\w/g,C=re(e=>e.replace(ie,e=>e.slice(1).toUpperCase())),ae=/\B([A-Z])/g,w=re(e=>e.replace(ae,`-$1`).toLowerCase()),oe=re(e=>e.charAt(0).toUpperCase()+e.slice(1)),se=re(e=>e?`on${oe(e)}`:``),ce=(e,t)=>!Object.is(e,t),le=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},T=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},ue=e=>{let t=parseFloat(e);return isNaN(t)?e:t},de,fe=()=>de||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{};function E(e){if(d(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=g(r)?ge(r):E(r);if(i)for(let e in i)t[e]=i[e]}return t}if(g(e)||v(e))return e}var pe=/;(?![^(]*\))/g,me=/:([^]+)/,he=/\/\*[^]*?\*\//g;function ge(e){let t={};return e.replace(he,``).split(pe).forEach(e=>{if(e){let n=e.split(me);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(g(e))t=e;else if(d(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(v(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}var _e=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,ve=e(_e);_e+``;function ye(e){return!!e||e===``}function be(e,t){if(e.length!==t.length)return!1;let n=!0;for(let r=0;n&&r<e.length;r++)n=xe(e[r],t[r]);return n}function xe(e,t){if(e===t)return!0;let n=m(e),r=m(t);if(n||r)return n&&r?e.getTime()===t.getTime():!1;if(n=_(e),r=_(t),n||r)return e===t;if(n=d(e),r=d(t),n||r)return n&&r?be(e,t):!1;if(n=v(e),r=v(t),n||r){if(!n||!r||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e){let r=e.hasOwnProperty(n),i=t.hasOwnProperty(n);if(r&&!i||!r&&i||!xe(e[n],t[n]))return!1}}return String(e)===String(t)}function Se(e,t){return e.findIndex(e=>xe(e,t))}var Ce=e=>!!(e&&e.__v_isRef===!0),O=e=>g(e)?e:e==null?``:d(e)||v(e)&&(e.toString===b||!h(e.toString))?Ce(e)?O(e.value):JSON.stringify(e,we,2):String(e),we=(e,t)=>Ce(t)?we(e,t.value):f(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Te(t,r)+` =>`]=n,e),{})}:p(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Te(e))}:_(t)?Te(t):v(t)&&!d(t)&&!S(t)?String(t):t,Te=(e,t=``)=>_(e)?`Symbol(${e.description??t})`:e,k,Ee=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&k&&(k.active?(this.parent=k,this.index=(k.scopes||(k.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let e,t;if(this.scopes)for(e=0,t=this.scopes.length;e<t;e++)this.scopes[e].pause();for(e=0,t=this.effects.length;e<t;e++)this.effects[e].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let e,t;if(this.scopes)for(e=0,t=this.scopes.length;e<t;e++)this.scopes[e].resume();for(e=0,t=this.effects.length;e<t;e++)this.effects[e].resume()}}run(e){if(this._active){let t=k;try{return k=this,e()}finally{k=t}}}on(){++this._on===1&&(this.prevScope=k,k=this)}off(){if(this._on>0&&--this._on===0){if(k===this)k=this.prevScope;else{let e=k;for(;e;){if(e.prevScope===this){e.prevScope=this.prevScope;break}e=e.prevScope}}this.prevScope=void 0}}stop(e){if(this._active){this._active=!1;let t,n;for(t=0,n=this.effects.length;t<n;t++)this.effects[t].stop();for(this.effects.length=0,t=0,n=this.cleanups.length;t<n;t++)this.cleanups[t]();if(this.cleanups.length=0,this.scopes){for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!e){let e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.parent=void 0}}};function De(){return k}var A,Oe=new WeakSet,ke=class{constructor(e){this.fn=e,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,k&&(k.active?k.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,Oe.has(this)&&(Oe.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||Ne(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,Ke(this),Ie(this);let e=A,t=He;A=this,He=!0;try{return this.fn()}finally{Le(this),A=e,He=t,this.flags&=-3}}stop(){if(this.flags&1){for(let e=this.deps;e;e=e.nextDep)Be(e);this.deps=this.depsTail=void 0,Ke(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?Oe.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){Re(this)&&this.run()}get dirty(){return Re(this)}},Ae=0,je,Me;function Ne(e,t=!1){if(e.flags|=8,t){e.next=Me,Me=e;return}e.next=je,je=e}function Pe(){Ae++}function Fe(){if(--Ae>0)return;if(Me){let e=Me;for(Me=void 0;e;){let t=e.next;e.next=void 0,e.flags&=-9,e=t}}let e;for(;je;){let t=je;for(je=void 0;t;){let n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(t){e||=t}t=n}}if(e)throw e}function Ie(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Le(e){let t,n=e.depsTail,r=n;for(;r;){let e=r.prevDep;r.version===-1?(r===n&&(n=e),Be(r),Ve(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=e}e.deps=t,e.depsTail=n}function Re(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(ze(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function ze(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===qe)||(e.globalVersion=qe,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Re(e))))return;e.flags|=2;let t=e.dep,n=A,r=He;A=e,He=!0;try{Ie(e);let n=e.fn(e._value);(t.version===0||ce(n,e._value))&&(e.flags|=128,e._value=n,t.version++)}catch(e){throw t.version++,e}finally{A=n,He=r,Le(e),e.flags&=-3}}function Be(e,t=!1){let{dep:n,prevSub:r,nextSub:i}=e;if(r&&(r.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let e=n.computed.deps;e;e=e.nextDep)Be(e,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function Ve(e){let{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}var He=!0,Ue=[];function We(){Ue.push(He),He=!1}function Ge(){let e=Ue.pop();He=e===void 0||e}function Ke(e){let{cleanup:t}=e;if(e.cleanup=void 0,t){let e=A;A=void 0;try{t()}finally{A=e}}}var qe=0,Je=class{constructor(e,t){this.sub=e,this.dep=t,this.version=t.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}},Ye=class{constructor(e){this.computed=e,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(e){if(!A||!He||A===this.computed)return;let t=this.activeLink;if(t===void 0||t.sub!==A)t=this.activeLink=new Je(A,this),A.deps?(t.prevDep=A.depsTail,A.depsTail.nextDep=t,A.depsTail=t):A.deps=A.depsTail=t,Xe(t);else if(t.version===-1&&(t.version=this.version,t.nextDep)){let e=t.nextDep;e.prevDep=t.prevDep,t.prevDep&&(t.prevDep.nextDep=e),t.prevDep=A.depsTail,t.nextDep=void 0,A.depsTail.nextDep=t,A.depsTail=t,A.deps===t&&(A.deps=e)}return t}trigger(e){this.version++,qe++,this.notify(e)}notify(e){Pe();try{for(let e=this.subs;e;e=e.prevSub)e.sub.notify()&&e.sub.dep.notify()}finally{Fe()}}};function Xe(e){if(e.dep.sc++,e.sub.flags&4){let t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let e=t.deps;e;e=e.nextDep)Xe(e)}let n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}var Ze=new WeakMap,Qe=Symbol(``),$e=Symbol(``),et=Symbol(``);function j(e,t,n){if(He&&A){let t=Ze.get(e);t||Ze.set(e,t=new Map);let r=t.get(n);r||(t.set(n,r=new Ye),r.map=t,r.key=n),r.track()}}function tt(e,t,n,r,i,a){let o=Ze.get(e);if(!o){qe++;return}let s=e=>{e&&e.trigger()};if(Pe(),t===`clear`)o.forEach(s);else{let i=d(e),a=i&&te(n);if(i&&n===`length`){let e=Number(r);o.forEach((t,n)=>{(n===`length`||n===et||!_(n)&&n>=e)&&s(t)})}else switch((n!==void 0||o.has(void 0))&&s(o.get(n)),a&&s(o.get(et)),t){case`add`:i?a&&s(o.get(`length`)):(s(o.get(Qe)),f(e)&&s(o.get($e)));break;case`delete`:i||(s(o.get(Qe)),f(e)&&s(o.get($e)));break;case`set`:f(e)&&s(o.get(Qe))}}Fe()}function nt(e){let t=M(e);return t===e?t:(j(t,`iterate`,et),Vt(e)?t:t.map(Wt))}function rt(e){return j(e=M(e),`iterate`,et),e}function it(e,t){return Bt(e)?Gt(zt(e)?Wt(t):t):Wt(t)}var at={__proto__:null,[Symbol.iterator](){return ot(this,Symbol.iterator,e=>it(this,e))},concat(...e){return nt(this).concat(...e.map(e=>d(e)?nt(e):e))},entries(){return ot(this,`entries`,e=>(e[1]=it(this,e[1]),e))},every(e,t){return ct(this,`every`,e,t,void 0,arguments)},filter(e,t){return ct(this,`filter`,e,t,e=>e.map(e=>it(this,e)),arguments)},find(e,t){return ct(this,`find`,e,t,e=>it(this,e),arguments)},findIndex(e,t){return ct(this,`findIndex`,e,t,void 0,arguments)},findLast(e,t){return ct(this,`findLast`,e,t,e=>it(this,e),arguments)},findLastIndex(e,t){return ct(this,`findLastIndex`,e,t,void 0,arguments)},forEach(e,t){return ct(this,`forEach`,e,t,void 0,arguments)},includes(...e){return ut(this,`includes`,e)},indexOf(...e){return ut(this,`indexOf`,e)},join(e){return nt(this).join(e)},lastIndexOf(...e){return ut(this,`lastIndexOf`,e)},map(e,t){return ct(this,`map`,e,t,void 0,arguments)},pop(){return dt(this,`pop`)},push(...e){return dt(this,`push`,e)},reduce(e,...t){return lt(this,`reduce`,e,t)},reduceRight(e,...t){return lt(this,`reduceRight`,e,t)},shift(){return dt(this,`shift`)},some(e,t){return ct(this,`some`,e,t,void 0,arguments)},splice(...e){return dt(this,`splice`,e)},toReversed(){return nt(this).toReversed()},toSorted(e){return nt(this).toSorted(e)},toSpliced(...e){return nt(this).toSpliced(...e)},unshift(...e){return dt(this,`unshift`,e)},values(){return ot(this,`values`,e=>it(this,e))}};function ot(e,t,n){let r=rt(e),i=r[t]();return r!==e&&!Vt(e)&&(i._next=i.next,i.next=()=>{let e=i._next();return e.done||(e.value=n(e.value)),e}),i}var st=Array.prototype;function ct(e,t,n,r,i,a){let o=rt(e),s=o!==e&&!Vt(e),c=o[t];if(c!==st[t]){let t=c.apply(e,a);return s?Wt(t):t}let l=n;o!==e&&(s?l=function(t,r){return n.call(this,it(e,t),r,e)}:n.length>2&&(l=function(t,r){return n.call(this,t,r,e)}));let u=c.call(o,l,r);return s&&i?i(u):u}function lt(e,t,n,r){let i=rt(e),a=i!==e&&!Vt(e),o=n,s=!1;i!==e&&(a?(s=r.length===0,o=function(t,r,i){return s&&(s=!1,t=it(e,t)),n.call(this,t,it(e,r),i,e)}):n.length>3&&(o=function(t,r,i){return n.call(this,t,r,i,e)}));let c=i[t](o,...r);return s?it(e,c):c}function ut(e,t,n){let r=M(e);j(r,`iterate`,et);let i=r[t](...n);return(i===-1||i===!1)&&Ht(n[0])?(n[0]=M(n[0]),r[t](...n)):i}function dt(e,t,n=[]){We(),Pe();let r=M(e)[t].apply(e,n);return Fe(),Ge(),r}var ft=e(`__proto__,__v_isRef,__isVue`),pt=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!==`arguments`&&e!==`caller`).map(e=>Symbol[e]).filter(_));function mt(e){_(e)||(e=String(e));let t=M(this);return j(t,`has`,e),t.hasOwnProperty(e)}var ht=class{constructor(e=!1,t=!1){this._isReadonly=e,this._isShallow=t}get(e,t,n){if(t===`__v_skip`)return e.__v_skip;let r=this._isReadonly,i=this._isShallow;if(t===`__v_isReactive`)return!r;if(t===`__v_isReadonly`)return r;if(t===`__v_isShallow`)return i;if(t===`__v_raw`)return n===(r?i?Nt:Mt:i?jt:At).get(e)||Object.getPrototypeOf(e)===Object.getPrototypeOf(n)?e:void 0;let a=d(e);if(!r){let e;if(a&&(e=at[t]))return e;if(t===`hasOwnProperty`)return mt}let o=Reflect.get(e,t,N(e)?e:n);if((_(t)?pt.has(t):ft(t))||(r||j(e,`get`,t),i))return o;if(N(o)){let e=a&&te(t)?o:o.value;return r&&v(e)?Lt(e):e}return v(o)?r?Lt(o):Ft(o):o}},gt=class extends ht{constructor(e=!1){super(!1,e)}set(e,t,n,r){let i=e[t],a=d(e)&&te(t);if(!this._isShallow){let e=Bt(i);if(!Vt(n)&&!Bt(n)&&(i=M(i),n=M(n)),!a&&N(i)&&!N(n))return e||(i.value=n),!0}let o=a?Number(t)<e.length:u(e,t),s=Reflect.set(e,t,n,N(e)?e:r);return e===M(r)&&(o?ce(n,i)&&tt(e,`set`,t,n,i):tt(e,`add`,t,n)),s}deleteProperty(e,t){let n=u(e,t),r=e[t],i=Reflect.deleteProperty(e,t);return i&&n&&tt(e,`delete`,t,void 0,r),i}has(e,t){let n=Reflect.has(e,t);return(!_(t)||!pt.has(t))&&j(e,`has`,t),n}ownKeys(e){return j(e,`iterate`,d(e)?`length`:Qe),Reflect.ownKeys(e)}},_t=class extends ht{constructor(e=!1){super(!0,e)}set(e,t){return!0}deleteProperty(e,t){return!0}},vt=new gt,yt=new _t,bt=new gt(!0),xt=e=>e,St=e=>Reflect.getPrototypeOf(e);function Ct(e,t,n){return function(...r){let i=this.__v_raw,a=M(i),o=f(a),c=e===`entries`||e===Symbol.iterator&&o,l=e===`keys`&&o,u=i[e](...r),d=n?xt:t?Gt:Wt;return!t&&j(a,`iterate`,l?$e:Qe),s(Object.create(u),{next(){let{value:e,done:t}=u.next();return t?{value:e,done:t}:{value:c?[d(e[0]),d(e[1])]:d(e),done:t}}})}}function wt(e){return function(...t){return e===`delete`?!1:e===`clear`?void 0:this}}function Tt(e,t){let n={get(n){let r=this.__v_raw,i=M(r),a=M(n);e||(ce(n,a)&&j(i,`get`,n),j(i,`get`,a));let{has:o}=St(i),s=t?xt:e?Gt:Wt;if(o.call(i,n))return s(r.get(n));if(o.call(i,a))return s(r.get(a));r!==i&&r.get(n)},get size(){let t=this.__v_raw;return!e&&j(M(t),`iterate`,Qe),t.size},has(t){let n=this.__v_raw,r=M(n),i=M(t);return e||(ce(t,i)&&j(r,`has`,t),j(r,`has`,i)),t===i?n.has(t):n.has(t)||n.has(i)},forEach(n,r){let i=this,a=i.__v_raw,o=M(a),s=t?xt:e?Gt:Wt;return!e&&j(o,`iterate`,Qe),a.forEach((e,t)=>n.call(r,s(e),s(t),i))}};return s(n,e?{add:wt(`add`),set:wt(`set`),delete:wt(`delete`),clear:wt(`clear`)}:{add(e){let n=M(this),r=St(n),i=M(e),a=!t&&!Vt(e)&&!Bt(e)?i:e;return r.has.call(n,a)||ce(e,a)&&r.has.call(n,e)||ce(i,a)&&r.has.call(n,i)||(n.add(a),tt(n,`add`,a,a)),this},set(e,n){!t&&!Vt(n)&&!Bt(n)&&(n=M(n));let r=M(this),{has:i,get:a}=St(r),o=i.call(r,e);o||=(e=M(e),i.call(r,e));let s=a.call(r,e);return r.set(e,n),o?ce(n,s)&&tt(r,`set`,e,n,s):tt(r,`add`,e,n),this},delete(e){let t=M(this),{has:n,get:r}=St(t),i=n.call(t,e);i||=(e=M(e),n.call(t,e));let a=r?r.call(t,e):void 0,o=t.delete(e);return i&&tt(t,`delete`,e,void 0,a),o},clear(){let e=M(this),t=e.size!==0,n=e.clear();return t&&tt(e,`clear`,void 0,void 0,void 0),n}}),[`keys`,`values`,`entries`,Symbol.iterator].forEach(r=>{n[r]=Ct(r,e,t)}),n}function Et(e,t){let n=Tt(e,t);return(t,r,i)=>r===`__v_isReactive`?!e:r===`__v_isReadonly`?e:r===`__v_raw`?t:Reflect.get(u(n,r)&&r in t?n:t,r,i)}var Dt={get:Et(!1,!1)},Ot={get:Et(!1,!0)},kt={get:Et(!0,!1)},At=new WeakMap,jt=new WeakMap,Mt=new WeakMap,Nt=new WeakMap;function Pt(e){switch(e){case`Object`:case`Array`:return 1;case`Map`:case`Set`:case`WeakMap`:case`WeakSet`:return 2;default:return 0}}function Ft(e){return Bt(e)?e:Rt(e,!1,vt,Dt,At)}function It(e){return Rt(e,!1,bt,Ot,jt)}function Lt(e){return Rt(e,!0,yt,kt,Mt)}function Rt(e,t,n,r,i){if(!v(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;let a=i.get(e);if(a)return a;let o=Pt(ee(e));if(o===0)return e;let s=new Proxy(e,o===2?r:n);return i.set(e,s),s}function zt(e){return Bt(e)?zt(e.__v_raw):!!(e&&e.__v_isReactive)}function Bt(e){return!!(e&&e.__v_isReadonly)}function Vt(e){return!!(e&&e.__v_isShallow)}function Ht(e){return e?!!e.__v_raw:!1}function M(e){let t=e&&e.__v_raw;return t?M(t):e}function Ut(e){return!u(e,`__v_skip`)&&Object.isExtensible(e)&&T(e,`__v_skip`,!0),e}var Wt=e=>v(e)?Ft(e):e,Gt=e=>v(e)?Lt(e):e;function N(e){return e?e.__v_isRef===!0:!1}function P(e){return Kt(e,!1)}function Kt(e,t){return N(e)?e:new qt(e,t)}var qt=class{constructor(e,t){this.dep=new Ye,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=t?e:M(e),this._value=t?e:Wt(e),this.__v_isShallow=t}get value(){return this.dep.track(),this._value}set value(e){let t=this._rawValue,n=this.__v_isShallow||Vt(e)||Bt(e);e=n?e:M(e),ce(e,t)&&(this._rawValue=e,this._value=n?e:Wt(e),this.dep.trigger())}};function F(e){return N(e)?e.value:e}var Jt={get:(e,t,n)=>t===`__v_raw`?e:F(Reflect.get(e,t,n)),set:(e,t,n,r)=>{let i=e[t];return N(i)&&!N(n)?(i.value=n,!0):Reflect.set(e,t,n,r)}};function Yt(e){return zt(e)?e:new Proxy(e,Jt)}var Xt=class{constructor(e,t,n){this.fn=e,this.setter=t,this._value=void 0,this.dep=new Ye(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=qe-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!t,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&A!==this)return Ne(this,!0),!0}get value(){let e=this.dep.track();return ze(this),e&&(e.version=this.dep.version),this._value}set value(e){this.setter&&this.setter(e)}};function Zt(e,t,n=!1){let r,i;return h(e)?r=e:(r=e.get,i=e.set),new Xt(r,i,n)}var Qt={},$t=new WeakMap,en=void 0;function tn(e,t=!1,n=en){if(n){let t=$t.get(n);t||$t.set(n,t=[]),t.push(e)}}function nn(e,n,i=t){let{immediate:a,deep:o,once:s,scheduler:l,augmentJob:u,call:f}=i,p=e=>o?e:Vt(e)||o===!1||o===0?rn(e,1):rn(e),m,g,_,v,y=!1,b=!1;if(N(e)?(g=()=>e.value,y=Vt(e)):zt(e)?(g=()=>p(e),y=!0):d(e)?(b=!0,y=e.some(e=>zt(e)||Vt(e)),g=()=>e.map(e=>{if(N(e))return e.value;if(zt(e))return p(e);if(h(e))return f?f(e,2):e()})):g=h(e)?n?f?()=>f(e,2):e:()=>{if(_){We();try{_()}finally{Ge()}}let t=en;en=m;try{return f?f(e,3,[v]):e(v)}finally{en=t}}:r,n&&o){let e=g,t=o===!0?1/0:o;g=()=>rn(e(),t)}let x=De(),ee=()=>{m.stop(),x&&x.active&&c(x.effects,m)};if(s&&n){let e=n;n=(...t)=>{e(...t),ee()}}let S=b?Array(e.length).fill(Qt):Qt,te=e=>{if(!(!(m.flags&1)||!m.dirty&&!e)){if(n){let e=m.run();if(o||y||(b?e.some((e,t)=>ce(e,S[t])):ce(e,S))){_&&_();let t=en;en=m;try{let t=[e,S===Qt?void 0:b&&S[0]===Qt?[]:S,v];S=e,f?f(n,3,t):n(...t)}finally{en=t}}}else m.run()}};return u&&u(te),m=new ke(g),m.scheduler=l?()=>l(te,!1):te,v=e=>tn(e,!1,m),_=m.onStop=()=>{let e=$t.get(m);if(e){if(f)f(e,4);else for(let t of e)t();$t.delete(m)}},n?a?te(!0):S=m.run():l?l(te.bind(null,!0),!0):m.run(),ee.pause=m.pause.bind(m),ee.resume=m.resume.bind(m),ee.stop=ee,ee}function rn(e,t=1/0,n){if(t<=0||!v(e)||e.__v_skip||(n||=new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,N(e))rn(e.value,t,n);else if(d(e))for(let r=0;r<e.length;r++)rn(e[r],t,n);else if(p(e)||f(e))e.forEach(e=>{rn(e,t,n)});else if(S(e)){for(let r in e)rn(e[r],t,n);for(let r of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,r)&&rn(e[r],t,n)}return e}function an(e,t,n,r){try{return r?e(...r):e()}catch(e){sn(e,t,n)}}function on(e,t,n,r){if(h(e)){let i=an(e,t,n,r);return i&&y(i)&&i.catch(e=>{sn(e,t,n)}),i}if(d(e)){let i=[];for(let a=0;a<e.length;a++)i.push(on(e[a],t,n,r));return i}}function sn(e,n,r,i=!0){let a=n?n.vnode:null,{errorHandler:o,throwUnhandledErrorInProduction:s}=n&&n.appContext.config||t;if(n){let t=n.parent,i=n.proxy,a=`https://vuejs.org/error-reference/#runtime-${r}`;for(;t;){let n=t.ec;if(n){for(let t=0;t<n.length;t++)if(n[t](e,i,a)===!1)return}t=t.parent}if(o){We(),an(o,null,10,[e,i,a]),Ge();return}}cn(e,r,a,i,s)}function cn(e,t,n,r=!0,i=!1){if(i)throw e;console.error(e)}var I=[],ln=-1,un=[],dn=null,fn=0,pn=Promise.resolve(),mn=null;function hn(e){let t=mn||pn;return e?t.then(this?e.bind(this):e):t}function gn(e){let t=ln+1,n=I.length;for(;t<n;){let r=t+n>>>1,i=I[r],a=Sn(i);a<e||a===e&&i.flags&2?t=r+1:n=r}return t}function _n(e){if(!(e.flags&1)){let t=Sn(e),n=I[I.length-1];!n||!(e.flags&2)&&t>=Sn(n)?I.push(e):I.splice(gn(t),0,e),e.flags|=1,vn()}}function vn(){mn||=pn.then(Cn)}function yn(e){d(e)?un.push(...e):dn&&e.id===-1?dn.splice(fn+1,0,e):e.flags&1||(un.push(e),e.flags|=1),vn()}function bn(e,t,n=ln+1){for(;n<I.length;n++){let t=I[n];if(t&&t.flags&2){if(e&&t.id!==e.uid)continue;I.splice(n,1),n--,t.flags&4&&(t.flags&=-2),t(),t.flags&4||(t.flags&=-2)}}}function xn(e){if(un.length){let e=[...new Set(un)].sort((e,t)=>Sn(e)-Sn(t));if(un.length=0,dn){dn.push(...e);return}for(dn=e,fn=0;fn<dn.length;fn++){let e=dn[fn];e.flags&4&&(e.flags&=-2),e.flags&8||e(),e.flags&=-2}dn=null,fn=0}}var Sn=e=>e.id==null?e.flags&2?-1:1/0:e.id;function Cn(e){try{for(ln=0;ln<I.length;ln++){let e=I[ln];e&&!(e.flags&8)&&(e.flags&4&&(e.flags&=-2),an(e,e.i,e.i?15:14),e.flags&4||(e.flags&=-2))}}finally{for(;ln<I.length;ln++){let e=I[ln];e&&(e.flags&=-2)}ln=-1,I.length=0,xn(e),mn=null,(I.length||un.length)&&Cn(e)}}var wn=null,Tn=null;function En(e){let t=wn;return wn=e,Tn=e&&e.type.__scopeId||null,t}function Dn(e,t=wn,n){if(!t||e._n)return e;let r=(...n)=>{r._d&&ki(-1);let i=En(t),a;try{a=e(...n)}finally{En(i),r._d&&ki(1)}return a};return r._n=!0,r._c=!0,r._d=!0,r}function On(e,n){if(wn===null)return e;let r=la(wn),i=e.dirs||=[];for(let e=0;e<n.length;e++){let[a,o,s,c=t]=n[e];a&&(h(a)&&(a={mounted:a,updated:a}),a.deep&&rn(o),i.push({dir:a,instance:r,value:o,oldValue:void 0,arg:s,modifiers:c}))}return e}function kn(e,t,n,r){let i=e.dirs,a=t&&t.dirs;for(let o=0;o<i.length;o++){let s=i[o];a&&(s.oldValue=a[o].value);let c=s.dir[r];c&&(We(),on(c,n,8,[e.el,s,e,t]),Ge())}}function An(e,t){if(J){let n=J.provides,r=J.parent&&J.parent.provides;r===n&&(n=J.provides=Object.create(r)),n[e]=t}}function jn(e,t,n=!1){let r=Ji();if(r||Pr){let i=Pr?Pr._context.provides:r?r.parent==null||r.ce?r.vnode.appContext&&r.vnode.appContext.provides:r.parent.provides:void 0;if(i&&e in i)return i[e];if(arguments.length>1)return n&&h(t)?t.call(r&&r.proxy):t}}var Mn=Symbol.for(`v-scx`),Nn=()=>jn(Mn);function Pn(e,t,n){return Fn(e,t,n)}function Fn(e,n,i=t){let{immediate:a,deep:o,flush:c,once:l}=i,u=s({},i),d=n&&a||!n&&c!==`post`,f;if(ea){if(c===`sync`){let e=Nn();f=e.__watcherHandles||=[]}else if(!d){let e=()=>{};return e.stop=r,e.resume=r,e.pause=r,e}}let p=J;u.call=(e,t,n)=>on(e,p,t,n);let m=!1;c===`post`?u.scheduler=e=>{B(e,p&&p.suspense)}:c!==`sync`&&(m=!0,u.scheduler=(e,t)=>{t?e():_n(e)}),u.augmentJob=e=>{n&&(e.flags|=4),m&&(e.flags|=2,p&&(e.id=p.uid,e.i=p))};let h=nn(e,n,u);return ea&&(f?f.push(h):d&&h()),h}function In(e,t,n){let r=this.proxy,i=g(e)?e.includes(`.`)?Ln(r,e):()=>r[e]:e.bind(r,r),a;h(t)?a=t:(a=t.handler,n=t);let o=Zi(this),s=Fn(i,a.bind(r),n);return o(),s}function Ln(e,t){let n=t.split(`.`);return()=>{let t=e;for(let e=0;e<n.length&&t;e++)t=t[n[e]];return t}}var Rn=Symbol(`_vte`),zn=e=>e.__isTeleport,Bn=Symbol(`_leaveCb`);function Vn(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Vn(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function L(e,t){return h(e)?s({name:e.name},t,{setup:e}):e}function Hn(e){e.ids=[e.ids[0]+e.ids[2]+++`-`,0,0]}function Un(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}var Wn=new WeakMap;function Gn(e,n,r,a,o=!1){if(d(e)){e.forEach((e,t)=>Gn(e,n&&(d(n)?n[t]:n),r,a,o));return}if(qn(a)&&!o){a.shapeFlag&512&&a.type.__asyncResolved&&a.component.subTree.component&&Gn(e,n,r,a.component.subTree);return}let s=a.shapeFlag&4?la(a.component):a.el,l=o?null:s,{i:f,r:p}=e,m=n&&n.r,_=f.refs===t?f.refs={}:f.refs,v=f.setupState,y=M(v),b=v===t?i:e=>!Un(_,e)&&u(y,e),x=(e,t)=>!(t&&Un(_,t));if(m!=null&&m!==p){if(Kn(n),g(m))_[m]=null,b(m)&&(v[m]=null);else if(N(m)){let e=n;x(m,e.k)&&(m.value=null),e.k&&(_[e.k]=null)}}if(h(p))an(p,f,12,[l,_]);else{let t=g(p),n=N(p);if(t||n){let i=()=>{if(e.f){let n=t?b(p)?v[p]:_[p]:x(p)||!e.k?p.value:_[e.k];if(o)d(n)&&c(n,s);else if(d(n))n.includes(s)||n.push(s);else if(t)_[p]=[s],b(p)&&(v[p]=_[p]);else{let t=[s];x(p,e.k)&&(p.value=t),e.k&&(_[e.k]=t)}}else t?(_[p]=l,b(p)&&(v[p]=l)):n&&(x(p,e.k)&&(p.value=l),e.k&&(_[e.k]=l))};if(l){let t=()=>{i(),Wn.delete(e)};t.id=-1,Wn.set(e,t),B(t,r)}else Kn(e),i()}}}function Kn(e){let t=Wn.get(e);t&&(t.flags|=8,Wn.delete(e))}fe().requestIdleCallback,fe().cancelIdleCallback;var qn=e=>!!e.type.__asyncLoader,Jn=e=>e.type.__isKeepAlive;function Yn(e,t){Zn(e,`a`,t)}function Xn(e,t){Zn(e,`da`,t)}function Zn(e,t,n=J){let r=e.__wdc||=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}return e()};if($n(t,r,n),n){let e=n.parent;for(;e&&e.parent;)Jn(e.parent.vnode)&&Qn(r,t,n,e),e=e.parent}}function Qn(e,t,n,r){let i=$n(t,e,r,!0);or(()=>{c(r[t],i)},n)}function $n(e,t,n=J,r=!1){if(n){let i=n[e]||(n[e]=[]),a=t.__weh||=(...r)=>{We();let i=Zi(n),a=on(t,n,e,r);return i(),Ge(),a};return r?i.unshift(a):i.push(a),a}}var er=e=>(t,n=J)=>{(!ea||e===`sp`)&&$n(e,(...e)=>t(...e),n)},tr=er(`bm`),nr=er(`m`),rr=er(`bu`),ir=er(`u`),ar=er(`bum`),or=er(`um`),sr=er(`sp`),cr=er(`rtg`),lr=er(`rtc`);function ur(e,t=J){$n(`ec`,e,t)}var dr=Symbol.for(`v-ndc`);function R(e,t,n,r){let i,a=n&&n[r],o=d(e);if(o||g(e)){let n=o&&zt(e),r=!1,s=!1;n&&(r=!Vt(e),s=Bt(e),e=rt(e)),i=Array(e.length);for(let n=0,o=e.length;n<o;n++)i[n]=t(r?s?Gt(Wt(e[n])):Wt(e[n]):e[n],n,void 0,a&&a[n])}else if(typeof e==`number`){i=Array(e);for(let n=0;n<e;n++)i[n]=t(n+1,n,void 0,a&&a[n])}else if(v(e)){if(e[Symbol.iterator])i=Array.from(e,(e,n)=>t(e,n,void 0,a&&a[n]));else{let n=Object.keys(e);i=Array(n.length);for(let r=0,o=n.length;r<o;r++){let o=n[r];i[r]=t(e[o],o,r,a&&a[r])}}}else i=[];return n&&(n[r]=i),i}var fr=e=>e?$i(e)?la(e):fr(e.parent):null,pr=s(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>fr(e.parent),$root:e=>fr(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Sr(e),$forceUpdate:e=>e.f||=()=>{_n(e.update)},$nextTick:e=>e.n||=hn.bind(e.proxy),$watch:e=>In.bind(e)}),mr=(e,n)=>e!==t&&!e.__isScriptSetup&&u(e,n),hr={get({_:e},n){if(n===`__v_skip`)return!0;let{ctx:r,setupState:i,data:a,props:o,accessCache:s,type:c,appContext:l}=e;if(n[0]!==`$`){let e=s[n];if(e!==void 0)switch(e){case 1:return i[n];case 2:return a[n];case 4:return r[n];case 3:return o[n]}else if(mr(i,n))return s[n]=1,i[n];else if(a!==t&&u(a,n))return s[n]=2,a[n];else if(u(o,n))return s[n]=3,o[n];else if(r!==t&&u(r,n))return s[n]=4,r[n];else _r&&(s[n]=0)}let d=pr[n],f,p;if(d)return n===`$attrs`&&j(e.attrs,`get`,``),d(e);if((f=c.__cssModules)&&(f=f[n]))return f;if(r!==t&&u(r,n))return s[n]=4,r[n];if(p=l.config.globalProperties,u(p,n))return p[n]},set({_:e},n,r){let{data:i,setupState:a,ctx:o}=e;return mr(a,n)?(a[n]=r,!0):i!==t&&u(i,n)?(i[n]=r,!0):u(e.props,n)||n[0]===`$`&&n.slice(1)in e?!1:(o[n]=r,!0)},has({_:{data:e,setupState:n,accessCache:r,ctx:i,appContext:a,props:o,type:s}},c){let l;return!!(r[c]||e!==t&&c[0]!==`$`&&u(e,c)||mr(n,c)||u(o,c)||u(i,c)||u(pr,c)||u(a.config.globalProperties,c)||(l=s.__cssModules)&&l[c])},defineProperty(e,t,n){return n.get==null?u(n,`value`)&&this.set(e,t,n.value,null):e._.accessCache[t]=0,Reflect.defineProperty(e,t,n)}};function gr(e){return d(e)?e.reduce((e,t)=>(e[t]=null,e),{}):e}var _r=!0;function vr(e){let t=Sr(e),n=e.proxy,i=e.ctx;_r=!1,t.beforeCreate&&br(t.beforeCreate,e,`bc`);let{data:a,computed:o,methods:s,watch:c,provide:l,inject:u,created:f,beforeMount:p,mounted:m,beforeUpdate:g,updated:_,activated:y,deactivated:b,beforeDestroy:x,beforeUnmount:ee,destroyed:S,unmounted:te,render:ne,renderTracked:re,renderTriggered:ie,errorCaptured:C,serverPrefetch:ae,expose:w,inheritAttrs:oe,components:se,directives:ce,filters:le}=t;if(u&&yr(u,i,null),s)for(let e in s){let t=s[e];h(t)&&(i[e]=t.bind(n))}if(a){let t=a.call(n,n);v(t)&&(e.data=Ft(t))}if(_r=!0,o)for(let e in o){let t=o[e],a=Y({get:h(t)?t.bind(n,n):h(t.get)?t.get.bind(n,n):r,set:!h(t)&&h(t.set)?t.set.bind(n):r});Object.defineProperty(i,e,{enumerable:!0,configurable:!0,get:()=>a.value,set:e=>a.value=e})}if(c)for(let e in c)xr(c[e],i,n,e);if(l){let e=h(l)?l.call(n):l;Reflect.ownKeys(e).forEach(t=>{An(t,e[t])})}f&&br(f,e,`c`);function T(e,t){d(t)?t.forEach(t=>e(t.bind(n))):t&&e(t.bind(n))}if(T(tr,p),T(nr,m),T(rr,g),T(ir,_),T(Yn,y),T(Xn,b),T(ur,C),T(lr,re),T(cr,ie),T(ar,ee),T(or,te),T(sr,ae),d(w)){if(w.length){let t=e.exposed||={};w.forEach(e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t,enumerable:!0})})}else e.exposed||={}}ne&&e.render===r&&(e.render=ne),oe!=null&&(e.inheritAttrs=oe),se&&(e.components=se),ce&&(e.directives=ce),ae&&Hn(e)}function yr(e,t,n=r){d(e)&&(e=Dr(e));for(let n in e){let r=e[n],i;i=v(r)?`default`in r?jn(r.from||n,r.default,!0):jn(r.from||n):jn(r),N(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e}):t[n]=i}}function br(e,t,n){on(d(e)?e.map(e=>e.bind(t.proxy)):e.bind(t.proxy),t,n)}function xr(e,t,n,r){let i=r.includes(`.`)?Ln(n,r):()=>n[r];if(g(e)){let n=t[e];h(n)&&Pn(i,n)}else if(h(e))Pn(i,e.bind(n));else if(v(e)){if(d(e))e.forEach(e=>xr(e,t,n,r));else{let r=h(e.handler)?e.handler.bind(n):t[e.handler];h(r)&&Pn(i,r,e)}}}function Sr(e){let t=e.type,{mixins:n,extends:r}=t,{mixins:i,optionsCache:a,config:{optionMergeStrategies:o}}=e.appContext,s=a.get(t),c;return s?c=s:!i.length&&!n&&!r?c=t:(c={},i.length&&i.forEach(e=>Cr(c,e,o,!0)),Cr(c,t,o)),v(t)&&a.set(t,c),c}function Cr(e,t,n,r=!1){let{mixins:i,extends:a}=t;a&&Cr(e,a,n,!0),i&&i.forEach(t=>Cr(e,t,n,!0));for(let i in t)if(!(r&&i===`expose`)){let r=wr[i]||n&&n[i];e[i]=r?r(e[i],t[i]):t[i]}return e}var wr={data:Tr,props:kr,emits:kr,methods:Or,computed:Or,beforeCreate:z,created:z,beforeMount:z,mounted:z,beforeUpdate:z,updated:z,beforeDestroy:z,beforeUnmount:z,destroyed:z,unmounted:z,activated:z,deactivated:z,errorCaptured:z,serverPrefetch:z,components:Or,directives:Or,watch:Ar,provide:Tr,inject:Er};function Tr(e,t){return t?e?function(){return s(h(e)?e.call(this,this):e,h(t)?t.call(this,this):t)}:t:e}function Er(e,t){return Or(Dr(e),Dr(t))}function Dr(e){if(d(e)){let t={};for(let n=0;n<e.length;n++)t[e[n]]=e[n];return t}return e}function z(e,t){return e?[...new Set([].concat(e,t))]:t}function Or(e,t){return e?s(Object.create(null),e,t):t}function kr(e,t){return e?d(e)&&d(t)?[...new Set([...e,...t])]:s(Object.create(null),gr(e),gr(t??{})):t}function Ar(e,t){if(!e)return t;if(!t)return e;let n=s(Object.create(null),e);for(let r in t)n[r]=z(e[r],t[r]);return n}function jr(){return{app:null,config:{isNativeTag:i,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}var Mr=0;function Nr(e,t){return function(n,r=null){h(n)||(n=s({},n)),r!=null&&!v(r)&&(r=null);let i=jr(),a=new WeakSet,o=[],c=!1,l=i.app={_uid:Mr++,_component:n,_props:r,_container:null,_context:i,_instance:null,version:da,get config(){return i.config},set config(e){},use(e,...t){return a.has(e)||(e&&h(e.install)?(a.add(e),e.install(l,...t)):h(e)&&(a.add(e),e(l,...t))),l},mixin(e){return i.mixins.includes(e)||i.mixins.push(e),l},component(e,t){return t?(i.components[e]=t,l):i.components[e]},directive(e,t){return t?(i.directives[e]=t,l):i.directives[e]},mount(a,o,s){if(!c){let u=l._ceVNode||K(n,r);return u.appContext=i,s===!0?s=`svg`:s===!1&&(s=void 0),o&&t?t(u,a):e(u,a,s),c=!0,l._container=a,a.__vue_app__=l,la(u.component)}},onUnmount(e){o.push(e)},unmount(){c&&(on(o,l._instance,16),e(null,l._container),delete l._container.__vue_app__)},provide(e,t){return i.provides[e]=t,l},runWithContext(e){let t=Pr;Pr=l;try{return e()}finally{Pr=t}}};return l}}var Pr=null,Fr=(e,t)=>t===`modelValue`||t===`model-value`?e.modelModifiers:e[`${t}Modifiers`]||e[`${C(t)}Modifiers`]||e[`${w(t)}Modifiers`];function Ir(e,n,...r){if(e.isUnmounted)return;let i=e.vnode.props||t,a=r,o=n.startsWith(`update:`),s=o&&Fr(i,n.slice(7));s&&(s.trim&&(a=r.map(e=>g(e)?e.trim():e)),s.number&&(a=r.map(ue)));let c,l=i[c=se(n)]||i[c=se(C(n))];!l&&o&&(l=i[c=se(w(n))]),l&&on(l,e,6,a);let u=i[c+`Once`];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[c])return;e.emitted[c]=!0,on(u,e,6,a)}}var Lr=new WeakMap;function Rr(e,t,n=!1){let r=n?Lr:t.emitsCache,i=r.get(e);if(i!==void 0)return i;let a=e.emits,o={},c=!1;if(!h(e)){let r=e=>{let n=Rr(e,t,!0);n&&(c=!0,s(o,n))};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}return!a&&!c?(v(e)&&r.set(e,null),null):(d(a)?a.forEach(e=>o[e]=null):s(o,a),v(e)&&r.set(e,o),o)}function zr(e,t){return!e||!a(t)?!1:(t=t.slice(2).replace(/Once$/,``),u(e,t[0].toLowerCase()+t.slice(1))||u(e,w(t))||u(e,t))}function Br(e){let{type:t,vnode:n,proxy:r,withProxy:i,propsOptions:[a],slots:s,attrs:c,emit:l,render:u,renderCache:d,props:f,data:p,setupState:m,ctx:h,inheritAttrs:g}=e,_=En(e),v,y;try{if(n.shapeFlag&4){let e=i||r,t=e;v=Bi(u.call(t,e,d,f,m,p,h)),y=c}else{let e=t;v=Bi(e.length>1?e(f,{attrs:c,slots:s,emit:l}):e(f,null)),y=t.props?c:Vr(c)}}catch(t){Ei.length=0,sn(t,e,1),v=K(wi)}let b=v;if(y&&g!==!1){let e=Object.keys(y),{shapeFlag:t}=b;e.length&&t&7&&(a&&e.some(o)&&(y=Hr(y,a)),b=Ri(b,y,!1,!0))}return n.dirs&&(b=Ri(b,null,!1,!0),b.dirs=b.dirs?b.dirs.concat(n.dirs):n.dirs),n.transition&&Vn(b,n.transition),v=b,En(_),v}var Vr=e=>{let t;for(let n in e)(n===`class`||n===`style`||a(n))&&((t||={})[n]=e[n]);return t},Hr=(e,t)=>{let n={};for(let r in e)(!o(r)||!(r.slice(9)in t))&&(n[r]=e[r]);return n};function Ur(e,t,n){let{props:r,children:i,component:a}=e,{props:o,children:s,patchFlag:c}=t,l=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&c>=0){if(c&1024)return!0;if(c&16)return r?Wr(r,o,l):!!o;if(c&8){let e=t.dynamicProps;for(let t=0;t<e.length;t++){let n=e[t];if(Gr(o,r,n)&&!zr(l,n))return!0}}}else return(i||s)&&(!s||!s.$stable)?!0:r===o?!1:r?!o||Wr(r,o,l):!!o;return!1}function Wr(e,t,n){let r=Object.keys(t);if(r.length!==Object.keys(e).length)return!0;for(let i=0;i<r.length;i++){let a=r[i];if(Gr(t,e,a)&&!zr(n,a))return!0}return!1}function Gr(e,t,n){let r=e[n],i=t[n];return n===`style`&&v(r)&&v(i)?!xe(r,i):r!==i}function Kr({vnode:e,parent:t,suspense:n},r){for(;t;){let n=t.subTree;if(n.suspense&&n.suspense.activeBranch===e&&(n.suspense.vnode.el=n.el=r,e=n),n===e)(e=t.vnode).el=r,t=t.parent;else break}n&&n.activeBranch===e&&(n.vnode.el=r)}var qr={},Jr=()=>Object.create(qr),Yr=e=>Object.getPrototypeOf(e)===qr;function Xr(e,t,n,r=!1){let i={},a=Jr();e.propsDefaults=Object.create(null),Qr(e,t,i,a);for(let t in e.propsOptions[0])t in i||(i[t]=void 0);e.props=n?r?i:It(i):e.type.props?i:a,e.attrs=a}function Zr(e,t,n,r){let{props:i,attrs:a,vnode:{patchFlag:o}}=e,s=M(i),[c]=e.propsOptions,l=!1;if((r||o>0)&&!(o&16)){if(o&8){let n=e.vnode.dynamicProps;for(let r=0;r<n.length;r++){let o=n[r];if(zr(e.emitsOptions,o))continue;let d=t[o];if(c){if(u(a,o))d!==a[o]&&(a[o]=d,l=!0);else{let t=C(o);i[t]=$r(c,s,t,d,e,!1)}}else d!==a[o]&&(a[o]=d,l=!0)}}}else{Qr(e,t,i,a)&&(l=!0);let r;for(let a in s)(!t||!u(t,a)&&((r=w(a))===a||!u(t,r)))&&(c?n&&(n[a]!==void 0||n[r]!==void 0)&&(i[a]=$r(c,s,a,void 0,e,!0)):delete i[a]);if(a!==s)for(let e in a)(!t||!u(t,e))&&(delete a[e],l=!0)}l&&tt(e.attrs,`set`,``)}function Qr(e,n,r,i){let[a,o]=e.propsOptions,s=!1,c;if(n)for(let t in n){if(ne(t))continue;let l=n[t],d;a&&u(a,d=C(t))?!o||!o.includes(d)?r[d]=l:(c||={})[d]=l:zr(e.emitsOptions,t)||(!(t in i)||l!==i[t])&&(i[t]=l,s=!0)}if(o){let n=M(r),i=c||t;for(let t=0;t<o.length;t++){let s=o[t];r[s]=$r(a,n,s,i[s],e,!u(i,s))}}return s}function $r(e,t,n,r,i,a){let o=e[n];if(o!=null){let e=u(o,`default`);if(e&&r===void 0){let e=o.default;if(o.type!==Function&&!o.skipFactory&&h(e)){let{propsDefaults:a}=i;if(n in a)r=a[n];else{let o=Zi(i);r=a[n]=e.call(null,t),o()}}else r=e;i.ce&&i.ce._setProp(n,r)}o[0]&&(a&&!e?r=!1:o[1]&&(r===``||r===w(n))&&(r=!0))}return r}var ei=new WeakMap;function ti(e,r,i=!1){let a=i?ei:r.propsCache,o=a.get(e);if(o)return o;let c=e.props,l={},f=[],p=!1;if(!h(e)){let t=e=>{p=!0;let[t,n]=ti(e,r,!0);s(l,t),n&&f.push(...n)};!i&&r.mixins.length&&r.mixins.forEach(t),e.extends&&t(e.extends),e.mixins&&e.mixins.forEach(t)}if(!c&&!p)return v(e)&&a.set(e,n),n;if(d(c))for(let e=0;e<c.length;e++){let n=C(c[e]);ni(n)&&(l[n]=t)}else if(c)for(let e in c){let t=C(e);if(ni(t)){let n=c[e],r=l[t]=d(n)||h(n)?{type:n}:s({},n),i=r.type,a=!1,o=!0;if(d(i))for(let e=0;e<i.length;++e){let t=i[e],n=h(t)&&t.name;if(n===`Boolean`){a=!0;break}n===`String`&&(o=!1)}else a=h(i)&&i.name===`Boolean`;r[0]=a,r[1]=o,(a||u(r,`default`))&&f.push(t)}}let m=[l,f];return v(e)&&a.set(e,m),m}function ni(e){return e[0]!==`$`&&!ne(e)}var ri=e=>e===`_`||e===`_ctx`||e===`$stable`,ii=e=>d(e)?e.map(Bi):[Bi(e)],ai=(e,t,n)=>{if(t._n)return t;let r=Dn((...e)=>ii(t(...e)),n);return r._c=!1,r},oi=(e,t,n)=>{let r=e._ctx;for(let n in e){if(ri(n))continue;let i=e[n];if(h(i))t[n]=ai(n,i,r);else if(i!=null){let e=ii(i);t[n]=()=>e}}},si=(e,t)=>{let n=ii(t);e.slots.default=()=>n},ci=(e,t,n)=>{for(let r in t)(n||!ri(r))&&(e[r]=t[r])},li=(e,t,n)=>{let r=e.slots=Jr();if(e.vnode.shapeFlag&32){let e=t._;e?(ci(r,t,n),n&&T(r,`_`,e,!0)):oi(t,r)}else t&&si(e,t)},ui=(e,n,r)=>{let{vnode:i,slots:a}=e,o=!0,s=t;if(i.shapeFlag&32){let e=n._;e?r&&e===1?o=!1:ci(a,n,r):(o=!n.$stable,oi(n,a)),s=n}else n&&(si(e,n),s={default:1});if(o)for(let e in a)!ri(e)&&s[e]==null&&delete a[e]},B=Si;function di(e){return fi(e)}function fi(e,i){let a=fe();a.__VUE__=!0;let{insert:o,remove:s,patchProp:c,createElement:l,createText:u,createComment:d,setText:f,setElementText:p,parentNode:m,nextSibling:h,setScopeId:g=r,insertStaticContent:_}=e,v=(e,t,n,r=null,i=null,a=null,o=void 0,s=null,c=!!t.dynamicChildren)=>{if(e===t)return;e&&!Ni(e,t)&&(r=xe(e),D(e,i,a,!0),e=null),t.patchFlag===-2&&(c=!1,t.dynamicChildren=null);let{type:l,ref:u,shapeFlag:d}=t;switch(l){case Ci:y(e,t,n,r);break;case wi:b(e,t,n,r);break;case Ti:e??x(t,n,r,o);break;case V:se(e,t,n,r,i,a,o,s,c);break;default:d&1?te(e,t,n,r,i,a,o,s,c):d&6?ce(e,t,n,r,i,a,o,s,c):(d&64||d&128)&&l.process(e,t,n,r,i,a,o,s,c,O)}u!=null&&i?Gn(u,e&&e.ref,a,t||e,!t):u==null&&e&&e.ref!=null&&Gn(e.ref,null,a,e,!0)},y=(e,t,n,r)=>{if(e==null)o(t.el=u(t.children),n,r);else{let n=t.el=e.el;t.children!==e.children&&f(n,t.children)}},b=(e,t,n,r)=>{e==null?o(t.el=d(t.children||``),n,r):t.el=e.el},x=(e,t,n,r)=>{[e.el,e.anchor]=_(e.children,t,n,r,e.el,e.anchor)},ee=({el:e,anchor:t},n,r)=>{let i;for(;e&&e!==t;)i=h(e),o(e,n,r),e=i;o(t,n,r)},S=({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=h(e),s(e),e=n;s(t)},te=(e,t,n,r,i,a,o,s,c)=>{if(t.type===`svg`?o=`svg`:t.type===`math`&&(o=`mathml`),e==null)re(t,n,r,i,a,o,s,c);else{let n=e.el&&e.el._isVueCE?e.el:null;try{n&&n._beginPatch(),ae(e,t,i,a,o,s,c)}finally{n&&n._endPatch()}}},re=(e,t,n,r,i,a,s,u)=>{let d,f,{props:m,shapeFlag:h,transition:g,dirs:_}=e;if(d=e.el=l(e.type,a,m&&m.is,m),h&8?p(d,e.children):h&16&&C(e.children,d,null,r,i,pi(e,a),s,u),_&&kn(e,null,r,`created`),ie(d,e,e.scopeId,s,r),m){for(let e in m)e!==`value`&&!ne(e)&&c(d,e,null,m[e],a,r);`value`in m&&c(d,`value`,null,m.value,a),(f=m.onVnodeBeforeMount)&&Wi(f,r,e)}_&&kn(e,null,r,`beforeMount`);let v=hi(i,g);v&&g.beforeEnter(d),o(d,t,n),((f=m&&m.onVnodeMounted)||v||_)&&B(()=>{try{f&&Wi(f,r,e),v&&g.enter(d),_&&kn(e,null,r,`mounted`)}finally{}},i)},ie=(e,t,n,r,i)=>{if(n&&g(e,n),r)for(let t=0;t<r.length;t++)g(e,r[t]);if(i){let n=i.subTree;if(t===n||xi(n.type)&&(n.ssContent===t||n.ssFallback===t)){let t=i.vnode;ie(e,t,t.scopeId,t.slotScopeIds,i.parent)}}},C=(e,t,n,r,i,a,o,s,c=0)=>{for(let l=c;l<e.length;l++){let c=e[l]=s?Vi(e[l]):Bi(e[l]);v(null,c,t,n,r,i,a,o,s)}},ae=(e,n,r,i,a,o,s)=>{let l=n.el=e.el,{patchFlag:u,dynamicChildren:d,dirs:f}=n;u|=e.patchFlag&16;let m=e.props||t,h=n.props||t,g;if(r&&mi(r,!1),(g=h.onVnodeBeforeUpdate)&&Wi(g,r,n,e),f&&kn(n,e,r,`beforeUpdate`),r&&mi(r,!0),(m.innerHTML&&h.innerHTML==null||m.textContent&&h.textContent==null)&&p(l,``),d?w(e.dynamicChildren,d,l,r,i,pi(n,a),o):s||pe(e,n,l,null,r,i,pi(n,a),o,!1),u>0){if(u&16)oe(l,m,h,r,a);else if(u&2&&m.class!==h.class&&c(l,`class`,null,h.class,a),u&4&&c(l,`style`,m.style,h.style,a),u&8){let e=n.dynamicProps;for(let t=0;t<e.length;t++){let n=e[t],i=m[n],o=h[n];(o!==i||n===`value`)&&c(l,n,i,o,a,r)}}u&1&&e.children!==n.children&&p(l,n.children)}else!s&&d==null&&oe(l,m,h,r,a);((g=h.onVnodeUpdated)||f)&&B(()=>{g&&Wi(g,r,n,e),f&&kn(n,e,r,`updated`)},i)},w=(e,t,n,r,i,a,o)=>{for(let s=0;s<t.length;s++){let c=e[s],l=t[s],u=c.el&&(c.type===V||!Ni(c,l)||c.shapeFlag&198)?m(c.el):n;v(c,l,u,null,r,i,a,o,!0)}},oe=(e,n,r,i,a)=>{if(n!==r){if(n!==t)for(let t in n)!ne(t)&&!(t in r)&&c(e,t,n[t],null,a,i);for(let t in r){if(ne(t))continue;let o=r[t],s=n[t];o!==s&&t!==`value`&&c(e,t,s,o,a,i)}`value`in r&&c(e,`value`,n.value,r.value,a)}},se=(e,t,n,r,i,a,s,c,l)=>{let d=t.el=e?e.el:u(``),f=t.anchor=e?e.anchor:u(``),{patchFlag:p,dynamicChildren:m,slotScopeIds:h}=t;h&&(c=c?c.concat(h):h),e==null?(o(d,n,r),o(f,n,r),C(t.children||[],n,f,i,a,s,c,l)):p>0&&p&64&&m&&e.dynamicChildren&&e.dynamicChildren.length===m.length?(w(e.dynamicChildren,m,n,i,a,s,c),(t.key!=null||i&&t===i.subTree)&&gi(e,t,!0)):pe(e,t,n,f,i,a,s,c,l)},ce=(e,t,n,r,i,a,o,s,c)=>{t.slotScopeIds=s,e==null?t.shapeFlag&512?i.ctx.activate(t,n,r,o,c):T(t,n,r,i,a,o,c):ue(e,t,c)},T=(e,t,n,r,i,a,o)=>{let s=e.component=qi(e,r,i);if(Jn(e)&&(s.ctx.renderer=O),ta(s,!1,o),s.asyncDep){if(i&&i.registerDep(s,de,o),!e.el){let r=s.subTree=K(wi);b(null,r,t,n),e.placeholder=r.el}}else de(s,e,t,n,i,a,o)},ue=(e,t,n)=>{let r=t.component=e.component;if(Ur(e,t,n)){if(r.asyncDep&&!r.asyncResolved){E(r,t,n);return}r.next=t,r.update()}else t.el=e.el,r.vnode=t},de=(e,t,n,r,i,a,o)=>{let s=()=>{if(e.isMounted){let{next:t,bu:n,u:r,parent:s,vnode:c}=e;{let n=vi(e);if(n){t&&(t.el=c.el,E(e,t,o)),n.asyncDep.then(()=>{B(()=>{e.isUnmounted||l()},i)});return}}let u=t,d;mi(e,!1),t?(t.el=c.el,E(e,t,o)):t=c,n&&le(n),(d=t.props&&t.props.onVnodeBeforeUpdate)&&Wi(d,s,t,c),mi(e,!0);let f=Br(e),p=e.subTree;e.subTree=f,v(p,f,m(p.el),xe(p),e,i,a),t.el=f.el,u===null&&Kr(e,f.el),r&&B(r,i),(d=t.props&&t.props.onVnodeUpdated)&&B(()=>Wi(d,s,t,c),i)}else{let o,{el:s,props:c}=t,{bm:l,m:u,parent:d,root:f,type:p}=e,m=qn(t);if(mi(e,!1),l&&le(l),!m&&(o=c&&c.onVnodeBeforeMount)&&Wi(o,d,t),mi(e,!0),s&&Te){let t=()=>{e.subTree=Br(e),Te(s,e.subTree,e,i,null)};m&&p.__asyncHydrate?p.__asyncHydrate(s,e,t):t()}else{f.ce&&f.ce._hasShadowRoot()&&f.ce._injectChildStyle(p,e.parent?e.parent.type:void 0);let o=e.subTree=Br(e);v(null,o,n,r,e,i,a),t.el=o.el}if(u&&B(u,i),!m&&(o=c&&c.onVnodeMounted)){let e=t;B(()=>Wi(o,d,e),i)}(t.shapeFlag&256||d&&qn(d.vnode)&&d.vnode.shapeFlag&256)&&e.a&&B(e.a,i),e.isMounted=!0,t=n=r=null}};e.scope.on();let c=e.effect=new ke(s);e.scope.off();let l=e.update=c.run.bind(c),u=e.job=c.runIfDirty.bind(c);u.i=e,u.id=e.uid,c.scheduler=()=>_n(u),mi(e,!0),l()},E=(e,t,n)=>{t.component=e;let r=e.vnode.props;e.vnode=t,e.next=null,Zr(e,t.props,r,n),ui(e,t.children,n),We(),bn(e),Ge()},pe=(e,t,n,r,i,a,o,s,c=!1)=>{let l=e&&e.children,u=e?e.shapeFlag:0,d=t.children,{patchFlag:f,shapeFlag:m}=t;if(f>0){if(f&128){he(l,d,n,r,i,a,o,s,c);return}if(f&256){me(l,d,n,r,i,a,o,s,c);return}}m&8?(u&16&&be(l,i,a),d!==l&&p(n,d)):u&16?m&16?he(l,d,n,r,i,a,o,s,c):be(l,i,a,!0):(u&8&&p(n,``),m&16&&C(d,n,r,i,a,o,s,c))},me=(e,t,r,i,a,o,s,c,l)=>{e||=n,t||=n;let u=e.length,d=t.length,f=Math.min(u,d),p;for(p=0;p<f;p++){let n=t[p]=l?Vi(t[p]):Bi(t[p]);v(e[p],n,r,null,a,o,s,c,l)}u>d?be(e,a,o,!0,!1,f):C(t,r,i,a,o,s,c,l,f)},he=(e,t,r,i,a,o,s,c,l)=>{let u=0,d=t.length,f=e.length-1,p=d-1;for(;u<=f&&u<=p;){let n=e[u],i=t[u]=l?Vi(t[u]):Bi(t[u]);if(Ni(n,i))v(n,i,r,null,a,o,s,c,l);else break;u++}for(;u<=f&&u<=p;){let n=e[f],i=t[p]=l?Vi(t[p]):Bi(t[p]);if(Ni(n,i))v(n,i,r,null,a,o,s,c,l);else break;f--,p--}if(u>f){if(u<=p){let e=p+1,n=e<d?t[e].el:i;for(;u<=p;)v(null,t[u]=l?Vi(t[u]):Bi(t[u]),r,n,a,o,s,c,l),u++}}else if(u>p)for(;u<=f;)D(e[u],a,o,!0),u++;else{let m=u,h=u,g=new Map;for(u=h;u<=p;u++){let e=t[u]=l?Vi(t[u]):Bi(t[u]);e.key!=null&&g.set(e.key,u)}let _,y=0,b=p-h+1,x=!1,ee=0,S=Array(b);for(u=0;u<b;u++)S[u]=0;for(u=m;u<=f;u++){let n=e[u];if(y>=b){D(n,a,o,!0);continue}let i;if(n.key!=null)i=g.get(n.key);else for(_=h;_<=p;_++)if(S[_-h]===0&&Ni(n,t[_])){i=_;break}i===void 0?D(n,a,o,!0):(S[i-h]=u+1,i>=ee?ee=i:x=!0,v(n,t[i],r,null,a,o,s,c,l),y++)}let te=x?_i(S):n;for(_=te.length-1,u=b-1;u>=0;u--){let e=h+u,n=t[e],f=t[e+1],p=e+1<d?f.el||bi(f):i;S[u]===0?v(null,n,r,p,a,o,s,c,l):x&&(_<0||u!==te[_]?ge(n,r,p,2):_--)}}},ge=(e,t,n,r,i=null)=>{let{el:a,type:c,transition:l,children:u,shapeFlag:d}=e;if(d&6){ge(e.component.subTree,t,n,r);return}if(d&128){e.suspense.move(t,n,r);return}if(d&64){c.move(e,t,n,O);return}if(c===V){o(a,t,n);for(let e=0;e<u.length;e++)ge(u[e],t,n,r);o(e.anchor,t,n);return}if(c===Ti){ee(e,t,n);return}if(r!==2&&d&1&&l){if(r===0)l.persisted&&!a[Bn]?o(a,t,n):(l.beforeEnter(a),o(a,t,n),B(()=>l.enter(a),i));else{let{leave:r,delayLeave:i,afterLeave:c}=l,u=()=>{e.ctx.isUnmounted?s(a):o(a,t,n)},d=()=>{let e=a._isLeaving||!!a[Bn];a._isLeaving&&a[Bn](!0),l.persisted&&!e?u():r(a,()=>{u(),c&&c()})};i?i(a,u,d):d()}}else o(a,t,n)},D=(e,t,n,r=!1,i=!1)=>{let{type:a,props:o,ref:s,children:c,dynamicChildren:l,shapeFlag:u,patchFlag:d,dirs:f,cacheIndex:p,memo:m}=e;if(d===-2&&(i=!1),s!=null&&(We(),Gn(s,null,n,e,!0),Ge()),p!=null&&(t.renderCache[p]=void 0),u&256){t.ctx.deactivate(e);return}let h=u&1&&f,g=!qn(e),_;if(g&&(_=o&&o.onVnodeBeforeUnmount)&&Wi(_,t,e),u&6)ye(e.component,n,r);else{if(u&128){e.suspense.unmount(n,r);return}h&&kn(e,null,t,`beforeUnmount`),u&64?e.type.remove(e,t,n,O,r):l&&!l.hasOnce&&(a!==V||d>0&&d&64)?be(l,t,n,!1,!0):(a===V&&d&384||!i&&u&16)&&be(c,t,n),r&&_e(e)}let v=m!=null&&p==null;(g&&(_=o&&o.onVnodeUnmounted)||h||v)&&B(()=>{_&&Wi(_,t,e),h&&kn(e,null,t,`unmounted`),v&&(e.el=null)},n)},_e=e=>{let{type:t,el:n,anchor:r,transition:i}=e;if(t===V){ve(n,r);return}if(t===Ti){S(e);return}let a=()=>{s(n),i&&!i.persisted&&i.afterLeave&&i.afterLeave()};if(e.shapeFlag&1&&i&&!i.persisted){let{leave:t,delayLeave:r}=i,o=()=>t(n,a);r?r(e.el,a,o):o()}else a()},ve=(e,t)=>{let n;for(;e!==t;)n=h(e),s(e),e=n;s(t)},ye=(e,t,n)=>{let{bum:r,scope:i,job:a,subTree:o,um:s,m:c,a:l}=e;yi(c),yi(l),r&&le(r),i.stop(),a&&(a.flags|=8,D(o,e,t,n)),s&&B(s,t),B(()=>{e.isUnmounted=!0},t)},be=(e,t,n,r=!1,i=!1,a=0)=>{for(let o=a;o<e.length;o++)D(e[o],t,n,r,i)},xe=e=>{if(e.shapeFlag&6)return xe(e.component.subTree);if(e.shapeFlag&128)return e.suspense.next();let t=h(e.anchor||e.el),n=t&&t[Rn];return n?h(n):t},Se=!1,Ce=(e,t,n)=>{let r;e==null?t._vnode&&(D(t._vnode,null,null,!0),r=t._vnode.component):v(t._vnode||null,e,t,null,null,null,n),t._vnode=e,Se||=(Se=!0,bn(r),xn(),!1)},O={p:v,um:D,m:ge,r:_e,mt:T,mc:C,pc:pe,pbc:w,n:xe,o:e},we,Te;return i&&([we,Te]=i(O)),{render:Ce,hydrate:we,createApp:Nr(Ce,we)}}function pi({type:e,props:t},n){return n===`svg`&&e===`foreignObject`||n===`mathml`&&e===`annotation-xml`&&t&&t.encoding&&t.encoding.includes(`html`)?void 0:n}function mi({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function hi(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function gi(e,t,n=!1){let r=e.children,i=t.children;if(d(r)&&d(i))for(let e=0;e<r.length;e++){let t=r[e],a=i[e];a.shapeFlag&1&&!a.dynamicChildren&&((a.patchFlag<=0||a.patchFlag===32)&&(a=i[e]=Vi(i[e]),a.el=t.el),!n&&a.patchFlag!==-2&&gi(t,a)),a.type===Ci&&(a.patchFlag===-1&&(a=i[e]=Vi(a)),a.el=t.el),a.type===wi&&!a.el&&(a.el=t.el)}}function _i(e){let t=e.slice(),n=[0],r,i,a,o,s,c=e.length;for(r=0;r<c;r++){let c=e[r];if(c!==0){if(i=n[n.length-1],e[i]<c){t[r]=i,n.push(r);continue}for(a=0,o=n.length-1;a<o;)s=a+o>>1,e[n[s]]<c?a=s+1:o=s;c<e[n[a]]&&(a>0&&(t[r]=n[a-1]),n[a]=r)}}for(a=n.length,o=n[a-1];a-->0;)n[a]=o,o=t[o];return n}function vi(e){let t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:vi(t)}function yi(e){if(e)for(let t=0;t<e.length;t++)e[t].flags|=8}function bi(e){if(e.placeholder)return e.placeholder;let t=e.component;return t?bi(t.subTree):null}var xi=e=>e.__isSuspense;function Si(e,t){t&&t.pendingBranch?d(e)?t.effects.push(...e):t.effects.push(e):yn(e)}var V=Symbol.for(`v-fgt`),Ci=Symbol.for(`v-txt`),wi=Symbol.for(`v-cmt`),Ti=Symbol.for(`v-stc`),Ei=[],H=null;function U(e=!1){Ei.push(H=e?null:[])}function Di(){Ei.pop(),H=Ei[Ei.length-1]||null}var Oi=1;function ki(e,t=!1){Oi+=e,e<0&&H&&t&&(H.hasOnce=!0)}function Ai(e){return e.dynamicChildren=Oi>0?H||n:null,Di(),Oi>0&&H&&H.push(e),e}function W(e,t,n,r,i,a){return Ai(G(e,t,n,r,i,a,!0))}function ji(e,t,n,r,i){return Ai(K(e,t,n,r,i,!0))}function Mi(e){return e?e.__v_isVNode===!0:!1}function Ni(e,t){return e.type===t.type&&e.key===t.key}var Pi=({key:e})=>e??null,Fi=({ref:e,ref_key:t,ref_for:n})=>(typeof e==`number`&&(e=``+e),e==null?null:g(e)||N(e)||h(e)?{i:wn,r:e,k:t,f:!!n}:e);function G(e,t=null,n=null,r=0,i=null,a=e===V?0:1,o=!1,s=!1){let c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Pi(t),ref:t&&Fi(t),scopeId:Tn,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:r,dynamicProps:i,dynamicChildren:null,appContext:null,ctx:wn};return s?(Hi(c,n),a&128&&e.normalize(c)):n&&(c.shapeFlag|=g(n)?8:16),Oi>0&&!o&&H&&(c.patchFlag>0||a&6)&&c.patchFlag!==32&&H.push(c),c}var K=Ii;function Ii(e,t=null,n=null,r=0,i=null,a=!1){if((!e||e===dr)&&(e=wi),Mi(e)){let r=Ri(e,t,!0);return n&&Hi(r,n),Oi>0&&!a&&H&&(r.shapeFlag&6?H[H.indexOf(e)]=r:H.push(r)),r.patchFlag=-2,r}if(ua(e)&&(e=e.__vccOpts),t){t=Li(t);let{class:e,style:n}=t;e&&!g(e)&&(t.class=D(e)),v(n)&&(Ht(n)&&!d(n)&&(n=s({},n)),t.style=E(n))}let o=g(e)?1:xi(e)?128:zn(e)?64:v(e)?4:h(e)?2:0;return G(e,t,n,r,i,o,a,!0)}function Li(e){return e?Ht(e)||Yr(e)?s({},e):e:null}function Ri(e,t,n=!1,r=!1){let{props:i,ref:a,patchFlag:o,children:s,transition:c}=e,l=t?Ui(i||{},t):i,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&Pi(l),ref:t&&t.ref?n&&a?d(a)?a.concat(Fi(t)):[a,Fi(t)]:Fi(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==V?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Ri(e.ssContent),ssFallback:e.ssFallback&&Ri(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return c&&r&&Vn(u,c.clone(u)),u}function zi(e=` `,t=0){return K(Ci,null,e,t)}function q(e=``,t=!1){return t?(U(),ji(wi,null,e)):K(wi,null,e)}function Bi(e){return e==null||typeof e==`boolean`?K(wi):d(e)?K(V,null,e.slice()):Mi(e)?Vi(e):K(Ci,null,String(e))}function Vi(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Ri(e)}function Hi(e,t){let n=0,{shapeFlag:r}=e;if(t==null)t=null;else if(d(t))n=16;else if(typeof t==`object`){if(r&65){let n=t.default;n&&(n._c&&(n._d=!1),Hi(e,n()),n._c&&(n._d=!0));return}{n=32;let r=t._;!r&&!Yr(t)?t._ctx=wn:r===3&&wn&&(wn.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}}else h(t)?(t={default:t,_ctx:wn},n=32):(t=String(t),r&64?(n=16,t=[zi(t)]):n=8);e.children=t,e.shapeFlag|=n}function Ui(...e){let t={};for(let n=0;n<e.length;n++){let r=e[n];for(let e in r)if(e===`class`)t.class!==r.class&&(t.class=D([t.class,r.class]));else if(e===`style`)t.style=E([t.style,r.style]);else if(a(e)){let n=t[e],i=r[e];i&&n!==i&&!(d(n)&&n.includes(i))?t[e]=n?[].concat(n,i):i:i==null&&n==null&&!o(e)&&(t[e]=i)}else e!==``&&(t[e]=r[e])}return t}function Wi(e,t,n,r=null){on(e,t,7,[n,r])}var Gi=jr(),Ki=0;function qi(e,n,r){let i=e.type,a=(n?n.appContext:e.appContext)||Gi,o={uid:Ki++,vnode:e,type:i,parent:n,appContext:a,root:null,next:null,subTree:null,effect:null,update:null,job:null,scope:new Ee(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:n?n.provides:Object.create(a.provides),ids:n?n.ids:[``,0,0],accessCache:null,renderCache:[],components:null,directives:null,propsOptions:ti(i,a),emitsOptions:Rr(i,a),emit:null,emitted:null,propsDefaults:t,inheritAttrs:i.inheritAttrs,ctx:t,data:t,props:t,attrs:t,slots:t,refs:t,setupState:t,setupContext:null,suspense:r,suspenseId:r?r.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return o.ctx={_:o},o.root=n?n.root:o,o.emit=Ir.bind(null,o),e.ce&&e.ce(o),o}var J=null,Ji=()=>J||wn,Yi,Xi;{let e=fe(),t=(t,n)=>{let r;return(r=e[t])||(r=e[t]=[]),r.push(n),e=>{r.length>1?r.forEach(t=>t(e)):r[0](e)}};Yi=t(`__VUE_INSTANCE_SETTERS__`,e=>J=e),Xi=t(`__VUE_SSR_SETTERS__`,e=>ea=e)}var Zi=e=>{let t=J;return Yi(e),e.scope.on(),()=>{e.scope.off(),Yi(t)}},Qi=()=>{J&&J.scope.off(),Yi(null)};function $i(e){return e.vnode.shapeFlag&4}var ea=!1;function ta(e,t=!1,n=!1){t&&Xi(t);let{props:r,children:i}=e.vnode,a=$i(e);Xr(e,r,a,t),li(e,i,n||t);let o=a?na(e,t):void 0;return t&&Xi(!1),o}function na(e,t){let n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,hr);let{setup:r}=n;if(r){We();let n=e.setupContext=r.length>1?ca(e):null,i=Zi(e),a=an(r,e,0,[e.props,n]),o=y(a);if(Ge(),i(),(o||e.sp)&&!qn(e)&&Hn(e),o){if(a.then(Qi,Qi),t)return a.then(n=>{ra(e,n,t)}).catch(t=>{sn(t,e,0)});e.asyncDep=a}else ra(e,a,t)}else oa(e,t)}function ra(e,t,n){h(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:v(t)&&(e.setupState=Yt(t)),oa(e,n)}var ia,aa;function oa(e,t,n){let i=e.type;if(!e.render){if(!t&&ia&&!i.render){let t=i.template||Sr(e).template;if(t){let{isCustomElement:n,compilerOptions:r}=e.appContext.config,{delimiters:a,compilerOptions:o}=i;i.render=ia(t,s(s({isCustomElement:n,delimiters:a},r),o))}}e.render=i.render||r,aa&&aa(e)}{let t=Zi(e);We();try{vr(e)}finally{Ge(),t()}}}var sa={get(e,t){return j(e,`get`,``),e[t]}};function ca(e){return{attrs:new Proxy(e.attrs,sa),slots:e.slots,emit:e.emit,expose:t=>{e.exposed=t||{}}}}function la(e){return e.exposed?e.exposeProxy||=new Proxy(Yt(Ut(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in pr)return pr[n](e)},has(e,t){return t in e||t in pr}}):e.proxy}function ua(e){return h(e)&&`__vccOpts`in e}var Y=(e,t)=>Zt(e,t,ea),da=`3.5.35`,fa=void 0,pa=typeof window<`u`&&window.trustedTypes;if(pa)try{fa=pa.createPolicy(`vue`,{createHTML:e=>e})}catch{}var ma=fa?e=>fa.createHTML(e):e=>e,ha=`http://www.w3.org/2000/svg`,ga=`http://www.w3.org/1998/Math/MathML`,_a=typeof document<`u`?document:null,va=_a&&_a.createElement(`template`),ya={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?_a.createElementNS(ha,e):t===`mathml`?_a.createElementNS(ga,e):n?_a.createElement(e,{is:n}):_a.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>_a.createTextNode(e),createComment:e=>_a.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>_a.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),!(i===a||!(i=i.nextSibling)););else{va.innerHTML=ma(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=va.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},ba=Symbol(`_vtc`);function xa(e,t,n){let r=e[ba];r&&(t=(t?[t,...r]:[...r]).join(` `)),t==null?e.removeAttribute(`class`):n?e.setAttribute(`class`,t):e.className=t}var Sa=Symbol(`_vod`),Ca=Symbol(`_vsh`),wa=Symbol(``),Ta=/(?:^|;)\s*display\s*:/;function Ea(e,t,n){let r=e.style,i=g(n),a=!1;if(n&&!i){if(t){if(g(t))for(let e of t.split(`;`)){let t=e.slice(0,e.indexOf(`:`)).trim();n[t]??Oa(r,t,``)}else for(let e in t)n[e]??Oa(r,e,``)}for(let i in n){i===`display`&&(a=!0);let o=n[i];o==null?Oa(r,i,``):Ma(e,i,!g(t)&&t?t[i]:void 0,o)||Oa(r,i,o)}}else if(i){if(t!==n){let e=r[wa];e&&(n+=`;`+e),r.cssText=n,a=Ta.test(n)}}else t&&e.removeAttribute(`style`);Sa in e&&(e[Sa]=a?r.display:``,e[Ca]&&(r.display=`none`))}var Da=/\s*!important$/;function Oa(e,t,n){if(d(n))n.forEach(n=>Oa(e,t,n));else if(n??=``,t.startsWith(`--`))e.setProperty(t,n);else{let r=ja(e,t);Da.test(n)?e.setProperty(w(r),n.replace(Da,``),`important`):e[r]=n}}var ka=[`Webkit`,`Moz`,`ms`],Aa={};function ja(e,t){let n=Aa[t];if(n)return n;let r=C(t);if(r!==`filter`&&r in e)return Aa[t]=r;r=oe(r);for(let n=0;n<ka.length;n++){let i=ka[n]+r;if(i in e)return Aa[t]=i}return t}function Ma(e,t,n,r){return e.tagName===`TEXTAREA`&&(t===`width`||t===`height`)&&g(r)&&n===r}var Na=`http://www.w3.org/1999/xlink`;function Pa(e,t,n,r,i,a=ve(t)){r&&t.startsWith(`xlink:`)?n==null?e.removeAttributeNS(Na,t.slice(6,t.length)):e.setAttributeNS(Na,t,n):n==null||a&&!ye(n)?e.removeAttribute(t):e.setAttribute(t,a?``:_(n)?String(n):n)}function Fa(e,t,n,r,i){if(t===`innerHTML`||t===`textContent`){n!=null&&(e[t]=t===`innerHTML`?ma(n):n);return}let a=e.tagName;if(t===`value`&&a!==`PROGRESS`&&!a.includes(`-`)){let r=a===`OPTION`?e.getAttribute(`value`)||``:e.value,i=n==null?e.type===`checkbox`?`on`:``:String(n);(r!==i||!(`_value`in e))&&(e.value=i),n??e.removeAttribute(t),e._value=n;return}let o=!1;if(n===``||n==null){let r=typeof e[t];r===`boolean`?n=ye(n):n==null&&r===`string`?(n=``,o=!0):r===`number`&&(n=0,o=!0)}try{e[t]=n}catch{}o&&e.removeAttribute(i||t)}function Ia(e,t,n,r){e.addEventListener(t,n,r)}function La(e,t,n,r){e.removeEventListener(t,n,r)}var Ra=Symbol(`_vei`);function za(e,t,n,r,i=null){let a=e[Ra]||(e[Ra]={}),o=a[t];if(r&&o)o.value=r;else{let[n,s]=Va(t);r?Ia(e,n,a[t]=Ga(r,i),s):o&&(La(e,n,o,s),a[t]=void 0)}}var Ba=/(?:Once|Passive|Capture)$/;function Va(e){let t;if(Ba.test(e)){t={};let n;for(;n=e.match(Ba);)e=e.slice(0,e.length-n[0].length),t[n[0].toLowerCase()]=!0}return[e[2]===`:`?e.slice(3):w(e.slice(2)),t]}var Ha=0,Ua=Promise.resolve(),Wa=()=>Ha||=(Ua.then(()=>Ha=0),Date.now());function Ga(e,t){let n=e=>{if(!e._vts)e._vts=Date.now();else if(e._vts<=n.attached)return;let r=n.value;if(d(r)){let n=e.stopImmediatePropagation;e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0};let i=r.slice(),a=[e];for(let n=0;n<i.length&&!e._stopped;n++){let e=i[n];e&&on(e,t,5,a)}}else on(r,t,5,[e])};return n.value=e,n.attached=Wa(),n}var Ka=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,qa=(e,t,n,r,i,s)=>{let c=i===`svg`;t===`class`?xa(e,r,c):t===`style`?Ea(e,n,r):a(t)?o(t)||za(e,t,n,r,s):(t[0]===`.`?(t=t.slice(1),!0):t[0]===`^`?(t=t.slice(1),!1):Ja(e,t,r,c))?(Fa(e,t,r),!e.tagName.includes(`-`)&&(t===`value`||t===`checked`||t===`selected`)&&Pa(e,t,r,c,s,t!==`value`)):e._isVueCE&&(Ya(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!g(r)))?Fa(e,C(t),r,s,t):(t===`true-value`?e._trueValue=r:t===`false-value`&&(e._falseValue=r),Pa(e,t,r,c))};function Ja(e,t,n,r){if(r)return!!(t===`innerHTML`||t===`textContent`||t in e&&Ka(t)&&h(n));if(t===`spellcheck`||t===`draggable`||t===`translate`||t===`autocorrect`||t===`sandbox`&&e.tagName===`IFRAME`||t===`form`||t===`list`&&e.tagName===`INPUT`||t===`type`&&e.tagName===`TEXTAREA`)return!1;if(t===`width`||t===`height`){let t=e.tagName;if(t===`IMG`||t===`VIDEO`||t===`CANVAS`||t===`SOURCE`)return!1}return Ka(t)&&g(n)?!1:t in e}function Ya(e,t){let n=e._def.props;if(!n)return!1;let r=C(t);return Array.isArray(n)?n.some(e=>C(e)===r):Object.keys(n).some(e=>C(e)===r)}var Xa=e=>{let t=e.props[`onUpdate:modelValue`]||!1;return d(t)?e=>le(t,e):t};function Za(e){e.target.composing=!0}function Qa(e){let t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event(`input`)))}var $a=Symbol(`_assign`);function eo(e,t,n){return t&&(e=e.trim()),n&&(e=ue(e)),e}var to={created(e,{modifiers:{lazy:t,trim:n,number:r}},i){e[$a]=Xa(i);let a=r||i.props&&i.props.type===`number`;Ia(e,t?`change`:`input`,t=>{t.target.composing||e[$a](eo(e.value,n,a))}),(n||a)&&Ia(e,`change`,()=>{e.value=eo(e.value,n,a)}),t||(Ia(e,`compositionstart`,Za),Ia(e,`compositionend`,Qa),Ia(e,`change`,Qa))},mounted(e,{value:t}){e.value=t??``},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[$a]=Xa(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?ue(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},no={deep:!0,created(e,{value:t,modifiers:{number:n}},r){let i=p(t);Ia(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?ue(io(e)):io(e));e[$a](e.multiple?i?new Set(t):t:t[0]),e._assigning=!0,hn(()=>{e._assigning=!1})}),e[$a]=Xa(r)},mounted(e,{value:t}){ro(e,t)},beforeUpdate(e,t,n){e[$a]=Xa(n)},updated(e,{value:t}){e._assigning||ro(e,t)}};function ro(e,t){let n=e.multiple,r=d(t);if(!(n&&!r&&!p(t))){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=io(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Se(t,o)>-1}else a.selected=t.has(o)}else if(xe(io(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function io(e){return`_value`in e?e._value:e.value}var ao=[`ctrl`,`shift`,`alt`,`meta`],oo={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>ao.some(n=>e[`${n}Key`]&&!t.includes(n))},so=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=oo[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},co={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},lo=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=w(n.key);if(t.some(e=>e===r||co[e]===r))return e(n)}))},uo=s({patchProp:qa},ya),fo;function po(){return fo||=di(uo)}var mo=((...e)=>{let t=po().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=go(e);if(!r)return;let i=t._component;!h(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,ho(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t});function ho(e){if(e instanceof SVGElement)return`svg`;if(typeof MathMLElement==`function`&&e instanceof MathMLElement)return`mathml`}function go(e){return g(e)?document.querySelector(e):e}function X(e){return e.schema?`${e.schema}.${e.name}`:e.name}var _o={table:20,column:20,group:10,enum:10};function vo(e,t){let n=t.trim().toLowerCase();if(n.length===0)return[];let r=[],i=[];for(let t of e.tables){let e=X(t);t.name.toLowerCase().includes(n)&&r.push({kind:`table`,label:t.name,context:e,tableKey:e});for(let r of t.columns)r.name.toLowerCase().includes(n)&&i.push({kind:`column`,label:r.name,context:e,tableKey:e})}let a=e.groups.filter(e=>e.name.toLowerCase().includes(n)).map(t=>({kind:`group`,label:t.name,context:`${e.tables.filter(e=>e.groupId===t.id).length} tables`,tableKey:null})),o=e.enums.filter(e=>e.name.toLowerCase().includes(n)).map(e=>({kind:`enum`,label:e.name,context:`${e.values.length} values`,tableKey:null}));return[...r.slice(0,_o.table),...i.slice(0,_o.column),...a.slice(0,_o.group),...o.slice(0,_o.enum)]}var yo={class:`w-full max-w-lg overflow-hidden rounded-md border border-border bg-background shadow-lg`},bo=[`placeholder`],xo={class:`max-h-80 overflow-y-auto`},So={key:0,class:`px-3 py-4 text-center text-xs text-muted-foreground`},Co=[`disabled`,`onClick`],wo={class:`w-14 shrink-0 text-[10px] uppercase text-muted-foreground`},To={class:`font-mono text-foreground`},Eo={class:`truncate text-[11px] text-muted-foreground`},Do=L({__name:`DocsSearch`,props:{snapshot:{},translate:{type:Function}},emits:[`select`,`selectEnum`],setup(e,{emit:t}){let n=e,r=t,i=P(!1),a=P(``),o=P(null),s=Y(()=>vo(n.snapshot,a.value));async function c(){i.value=!0,a.value=``,await hn(),o.value?.focus()}function l(e){if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`){e.preventDefault(),i.value?i.value=!1:c();return}e.key===`Escape`&&i.value&&(i.value=!1)}function u(e){return e.kind===`enum`||e.tableKey!==null}function d(e){if(e.kind===`enum`){r(`selectEnum`,e.label),i.value=!1;return}e.tableKey!==null&&(r(`select`,e.tableKey),i.value=!1)}return nr(()=>window.addEventListener(`keydown`,l)),ar(()=>window.removeEventListener(`keydown`,l)),(t,n)=>(U(),W(`div`,null,[G(`button`,{type:`button`,class:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[0]||=e=>c()},[G(`span`,null,O(e.translate(`docs.searchLabel`)),1),n[3]||=G(`span`,{class:`rounded bg-muted/50 px-1 py-0.5 text-[10px]`},`⌘K`,-1)]),i.value?(U(),W(`div`,{key:0,class:`fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-24`,onClick:n[2]||=so(e=>i.value=!1,[`self`])},[G(`div`,yo,[On(G(`input`,{ref_key:`input`,ref:o,"onUpdate:modelValue":n[1]||=e=>a.value=e,type:`text`,placeholder:e.translate(`docs.search`),class:`w-full border-b border-border bg-transparent px-3 py-2 text-sm text-foreground outline-none`},null,8,bo),[[to,a.value]]),G(`ul`,xo,[a.value.trim()!==``&&s.value.length===0?(U(),W(`li`,So,`Nothing matches “`+O(a.value)+`”.`,1)):q(``,!0),(U(!0),W(V,null,R(s.value,(e,t)=>(U(),W(`li`,{key:`${e.kind}-${e.context}-${e.label}-${t}`},[G(`button`,{type:`button`,class:D([`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-xs transition-colors`,u(e)?`hover:bg-muted/40`:`cursor-default text-muted-foreground`]),disabled:!u(e),onClick:t=>d(e)},[G(`span`,wo,O(e.kind),1),G(`span`,To,O(e.label),1),G(`span`,Eo,O(e.context),1)],10,Co)]))),128))])])])):q(``,!0)]))}});function Oo(e){if(e===null)return{};let t=(Math.trunc(e)%360+360)%360;return{"--h":String(t)}}var ko={class:`flex w-64 shrink-0 flex-col gap-3 overflow-y-auto border-r border-border bg-background p-3`},Ao={class:`flex flex-col gap-1`},jo={class:`px-2 text-[10px] uppercase tracking-wide text-muted-foreground`},Mo={class:`flex rounded border border-border p-0.5`},No={key:0,class:`h-2 w-2 shrink-0 rounded-full`,style:{"background-color":`var(--group-c)`}},Po={class:`truncate text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`},Fo=[`onClick`],Io=L({__name:`DocsSidebar`,props:{sections:{},mode:{},activeKey:{},translate:{type:Function}},emits:[`update:mode`,`select`,`home`],setup(e,{emit:t}){let n=t;return(t,r)=>(U(),W(`nav`,ko,[G(`button`,{type:`button`,class:`rounded px-2 py-1 text-left text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/40`,onClick:r[0]||=e=>n(`home`)},O(e.translate(`docs.overview`)),1),G(`div`,Ao,[G(`span`,jo,O(e.translate(`docs.groupBy`)),1),G(`div`,Mo,[G(`button`,{type:`button`,class:D([`flex-1 rounded px-2 py-1 text-xs transition-colors`,e.mode===`schema`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:r[1]||=e=>n(`update:mode`,`schema`)},O(e.translate(`docs.groupBySchema`)),3),G(`button`,{type:`button`,class:D([`flex-1 rounded px-2 py-1 text-xs transition-colors`,e.mode===`group`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:r[2]||=e=>n(`update:mode`,`group`)},O(e.translate(`docs.groupByTableGroup`)),3)])]),(U(!0),W(V,null,R(e.sections,t=>(U(),W(`div`,{key:t.key,class:`flex flex-col gap-0.5`},[G(`div`,{class:D([`flex items-center gap-1.5 px-2 py-1`,{"docs-group":t.hue!==null}]),style:E(F(Oo)(t.hue))},[t.hue===null?q(``,!0):(U(),W(`span`,No)),G(`span`,Po,O(t.label||e.translate(t.fallbackKey)),1)],6),(U(!0),W(V,null,R(t.tables,t=>(U(),W(`button`,{key:F(X)(t),type:`button`,class:D([`truncate rounded px-2 py-1 text-left font-mono text-xs transition-colors`,e.activeKey===F(X)(t)?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:e=>n(`select`,F(X)(t))},O(t.name),11,Fo))),128))]))),128))]))}});function Lo(e,t){return e.name.localeCompare(t.name)}function Ro(e){let t=new Map;for(let n of e.tables){let e=n.schema??``,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({key:e,label:e,fallbackKey:`docs.noSchema`,hue:null,note:null,tables:[...t].sort(Lo)}))}function zo(e){let t=new Map(e.groups.map(e=>[e.id,e])),n=[];for(let t of e.groups){let r=e.tables.filter(e=>e.groupId===t.id).sort(Lo);r.length!==0&&n.push({key:t.id,label:t.name,fallbackKey:`docs.noGroup`,hue:t.hue,note:t.note,tables:r})}let r=e.tables.filter(e=>e.groupId===null||!t.has(e.groupId)).sort(Lo);return r.length>0&&n.push({key:``,label:``,fallbackKey:`docs.noGroup`,hue:null,note:null,tables:r}),n}function Bo(e,t){let n=[];for(let r of e.tables)for(let e of r.columns)e.data_type===t&&n.push({tableKey:X(r),table:r.name,column:e.name});return n}function Vo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ho=Vo();function Uo(e){Ho=e}var Wo={exec:()=>null};function Go(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Z(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Q.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Ko=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Q={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Go(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Go(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Go(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Go(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Go(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Go(e=>RegExp(`^ {0,${e}}>`))},qo=/^(?:[ \t]*(?:\n|$))+/,Jo=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Yo=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Xo=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Zo=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Qo=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,$o=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,es=Z($o).replace(/bull/g,Qo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),ts=Z($o).replace(/bull/g,Qo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ns=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,rs=/^[^\n]+/,is=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,as=Z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,is).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),os=Z(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Qo).getRegex(),ss=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,cs=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ls=Z(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,cs).replace(`tag`,ss).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),us=Z(ns).replace(`hr`,Xo).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ss).getRegex(),ds={blockquote:Z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,us).getRegex(),code:Jo,def:as,fences:Yo,heading:Zo,hr:Xo,html:ls,lheading:es,list:os,newline:qo,paragraph:us,table:Wo,text:rs},fs=Z(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,Xo).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ss).getRegex(),ps={...ds,lheading:ts,table:fs,paragraph:Z(ns).replace(`hr`,Xo).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,fs).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ss).getRegex()},ms={...ds,html:Z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,cs).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Wo,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Z(ns).replace(`hr`,Xo).replace(`heading`,` *#{1,6} *[^
-]`).replace(`lheading`,es).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},hs=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,gs=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,_s=/^( {2,}|\\)\n(?!\s*$)/,vs=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ys=/[\p{P}\p{S}]/u,bs=/[\s\p{P}\p{S}]/u,xs=/[^\s\p{P}\p{S}]/u,Ss=Z(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,bs).getRegex(),Cs=/(?!~)[\p{P}\p{S}]/u,ws=/(?!~)[\s\p{P}\p{S}]/u,Ts=/(?:[^\s\p{P}\p{S}]|~)/u,Es=Z(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Ko?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Ds=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Os=Z(Ds,`u`).replace(/punct/g,ys).getRegex(),ks=Z(Ds,`u`).replace(/punct/g,Cs).getRegex(),As=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,js=Z(As,`gu`).replace(/notPunctSpace/g,xs).replace(/punctSpace/g,bs).replace(/punct/g,ys).getRegex(),Ms=Z(As,`gu`).replace(/notPunctSpace/g,Ts).replace(/punctSpace/g,ws).replace(/punct/g,Cs).getRegex(),Ns=Z(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,xs).replace(/punctSpace/g,bs).replace(/punct/g,ys).getRegex(),Ps=Z(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,ys).getRegex(),Fs=Z(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,xs).replace(/punctSpace/g,bs).replace(/punct/g,ys).getRegex(),Is=Z(/\\(punct)/,`gu`).replace(/punct/g,ys).getRegex(),Ls=Z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Rs=Z(cs).replace(`(?:-->|$)`,`-->`).getRegex(),zs=Z(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,Rs).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Bs=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Vs=Z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Bs).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Hs=Z(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Bs).replace(`ref`,is).getRegex(),Us=Z(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,is).getRegex(),Ws=Z(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Hs).replace(`nolink`,Us).getRegex(),Gs=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ks={_backpedal:Wo,anyPunctuation:Is,autolink:Ls,blockSkip:Es,br:_s,code:gs,del:Wo,delLDelim:Wo,delRDelim:Wo,emStrongLDelim:Os,emStrongRDelimAst:js,emStrongRDelimUnd:Ns,escape:hs,link:Vs,nolink:Us,punctuation:Ss,reflink:Hs,reflinkSearch:Ws,tag:zs,text:vs,url:Wo},qs={...Ks,link:Z(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Bs).getRegex(),reflink:Z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Bs).getRegex()},Js={...Ks,emStrongRDelimAst:Ms,emStrongLDelim:ks,delLDelim:Ps,delRDelim:Fs,url:Z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Gs).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Z(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Gs).getRegex()},Ys={...Js,br:Z(_s).replace(`{2,}`,`*`).getRegex(),text:Z(Js.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},Xs={normal:ds,gfm:ps,pedantic:ms},Zs={normal:Ks,gfm:Js,breaks:Ys,pedantic:qs},Qs={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},$s=e=>Qs[e];function ec(e,t){if(t){if(Q.escapeTest.test(e))return e.replace(Q.escapeReplace,$s)}else if(Q.escapeTestNoEncode.test(e))return e.replace(Q.escapeReplaceNoEncode,$s);return e}function tc(e){try{e=encodeURI(e).replace(Q.percentDecode,`%`)}catch{return null}return e}function nc(e,t){let n=e.replace(Q.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Q.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(Q.slashPipe,`|`);return n}function rc(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function ic(e){let t=e.split(`
+(function(){function e(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var t={},n=[],r=()=>{},i=()=>!1,a=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),o=e=>e.startsWith(`onUpdate:`),s=Object.assign,c=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},l=Object.prototype.hasOwnProperty,u=(e,t)=>l.call(e,t),d=Array.isArray,f=e=>x(e)===`[object Map]`,p=e=>x(e)===`[object Set]`,m=e=>x(e)===`[object Date]`,h=e=>typeof e==`function`,g=e=>typeof e==`string`,_=e=>typeof e==`symbol`,v=e=>typeof e==`object`&&!!e,y=e=>(v(e)||h(e))&&h(e.then)&&h(e.catch),b=Object.prototype.toString,x=e=>b.call(e),ee=e=>x(e).slice(8,-1),S=e=>x(e)===`[object Object]`,te=e=>g(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=e(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},ie=/-\w/g,C=re(e=>e.replace(ie,e=>e.slice(1).toUpperCase())),ae=/\B([A-Z])/g,w=re(e=>e.replace(ae,`-$1`).toLowerCase()),oe=re(e=>e.charAt(0).toUpperCase()+e.slice(1)),se=re(e=>e?`on${oe(e)}`:``),ce=(e,t)=>!Object.is(e,t),le=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},T=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},ue=e=>{let t=parseFloat(e);return isNaN(t)?e:t},de,fe=()=>de||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{};function E(e){if(d(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=g(r)?ge(r):E(r);if(i)for(let e in i)t[e]=i[e]}return t}if(g(e)||v(e))return e}var pe=/;(?![^(]*\))/g,me=/:([^]+)/,he=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function ge(e){let t={};return e.replace(he,e=>e.startsWith(`/*`)?``:e).split(pe).forEach(e=>{if(e){let n=e.split(me);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(g(e))t=e;else if(d(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(v(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}var _e=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`,ve=e(_e);_e+``;function ye(e){return!!e||e===``}function be(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=we(e[i],t[i],n);return r}function xe(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&we(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Se(e,t,n){let r=f(e),i=f(t);if(r||i||(r=p(e),i=p(t),r||i))return r&&i?xe(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!we(e[r],t[r],n))return!1}return String(e)===String(t)}function Ce(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function we(e,t,n){if(e===t)return!0;let r=m(e),i=m(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=_(e),i=_(t),r||i?e===t:(r=d(e),i=d(t),r||i?r&&i?Ce(e,t,n,be):!1:(r=v(e),i=v(t),r||i?!r||!i?!1:Ce(e,t,n,Se):String(e)===String(t))))}function Te(e,t){return e.findIndex(e=>we(e,t))}var Ee=e=>!!(e&&e.__v_isRef===!0),O=e=>g(e)?e:e==null?``:d(e)||v(e)&&(e.toString===b||!h(e.toString))?Ee(e)?O(e.value):JSON.stringify(e,De,2):String(e),De=(e,t)=>Ee(t)?De(e,t.value):f(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Oe(t,r)+` =>`]=n,e),{})}:p(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Oe(e))}:_(t)?Oe(t):v(t)&&!d(t)&&!S(t)?String(t):t,Oe=(e,t=``)=>_(e)?`Symbol(${e.description??t})`:e,k,ke=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&k&&(k.active?(this.parent=k,this.index=(k.scopes||(k.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let e,t;if(this.scopes){let n=this.scopes.slice();for(e=0,t=n.length;e<t;e++)n[e].pause()}for(e=0,t=this.effects.length;e<t;e++)this.effects[e].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let e,t;if(this.scopes){let n=this.scopes.slice();for(e=0,t=n.length;e<t;e++)n[e].resume()}let n=this.effects.slice();for(e=0,t=n.length;e<t;e++)n[e].resume()}}run(e){if(this._active){let t=k;try{return k=this,e()}finally{k=t}}}on(){++this._on===1&&(this.prevScope=k,k=this)}off(){if(this._on>0&&--this._on===0){if(k===this)k=this.prevScope;else{let e=k;for(;e;){if(e.prevScope===this){e.prevScope=this.prevScope;break}e=e.prevScope}}this.prevScope=void 0}}stop(e){if(this._active){this._active=!1;let t,n;for(t=0,n=this.effects.length;t<n;t++)this.effects[t].stop();for(this.effects.length=0,t=0,n=this.cleanups.length;t<n;t++)this.cleanups[t]();if(this.cleanups.length=0,this.scopes){let e=this.scopes.slice();for(t=0,n=e.length;t<n;t++)e[t].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!e){let e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.parent=void 0}}};function Ae(){return k}var A,je=new WeakSet,Me=class{constructor(e){this.fn=e,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,k&&(k.active?k.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,je.has(this)&&(je.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||Ie(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,Ye(this),ze(this);let e=A,t=Ge;A=this,Ge=!0;try{return this.fn()}finally{Be(this),A=e,Ge=t,this.flags&=-3}}stop(){if(this.flags&1){for(let e=this.deps;e;e=e.nextDep)Ue(e);this.deps=this.depsTail=void 0,Ye(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?je.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){Ve(this)&&this.run()}get dirty(){return Ve(this)}},Ne=0,Pe,Fe;function Ie(e,t=!1){e.flags|=8,t?(e.next=Fe,Fe=e):(e.next=Pe,Pe=e)}function Le(){Ne++}function Re(){if(--Ne>0)return;if(Fe){let e=Fe;for(Fe=void 0;e;){let t=e.next;e.next=void 0,e.flags&=-9,e=t}}let e;for(;Pe;){let t=Pe;for(Pe=void 0;t;){let n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(t){e||=t}t=n}}if(e)throw e}function ze(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Be(e){let t,n=e.depsTail,r=n;for(;r;){let e=r.prevDep;r.version===-1?(r===n&&(n=e),Ue(r),We(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=e}e.deps=t,e.depsTail=n}function Ve(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(He(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function He(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Xe)||(e.globalVersion=Xe,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Ve(e))))return;e.flags|=2;let t=e.dep,n=A,r=Ge;A=e,Ge=!0;try{ze(e);let n=e.fn(e._value);(t.version===0||ce(n,e._value))&&(e.flags|=128,e._value=n,t.version++)}catch(e){throw t.version++,e}finally{A=n,Ge=r,Be(e),e.flags&=-3}}function Ue(e,t=!1){let{dep:n,prevSub:r,nextSub:i}=e;if(r&&(r.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let e=n.computed.deps;e;e=e.nextDep)Ue(e,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function We(e){let{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}var Ge=!0,Ke=[];function qe(){Ke.push(Ge),Ge=!1}function Je(){let e=Ke.pop();Ge=e===void 0||e}function Ye(e){let{cleanup:t}=e;if(e.cleanup=void 0,t){let e=A;A=void 0;try{t()}finally{A=e}}}var Xe=0,Ze=class{constructor(e,t){this.sub=e,this.dep=t,this.version=t.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}},Qe=class{constructor(e){this.computed=e,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(e){if(!A||!Ge||A===this.computed)return;let t=this.activeLink;if(t===void 0||t.sub!==A)t=this.activeLink=new Ze(A,this),A.deps?(t.prevDep=A.depsTail,A.depsTail.nextDep=t,A.depsTail=t):A.deps=A.depsTail=t,$e(t);else if(t.version===-1&&(t.version=this.version,t.nextDep)){let e=t.nextDep;e.prevDep=t.prevDep,t.prevDep&&(t.prevDep.nextDep=e),t.prevDep=A.depsTail,t.nextDep=void 0,A.depsTail.nextDep=t,A.depsTail=t,A.deps===t&&(A.deps=e)}return t}trigger(e){this.version++,Xe++,this.notify(e)}notify(e){Le();try{for(let e=this.subs;e;e=e.prevSub)e.sub.notify()&&e.sub.dep.notify()}finally{Re()}}};function $e(e){if(e.dep.sc++,e.sub.flags&4){let t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let e=t.deps;e;e=e.nextDep)$e(e)}let n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}var et=new WeakMap,tt=Symbol(``),nt=Symbol(``),rt=Symbol(``);function j(e,t,n){if(Ge&&A){let t=et.get(e);t||et.set(e,t=new Map);let r=t.get(n);r||(t.set(n,r=new Qe),r.map=t,r.key=n),r.track()}}function it(e,t,n,r,i,a){let o=et.get(e);if(!o){Xe++;return}let s=e=>{e&&e.trigger()};if(Le(),t===`clear`)o.forEach(s);else{let i=d(e),a=i&&te(n);if(i&&n===`length`){let e=Number(r);o.forEach((t,n)=>{(n===`length`||n===rt||!_(n)&&n>=e)&&s(t)})}else switch((n!==void 0||o.has(void 0))&&s(o.get(n)),a&&s(o.get(rt)),t){case`add`:i?a&&s(o.get(`length`)):(s(o.get(tt)),f(e)&&s(o.get(nt)));break;case`delete`:i||(s(o.get(tt)),f(e)&&s(o.get(nt)));break;case`set`:f(e)&&s(o.get(tt))}}Re()}function at(e){let t=M(e);return t===e||(j(t,`iterate`,rt),Gt(e))?t:Wt(e)?Ut(e)?t.map(e=>Yt(Jt(e))):t.map(Yt):t.map(Jt)}function ot(e){return j(e=M(e),`iterate`,rt),e}function st(e,t){return Wt(e)?Yt(Ut(e)?Jt(t):t):Jt(t)}var ct={__proto__:null,[Symbol.iterator](){return lt(this,Symbol.iterator,e=>st(this,e))},concat(...e){return at(this).concat(...e.map(e=>d(e)?at(e):e))},entries(){return lt(this,`entries`,e=>(e[1]=st(this,e[1]),e))},every(e,t){return ft(this,`every`,e,t,void 0,arguments)},filter(e,t){return ft(this,`filter`,e,t,e=>e.map(e=>st(this,e)),arguments)},find(e,t){return ft(this,`find`,e,t,e=>st(this,e),arguments)},findIndex(e,t){return ft(this,`findIndex`,e,t,void 0,arguments)},findLast(e,t){return ft(this,`findLast`,e,t,e=>st(this,e),arguments)},findLastIndex(e,t){return ft(this,`findLastIndex`,e,t,void 0,arguments)},forEach(e,t){return ft(this,`forEach`,e,t,void 0,arguments)},includes(...e){return mt(this,`includes`,e)},indexOf(...e){return mt(this,`indexOf`,e)},join(e){return at(this).join(e)},lastIndexOf(...e){return mt(this,`lastIndexOf`,e)},map(e,t){return ft(this,`map`,e,t,void 0,arguments)},pop(){return ht(this,`pop`)},push(...e){return ht(this,`push`,e)},reduce(e,...t){return pt(this,`reduce`,e,t)},reduceRight(e,...t){return pt(this,`reduceRight`,e,t)},shift(){return ht(this,`shift`)},some(e,t){return ft(this,`some`,e,t,void 0,arguments)},splice(...e){return ht(this,`splice`,e)},toReversed(){return at(this).toReversed()},toSorted(e){return at(this).toSorted(e)},toSpliced(...e){return at(this).toSpliced(...e)},unshift(...e){return ht(this,`unshift`,e)},values(){return lt(this,`values`,e=>st(this,e))}};function lt(e,t,n){let r=ot(e),i=r[t],a=i.call(r);if(r!==e&&!Gt(e)){if(a[Symbol.toStringTag]===`Array Iterator`){let e=Object.create(Object.getPrototypeOf(a));return e.next=()=>ut(a.next(),n),i!==dt[t]&&Object.defineProperties(e,{return:{get(){let e=a.return;return typeof e==`function`?e.bind(a):e}},throw:{get(){let e=a.throw;return typeof e==`function`?e.bind(a):e}}}),e}a._next=a.next,a.next=()=>ut(a._next(),n)}return a}function ut(e,t){return e.done||(e.value=t(e.value)),e}var dt=Array.prototype;function ft(e,t,n,r,i,a){let o=ot(e),s=o!==e&&!Gt(e),c=o[t];if(c!==dt[t]){let t=c.apply(e,a);return s?Jt(t):t}let l=n;o!==e&&(s?l=function(t,r){return n.call(this,st(e,t),r,e)}:n.length>2&&(l=function(t,r){return n.call(this,t,r,e)}));let u=c.call(o,l,r);return s&&i?i(u):u}function pt(e,t,n,r){let i=ot(e),a=i!==e&&!Gt(e),o=n,s=!1;i!==e&&(a?(s=r.length===0,o=function(t,r,i){return s&&(s=!1,t=st(e,t)),n.call(this,t,st(e,r),i,e)}):n.length>3&&(o=function(t,r,i){return n.call(this,t,r,i,e)}));let c=i[t](o,...r);return s?st(e,c):c}function mt(e,t,n){let r=M(e);j(r,`iterate`,rt);let i=r[t](...n);return(i===-1||i===!1)&&Kt(n[0])?(n[0]=M(n[0]),r[t](...n)):i}function ht(e,t,n=[]){qe(),Le();let r=M(e)[t].apply(e,n);return Re(),Je(),r}var gt=e(`__proto__,__v_isRef,__isVue`),_t=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!==`arguments`&&e!==`caller`).map(e=>Symbol[e]).filter(_));function vt(e){_(e)||(e=String(e));let t=M(this);return j(t,`has`,e),t.hasOwnProperty(e)}var yt=class{constructor(e=!1,t=!1){this._isReadonly=e,this._isShallow=t}get(e,t,n){if(t===`__v_skip`)return e.__v_skip;let r=this._isReadonly,i=this._isShallow;if(t===`__v_isReactive`)return!r;if(t===`__v_isReadonly`)return r;if(t===`__v_isShallow`)return i;if(t===`__v_raw`)return n===(r?i?Lt:It:i?Ft:Pt).get(e)||Object.getPrototypeOf(e)===Object.getPrototypeOf(n)?e:void 0;let a=d(e);if(!r){let e;if(a&&(e=ct[t]))return e;if(t===`hasOwnProperty`)return vt}let o=Reflect.get(e,t,N(e)?e:n);if((_(t)?_t.has(t):gt(t))||(r||j(e,`get`,t),i))return o;if(N(o)){let e=a&&te(t)?o:o.value;return r&&v(e)?Vt(e):e}return v(o)?r?Vt(o):zt(o):o}},bt=class extends yt{constructor(e=!1){super(!1,e)}set(e,t,n,r){let i=e[t],a=d(e)&&te(t);if(!this._isShallow){let e=Wt(i);if(!Gt(n)&&!Wt(n)&&(i=M(i),n=M(n)),!a&&N(i)&&!N(n))return e||(i.value=n),!0}let o=a?Number(t)<e.length:u(e,t),s=Reflect.set(e,t,n,N(e)?e:r);return e===M(r)&&s&&(o?ce(n,i)&&it(e,`set`,t,n,i):it(e,`add`,t,n)),s}deleteProperty(e,t){let n=u(e,t),r=e[t],i=Reflect.deleteProperty(e,t);return i&&n&&it(e,`delete`,t,void 0,r),i}has(e,t){let n=Reflect.has(e,t);return(!_(t)||!_t.has(t))&&j(e,`has`,t),n}ownKeys(e){return j(e,`iterate`,d(e)?`length`:tt),Reflect.ownKeys(e)}},xt=class extends yt{constructor(e=!1){super(!0,e)}set(e,t){return!0}deleteProperty(e,t){return!0}},St=new bt,Ct=new xt,wt=new bt(!0),Tt=e=>e,Et=e=>Reflect.getPrototypeOf(e);function Dt(e,t,n){return function(...r){let i=this.__v_raw,a=M(i),o=f(a),c=e===`entries`||e===Symbol.iterator&&o,l=e===`keys`&&o,u=i[e](...r),d=n?Tt:t?Yt:Jt;return!t&&j(a,`iterate`,l?nt:tt),s(Object.create(u),{next(){let{value:e,done:t}=u.next();return t?{value:e,done:t}:{value:c?[d(e[0]),d(e[1])]:d(e),done:t}}})}}function Ot(e){return function(...t){return e===`delete`?!1:e===`clear`?void 0:this}}function kt(e,t){let n={get(n){let r=this.__v_raw,i=M(r),a=M(n);e||(ce(n,a)&&j(i,`get`,n),j(i,`get`,a));let{has:o}=Et(i),s=t?Tt:e?Yt:Jt;if(o.call(i,n))return s(r.get(n));if(o.call(i,a))return s(r.get(a));r!==i&&r.get(n)},get size(){let t=this.__v_raw;return!e&&j(M(t),`iterate`,tt),t.size},has(t){let n=this.__v_raw,r=M(n),i=M(t);return e||(ce(t,i)&&j(r,`has`,t),j(r,`has`,i)),t===i?n.has(t):n.has(t)||n.has(i)},forEach(n,r){let i=this,a=i.__v_raw,o=M(a),s=t?Tt:e?Yt:Jt;return!e&&j(o,`iterate`,tt),a.forEach((e,t)=>n.call(r,s(e),s(t),i))}};return s(n,e?{add:Ot(`add`),set:Ot(`set`),delete:Ot(`delete`),clear:Ot(`clear`)}:{add(e){let n=M(this),r=Et(n),i=M(e),a=!t&&!Gt(e)&&!Wt(e)?i:e;return r.has.call(n,a)||ce(e,a)&&r.has.call(n,e)||ce(i,a)&&r.has.call(n,i)||(n.add(a),it(n,`add`,a,a)),this},set(e,n){!t&&!Gt(n)&&!Wt(n)&&(n=M(n));let r=M(this),{has:i,get:a}=Et(r),o=i.call(r,e);o||=(e=M(e),i.call(r,e));let s=a.call(r,e);return r.set(e,n),o?ce(n,s)&&it(r,`set`,e,n,s):it(r,`add`,e,n),this},delete(e){let t=M(this),{has:n,get:r}=Et(t),i=n.call(t,e);i||=(e=M(e),n.call(t,e));let a=r?r.call(t,e):void 0,o=t.delete(e);return i&&it(t,`delete`,e,void 0,a),o},clear(){let e=M(this),t=e.size!==0,n=e.clear();return t&&it(e,`clear`,void 0,void 0,void 0),n}}),[`keys`,`values`,`entries`,Symbol.iterator].forEach(r=>{n[r]=Dt(r,e,t)}),n}function At(e,t){let n=kt(e,t);return(r,i,a)=>i===`__v_isReactive`?!e:i===`__v_isReadonly`?e:i===`__v_isShallow`?t:i===`__v_raw`?r:Reflect.get(u(n,i)&&i in r?n:r,i,a)}var jt={get:At(!1,!1)},Mt={get:At(!1,!0)},Nt={get:At(!0,!1)},Pt=new WeakMap,Ft=new WeakMap,It=new WeakMap,Lt=new WeakMap;function Rt(e){switch(e){case`Object`:case`Array`:return 1;case`Map`:case`Set`:case`WeakMap`:case`WeakSet`:return 2;default:return 0}}function zt(e){return Wt(e)?e:Ht(e,!1,St,jt,Pt)}function Bt(e){return Ht(e,!1,wt,Mt,Ft)}function Vt(e){return Ht(e,!0,Ct,Nt,It)}function Ht(e,t,n,r,i){if(!v(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;let a=i.get(e);if(a)return a;let o=Rt(ee(e));if(o===0)return e;let s=new Proxy(e,o===2?r:n);return i.set(e,s),s}function Ut(e){return Wt(e)?Ut(e.__v_raw):!!(e&&e.__v_isReactive)}function Wt(e){return!!(e&&e.__v_isReadonly)}function Gt(e){return!!(e&&e.__v_isShallow)}function Kt(e){return e?!!e.__v_raw:!1}function M(e){let t=e&&e.__v_raw;return t?M(t):e}function qt(e){return!u(e,`__v_skip`)&&Object.isExtensible(e)&&T(e,`__v_skip`,!0),e}var Jt=e=>v(e)?zt(e):e,Yt=e=>v(e)?Vt(e):e;function N(e){return e?e.__v_isRef===!0:!1}function P(e){return Xt(e,!1)}function Xt(e,t){return N(e)?e:new Zt(e,t)}var Zt=class{constructor(e,t){this.dep=new Qe,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=t?e:M(e),this._value=t?e:Jt(e),this.__v_isShallow=t}get value(){return this.dep.track(),this._value}set value(e){let t=this._rawValue,n=this.__v_isShallow||Gt(e)||Wt(e);e=n?e:M(e),ce(e,t)&&(this._rawValue=e,this._value=n?e:Jt(e),this.dep.trigger())}};function F(e){return N(e)?e.value:e}var Qt={get:(e,t,n)=>t===`__v_raw`?e:F(Reflect.get(e,t,n)),set:(e,t,n,r)=>{let i=e[t];return N(i)&&!N(n)?(i.value=n,!0):Reflect.set(e,t,n,r)}};function $t(e){return Ut(e)?e:new Proxy(e,Qt)}var en=class{constructor(e,t,n){this.fn=e,this.setter=t,this._value=void 0,this.dep=new Qe(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=Xe-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!t,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&A!==this)return Ie(this,!0),!0}get value(){let e=this.dep.track();return He(this),e&&(e.version=this.dep.version),this._value}set value(e){this.setter&&this.setter(e)}};function tn(e,t,n=!1){let r,i;return h(e)?r=e:(r=e.get,i=e.set),new en(r,i,n)}var nn={},rn=new WeakMap,an=void 0;function on(e,t=!1,n=an){if(n){let t=rn.get(n);t||rn.set(n,t=[]),t.push(e)}}function sn(e,n,i=t){let{immediate:a,deep:o,once:s,scheduler:l,augmentJob:u,call:f}=i,p=e=>o?e:Gt(e)||o===!1||o===0?cn(e,1):cn(e),m,g,_,v,y=!1,b=!1;if(N(e)?(g=()=>e.value,y=Gt(e)):Ut(e)?(g=()=>p(e),y=!0):d(e)?(b=!0,y=e.some(e=>Ut(e)||Gt(e)),g=()=>e.map(e=>{if(N(e))return e.value;if(Ut(e))return p(e);if(h(e))return f?f(e,2):e()})):g=h(e)?n?f?()=>f(e,2):e:()=>{if(_){qe();try{_()}finally{Je()}}let t=an;an=m;try{return f?f(e,3,[v]):e(v)}finally{an=t}}:r,n&&o){let e=g,t=o===!0?1/0:o;g=()=>cn(e(),t)}let x=Ae(),ee=()=>{m.stop(),x&&x.active&&c(x.effects,m)};if(s&&n){let e=n;n=(...t)=>{try{return e(...t)}finally{ee()}}}let S=b?Array(e.length).fill(nn):nn,te=e=>{if(m.flags&1&&(m.dirty||e)){if(n){let t=m.run();if(e||o||y||(b?t.some((e,t)=>ce(e,S[t])):ce(t,S))){let e=an;qe();try{_&&_(),an=m;let e=[t,S===nn?void 0:b&&S[0]===nn?[]:S,v];S=t,f?f(n,3,e):n(...e)}finally{an=e,Je()}}}else m.run()}};return u&&u(te),m=new Me(g),m.scheduler=l?()=>l(te,!1):te,v=e=>on(e,!1,m),_=m.onStop=()=>{let e=rn.get(m);if(e){if(f)f(e,4);else for(let t of e)t();rn.delete(m)}},n?a?te(!0):S=m.run():l?l(te.bind(null,!0),!0):m.run(),ee.pause=m.pause.bind(m),ee.resume=m.resume.bind(m),ee.stop=ee,ee}function cn(e,t=1/0,n){if(t<=0||!v(e)||e.__v_skip||(n||=new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,N(e))cn(e.value,t,n);else if(d(e))for(let r=0;r<e.length;r++)cn(e[r],t,n);else if(p(e)||f(e))e.forEach(e=>{cn(e,t,n)});else if(S(e)){for(let r in e)cn(e[r],t,n);for(let r of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,r)&&cn(e[r],t,n)}return e}function ln(e,t,n,r){try{return r?e(...r):e()}catch(e){dn(e,t,n)}}function un(e,t,n,r){if(h(e)){let i=ln(e,t,n,r);return i&&y(i)&&i.catch(e=>{dn(e,t,n)}),i}if(d(e)){let i=[];for(let a=0;a<e.length;a++)i.push(un(e[a],t,n,r));return i}}function dn(e,n,r,i=!0){let a=n?n.vnode:null,{errorHandler:o,throwUnhandledErrorInProduction:s}=n&&n.appContext.config||t;if(n){let t=n.parent,i=n.proxy,a=`https://vuejs.org/error-reference/#runtime-${r}`;for(;t;){let n=t.ec;if(n){for(let t=0;t<n.length;t++)if(n[t](e,i,a)===!1)return}t=t.parent}if(o){qe(),ln(o,null,10,[e,i,a]),Je();return}}fn(e,r,a,i,s)}function fn(e,t,n,r=!0,i=!1){if(i)throw e;console.error(e)}var I=[],pn=-1,mn=[],hn=null,gn=0,_n=Promise.resolve(),vn=null;function yn(e){let t=vn||_n;return e?t.then(this?e.bind(this):e):t}function bn(e){let t=pn+1,n=I.length;for(;t<n;){let r=t+n>>>1,i=I[r],a=On(i);a<e||a===e&&i.flags&2?t=r+1:n=r}return t}function xn(e){if(!(e.flags&1)){let t=On(e),n=I[I.length-1];!n||!(e.flags&2)&&t>=On(n)?I.push(e):I.splice(bn(t),0,e),e.flags|=1,Sn()}}function Sn(){vn||=_n.then(kn)}function Cn(e){if(!d(e))hn&&e.id===-1?hn.splice(gn+1,0,e):e.flags&1||(mn.push(e),e.flags|=1);else for(let t=0;t<e.length;t++)mn.push(e[t]);Sn()}function wn(e,t,n,r=pn+1){for(;r<I.length;r++){let n=I[r];if(n&&n.flags&2){if(e&&n.id!==e.uid||t!==void 0&&!(n.id>=t))continue;I.splice(r,1),r=e?r-1:pn,n.flags&4&&(n.flags&=-2),n(),n.flags&4||(n.flags&=-2)}}}function Tn(e,t,n=0){if(mn.length){let e=mn,r=0;if(t){e=[];for(let i=0;i<mn.length;i++){let a=mn[i];(a.i===void 0?t.has(a):!a.i||a.i.uid<n)?mn[r++]=a:e.push(a)}}let i=[...new Set(e)].sort((e,t)=>On(e)-On(t));if(mn.length=r,hn){for(let e=0;e<i.length;e++)hn.push(i[e]);return}for(hn=i,gn=0;gn<hn.length;gn++){let e=hn[gn];e.flags&4&&(e.flags&=-2),e.flags&8||e(),e.flags&=-2}hn=null,gn=0}}var En=!1;function Dn(e,t){if(En){e();return}let n=t===void 0?void 0:new Set(mn);e(),En=!0;try{wn(void 0,t),Tn(void 0,n,t)}finally{En=!1}}var On=e=>e.id==null?e.flags&2?-1:1/0:e.id;function kn(e){try{for(pn=0;pn<I.length;pn++){let e=I[pn];e&&!(e.flags&8)&&(e.flags&4&&(e.flags&=-2),ln(e,e.i,e.i?15:14),e.flags&4||(e.flags&=-2))}}finally{for(;pn<I.length;pn++){let e=I[pn];e&&(e.flags&=-2)}pn=-1,I.length=0,Tn(e),vn=null,(I.length||mn.length)&&kn(e)}}var An=null,jn=null;function Mn(e){let t=An;return An=e,jn=e&&e.type.__scopeId||null,t}function Nn(e,t=An,n){if(!t||e._n)return e;let r=(...n)=>{r._d&&zi(-1);let i=Mn(t),a=Ii.length,o;try{o=e(...n)}finally{for(let e=Ii.length;e>a;e--)Li();Mn(i),r._d&&zi(1)}return o};return r._n=!0,r._c=!0,r._d=!0,r}function Pn(e,n){if(An===null)return e;let r=ba(An),i=e.dirs||=[];for(let e=0;e<n.length;e++){let[a,o,s,c=t]=n[e];a&&(h(a)&&(a={mounted:a,updated:a}),a.deep&&cn(o),i.push({dir:a,instance:r,value:o,oldValue:void 0,arg:s,modifiers:c}))}return e}function Fn(e,t,n,r){let i=e.dirs,a=t&&t.dirs;for(let o=0;o<i.length;o++){let s=i[o];a&&(s.oldValue=a[o].value);let c=s.dir[r];c&&(qe(),un(c,n,8,[e.el,s,e,t]),Je())}}function In(e,t){if(J){let n=J.provides,r=J.parent&&J.parent.provides;r===n&&(n=J.provides=Object.create(r)),n[e]=t}}function Ln(e,t,n=!1){let r=aa();if(r||Ur){let i=Ur?Ur._context.provides:r?r.parent==null||r.ce?r.vnode.appContext&&r.vnode.appContext.provides:r.parent.provides:void 0;if(i&&e in i)return i[e];if(arguments.length>1)return n&&h(t)?t.call(r&&r.proxy):t}}var Rn=Symbol.for(`v-scx`),zn=()=>Ln(Rn);function Bn(e,t,n){return Vn(e,t,n)}function Vn(e,n,i=t){let{immediate:a,deep:o,flush:c,once:l}=i,u=s({},i),d=n&&a||!n&&c!==`post`,f;if(da){if(c===`sync`){let e=zn();f=e.__watcherHandles||=[]}else if(!d){let e=()=>{};return e.stop=r,e.resume=r,e.pause=r,e}}let p=J;u.call=(e,t,n)=>un(e,p,t,n);let m=!1;c===`post`?u.scheduler=e=>{e.i=p,B(e,p&&p.suspense)}:c!==`sync`&&(m=!0,u.scheduler=(e,t)=>{t?e():xn(e)}),u.augmentJob=e=>{n&&(e.flags|=4),m&&(e.flags|=2,p&&(e.id=p.uid,e.i=p))};let h=sn(e,n,u);return da&&(f?f.push(h):d&&h()),h}function Hn(e,t,n){let r=this.proxy,i=g(e)?e.includes(`.`)?Un(r,e):()=>r[e]:e.bind(r,r),a;h(t)?a=t:(a=t.handler,n=t);let o=ca(this),s=Vn(i,a.bind(r),n);return o(),s}function Un(e,t){let n=t.split(`.`);return()=>{let t=e;for(let e=0;e<n.length&&t;e++)t=t[n[e]];return t}}var Wn=Symbol(`_vte`),Gn=e=>e.__isTeleport,Kn=Symbol(`_leaveCb`);function qn(e){let t=e[0];if(e.length>1){for(let n of e)if(n.type!==Pi){t=n;break}}return t}function Jn(e){if(!rr(e))return Gn(e.type)&&e.children?qn(e.children):e;if(e.component)return e.component.subTree;let{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&h(n.default))return n.default()}}function Yn(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;let n=e.component.subTree;Yn(Gn(n.type)&&Jn(n)||n,t)}else if(e.shapeFlag&128)e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback);else if(e.transition=t,e.type===V&&d(e.children)){let n=Xr(e.children,!1);n&&Yn(n,t)}}function Xn(e){if(e.component)return Xn(e.component.subTree);if(e.type===V){let t=d(e.children)&&Xr(e.children,!1);return t?Xn(t):void 0}if(e.type!==Pi)return e}function L(e,t){return h(e)?s({name:e.name},t,{setup:e}):e}function Zn(e){e.ids=[e.ids[0]+e.ids[2]+++`-`,0,0]}function Qn(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}var $n=new WeakMap;function er(e,n,r,a,o=!1){if(d(e)){e.forEach((e,t)=>er(e,n&&(d(n)?n[t]:n),r,a,o));return}if(nr(a)&&!o){a.shapeFlag&512&&a.type.__asyncResolved&&a.component.subTree.component&&er(e,n,r,a.component.subTree);return}let s=a.shapeFlag&4?ba(a.component):a.el,l=o?null:s,{i:f,r:p}=e,m=n&&n.r,_=f.refs===t?f.refs={}:f.refs,v=f.setupState,y=M(v),b=v===t?i:e=>!Qn(_,e)&&u(y,e),x=(e,t)=>!(t&&Qn(_,t));if(m!=null&&m!==p){if(tr(n),g(m))_[m]=null,b(m)&&(v[m]=null);else if(N(m)){let e=n;x(m,e.k)&&(m.value=null),e.k&&(_[e.k]=null)}}if(h(p))ln(p,f,12,[l,_]);else{let t=g(p),n=N(p);if(t||n){let i=()=>{if(e.f){let n=t?b(p)?v[p]:_[p]:x(p)||!e.k?p.value:_[e.k];if(o)d(n)&&c(n,s);else if(d(n))n.includes(s)||n.push(s);else if(t)_[p]=[s],b(p)&&(v[p]=_[p]);else{let t=[s];x(p,e.k)&&(p.value=t),e.k&&(_[e.k]=t)}}else t?(_[p]=l,b(p)&&(v[p]=l)):n&&(x(p,e.k)&&(p.value=l),e.k&&(_[e.k]=l))};if(l){let t=()=>{i(),$n.delete(e)};t.id=-1,$n.set(e,t),B(t,r)}else tr(e),i()}}}function tr(e){let t=$n.get(e);t&&(t.flags|=8,$n.delete(e))}fe().requestIdleCallback,fe().cancelIdleCallback;var nr=e=>!!e.type.__asyncLoader,rr=e=>e.type.__isKeepAlive;function ir(e,t){or(e,`a`,t)}function ar(e,t){or(e,`da`,t)}function or(e,t,n=J){let r=e.__wdc||=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}return e()};if(cr(t,r,n),n){let e=n.parent;for(;e&&e.parent;)rr(e.parent.vnode)&&sr(r,t,n,e),e=e.parent}}function sr(e,t,n,r){let i=cr(t,e,r,!0);hr(()=>{c(r[t],i)},n)}function cr(e,t,n=J,r=!1){if(n){let i=n[e]||(n[e]=[]),a=t.__weh||=(...r)=>{qe();let i=ca(n),a=un(t,n,e,r);return i(),Je(),a};return r?i.unshift(a):i.push(a),a}}var lr=e=>(t,n=J)=>{(!da||e===`sp`)&&cr(e,(...e)=>t(...e),n)},ur=lr(`bm`),dr=lr(`m`),fr=lr(`bu`),pr=lr(`u`),mr=lr(`bum`),hr=lr(`um`),gr=lr(`sp`),_r=lr(`rtg`),vr=lr(`rtc`);function yr(e,t=J){cr(`ec`,e,t)}var br=Symbol.for(`v-ndc`);function R(e,t,n,r){let i,a=n&&n[r],o=d(e);if(o||g(e)){let n=o&&Ut(e),r=!1,s=!1;n&&(r=!Gt(e),s=Wt(e),e=ot(e)),i=Array(e.length);for(let n=0,o=e.length;n<o;n++)i[n]=t(r?s?Yt(Jt(e[n])):Jt(e[n]):e[n],n,void 0,a&&a[n])}else if(typeof e==`number`){if(!Number.isInteger(e)||e<0)i=[];else{i=Array(e);for(let n=0;n<e;n++)i[n]=t(n+1,n,void 0,a&&a[n])}}else if(v(e)){if(e[Symbol.iterator])i=Array.from(e,(e,n)=>t(e,n,void 0,a&&a[n]));else{let n=Object.keys(e);i=Array(n.length);for(let r=0,o=n.length;r<o;r++){let o=n[r];i[r]=t(e[o],o,r,a&&a[r])}}}else i=[];return n&&(n[r]=i),i}var xr=e=>e?ua(e)?ba(e):xr(e.parent):null,Sr=s(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>xr(e.parent),$root:e=>xr(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>jr(e),$forceUpdate:e=>e.f||=()=>{xn(e.update)},$nextTick:e=>e.n||=yn.bind(e.proxy),$watch:e=>Hn.bind(e)}),Cr=(e,n)=>e!==t&&!e.__isScriptSetup&&u(e,n),wr={get({_:e},n){if(n===`__v_skip`)return!0;let{ctx:r,setupState:i,data:a,props:o,accessCache:s,type:c,appContext:l}=e;if(n[0]!==`$`){let e=s[n];if(e!==void 0)switch(e){case 1:return i[n];case 2:return a[n];case 4:return r[n];case 3:return o[n]}else if(Cr(i,n))return s[n]=1,i[n];else if(a!==t&&u(a,n))return s[n]=2,a[n];else if(u(o,n))return s[n]=3,o[n];else if(r!==t&&u(r,n))return s[n]=4,r[n];else Er&&(s[n]=0)}let d=Sr[n],f,p;if(d)return n===`$attrs`&&j(e.attrs,`get`,``),d(e);if((f=c.__cssModules)&&(f=f[n]))return f;if(r!==t&&u(r,n))return s[n]=4,r[n];if(p=l.config.globalProperties,u(p,n))return p[n]},set({_:e},n,r){let{data:i,setupState:a,ctx:o}=e;return Cr(a,n)?(a[n]=r,!0):i!==t&&u(i,n)?(i[n]=r,!0):u(e.props,n)||n[0]===`$`&&n.slice(1)in e?!1:(o[n]=r,!0)},has({_:{data:e,setupState:n,accessCache:r,ctx:i,appContext:a,props:o,type:s}},c){let l;return!!(r[c]||e!==t&&c[0]!==`$`&&u(e,c)||Cr(n,c)||u(o,c)||u(i,c)||u(Sr,c)||u(a.config.globalProperties,c)||(l=s.__cssModules)&&l[c])},defineProperty(e,t,n){return n.get==null?u(n,`value`)&&this.set(e,t,n.value,null):e._.accessCache[t]=0,Reflect.defineProperty(e,t,n)}};function Tr(e){return d(e)?e.reduce((e,t)=>(e[t]=null,e),{}):e}var Er=!0;function Dr(e){let t=jr(e),n=e.proxy,i=e.ctx;Er=!1,t.beforeCreate&&kr(t.beforeCreate,e,`bc`);let{data:a,computed:o,methods:s,watch:c,provide:l,inject:u,created:f,beforeMount:p,mounted:m,beforeUpdate:g,updated:_,activated:y,deactivated:b,beforeDestroy:x,beforeUnmount:ee,destroyed:S,unmounted:te,render:ne,renderTracked:re,renderTriggered:ie,errorCaptured:C,serverPrefetch:ae,expose:w,inheritAttrs:oe,components:se,directives:ce,filters:le}=t;if(u&&Or(u,i,null),s)for(let e in s){let t=s[e];h(t)&&(i[e]=t.bind(n))}if(a){let t=a.call(n,n);v(t)&&(e.data=zt(t))}if(Er=!0,o)for(let e in o){let t=o[e],a=Y({get:h(t)?t.bind(n,n):h(t.get)?t.get.bind(n,n):r,set:!h(t)&&h(t.set)?t.set.bind(n):r});Object.defineProperty(i,e,{enumerable:!0,configurable:!0,get:()=>a.value,set:e=>a.value=e})}if(c)for(let e in c)Ar(c[e],i,n,e);if(l){let e=h(l)?l.call(n):l;Reflect.ownKeys(e).forEach(t=>{In(t,e[t])})}f&&kr(f,e,`c`);function T(e,t){d(t)?t.forEach(t=>e(t.bind(n))):t&&e(t.bind(n))}if(T(ur,p),T(dr,m),T(fr,g),T(pr,_),T(ir,y),T(ar,b),T(yr,C),T(vr,re),T(_r,ie),T(mr,ee),T(hr,te),T(gr,ae),d(w)){if(w.length){let t=e.exposed||={};w.forEach(e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t,enumerable:!0})})}else e.exposed||={}}ne&&e.render===r&&(e.render=ne),oe!=null&&(e.inheritAttrs=oe),se&&(e.components=se),ce&&(e.directives=ce),ae&&Zn(e)}function Or(e,t,n=r){d(e)&&(e=Ir(e));for(let n in e){let r=e[n],i;i=v(r)?`default`in r?Ln(r.from||n,r.default,!0):Ln(r.from||n):Ln(r),N(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e}):t[n]=i}}function kr(e,t,n){un(d(e)?e.map(e=>e.bind(t.proxy)):e.bind(t.proxy),t,n)}function Ar(e,t,n,r){let i=r.includes(`.`)?Un(n,r):()=>n[r];if(g(e)){let n=t[e];h(n)&&Bn(i,n)}else if(h(e))Bn(i,e.bind(n));else if(v(e)){if(d(e))e.forEach(e=>Ar(e,t,n,r));else{let r=h(e.handler)?e.handler.bind(n):t[e.handler];h(r)&&Bn(i,r,e)}}}function jr(e){let t=e.type,{mixins:n,extends:r}=t,{mixins:i,optionsCache:a,config:{optionMergeStrategies:o}}=e.appContext,s=a.get(t),c;return s?c=s:!i.length&&!n&&!r?c=t:(c={},i.length&&i.forEach(e=>Mr(c,e,o,!0)),Mr(c,t,o)),v(t)&&a.set(t,c),c}function Mr(e,t,n,r=!1){let{mixins:i,extends:a}=t;a&&Mr(e,a,n,!0),i&&i.forEach(t=>Mr(e,t,n,!0));for(let i in t)if(!(r&&i===`expose`)){let r=Nr[i]||n&&n[i];e[i]=r?r(e[i],t[i]):t[i]}return e}var Nr={data:Pr,props:Rr,emits:Rr,methods:Lr,computed:Lr,beforeCreate:z,created:z,beforeMount:z,mounted:z,beforeUpdate:z,updated:z,beforeDestroy:z,beforeUnmount:z,destroyed:z,unmounted:z,activated:z,deactivated:z,errorCaptured:z,serverPrefetch:z,components:Lr,directives:Lr,watch:zr,provide:Pr,inject:Fr};function Pr(e,t){return t?e?function(){return s(h(e)?e.call(this,this):e,h(t)?t.call(this,this):t)}:t:e}function Fr(e,t){return Lr(Ir(e),Ir(t))}function Ir(e){if(d(e)){let t={};for(let n=0;n<e.length;n++)t[e[n]]=e[n];return t}return e}function z(e,t){return e?[...new Set([].concat(e,t))]:t}function Lr(e,t){return e?s(Object.create(null),e,t):t}function Rr(e,t){return e?d(e)&&d(t)?[...new Set([...e,...t])]:s(Object.create(null),Tr(e),Tr(t??{})):t}function zr(e,t){if(!e)return t;if(!t)return e;let n=s(Object.create(null),e);for(let r in t)n[r]=z(e[r],t[r]);return n}function Br(){return{app:null,config:{isNativeTag:i,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}var Vr=0;function Hr(e,t){return function(n,r=null){h(n)||(n=s({},n)),r!=null&&!v(r)&&(r=null);let i=Br(),a=new WeakSet,o=[],c=!1,l=i.app={_uid:Vr++,_component:n,_props:r,_container:null,_context:i,_instance:null,version:Sa,get config(){return i.config},set config(e){},use(e,...t){return a.has(e)||(e&&h(e.install)?(a.add(e),e.install(l,...t)):h(e)&&(a.add(e),e(l,...t))),l},mixin(e){return i.mixins.includes(e)||i.mixins.push(e),l},component(e,t){return t?(i.components[e]=t,l):i.components[e]},directive(e,t){return t?(i.directives[e]=t,l):i.directives[e]},mount(a,o,s){if(!c){let u=l._ceVNode||K(n,r);return u.appContext=i,s===!0?s=`svg`:s===!1&&(s=void 0),o&&t?t(u,a):e(u,a,s),c=!0,l._container=a,a.__vue_app__=l,ba(u.component)}},onUnmount(e){o.push(e)},unmount(){c&&(un(o,l._instance,16),e(null,l._container),delete l._container.__vue_app__)},provide(e,t){return i.provides[e]=t,l},runWithContext(e){let t=Ur;Ur=l;try{return e()}finally{Ur=t}}};return l}}var Ur=null,Wr=(e,t)=>t===`modelValue`||t===`model-value`?e.modelModifiers:e[`${t}Modifiers`]||e[`${C(t)}Modifiers`]||e[`${w(t)}Modifiers`];function Gr(e,n,...r){if(e.isUnmounted)return;let i=e.vnode.props||t,a=r,o=n.startsWith(`update:`),s=o&&Wr(i,n.slice(7));s&&(s.trim&&(a=r.map(e=>g(e)?e.trim():e)),s.number&&(a=a.map(ue)));let c,l=i[c=se(n)]||i[c=se(C(n))];!l&&o&&(l=i[c=se(w(n))]),l&&un(l,e,6,a);let u=i[c+`Once`];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[c])return;e.emitted[c]=!0,un(u,e,6,a)}}var Kr=new WeakMap;function qr(e,t,n=!1){let r=n?Kr:t.emitsCache,i=r.get(e);if(i!==void 0)return i;let a=e.emits,o={},c=!1;if(!h(e)){let r=e=>{let n=qr(e,t,!0);n&&(c=!0,s(o,n))};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}return!a&&!c?(v(e)&&r.set(e,null),null):(d(a)?a.forEach(e=>o[e]=null):s(o,a),v(e)&&r.set(e,o),o)}function Jr(e,t){return!e||!a(t)?!1:(t=t.slice(2),t=t===`Once`?t:t.replace(/Once$/,``),u(e,t[0].toLowerCase()+t.slice(1))||u(e,w(t))||u(e,t))}function Yr(e){let{type:t,vnode:n,proxy:r,withProxy:i,propsOptions:[a],slots:s,attrs:c,emit:l,render:u,renderCache:d,props:f,data:p,setupState:m,ctx:h,inheritAttrs:g}=e,_=Mn(e),v,y;try{if(n.shapeFlag&4){let e=i||r,t=e;v=Xi(u.call(t,e,d,f,m,p,h)),y=c}else{let e=t;v=Xi(e.length>1?e(f,{attrs:c,slots:s,emit:l}):e(f,null)),y=t.props?c:Zr(c)}}catch(t){Ii.length=0,dn(t,e,1),v=K(Pi)}let b=v;if(y&&g!==!1){let e=Object.keys(y),{shapeFlag:t}=b;e.length&&t&7&&(a&&e.some(o)&&(y=Qr(y,a)),b=Ji(b,y,!1,!0))}return n.dirs&&(b=Ji(b,null,!1,!0),b.dirs=b.dirs?b.dirs.concat(n.dirs):n.dirs),n.transition&&Yn(Gn(b.type)&&Jn(b)||b,n.transition),v=b,Mn(_),v}function Xr(e,t=!0){let n;for(let t=0;t<e.length;t++){let r=e[t];if(Hi(r)){if(r.type!==Pi||r.children===`v-if`){if(n)return;n=r}}else return}return n}var Zr=e=>{let t;for(let n in e)(n===`class`||n===`style`||a(n))&&((t||={})[n]=e[n]);return t},Qr=(e,t)=>{let n={};for(let r in e)(!o(r)||!(r.slice(9)in t))&&(n[r]=e[r]);return n};function $r(e,t,n){let{props:r,children:i,component:a}=e,{props:o,children:s,patchFlag:c}=t,l=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&c>=0){if(c&1024)return!0;if(c&16)return r?ei(r,o,l):!!o;if(c&8){let e=t.dynamicProps;for(let t=0;t<e.length;t++){let n=e[t];if(ti(o,r,n)&&!Jr(l,n))return!0}}}else return(i||s)&&(!s||!s.$stable)?!0:r===o?!1:r?!o||ei(r,o,l):!!o;return!1}function ei(e,t,n){let r=Object.keys(t);if(r.length!==Object.keys(e).length)return!0;for(let i=0;i<r.length;i++){let a=r[i];if(!u(e,a)||ti(t,e,a)&&!Jr(n,a))return!0}return!1}function ti(e,t,n){let r=e[n],i=t[n];return n===`style`&&v(r)&&v(i)?!we(r,i):r!==i}function ni({vnode:e,parent:t,suspense:n},r){for(;t;){let n=t.subTree;if(n.suspense&&n.suspense.activeBranch===e&&(n.suspense.vnode.el=n.el=r,e=n),n===e)(e=t.vnode).el=r,t=t.parent;else break}n&&n.activeBranch===e&&(n.vnode.el=r)}var ri={},ii=()=>Object.create(ri),ai=e=>Object.getPrototypeOf(e)===ri;function oi(e,t,n,r=!1){let i={},a=ii();e.propsDefaults=Object.create(null),ci(e,t,i,a);for(let t in e.propsOptions[0])t in i||(i[t]=void 0);e.props=n?r?i:Bt(i):e.type.props?i:a,e.attrs=a}function si(e,t,n,r){let{props:i,attrs:a,vnode:{patchFlag:o}}=e,s=M(i),[c]=e.propsOptions,l=!1;if((r||o>0)&&!(o&16)){if(o&8){let n=e.vnode.dynamicProps;for(let r=0;r<n.length;r++){let o=n[r];if(Jr(e.emitsOptions,o))continue;let d=t[o];if(c){if(u(a,o))d!==a[o]&&(a[o]=d,l=!0);else{let t=C(o);i[t]=li(c,s,t,d,e,!1)}}else d!==a[o]&&(a[o]=d,l=!0)}}}else{ci(e,t,i,a)&&(l=!0);let r;for(let a in s)(!t||!u(t,a)&&((r=w(a))===a||!u(t,r)))&&(c?n&&(n[a]!==void 0||n[r]!==void 0)&&(i[a]=li(c,s,a,void 0,e,!0)):delete i[a]);if(a!==s)for(let e in a)(!t||!u(t,e))&&(delete a[e],l=!0)}l&&it(e.attrs,`set`,``)}function ci(e,n,r,i){let[a,o]=e.propsOptions,s=!1,c;if(n)for(let t in n){if(ne(t))continue;let l=n[t],d;a&&u(a,d=C(t))?!o||!o.includes(d)?r[d]=l:(c||={})[d]=l:Jr(e.emitsOptions,t)||(!(t in i)||l!==i[t])&&(i[t]=l,s=!0)}if(o){let n=M(r),i=c||t;for(let t=0;t<o.length;t++){let s=o[t];r[s]=li(a,n,s,i[s],e,!u(i,s))}}return s}function li(e,t,n,r,i,a){let o=e[n];if(o!=null){let e=u(o,`default`);if(e&&r===void 0){let e=o.default;if(o.type!==Function&&!o.skipFactory&&h(e)){let{propsDefaults:a}=i;if(n in a)r=a[n];else{let o=ca(i);r=a[n]=e.call(null,t),o()}}else r=e;i.ce&&i.ce._setProp(n,r)}o[0]&&(a&&!e?r=!1:o[1]&&(r===``||r===w(n))&&(r=!0))}return r}var ui=new WeakMap;function di(e,r,i=!1){let a=i?ui:r.propsCache,o=a.get(e);if(o)return o;let c=e.props,l={},f=[],p=!1;if(!h(e)){let t=e=>{p=!0;let[t,n]=di(e,r,!0);s(l,t),n&&f.push(...n)};!i&&r.mixins.length&&r.mixins.forEach(t),e.extends&&t(e.extends),e.mixins&&e.mixins.forEach(t)}if(!c&&!p)return v(e)&&a.set(e,n),n;if(d(c))for(let e=0;e<c.length;e++){let n=C(c[e]);fi(n)&&(l[n]=t)}else if(c)for(let e in c){let t=C(e);if(fi(t)){let n=c[e],r=l[t]=d(n)||h(n)?{type:n}:s({},n),i=r.type,a=!1,o=!0;if(d(i))for(let e=0;e<i.length;++e){let t=i[e],n=h(t)&&t.name;if(n===`Boolean`){a=!0;break}n===`String`&&(o=!1)}else a=h(i)&&i.name===`Boolean`;r[0]=a,r[1]=o,(a||u(r,`default`))&&f.push(t)}}let m=[l,f];return v(e)&&a.set(e,m),m}function fi(e){return e[0]!==`$`&&!ne(e)}var pi=e=>e===`_`||e===`_ctx`||e===`$stable`,mi=e=>d(e)?e.map(Xi):[Xi(e)],hi=(e,t,n)=>{if(t._n)return t;let r=Nn((...e)=>mi(t(...e)),n);return r._c=!1,r},gi=(e,t,n)=>{let r=e._ctx;for(let n in e){if(pi(n))continue;let i=e[n];if(h(i))t[n]=hi(n,i,r);else if(i!=null){let e=mi(i);t[n]=()=>e}}},_i=(e,t)=>{let n=mi(t);e.slots.default=()=>n},vi=(e,t,n)=>{for(let r in t)(n||!pi(r))&&(e[r]=t[r])},yi=(e,t,n)=>{let r=e.slots=ii();if(e.vnode.shapeFlag&32){let e=t._;e?(vi(r,t,n),n&&T(r,`_`,e,!0)):gi(t,r)}else t&&_i(e,t)},bi=(e,n,r)=>{let{vnode:i,slots:a}=e,o=!0,s=t;if(i.shapeFlag&32){let e=n._;e?r&&e===1?o=!1:vi(a,n,r):(o=!n.$stable,gi(n,a)),s=n}else n&&(_i(e,n),s={default:1});if(o)for(let e in a)!pi(e)&&s[e]==null&&delete a[e]},B=Mi;function xi(e){return Si(e)}function Si(e,i){let a=fe();a.__VUE__=!0;let{insert:o,remove:s,patchProp:c,createElement:l,createText:u,createComment:d,setText:f,setElementText:p,parentNode:m,nextSibling:h,setScopeId:g=r,insertStaticContent:_}=e,v=(e,t,r,i=null,a=null,o=null,s=void 0,c=null,l=!!t.dynamicChildren)=>{if(e===t)return;e&&!Ui(e,t)&&(i=xe(e),D(e,a,o,!0),e=null),t.patchFlag===-2&&(l=!1,t.dynamicChildren=null),t.dynamicChildren&&e&&e.dynamicChildren&&e.dynamicChildren.hasOnce&&(t.dynamicChildren===n&&(t.dynamicChildren=[]),t.dynamicChildren.hasOnce=!0);let{type:u,ref:d,shapeFlag:f}=t;switch(u){case Ni:y(e,t,r,i);break;case Pi:b(e,t,r,i);break;case Fi:e??x(t,r,i,s);break;case V:se(e,t,r,i,a,o,s,c,l);break;default:f&1?te(e,t,r,i,a,o,s,c,l):f&6?ce(e,t,r,i,a,o,s,c,l):(f&64||f&128)&&u.process(e,t,r,i,a,o,s,c,l,Ce)}d!=null&&a?er(d,e&&e.ref,o,t||e,!t):d==null&&e&&e.ref!=null&&er(e.ref,null,o,e,!0)},y=(e,t,n,r)=>{if(e==null)o(t.el=u(t.children),n,r);else{let n=t.el=e.el;t.children!==e.children&&f(n,t.children)}},b=(e,t,n,r)=>{e==null?o(t.el=d(t.children||``),n,r):t.el=e.el},x=(e,t,n,r)=>{[e.el,e.anchor]=_(e.children,t,n,r,e.el,e.anchor)},ee=({el:e,anchor:t},n,r)=>{let i;for(;e&&e!==t;)i=h(e),o(e,n,r),e=i;o(t,n,r)},S=({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=h(e),s(e),e=n;s(t)},te=(e,t,n,r,i,a,o,s,c)=>{if(t.type===`svg`?o=`svg`:t.type===`math`&&(o=`mathml`),e==null)re(t,n,r,i,a,o,s,c);else{let n=e.el&&e.el._isVueCE?e.el:null;try{n&&n._beginPatch(),ae(e,t,i,a,o,s,c)}finally{n&&n._endPatch()}}},re=(e,t,n,r,i,a,s,u)=>{let d,f,{props:m,shapeFlag:h,transition:g,dirs:_}=e;if(d=e.el=l(e.type,a,m&&m.is,m),h&8?p(d,e.children):h&16&&C(e.children,d,null,r,i,Ci(e,a),s,u),_&&Fn(e,null,r,`created`),ie(d,e,e.scopeId,s,r),m){for(let e in m)e!==`value`&&!ne(e)&&c(d,e,null,m[e],a,r);`value`in m&&c(d,`value`,null,m.value,a),(f=m.onVnodeBeforeMount)&&ea(f,r,e)}_&&Fn(e,null,r,`beforeMount`);let v=Ti(i,g);v&&g.beforeEnter(d),o(d,t,n),((f=m&&m.onVnodeMounted)||v||_)&&B(()=>{try{f&&ea(f,r,e),v&&g.enter(d),_&&Fn(e,null,r,`mounted`)}finally{}},i)},ie=(e,t,n,r,i)=>{if(n&&g(e,n),r)for(let t=0;t<r.length;t++)g(e,r[t]);if(i){let n=i.subTree;if(t===n||ji(n.type)&&(n.ssContent===t||n.ssFallback===t)){let t=i.vnode;ie(e,t,t.scopeId,t.slotScopeIds,i.parent)}}},C=(e,t,n,r,i,a,o,s,c=0)=>{for(let l=c;l<e.length;l++){let c=e[l]=s?Zi(e[l]):Xi(e[l]);v(null,c,t,n,r,i,a,o,s)}},ae=(e,n,r,i,a,o,s)=>{let l=n.el=e.el,{patchFlag:u,dynamicChildren:d,dirs:f}=n;u|=e.patchFlag&16;let m=e.props||t,h=n.props||t,g;if(r&&wi(r,!1),(g=h.onVnodeBeforeUpdate)&&ea(g,r,n,e),f&&Fn(n,e,r,`beforeUpdate`),r&&wi(r,!0),d&&(!e.dynamicChildren||e.dynamicChildren.length!==d.length)&&(u=0,s=!1,d=null),(m.innerHTML&&h.innerHTML==null||m.textContent&&h.textContent==null)&&p(l,``),d?w(e.dynamicChildren,d,l,r,i,Ci(n,a),o):s||pe(e,n,l,null,r,i,Ci(n,a),o,!1),u>0){if(u&16)oe(l,m,h,r,a);else if(u&2&&m.class!==h.class&&c(l,`class`,null,h.class,a),u&4&&c(l,`style`,m.style,h.style,a),u&8){let e=n.dynamicProps;for(let t=0;t<e.length;t++){let n=e[t],i=m[n],o=h[n];(o!==i||n===`value`)&&c(l,n,i,o,a,r)}}u&1&&e.children!==n.children&&p(l,n.children)}else!s&&d==null&&oe(l,m,h,r,a);((g=h.onVnodeUpdated)||f)&&B(()=>{g&&ea(g,r,n,e),f&&Fn(n,e,r,`updated`)},i)},w=(e,t,n,r,i,a,o)=>{for(let s=0;s<t.length;s++){let c=e[s],l=t[s],u=c.el||Ai(c),d=u&&(c.type===V||!Ui(c,l)||c.shapeFlag&198)?m(u):n;v(c,l,d,null,r,i,a,o,!0)}},oe=(e,n,r,i,a)=>{if(n!==r){if(n!==t)for(let t in n)!ne(t)&&!(t in r)&&c(e,t,n[t],null,a,i);for(let t in r){if(ne(t))continue;let o=r[t],s=n[t];o!==s&&t!==`value`&&c(e,t,s,o,a,i)}`value`in r&&c(e,`value`,n.value,r.value,a)}},se=(e,t,n,r,i,a,s,c,l)=>{let d=t.el=e?e.el:u(``),f=t.anchor=e?e.anchor:u(``),{patchFlag:p,dynamicChildren:m,slotScopeIds:h}=t;h&&(c=c?c.concat(h):h),e==null?(o(d,n,r),o(f,n,r),C(t.children||[],n,f,i,a,s,c,l)):p>0&&p&64&&m&&e.dynamicChildren&&e.dynamicChildren.length===m.length?(w(e.dynamicChildren,m,n,i,a,s,c),(t.key!=null||i&&t===i.subTree)&&Ei(e,t,!0)):pe(e,t,n,f,i,a,s,c,l)},ce=(e,t,n,r,i,a,o,s,c)=>{t.slotScopeIds=s,e==null?t.shapeFlag&512?i.ctx.activate(t,n,r,o,c):T(t,n,r,i,a,o,c):ue(e,t,c)},T=(e,t,n,r,i,a,o)=>{let s=e.component=ia(e,r,i);if(rr(e)&&(s.ctx.renderer=Ce),fa(s,!1,o),s.asyncDep){if(i&&i.registerDep(s,de,o,a),!e.el){let r=s.subTree=K(Pi);b(null,r,t,n),e.placeholder=r.el}}else de(s,e,t,n,i,a,o)},ue=(e,t,n)=>{let r=t.component=e.component;if($r(e,t,n)){if(r.asyncDep&&!r.asyncResolved){t.el=e.el,t.placeholder=e.placeholder,E(r,t,n);return}r.next=t,r.update()}else t.el=e.el,t.placeholder=e.placeholder,r.vnode=t},de=(e,t,n,r,i,a,o)=>{let s=()=>{if(e.isMounted){let{next:t,bu:n,u:r,parent:s,vnode:c}=e;{let n=Oi(e);if(n){t&&(t.el=c.el,E(e,t,o)),n.asyncDep.then(()=>{B(()=>{e.isUnmounted||l()},i)});return}}let u=t,d;wi(e,!1),t?(t.el=c.el,E(e,t,o)):t=c,n&&le(n),(d=t.props&&t.props.onVnodeBeforeUpdate)&&ea(d,s,t,c),wi(e,!0);let f=Yr(e),p=e.subTree;e.subTree=f,v(p,f,m(p.el),xe(p),e,i,a),t.el=f.el,u===null&&ni(e,f.el),r&&B(r,i),(d=t.props&&t.props.onVnodeUpdated)&&B(()=>ea(d,s,t,c),i)}else{let o,{el:s,props:c}=t,{bm:l,m:u,parent:d,root:f,type:p}=e,m=nr(t);if(wi(e,!1),l&&le(l),!m&&(o=c&&c.onVnodeBeforeMount)&&ea(o,d,t),wi(e,!0),s&&Te){let t=()=>{e.subTree=Yr(e),Te(s,e.subTree,e,i,null)};m&&p.__asyncHydrate?p.__asyncHydrate(s,e,t):t()}else{f.ce&&f.ce._hasShadowRoot()&&f.ce._injectChildStyle(p,e.parent?e.parent.type:void 0);let o=e.subTree=Yr(e);v(null,o,n,r,e,i,a),t.el=o.el}if(u&&B(u,i),!m&&(o=c&&c.onVnodeMounted)){let e=t;B(()=>ea(o,d,e),i)}(t.shapeFlag&256||d&&nr(d.vnode)&&d.vnode.shapeFlag&256)&&e.a&&B(e.a,i),e.isMounted=!0,t=n=r=null}};e.scope.on();let c=e.effect=new Me(s);e.scope.off();let l=e.update=c.run.bind(c),u=e.job=c.runIfDirty.bind(c);u.i=e,u.id=e.uid,c.scheduler=()=>xn(u),wi(e,!0),l()},E=(e,t,n)=>{t.component=e;let r=e.vnode.props;e.vnode=t,e.next=null,si(e,t.props,r,n),bi(e,t.children,n),qe(),wn(e),Je()},pe=(e,t,n,r,i,a,o,s,c=!1)=>{let l=e&&e.children,u=e?e.shapeFlag:0,d=t.children,{patchFlag:f,shapeFlag:m}=t;if(f>0){if(f&128){he(l,d,n,r,i,a,o,s,c);return}if(f&256){me(l,d,n,r,i,a,o,s,c);return}}m&8?(u&16&&be(l,i,a),d!==l&&p(n,d)):u&16?m&16?he(l,d,n,r,i,a,o,s,c):be(l,i,a,!0):(u&8&&p(n,``),m&16&&C(d,n,r,i,a,o,s,c))},me=(e,t,r,i,a,o,s,c,l)=>{e||=n,t||=n;let u=e.length,d=t.length,f=Math.min(u,d),p=0;for(;p<f;p++){let n=t[p]=l?Zi(t[p]):Xi(t[p]);v(e[p],n,r,null,a,o,s,c,l)}u>d?be(e,a,o,!0,!1,f):C(t,r,i,a,o,s,c,l,f)},he=(e,t,r,i,a,o,s,c,l)=>{let u=0,d=t.length,f=e.length-1,p=d-1;for(;u<=f&&u<=p;){let n=e[u],i=t[u]=l?Zi(t[u]):Xi(t[u]);if(Ui(n,i))v(n,i,r,null,a,o,s,c,l);else break;u++}for(;u<=f&&u<=p;){let n=e[f],i=t[p]=l?Zi(t[p]):Xi(t[p]);if(Ui(n,i))v(n,i,r,null,a,o,s,c,l);else break;f--,p--}if(u>f){if(u<=p){let e=p+1,n=e<d?t[e].el:i;for(;u<=p;)v(null,t[u]=l?Zi(t[u]):Xi(t[u]),r,n,a,o,s,c,l),u++}}else if(u>p)for(;u<=f;)D(e[u],a,o,!0),u++;else{let m=u,h=u,g=new Map;for(u=h;u<=p;u++){let e=t[u]=l?Zi(t[u]):Xi(t[u]);e.key!=null&&g.set(e.key,u)}let _,y=0,b=p-h+1,x=!1,ee=0,S=Array(b);for(u=0;u<b;u++)S[u]=0;for(u=m;u<=f;u++){let n=e[u];if(y>=b){D(n,a,o,!0);continue}let i;if(n.key!=null)i=g.get(n.key);else for(_=h;_<=p;_++)if(S[_-h]===0&&Ui(n,t[_])){i=_;break}i===void 0?D(n,a,o,!0):(S[i-h]=u+1,i>=ee?ee=i:x=!0,v(n,t[i],r,null,a,o,s,c,l),y++)}let te=x?Di(S):n;for(_=te.length-1,u=b-1;u>=0;u--){let e=h+u,n=t[e],f=t[e+1],p=e+1<d?f.el||Ai(f):i;S[u]===0?v(null,n,r,p,a,o,s,c,l):x&&(_<0||u!==te[_]?ge(n,r,p,2):_--)}}},ge=(e,t,n,r,i=null)=>{let{el:a,type:c,transition:l,children:u,shapeFlag:d}=e;if(d&6)ge(e.component.subTree,t,n,r);else if(d&128)e.suspense.move(t,n,r);else if(d&64)c.move(e,t,n,Ce);else if(c===V){o(a,t,n);for(let e=0;e<u.length;e++)ge(u[e],t,n,r);o(e.anchor,t,n)}else if(c===Fi)ee(e,t,n);else if(r!==2&&d&1&&l){if(r===0)l.persisted&&!a[Kn]?o(a,t,n):(l.beforeEnter(a),o(a,t,n),B(()=>l.enter(a),i));else{let{leave:r,delayLeave:i,afterLeave:c}=l,u=()=>{e.ctx.isUnmounted?s(a):o(a,t,n)},d=()=>{let e=a._isLeaving||!!a[Kn];a._isLeaving&&a[Kn](!0),l.persisted&&!e?u():r(a,()=>{u(),c&&c()})};i?i(a,u,d):d()}}else o(a,t,n)},D=(e,t,n,r=!1,i=!1)=>{let{type:a,props:o,ref:s,children:c,dynamicChildren:l,shapeFlag:u,patchFlag:d,dirs:f,cacheIndex:p,memo:m}=e;if((d===-2||l&&l.hasOnce)&&(i=!1),s!=null&&(qe(),er(s,null,n,e,!0),Je()),p!=null&&(!e.ctx||e.ctx===t)&&(t.renderCache[p]=void 0),u&256){t.ctx.deactivate(e);return}let h=u&1&&f,g=!nr(e),_;if(g&&(_=o&&o.onVnodeBeforeUnmount)&&ea(_,t,e),u&6)ye(e.component,n,r);else{if(u&128){e.suspense.unmount(n,r);return}h&&Fn(e,null,t,`beforeUnmount`),u&64?e.type.remove(e,t,n,Ce,r):l&&!l.hasOnce&&(a!==V||d>0&&d&64)?be(l,t,n,!1,!0):(a===V&&d&384||!i&&u&16)&&be(c,t,n),r&&_e(e)}let v=m!=null&&p==null;(g&&(_=o&&o.onVnodeUnmounted)||h||v)&&B(()=>{_&&ea(_,t,e),h&&Fn(e,null,t,`unmounted`),v&&(e.el=null)},n)},_e=e=>{let{type:t,el:n,anchor:r,transition:i}=e,a=t===V;if(a&&!i){ve(n,r);return}if(t===Fi){S(e),i&&!i.persisted&&i.afterLeave&&i.afterLeave();return}let o=a?Xn(e):e,c=()=>{a?m(n)&&ve(n,r):s(n),i&&!i.persisted&&i.afterLeave&&i.afterLeave()};if(o&&o.shapeFlag&1&&i&&!i.persisted){let{leave:e,delayLeave:t}=i,n=o.el,r=()=>e(n,c);t?t(n,c,r):r()}else c()},ve=(e,t)=>{let n;for(;e!==t;)n=h(e),s(e),e=n;s(t)},ye=(e,t,n)=>{let{bum:r,scope:i,job:a,subTree:o,um:s,m:c,a:l}=e;ki(c),ki(l),r&&le(r),i.stop(),a?(a.flags|=8,D(o,e,t,n)):e.vnode.el&&o&&(o.transition=e.vnode.transition,D(o,e,t,n)),s&&B(s,t),B(()=>{e.isUnmounted=!0},t)},be=(e,t,n,r=!1,i=!1,a=0)=>{for(let o=a;o<e.length;o++)D(e[o],t,n,r,i)},xe=e=>{if(e.shapeFlag&6)return xe(e.component.subTree);if(e.shapeFlag&128)return e.suspense.next();let t=h(e.anchor||e.el),n=t&&t[Wn];return n?h(n):t},Se=(e,t,n)=>{Dn(()=>{e==null?t._vnode&&D(t._vnode,null,null,!0):v(t._vnode||null,e,t,null,null,null,n),t._vnode=e},e&&t._vnode?void 0:e&&e.component?e.component.uid:ra())},Ce={p:v,um:D,m:ge,r:_e,mt:T,mc:C,pc:pe,pbc:w,n:xe,o:e},we,Te;return i&&([we,Te]=i(Ce)),{render:Se,hydrate:we,createApp:Hr(Se,we)}}function Ci({type:e,props:t},n){return n===`svg`&&e===`foreignObject`||n===`mathml`&&e===`annotation-xml`&&t&&t.encoding&&t.encoding.includes(`html`)?void 0:n}function wi({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Ti(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Ei(e,t,n=!1){let r=e.children,i=t.children;if(d(r)&&d(i))for(let e=0;e<r.length;e++){let t=r[e],a=i[e];a.shapeFlag&1&&!a.dynamicChildren&&((a.patchFlag<=0||a.patchFlag===32)&&(a=i[e]=Zi(i[e]),a.el=t.el),!n&&a.patchFlag!==-2&&Ei(t,a)),a.type===Ni&&(a.patchFlag===-1&&(a=i[e]=Zi(a)),a.el=t.el),a.type===Pi&&!a.el&&(a.el=t.el)}}function Di(e){let t=e.slice(),n=[0],r,i,a,o,s,c=e.length;for(r=0;r<c;r++){let c=e[r];if(c!==0){if(i=n[n.length-1],e[i]<c){t[r]=i,n.push(r);continue}for(a=0,o=n.length-1;a<o;)s=a+o>>1,e[n[s]]<c?a=s+1:o=s;c<e[n[a]]&&(a>0&&(t[r]=n[a-1]),n[a]=r)}}for(a=n.length,o=n[a-1];a-->0;)n[a]=o,o=t[o];return n}function Oi(e){let t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:Oi(t)}function ki(e){if(e)for(let t=0;t<e.length;t++)e[t].flags|=8}function Ai(e){if(e.placeholder)return e.placeholder;let t=e.component;return t?Ai(t.subTree):null}var ji=e=>e.__isSuspense;function Mi(e,t){t&&t.pendingBranch?d(e)?t.effects.push(...e):t.effects.push(e):Cn(e)}var V=Symbol.for(`v-fgt`),Ni=Symbol.for(`v-txt`),Pi=Symbol.for(`v-cmt`),Fi=Symbol.for(`v-stc`),Ii=[],H=null;function U(e=!1){Ii.push(H=e?null:[])}function Li(){Ii.pop(),H=Ii[Ii.length-1]||null}var Ri=1;function zi(e,t=!1){Ri+=e,e<0&&H&&t&&(H.hasOnce=!0)}function Bi(e){return e.dynamicChildren=Ri>0?H||n:null,Li(),Ri>0&&H&&H.push(e),e}function W(e,t,n,r,i,a){return Bi(G(e,t,n,r,i,a,!0))}function Vi(e,t,n,r,i){return Bi(K(e,t,n,r,i,!0))}function Hi(e){return e?e.__v_isVNode===!0:!1}function Ui(e,t){return e.type===t.type&&e.key===t.key}var Wi=({key:e})=>e??null,Gi=({ref:e,ref_key:t,ref_for:n})=>(typeof e==`number`&&(e=``+e),e==null?null:g(e)||N(e)||h(e)?{i:An,r:e,k:t,f:!!n}:e);function G(e,t=null,n=null,r=0,i=null,a=e===V?0:1,o=!1,s=!1){let c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Wi(t),ref:t&&Gi(t),scopeId:jn,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:r,dynamicProps:i,dynamicChildren:null,appContext:null,ctx:An};return s?(Qi(c,n),a&128&&e.normalize(c)):n&&(c.shapeFlag|=g(n)?8:16),Ri>0&&!o&&H&&(c.patchFlag>0||a&6)&&c.patchFlag!==32&&H.push(c),c}var K=Ki;function Ki(e,t=null,n=null,r=0,i=null,a=!1){if((!e||e===br)&&(e=Pi),Hi(e)){let r=Ji(e,t,!0);return n&&Qi(r,n),Ri>0&&!a&&H&&(r.shapeFlag&6?H[H.indexOf(e)]=r:H.push(r)),r.patchFlag=-2,r}if(xa(e)&&(e=e.__vccOpts),t){t=qi(t);let{class:e,style:n}=t;e&&!g(e)&&(t.class=D(e)),v(n)&&(Kt(n)&&!d(n)&&(n=s({},n)),t.style=E(n))}let o=g(e)?1:ji(e)?128:Gn(e)?64:v(e)?4:h(e)?2:0;return G(e,t,n,r,i,o,a,!0)}function qi(e){return e?Kt(e)||ai(e)?s({},e):e:null}function Ji(e,t,n=!1,r=!1){let{props:i,ref:a,patchFlag:o,children:s,transition:c}=e,l=t?$i(i||{},t):i,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&Wi(l),ref:t&&t.ref?n&&a?d(a)?a.concat(Gi(t)):[a,Gi(t)]:Gi(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==V?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Ji(e.ssContent),ssFallback:e.ssFallback&&Ji(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce,cacheIndex:e.cacheIndex};return c&&r&&Yn(u,c.clone(u)),u}function Yi(e=` `,t=0){return K(Ni,null,e,t)}function q(e=``,t=!1){return t?(U(),Vi(Pi,null,e)):K(Pi,null,e)}function Xi(e){return e==null||typeof e==`boolean`?K(Pi):d(e)?K(V,null,e.slice()):Hi(e)?Zi(e):K(Ni,null,String(e))}function Zi(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Ji(e)}function Qi(e,t){let n=0,{shapeFlag:r}=e;if(t==null)t=null;else if(d(t))n=16;else if(typeof t==`object`){if(r&65){let n=t.default;n&&(n._c&&(n._d=!1),Qi(e,n()),n._c&&(n._d=!0));return}{n=32;let r=t._;!r&&!ai(t)?t._ctx=An:r===3&&An&&(An.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}}else if(h(t)){if(r&65){Qi(e,{default:t});return}t={default:t,_ctx:An},n=32}else t=String(t),r&64?(n=16,t=[Yi(t)]):n=8;e.children=t,e.shapeFlag|=n}function $i(...e){let t={};for(let n=0;n<e.length;n++){let r=e[n];for(let e in r)if(e===`class`)t.class!==r.class&&(t.class=D([t.class,r.class]));else if(e===`style`)t.style=E([t.style,r.style]);else if(a(e)){let n=t[e],i=r[e];i&&n!==i&&!(d(n)&&n.includes(i))?t[e]=n?[].concat(n,i):i:i==null&&n==null&&!o(e)&&(t[e]=i)}else e!==``&&(t[e]=r[e])}return t}function ea(e,t,n,r=null){un(e,t,7,[n,r])}var ta=Br(),na=0;function ra(){return na}function ia(e,n,r){let i=e.type,a=(n?n.appContext:e.appContext)||ta,o={uid:na++,vnode:e,type:i,parent:n,appContext:a,root:null,next:null,subTree:null,effect:null,update:null,job:null,scope:new ke(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:n?n.provides:Object.create(a.provides),ids:n?n.ids:[``,0,0],accessCache:null,renderCache:[],components:null,directives:null,propsOptions:di(i,a),emitsOptions:qr(i,a),emit:null,emitted:null,propsDefaults:t,inheritAttrs:i.inheritAttrs,ctx:t,data:t,props:t,attrs:t,slots:t,refs:t,setupState:t,setupContext:null,suspense:r,suspenseId:r?r.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return o.ctx={_:o},o.root=n?n.root:o,o.emit=Gr.bind(null,o),e.ce&&e.ce(o),o}var J=null,aa=()=>J||An,oa,sa;{let e=fe(),t=(t,n)=>{let r;return(r=e[t])||(r=e[t]=[]),r.push(n),e=>{r.length>1?r.forEach(t=>t(e)):r[0](e)}};oa=t(`__VUE_INSTANCE_SETTERS__`,e=>J=e),sa=t(`__VUE_SSR_SETTERS__`,e=>da=e)}var ca=e=>{let t=J;return oa(e),e.scope.on(),()=>{e.scope.off(),oa(t)}},la=()=>{J&&J.scope.off(),oa(null)};function ua(e){return e.vnode.shapeFlag&4}var da=!1;function fa(e,t=!1,n=!1){t&&sa(t);let{props:r,children:i}=e.vnode,a=ua(e);oi(e,r,a,t),yi(e,i,n||t);let o=a?pa(e,t):void 0;return t&&sa(!1),o}function pa(e,t){let n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,wr);let{setup:r}=n;if(r){qe();let n=e.setupContext=r.length>1?ya(e):null,i=ca(e),a=ln(r,e,0,[e.props,n]),o=y(a);if(Je(),i(),(o||e.sp)&&!nr(e)&&Zn(e),o){if(a.then(la,la),t)return a.then(n=>{sa(!0);try{ma(e,n,t)}finally{sa(!1)}}).catch(t=>{dn(t,e,0)});e.asyncDep=a}else ma(e,a,t)}else _a(e,t)}function ma(e,t,n){h(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:v(t)&&(e.setupState=$t(t)),_a(e,n)}var ha,ga;function _a(e,t,n){let i=e.type;if(!e.render){if(!t&&ha&&!i.render){let t=i.template||jr(e).template;if(t){let{isCustomElement:n,compilerOptions:r}=e.appContext.config,{delimiters:a,compilerOptions:o}=i;i.render=ha(t,s(s({isCustomElement:n,delimiters:a},r),o))}}e.render=i.render||r,ga&&ga(e)}{let t=ca(e);qe();try{Dr(e)}finally{Je(),t()}}}var va={get(e,t){return j(e,`get`,``),e[t]}};function ya(e){return{attrs:new Proxy(e.attrs,va),slots:e.slots,emit:e.emit,expose:t=>{e.exposed=t||{}}}}function ba(e){return e.exposed?e.exposeProxy||=new Proxy($t(qt(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Sr)return Sr[n](e)},has(e,t){return t in e||t in Sr}}):e.proxy}function xa(e){return h(e)&&`__vccOpts`in e}var Y=(e,t)=>tn(e,t,da),Sa=`3.5.44`,Ca=void 0,wa=typeof window<`u`&&window.trustedTypes;if(wa)try{Ca=wa.createPolicy(`vue`,{createHTML:e=>e})}catch{}var Ta=Ca?e=>Ca.createHTML(e):e=>e,Ea=`http://www.w3.org/2000/svg`,Da=`http://www.w3.org/1998/Math/MathML`,Oa=typeof document<`u`?document:null,ka=Oa&&Oa.createElement(`template`),Aa={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?Oa.createElementNS(Ea,e):t===`mathml`?Oa.createElementNS(Da,e):n?Oa.createElement(e,{is:n}):Oa.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>Oa.createTextNode(e),createComment:e=>Oa.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Oa.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),i!==a&&(i=i.nextSibling););else{ka.innerHTML=Ta(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=ka.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},ja=Symbol(`_vtc`);function Ma(e,t,n){let r=e[ja];r&&(t=(t?[t,...r]:[...r]).join(` `)),t==null?e.removeAttribute(`class`):n?e.setAttribute(`class`,t):e.className=t}var Na=Symbol(`_vod`),Pa=Symbol(`_vsh`),Fa=Symbol(``),Ia=/(?:^|;)\s*display\s*:/;function La(e,t,n){let r=e.style,i=g(n),a=!1;if(n&&!i){if(t){if(g(t))for(let e of t.split(`;`)){let t=e.slice(0,e.indexOf(`:`)).trim();n[t]??za(r,t,``)}else for(let e in t)n[e]??za(r,e,``)}for(let i in n){i===`display`&&(a=!0);let o=n[i];o==null?za(r,i,``):Ua(e,i,!g(t)&&t?t[i]:void 0,o)||za(r,i,o)}}else if(i){if(t!==n){let e=r[Fa];e&&(n+=`;`+e),r.cssText=n,a=Ia.test(n)}}else t&&e.removeAttribute(`style`);Na in e&&((!i||t!==n)&&(e[Na]=a?r.display:``),e[Pa]&&(r.display=`none`))}var Ra=/\s*!important$/;function za(e,t,n){if(d(n))n.forEach(n=>za(e,t,n));else if(n??=``,t.startsWith(`--`))Ra.test(n)?e.setProperty(t,n.replace(Ra,``),`important`):e.setProperty(t,n);else{let r=Ha(e,t);Ra.test(n)?e.setProperty(w(r),n.replace(Ra,``),`important`):e[r]=n}}var Ba=[`Webkit`,`Moz`,`ms`],Va={};function Ha(e,t){let n=Va[t];if(n)return n;let r=C(t);if(r!==`filter`&&r in e)return Va[t]=r;r=oe(r);for(let n=0;n<Ba.length;n++){let i=Ba[n]+r;if(i in e)return Va[t]=i}return t}function Ua(e,t,n,r){return e.tagName===`TEXTAREA`&&(t===`width`||t===`height`)&&g(r)&&n===r}var Wa=`http://www.w3.org/1999/xlink`;function Ga(e,t,n,r,i,a=ve(t)){r&&t.startsWith(`xlink:`)?n==null?e.removeAttributeNS(Wa,t.slice(6,t.length)):e.setAttributeNS(Wa,t,n):n==null||a&&!ye(n)?e.removeAttribute(t):e.setAttribute(t,a?``:_(n)?String(n):n)}function Ka(e,t,n,r,i){if(t===`innerHTML`||t===`textContent`){n!=null&&(e[t]=t===`innerHTML`?Ta(n):n);return}let a=e.tagName;if(t===`value`&&a!==`PROGRESS`&&!a.includes(`-`)){let r=a===`OPTION`?e.getAttribute(`value`)||``:e.value,i=n==null?e.type===`checkbox`?`on`:``:String(n);(r!==i||!(`_value`in e))&&(e.value=i),n??e.removeAttribute(t),e._value=n;return}let o=!1;if(n===``||n==null){let r=typeof e[t];r===`boolean`?n=ye(n):n==null&&r===`string`?(n=``,o=!0):r===`number`&&(n=0,o=!0)}try{e[t]=n}catch{}o&&e.removeAttribute(i||t)}function qa(e,t,n,r){e.addEventListener(t,n,r)}function Ja(e,t,n,r){e.removeEventListener(t,n,r)}var Ya=Symbol(`_vei`);function Xa(e,t,n,r,i=null){let a=e[Ya]||(e[Ya]={}),o=a[t];if(r&&o)o.value=r;else{let[n,s]=$a(t);r?qa(e,n,a[t]=ro(r,i),s):o&&(Ja(e,n,o,s),a[t]=void 0)}}var Za=/(Once|Passive|Capture)$/,Qa=/^on:?(?:Once|Passive|Capture)$/;function $a(e){let t,n;for(;(n=e.match(Za))&&!Qa.test(e);)t||={},e=e.slice(0,e.length-n[1].length),t[n[1].toLowerCase()]=!0;return[e[2]===`:`?e.slice(3):w(e.slice(2)),t]}var eo=0,to=Promise.resolve(),no=()=>eo||=(to.then(()=>eo=0),Date.now());function ro(e,t){let n=e=>{if(!e._vts)e._vts=Date.now();else if(e._vts<=n.attached)return;let r=n.value;if(d(r)){let n=e.stopImmediatePropagation;e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0};let i=r.slice(),a=[e];for(let n=0;n<i.length&&!e._stopped;n++){let e=i[n];e&&un(e,t,5,a)}}else un(r,t,5,[e])};return n.value=e,n.attached=no(),n}var io=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,ao=(e,t,n,r,i,s)=>{let c=i===`svg`;t===`class`?Ma(e,r,c):t===`style`?La(e,n,r):a(t)?o(t)||Xa(e,t,n,r,s):(t[0]===`.`?(t=t.slice(1),1):t[0]===`^`?(t=t.slice(1),0):oo(e,t,r,c))?(Ka(e,t,r),!e.tagName.includes(`-`)&&(t===`value`||t===`checked`||t===`selected`)&&Ga(e,t,r,c,s,t!==`value`)):e._isVueCE&&(so(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!g(r)))?Ka(e,C(t),r,s,t):(t===`true-value`?e._trueValue=r:t===`false-value`&&(e._falseValue=r),Ga(e,t,r,c))};function oo(e,t,n,r){if(r)return!!(t===`innerHTML`||t===`textContent`||t in e&&io(t)&&h(n));if(t===`spellcheck`||t===`draggable`||t===`translate`||t===`autocorrect`||t===`sandbox`&&e.tagName===`IFRAME`||t===`form`||t===`list`&&e.tagName===`INPUT`||t===`type`&&e.tagName===`TEXTAREA`)return!1;if(t===`width`||t===`height`){let t=e.tagName;if(t===`IMG`||t===`VIDEO`||t===`CANVAS`||t===`SOURCE`)return!1}return io(t)&&g(n)?!1:t in e}function so(e,t){let n=e._def.props;if(!n)return!1;let r=C(t);return Array.isArray(n)?n.some(e=>C(e)===r):Object.keys(n).some(e=>C(e)===r)}var co=e=>{let t=e.props[`onUpdate:modelValue`]||!1;return d(t)?e=>le(t,e):t};function lo(e){e.target.composing=!0}function uo(e){let t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event(`input`)))}var fo=Symbol(`_assign`),po=Symbol(`_initialValue`);function mo(e,t,n){return t&&(e=e.trim()),n&&(e=ue(e)),e}var ho={created(e,{modifiers:{lazy:t,trim:n,number:r}},i){e.parentNode&&(e.type===`text`?e[po]=e.defaultValue.replace(/[\r\n]/g,``):e.type===`textarea`&&(e[po]=e.defaultValue.replace(/\r\n?/g,`
+`))),e[fo]=co(i);let a=r||i.props&&i.props.type===`number`;qa(e,t?`change`:`input`,t=>{t.target.composing||e[fo](mo(e.value,n,a))}),(n||a)&&qa(e,`change`,()=>{e.value=mo(e.value,n,a)}),t||(qa(e,`compositionstart`,lo),qa(e,`compositionend`,uo),qa(e,`change`,uo))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[po];delete e[po],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[fo](mo(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[fo]=co(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?ue(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},go={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,qa(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?ue(yo(e)):yo(e)),r=e.multiple,i=r?p(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?d(i)?t.slice():t:i];try{e[fo](i)}finally{yn(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[fo]=co(r)},mounted(e,{value:t}){vo(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[fo]=co(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!_o(t,n[1],n[0]))&&vo(e,t)}};function _o(e,t,n){if(!n||d(e))return we(e,t);if(p(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function vo(e,t){let n=e.multiple,r=d(t);if(!n||r||p(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=yo(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Te(t,o)>-1}else a.selected=t.has(o)}else if(we(yo(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function yo(e){return`_value`in e?e._value:e.value}var bo=[`ctrl`,`shift`,`alt`,`meta`],xo={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>bo.some(n=>e[`${n}Key`]&&!t.includes(n))},So=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=xo[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Co={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},wo=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=w(n.key);if(t.some(e=>e===r||Co[e]===r))return e(n)}))},To=s({patchProp:ao},Aa),Eo;function Do(){return Eo||=xi(To)}var Oo=((...e)=>{let t=Do().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Ao(e);if(!r)return;let i=t._component;!h(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,ko(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t});function ko(e){if(e instanceof SVGElement)return`svg`;if(typeof MathMLElement==`function`&&e instanceof MathMLElement)return`mathml`}function Ao(e){return g(e)?document.querySelector(e):e}function X(e){return e.schema?`${e.schema}.${e.name}`:e.name}var jo={table:20,column:20,group:10,enum:10};function Mo(e,t){let n=t.trim().toLowerCase();if(n.length===0)return[];let r=[],i=[];for(let t of e.tables){let e=X(t);t.name.toLowerCase().includes(n)&&r.push({kind:`table`,label:t.name,context:e,tableKey:e});for(let r of t.columns)r.name.toLowerCase().includes(n)&&i.push({kind:`column`,label:r.name,context:e,tableKey:e})}let a=e.groups.filter(e=>e.name.toLowerCase().includes(n)).map(t=>({kind:`group`,label:t.name,context:`${e.tables.filter(e=>e.groupId===t.id).length} tables`,tableKey:null})),o=e.enums.filter(e=>e.name.toLowerCase().includes(n)).map(e=>({kind:`enum`,label:e.name,context:`${e.values.length} values`,tableKey:null}));return[...r.slice(0,jo.table),...i.slice(0,jo.column),...a.slice(0,jo.group),...o.slice(0,jo.enum)]}var No={class:`w-full max-w-lg overflow-hidden rounded-md border border-border bg-background shadow-lg`},Po=[`placeholder`],Fo={class:`max-h-80 overflow-y-auto`},Io={key:0,class:`px-3 py-4 text-center text-xs text-muted-foreground`},Lo=[`disabled`,`onClick`],Ro={class:`w-14 shrink-0 text-[10px] uppercase text-muted-foreground`},zo={class:`font-mono text-foreground`},Bo={class:`truncate text-[11px] text-muted-foreground`},Vo=L({__name:`DocsSearch`,props:{snapshot:{},translate:{type:Function}},emits:[`select`,`selectEnum`],setup(e,{emit:t}){let n=e,r=t,i=P(!1),a=P(``),o=P(null),s=Y(()=>Mo(n.snapshot,a.value));async function c(){i.value=!0,a.value=``,await yn(),o.value?.focus()}function l(e){(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`?(e.preventDefault(),i.value?i.value=!1:c()):e.key===`Escape`&&i.value&&(i.value=!1)}function u(e){return e.kind===`enum`||e.tableKey!==null}function d(e){e.kind===`enum`?(r(`selectEnum`,e.label),i.value=!1):e.tableKey!==null&&(r(`select`,e.tableKey),i.value=!1)}return dr(()=>window.addEventListener(`keydown`,l)),mr(()=>window.removeEventListener(`keydown`,l)),(t,n)=>(U(),W(`div`,null,[G(`button`,{type:`button`,class:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[0]||=e=>c()},[G(`span`,null,O(e.translate(`docs.searchLabel`)),1),n[3]||=G(`span`,{class:`rounded bg-muted/50 px-1 py-0.5 text-[10px]`},`⌘K`,-1)]),i.value?(U(),W(`div`,{key:0,class:`fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-24`,onClick:n[2]||=So(e=>i.value=!1,[`self`])},[G(`div`,No,[Pn(G(`input`,{ref_key:`input`,ref:o,"onUpdate:modelValue":n[1]||=e=>a.value=e,type:`text`,placeholder:e.translate(`docs.search`),class:`w-full border-b border-border bg-transparent px-3 py-2 text-sm text-foreground outline-none`},null,8,Po),[[ho,a.value]]),G(`ul`,Fo,[a.value.trim()!==``&&s.value.length===0?(U(),W(`li`,Io,`Nothing matches “`+O(a.value)+`”.`,1)):q(``,!0),(U(!0),W(V,null,R(s.value,(e,t)=>(U(),W(`li`,{key:`${e.kind}-${e.context}-${e.label}-${t}`},[G(`button`,{type:`button`,class:D([`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-xs transition-colors`,u(e)?`hover:bg-muted/40`:`cursor-default text-muted-foreground`]),disabled:!u(e),onClick:t=>d(e)},[G(`span`,Ro,O(e.kind),1),G(`span`,zo,O(e.label),1),G(`span`,Bo,O(e.context),1)],10,Lo)]))),128))])])])):q(``,!0)]))}});function Ho(e){if(e===null)return{};let t=(Math.trunc(e)%360+360)%360;return{"--h":String(t)}}var Uo={class:`flex w-64 shrink-0 flex-col gap-3 overflow-y-auto border-r border-border bg-background p-3`},Wo={class:`flex flex-col gap-1`},Go={class:`px-2 text-[10px] uppercase tracking-wide text-muted-foreground`},Ko={class:`flex rounded border border-border p-0.5`},qo={key:0,class:`h-2 w-2 shrink-0 rounded-full`,style:{"background-color":`var(--group-c)`}},Jo={class:`truncate text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`},Yo=[`onClick`],Xo=L({__name:`DocsSidebar`,props:{sections:{},mode:{},activeKey:{},translate:{type:Function}},emits:[`update:mode`,`select`,`home`],setup(e,{emit:t}){let n=t;return(t,r)=>(U(),W(`nav`,Uo,[G(`button`,{type:`button`,class:`rounded px-2 py-1 text-left text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/40`,onClick:r[0]||=e=>n(`home`)},O(e.translate(`docs.overview`)),1),G(`div`,Wo,[G(`span`,Go,O(e.translate(`docs.groupBy`)),1),G(`div`,Ko,[G(`button`,{type:`button`,class:D([`flex-1 rounded px-2 py-1 text-xs transition-colors`,e.mode===`schema`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:r[1]||=e=>n(`update:mode`,`schema`)},O(e.translate(`docs.groupBySchema`)),3),G(`button`,{type:`button`,class:D([`flex-1 rounded px-2 py-1 text-xs transition-colors`,e.mode===`group`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:r[2]||=e=>n(`update:mode`,`group`)},O(e.translate(`docs.groupByTableGroup`)),3)])]),(U(!0),W(V,null,R(e.sections,t=>(U(),W(`div`,{key:t.key,class:`flex flex-col gap-0.5`},[G(`div`,{class:D([`flex items-center gap-1.5 px-2 py-1`,{"docs-group":t.hue!==null}]),style:E(F(Ho)(t.hue))},[t.hue===null?q(``,!0):(U(),W(`span`,qo)),G(`span`,Jo,O(t.label||e.translate(t.fallbackKey)),1)],6),(U(!0),W(V,null,R(t.tables,t=>(U(),W(`button`,{key:F(X)(t),type:`button`,class:D([`truncate rounded px-2 py-1 text-left font-mono text-xs transition-colors`,e.activeKey===F(X)(t)?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:e=>n(`select`,F(X)(t))},O(t.name),11,Yo))),128))]))),128))]))}});function Zo(e,t){return e.name.localeCompare(t.name)}function Qo(e){let t=new Map;for(let n of e.tables){let e=n.schema??``,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({key:e,label:e,fallbackKey:`docs.noSchema`,hue:null,note:null,tables:[...t].sort(Zo)}))}function $o(e){let t=new Map(e.groups.map(e=>[e.id,e])),n=[];for(let t of e.groups){let r=e.tables.filter(e=>e.groupId===t.id).sort(Zo);r.length!==0&&n.push({key:t.id,label:t.name,fallbackKey:`docs.noGroup`,hue:t.hue,note:t.note,tables:r})}let r=e.tables.filter(e=>e.groupId===null||!t.has(e.groupId)).sort(Zo);return r.length>0&&n.push({key:``,label:``,fallbackKey:`docs.noGroup`,hue:null,note:null,tables:r}),n}function es(e,t){let n=[];for(let r of e.tables)for(let e of r.columns)e.data_type===t&&n.push({tableKey:X(r),table:r.name,column:e.name});return n}function ts(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ns=ts();function rs(e){ns=e}var is={exec:()=>null};function as(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Z(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Q.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var os=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Q={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:as(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:as(e=>RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:as(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:as(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:as(e=>RegExp(`^ {0,${e}}(?:</?(?:${xs})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,`i`)),blockquoteBeginRegex:as(e=>RegExp(`^ {0,${e}}>`))},ss=/^(?:[ \t]*(?:\n|$))+/,cs=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ls=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,us=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ds=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,fs=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ps=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ms=Z(ps).replace(/bull/g,fs).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),hs=Z(ps).replace(/bull/g,fs).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),gs=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,_s=/^[^\n]+/,vs=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ys=Z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,vs).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),bs=Z(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,fs).getRegex(),xs=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,Ss=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Cs=Z(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,Ss).replace(`tag`,xs).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ws=e=>Z(gs).replace(`hr`,us).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,xs).getRegex(),Ts=ws(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Es=ws(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ds={blockquote:Z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Es).getRegex(),code:cs,def:ys,fences:ls,heading:ds,hr:us,html:Cs,lheading:ms,list:bs,newline:ss,paragraph:Ts,table:is,text:_s},Os=Z(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,us).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,xs).getRegex(),ks={...Ds,lheading:hs,table:Os,paragraph:Z(gs).replace(`hr`,us).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Os).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,xs).getRegex()},As={...Ds,html:Z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Ss).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:is,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Z(gs).replace(`hr`,us).replace(`heading`,` *#{1,6} *[^
+]`).replace(`lheading`,ms).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},js=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ms=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ns=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Ps=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Fs=/[\p{P}\p{S}]/u,Is=/[\s\p{P}\p{S}]/u,Ls=/[^\s\p{P}\p{S}]/u,Rs=Z(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Is).getRegex(),zs=/[\p{Pi}\p{Ps}"']/u,Bs=/(?!~)[\p{P}\p{S}]/u,Vs=/(?!~)[\s\p{P}\p{S}]/u,Hs=/(?:[^\s\p{P}\p{S}]|~)/u,Us=Z(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,os?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Ws=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Gs=Z(Ws,`u`).replace(/punct/g,Fs).getRegex(),Ks=Z(Ws,`u`).replace(/punct/g,Bs).getRegex(),qs=Z(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,zs).replace(/punct/g,Fs).getRegex(),Js=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Ys=Z(Js,`gu`).replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,Is).replace(/punct/g,Fs).getRegex(),Xs=Z(Js,`gu`).replace(/notPunctSpace/g,Hs).replace(/punctSpace/g,Vs).replace(/punct/g,Bs).getRegex(),Zs=Z(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,Is).replace(/punct/g,Fs).getRegex(),Qs=Z(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,Is).replace(/punct/g,Fs).getRegex(),$s=Z(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,Is).replace(/punct/g,Fs).getRegex(),ec=Z(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Fs).getRegex(),tc=Z(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,Is).replace(/punct/g,Fs).getRegex(),nc=Z(/\\(punct)/,`gu`).replace(/punct/g,Fs).getRegex(),rc=Z(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,`gu`).replace(/punct/g,Fs).getRegex(),ic=Z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ac=Z(Ss).replace(`(?:-->|$)`,`-->`).getRegex(),oc=Z(`^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,ac).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),sc=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,cc=Z(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace(`brackets`,sc).getRegex(),lc=Z(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace(`label`,cc).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),uc=Z(/^!?\[(label)\]\[(ref)\]/).replace(`label`,cc).replace(`ref`,vs).getRegex(),dc=Z(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,vs).getRegex(),fc=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,pc=Z(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace(`brackets`,sc).getRegex(),mc=Z(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Z(/^!?\[(label)\]\[(ref)\]/).replace(`label`,pc).replace(`ref`,fc).getRegex()).replace(`nolink`,Z(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,fc).getRegex()).getRegex(),hc=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,gc=Z(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_c={_backpedal:is,anyPunctuation:nc,anyPunctuationOutsideCode:rc,autolink:ic,blockSkip:Us,br:Ns,code:Ms,del:is,delLDelim:is,delRDelim:is,emStrongLDelim:Gs,emStrongRDelimAst:Ys,emStrongRDelimUnd:Qs,escape:js,link:lc,nolink:dc,punctuation:Rs,reflink:uc,reflinkSearch:mc,tag:oc,text:Ps,url:is},vc={..._c,emStrongLDelim:qs,emStrongRDelimAst:Zs,emStrongRDelimUnd:$s,link:Z(/^!?\[(label)\]\((.*?)\)/).replace(`label`,cc).getRegex(),reflink:Z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,cc).getRegex()},yc={..._c,emStrongRDelimAst:Xs,emStrongLDelim:Ks,delLDelim:ec,delRDelim:tc,url:Z(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`emailProtocol`,gc).replace(`protocol`,hc).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Z(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace(`protocol`,hc).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},bc={...yc,br:Z(Ns).replace(`{2,}`,`*`).getRegex(),text:Z(yc.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},xc={normal:Ds,gfm:ks,pedantic:As},Sc={normal:_c,gfm:yc,breaks:bc,pedantic:vc},Cc={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},wc=e=>Cc[e];function Tc(e,t){if(t){if(Q.escapeTest.test(e))return e.replace(Q.escapeReplace,wc)}else if(Q.escapeTestNoEncode.test(e))return e.replace(Q.escapeReplaceNoEncode,wc);return e}function Ec(e){return Q.numericCharacterReference.test(e)?e.replace(Q.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return`&amp;`;let r=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return r===0||r>1114111||r>=55296&&r<=57343?`�`:r===38?`&amp;`:String.fromCodePoint(r)}):e}function Dc(e){try{e=encodeURI(e).replace(Q.percentDecode,`%`)}catch{return null}return e}function Oc(e,t){let n=e.replace(Q.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Q.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(Q.slashPipe,`|`);return n}function kc(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Ac(e){let t=e.split(`
`),n=t.length-1;for(;n>=0&&Q.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
-`)}function ac(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function oc(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function sc(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function cc(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
-`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
-`)}var lc=class{options;rules;lexer;constructor(e){this.options=e||Ho}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:ic(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=cc(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=rc(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:rc(t[0],`
-`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:rc(t[0],`
-`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=rc(t[0],`
+`)}function jc(e){return e.trim().toLowerCase().toUpperCase().toLowerCase()}function Mc(e,t){if(e.indexOf(t[0])===-1&&e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Nc(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Pc(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`),c=e[0].charAt(0)===`!`,l=r.state.inLink,u=r.state.linkEmitted,d=r.state.inRawBlock;r.state.inLink=!0,r.state.linkEmitted=!1;let f=r.inlineTokens(s),p=r.state.linkEmitted;if(r.state.linkEmitted=u,r.state.inLink=l,!c){if(p){r.state.inRawBlock=d;return}r.state.linkEmitted=!0}return{type:c?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:f}}function Fc(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
+`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return e.slice(Math.min(r.length,i.length))}).join(`
+`)}function Ic(e,t,n,r){if(!t.includes(`<`))return!1;for(let i=0;i<t.length;i++){if(t[i]===`\\`){i++;continue}if(t[i]==="`"){let e=r.inline.code.exec(t.slice(i));if(e){i+=e[0].length-1;continue}}if(t[i]!==`<`)continue;let a=e.slice(n+i),o=r.inline.tag.exec(a)||r.inline.autolink.exec(a);if(o){if(o[0].length>t.length-i)return!0;i+=o[0].length-1}}return!1}var Lc=class{options;rules;lexer;constructor(e){this.options=e||ns}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:Ac(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Fc(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=kc(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceTabChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:kc(t[0],`
+`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:kc(t[0],`
+`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=kc(t[0],`
`).split(`
-`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
+`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o=0;for(;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
$1`).replace(this.rules.other.blockquoteSetextReplace2,``);n=n?`${n}
${s}`:s,r=r?`${r}
-${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,e.length===0)break;let u=i.at(-1);if(u?.type===`code`)break;if(u?.type===`blockquote`){let t=u,a=t.raw+`
-`+e.join(`
-`),o=this.blockquote(a);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,r=r.substring(0,r.length-t.text.length)+o.text;break}if(u?.type===`list`){let t=u,a=t.raw+`
+${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,e.length===0)break;let u=i.at(-1);if(u?.type===`code`||u?.type===`heading`||u?.type===`hr`||u?.type===`html`)break;if(u?.type===`blockquote`){let t=u,a=e.join(`
+`),o=t.raw+`
+`+a.replace(this.rules.other.blockquoteSetextReplace2,``),s=this.blockquote(o);i[i.length-1]=s;let c=o.substring(s.raw.length).replace(/^\n/,``),l=c?c.split(`
+`).length:0,d=l?e.slice(0,-l):e;d.length>0&&(n=`${n}
+${d.join(`
+`)}`),r=r.substring(0,r.length-t.text.length)+s.text;break}if(u?.type===`list`){let t=u,a=t.raw+`
`+e.join(`
`),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
-`);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=oc(t[2].split(`
-`,1)[0],t[1].length),l=e.split(`
-`,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
-`,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
-`,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
-`+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
-`+l}u=!l.trim(),r+=p+`
-`,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=ic(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:rc(t[0],`
-`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=nc(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
-`):[],a={type:`table`,raw:rc(t[0],`
-`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(nc(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:rc(t[0],`
+`)}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=e,r=()=>n.length-e.length,i=t[1].trim(),a=i.length>1,o={type:`list`,raw:``,ordered:a,start:a?+i.slice(0,-1):``,loose:!1,items:[]};i=a?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=a?i:`[*+-]`);let s=this.rules.other.listItemRegex(i),c=!1;for(;e;){let i=!1,a=``;if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;let l=r();e=e.substring(t[0].length);let u=t[2].split(`
+`,1)[0],d=t[1].length,f=this.options.pedantic?Nc(u,d):u.replace(this.rules.other.leadingSpaceTab,e=>Nc(e,d)),p=e.split(`
+`,1)[0],m=!f.trim(),h=0;if(this.options.pedantic?(h=2,a=f.trimStart()):m?h=d+1:(h=f.search(this.rules.other.nonSpaceChar),h=h>4?1:h,a=f.slice(h),h+=d),m&&this.rules.other.blankLine.test(p)&&(e=e.substring(p.length+1),i=!0),!i){let t=this.rules.other.nextBulletRegex(h),n=this.rules.other.hrRegex(h),r=this.rules.other.fencesBeginRegex(h),i=this.rules.other.headingBeginRegex(h),o=this.rules.other.htmlBeginRegex(h),s=this.rules.other.blockquoteBeginRegex(h);for(;e;){let c=e.split(`
+`,1)[0],l;if(p=c,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting,` `),l=p):l=p.replace(this.rules.other.leadingSpaceTab,e=>Nc(e)),r.test(p)||i.test(p)||o.test(p)||s.test(p)||t.test(p)||n.test(p))break;if(l.search(this.rules.other.nonSpaceChar)>=h||!p.trim())a+=`
+`+l.slice(h);else{if(m||f.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||r.test(f)||i.test(f)||n.test(f))break;a+=`
+`+p}m=!p.trim(),e=e.substring(c.length+1),f=l.slice(h)}}let g=n.slice(l,r());o.loose||(c?o.loose=!0:this.rules.other.doubleBlankLine.test(g)&&(c=!0)),o.items.push({type:`list_item`,raw:g,task:!!this.options.gfm&&this.rules.other.listIsTask.test(a),loose:!1,text:a,tokens:[]})}let l=o.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;o.raw=n.slice(0,r()).trimEnd();for(let e of o.items)if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),!o.loose){let t=e.tokens.filter(e=>e.type===`space`);o.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}for(let e of o.items){let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,o.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1}if(o.loose)for(let e of o.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=Ac(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&Mc(t[2],`()`)!==-1)return;let e=jc(t[1]).replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:kc(t[0],`
+`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Oc(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
+`):[],a={type:`table`,raw:kc(t[0],`
+`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(Oc(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:kc(t[0],`
`),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
-`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=rc(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=ac(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),sc(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return sc(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},uc=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Ho,this.options.tokenizer=this.options.tokenizer||new lc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:Q,block:Xs.normal,inline:Zs.normal};this.options.pedantic?(t.block=Xs.pedantic,t.inline=Zs.pedantic):this.options.gfm&&(t.block=Xs.gfm,t.inline=this.options.breaks?Zs.breaks:Zs.gfm),this.tokenizer.rules=t}static get rules(){return{block:Xs,inline:Zs}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Q.carriageReturn,`
+`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)===`!`?2:1;if(!this.options.pedantic&&Ic(e,t[1],n,this.rules))return;let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let e=kc(r.slice(0,-1),`\\`);if((r.length-e.length)%2==0)return}else{let e=Mc(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let i=t[2],a=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(i);e&&(i=e[1],a=e[3])}else a=t[3]?t[3].slice(1,-1):``;return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(i=this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i.slice(1):i.slice(1,-1)),Pc(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,`$1`),title:a&&a.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=n[0].charAt(0)===`!`?2:1;if(!this.options.pedantic&&Ic(e,n[1],r,this.rules))return;let i=t[jc((n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `))];if(!i){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Pc(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,a,o,s=i,c=0,l=r[0][0],u=n===l,d=l===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){s+=o;continue}if(r[5]||r[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let t=[...r[0]][0].length,n=e.slice(0,i+r.index+t+o);if(Math.min(i,o)%2){let e=n.slice(1,-1);return{type:`em`,raw:n,text:e,tokens:this.lexer.inlineTokens(e)}}let l=n.slice(2,-2);return{type:`strong`,raw:n,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,autolink:!0,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,autolink:!0,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:e?t[0]:Ec(t[0]),escaped:e}}}},Rc=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ns,this.options.tokenizer=this.options.tokenizer||new Lc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:Q,block:xc.normal,inline:Sc.normal};this.options.pedantic?(t.block=xc.pedantic,t.inline=Sc.pedantic):this.options.gfm&&(t.block=xc.gfm,t.inline=this.options.breaks?Sc.breaks:Sc.gfm),this.tokenizer.rules=t}static get rules(){return{block:xc,inline:Sc}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Q.carriageReturn,`
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Q.tabCharGlobal,` `).replace(Q.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
`)?``:`
`)+i.raw,n.text+=`
-`+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
+`+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if((i=this.tokenizer.fences(e))||(i=this.tokenizer.heading(e))||(i=this.tokenizer.hr(e))||(i=this.tokenizer.blockquote(e))||(i=this.tokenizer.list(e))||(i=this.tokenizer.html(e))){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
`)?``:`
`)+i.raw,n.text+=`
-`+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(`
+`+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if((i=this.tokenizer.table(e))||(i=this.tokenizer.lheading(e))){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(`
`)?``:`
`)+i.raw,r.text+=`
-`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
+`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length)}else if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
`)?``:`
`)+i.raw,n.text+=`
-`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},dc=class{options;parser;constructor(e){this.options=e||Ho}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Q.notSpaceStart)?.[0],i=e.replace(Q.endingNewline,``)+`
-`;return r?`<pre><code class="language-`+ec(r)+`">`+(n?i:ec(i,!0))+`</code></pre>
-`:`<pre><code>`+(n?i:ec(i,!0))+`</code></pre>
+`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i)}else if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes(`[`))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!==`!`)return!0;for(let t of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let e=t[0],n=e.lastIndexOf(`[`);if(e.charAt(0)!==`!`&&Object.hasOwn(this.tokens.links,jc(e.slice(n+1,-1)))&&!(n>1&&this.linkInText(e.slice(1,n-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(`)`);try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e;if(this.tokens.links&&e.includes(`[`)){let e=this.tokenizer.rules.inline.reflinkSearch,t=n=>{let r=n.lastIndexOf(`[`);if(!Object.hasOwn(this.tokens.links,jc(n.slice(r+1,-1))))return n;if(r>1&&n.charAt(0)!==`!`){let i=n.slice(1,r-1);if(this.linkInText(i))return`[`+i.replace(e,t)+`][`+`a`.repeat(n.length-r-2)+`]`}return`[`+`a`.repeat(n.length-2)+`]`};n=n.replace(e,t)}n=n.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(e,t,n)=>n?`+`.repeat(e.length):t?t+e.slice(t.length,-t.length).replace(/`/g,`+`)+t:e),n=n.replace(this.tokenizer.rules.inline.blockSkip,(e,t,n)=>{let r=n?n.length:0;return e.slice(0,r)+`[`+`a`.repeat(e.length-r-2)+`]`}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let r=!1,i=``,a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(i=``),r=!1;let o;if(this.options.extensions?.inline?.some(n=>(o=n.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if((o=this.tokenizer.escape(e))||(o=this.tokenizer.tag(e))||(o=this.tokenizer.link(e))){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let n=t.at(-1);o.type===`text`&&n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if((o=this.tokenizer.emStrong(e,n,i))||(o=this.tokenizer.codespan(e))||(o=this.tokenizer.br(e))||(o=this.tokenizer.del(e,n,i))||(o=this.tokenizer.autolink(e))||!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(o=this.tokenizer.inlineText(s)){e=e.substring(o.raw.length),o.raw.slice(-1)!==`_`&&(i=o.raw.slice(-1)),r=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o)}else if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},zc=class{options;parser;constructor(e){this.options=e||ns}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Q.notSpaceStart)?.[0],i=e?e.replace(Q.endingNewline,``)+`
+`:``;return r?`<pre><code class="language-`+Tc(r)+`">`+(n?i:Tc(i,!0))+`</code></pre>
+`:`<pre><code>`+(n?i:Tc(i,!0))+`</code></pre>
`}blockquote({tokens:e}){return`<blockquote>
${this.parser.parse(e)}</blockquote>
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -60,5 +62,5 @@ ${this.parser.parse(e)}</blockquote>
`}tablerow({text:e}){return`<tr>
${e}</tr>
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
-`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${ec(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=tc(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+ec(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=tc(e);if(i===null)return ec(n);e=i;let a=`<img src="${e}" alt="${ec(n)}"`;return t&&(a+=` title="${ec(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:ec(e.text)}},fc=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},pc=class e{options;renderer;textRenderer;constructor(e){this.options=e||Ho,this.options.renderer=this.options.renderer||new dc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new fc}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},mc=class{options;block;constructor(e){this.options=e||Ho}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?uc.lex:uc.lexInline}provideParser(e=this.block){return e?pc.parse:pc.parseInline}},hc=class{defaults=Vo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=pc;Renderer=dc;TextRenderer=fc;Lexer=uc;Tokenizer=lc;Hooks=mc;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new dc(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new lc(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new mc;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=mc.passThroughHooks.has(n)?e=>{if(this.defaults.async&&mc.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return uc.lex(e,t??this.defaults)}parser(e,t){return pc.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?uc.lex:uc.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?pc.parse:pc.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?uc.lex:uc.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?pc.parse:pc.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
-Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+ec(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},gc=new hc;function $(e,t){return gc.parse(e,t)}$.options=$.setOptions=function(e){return gc.setOptions(e),$.defaults=gc.defaults,Uo($.defaults),$},$.getDefaults=Vo,$.defaults=Ho,$.use=function(...e){return gc.use(...e),$.defaults=gc.defaults,Uo($.defaults),$},$.walkTokens=function(e,t){return gc.walkTokens(e,t)},$.parseInline=gc.parseInline,$.Parser=pc,$.parser=pc.parse,$.Renderer=dc,$.TextRenderer=fc,$.Lexer=uc,$.lexer=uc.lex,$.Tokenizer=lc,$.Hooks=mc,$.parse=$,$.options,$.setOptions,$.use,$.walkTokens,$.parseInline,pc.parse,uc.lex;function _c(e){return String(e??``).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}var vc=/^(https?:|mailto:)/i;function yc(e){let t=String(e??``).trim();return t===``||/^[/\\]{2}/.test(t)?null:t.startsWith(`#`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)||vc.test(t)?t:null}var bc=new hc({renderer:{html({text:e}){return _c(e)},link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=yc(e);if(i===null)return r;let a=t?` title="${_c(t)}"`:``;return`<a href="${_c(i)}"${a}>${r}</a>`},image({href:e,title:t,text:n}){let r=yc(e);if(r===null)return _c(n);let i=t?` title="${_c(t)}"`:``;return`<img src="${_c(r)}" alt="${_c(n)}"${i}>`}}});function xc(e){return e===null||e.trim()===``?``:bc.parse(e)}var Sc={class:`text-sm text-muted-foreground`},Cc=[`title`,`innerHTML`],wc=L({__name:`NoteEditor`,props:{modelValue:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=P(!1),a=P(``),o=P(null);async function s(){n.readonly||(a.value=n.modelValue,i.value=!0,await hn(),o.value?.focus())}function c(){i.value=!1,a.value!==n.modelValue&&r(`update:modelValue`,a.value)}function l(){a.value=n.modelValue,i.value=!1}return(t,n)=>(U(),W(`div`,Sc,[i.value?On((U(),W(`textarea`,{key:0,ref_key:`input`,ref:o,"onUpdate:modelValue":n[0]||=e=>a.value=e,rows:`4`,class:`w-full resize-y rounded border border-border bg-background p-2 font-mono text-xs text-foreground outline-none focus:border-ring`,onBlur:n[1]||=e=>c(),onKeydown:n[2]||=lo(e=>l(),[`escape`])},null,544)),[[to,a.value]]):e.modelValue.trim()===``?e.readonly?q(``,!0):(U(),W(`button`,{key:2,type:`button`,class:`rounded border border-dashed border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[4]||=e=>s()},O(e.translate(`docs.addNote`)),1)):(U(),W(`div`,{key:1,class:D([`leading-relaxed`,e.readonly?``:`cursor-text rounded transition-colors hover:bg-muted/30`]),title:e.readonly?void 0:e.translate(`docs.editNote`),onClick:n[3]||=e=>s(),innerHTML:F(xc)(e.modelValue)},null,10,Cc))]))}}),Tc={class:`flex flex-col gap-5`},Ec={class:`flex flex-col gap-2`},Dc={class:`flex flex-wrap items-center gap-2`},Oc={class:`font-mono text-lg font-semibold text-foreground`},kc={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},Ac={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},jc={class:`flex flex-wrap gap-1`},Mc={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Nc={key:0,class:`text-xs text-muted-foreground`},Pc={key:1,class:`flex flex-col gap-1`},Fc=[`onClick`],Ic=L({__name:`EnumPage`,props:{enumType:{},snapshot:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.enumType.schema?`${n.enumType.schema}.${n.enumType.name}`:n.enumType.name),a=Y(()=>Bo(n.snapshot,n.enumType.name));return(t,n)=>(U(),W(`article`,Tc,[G(`header`,Ec,[G(`div`,Dc,[G(`h2`,Oc,O(i.value),1),e.enumType.synthesized?(U(),W(`span`,kc,`synthesized`)):q(``,!0)]),K(wc,{"model-value":e.enumType.note??``,readonly:``,translate:e.translate},null,8,[`model-value`,`translate`])]),G(`section`,null,[G(`h3`,Ac,O(e.translate(`docs.enumValues`)),1),G(`ul`,jc,[(U(!0),W(V,null,R(e.enumType.values,e=>(U(),W(`li`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground`},O(e),1))),128))])]),G(`section`,null,[G(`h3`,Mc,O(e.translate(`docs.usedBy`)),1),a.value.length===0?(U(),W(`p`,Nc,`No column uses this enum.`)):(U(),W(`ul`,Pc,[(U(!0),W(V,null,R(a.value,e=>(U(),W(`li`,{key:`${e.tableKey}.${e.column}`,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left font-mono transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,e.tableKey)},O(e.tableKey)+`.`+O(e.column),9,Fc)]))),128))]))])]))}}),Lc={class:`flex flex-col gap-3`},Rc={class:`flex flex-col gap-1`},zc={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},Bc=[`value`,`placeholder`],Vc={class:`flex flex-col gap-2`},Hc={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},Uc={class:`flex items-center gap-1.5`},Wc=[`title`,`onClick`],Gc=[`value`,`title`],Kc={class:`grid grid-cols-2 gap-2`},qc={class:`docs-ground-light flex items-center gap-2 overflow-hidden rounded border border-border bg-white p-2`},Jc={class:`dark flex items-center gap-2 overflow-hidden rounded border border-border bg-neutral-900 p-2`},Yc={class:`flex justify-end`},Xc=L({__name:`GroupEditor`,props:{group:{},translate:{type:Function}},emits:[`update:group`,`delete`],setup(e,{emit:t}){let n=e,r=t,i=Array.from({length:12},(e,t)=>t*30);function a(e){r(`update:group`,{...n.group,name:e.target.value})}function o(e){r(`update:group`,{...n.group,hue:e})}function s(e){o(Number(e.target.value))}function c(e){return`${n.translate(`docs.groupColour`)} ${e}°`}return(t,n)=>(U(),W(`div`,Lc,[G(`label`,Rc,[G(`span`,zc,O(e.translate(`docs.groupName`)),1),G(`input`,{type:`text`,value:e.group.name,placeholder:e.translate(`docs.groupName`),class:`rounded border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus:border-ring`,onInput:n[0]||=e=>a(e)},null,40,Bc)]),G(`div`,Vc,[G(`span`,Hc,O(e.translate(`docs.groupColour`)),1),G(`div`,Uc,[(U(!0),W(V,null,R(F(i),t=>(U(),W(`button`,{key:t,type:`button`,class:D([`docs-group h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105`,e.group.hue===t?`ring-2 ring-ring ring-offset-2`:`border-border`]),style:E([{"background-color":`var(--group-c)`},F(Oo)(t)]),title:c(t),onClick:e=>o(t)},null,14,Wc))),128))]),G(`input`,{type:`range`,min:`0`,max:`359`,value:e.group.hue,class:`w-full`,title:c(e.group.hue),onInput:n[1]||=e=>s(e)},null,40,Gc),G(`div`,Kc,[G(`div`,qc,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)]),G(`div`,Jc,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)])])]),G(`div`,Yc,[G(`button`,{type:`button`,class:`rounded border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[2]||=t=>r(`delete`,e.group.id)},O(e.translate(`docs.deleteGroup`)),1)])]))}});function Zc(e,t={},n=!1){let r=Math.max(1,t.columnsPerRow??Math.ceil(Math.sqrt(Math.max(e.length,1)))),i=t.cardWidth??260,a=t.gapX??56,o=t.gapY??40,s=t.margin??40,c=t.rowHeight,l=e=>c??44+(e.columns?.length??0)*24+12,u={},d=s;for(let t=0;t<e.length;t+=r){let c=e.slice(t,t+r),f=Math.max(...c.map(l));c.forEach((e,t)=>{let r={x:s+t*(i+a),y:d};u[e.name]=r,n&&e.schema&&(u[`${e.schema}.${e.name}`]=r)}),d+=f+o}return u}function Qc(e,t,n){let r=t.x-e.x,i=t.y-e.y;if(r===0&&i===0)return{x:e.x,y:e.y};let a=r===0?1/0:n.width/Math.abs(r),o=i===0?1/0:n.height/Math.abs(i),s=Math.min(a,o);return{x:e.x+r*s,y:e.y+i*s}}var $c={class:`overflow-auto`},el=[`width`,`height`,`viewBox`],tl=[`x1`,`y1`,`x2`,`y2`],nl=[`x`,`y`,`onClick`],rl=[`x`,`y`],il=[`x`,`y`],al=260,ol=220,sl=40,cl=8,ll=L({__name:`SchemaDiagram`,props:{snapshot:{}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i={width:al/2,height:ol/2},a=Y(()=>Zc(n.snapshot.tables.map(e=>({name:X(e),columns:e.columns})))),o=Y(()=>new Map(n.snapshot.groups.map(e=>[e.id,e]))),s=Y(()=>n.snapshot.tables.map(e=>{let t=X(e),n=a.value[t]??{x:sl,y:sl},r=e.groupId?o.value.get(e.groupId)??null:null;return{key:t,x:n.x,y:n.y,hue:r?.hue??null,columns:e.columns.slice(0,cl).map(e=>e.name)}}));function c(e){let t=a.value[e]??{x:sl,y:sl};return{x:t.x+al/2,y:t.y+ol/2}}let l=Y(()=>{let e=new Set(Object.keys(a.value));return n.snapshot.relationships.map(e=>({relationship:e,fromKey:X({schema:e.from.schema,name:e.from.table}),toKey:X({schema:e.to.schema,name:e.to.table})})).filter(({fromKey:t,toKey:n})=>e.has(t)&&e.has(n)).map(({relationship:e,fromKey:t,toKey:n})=>{let r=c(t),a=c(n);return{id:e.id,from:Qc(r,a,i),to:Qc(a,r,i)}})}),u=Y(()=>Math.max(0,...s.value.map(e=>e.x+al))+sl),d=Y(()=>Math.max(0,...s.value.map(e=>e.y+ol))+sl);function f(e){return e===null?{}:{...Oo(e),fill:`var(--group-tint)`}}return(e,t)=>(U(),W(`div`,$c,[(U(),W(`svg`,{width:u.value,height:d.value,viewBox:`0 0 ${u.value} ${d.value}`,class:`block`},[(U(!0),W(V,null,R(l.value,e=>(U(),W(`line`,{key:e.id,x1:e.from.x,y1:e.from.y,x2:e.to.x,y2:e.to.y,class:`stroke-border`,"stroke-width":`1.5`},null,8,tl))),128)),(U(!0),W(V,null,R(s.value,e=>(U(),W(`g`,{key:e.key},[G(`rect`,{x:e.x,y:e.y,width:al,height:ol,rx:`6`,class:D([`cursor-pointer stroke-border`,e.hue===null?`fill-card`:`docs-group`]),style:E(f(e.hue)),"stroke-width":`1`,onClick:t=>r(`select`,e.key)},null,14,nl),G(`text`,{x:e.x+10,y:e.y+22,class:`pointer-events-none fill-foreground font-mono text-[11px] font-semibold`},O(e.key),9,rl),(U(!0),W(V,null,R(e.columns,(t,n)=>(U(),W(`text`,{key:t,x:e.x+10,y:e.y+42+n*18,class:`pointer-events-none fill-muted-foreground font-mono text-[10px]`},O(t),9,il))),128))]))),128))],8,el))]))}}),ul={class:`overflow-hidden rounded-md border border-border`},dl={class:`w-full text-xs`},fl={class:`bg-muted/30`},pl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},ml={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},hl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},gl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},_l={class:`px-2 py-1.5 font-mono font-medium text-foreground`},vl={class:`px-2 py-1.5 font-mono text-muted-foreground`},yl={class:`px-2 py-1.5`},bl={class:`flex flex-wrap gap-1`},xl={class:`px-2 py-1.5 text-muted-foreground`},Sl={class:`flex items-start gap-1`},Cl=[`title`],wl=L({__name:`ColumnTable`,props:{columns:{},columnNotes:{},tableKey:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`edit`],setup(e,{emit:t}){let n=e,r=t;function i(e){let t=e.data_type.trim();if(t.includes(`(`))return t;if(e.character_maximum_length!==null)return`${t}(${e.character_maximum_length})`;if(e.numeric_precision!==null){let n=e.numeric_scale===null?``:`,${e.numeric_scale}`;return`${t}(${e.numeric_precision}${n})`}return t}function a(e){let t=[];return e.is_primary_key&&t.push(`pk`),e.is_nullable||t.push(`not null`),e.column_default!==null&&t.push(`default: ${e.column_default}`),e.extra!==null&&e.extra!==``&&t.push(e.extra),e.enum_values!==void 0&&e.enum_values.length>0&&t.push(`enum: ${e.enum_values.join(`, `)}`),t}function o(e){return n.columnNotes[e.name]??null}function s(e){let t=o(e)?.shadowed;return t?`Database comment: ${t}`:void 0}return(t,n)=>(U(),W(`div`,ul,[G(`table`,dl,[G(`thead`,null,[G(`tr`,fl,[G(`th`,pl,O(e.translate(`docs.columnHeader`)),1),G(`th`,ml,O(e.translate(`docs.typeHeader`)),1),G(`th`,hl,O(e.translate(`docs.settingsHeader`)),1),G(`th`,gl,O(e.translate(`docs.noteHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.columns,t=>(U(),W(`tr`,{key:t.name,class:`border-t border-border align-top`},[G(`td`,_l,O(t.name),1),G(`td`,vl,O(i(t)),1),G(`td`,yl,[G(`div`,bl,[(U(!0),W(V,null,R(a(t),e=>(U(),W(`span`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] text-muted-foreground`},O(e),1))),128))])]),G(`td`,xl,[G(`div`,Sl,[o(t)?.source===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium`,title:s(t)},`⬤ `+O(e.translate(`docs.localNote`)),9,Cl)):q(``,!0),K(wc,{class:`min-w-0 flex-1`,"model-value":o(t)?.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n=>r(`edit`,{kind:`columnNote`,tableKey:e.tableKey,column:t.name,note:n})},null,8,[`model-value`,`readonly`,`translate`,`onUpdate:modelValue`])])])]))),128))])])]))}}),Tl={class:`flex items-center gap-1.5`},El=[`value`],Dl={value:``},Ol=[`value`],kl=`__dbx_new_group__`,Al=L({__name:`GroupPicker`,props:{groups:{},modelValue:{},translate:{type:Function}},emits:[`update:modelValue`,`create`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.groups.find(e=>e.id===n.modelValue)??null);function a(e){let t=e.target;if(t.value===kl&&!n.groups.some(e=>e.id===kl)){t.value=n.modelValue??``,r(`create`);return}r(`update:modelValue`,t.value===``?null:t.value)}return(t,n)=>(U(),W(`div`,Tl,[i.value?(U(),W(`span`,{key:0,class:`docs-group h-3 w-3 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(i.value.hue)])},null,4)):q(``,!0),G(`select`,{value:e.modelValue??``,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground outline-none focus:border-ring`,onChange:n[0]||=e=>a(e)},[G(`option`,Dl,O(e.translate(`docs.noGroup`)),1),(U(!0),W(V,null,R(e.groups,e=>(U(),W(`option`,{key:e.id,value:e.id},O(e.name),9,Ol))),128)),G(`option`,{value:kl},O(e.translate(`docs.newGroup`)),1)],40,El)]))}}),jl={class:`grid gap-4 sm:grid-cols-2`},Ml={class:`mb-1.5 text-xs font-medium text-muted-foreground`},Nl={key:0,class:`text-xs text-muted-foreground`},Pl={key:1,class:`flex flex-col gap-1`},Fl=[`onClick`],Il={class:`font-mono`},Ll={class:`mx-1.5 text-muted-foreground`},Rl={class:`font-mono`},zl={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},Bl={class:`mb-1.5 text-xs font-medium text-muted-foreground`},Vl={key:0,class:`text-xs text-muted-foreground`},Hl={key:1,class:`flex flex-col gap-1`},Ul=[`onClick`],Wl={class:`font-mono`},Gl={class:`mx-1.5 text-muted-foreground`},Kl={class:`font-mono`},ql={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},Jl=L({__name:`RelationshipList`,props:{relationships:{},schema:{},table:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t;function i(e){return e.table===n.table&&(e.schema??null)===n.schema}function a(e){return X({schema:e.schema,name:e.table})}function o(e){return`${a(e)}.${e.column}`}function s(e){return e.cardinality===`ONE_TO_ONE`?`1 – 1`:`* – 1`}function c(e){let t=[];return e.onUpdate&&t.push(`on update ${e.onUpdate}`),e.onDelete&&t.push(`on delete ${e.onDelete}`),t}let l=Y(()=>n.relationships.filter(e=>i(e.from))),u=Y(()=>n.relationships.filter(e=>i(e.to)));return(t,n)=>(U(),W(`div`,jl,[G(`section`,null,[G(`h4`,Ml,O(e.translate(`docs.references`))+` (`+O(l.value.length)+`)`,1),l.value.length===0?(U(),W(`p`,Nl,O(e.translate(`docs.noOutgoingRelationships`)),1)):(U(),W(`ul`,Pl,[(U(!0),W(V,null,R(l.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.to))},[G(`span`,Il,O(e.from.column),1),G(`span`,Ll,O(s(e)),1),G(`span`,Rl,O(o(e.to)),1),c(e).length>0?(U(),W(`span`,zl,O(c(e).join(`, `)),1)):q(``,!0)],8,Fl)]))),128))]))]),G(`section`,null,[G(`h4`,Bl,O(e.translate(`docs.referencedBy`))+` (`+O(u.value.length)+`)`,1),u.value.length===0?(U(),W(`p`,Vl,O(e.translate(`docs.noIncomingRelationships`)),1)):(U(),W(`ul`,Hl,[(U(!0),W(V,null,R(u.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.from))},[G(`span`,Wl,O(o(e.from)),1),G(`span`,Gl,O(s(e)),1),G(`span`,Kl,O(e.to.column),1),c(e).length>0?(U(),W(`span`,ql,O(c(e).join(`, `)),1)):q(``,!0)],8,Ul)]))),128))]))])]))}}),Yl={class:`flex flex-col gap-5`},Xl={class:`flex flex-col gap-2`},Zl={class:`flex flex-wrap items-center gap-2`},Ql={class:`font-mono text-lg font-semibold text-foreground`},$l={class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},eu={key:1,class:`text-[10px] text-muted-foreground`},tu={class:`flex items-start gap-2`},nu=[`title`],ru={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},iu={key:0},au={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},ou={class:`overflow-hidden rounded-md border border-border`},su={class:`w-full text-xs`},cu={class:`bg-muted/30`},lu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},uu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},du={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},fu={class:`px-2 py-1.5 font-mono`},pu={class:`px-2 py-1.5 font-mono text-muted-foreground`},mu={class:`px-2 py-1.5`},hu={class:`flex flex-wrap gap-1 text-[10px] text-muted-foreground`},gu={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5`},_u={key:1,class:`rounded bg-muted/50 px-1.5 py-0.5`},vu={key:2,class:`rounded bg-muted/50 px-1.5 py-0.5`},yu={key:3,class:`rounded bg-muted/50 px-1.5 py-0.5`},bu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},xu={key:1},Su={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Cu={class:`overflow-x-auto rounded-md border border-border bg-muted/20 p-2 font-mono text-xs`},wu=L({__name:`TablePage`,props:{table:{},relationships:{},group:{},annotationGroups:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`select`,`edit`,`createGroup`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>X(n.table)),a=Y(()=>n.table.kind.toLowerCase().replace(/_/g,` `)),o=Y(()=>n.table.shadowedNote?`Database comment: ${n.table.shadowedNote}`:void 0);return(t,n)=>(U(),W(`article`,Yl,[G(`header`,Xl,[G(`div`,Zl,[G(`h2`,Ql,O(i.value),1),G(`span`,$l,O(a.value),1),e.group?(U(),W(`span`,{key:0,class:`docs-group rounded px-1.5 py-0.5 text-[10px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)):q(``,!0),e.table.estimatedRows===null?q(``,!0):(U(),W(`span`,eu,` ~`+O(e.table.estimatedRows)+` rows `,1))]),G(`div`,tu,[e.table.noteSource===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium text-muted-foreground`,title:o.value},`⬤ `+O(e.translate(`docs.localNote`)),9,nu)):q(``,!0),K(wc,{class:`min-w-0 flex-1`,"model-value":e.table.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n[0]||=e=>r(`edit`,{kind:`tableNote`,tableKey:i.value,note:e})},null,8,[`model-value`,`readonly`,`translate`])]),e.readonly?q(``,!0):(U(),ji(Al,{key:0,groups:e.annotationGroups,"model-value":e.table.groupId,translate:e.translate,"onUpdate:modelValue":n[1]||=e=>r(`edit`,{kind:`tableGroup`,tableKey:i.value,groupId:e}),onCreate:n[2]||=e=>r(`createGroup`,i.value)},null,8,[`groups`,`model-value`,`translate`]))]),G(`section`,null,[G(`h3`,ru,O(e.translate(`docs.columns`)),1),K(wl,{columns:e.table.columns,"column-notes":e.table.columnNotes,"table-key":i.value,readonly:e.readonly,translate:e.translate,onEdit:n[3]||=e=>r(`edit`,e)},null,8,[`columns`,`column-notes`,`table-key`,`readonly`,`translate`])]),e.table.indexes.length>0?(U(),W(`section`,iu,[G(`h3`,au,O(e.translate(`docs.indexes`)),1),G(`div`,ou,[G(`table`,su,[G(`thead`,null,[G(`tr`,cu,[G(`th`,lu,O(e.translate(`docs.nameHeader`)),1),G(`th`,uu,O(e.translate(`docs.columns`)),1),G(`th`,du,O(e.translate(`docs.settingsHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.table.indexes,e=>(U(),W(`tr`,{key:e.name,class:`border-t border-border align-top`},[G(`td`,fu,O(e.name),1),G(`td`,pu,[zi(O(e.columns.join(`, `)),1),e.included_columns&&e.included_columns.length>0?(U(),W(V,{key:0},[zi(` (include `+O(e.included_columns.join(`, `))+`) `,1)],64)):q(``,!0)]),G(`td`,mu,[G(`div`,hu,[e.is_primary?(U(),W(`span`,gu,`pk`)):q(``,!0),e.is_unique?(U(),W(`span`,_u,`unique`)):q(``,!0),e.index_type?(U(),W(`span`,vu,O(e.index_type),1)):q(``,!0),e.filter?(U(),W(`span`,yu,`where `+O(e.filter),1)):q(``,!0)])])]))),128))])])])])):q(``,!0),G(`section`,null,[G(`h3`,bu,O(e.translate(`docs.relationships`)),1),K(Jl,{relationships:e.relationships,schema:e.table.schema,table:e.table.name,translate:e.translate,onSelect:n[4]||=e=>r(`select`,e)},null,8,[`relationships`,`schema`,`table`,`translate`])]),e.table.viewDefinition?(U(),W(`section`,xu,[G(`h3`,Su,O(e.translate(`docs.definitionHeader`)),1),G(`pre`,Cu,O(e.table.viewDefinition),1)])):q(``,!0)]))}});function Tu(e,t){switch(e.kind){case`tableSkipped`:return{severity:`warning`,title:t(`docs.warnings.tableSkipped.title`),detail:t(`docs.warnings.tableSkipped.detail`,{table:e.table,reason:e.reason})};case`noForeignKeyMetadata`:return{severity:`info`,title:t(`docs.warnings.noForeignKeyMetadata.title`),detail:t(`docs.warnings.noForeignKeyMetadata.detail`,{engine:e.engine})};case`commentsUnsupported`:return{severity:`info`,title:t(`docs.warnings.commentsUnsupported.title`),detail:t(`docs.warnings.commentsUnsupported.detail`,{engine:e.engine})};case`orphanedNotes`:return{severity:`warning`,title:t(`docs.warnings.orphanedNotes.title`),detail:t(`docs.warnings.orphanedNotes.detail`,{count:e.count})};case`dbmlOmitted`:return{severity:`info`,title:t(`docs.warnings.dbmlOmitted.title`),detail:t(`docs.warnings.dbmlOmitted.detail`,{item:e.item,table:e.table,reason:e.reason})}}}var Eu={key:0,class:`flex flex-col gap-2`},Du={class:`font-medium`},Ou={class:`mt-0.5 leading-relaxed`},ku=L({__name:`WarningBanner`,props:{warnings:{},translate:{type:Function}},setup(e){let t=e,n=Y(()=>t.warnings.map((e,n)=>({key:`${e.kind}-${n}`,...Tu(e,t.translate)})));return(e,t)=>n.value.length>0?(U(),W(`div`,Eu,[(U(!0),W(V,null,R(n.value,e=>(U(),W(`div`,{key:e.key,class:D([`rounded-md border px-3 py-2 text-xs`,e.severity===`warning`?`border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200`:`border-border bg-muted/30 text-muted-foreground`])},[G(`div`,Du,O(e.title),1),G(`div`,Ou,O(e.detail),1)],2))),128))])):q(``,!0)}}),Au={class:`flex flex-col gap-6`},ju={class:`flex items-baseline gap-2`},Mu={class:`text-sm font-semibold text-foreground`},Nu={class:`text-xs text-muted-foreground`},Pu=[`innerHTML`],Fu={class:`grid gap-1 sm:grid-cols-2 lg:grid-cols-3`},Iu=[`onClick`],Lu={class:`font-mono text-xs font-medium text-foreground`},Ru={key:0,class:`text-[10px] uppercase text-muted-foreground`},zu=[`innerHTML`],Bu=L({__name:`WikiIndex`,props:{sections:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=t;return(t,r)=>(U(),W(`div`,Au,[(U(!0),W(V,null,R(e.sections,t=>(U(),W(`section`,{key:t.key,class:`flex flex-col gap-2`},[G(`div`,{class:D([`flex flex-col gap-1 border-l-2 pl-3`,{"docs-group":t.hue!==null}]),style:E([{"border-color":`var(--group-c, var(--border))`},F(Oo)(t.hue)])},[G(`div`,ju,[G(`h2`,Mu,O(t.label||e.translate(t.fallbackKey)),1),G(`span`,Nu,O(t.tables.length)+` tables`,1)]),t.note?(U(),W(`div`,{key:0,class:`text-xs text-muted-foreground`,innerHTML:F(xc)(t.note)},null,8,Pu)):q(``,!0)],6),G(`ul`,Fu,[(U(!0),W(V,null,R(t.tables,e=>(U(),W(`li`,{key:F(X)(e),class:`flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 transition-colors hover:bg-muted/40`},[G(`button`,{type:`button`,class:`flex w-full items-baseline gap-1.5 text-left`,onClick:t=>n(`select`,F(X)(e))},[G(`span`,Lu,O(e.name),1),e.kind===`TABLE`?q(``,!0):(U(),W(`span`,Ru,O(e.kind.toLowerCase().replace(/_/g,` `)),1))],8,Iu),e.note?(U(),W(`div`,{key:0,class:`line-clamp-2 text-[11px] text-muted-foreground`,innerHTML:F(xc)(e.note)},null,8,zu)):q(``,!0)]))),128))])]))),128))]))}});function Vu(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=crypto.getRandomValues(new Uint8Array(16));return e[6]=e[6]&15|64,e[8]=e[8]&63|128,Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``).replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,`$1-$2-$3-$4-$5`)}return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Hu={class:`flex h-full min-h-0 bg-background text-foreground`},Uu={class:`flex h-full min-h-0 w-64 shrink-0 flex-col`},Wu={class:`flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto p-4`},Gu={class:`flex flex-wrap items-start justify-between gap-3`},Ku={class:`flex flex-col gap-1`},qu={class:`text-base font-semibold`},Ju={class:`text-xs text-muted-foreground`},Yu={key:0,class:`flex flex-col gap-4`},Xu={key:0,class:`flex flex-col gap-2`},Zu={class:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Qu=L({__name:`DocsApp`,props:{snapshot:{},annotations:{},readonly:{type:Boolean},translate:{},route:{},diagram:{default:`external`}},emits:[`edit`,`update:route`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.readonly??!1),a=Y(()=>n.annotations.groups??[]),o=P(n.snapshot.groups.length>0?`group`:`schema`),s=P(null),c=P(null),l=P(!1),u=Y(()=>n.route?n.route:l.value?{kind:`diagram`}:c.value===null?s.value===null?{kind:`index`}:{kind:`table`,key:s.value}:{kind:`enum`,name:c.value}),d=Y(()=>u.value.kind===`table`?u.value.key:null),f=Y(()=>u.value.kind===`enum`?u.value.name:null),p=Y(()=>o.value===`schema`?Ro(n.snapshot):zo(n.snapshot)),m=Y(()=>n.snapshot.tables.find(e=>X(e)===d.value)??null),h=Y(()=>f.value===null?null:n.snapshot.enums.find(e=>e.name===f.value)??null),g=Y(()=>u.value.kind===`diagram`?`diagram`:h.value===null?m.value===null?`index`:`table`:`enum`),_=Y(()=>{let e=m.value?.groupId;return e?n.snapshot.groups.find(t=>t.id===e)??null:null});function v(e){n.snapshot.tables.some(t=>X(t)===e)&&(c.value=null,l.value=!1,s.value=e,r(`update:route`,{kind:`table`,key:e}))}function y(e){n.snapshot.enums.some(t=>t.name===e)&&(s.value=null,l.value=!1,c.value=e,r(`update:route`,{kind:`enum`,name:e}))}function b(){s.value=null,c.value=null,l.value=!0,r(`update:route`,{kind:`diagram`})}function x(){s.value=null,c.value=null,l.value=!1,r(`update:route`,{kind:`index`})}function ee(e){let t={id:Vu(),name:n.translate(`docs.newGroup`),hue:a.value.length*47%360};r(`edit`,{kind:`upsertGroup`,group:t}),r(`edit`,{kind:`tableGroup`,tableKey:e,groupId:t.id})}return(t,n)=>(U(),W(`div`,Hu,[G(`div`,Uu,[K(Io,{class:`min-h-0 flex-1`,sections:p.value,mode:o.value,"active-key":d.value,translate:e.translate,"onUpdate:mode":n[0]||=e=>o.value=e,onSelect:v,onHome:n[1]||=e=>x()},null,8,[`sections`,`mode`,`active-key`,`translate`]),e.diagram===`inline`?(U(),W(`button`,{key:0,type:`button`,class:D([`shrink-0 border-t border-r border-border bg-background px-3 py-2 text-left text-xs font-medium transition-colors`,g.value===`diagram`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:n[2]||=e=>b()},O(e.translate(`docs.diagram`)),3)):q(``,!0)]),G(`main`,Wu,[G(`header`,Gu,[G(`div`,Ku,[G(`h1`,qu,O(e.snapshot.project.name),1),G(`p`,Ju,[zi(O(e.snapshot.project.databaseType),1),e.snapshot.project.database?(U(),W(V,{key:0},[zi(` · `+O(e.snapshot.project.database),1)],64)):q(``,!0),zi(` · `+O(e.snapshot.tables.length)+` tables · generated `+O(e.snapshot.project.generatedAt),1)])]),K(Do,{snapshot:e.snapshot,translate:e.translate,onSelect:v,onSelectEnum:y},null,8,[`snapshot`,`translate`])]),K(ku,{warnings:e.snapshot.warnings,translate:e.translate},null,8,[`warnings`,`translate`]),g.value===`index`?(U(),W(`div`,Yu,[K(wc,{"model-value":e.snapshot.project.note??``,readonly:i.value,translate:e.translate,"onUpdate:modelValue":n[3]||=e=>r(`edit`,{kind:`projectNote`,note:e})},null,8,[`model-value`,`readonly`,`translate`]),K(Bu,{sections:p.value,translate:e.translate,onSelect:v},null,8,[`sections`,`translate`]),!i.value&&a.value.length>0?(U(),W(`section`,Xu,[G(`h2`,Zu,O(e.translate(`docs.groups`)),1),(U(!0),W(V,null,R(a.value,t=>(U(),ji(Xc,{key:t.id,group:t,translate:e.translate,"onUpdate:group":n[4]||=e=>r(`edit`,{kind:`upsertGroup`,group:e}),onDelete:n[5]||=e=>r(`edit`,{kind:`removeGroup`,groupId:e})},null,8,[`group`,`translate`]))),128))])):q(``,!0)])):g.value===`table`&&m.value?(U(),ji(wu,{key:1,table:m.value,relationships:e.snapshot.relationships,group:_.value,"annotation-groups":a.value,readonly:i.value,translate:e.translate,onSelect:v,onEdit:n[6]||=e=>r(`edit`,e),onCreateGroup:ee},null,8,[`table`,`relationships`,`group`,`annotation-groups`,`readonly`,`translate`])):h.value?(U(),ji(Ic,{key:2,"enum-type":h.value,snapshot:e.snapshot,translate:e.translate,onSelect:v},null,8,[`enum-type`,`snapshot`,`translate`])):g.value===`diagram`?(U(),ji(ll,{key:3,snapshot:e.snapshot,onSelect:v},null,8,[`snapshot`])):q(``,!0)])]))}}),$u={kind:`index`};function ed(e,t,n){if(!e.startsWith(`#`))return $u;let[r,...i]=e.slice(1).replace(/^\//,``).split(`/`),a=i.join(`/`);if(r===`diagram`&&a===``)return n?{kind:`diagram`}:$u;if(a===``)return $u;let o;try{o=decodeURIComponent(a)}catch{return $u}return r===`table`?t.tables.some(e=>X(e)===o)?{kind:`table`,key:o}:$u:r===`enum`&&(t.enums??[]).some(e=>e.name===o)?{kind:`enum`,name:o}:$u}function td(e){switch(e.kind){case`table`:return`#/table/${encodeURIComponent(e.key)}`;case`enum`:return`#/enum/${encodeURIComponent(e.name)}`;case`diagram`:return`#/diagram`;default:return`#/`}}var nd=[{value:`en`,flag:`🇺🇸`,label:`English`},{value:`az`,flag:`🇦🇿`,label:`Azərbaycan`},{value:`es`,flag:`🇪🇸`,label:`Español`},{value:`id`,flag:`🇮🇩`,label:`Bahasa Indonesia`},{value:`it`,flag:`🇮🇹`,label:`Italiano`},{value:`ja`,flag:`🇯🇵`,label:`日本語`},{value:`ko`,flag:`🇰🇷`,label:`한국어`},{value:`pt-BR`,flag:`🇧🇷`,label:`Português`},{value:`ru`,flag:`🇷🇺`,label:`Русский`},{value:`th`,flag:`🇹🇭`,label:`ภาษาไทย`},{value:`tr`,flag:`🇹🇷`,label:`Türkçe`},{value:`zh-CN`,flag:`🇨🇳`,label:`简体中文`},{value:`zh-TW`,flag:`繁`,label:`繁體中文`}],rd={en:{title:`Documentation`,groupBySchema:`Schemas`,groupByTableGroup:`Table Groups`,noGroup:`(no group)`,noSchema:`(no schema)`,search:`Search tables, columns, groups…`,columns:`Columns`,indexes:`Indexes`,references:`References`,referencedBy:`Referenced by`,localNote:`LOCAL`,shadowedComment:`Database comment: {comment}`,addNote:`Add a note`,editNote:`Edit note`,newGroup:`New group…`,groupName:`Group name`,groupColour:`Colour`,deleteGroup:`Delete group`,enumValues:`Values`,usedBy:`Used by`,openDiagram:`Open schema diagram`,saving:`Saving…`,saved:`Saved`,saveFailed:`Could not save notes: {error}`,overview:`Overview`,groupBy:`Group by`,searchLabel:`Search`,groups:`Groups`,relationships:`Relationships`,columnHeader:`Column`,typeHeader:`Type`,settingsHeader:`Settings`,noteHeader:`Note`,nameHeader:`Name`,definitionHeader:`Definition`,noOutgoingRelationships:`This table references no other table.`,noIncomingRelationships:`No table references this one.`,diagram:`Diagram`,language:`Language`,theme:`Theme`,themeLight:`Light`,themeDark:`Dark`,exportHtml:`Export HTML…`,exporting:`Exporting…`,exportFailed:`Could not export: {error}`,warnings:{tableSkipped:{title:`A table could not be documented`,detail:`{table} was skipped: {reason}. It is missing from this documentation.`},noForeignKeyMetadata:{title:`No relationships available`,detail:`{engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.`},commentsUnsupported:{title:`Database comments unavailable`,detail:`{engine} does not support table or column comments, so every description here comes from this project's own notes.`},orphanedNotes:{title:`Some notes no longer match anything`,detail:`{count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.`},dbmlOmitted:{title:`Not representable in DBML`,detail:`{item} on {table} is documented here but omitted from the exported DBML: {reason}.`}}},es:{title:`Documentación`,groupBySchema:`Esquemas`,groupByTableGroup:`Grupos de tablas`,noGroup:`(sin grupo)`,noSchema:`(sin esquema)`,search:`Buscar tablas, columnas, grupos…`,columns:`Columnas`,indexes:`Índices`,references:`Referencias`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentario de la base de datos: {comment}`,addNote:`Agregar una nota`,editNote:`Editar nota`,newGroup:`Nuevo grupo…`,groupName:`Nombre del grupo`,groupColour:`Color`,deleteGroup:`Eliminar grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama del esquema`,saving:`Guardando…`,saved:`Guardado`,saveFailed:`No se pudieron guardar las notas: {error}`,overview:`Información general`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relaciones`,columnHeader:`Columna`,typeHeader:`Tipo`,settingsHeader:`Configuración`,noteHeader:`Nota`,nameHeader:`Nombre`,definitionHeader:`Definición`,noOutgoingRelationships:`Esta tabla no referencia ninguna otra tabla.`,noIncomingRelationships:`Ninguna tabla referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Oscuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`No se pudo exportar: {error}`,warnings:{tableSkipped:{title:`No se pudo documentar una tabla`,detail:`{table} fue omitida: {reason}. Falta en esta documentación.`},noForeignKeyMetadata:{title:`No hay relaciones disponibles`,detail:`{engine} no reporta metadatos de claves foráneas, por lo que no se pudieron derivar relaciones. El diagrama está completo para este motor.`},commentsUnsupported:{title:`Comentarios de base de datos no disponibles`,detail:`{engine} no admite comentarios en tablas o columnas, por lo que toda descripción aquí proviene de las notas de este proyecto.`},orphanedNotes:{title:`Algunas notas ya no coinciden con nada`,detail:`{count} nota(s) hacen referencia a una tabla o columna que ya no existe. No se eliminó nada — vuelva a asignarlas o elimínelas en el archivo de notas.`},dbmlOmitted:{title:`No representable en DBML`,detail:`{item} en {table} está documentado aquí pero se omitió del DBML exportado: {reason}.`}}},it:{title:`Documentazione`,groupBySchema:`Schemi`,groupByTableGroup:`Gruppi di tabelle`,noGroup:`(nessun gruppo)`,noSchema:`(nessuno schema)`,search:`Cerca tabelle, colonne, gruppi…`,columns:`Colonne`,indexes:`Indici`,references:`Riferimenti`,referencedBy:`Referenziato da`,localNote:`LOCALE`,shadowedComment:`Commento del database: {comment}`,addNote:`Aggiungi una nota`,editNote:`Modifica nota`,newGroup:`Nuovo gruppo…`,groupName:`Nome del gruppo`,groupColour:`Colore`,deleteGroup:`Elimina gruppo`,enumValues:`Valori`,usedBy:`Usato da`,openDiagram:`Apri diagramma dello schema`,saving:`Salvataggio…`,saved:`Salvato`,saveFailed:`Impossibile salvare le note: {error}`,overview:`Panoramica`,groupBy:`Raggruppa per`,searchLabel:`Cerca`,groups:`Gruppi`,relationships:`Relazioni`,columnHeader:`Colonna`,typeHeader:`Tipo`,settingsHeader:`Impostazioni`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definizione`,noOutgoingRelationships:`Questa tabella non fa riferimento a nessun'altra tabella.`,noIncomingRelationships:`Nessuna tabella fa riferimento a questa.`,diagram:`Diagramma`,language:`Lingua`,theme:`Tema`,themeLight:`Chiaro`,themeDark:`Scuro`,exportHtml:`Esporta HTML…`,exporting:`Esportazione…`,exportFailed:`Impossibile esportare: {error}`,warnings:{tableSkipped:{title:`Impossibile documentare una tabella`,detail:`{table} è stata saltata: {reason}. Manca da questa documentazione.`},noForeignKeyMetadata:{title:`Nessuna relazione disponibile`,detail:`{engine} non riporta i metadati delle chiavi esterne, quindi non è stato possibile derivare alcuna relazione. Il diagramma è completo per questo motore.`},commentsUnsupported:{title:`Commenti del database non disponibili`,detail:`{engine} non supporta i commenti su tabelle o colonne, quindi ogni descrizione qui proviene dalle note di questo progetto.`},orphanedNotes:{title:`Alcune note non corrispondono più a nulla`,detail:`{count} nota/e fanno riferimento a una tabella o colonna che non esiste più. Nulla è stato eliminato — rimappa o rimuovi queste note nel file delle note.`},dbmlOmitted:{title:`Non rappresentabile in DBML`,detail:`{item} su {table} è documentato qui ma omesso dal DBML esportato: {reason}.`}}},ja:{title:`ドキュメント`,groupBySchema:`スキーマ`,groupByTableGroup:`テーブルグループ`,noGroup:`(グループなし)`,noSchema:`(スキーマなし)`,search:`テーブル、カラム、グループを検索…`,columns:`カラム`,indexes:`インデックス`,references:`参照`,referencedBy:`参照元`,localNote:`ローカル`,shadowedComment:`データベースのコメント: {comment}`,addNote:`メモを追加`,editNote:`メモを編集`,newGroup:`新しいグループ…`,groupName:`グループ名`,groupColour:`色`,deleteGroup:`グループを削除`,enumValues:`値`,usedBy:`使用元`,openDiagram:`スキーマ図を開く`,saving:`保存中…`,saved:`保存済み`,saveFailed:`メモを保存できませんでした: {error}`,overview:`概要`,groupBy:`グループ化`,searchLabel:`検索`,groups:`グループ`,relationships:`リレーションシップ`,columnHeader:`カラム`,typeHeader:`型`,settingsHeader:`設定`,noteHeader:`メモ`,nameHeader:`名前`,definitionHeader:`定義`,noOutgoingRelationships:`このテーブルは他のテーブルを参照していません。`,noIncomingRelationships:`このテーブルを参照しているテーブルはありません。`,diagram:`図`,language:`言語`,theme:`テーマ`,themeLight:`ライト`,themeDark:`ダーク`,exportHtml:`HTMLをエクスポート…`,exporting:`エクスポート中…`,exportFailed:`エクスポートできませんでした: {error}`,warnings:{tableSkipped:{title:`ドキュメント化できないテーブルがあります`,detail:`{table} はスキップされました: {reason}。このドキュメントには含まれていません。`},noForeignKeyMetadata:{title:`リレーションシップを表示できません`,detail:`{engine} は外部キーのメタデータを返さないため、関係線は表示されません。これはこのエンジンの仕様です。`},commentsUnsupported:{title:`データベースのコメントは利用できません`,detail:`{engine} はテーブルやカラムのコメントをサポートしていないため、ここでの説明はすべてこのプロジェクトのメモから提供されています。`},orphanedNotes:{title:`対象がなくなったメモがあります`,detail:`{count} 件のメモが、既に存在しないテーブルまたはカラムを参照しています。何も削除されていません。メモファイルで再割り当てまたは削除してください。`},dbmlOmitted:{title:`DBMLでは表現できません`,detail:`{table} の {item} はここに記載されていますが、エクスポートされたDBMLからは除外されています: {reason}。`}}},ko:{title:`문서`,groupBySchema:`스키마`,groupByTableGroup:`테이블 그룹`,noGroup:`(그룹 없음)`,noSchema:`(스키마 없음)`,search:`테이블, 컬럼, 그룹 검색…`,columns:`컬럼`,indexes:`인덱스`,references:`참조`,referencedBy:`참조된 위치`,localNote:`로컬`,shadowedComment:`데이터베이스 코멘트: {comment}`,addNote:`메모 추가`,editNote:`메모 편집`,newGroup:`새 그룹…`,groupName:`그룹 이름`,groupColour:`색상`,deleteGroup:`그룹 삭제`,enumValues:`값`,usedBy:`사용처`,openDiagram:`스키마 다이어그램 열기`,saving:`저장 중…`,saved:`저장됨`,saveFailed:`메모를 저장할 수 없습니다: {error}`,overview:`개요`,groupBy:`그룹화 기준`,searchLabel:`검색`,groups:`그룹`,relationships:`관계`,columnHeader:`컬럼`,typeHeader:`유형`,settingsHeader:`설정`,noteHeader:`메모`,nameHeader:`이름`,definitionHeader:`정의`,noOutgoingRelationships:`이 테이블은 다른 테이블을 참조하지 않습니다.`,noIncomingRelationships:`이 테이블을 참조하는 테이블이 없습니다.`,diagram:`다이어그램`,language:`언어`,theme:`테마`,themeLight:`라이트`,themeDark:`다크`,exportHtml:`HTML 내보내기…`,exporting:`내보내는 중…`,exportFailed:`내보낼 수 없습니다: {error}`,warnings:{tableSkipped:{title:`문서화할 수 없는 테이블이 있습니다`,detail:`{table} 을(를) 건너뛰었습니다: {reason}. 이 문서에서 누락되었습니다.`},noForeignKeyMetadata:{title:`표시할 관계가 없습니다`,detail:`{engine} 은(는) 외래 키 메타데이터를 보고하지 않으므로 관계를 도출할 수 없습니다. 이 엔진에 대해서는 다이어그램이 완전합니다.`},commentsUnsupported:{title:`데이터베이스 코멘트를 사용할 수 없습니다`,detail:`{engine} 은(는) 테이블 또는 컬럼 코멘트를 지원하지 않으므로 여기의 모든 설명은 이 프로젝트의 메모에서만 제공됩니다.`},orphanedNotes:{title:`더 이상 일치하는 대상이 없는 메모가 있습니다`,detail:`{count} 개의 메모가 더 이상 존재하지 않는 테이블 또는 컬럼을 참조하고 있습니다. 삭제된 항목은 없습니다 — 메모 파일에서 다시 매핑하거나 제거하세요.`},dbmlOmitted:{title:`DBML로 표현할 수 없습니다`,detail:`{table} 의 {item} 은(는) 여기에 문서화되어 있지만 내보낸 DBML에서는 제외되었습니다: {reason}.`}}},"pt-BR":{title:`Documentação`,groupBySchema:`Schemas`,groupByTableGroup:`Grupos de tabelas`,noGroup:`(sem grupo)`,noSchema:`(sem schema)`,search:`Buscar tabelas, colunas, grupos…`,columns:`Colunas`,indexes:`Índices`,references:`Referências`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentário do banco de dados: {comment}`,addNote:`Adicionar uma nota`,editNote:`Editar nota`,newGroup:`Novo grupo…`,groupName:`Nome do grupo`,groupColour:`Cor`,deleteGroup:`Excluir grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama do schema`,saving:`Salvando…`,saved:`Salvo`,saveFailed:`Não foi possível salvar as notas: {error}`,overview:`Visão geral`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relacionamentos`,columnHeader:`Coluna`,typeHeader:`Tipo`,settingsHeader:`Configurações`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definição`,noOutgoingRelationships:`Esta tabela não referencia nenhuma outra tabela.`,noIncomingRelationships:`Nenhuma tabela referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Escuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`Não foi possível exportar: {error}`,warnings:{tableSkipped:{title:`Uma tabela não pôde ser documentada`,detail:`{table} foi ignorada: {reason}. Ela está faltando nesta documentação.`},noForeignKeyMetadata:{title:`Nenhum relacionamento disponível`,detail:`{engine} não reporta metadados de foreign key, então nenhum relacionamento pôde ser derivado. O diagrama está completo para este engine.`},commentsUnsupported:{title:`Comentários do banco de dados indisponíveis`,detail:`{engine} não suporta comentários em tabelas ou colunas, então toda descrição aqui vem apenas das notas deste projeto.`},orphanedNotes:{title:`Algumas notas não correspondem mais a nada`,detail:`{count} nota(s) referenciam uma tabela ou coluna que não existe mais. Nada foi excluído — remapeie ou remova essas notas no arquivo de notas.`},dbmlOmitted:{title:`Não representável em DBML`,detail:`{item} em {table} está documentado aqui mas foi omitido do DBML exportado: {reason}.`}}},"zh-CN":{title:`文档`,groupBySchema:`Schema`,groupByTableGroup:`表分组`,noGroup:`(无分组)`,noSchema:`(无 Schema)`,search:`搜索表、列、分组…`,columns:`列`,indexes:`索引`,references:`引用`,referencedBy:`被引用`,localNote:`本地`,shadowedComment:`数据库注释: {comment}`,addNote:`添加备注`,editNote:`编辑备注`,newGroup:`新建分组…`,groupName:`分组名称`,groupColour:`颜色`,deleteGroup:`删除分组`,enumValues:`值`,usedBy:`被使用于`,openDiagram:`打开 Schema 图`,saving:`保存中…`,saved:`已保存`,saveFailed:`无法保存备注: {error}`,overview:`概览`,groupBy:`分组方式`,searchLabel:`搜索`,groups:`分组`,relationships:`关系`,columnHeader:`列`,typeHeader:`类型`,settingsHeader:`设置`,noteHeader:`备注`,nameHeader:`名称`,definitionHeader:`定义`,noOutgoingRelationships:`此表未引用任何其他表。`,noIncomingRelationships:`没有表引用此表。`,diagram:`图`,language:`语言`,theme:`主题`,themeLight:`浅色`,themeDark:`深色`,exportHtml:`导出 HTML…`,exporting:`导出中…`,exportFailed:`无法导出: {error}`,warnings:{tableSkipped:{title:`有一张表无法生成文档`,detail:`{table} 被跳过: {reason}。此文档中缺少该表。`},noForeignKeyMetadata:{title:`没有可用的关系`,detail:`{engine} 不报告外键元数据,因此无法推导出任何关系。此图对该数据库引擎而言已经完整。`},commentsUnsupported:{title:`数据库注释不可用`,detail:`{engine} 不支持表或列注释,因此这里的所有描述均仅来自本项目的备注。`},orphanedNotes:{title:`部分备注已不再对应任何内容`,detail:`{count} 条备注引用的表或列已不存在。没有任何内容被删除 — 请在备注文件中重新映射或移除它们。`},dbmlOmitted:{title:`无法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此处记录,但已从导出的 DBML 中省略: {reason}。`}}},"zh-TW":{title:`文件`,groupBySchema:`Schema`,groupByTableGroup:`資料表分組`,noGroup:`(無分組)`,noSchema:`(無 Schema)`,search:`搜尋資料表、欄位、分組…`,columns:`欄位`,indexes:`索引`,references:`參照`,referencedBy:`被參照`,localNote:`本機`,shadowedComment:`資料庫註解: {comment}`,addNote:`新增備註`,editNote:`編輯備註`,newGroup:`新增分組…`,groupName:`分組名稱`,groupColour:`顏色`,deleteGroup:`刪除分組`,enumValues:`值`,usedBy:`被使用於`,openDiagram:`開啟 Schema 圖`,saving:`儲存中…`,saved:`已儲存`,saveFailed:`無法儲存備註: {error}`,overview:`總覽`,groupBy:`分組方式`,searchLabel:`搜尋`,groups:`分組`,relationships:`關聯`,columnHeader:`欄位`,typeHeader:`類型`,settingsHeader:`設定`,noteHeader:`備註`,nameHeader:`名稱`,definitionHeader:`定義`,noOutgoingRelationships:`此資料表未參照任何其他資料表。`,noIncomingRelationships:`沒有資料表參照此資料表。`,diagram:`圖表`,language:`語言`,theme:`主題`,themeLight:`淺色`,themeDark:`深色`,exportHtml:`匯出 HTML…`,exporting:`匯出中…`,exportFailed:`無法匯出: {error}`,warnings:{tableSkipped:{title:`有一張資料表無法產生文件`,detail:`{table} 被略過: {reason}。此文件中缺少該資料表。`},noForeignKeyMetadata:{title:`沒有可用的關聯`,detail:`{engine} 未回報外鍵中繼資料,因此無法推導出任何關聯。此圖對該資料庫引擎而言已經完整。`},commentsUnsupported:{title:`資料庫註解無法使用`,detail:`{engine} 不支援資料表或欄位註解,因此這裡的所有說明均僅來自本專案的備註。`},orphanedNotes:{title:`部分備註已不再對應任何內容`,detail:`{count} 筆備註參照的資料表或欄位已不存在。沒有任何內容被刪除 — 請在備註檔案中重新對應或移除它們。`},dbmlOmitted:{title:`無法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此處記錄,但已從匯出的 DBML 中省略: {reason}。`}}}};function id(e,t){let n=t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e);return typeof n==`string`?n:null}function ad(e){let t=rd[e]??rd.en;return(e,n)=>{let r=e.startsWith(`docs.`)?e.slice(5):e,i=id(t,r)??id(rd.en,r);return i===null?e:n?i.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):i}}var od={class:`flex h-full min-h-0 flex-col bg-background text-foreground`},sd={class:`flex shrink-0 flex-wrap items-center justify-end gap-4 border-b border-border px-4 py-2`},cd={class:`flex items-center gap-2 text-xs text-muted-foreground`},ld={value:`light`},ud={value:`dark`},dd={class:`flex items-center gap-2 text-xs text-muted-foreground`},fd=[`value`],pd=L({__name:`ExportApp`,props:{payload:{}},setup(e){let t=e,n=P(t.payload.lang in rd?t.payload.lang:`en`),r=Y(()=>ad(n.value)),i=nd.filter(e=>e.value in rd),a=P(typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`);Pn(a,e=>{let t=document.documentElement;t.classList.toggle(`dark`,e===`dark`),t.style.colorScheme=e},{immediate:!0}),Pn(n,e=>{document.documentElement.lang=e},{immediate:!0});let o=P(ed(location.hash,t.payload.snapshot,!0));function s(){o.value=ed(location.hash,t.payload.snapshot,!0)}function c(e){o.value=e;let t=td(e);location.hash!==t&&(location.hash=t)}return nr(()=>window.addEventListener(`hashchange`,s)),ar(()=>window.removeEventListener(`hashchange`,s)),(t,s)=>(U(),W(`div`,od,[G(`div`,sd,[G(`label`,cd,[zi(O(r.value(`docs.theme`))+` `,1),On(G(`select`,{"onUpdate:modelValue":s[0]||=e=>a.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[G(`option`,ld,O(r.value(`docs.themeLight`)),1),G(`option`,ud,O(r.value(`docs.themeDark`)),1)],512),[[no,a.value]])]),G(`label`,dd,[zi(O(r.value(`docs.language`))+` `,1),On(G(`select`,{"onUpdate:modelValue":s[1]||=e=>n.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[(U(!0),W(V,null,R(F(i),e=>(U(),W(`option`,{key:e.value,value:e.value},O(e.label),9,fd))),128))],512),[[no,n.value]])])]),K(Qu,{class:`min-h-0 flex-1`,snapshot:e.payload.snapshot,annotations:e.payload.annotations,readonly:!0,translate:r.value,route:o.value,diagram:`inline`,"onUpdate:route":c},null,8,[`snapshot`,`annotations`,`translate`,`route`])]))}});function md(){let e=document.querySelector(`script[type='application/dbx-snapshot']`);if(e===null)throw Error(`no <script type='application/dbx-snapshot'> in this document`);let t=atob((e.textContent??``).trim()),n=Uint8Array.from(t,e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}try{mo(pd,{payload:md()}).mount(`#app`)}catch(e){let t=document.createElement(`p`);t.style.cssText=`margin:2rem;font-family:system-ui,sans-serif`,t.textContent=`This documentation file could not be read: ${e instanceof Error?e.message:String(e)}`,document.querySelector(`#app`)?.replaceChildren(t)}})();
\ No newline at end of file
+`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Tc(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:r,autolink:i}){let a=i?Tc(n,!0):this.parser.parseInline(r),o=Dc(e);if(o===null)return a;e=Tc(o,i);let s=`<a href="`+e+`"`;return t&&(s+=` title="`+Tc(t)+`"`),s+=`>`+a+`</a>`,s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Dc(e);if(i===null)return Tc(n);e=i;let a=`<img src="${Tc(e)}" alt="${Tc(n)}"`;return t&&(a+=` title="${Tc(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Tc(e.text)}},Bc=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},Vc=class e{options;renderer;textRenderer;constructor(e){this.options=e||ns,this.options.renderer=this.options.renderer||new zc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bc}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`checkbox`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`checkbox`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},Hc=class{options;block;constructor(e){this.options=e||ns}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Rc.lex:Rc.lexInline}provideParser(e=this.block){return e?Vc.parse:Vc.parseInline}};function Uc(e,t){if(Array.isArray(t))for(let n=0;n<t.length;n++)e.push(t[n]);else e.push(t)}var Wc=class{defaults=ts();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Vc;Renderer=zc;TextRenderer=Bc;Lexer=Rc;Tokenizer=Lc;Hooks=Hc;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(Uc(n,t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)Uc(n,this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)Uc(n,this.walkTokens(e.tokens,t));break}case`list`:{let e=r;Uc(n,this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);Uc(n,this.walkTokens(i,t))}):e.tokens&&Uc(n,this.walkTokens(e.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new zc(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Lc(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Hc;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=Hc.passThroughHooks.has(n)?e=>{if(this.defaults.async&&Hc.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&Uc(n,t.call(this,e)),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Rc.lex(e,t??this.defaults)}parser(e,t){return Vc.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Rc.lex:Rc.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Vc.parse:Vc.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Rc.lex:Rc.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Vc.parse:Vc.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
+Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Tc(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Gc=new Wc;function $(e,t){return Gc.parse(e,t)}$.options=$.setOptions=function(e){return Gc.setOptions(e),$.defaults=Gc.defaults,rs($.defaults),$},$.getDefaults=ts,$.defaults=ns;function Kc(...e){return Gc.use(...e),$.defaults=Gc.defaults,rs($.defaults),$}$.use=Kc,$.walkTokens=function(e,t){return Gc.walkTokens(e,t)},$.parseInline=Gc.parseInline,$.Parser=Vc,$.parser=Vc.parse,$.Renderer=zc,$.TextRenderer=Bc,$.Lexer=Rc,$.lexer=Rc.lex,$.Tokenizer=Lc,$.Hooks=Hc,$.parse=$,$.options,$.setOptions,$.walkTokens,$.parseInline,Vc.parse,Rc.lex;function qc(e){return String(e??``).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}var Jc=/^(https?:|mailto:)/i;function Yc(e){let t=String(e??``).trim();return t===``||/^[/\\]{2}/.test(t)?null:t.startsWith(`#`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)||Jc.test(t)?t:null}var Xc=new Wc({renderer:{html({text:e}){return qc(e)},link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Yc(e);if(i===null)return r;let a=t?` title="${qc(t)}"`:``;return`<a href="${qc(i)}"${a}>${r}</a>`},image({href:e,title:t,text:n}){let r=Yc(e);if(r===null)return qc(n);let i=t?` title="${qc(t)}"`:``;return`<img src="${qc(r)}" alt="${qc(n)}"${i}>`}}});function Zc(e){return e===null||e.trim()===``?``:Xc.parse(e)}var Qc={class:`text-sm text-muted-foreground`},$c=[`title`,`innerHTML`],el=L({__name:`NoteEditor`,props:{modelValue:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=P(!1),a=P(``),o=P(null);async function s(){n.readonly||(a.value=n.modelValue,i.value=!0,await yn(),o.value?.focus())}function c(){i.value=!1,a.value!==n.modelValue&&r(`update:modelValue`,a.value)}function l(){a.value=n.modelValue,i.value=!1}return(t,n)=>(U(),W(`div`,Qc,[i.value?Pn((U(),W(`textarea`,{key:0,ref_key:`input`,ref:o,"onUpdate:modelValue":n[0]||=e=>a.value=e,rows:`4`,class:`w-full resize-y rounded border border-border bg-background p-2 font-mono text-xs text-foreground outline-none focus:border-ring`,onBlur:n[1]||=e=>c(),onKeydown:n[2]||=wo(e=>l(),[`escape`])},null,544)),[[ho,a.value]]):e.modelValue.trim()===``?e.readonly?q(``,!0):(U(),W(`button`,{key:2,type:`button`,class:`rounded border border-dashed border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[4]||=e=>s()},O(e.translate(`docs.addNote`)),1)):(U(),W(`div`,{key:1,class:D([`leading-relaxed`,e.readonly?``:`cursor-text rounded transition-colors hover:bg-muted/30`]),title:e.readonly?void 0:e.translate(`docs.editNote`),onClick:n[3]||=e=>s(),innerHTML:F(Zc)(e.modelValue)},null,10,$c))]))}}),tl={class:`flex flex-col gap-5`},nl={class:`flex flex-col gap-2`},rl={class:`flex flex-wrap items-center gap-2`},il={class:`font-mono text-lg font-semibold text-foreground`},al={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},ol={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},sl={class:`flex flex-wrap gap-1`},cl={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},ll={key:0,class:`text-xs text-muted-foreground`},ul={key:1,class:`flex flex-col gap-1`},dl=[`onClick`],fl=L({__name:`EnumPage`,props:{enumType:{},snapshot:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.enumType.schema?`${n.enumType.schema}.${n.enumType.name}`:n.enumType.name),a=Y(()=>es(n.snapshot,n.enumType.name));return(t,n)=>(U(),W(`article`,tl,[G(`header`,nl,[G(`div`,rl,[G(`h2`,il,O(i.value),1),e.enumType.synthesized?(U(),W(`span`,al,`synthesized`)):q(``,!0)]),K(el,{"model-value":e.enumType.note??``,readonly:``,translate:e.translate},null,8,[`model-value`,`translate`])]),G(`section`,null,[G(`h3`,ol,O(e.translate(`docs.enumValues`)),1),G(`ul`,sl,[(U(!0),W(V,null,R(e.enumType.values,e=>(U(),W(`li`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground`},O(e),1))),128))])]),G(`section`,null,[G(`h3`,cl,O(e.translate(`docs.usedBy`)),1),a.value.length===0?(U(),W(`p`,ll,`No column uses this enum.`)):(U(),W(`ul`,ul,[(U(!0),W(V,null,R(a.value,e=>(U(),W(`li`,{key:`${e.tableKey}.${e.column}`,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left font-mono transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,e.tableKey)},O(e.tableKey)+`.`+O(e.column),9,dl)]))),128))]))])]))}}),pl={class:`flex flex-col gap-3`},ml={class:`flex flex-col gap-1`},hl={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},gl=[`value`,`placeholder`],_l={class:`flex flex-col gap-2`},vl={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},yl={class:`flex items-center gap-1.5`},bl=[`title`,`onClick`],xl=[`value`,`title`],Sl={class:`grid grid-cols-2 gap-2`},Cl={class:`docs-ground-light flex items-center gap-2 overflow-hidden rounded border border-border bg-white p-2`},wl={class:`dark flex items-center gap-2 overflow-hidden rounded border border-border bg-neutral-900 p-2`},Tl={class:`flex justify-end`},El=L({__name:`GroupEditor`,props:{group:{},translate:{type:Function}},emits:[`update:group`,`delete`],setup(e,{emit:t}){let n=e,r=t,i=Array.from({length:12},(e,t)=>t*30);function a(e){r(`update:group`,{...n.group,name:e.target.value})}function o(e){r(`update:group`,{...n.group,hue:e})}function s(e){o(Number(e.target.value))}function c(e){return`${n.translate(`docs.groupColour`)} ${e}°`}return(t,n)=>(U(),W(`div`,pl,[G(`label`,ml,[G(`span`,hl,O(e.translate(`docs.groupName`)),1),G(`input`,{type:`text`,value:e.group.name,placeholder:e.translate(`docs.groupName`),class:`rounded border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus:border-ring`,onInput:n[0]||=e=>a(e)},null,40,gl)]),G(`div`,_l,[G(`span`,vl,O(e.translate(`docs.groupColour`)),1),G(`div`,yl,[(U(!0),W(V,null,R(F(i),t=>(U(),W(`button`,{key:t,type:`button`,class:D([`docs-group h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105`,e.group.hue===t?`ring-2 ring-ring ring-offset-2`:`border-border`]),style:E([{"background-color":`var(--group-c)`},F(Ho)(t)]),title:c(t),onClick:e=>o(t)},null,14,bl))),128))]),G(`input`,{type:`range`,min:`0`,max:`359`,value:e.group.hue,class:`w-full`,title:c(e.group.hue),onInput:n[1]||=e=>s(e)},null,40,xl),G(`div`,Sl,[G(`div`,Cl,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Ho)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Ho)(e.group.hue)])},O(e.group.name),5)]),G(`div`,wl,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Ho)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Ho)(e.group.hue)])},O(e.group.name),5)])])]),G(`div`,Tl,[G(`button`,{type:`button`,class:`rounded border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[2]||=t=>r(`delete`,e.group.id)},O(e.translate(`docs.deleteGroup`)),1)])]))}});function Dl(e,t={},n=!1){let r=Math.max(1,t.columnsPerRow??Math.ceil(Math.sqrt(Math.max(e.length,1)))),i=t.cardWidth??260,a=t.gapX??56,o=t.gapY??40,s=t.margin??40,c=t.rowHeight,l=e=>c??44+(e.columns?.length??0)*24+12,u={},d=s;for(let t=0;t<e.length;t+=r){let c=e.slice(t,t+r),f=Math.max(...c.map(l));c.forEach((e,t)=>{let r={x:s+t*(i+a),y:d};u[e.name]=r,n&&e.schema&&(u[`${e.schema}.${e.name}`]=r)}),d+=f+o}return u}function Ol(e,t,n){let r=t.x-e.x,i=t.y-e.y;if(r===0&&i===0)return{x:e.x,y:e.y};let a=r===0?1/0:n.width/Math.abs(r),o=i===0?1/0:n.height/Math.abs(i),s=Math.min(a,o);return{x:e.x+r*s,y:e.y+i*s}}var kl={class:`overflow-auto`},Al=[`width`,`height`,`viewBox`],jl=[`x1`,`y1`,`x2`,`y2`],Ml=[`x`,`y`,`onClick`],Nl=[`x`,`y`],Pl=[`x`,`y`],Fl=260,Il=220,Ll=40,Rl=8,zl=L({__name:`SchemaDiagram`,props:{snapshot:{}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i={width:Fl/2,height:Il/2},a=Y(()=>Dl(n.snapshot.tables.map(e=>({name:X(e),columns:e.columns})))),o=Y(()=>new Map(n.snapshot.groups.map(e=>[e.id,e]))),s=Y(()=>n.snapshot.tables.map(e=>{let t=X(e),n=a.value[t]??{x:Ll,y:Ll},r=e.groupId?o.value.get(e.groupId)??null:null;return{key:t,x:n.x,y:n.y,hue:r?.hue??null,columns:e.columns.slice(0,Rl).map(e=>e.name)}}));function c(e){let t=a.value[e]??{x:Ll,y:Ll};return{x:t.x+Fl/2,y:t.y+Il/2}}let l=Y(()=>{let e=new Set(Object.keys(a.value));return n.snapshot.relationships.map(e=>({relationship:e,fromKey:X({schema:e.from.schema,name:e.from.table}),toKey:X({schema:e.to.schema,name:e.to.table})})).filter(({fromKey:t,toKey:n})=>e.has(t)&&e.has(n)).map(({relationship:e,fromKey:t,toKey:n})=>{let r=c(t),a=c(n);return{id:e.id,from:Ol(r,a,i),to:Ol(a,r,i)}})}),u=Y(()=>Math.max(0,...s.value.map(e=>e.x+Fl))+Ll),d=Y(()=>Math.max(0,...s.value.map(e=>e.y+Il))+Ll);function f(e){return e===null?{}:{...Ho(e),fill:`var(--group-tint)`}}return(e,t)=>(U(),W(`div`,kl,[(U(),W(`svg`,{width:u.value,height:d.value,viewBox:`0 0 ${u.value} ${d.value}`,class:`block`},[(U(!0),W(V,null,R(l.value,e=>(U(),W(`line`,{key:e.id,x1:e.from.x,y1:e.from.y,x2:e.to.x,y2:e.to.y,class:`stroke-border`,"stroke-width":`1.5`},null,8,jl))),128)),(U(!0),W(V,null,R(s.value,e=>(U(),W(`g`,{key:e.key},[G(`rect`,{x:e.x,y:e.y,width:Fl,height:Il,rx:`6`,class:D([`cursor-pointer stroke-border`,e.hue===null?`fill-card`:`docs-group`]),style:E(f(e.hue)),"stroke-width":`1`,onClick:t=>r(`select`,e.key)},null,14,Ml),G(`text`,{x:e.x+10,y:e.y+22,class:`pointer-events-none fill-foreground font-mono text-[11px] font-semibold`},O(e.key),9,Nl),(U(!0),W(V,null,R(e.columns,(t,n)=>(U(),W(`text`,{key:t,x:e.x+10,y:e.y+42+n*18,class:`pointer-events-none fill-muted-foreground font-mono text-[10px]`},O(t),9,Pl))),128))]))),128))],8,Al))]))}}),Bl={class:`overflow-hidden rounded-md border border-border`},Vl={class:`w-full text-xs`},Hl={class:`bg-muted/30`},Ul={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},Wl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},Gl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},Kl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},ql={class:`px-2 py-1.5 font-mono font-medium text-foreground`},Jl={class:`px-2 py-1.5 font-mono text-muted-foreground`},Yl={class:`px-2 py-1.5`},Xl={class:`flex flex-wrap gap-1`},Zl={class:`px-2 py-1.5 text-muted-foreground`},Ql={class:`flex items-start gap-1`},$l=[`title`],eu=L({__name:`ColumnTable`,props:{columns:{},columnNotes:{},tableKey:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`edit`],setup(e,{emit:t}){let n=e,r=t;function i(e){let t=e.data_type.trim();if(t.includes(`(`))return t;if(e.character_maximum_length!==null)return`${t}(${e.character_maximum_length})`;if(e.numeric_precision!==null){let n=e.numeric_scale===null?``:`,${e.numeric_scale}`;return`${t}(${e.numeric_precision}${n})`}return t}function a(e){let t=[];return e.is_primary_key&&t.push(`pk`),e.is_nullable||t.push(`not null`),e.column_default!==null&&t.push(`default: ${e.column_default}`),e.extra!==null&&e.extra!==``&&t.push(e.extra),e.enum_values!==void 0&&e.enum_values.length>0&&t.push(`enum: ${e.enum_values.join(`, `)}`),t}function o(e){return n.columnNotes[e.name]??null}function s(e){let t=o(e)?.shadowed;return t?`Database comment: ${t}`:void 0}return(t,n)=>(U(),W(`div`,Bl,[G(`table`,Vl,[G(`thead`,null,[G(`tr`,Hl,[G(`th`,Ul,O(e.translate(`docs.columnHeader`)),1),G(`th`,Wl,O(e.translate(`docs.typeHeader`)),1),G(`th`,Gl,O(e.translate(`docs.settingsHeader`)),1),G(`th`,Kl,O(e.translate(`docs.noteHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.columns,t=>(U(),W(`tr`,{key:t.name,class:`border-t border-border align-top`},[G(`td`,ql,O(t.name),1),G(`td`,Jl,O(i(t)),1),G(`td`,Yl,[G(`div`,Xl,[(U(!0),W(V,null,R(a(t),e=>(U(),W(`span`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] text-muted-foreground`},O(e),1))),128))])]),G(`td`,Zl,[G(`div`,Ql,[o(t)?.source===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium`,title:s(t)},`⬤ `+O(e.translate(`docs.localNote`)),9,$l)):q(``,!0),K(el,{class:`min-w-0 flex-1`,"model-value":o(t)?.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n=>r(`edit`,{kind:`columnNote`,tableKey:e.tableKey,column:t.name,note:n})},null,8,[`model-value`,`readonly`,`translate`,`onUpdate:modelValue`])])])]))),128))])])]))}}),tu={class:`flex items-center gap-1.5`},nu=[`value`],ru={value:``},iu=[`value`],au=`__dbx_new_group__`,ou=L({__name:`GroupPicker`,props:{groups:{},modelValue:{},translate:{type:Function}},emits:[`update:modelValue`,`create`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.groups.find(e=>e.id===n.modelValue)??null);function a(e){let t=e.target;t.value===au&&!n.groups.some(e=>e.id===au)?(t.value=n.modelValue??``,r(`create`)):r(`update:modelValue`,t.value===``?null:t.value)}return(t,n)=>(U(),W(`div`,tu,[i.value?(U(),W(`span`,{key:0,class:`docs-group h-3 w-3 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Ho)(i.value.hue)])},null,4)):q(``,!0),G(`select`,{value:e.modelValue??``,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground outline-none focus:border-ring`,onChange:n[0]||=e=>a(e)},[G(`option`,ru,O(e.translate(`docs.noGroup`)),1),(U(!0),W(V,null,R(e.groups,e=>(U(),W(`option`,{key:e.id,value:e.id},O(e.name),9,iu))),128)),G(`option`,{value:au},O(e.translate(`docs.newGroup`)),1)],40,nu)]))}}),su={class:`grid gap-4 sm:grid-cols-2`},cu={class:`mb-1.5 text-xs font-medium text-muted-foreground`},lu={key:0,class:`text-xs text-muted-foreground`},uu={key:1,class:`flex flex-col gap-1`},du=[`onClick`],fu={class:`font-mono`},pu={class:`mx-1.5 text-muted-foreground`},mu={class:`font-mono`},hu={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},gu={class:`mb-1.5 text-xs font-medium text-muted-foreground`},_u={key:0,class:`text-xs text-muted-foreground`},vu={key:1,class:`flex flex-col gap-1`},yu=[`onClick`],bu={class:`font-mono`},xu={class:`mx-1.5 text-muted-foreground`},Su={class:`font-mono`},Cu={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},wu=L({__name:`RelationshipList`,props:{relationships:{},schema:{},table:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t;function i(e){return e.table===n.table&&(e.schema??null)===n.schema}function a(e){return X({schema:e.schema,name:e.table})}function o(e){return`${a(e)}.${e.column}`}function s(e){return e.cardinality===`ONE_TO_ONE`?`1 – 1`:`* – 1`}function c(e){let t=[];return e.onUpdate&&t.push(`on update ${e.onUpdate}`),e.onDelete&&t.push(`on delete ${e.onDelete}`),t}let l=Y(()=>n.relationships.filter(e=>i(e.from))),u=Y(()=>n.relationships.filter(e=>i(e.to)));return(t,n)=>(U(),W(`div`,su,[G(`section`,null,[G(`h4`,cu,O(e.translate(`docs.references`))+` (`+O(l.value.length)+`)`,1),l.value.length===0?(U(),W(`p`,lu,O(e.translate(`docs.noOutgoingRelationships`)),1)):(U(),W(`ul`,uu,[(U(!0),W(V,null,R(l.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.to))},[G(`span`,fu,O(e.from.column),1),G(`span`,pu,O(s(e)),1),G(`span`,mu,O(o(e.to)),1),c(e).length>0?(U(),W(`span`,hu,O(c(e).join(`, `)),1)):q(``,!0)],8,du)]))),128))]))]),G(`section`,null,[G(`h4`,gu,O(e.translate(`docs.referencedBy`))+` (`+O(u.value.length)+`)`,1),u.value.length===0?(U(),W(`p`,_u,O(e.translate(`docs.noIncomingRelationships`)),1)):(U(),W(`ul`,vu,[(U(!0),W(V,null,R(u.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.from))},[G(`span`,bu,O(o(e.from)),1),G(`span`,xu,O(s(e)),1),G(`span`,Su,O(e.to.column),1),c(e).length>0?(U(),W(`span`,Cu,O(c(e).join(`, `)),1)):q(``,!0)],8,yu)]))),128))]))])]))}}),Tu={class:`flex flex-col gap-5`},Eu={class:`flex flex-col gap-2`},Du={class:`flex flex-wrap items-center gap-2`},Ou={class:`font-mono text-lg font-semibold text-foreground`},ku={class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},Au={key:1,class:`text-[10px] text-muted-foreground`},ju={class:`flex items-start gap-2`},Mu=[`title`],Nu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Pu={key:0},Fu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Iu={class:`overflow-hidden rounded-md border border-border`},Lu={class:`w-full text-xs`},Ru={class:`bg-muted/30`},zu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},Bu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},Vu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},Hu={class:`px-2 py-1.5 font-mono`},Uu={class:`px-2 py-1.5 font-mono text-muted-foreground`},Wu={class:`px-2 py-1.5`},Gu={class:`flex flex-wrap gap-1 text-[10px] text-muted-foreground`},Ku={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5`},qu={key:1,class:`rounded bg-muted/50 px-1.5 py-0.5`},Ju={key:2,class:`rounded bg-muted/50 px-1.5 py-0.5`},Yu={key:3,class:`rounded bg-muted/50 px-1.5 py-0.5`},Xu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Zu={key:1},Qu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},$u={class:`overflow-x-auto rounded-md border border-border bg-muted/20 p-2 font-mono text-xs`},ed=L({__name:`TablePage`,props:{table:{},relationships:{},group:{},annotationGroups:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`select`,`edit`,`createGroup`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>X(n.table)),a=Y(()=>n.table.kind.toLowerCase().replace(/_/g,` `)),o=Y(()=>n.table.shadowedNote?`Database comment: ${n.table.shadowedNote}`:void 0);return(t,n)=>(U(),W(`article`,Tu,[G(`header`,Eu,[G(`div`,Du,[G(`h2`,Ou,O(i.value),1),G(`span`,ku,O(a.value),1),e.group?(U(),W(`span`,{key:0,class:`docs-group rounded px-1.5 py-0.5 text-[10px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Ho)(e.group.hue)])},O(e.group.name),5)):q(``,!0),e.table.estimatedRows===null?q(``,!0):(U(),W(`span`,Au,` ~`+O(e.table.estimatedRows)+` rows `,1))]),G(`div`,ju,[e.table.noteSource===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium text-muted-foreground`,title:o.value},`⬤ `+O(e.translate(`docs.localNote`)),9,Mu)):q(``,!0),K(el,{class:`min-w-0 flex-1`,"model-value":e.table.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n[0]||=e=>r(`edit`,{kind:`tableNote`,tableKey:i.value,note:e})},null,8,[`model-value`,`readonly`,`translate`])]),e.readonly?q(``,!0):(U(),Vi(ou,{key:0,groups:e.annotationGroups,"model-value":e.table.groupId,translate:e.translate,"onUpdate:modelValue":n[1]||=e=>r(`edit`,{kind:`tableGroup`,tableKey:i.value,groupId:e}),onCreate:n[2]||=e=>r(`createGroup`,i.value)},null,8,[`groups`,`model-value`,`translate`]))]),G(`section`,null,[G(`h3`,Nu,O(e.translate(`docs.columns`)),1),K(eu,{columns:e.table.columns,"column-notes":e.table.columnNotes,"table-key":i.value,readonly:e.readonly,translate:e.translate,onEdit:n[3]||=e=>r(`edit`,e)},null,8,[`columns`,`column-notes`,`table-key`,`readonly`,`translate`])]),e.table.indexes.length>0?(U(),W(`section`,Pu,[G(`h3`,Fu,O(e.translate(`docs.indexes`)),1),G(`div`,Iu,[G(`table`,Lu,[G(`thead`,null,[G(`tr`,Ru,[G(`th`,zu,O(e.translate(`docs.nameHeader`)),1),G(`th`,Bu,O(e.translate(`docs.columns`)),1),G(`th`,Vu,O(e.translate(`docs.settingsHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.table.indexes,e=>(U(),W(`tr`,{key:e.name,class:`border-t border-border align-top`},[G(`td`,Hu,O(e.name),1),G(`td`,Uu,[Yi(O(e.columns.join(`, `)),1),e.included_columns&&e.included_columns.length>0?(U(),W(V,{key:0},[Yi(` (include `+O(e.included_columns.join(`, `))+`) `,1)],64)):q(``,!0)]),G(`td`,Wu,[G(`div`,Gu,[e.is_primary?(U(),W(`span`,Ku,`pk`)):q(``,!0),e.is_unique?(U(),W(`span`,qu,`unique`)):q(``,!0),e.index_type?(U(),W(`span`,Ju,O(e.index_type),1)):q(``,!0),e.filter?(U(),W(`span`,Yu,`where `+O(e.filter),1)):q(``,!0)])])]))),128))])])])])):q(``,!0),G(`section`,null,[G(`h3`,Xu,O(e.translate(`docs.relationships`)),1),K(wu,{relationships:e.relationships,schema:e.table.schema,table:e.table.name,translate:e.translate,onSelect:n[4]||=e=>r(`select`,e)},null,8,[`relationships`,`schema`,`table`,`translate`])]),e.table.viewDefinition?(U(),W(`section`,Zu,[G(`h3`,Qu,O(e.translate(`docs.definitionHeader`)),1),G(`pre`,$u,O(e.table.viewDefinition),1)])):q(``,!0)]))}});function td(e,t){switch(e.kind){case`tableSkipped`:return{severity:`warning`,title:t(`docs.warnings.tableSkipped.title`),detail:t(`docs.warnings.tableSkipped.detail`,{table:e.table,reason:e.reason})};case`noForeignKeyMetadata`:return{severity:`info`,title:t(`docs.warnings.noForeignKeyMetadata.title`),detail:t(`docs.warnings.noForeignKeyMetadata.detail`,{engine:e.engine})};case`commentsUnsupported`:return{severity:`info`,title:t(`docs.warnings.commentsUnsupported.title`),detail:t(`docs.warnings.commentsUnsupported.detail`,{engine:e.engine})};case`orphanedNotes`:return{severity:`warning`,title:t(`docs.warnings.orphanedNotes.title`),detail:t(`docs.warnings.orphanedNotes.detail`,{count:e.count})};case`dbmlOmitted`:return{severity:`info`,title:t(`docs.warnings.dbmlOmitted.title`),detail:t(`docs.warnings.dbmlOmitted.detail`,{item:e.item,table:e.table,reason:e.reason})}}}var nd={key:0,class:`flex flex-col gap-2`},rd={class:`font-medium`},id={class:`mt-0.5 leading-relaxed`},ad=L({__name:`WarningBanner`,props:{warnings:{},translate:{type:Function}},setup(e){let t=e,n=Y(()=>t.warnings.map((e,n)=>({key:`${e.kind}-${n}`,...td(e,t.translate)})));return(e,t)=>n.value.length>0?(U(),W(`div`,nd,[(U(!0),W(V,null,R(n.value,e=>(U(),W(`div`,{key:e.key,class:D([`rounded-md border px-3 py-2 text-xs`,e.severity===`warning`?`border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200`:`border-border bg-muted/30 text-muted-foreground`])},[G(`div`,rd,O(e.title),1),G(`div`,id,O(e.detail),1)],2))),128))])):q(``,!0)}}),od={class:`flex flex-col gap-6`},sd={class:`flex items-baseline gap-2`},cd={class:`text-sm font-semibold text-foreground`},ld={class:`text-xs text-muted-foreground`},ud=[`innerHTML`],dd={class:`grid gap-1 sm:grid-cols-2 lg:grid-cols-3`},fd=[`onClick`],pd={class:`font-mono text-xs font-medium text-foreground`},md={key:0,class:`text-[10px] uppercase text-muted-foreground`},hd=[`innerHTML`],gd=L({__name:`WikiIndex`,props:{sections:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=t;return(t,r)=>(U(),W(`div`,od,[(U(!0),W(V,null,R(e.sections,t=>(U(),W(`section`,{key:t.key,class:`flex flex-col gap-2`},[G(`div`,{class:D([`flex flex-col gap-1 border-l-2 pl-3`,{"docs-group":t.hue!==null}]),style:E([{"border-color":`var(--group-c, var(--border))`},F(Ho)(t.hue)])},[G(`div`,sd,[G(`h2`,cd,O(t.label||e.translate(t.fallbackKey)),1),G(`span`,ld,O(t.tables.length)+` tables`,1)]),t.note?(U(),W(`div`,{key:0,class:`text-xs text-muted-foreground`,innerHTML:F(Zc)(t.note)},null,8,ud)):q(``,!0)],6),G(`ul`,dd,[(U(!0),W(V,null,R(t.tables,e=>(U(),W(`li`,{key:F(X)(e),class:`flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 transition-colors hover:bg-muted/40`},[G(`button`,{type:`button`,class:`flex w-full items-baseline gap-1.5 text-left`,onClick:t=>n(`select`,F(X)(e))},[G(`span`,pd,O(e.name),1),e.kind===`TABLE`?q(``,!0):(U(),W(`span`,md,O(e.kind.toLowerCase().replace(/_/g,` `)),1))],8,fd),e.note?(U(),W(`div`,{key:0,class:`line-clamp-2 text-[11px] text-muted-foreground`,innerHTML:F(Zc)(e.note)},null,8,hd)):q(``,!0)]))),128))])]))),128))]))}});function _d(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=crypto.getRandomValues(new Uint8Array(16));return e[6]=e[6]&15|64,e[8]=e[8]&63|128,Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``).replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,`$1-$2-$3-$4-$5`)}return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var vd={class:`flex h-full min-h-0 bg-background text-foreground`},yd={class:`flex h-full min-h-0 w-64 shrink-0 flex-col`},bd={class:`flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto p-4`},xd={class:`flex flex-wrap items-start justify-between gap-3`},Sd={class:`flex flex-col gap-1`},Cd={class:`text-base font-semibold`},wd={class:`text-xs text-muted-foreground`},Td={key:0,class:`flex flex-col gap-4`},Ed={key:0,class:`flex flex-col gap-2`},Dd={class:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Od=L({__name:`DocsApp`,props:{snapshot:{},annotations:{},readonly:{type:Boolean},translate:{},route:{},diagram:{default:`external`}},emits:[`edit`,`update:route`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.readonly??!1),a=Y(()=>n.annotations.groups??[]),o=P(n.snapshot.groups.length>0?`group`:`schema`),s=P(null),c=P(null),l=P(!1),u=Y(()=>n.route?n.route:l.value?{kind:`diagram`}:c.value===null?s.value===null?{kind:`index`}:{kind:`table`,key:s.value}:{kind:`enum`,name:c.value}),d=Y(()=>u.value.kind===`table`?u.value.key:null),f=Y(()=>u.value.kind===`enum`?u.value.name:null),p=Y(()=>o.value===`schema`?Qo(n.snapshot):$o(n.snapshot)),m=Y(()=>n.snapshot.tables.find(e=>X(e)===d.value)??null),h=Y(()=>f.value===null?null:n.snapshot.enums.find(e=>e.name===f.value)??null),g=Y(()=>u.value.kind===`diagram`?`diagram`:h.value===null?m.value===null?`index`:`table`:`enum`),_=Y(()=>{let e=m.value?.groupId;return e?n.snapshot.groups.find(t=>t.id===e)??null:null});function v(e){n.snapshot.tables.some(t=>X(t)===e)&&(c.value=null,l.value=!1,s.value=e,r(`update:route`,{kind:`table`,key:e}))}function y(e){n.snapshot.enums.some(t=>t.name===e)&&(s.value=null,l.value=!1,c.value=e,r(`update:route`,{kind:`enum`,name:e}))}function b(){s.value=null,c.value=null,l.value=!0,r(`update:route`,{kind:`diagram`})}function x(){s.value=null,c.value=null,l.value=!1,r(`update:route`,{kind:`index`})}function ee(e){let t={id:_d(),name:n.translate(`docs.newGroup`),hue:a.value.length*47%360};r(`edit`,{kind:`upsertGroup`,group:t}),r(`edit`,{kind:`tableGroup`,tableKey:e,groupId:t.id})}return(t,n)=>(U(),W(`div`,vd,[G(`div`,yd,[K(Xo,{class:`min-h-0 flex-1`,sections:p.value,mode:o.value,"active-key":d.value,translate:e.translate,"onUpdate:mode":n[0]||=e=>o.value=e,onSelect:v,onHome:n[1]||=e=>x()},null,8,[`sections`,`mode`,`active-key`,`translate`]),e.diagram===`inline`?(U(),W(`button`,{key:0,type:`button`,class:D([`shrink-0 border-t border-r border-border bg-background px-3 py-2 text-left text-xs font-medium transition-colors`,g.value===`diagram`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:n[2]||=e=>b()},O(e.translate(`docs.diagram`)),3)):q(``,!0)]),G(`main`,bd,[G(`header`,xd,[G(`div`,Sd,[G(`h1`,Cd,O(e.snapshot.project.name),1),G(`p`,wd,[Yi(O(e.snapshot.project.databaseType),1),e.snapshot.project.database?(U(),W(V,{key:0},[Yi(` · `+O(e.snapshot.project.database),1)],64)):q(``,!0),Yi(` · `+O(e.snapshot.tables.length)+` tables · generated `+O(e.snapshot.project.generatedAt),1)])]),K(Vo,{snapshot:e.snapshot,translate:e.translate,onSelect:v,onSelectEnum:y},null,8,[`snapshot`,`translate`])]),K(ad,{warnings:e.snapshot.warnings,translate:e.translate},null,8,[`warnings`,`translate`]),g.value===`index`?(U(),W(`div`,Td,[K(el,{"model-value":e.snapshot.project.note??``,readonly:i.value,translate:e.translate,"onUpdate:modelValue":n[3]||=e=>r(`edit`,{kind:`projectNote`,note:e})},null,8,[`model-value`,`readonly`,`translate`]),K(gd,{sections:p.value,translate:e.translate,onSelect:v},null,8,[`sections`,`translate`]),!i.value&&a.value.length>0?(U(),W(`section`,Ed,[G(`h2`,Dd,O(e.translate(`docs.groups`)),1),(U(!0),W(V,null,R(a.value,t=>(U(),Vi(El,{key:t.id,group:t,translate:e.translate,"onUpdate:group":n[4]||=e=>r(`edit`,{kind:`upsertGroup`,group:e}),onDelete:n[5]||=e=>r(`edit`,{kind:`removeGroup`,groupId:e})},null,8,[`group`,`translate`]))),128))])):q(``,!0)])):g.value===`table`&&m.value?(U(),Vi(ed,{key:1,table:m.value,relationships:e.snapshot.relationships,group:_.value,"annotation-groups":a.value,readonly:i.value,translate:e.translate,onSelect:v,onEdit:n[6]||=e=>r(`edit`,e),onCreateGroup:ee},null,8,[`table`,`relationships`,`group`,`annotation-groups`,`readonly`,`translate`])):h.value?(U(),Vi(fl,{key:2,"enum-type":h.value,snapshot:e.snapshot,translate:e.translate,onSelect:v},null,8,[`enum-type`,`snapshot`,`translate`])):g.value===`diagram`?(U(),Vi(zl,{key:3,snapshot:e.snapshot,onSelect:v},null,8,[`snapshot`])):q(``,!0)])]))}}),kd={kind:`index`};function Ad(e,t,n){if(!e.startsWith(`#`))return kd;let[r,...i]=e.slice(1).replace(/^\//,``).split(`/`),a=i.join(`/`);if(r===`diagram`&&a===``)return n?{kind:`diagram`}:kd;if(a===``)return kd;let o;try{o=decodeURIComponent(a)}catch{return kd}return r===`table`?t.tables.some(e=>X(e)===o)?{kind:`table`,key:o}:kd:r===`enum`&&(t.enums??[]).some(e=>e.name===o)?{kind:`enum`,name:o}:kd}function jd(e){switch(e.kind){case`table`:return`#/table/${encodeURIComponent(e.key)}`;case`enum`:return`#/enum/${encodeURIComponent(e.name)}`;case`diagram`:return`#/diagram`;default:return`#/`}}var Md=[{value:`en`,flag:`🇺🇸`,label:`English`},{value:`az`,flag:`🇦🇿`,label:`Azərbaycan`},{value:`es`,flag:`🇪🇸`,label:`Español`},{value:`id`,flag:`🇮🇩`,label:`Bahasa Indonesia`},{value:`it`,flag:`🇮🇹`,label:`Italiano`},{value:`ja`,flag:`🇯🇵`,label:`日本語`},{value:`ko`,flag:`🇰🇷`,label:`한국어`},{value:`pt-BR`,flag:`🇧🇷`,label:`Português`},{value:`ru`,flag:`🇷🇺`,label:`Русский`},{value:`th`,flag:`🇹🇭`,label:`ภาษาไทย`},{value:`tr`,flag:`🇹🇷`,label:`Türkçe`},{value:`zh-CN`,flag:`🇨🇳`,label:`简体中文`},{value:`zh-TW`,flag:`繁`,label:`繁體中文`}],Nd={en:{title:`Documentation`,groupBySchema:`Schemas`,groupByTableGroup:`Table Groups`,noGroup:`(no group)`,noSchema:`(no schema)`,search:`Search tables, columns, groups…`,columns:`Columns`,indexes:`Indexes`,references:`References`,referencedBy:`Referenced by`,localNote:`LOCAL`,shadowedComment:`Database comment: {comment}`,addNote:`Add a note`,editNote:`Edit note`,newGroup:`New group…`,groupName:`Group name`,groupColour:`Colour`,deleteGroup:`Delete group`,enumValues:`Values`,usedBy:`Used by`,openDiagram:`Open schema diagram`,saving:`Saving…`,saved:`Saved`,saveFailed:`Could not save notes: {error}`,overview:`Overview`,groupBy:`Group by`,searchLabel:`Search`,groups:`Groups`,relationships:`Relationships`,columnHeader:`Column`,typeHeader:`Type`,settingsHeader:`Settings`,noteHeader:`Note`,nameHeader:`Name`,definitionHeader:`Definition`,noOutgoingRelationships:`This table references no other table.`,noIncomingRelationships:`No table references this one.`,diagram:`Diagram`,language:`Language`,theme:`Theme`,themeLight:`Light`,themeDark:`Dark`,exportHtml:`Export HTML…`,exporting:`Exporting…`,exportFailed:`Could not export: {error}`,warnings:{tableSkipped:{title:`A table could not be documented`,detail:`{table} was skipped: {reason}. It is missing from this documentation.`},noForeignKeyMetadata:{title:`No relationships available`,detail:`{engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.`},commentsUnsupported:{title:`Database comments unavailable`,detail:`{engine} does not support table or column comments, so every description here comes from this project's own notes.`},orphanedNotes:{title:`Some notes no longer match anything`,detail:`{count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.`},dbmlOmitted:{title:`Not representable in DBML`,detail:`{item} on {table} is documented here but omitted from the exported DBML: {reason}.`}}},es:{title:`Documentación`,groupBySchema:`Esquemas`,groupByTableGroup:`Grupos de tablas`,noGroup:`(sin grupo)`,noSchema:`(sin esquema)`,search:`Buscar tablas, columnas, grupos…`,columns:`Columnas`,indexes:`Índices`,references:`Referencias`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentario de la base de datos: {comment}`,addNote:`Agregar una nota`,editNote:`Editar nota`,newGroup:`Nuevo grupo…`,groupName:`Nombre del grupo`,groupColour:`Color`,deleteGroup:`Eliminar grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama del esquema`,saving:`Guardando…`,saved:`Guardado`,saveFailed:`No se pudieron guardar las notas: {error}`,overview:`Información general`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relaciones`,columnHeader:`Columna`,typeHeader:`Tipo`,settingsHeader:`Configuración`,noteHeader:`Nota`,nameHeader:`Nombre`,definitionHeader:`Definición`,noOutgoingRelationships:`Esta tabla no referencia ninguna otra tabla.`,noIncomingRelationships:`Ninguna tabla referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Oscuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`No se pudo exportar: {error}`,warnings:{tableSkipped:{title:`No se pudo documentar una tabla`,detail:`{table} fue omitida: {reason}. Falta en esta documentación.`},noForeignKeyMetadata:{title:`No hay relaciones disponibles`,detail:`{engine} no reporta metadatos de claves foráneas, por lo que no se pudieron derivar relaciones. El diagrama está completo para este motor.`},commentsUnsupported:{title:`Comentarios de base de datos no disponibles`,detail:`{engine} no admite comentarios en tablas o columnas, por lo que toda descripción aquí proviene de las notas de este proyecto.`},orphanedNotes:{title:`Algunas notas ya no coinciden con nada`,detail:`{count} nota(s) hacen referencia a una tabla o columna que ya no existe. No se eliminó nada — vuelva a asignarlas o elimínelas en el archivo de notas.`},dbmlOmitted:{title:`No representable en DBML`,detail:`{item} en {table} está documentado aquí pero se omitió del DBML exportado: {reason}.`}}},it:{title:`Documentazione`,groupBySchema:`Schemi`,groupByTableGroup:`Gruppi di tabelle`,noGroup:`(nessun gruppo)`,noSchema:`(nessuno schema)`,search:`Cerca tabelle, colonne, gruppi…`,columns:`Colonne`,indexes:`Indici`,references:`Riferimenti`,referencedBy:`Referenziato da`,localNote:`LOCALE`,shadowedComment:`Commento del database: {comment}`,addNote:`Aggiungi una nota`,editNote:`Modifica nota`,newGroup:`Nuovo gruppo…`,groupName:`Nome del gruppo`,groupColour:`Colore`,deleteGroup:`Elimina gruppo`,enumValues:`Valori`,usedBy:`Usato da`,openDiagram:`Apri diagramma dello schema`,saving:`Salvataggio…`,saved:`Salvato`,saveFailed:`Impossibile salvare le note: {error}`,overview:`Panoramica`,groupBy:`Raggruppa per`,searchLabel:`Cerca`,groups:`Gruppi`,relationships:`Relazioni`,columnHeader:`Colonna`,typeHeader:`Tipo`,settingsHeader:`Impostazioni`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definizione`,noOutgoingRelationships:`Questa tabella non fa riferimento a nessun'altra tabella.`,noIncomingRelationships:`Nessuna tabella fa riferimento a questa.`,diagram:`Diagramma`,language:`Lingua`,theme:`Tema`,themeLight:`Chiaro`,themeDark:`Scuro`,exportHtml:`Esporta HTML…`,exporting:`Esportazione…`,exportFailed:`Impossibile esportare: {error}`,warnings:{tableSkipped:{title:`Impossibile documentare una tabella`,detail:`{table} è stata saltata: {reason}. Manca da questa documentazione.`},noForeignKeyMetadata:{title:`Nessuna relazione disponibile`,detail:`{engine} non riporta i metadati delle chiavi esterne, quindi non è stato possibile derivare alcuna relazione. Il diagramma è completo per questo motore.`},commentsUnsupported:{title:`Commenti del database non disponibili`,detail:`{engine} non supporta i commenti su tabelle o colonne, quindi ogni descrizione qui proviene dalle note di questo progetto.`},orphanedNotes:{title:`Alcune note non corrispondono più a nulla`,detail:`{count} nota/e fanno riferimento a una tabella o colonna che non esiste più. Nulla è stato eliminato — rimappa o rimuovi queste note nel file delle note.`},dbmlOmitted:{title:`Non rappresentabile in DBML`,detail:`{item} su {table} è documentato qui ma omesso dal DBML esportato: {reason}.`}}},ja:{title:`ドキュメント`,groupBySchema:`スキーマ`,groupByTableGroup:`テーブルグループ`,noGroup:`(グループなし)`,noSchema:`(スキーマなし)`,search:`テーブル、カラム、グループを検索…`,columns:`カラム`,indexes:`インデックス`,references:`参照`,referencedBy:`参照元`,localNote:`ローカル`,shadowedComment:`データベースのコメント: {comment}`,addNote:`メモを追加`,editNote:`メモを編集`,newGroup:`新しいグループ…`,groupName:`グループ名`,groupColour:`色`,deleteGroup:`グループを削除`,enumValues:`値`,usedBy:`使用元`,openDiagram:`スキーマ図を開く`,saving:`保存中…`,saved:`保存済み`,saveFailed:`メモを保存できませんでした: {error}`,overview:`概要`,groupBy:`グループ化`,searchLabel:`検索`,groups:`グループ`,relationships:`リレーションシップ`,columnHeader:`カラム`,typeHeader:`型`,settingsHeader:`設定`,noteHeader:`メモ`,nameHeader:`名前`,definitionHeader:`定義`,noOutgoingRelationships:`このテーブルは他のテーブルを参照していません。`,noIncomingRelationships:`このテーブルを参照しているテーブルはありません。`,diagram:`図`,language:`言語`,theme:`テーマ`,themeLight:`ライト`,themeDark:`ダーク`,exportHtml:`HTMLをエクスポート…`,exporting:`エクスポート中…`,exportFailed:`エクスポートできませんでした: {error}`,warnings:{tableSkipped:{title:`ドキュメント化できないテーブルがあります`,detail:`{table} はスキップされました: {reason}。このドキュメントには含まれていません。`},noForeignKeyMetadata:{title:`リレーションシップを表示できません`,detail:`{engine} は外部キーのメタデータを返さないため、関係線は表示されません。これはこのエンジンの仕様です。`},commentsUnsupported:{title:`データベースのコメントは利用できません`,detail:`{engine} はテーブルやカラムのコメントをサポートしていないため、ここでの説明はすべてこのプロジェクトのメモから提供されています。`},orphanedNotes:{title:`対象がなくなったメモがあります`,detail:`{count} 件のメモが、既に存在しないテーブルまたはカラムを参照しています。何も削除されていません。メモファイルで再割り当てまたは削除してください。`},dbmlOmitted:{title:`DBMLでは表現できません`,detail:`{table} の {item} はここに記載されていますが、エクスポートされたDBMLからは除外されています: {reason}。`}}},ko:{title:`문서`,groupBySchema:`스키마`,groupByTableGroup:`테이블 그룹`,noGroup:`(그룹 없음)`,noSchema:`(스키마 없음)`,search:`테이블, 컬럼, 그룹 검색…`,columns:`컬럼`,indexes:`인덱스`,references:`참조`,referencedBy:`참조된 위치`,localNote:`로컬`,shadowedComment:`데이터베이스 코멘트: {comment}`,addNote:`메모 추가`,editNote:`메모 편집`,newGroup:`새 그룹…`,groupName:`그룹 이름`,groupColour:`색상`,deleteGroup:`그룹 삭제`,enumValues:`값`,usedBy:`사용처`,openDiagram:`스키마 다이어그램 열기`,saving:`저장 중…`,saved:`저장됨`,saveFailed:`메모를 저장할 수 없습니다: {error}`,overview:`개요`,groupBy:`그룹화 기준`,searchLabel:`검색`,groups:`그룹`,relationships:`관계`,columnHeader:`컬럼`,typeHeader:`유형`,settingsHeader:`설정`,noteHeader:`메모`,nameHeader:`이름`,definitionHeader:`정의`,noOutgoingRelationships:`이 테이블은 다른 테이블을 참조하지 않습니다.`,noIncomingRelationships:`이 테이블을 참조하는 테이블이 없습니다.`,diagram:`다이어그램`,language:`언어`,theme:`테마`,themeLight:`라이트`,themeDark:`다크`,exportHtml:`HTML 내보내기…`,exporting:`내보내는 중…`,exportFailed:`내보낼 수 없습니다: {error}`,warnings:{tableSkipped:{title:`문서화할 수 없는 테이블이 있습니다`,detail:`{table} 을(를) 건너뛰었습니다: {reason}. 이 문서에서 누락되었습니다.`},noForeignKeyMetadata:{title:`표시할 관계가 없습니다`,detail:`{engine} 은(는) 외래 키 메타데이터를 보고하지 않으므로 관계를 도출할 수 없습니다. 이 엔진에 대해서는 다이어그램이 완전합니다.`},commentsUnsupported:{title:`데이터베이스 코멘트를 사용할 수 없습니다`,detail:`{engine} 은(는) 테이블 또는 컬럼 코멘트를 지원하지 않으므로 여기의 모든 설명은 이 프로젝트의 메모에서만 제공됩니다.`},orphanedNotes:{title:`더 이상 일치하는 대상이 없는 메모가 있습니다`,detail:`{count} 개의 메모가 더 이상 존재하지 않는 테이블 또는 컬럼을 참조하고 있습니다. 삭제된 항목은 없습니다 — 메모 파일에서 다시 매핑하거나 제거하세요.`},dbmlOmitted:{title:`DBML로 표현할 수 없습니다`,detail:`{table} 의 {item} 은(는) 여기에 문서화되어 있지만 내보낸 DBML에서는 제외되었습니다: {reason}.`}}},"pt-BR":{title:`Documentação`,groupBySchema:`Schemas`,groupByTableGroup:`Grupos de tabelas`,noGroup:`(sem grupo)`,noSchema:`(sem schema)`,search:`Buscar tabelas, colunas, grupos…`,columns:`Colunas`,indexes:`Índices`,references:`Referências`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentário do banco de dados: {comment}`,addNote:`Adicionar uma nota`,editNote:`Editar nota`,newGroup:`Novo grupo…`,groupName:`Nome do grupo`,groupColour:`Cor`,deleteGroup:`Excluir grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama do schema`,saving:`Salvando…`,saved:`Salvo`,saveFailed:`Não foi possível salvar as notas: {error}`,overview:`Visão geral`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relacionamentos`,columnHeader:`Coluna`,typeHeader:`Tipo`,settingsHeader:`Configurações`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definição`,noOutgoingRelationships:`Esta tabela não referencia nenhuma outra tabela.`,noIncomingRelationships:`Nenhuma tabela referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Escuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`Não foi possível exportar: {error}`,warnings:{tableSkipped:{title:`Uma tabela não pôde ser documentada`,detail:`{table} foi ignorada: {reason}. Ela está faltando nesta documentação.`},noForeignKeyMetadata:{title:`Nenhum relacionamento disponível`,detail:`{engine} não reporta metadados de foreign key, então nenhum relacionamento pôde ser derivado. O diagrama está completo para este engine.`},commentsUnsupported:{title:`Comentários do banco de dados indisponíveis`,detail:`{engine} não suporta comentários em tabelas ou colunas, então toda descrição aqui vem apenas das notas deste projeto.`},orphanedNotes:{title:`Algumas notas não correspondem mais a nada`,detail:`{count} nota(s) referenciam uma tabela ou coluna que não existe mais. Nada foi excluído — remapeie ou remova essas notas no arquivo de notas.`},dbmlOmitted:{title:`Não representável em DBML`,detail:`{item} em {table} está documentado aqui mas foi omitido do DBML exportado: {reason}.`}}},"zh-CN":{title:`文档`,groupBySchema:`Schema`,groupByTableGroup:`表分组`,noGroup:`(无分组)`,noSchema:`(无 Schema)`,search:`搜索表、列、分组…`,columns:`列`,indexes:`索引`,references:`引用`,referencedBy:`被引用`,localNote:`本地`,shadowedComment:`数据库注释: {comment}`,addNote:`添加备注`,editNote:`编辑备注`,newGroup:`新建分组…`,groupName:`分组名称`,groupColour:`颜色`,deleteGroup:`删除分组`,enumValues:`值`,usedBy:`被使用于`,openDiagram:`打开 Schema 图`,saving:`保存中…`,saved:`已保存`,saveFailed:`无法保存备注: {error}`,overview:`概览`,groupBy:`分组方式`,searchLabel:`搜索`,groups:`分组`,relationships:`关系`,columnHeader:`列`,typeHeader:`类型`,settingsHeader:`设置`,noteHeader:`备注`,nameHeader:`名称`,definitionHeader:`定义`,noOutgoingRelationships:`此表未引用任何其他表。`,noIncomingRelationships:`没有表引用此表。`,diagram:`图`,language:`语言`,theme:`主题`,themeLight:`浅色`,themeDark:`深色`,exportHtml:`导出 HTML…`,exporting:`导出中…`,exportFailed:`无法导出: {error}`,warnings:{tableSkipped:{title:`有一张表无法生成文档`,detail:`{table} 被跳过: {reason}。此文档中缺少该表。`},noForeignKeyMetadata:{title:`没有可用的关系`,detail:`{engine} 不报告外键元数据,因此无法推导出任何关系。此图对该数据库引擎而言已经完整。`},commentsUnsupported:{title:`数据库注释不可用`,detail:`{engine} 不支持表或列注释,因此这里的所有描述均仅来自本项目的备注。`},orphanedNotes:{title:`部分备注已不再对应任何内容`,detail:`{count} 条备注引用的表或列已不存在。没有任何内容被删除 — 请在备注文件中重新映射或移除它们。`},dbmlOmitted:{title:`无法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此处记录,但已从导出的 DBML 中省略: {reason}。`}}},"zh-TW":{title:`文件`,groupBySchema:`Schema`,groupByTableGroup:`資料表分組`,noGroup:`(無分組)`,noSchema:`(無 Schema)`,search:`搜尋資料表、欄位、分組…`,columns:`欄位`,indexes:`索引`,references:`參照`,referencedBy:`被參照`,localNote:`本機`,shadowedComment:`資料庫註解: {comment}`,addNote:`新增備註`,editNote:`編輯備註`,newGroup:`新增分組…`,groupName:`分組名稱`,groupColour:`顏色`,deleteGroup:`刪除分組`,enumValues:`值`,usedBy:`被使用於`,openDiagram:`開啟 Schema 圖`,saving:`儲存中…`,saved:`已儲存`,saveFailed:`無法儲存備註: {error}`,overview:`總覽`,groupBy:`分組方式`,searchLabel:`搜尋`,groups:`分組`,relationships:`關聯`,columnHeader:`欄位`,typeHeader:`類型`,settingsHeader:`設定`,noteHeader:`備註`,nameHeader:`名稱`,definitionHeader:`定義`,noOutgoingRelationships:`此資料表未參照任何其他資料表。`,noIncomingRelationships:`沒有資料表參照此資料表。`,diagram:`圖表`,language:`語言`,theme:`主題`,themeLight:`淺色`,themeDark:`深色`,exportHtml:`匯出 HTML…`,exporting:`匯出中…`,exportFailed:`無法匯出: {error}`,warnings:{tableSkipped:{title:`有一張資料表無法產生文件`,detail:`{table} 被略過: {reason}。此文件中缺少該資料表。`},noForeignKeyMetadata:{title:`沒有可用的關聯`,detail:`{engine} 未回報外鍵中繼資料,因此無法推導出任何關聯。此圖對該資料庫引擎而言已經完整。`},commentsUnsupported:{title:`資料庫註解無法使用`,detail:`{engine} 不支援資料表或欄位註解,因此這裡的所有說明均僅來自本專案的備註。`},orphanedNotes:{title:`部分備註已不再對應任何內容`,detail:`{count} 筆備註參照的資料表或欄位已不存在。沒有任何內容被刪除 — 請在備註檔案中重新對應或移除它們。`},dbmlOmitted:{title:`無法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此處記錄,但已從匯出的 DBML 中省略: {reason}。`}}}};function Pd(e,t){let n=t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e);return typeof n==`string`?n:null}function Fd(e){let t=Nd[e]??Nd.en;return(e,n)=>{let r=e.startsWith(`docs.`)?e.slice(5):e,i=Pd(t,r)??Pd(Nd.en,r);return i===null?e:n?i.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):i}}var Id={class:`flex h-full min-h-0 flex-col bg-background text-foreground`},Ld={class:`flex shrink-0 flex-wrap items-center justify-end gap-4 border-b border-border px-4 py-2`},Rd={class:`flex items-center gap-2 text-xs text-muted-foreground`},zd={value:`light`},Bd={value:`dark`},Vd={class:`flex items-center gap-2 text-xs text-muted-foreground`},Hd=[`value`],Ud=L({__name:`ExportApp`,props:{payload:{}},setup(e){let t=e,n=P(t.payload.lang in Nd?t.payload.lang:`en`),r=Y(()=>Fd(n.value)),i=Md.filter(e=>e.value in Nd),a=P(typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`);Bn(a,e=>{let t=document.documentElement;t.classList.toggle(`dark`,e===`dark`),t.style.colorScheme=e},{immediate:!0}),Bn(n,e=>{document.documentElement.lang=e},{immediate:!0});let o=P(Ad(location.hash,t.payload.snapshot,!0));function s(){o.value=Ad(location.hash,t.payload.snapshot,!0)}function c(e){o.value=e;let t=jd(e);location.hash!==t&&(location.hash=t)}return dr(()=>window.addEventListener(`hashchange`,s)),mr(()=>window.removeEventListener(`hashchange`,s)),(t,s)=>(U(),W(`div`,Id,[G(`div`,Ld,[G(`label`,Rd,[Yi(O(r.value(`docs.theme`))+` `,1),Pn(G(`select`,{"onUpdate:modelValue":s[0]||=e=>a.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[G(`option`,zd,O(r.value(`docs.themeLight`)),1),G(`option`,Bd,O(r.value(`docs.themeDark`)),1)],512),[[go,a.value]])]),G(`label`,Vd,[Yi(O(r.value(`docs.language`))+` `,1),Pn(G(`select`,{"onUpdate:modelValue":s[1]||=e=>n.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[(U(!0),W(V,null,R(F(i),e=>(U(),W(`option`,{key:e.value,value:e.value},O(e.label),9,Hd))),128))],512),[[go,n.value]])])]),K(Od,{class:`min-h-0 flex-1`,snapshot:e.payload.snapshot,annotations:e.payload.annotations,readonly:!0,translate:r.value,route:o.value,diagram:`inline`,"onUpdate:route":c},null,8,[`snapshot`,`annotations`,`translate`,`route`])]))}});function Wd(){let e=document.querySelector(`script[type='application/dbx-snapshot']`);if(e===null)throw Error(`no <script type='application/dbx-snapshot'> in this document`);let t=atob((e.textContent??``).trim()),n=Uint8Array.from(t,e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}try{Oo(Ud,{payload:Wd()}).mount(`#app`)}catch(e){let t=document.createElement(`p`);t.style.cssText=`margin:2rem;font-family:system-ui,sans-serif`,t.textContent=`This documentation file could not be read: ${e instanceof Error?e.message:String(e)}`,document.querySelector(`#app`)?.replaceChildren(t)}})();
\ No newline at end of file
diff --git a/crates/dbx-core/assets/docs-export.manifest.json b/crates/dbx-core/assets/docs-export.manifest.json
index 287585995c..f76b87de90 100644
--- a/crates/dbx-core/assets/docs-export.manifest.json
+++ b/crates/dbx-core/assets/docs-export.manifest.json
@@ -44,10 +44,10 @@
"apps/desktop/vite.docs-export.config.ts": "833bc2cbd99f9c0740cbc1584640458492bad75c9518db4d1ce0edd6958881ec"
},
"deps": {
- "@vue/reactivity": "3.5.35",
- "@vue/runtime-core": "3.5.35",
- "@vue/runtime-dom": "3.5.35",
- "@vue/shared": "3.5.35",
- "marked": "18.0.4"
+ "@vue/reactivity": "3.5.44",
+ "@vue/runtime-core": "3.5.44",
+ "@vue/runtime-dom": "3.5.44",
+ "@vue/shared": "3.5.44",
+ "marked": "18.1.1"
}
}
diff --git a/crates/dbx-core/src/data/docs/dbml.rs b/crates/dbx-core/src/data/docs/dbml.rs
index 6df6a0bed9..8a3d18ed55 100644
--- a/crates/dbx-core/src/data/docs/dbml.rs
+++ b/crates/dbx-core/src/data/docs/dbml.rs
@@ -591,6 +591,9 @@ mod tests {
#[test]
fn renders_an_indexes_block() {
let index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_user_placed".to_string(),
columns: vec!["user_id".to_string(), "placed_at".to_string()],
is_unique: false,
@@ -617,6 +620,9 @@ mod tests {
#[test]
fn a_unique_index_carries_the_unique_setting() {
let index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "uq_orders_ref".to_string(),
columns: vec!["reference".to_string()],
is_unique: true,
@@ -639,6 +645,9 @@ mod tests {
#[test]
fn the_primary_key_index_is_skipped_because_columns_already_carry_pk() {
let index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "orders_pkey".to_string(),
columns: vec!["id".to_string()],
is_unique: true,
@@ -664,6 +673,9 @@ mod tests {
#[test]
fn a_filtered_index_is_omitted_and_warned_about() {
let index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_open".to_string(),
columns: vec!["status".to_string()],
is_unique: false,
@@ -869,6 +881,9 @@ mod tests {
#[test]
fn warnings_from_table_rendering_reach_the_output() {
let index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_partial".to_string(),
columns: vec!["status".to_string()],
is_unique: false,
diff --git a/crates/dbx-core/src/data/docs/relations.rs b/crates/dbx-core/src/data/docs/relations.rs
index c23fd17b67..8244424c5b 100644
--- a/crates/dbx-core/src/data/docs/relations.rs
+++ b/crates/dbx-core/src/data/docs/relations.rs
@@ -185,6 +185,9 @@ mod tests {
fn unique_index(name: &str, columns: &[&str]) -> IndexInfo {
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.to_string(),
columns: columns.iter().map(|c| c.to_string()).collect(),
is_unique: true,
diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rs
index 0ab8b64e6f..2282b0fb52 100644
--- a/crates/dbx-core/src/data/transfer.rs
+++ b/crates/dbx-core/src/data/transfer.rs
@@ -2061,7 +2061,10 @@ fn h2_writable_transfer_columns(
if *mode == TransferMode::Upsert
&& target.is_some_and(|target| is_postgres_generated_always_identity_extra(target.extra.as_deref()))
{
- return Err(format!("H2 Upsert cannot assign GENERATED ALWAYS identity column '{}'. Use append/overwrite or change the target column to GENERATED BY DEFAULT.", source.name));
+ return Err(format!(
+ "H2 Upsert cannot assign GENERATED ALWAYS identity column '{}'. Use append/overwrite or change the target column to GENERATED BY DEFAULT.",
+ source.name
+ ));
}
columns.push(source.clone());
}
@@ -13841,7 +13844,14 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
let columns = vec!["ID".into(), "PART".into(), "NAME".into()];
let rows = vec![vec![json!(1), json!(1), json!("o'clock")], vec![json!(1), json!(2), json!(null)]];
assert_eq!(
- generate_upsert(&columns, &rows, "ITEMS", "TransferTarget", &DatabaseType::H2, &["ID".into(), "PART".into()]),
+ generate_upsert(
+ &columns,
+ &rows,
+ "ITEMS",
+ "TransferTarget",
+ &DatabaseType::H2,
+ &["ID".into(), "PART".into()]
+ ),
"MERGE INTO \"TransferTarget\".\"ITEMS\" (\"ID\", \"PART\", \"NAME\") KEY (\"ID\", \"PART\") VALUES\n(1, 1, 'o''clock'),\n(1, 2, NULL)"
);
assert_eq!(
@@ -17514,7 +17524,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
for source_schema in ["sales#old", "o'connor", "we]ird", "other[src", "we--ird", "we/*ird", "雪#'[]"] {
let source_identifier = format!("[{}]", source_schema.replace(']', "]]"));
let source_literal = format!("N'{}'", source_schema.replace('\'', "''"));
- let ddl = format!("CREATE TABLE {source_identifier}.[t] ([id] int);\nEXEC sys.sp_addextendedproperty @name=N'MS_Description', @value={source_literal}, @level0type=N'SCHEMA', @level0name={source_literal}, @level1type=N'TABLE', @level1name=N't';");
+ let ddl = format!(
+ "CREATE TABLE {source_identifier}.[t] ([id] int);\nEXEC sys.sp_addextendedproperty @name=N'MS_Description', @value={source_literal}, @level0type=N'SCHEMA', @level0name={source_literal}, @level1type=N'TABLE', @level1name=N't';"
+ );
let rewritten = rewrite_sqlserver_bracketed_schema_qualifier(&ddl, source_schema, "dst");
let expected = ddl
.replace(&format!("CREATE TABLE {source_identifier}."), "CREATE TABLE [dst].")
@@ -18815,6 +18827,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_generates_index_and_foreign_key_sql() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_name_idx".to_string(),
columns: vec!["lower(name)".to_string()],
is_unique: false,
@@ -18870,6 +18885,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_index_ddl_includes_opclass_for_gin_trigram() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_name_trgm_idx".to_string(),
columns: vec!["name".to_string()],
is_unique: false,
@@ -18898,6 +18916,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
// (`syntax error at or near "NOT"`), so the transfer must fall back to the
// plain form there (issue #8853).
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_name_idx".to_string(),
columns: vec!["name".to_string(), "status".to_string()],
is_unique: false,
@@ -18933,6 +18954,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_index_ddl_no_opclass_when_all_default() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_name_idx".to_string(),
columns: vec!["name".to_string(), "status".to_string()],
is_unique: false,
@@ -18964,6 +18988,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
// `indclass` into `column_opclasses`, so transfer DDL must append it to an
// expression key just like a real column.
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_lower_email_idx".to_string(),
columns: vec!["lower(email)".to_string()],
is_unique: false,
@@ -18990,6 +19017,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_index_ddl_mixed_opclass_and_default() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_name_status_idx".to_string(),
columns: vec!["name".to_string(), "status".to_string()],
is_unique: false,
@@ -19015,6 +19045,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_index_ddl_preserves_per_key_ordering_and_include_columns() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "event_order_idx".to_string(),
columns: vec![
"created_at".to_string(),
@@ -19045,6 +19078,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_index_ddl_ignores_access_method_options_for_non_btree_indexes() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "events_payload_idx".to_string(),
columns: vec!["payload".to_string()],
is_unique: false,
@@ -19071,6 +19107,9 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn postgres_index_ddl_empty_column_opclasses_vec_falls_back_to_no_opclass() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_name_idx".to_string(),
columns: vec!["name".to_string()],
is_unique: false,
@@ -20753,7 +20792,10 @@ SELECT 1 FROM dual"#
"target_db",
true,
);
- assert_eq!(sql, "INSERT INTO `target_db`.`events` (`id`, `numbers`, `tags`) SELECT `id`, `numbers`, `tags` FROM `source_db`.`events`");
+ assert_eq!(
+ sql,
+ "INSERT INTO `target_db`.`events` (`id`, `numbers`, `tags`) SELECT `id`, `numbers`, `tags` FROM `source_db`.`events`"
+ );
}
#[test]
diff --git a/crates/dbx-core/src/data/transfer/db2_tests.rs b/crates/dbx-core/src/data/transfer/db2_tests.rs
index 183e5797af..bfecc95180 100644
--- a/crates/dbx-core/src/data/transfer/db2_tests.rs
+++ b/crates/dbx-core/src/data/transfer/db2_tests.rs
@@ -131,7 +131,10 @@ fn db2_transfer_writes_multiple_rows_without_changing_backslashes_or_binary_valu
&DatabaseType::Db2,
None,
);
- assert_eq!(sql, "INSERT INTO \"APP\".\"EVENTS\" (\"PATH\", \"PAYLOAD\") VALUES\n('C:\\data\\O''Brien', BX'00ff'),\n('中文', BX'')");
+ assert_eq!(
+ sql,
+ "INSERT INTO \"APP\".\"EVENTS\" (\"PATH\", \"PAYLOAD\") VALUES\n('C:\\data\\O''Brien', BX'00ff'),\n('中文', BX'')"
+ );
assert_eq!(transfer::escape_value_typed(&json!("0xFF"), &DatabaseType::Db2, Some("VARCHAR(20)")), "'0xFF'");
assert_eq!(transfer::escape_value_typed(&json!(true), &DatabaseType::Db2, Some("BOOLEAN")), "TRUE");
assert_eq!(transfer::escape_value(&json!(null), &DatabaseType::Db2), "NULL");
diff --git a/crates/dbx-core/src/data/transfer/ddl_plan.rs b/crates/dbx-core/src/data/transfer/ddl_plan.rs
index 36e7de51f5..9b4be43998 100644
--- a/crates/dbx-core/src/data/transfer/ddl_plan.rs
+++ b/crates/dbx-core/src/data/transfer/ddl_plan.rs
@@ -123,7 +123,9 @@ pub(super) async fn prepare_table_ddl(
match db::doris::get_catalog_table_ddl(&pool, catalog, &request.source_database, table).await {
Ok(ddl) => (ddl, true),
Err(err) => {
- log::warn!("[transfer] catalog DDL read failed for {table} in catalog '{catalog}': {err}; falling back to generated DDL");
+ log::warn!(
+ "[transfer] catalog DDL read failed for {table} in catalog '{catalog}': {err}; falling back to generated DDL"
+ );
(
generate_create_table_ddl_with_column_quoting(
columns,
@@ -452,9 +454,12 @@ mod tests {
)
.await
.unwrap();
- assert_eq!(prepared.deferred_fk_alters, vec![
- "ALTER TABLE `resolved_child` ADD CONSTRAINT `fk_child_parent` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT"
- ]);
+ assert_eq!(
+ prepared.deferred_fk_alters,
+ vec![
+ "ALTER TABLE `resolved_child` ADD CONSTRAINT `fk_child_parent` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT"
+ ]
+ );
assert!(prepared.ddl.contains("`resolved_child`"), "{}", prepared.ddl);
}
diff --git a/crates/dbx-core/src/data/transfer/iris_tests.rs b/crates/dbx-core/src/data/transfer/iris_tests.rs
index 55d3dd2775..8f08318643 100644
--- a/crates/dbx-core/src/data/transfer/iris_tests.rs
+++ b/crates/dbx-core/src/data/transfer/iris_tests.rs
@@ -11,9 +11,19 @@ fn iris_transfer_pages_advance_with_top_and_vid() {
for offset in [2, 4] {
assert_eq!(
pagination_sql_with_order(
- &columns, "items", "SQLUSER", &DatabaseType::Iris, offset, 2, &["id".into()], None,
+ &columns,
+ "items",
+ "SQLUSER",
+ &DatabaseType::Iris,
+ offset,
+ 2,
+ &["id".into()],
+ None,
),
- format!("SELECT * FROM (SELECT TOP {} \"id\", \"name\" FROM \"SQLUSER\".\"items\" ORDER BY \"id\") WHERE %VID > {offset}", offset + 2)
+ format!(
+ "SELECT * FROM (SELECT TOP {} \"id\", \"name\" FROM \"SQLUSER\".\"items\" ORDER BY \"id\") WHERE %VID > {offset}",
+ offset + 2
+ )
);
}
assert_eq!(
@@ -26,8 +36,15 @@ fn iris_transfer_pages_advance_with_top_and_vid() {
fn iris_transfer_filtered_pages_preserve_predicates_order_and_quoting() {
assert_eq!(
pagination_sql_with_filter_order(
- &["item\"id".into()], "item\"s", "team space", &DatabaseType::Iris,
- 2, 2, Some("WHERE active = 1"), Some("\"item\"\"id\" DESC"), &[],
+ &["item\"id".into()],
+ "item\"s",
+ "team space",
+ &DatabaseType::Iris,
+ 2,
+ 2,
+ Some("WHERE active = 1"),
+ Some("\"item\"\"id\" DESC"),
+ &[],
),
"SELECT * FROM (SELECT TOP 4 \"item\"\"id\" FROM \"team space\".\"item\"\"s\" WHERE (active = 1) ORDER BY \"item\"\"id\" DESC) WHERE %VID > 2"
);
diff --git a/crates/dbx-core/src/data/transfer/structure_plan.rs b/crates/dbx-core/src/data/transfer/structure_plan.rs
index 64d6f749f9..e9fb878dff 100644
--- a/crates/dbx-core/src/data/transfer/structure_plan.rs
+++ b/crates/dbx-core/src/data/transfer/structure_plan.rs
@@ -552,6 +552,9 @@ mod tests {
#[test]
fn structured_ddl_metadata_produces_operation_dtos() {
let index = db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_created_at".into(),
columns: vec!["lower(\"email\")".into()],
is_unique: false,
diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rs
index 02b27a337e..116d9b456b 100644
--- a/crates/dbx-core/src/schema/mod.rs
+++ b/crates/dbx-core/src/schema/mod.rs
@@ -3224,6 +3224,9 @@ mod tests {
#[test]
fn reference_keys_require_effective_unfiltered_plain_unique_columns() {
let index = |name: &str, columns: &[&str], is_unique: bool, is_primary: bool| db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.to_string(),
columns: columns.iter().map(|column| (*column).to_string()).collect(),
is_unique,
@@ -10299,6 +10302,9 @@ async fn external_driver_gaussdb_m_indexes(
let is_primary =
current_name.to_lowercase().ends_with("_pkey") || current_name.eq_ignore_ascii_case("primary");
indexes.push(db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: current_name.clone(),
columns: current_columns.clone(),
is_unique: current_non_unique == 0,
@@ -10371,6 +10377,9 @@ async fn external_driver_gaussdb_m_indexes(
if !current_name.is_empty() {
let is_primary = current_name.to_lowercase().ends_with("_pkey") || current_name.eq_ignore_ascii_case("primary");
indexes.push(db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: current_name,
columns: current_columns,
is_unique: current_non_unique == 0,
@@ -12954,6 +12963,9 @@ mod ddl_tests {
id.is_primary_key = true;
let indexes = vec![
db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "pk_accounts".to_string(),
columns: vec!["id".to_string()],
is_unique: true,
@@ -12968,6 +12980,9 @@ mod ddl_tests {
constraint_backed: true,
},
db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "uq_accounts_code".to_string(),
columns: vec!["code".to_string()],
is_unique: true,
@@ -12982,6 +12997,9 @@ mod ddl_tests {
constraint_backed: true,
},
db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_accounts_display_name".to_string(),
columns: vec!["display_name".to_string()],
is_unique: true,
@@ -13012,6 +13030,7 @@ mod ddl_tests {
initially_deferred: Some(false),
enabled: Some(true),
valid: Some(true),
+ oracle_metadata: None,
},
db::ConstraintInfo {
name: "uq_accounts_code".to_string(),
@@ -13028,6 +13047,7 @@ mod ddl_tests {
initially_deferred: Some(true),
enabled: Some(true),
valid: Some(true),
+ oracle_metadata: None,
},
];
@@ -13173,6 +13193,9 @@ mod ddl_tests {
// expression key just like a real column.
let id = column("id", "integer");
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_lower_email_trgm_idx".to_string(),
columns: vec!["lower(email)".to_string()],
is_unique: false,
@@ -13199,6 +13222,9 @@ mod ddl_tests {
fn postgres_table_ddl_preserves_btree_key_order_and_nulls_position() {
let id = column("id", "bigint");
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_id_order_idx".to_string(),
columns: vec!["id".to_string(), "id".to_string()],
is_unique: false,
@@ -13223,6 +13249,9 @@ mod ddl_tests {
fn postgres_primary_index(keys: &[&str]) -> db::IndexInfo {
db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "psckdmx_pkey".to_string(),
columns: keys.iter().map(|key| (*key).to_string()).collect(),
is_unique: true,
@@ -13464,6 +13493,9 @@ mod ddl_tests {
let mut id = column("id", "integer");
id.is_primary_key = true;
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "events_payload_idx".to_string(),
columns: vec!["payload".to_string()],
is_unique: false,
@@ -13515,6 +13547,9 @@ mod ddl_tests {
#[test]
fn postgres_partition_ddl_preserves_local_unique_without_local_primary_key() {
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "events_2026_code_key".to_string(),
columns: vec!["code".to_string()],
is_unique: true,
@@ -13543,6 +13578,7 @@ mod ddl_tests {
initially_deferred: Some(false),
enabled: Some(true),
valid: Some(true),
+ oracle_metadata: None,
}];
let partition_info = db::postgres::PostgresTablePartitionInfo {
is_partition: true,
@@ -13579,6 +13615,9 @@ mod ddl_tests {
let mut id = column("id", "integer");
id.is_primary_key = true;
let indexes = vec![db::IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "events_2026_pkey".to_string(),
columns: vec!["id".to_string()],
is_unique: true,
diff --git a/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs b/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs
index aca683a212..64662e97ad 100644
--- a/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs
+++ b/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs
@@ -1527,6 +1527,9 @@ mod tests {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
}
}
@@ -1705,6 +1708,7 @@ mod tests {
comment: String::new(),
concurrently: false,
original: None,
+ oracle_original_missing: false,
marked_for_drop: false,
});
let preview = preview_sqlite_table_structure_change_with_pool(pool.clone(), options.clone()).await.unwrap();
@@ -2025,6 +2029,9 @@ mod tests {
comment: String::new(),
concurrently: false,
original: Some(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "uq_items_value".to_string(),
columns: vec!["value".to_string()],
is_unique: true,
@@ -2037,6 +2044,7 @@ mod tests {
column_opclasses: vec![],
constraint_backed: false,
}),
+ oracle_original_missing: false,
marked_for_drop: true,
});
let preview = preview_sqlite_table_structure_change_with_pool(pool.clone(), options.clone()).await.unwrap();
diff --git a/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs b/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs
index f961506829..a5ff4c3250 100644
--- a/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs
+++ b/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs
@@ -59,6 +59,9 @@ fn change_options(table_name: &str, columns: Vec<EditableStructureColumn>) -> Ta
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
}
}
diff --git a/crates/dbx-core/tests/live_mysql_generated_columns.rs b/crates/dbx-core/tests/live_mysql_generated_columns.rs
index 4e0b2883ac..73966b633b 100644
--- a/crates/dbx-core/tests/live_mysql_generated_columns.rs
+++ b/crates/dbx-core/tests/live_mysql_generated_columns.rs
@@ -55,6 +55,9 @@ fn change_options(table_name: &str, columns: Vec<EditableStructureColumn>) -> Ta
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
}
}
diff --git a/crates/dbx-core/tests/live_postgres_concurrent_index.rs b/crates/dbx-core/tests/live_postgres_concurrent_index.rs
index b2295b7157..be591054e9 100644
--- a/crates/dbx-core/tests/live_postgres_concurrent_index.rs
+++ b/crates/dbx-core/tests/live_postgres_concurrent_index.rs
@@ -29,6 +29,7 @@ fn concurrent_index(columns: Vec<&str>) -> EditableStructureIndex {
comment: String::new(),
concurrently: true,
original: None,
+ oracle_original_missing: false,
marked_for_drop: false,
}
}
@@ -69,6 +70,9 @@ async fn live_postgres_concurrent_index_builds_valid_index() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
});
assert!(result.warnings.is_empty(), "{:?}", result.warnings);
assert_eq!(
@@ -206,6 +210,9 @@ async fn live_postgres_partitioned_parent_concurrent_request_rejected() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
});
assert_eq!(
result.warnings,
diff --git a/crates/dbx-core/tests/live_postgres_partitioning.rs b/crates/dbx-core/tests/live_postgres_partitioning.rs
index 6b79ec201c..b432247584 100644
--- a/crates/dbx-core/tests/live_postgres_partitioning.rs
+++ b/crates/dbx-core/tests/live_postgres_partitioning.rs
@@ -321,6 +321,9 @@ async fn live_postgres_create_partitioned_table_executes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
};
let create = build_create_partitioned_table_sql(
options,
diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rs
index 204bd6452a..dc5f2e2104 100644
--- a/crates/dbx-core/tests/live_sqlserver_completion.rs
+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs
@@ -1031,6 +1031,9 @@ async fn live_sqlserver_table_structure_default_changes_drop_existing_constraint
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
assert_eq!(result.statements.len(), 4);
diff --git a/crates/dbx-core/tests/schema_diff_case_options.rs b/crates/dbx-core/tests/schema_diff_case_options.rs
index f01b929b5a..56bff24d02 100644
--- a/crates/dbx-core/tests/schema_diff_case_options.rs
+++ b/crates/dbx-core/tests/schema_diff_case_options.rs
@@ -20,6 +20,9 @@ fn column(name: &str, data_type: &str) -> ColumnInfo {
fn index(name: &str, columns: &[&str]) -> IndexInfo {
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.to_string(),
columns: columns.iter().map(|column| (*column).to_string()).collect(),
is_unique: false,
diff --git a/crates/dbx-driver-mongodb/src/mongo_driver.rs b/crates/dbx-driver-mongodb/src/mongo_driver.rs
index ce81b7384c..1ca9255678 100644
--- a/crates/dbx-driver-mongodb/src/mongo_driver.rs
+++ b/crates/dbx-driver-mongodb/src/mongo_driver.rs
@@ -965,6 +965,9 @@ fn index_info_from_model(model: IndexModel) -> IndexInfo {
.and_then(|options| options.partial_filter_expression.as_ref())
.map(|filter| bson_to_json(&Bson::Document(filter.clone())).to_string());
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
is_unique: model.options.as_ref().and_then(|options| options.unique).unwrap_or(false),
is_primary: name == "_id_",
name,
@@ -4499,6 +4502,9 @@ mod tests {
#[test]
fn index_spec_from_index_info_marks_properties_as_incomplete() {
let spec = index_spec_from_index_info(&IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "email_1".to_string(),
columns: vec!["email".to_string()],
is_unique: true,
@@ -4527,6 +4533,9 @@ mod tests {
#[test]
fn index_spec_from_index_info_falls_back_to_columns_without_an_index_type() {
let spec = index_spec_from_index_info(&IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "compound".to_string(),
columns: vec!["a".to_string(), "b".to_string()],
is_unique: false,
@@ -4773,6 +4782,9 @@ mod tests {
fn diff_dropped_index_names_reports_removed_indexes() {
let before = vec![
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "_id_".to_string(),
columns: vec!["_id".to_string()],
is_unique: true,
@@ -4787,6 +4799,9 @@ mod tests {
constraint_backed: false,
},
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_email_unique".to_string(),
columns: vec!["email".to_string()],
is_unique: true,
@@ -4801,6 +4816,9 @@ mod tests {
constraint_backed: false,
},
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "users_status_idx".to_string(),
columns: vec!["status".to_string()],
is_unique: false,
diff --git a/crates/dbx-driver-mysql/src/manticoresearch.rs b/crates/dbx-driver-mysql/src/manticoresearch.rs
index a6d6034cc9..f182404924 100644
--- a/crates/dbx-driver-mysql/src/manticoresearch.rs
+++ b/crates/dbx-driver-mysql/src/manticoresearch.rs
@@ -201,6 +201,9 @@ fn index_info_from_row(row: &mysql_async::Row) -> IndexInfo {
.collect();
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.clone(),
columns: vec![name],
is_unique: false,
diff --git a/crates/dbx-driver-mysql/src/mysql.rs b/crates/dbx-driver-mysql/src/mysql.rs
index 5e27585f33..3fe667ee96 100644
--- a/crates/dbx-driver-mysql/src/mysql.rs
+++ b/crates/dbx-driver-mysql/src/mysql.rs
@@ -153,7 +153,8 @@ pub async fn get_event_info<P: MySqlPoolAccess + ?Sized>(
let mut conn = get_conn_with_health_check(pool).await?;
let sql = format!(
"SELECT EVENT_SCHEMA, EVENT_NAME, DEFINER, TIME_ZONE, EVENT_TYPE, EXECUTE_AT, INTERVAL_VALUE, INTERVAL_FIELD, STARTS, ENDS, STATUS, ON_COMPLETION, EVENT_COMMENT, EVENT_DEFINITION, CREATED, LAST_ALTERED, LAST_EXECUTED FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {} AND EVENT_NAME = {} LIMIT 1",
- quote_value(database), quote_value(name)
+ quote_value(database),
+ quote_value(name)
);
let row = conn
.query_first::<mysql_async::Row, _>(sql)
@@ -3297,7 +3298,9 @@ pub async fn list_tables_filtered(
.collect();
if tables.is_empty() {
- log::debug!("Falling back to SHOW TABLES for database `{database}` after information_schema.TABLES returned no named tables");
+ log::debug!(
+ "Falling back to SHOW TABLES for database `{database}` after information_schema.TABLES returned no named tables"
+ );
return list_tables_show_filtered(pool, database, filter)
.await
.map(|tables| filter_list_tables_fallback(tables, filter, limit, offset, object_types, table_name_filter));
@@ -7104,6 +7107,9 @@ pub async fn list_indexes(pool: &MySqlPool, database: &str, table: &str) -> Resu
let index_position = indexes.len();
index_positions.insert(name.clone(), index_position);
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.clone(),
columns: Vec::new(),
is_unique: get_opt_i32(&row, "NON_UNIQUE").unwrap_or(1) == 0,
@@ -9781,11 +9787,7 @@ mod tests {
Some(MySqlSetupMode::Compatible),
"{error}"
);
- assert_eq!(
- mysql_group_concat_setup_fallback_mode(MySqlSetupMode::Compatible, error),
- None,
- "{error}"
- );
+ assert_eq!(mysql_group_concat_setup_fallback_mode(MySqlSetupMode::Compatible, error), None, "{error}");
}
}
@@ -9803,11 +9805,7 @@ mod tests {
Some(MySqlSetupMode::Compatible),
"{error}"
);
- assert_eq!(
- mysql_group_concat_setup_fallback_mode(MySqlSetupMode::Compatible, error),
- None,
- "{error}"
- );
+ assert_eq!(mysql_group_concat_setup_fallback_mode(MySqlSetupMode::Compatible, error), None, "{error}");
}
}
diff --git a/crates/dbx-driver-mysql/src/mysql_compatible.rs b/crates/dbx-driver-mysql/src/mysql_compatible.rs
index 1c4dca2db8..815cedc27c 100644
--- a/crates/dbx-driver-mysql/src/mysql_compatible.rs
+++ b/crates/dbx-driver-mysql/src/mysql_compatible.rs
@@ -322,6 +322,9 @@ fn table_key_index(name: &str, line: &str, is_unique: bool, is_primary: bool, in
return None;
}
Some(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.to_string(),
columns,
is_unique,
@@ -345,6 +348,9 @@ fn secondary_index(line: &str) -> Option<IndexInfo> {
return None;
}
Some(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name,
columns,
is_unique: false,
diff --git a/crates/dbx-driver-mysql/src/ob_oracle.rs b/crates/dbx-driver-mysql/src/ob_oracle.rs
index 3972658f20..efd2131173 100644
--- a/crates/dbx-driver-mysql/src/ob_oracle.rs
+++ b/crates/dbx-driver-mysql/src/ob_oracle.rs
@@ -1,3 +1,5 @@
+use std::collections::BTreeMap;
+
use mysql_async::prelude::*;
use crate::types::{ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, ObjectInfo, TableInfo, TriggerInfo};
@@ -211,16 +213,18 @@ fn format_oracle_type(data_type: &str, precision: Option<i32>, scale: Option<i32
fn list_indexes_sql(schema: &str, table: &str) -> String {
format!(
- "SELECT ai.INDEX_NAME, \
- LISTAGG(aic.COLUMN_NAME, ',') WITHIN GROUP (ORDER BY aic.COLUMN_POSITION) AS COLUMNS, \
- ai.UNIQUENESS, \
- CASE WHEN ac.CONSTRAINT_TYPE = 'P' THEN 1 ELSE 0 END AS IS_PRIMARY \
+ "SELECT ai.INDEX_NAME, aic.COLUMN_NAME, ai.UNIQUENESS, \
+ CASE WHEN ac.CONSTRAINT_NAME IS NULL THEN 0 ELSE 1 END AS IS_PRIMARY, ai.INDEX_TYPE, ai.PARTITIONED, \
+ ai.VISIBILITY, aic.DESCEND, aie.COLUMN_EXPRESSION, aic.COLUMN_POSITION \
FROM ALL_INDEXES ai \
- JOIN ALL_IND_COLUMNS aic ON ai.INDEX_NAME = aic.INDEX_NAME AND ai.TABLE_OWNER = aic.TABLE_OWNER \
- LEFT JOIN ALL_CONSTRAINTS ac ON ac.INDEX_NAME = ai.INDEX_NAME AND ac.OWNER = ai.TABLE_OWNER AND ac.CONSTRAINT_TYPE = 'P' \
+ JOIN ALL_IND_COLUMNS aic ON ai.INDEX_NAME = aic.INDEX_NAME AND ai.OWNER = aic.INDEX_OWNER \
+ AND ai.TABLE_OWNER = aic.TABLE_OWNER AND ai.TABLE_NAME = aic.TABLE_NAME \
+ LEFT JOIN ALL_IND_EXPRESSIONS aie ON aie.INDEX_OWNER = aic.INDEX_OWNER AND aie.INDEX_NAME = aic.INDEX_NAME \
+ AND aie.TABLE_OWNER = aic.TABLE_OWNER AND aie.TABLE_NAME = aic.TABLE_NAME AND aie.COLUMN_POSITION = aic.COLUMN_POSITION \
+ LEFT JOIN ALL_CONSTRAINTS ac ON ac.INDEX_NAME = ai.INDEX_NAME AND ac.OWNER = ai.TABLE_OWNER \
+ AND ac.TABLE_NAME = ai.TABLE_NAME AND ac.CONSTRAINT_TYPE = 'P' \
WHERE ai.TABLE_OWNER = {s} AND ai.TABLE_NAME = {t} \
- GROUP BY ai.INDEX_NAME, ai.UNIQUENESS, ac.CONSTRAINT_TYPE \
- ORDER BY ai.INDEX_NAME",
+ ORDER BY ai.INDEX_NAME, aic.COLUMN_POSITION",
s = metadata_owner_sql(schema),
t = quote_value(table),
)
@@ -232,26 +236,47 @@ pub async fn list_indexes(pool: &mysql_async::Pool, schema: &str, table: &str) -
let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
- Ok(rows
- .iter()
- .map(|row| {
- let cols_str = get_str(row, 1);
- IndexInfo {
- name: get_str(row, 0),
- columns: cols_str.split(',').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect(),
- is_unique: get_str(row, 2) == "UNIQUE",
- is_primary: row_get::<i32, _>(row, 3).unwrap_or(0) == 1,
- filter: None,
- index_type: None,
- included_columns: None,
- comment: None,
- key_is_expression: Vec::new(),
- column_opclasses: vec![],
- key_options: Vec::new(),
- constraint_backed: false,
- }
- })
- .collect())
+ let mut indexes = BTreeMap::<String, IndexInfo>::new();
+ for row in &rows {
+ let name = get_str(row, 0);
+ let visibility = get_str(row, 6);
+ let partitioned = get_str(row, 5);
+ let direction = get_str(row, 7);
+ let expression = get_opt_str(row, 8).filter(|value| !value.trim().is_empty());
+ let column = get_str(row, 1);
+ let position = row_get::<u64, _>(row, 9).unwrap_or(0) as usize;
+ let index = indexes.entry(name.clone()).or_insert_with(|| IndexInfo {
+ key_directions: Vec::new(),
+ visibility: Some(visibility.clone()),
+ key_metadata_complete: true,
+ name,
+ columns: Vec::new(),
+ is_unique: get_str(row, 2) == "UNIQUE",
+ is_primary: row_get::<i32, _>(row, 3).unwrap_or(0) == 1,
+ filter: None,
+ index_type: get_opt_str(row, 4),
+ included_columns: None,
+ comment: None,
+ key_is_expression: Vec::new(),
+ column_opclasses: Vec::new(),
+ key_options: Vec::new(),
+ constraint_backed: false,
+ });
+ if position != index.columns.len() + 1
+ || !matches!(direction.as_str(), "ASC" | "DESC")
+ || !matches!(visibility.as_str(), "VISIBLE" | "INVISIBLE")
+ || index.visibility.as_deref() != Some(visibility.as_str())
+ || partitioned != "NO"
+ || !matches!(get_str(row, 4).as_str(), "NORMAL" | "FUNCTION-BASED NORMAL")
+ || (expression.is_none() && column.starts_with("SYS_NC") && column.ends_with('$'))
+ {
+ index.key_metadata_complete = false;
+ }
+ index.columns.push(expression.clone().unwrap_or(column));
+ index.key_is_expression.push(expression.is_some());
+ index.key_directions.push(direction);
+ }
+ Ok(indexes.into_values().collect())
}
pub async fn list_foreign_keys(
diff --git a/crates/dbx-driver-postgres/src/postgres.rs b/crates/dbx-driver-postgres/src/postgres.rs
index 3e35b9d3fd..4f268136f5 100644
--- a/crates/dbx-driver-postgres/src/postgres.rs
+++ b/crates/dbx-driver-postgres/src/postgres.rs
@@ -5354,6 +5354,9 @@ async fn list_indexes_for_relations_with_sql(
let all_key_options: Vec<i16> = row.try_get::<_, Vec<i16>>(12).unwrap_or_default();
let key_options = if all_key_options.len() == split_at { all_key_options } else { Vec::new() };
result.entry(relid).or_default().push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: pg_row_try_string(row, 1),
columns: key_cols,
is_unique: pg_row_try_bool(row, 4).unwrap_or(false),
@@ -5834,6 +5837,7 @@ pub async fn list_constraints(pool: &Pool, schema: &str, table: &str) -> Result<
initially_deferred: Some(row.try_get::<_, bool>(11).unwrap_or(false)),
enabled: Some(true),
valid: Some(row.try_get::<_, bool>(12).unwrap_or(true)),
+ oracle_metadata: None,
})
.collect())
}
@@ -5905,6 +5909,7 @@ pub async fn list_opengauss_constraints(pool: &Pool, schema: &str, table: &str)
initially_deferred: Some(pg_row_try_bool(&row, 11).unwrap_or(false)),
enabled: Some(true),
valid: Some(pg_row_try_bool(&row, 12).unwrap_or(true)),
+ oracle_metadata: None,
});
}
Ok(result)
@@ -9861,6 +9866,9 @@ async fn list_indexes_with_sql(
let all_key_options: Vec<i16> = row.try_get::<_, Vec<i16>>(11).unwrap_or_default();
let key_options = if all_key_options.len() == split_at { all_key_options } else { Vec::new() };
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: pg_row_try_string(row, 0),
columns: key_cols,
is_unique: pg_row_try_bool(row, 3).unwrap_or(false),
diff --git a/crates/dbx-driver-sqlserver/src/sqlserver.rs b/crates/dbx-driver-sqlserver/src/sqlserver.rs
index 659b0edcaa..6eb8750e49 100644
--- a/crates/dbx-driver-sqlserver/src/sqlserver.rs
+++ b/crates/dbx-driver-sqlserver/src/sqlserver.rs
@@ -3227,6 +3227,9 @@ pub async fn list_indexes(client: &mut SqlServerClient, schema: &str, table: &st
let cols_str = row.get::<&str, _>(1).unwrap_or("");
let inc_str = row.get::<&str, _>(5).unwrap_or("");
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: row.get::<&str, _>(0).unwrap_or("").to_string(),
columns: cols_str.split(',').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect(),
is_unique: row.get::<bool, _>(2).unwrap_or(false),
@@ -3482,6 +3485,7 @@ pub async fn list_constraints(
initially_deferred: Some(false),
enabled: Some(row.get::<bool, _>(9).unwrap_or(true)),
valid: Some(row.get::<bool, _>(10).unwrap_or(true)),
+ oracle_metadata: None,
}
})
.collect())
diff --git a/crates/dbx-drivers/src/db/clickhouse_driver.rs b/crates/dbx-drivers/src/db/clickhouse_driver.rs
index 1271c1a13c..68b62a5e1e 100644
--- a/crates/dbx-drivers/src/db/clickhouse_driver.rs
+++ b/crates/dbx-drivers/src/db/clickhouse_driver.rs
@@ -556,6 +556,9 @@ fn clickhouse_index_from_skipping_row(row: &[serde_json::Value]) -> IndexInfo {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
key_options: Vec::new(),
constraint_backed: false,
@@ -805,6 +808,9 @@ pub async fn list_indexes(client: &ChClient, database: &str, table: &str) -> Res
.filter(|value| !value.trim().is_empty())
{
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "PRIMARY".to_string(),
columns: split_clickhouse_expression_list(primary_key),
is_unique: false,
diff --git a/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs b/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs
index 0f3b3a08ea..4be3e2560e 100644
--- a/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs
+++ b/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs
@@ -188,6 +188,9 @@ pub async fn list_indexes(client: &CloudflareD1Client, _schema: &str, table: &st
let columns =
column_result.rows.iter().filter_map(|row| value_by_column(&column_result.columns, row, "name")).collect();
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name,
columns,
is_unique,
diff --git a/crates/dbx-drivers/src/db/questdb.rs b/crates/dbx-drivers/src/db/questdb.rs
index da0ba4ad48..2a98c644da 100644
--- a/crates/dbx-drivers/src/db/questdb.rs
+++ b/crates/dbx-drivers/src/db/questdb.rs
@@ -171,6 +171,9 @@ pub async fn list_indexes(pool: &Pool, _schema: &str, table: &str) -> Result<Vec
let column: String = row.get::<_, String>(0);
let key_cols = vec![column];
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: row.get::<_, String>(0),
columns: key_cols,
is_unique: false,
diff --git a/crates/dbx-drivers/src/db/rqlite_driver.rs b/crates/dbx-drivers/src/db/rqlite_driver.rs
index 85113fe502..af844b2afd 100644
--- a/crates/dbx-drivers/src/db/rqlite_driver.rs
+++ b/crates/dbx-drivers/src/db/rqlite_driver.rs
@@ -172,6 +172,9 @@ pub async fn list_indexes(client: &RqliteClient, _schema: &str, table: &str) ->
.filter_map(|row| value_by_column(&column_result.columns, row, "name"))
.collect();
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name,
columns,
is_unique,
diff --git a/crates/dbx-drivers/src/db/sqlite.rs b/crates/dbx-drivers/src/db/sqlite.rs
index 578847511f..d1a3ebe749 100644
--- a/crates/dbx-drivers/src/db/sqlite.rs
+++ b/crates/dbx-drivers/src/db/sqlite.rs
@@ -2516,6 +2516,9 @@ pub async fn list_indexes(pool: &SqliteHandle, schema: &str, table: &str) -> Res
})
.collect();
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name,
columns,
is_unique,
@@ -2572,6 +2575,9 @@ pub async fn list_indexes(pool: &SqliteHandle, schema: &str, table: &str) -> Res
.collect::<Vec<_>>();
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name,
columns,
is_unique,
diff --git a/crates/dbx-drivers/src/db/turso_driver.rs b/crates/dbx-drivers/src/db/turso_driver.rs
index 748fa7ecc9..d8f409cfa1 100644
--- a/crates/dbx-drivers/src/db/turso_driver.rs
+++ b/crates/dbx-drivers/src/db/turso_driver.rs
@@ -214,6 +214,9 @@ pub async fn list_indexes(client: &TursoClient, _schema: &str, table: &str) -> R
.filter_map(|row| value_by_column(&column_result.columns, row, "name"))
.collect();
indexes.push(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name,
columns,
is_unique,
diff --git a/crates/dbx-sql-schema/src/db_admin_sql.rs b/crates/dbx-sql-schema/src/db_admin_sql.rs
index 99a78d1ffc..1c2d01a36f 100644
--- a/crates/dbx-sql-schema/src/db_admin_sql.rs
+++ b/crates/dbx-sql-schema/src/db_admin_sql.rs
@@ -3184,6 +3184,9 @@ mod tests {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
});
assert_eq!(create.warnings, Vec::<String>::new());
assert_eq!(
diff --git a/crates/dbx-sql-schema/src/schema_diff.rs b/crates/dbx-sql-schema/src/schema_diff.rs
index 195502ff18..98969fe84b 100644
--- a/crates/dbx-sql-schema/src/schema_diff.rs
+++ b/crates/dbx-sql-schema/src/schema_diff.rs
@@ -6995,6 +6995,9 @@ mod tests {
fn index(overrides: IndexInfo) -> IndexInfo {
IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: if overrides.name.is_empty() { "idx_users_email".to_string() } else { overrides.name },
columns: if overrides.columns.is_empty() { vec!["email".to_string()] } else { overrides.columns },
is_unique: overrides.is_unique,
@@ -7189,6 +7192,9 @@ mod tests {
target_column.column_default = Some("target".to_string());
target_column.comment = Some("target comment".to_string());
options.source_details[0].indexes.push(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "uq_users_name".to_string(),
columns: vec!["name".to_string()],
is_unique: true,
@@ -8324,6 +8330,9 @@ mod tests {
fn sqlserver_drops_changed_indexes_and_defaults_before_columns() {
let target_column = ColumnInfo { column_default: Some("((0))".into()), ..column("legacy_status", "int", None) };
let target_index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_events_legacy_status".into(),
columns: vec!["legacy_status".into()],
is_unique: false,
@@ -8389,6 +8398,9 @@ mod tests {
let source_column = column("amount", "bigint", None);
let target_column = column("amount", "int", None);
let unchanged_index = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_events_amount".into(),
columns: vec!["amount".into()],
is_unique: false,
@@ -8459,6 +8471,9 @@ mod tests {
#[test]
fn sqlserver_index_and_foreign_key_forms_follow_tsql() {
let btree = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_events_status".into(),
columns: vec!["status".into()],
is_unique: true,
@@ -8480,6 +8495,9 @@ mod tests {
assert!(!btree_sql.contains("BTREE"));
let columnstore = IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "ix_events_analytics".into(),
columns: Vec::new(),
is_unique: false,
@@ -9193,6 +9211,9 @@ mod tests {
fn detects_modified_indexes_not_only_added_or_removed_indexes() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_status".to_string(),
columns: vec!["status".to_string(), "created_at".to_string()],
is_unique: false,
@@ -9207,6 +9228,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_status".to_string(),
columns: vec!["status".to_string()],
is_unique: true,
@@ -9230,6 +9254,9 @@ mod tests {
#[test]
fn detects_opclass_change_in_postgres_index() {
let source_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_name_trgm".to_string(),
columns: vec!["name".to_string()],
is_unique: false,
@@ -9244,6 +9271,9 @@ mod tests {
constraint_backed: false,
});
let target_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_name_trgm".to_string(),
columns: vec!["name".to_string()],
is_unique: false,
@@ -9273,6 +9303,9 @@ mod tests {
fn detects_mysql_functional_index_changes_and_preserves_expression_ddl() {
let functional_key_part = "((case when (`STATUS` = _utf8mb4'online') then _utf8mb4'online' else NULL end))";
let source_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "test_UNIQUE".to_string(),
columns: vec!["attr".to_string(), "attr2".to_string(), functional_key_part.to_string()],
is_unique: true,
@@ -9287,6 +9320,9 @@ mod tests {
constraint_backed: false,
});
let target_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "test_UNIQUE".to_string(),
columns: vec!["attr".to_string(), "attr2".to_string()],
is_unique: true,
@@ -9347,6 +9383,9 @@ mod tests {
// whole expression as an identifier turned it into a literal (and nonexistent) column.
let expression_key_part = "COALESCE(height, '-1'::integer::double precision)";
let new_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "uq_tankong_sta_type_time".to_string(),
columns: vec![
"sta_id".to_string(),
@@ -9415,6 +9454,9 @@ mod tests {
let expression_key_part =
"(((category)::text = ANY ((ARRAY['industrial'::character varying, 'macro'::character varying])::text[])))";
let new_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "index_repro_rank".to_string(),
columns: vec![
"((has_current_analysis AND (NOT dirty) AND researchable))".to_string(),
@@ -9486,6 +9528,9 @@ mod tests {
// `indoption` is only meaningful for B-tree keys, so a GIN index must not gain
// `ASC NULLS LAST` suffixes even when the introspection reports the flags.
let new_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_payload_gin".to_string(),
columns: vec!["payload".to_string()],
is_unique: false,
@@ -9549,6 +9594,9 @@ mod tests {
// parts from pg_get_indexdef are left unquoted.
let expression_key_part = "COALESCE(height, '-1'::integer::double precision)";
let new_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "uq_weird_columns".to_string(),
columns: vec![
"order item".to_string(),
@@ -9624,6 +9672,9 @@ mod tests {
fn quotes_expression_like_column_names_without_agent_provenance() {
for db_type in [DatabaseType::Kingbase, DatabaseType::Vastbase] {
let new_index = index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_weird_columns".to_string(),
columns: vec!["order item".to_string(), "a(b)".to_string(), "a::b".to_string()],
key_is_expression: Vec::new(),
@@ -9743,6 +9794,9 @@ mod tests {
diff_type: "modified".to_string(),
name: "idx_orders_status".to_string(),
source: Some(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_status".to_string(),
columns: vec!["status".to_string(), "created_at".to_string()],
is_unique: true,
@@ -10233,6 +10287,9 @@ mod tests {
diff_type: "added".to_string(),
name: "idx_orders_status".to_string(),
source: Some(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_orders_status".to_string(),
columns: vec!["status".to_string()],
is_unique: false,
@@ -10965,6 +11022,9 @@ mod tests {
column("User ID", "bigint", None),
],
indexes: vec![index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "Order Status IDX".to_string(),
columns: vec!["Status".to_string()],
is_unique: true,
@@ -11031,6 +11091,9 @@ mod tests {
column("user-id", "bigint", None),
],
indexes: vec![index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "status-index".to_string(),
columns: vec!["status".to_string()],
is_unique: true,
@@ -11087,6 +11150,9 @@ mod tests {
column("parent id", "TEXT", None),
],
indexes: vec![index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "active status index".to_string(),
columns: vec!["status".to_string()],
is_unique: false,
@@ -12214,6 +12280,9 @@ mod tests {
diff_type: "added".to_string(),
name: "idx_name".to_string(),
source: Some(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_name".to_string(),
columns: vec!["name2".to_string()],
is_unique: false,
@@ -12259,6 +12328,9 @@ mod tests {
name: "idx_old".to_string(),
source: None,
target: Some(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_old".to_string(),
columns: vec!["name".to_string()],
is_unique: false,
@@ -12678,6 +12750,9 @@ mod tests {
fn index_type_diff_btree_vs_hash() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into()],
is_unique: false,
@@ -12692,6 +12767,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into()],
is_unique: false,
@@ -12714,6 +12792,9 @@ mod tests {
fn index_type_fulltext_detected() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["content".into()],
is_unique: false,
@@ -12728,6 +12809,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["content".into()],
is_unique: false,
@@ -12750,6 +12834,9 @@ mod tests {
fn index_column_order_different() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into(), "b".into()],
is_unique: false,
@@ -12764,6 +12851,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["b".into(), "a".into()],
is_unique: false,
@@ -12787,6 +12877,9 @@ mod tests {
fn index_included_columns_diff() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into()],
is_unique: true,
@@ -12801,6 +12894,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into()],
is_unique: true,
@@ -12823,6 +12919,9 @@ mod tests {
fn index_included_columns_added() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into()],
is_unique: true,
@@ -12837,6 +12936,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["a".into()],
is_unique: true,
@@ -12859,6 +12961,9 @@ mod tests {
fn index_filter_change() {
let diffs = diff_indexes(
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["status".into()],
is_unique: false,
@@ -12873,6 +12978,9 @@ mod tests {
constraint_backed: false,
})],
&[index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_t".into(),
columns: vec!["status".into()],
is_unique: false,
@@ -12897,6 +13005,9 @@ mod tests {
let diffs = diff_indexes(
&[
index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_new".into(),
columns: vec!["a".into()],
is_unique: true,
@@ -12911,6 +13022,9 @@ mod tests {
constraint_backed: false,
}),
index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_modified".into(),
columns: vec!["a".into(), "b".into()],
is_unique: false,
@@ -12927,6 +13041,9 @@ mod tests {
],
&[
index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_removed".into(),
columns: vec!["c".into()],
is_unique: false,
@@ -12941,6 +13058,9 @@ mod tests {
constraint_backed: false,
}),
index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_modified".into(),
columns: vec!["a".into()],
is_unique: true,
@@ -13320,6 +13440,9 @@ mod tests {
diff_type: "added".to_string(),
name: "idx_name".into(),
source: Some(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_name".into(),
columns: vec!["name2".into()],
is_unique: false,
@@ -13341,6 +13464,9 @@ mod tests {
name: "idx_old".into(),
source: None,
target: Some(index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_old".into(),
columns: vec!["name".into()],
is_unique: false,
@@ -13758,6 +13884,9 @@ mod tests {
diff_type: "added".into(),
name: "idx_del_flag".into(),
source: Some(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_del_flag".into(),
columns: vec!["del_flag".into()],
is_unique: false,
@@ -14048,6 +14177,9 @@ mod tests {
diff_type: "added".into(),
name: "idx_views".into(),
source: Some(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: "idx_views".into(),
columns: vec!["views".into()],
is_unique: false,
@@ -15466,6 +15598,9 @@ mod tests {
fn named_index(name: &str, columns: &[&str], is_unique: bool) -> IndexInfo {
index(IndexInfo {
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
name: name.to_string(),
columns: columns.iter().map(|column| (*column).to_string()).collect(),
is_unique,
diff --git a/crates/dbx-sql-schema/src/table_structure_sql.rs b/crates/dbx-sql-schema/src/table_structure_sql.rs
index fabbc260d7..d0ebfa2ee2 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql.rs
@@ -8,9 +8,12 @@ mod create_dialect;
mod create_options;
mod create_table;
mod dialect;
+mod existing_primary_key;
mod foreign_keys;
mod indexes;
mod mysql_engine;
+mod oracle_constraints;
+mod oracle_foreign_keys;
mod owner;
mod partitions;
mod starrocks_layout;
@@ -59,10 +62,18 @@ pub fn build_table_structure_change_sql_with_context(
mut options: TableStructureSqlOptions,
starrocks: Option<StarRocksAlterOptions>,
) -> TableStructureSqlResult {
+ if options.oracle_constraint_changes.is_some() {
+ return oracle_constraints::build_changes(options);
+ }
+ if options.oracle_foreign_key_changes.is_some() {
+ return oracle_foreign_keys::build_changes(options);
+ }
+ if options.primary_key_change.is_some() {
+ return existing_primary_key::build_existing_primary_key_change(options);
+ }
if alter_dialect::is_starrocks(&options) {
return alter_dialect::build(&options, starrocks);
}
-
let mysql_engine_errors = validate_mysql_engine(&options);
if !mysql_engine_errors.is_empty() {
return TableStructureSqlResult { statements: Vec::new(), warnings: mysql_engine_errors };
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/comments.rs b/crates/dbx-sql-schema/src/table_structure_sql/comments.rs
index 5b115d319e..2cc701b73a 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/comments.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/comments.rs
@@ -258,6 +258,9 @@ mod tests {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_foreign_key_changes: None,
+ oracle_constraint_changes: None,
foreign_table,
}
}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
index 3addb3b8d1..ada6434e34 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
@@ -82,6 +82,10 @@ fn build_create_table_sql_impl(
options.table_name = clean(&options.table_name);
}
strip_inherited_mysql_column_charsets(&mut options);
+ let ordered_foreign_keys = match super::oracle_foreign_keys::build_new_table_keys(&options) {
+ Ok(statements) => statements,
+ Err(message) => return TableStructureSqlResult { statements: Vec::new(), warnings: vec![message.into()] },
+ };
let mut warnings = Vec::new();
warnings.extend(validate_mysql_engine(&options));
if let Some(value) = &options.mysql_auto_increment_value {
@@ -457,7 +461,11 @@ fn build_create_table_sql_impl(
));
}
- statements.extend(build_foreign_key_sql_for_new_table(&options, &mut warnings));
+ if options.oracle_foreign_key_changes.is_some() {
+ statements.extend(ordered_foreign_keys);
+ } else {
+ statements.extend(build_foreign_key_sql_for_new_table(&options, &mut warnings));
+ }
statements.extend(build_trigger_sql_for_new_table(&options, &mut warnings));
TableStructureSqlResult { statements, warnings }
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/existing_primary_key.rs b/crates/dbx-sql-schema/src/table_structure_sql/existing_primary_key.rs
new file mode 100644
index 0000000000..8b9b41de35
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/existing_primary_key.rs
@@ -0,0 +1,149 @@
+use std::collections::HashSet;
+
+use super::dialect::StructureDialect;
+use super::util::{qualified_table, quote_ident};
+use super::{build_table_structure_change_sql, TableStructureSqlOptions, TableStructureSqlResult};
+use crate::models::connection::DatabaseType;
+
+pub(super) fn build_existing_primary_key_change(mut options: TableStructureSqlOptions) -> TableStructureSqlResult {
+ let change = options.primary_key_change.take().expect("existing primary key change");
+ let reject =
+ |message: &str| TableStructureSqlResult { statements: Vec::new(), warnings: vec![message.to_string()] };
+ let oracle = options.database_type == Some(DatabaseType::Oracle);
+ if !matches!(options.database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle))
+ || options.is_gaussdb_m_mode
+ {
+ return reject("Ordered existing primary key changes are only supported for Oracle and OceanBase Oracle.");
+ }
+ if change.name.trim().is_empty() || change.original_columns.is_empty() {
+ return reject("The original primary key name and ordered columns are required.");
+ }
+ let original: HashSet<_> = change.original_columns.iter().collect();
+ let target: HashSet<_> = change.columns.iter().collect();
+ if original.len() != change.original_columns.len() || target.len() != change.columns.len() {
+ return reject("Primary key columns must not repeat.");
+ }
+ if oracle {
+ if change
+ .oracle_state
+ .as_ref()
+ .is_some_and(|state| (!state.deferrable && state.initially_deferred) || (state.validated && state.rely))
+ {
+ return reject("The captured Oracle primary key state is invalid.");
+ }
+ let Some(index) = &change.oracle_index else {
+ return reject("The original Oracle index identity and explicit index policy are required.");
+ };
+ let no_index = index.policy == "none";
+ let enabled = change.oracle_state.as_ref().is_none_or(|state| state.enabled);
+ if !matches!(index.policy.as_str(), "keep" | "drop" | "none")
+ || index.owner.trim().is_empty()
+ || options.schema.as_deref() != Some(index.owner.as_str())
+ || (no_index && (enabled || !index.name.is_empty()))
+ || (!no_index && index.name.trim().is_empty())
+ {
+ return reject("The Oracle index identity or policy is invalid.");
+ }
+ let new_index_required =
+ enabled && !change.columns.is_empty() && (index.policy == "drop" || original != target);
+ if new_index_required {
+ let Some(name) = index.new_name.as_deref() else {
+ return reject("A verified new Oracle index name is required.");
+ };
+ if name.is_empty()
+ || name.len() > 30
+ || !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
+ || !name.as_bytes()[0].is_ascii_alphabetic()
+ || name == index.name
+ {
+ return reject("The new Oracle index name is invalid or conflicts with the original index.");
+ }
+ } else if index.new_name.is_some() {
+ return reject("This Oracle primary key plan does not create a new index.");
+ }
+ } else if change.oracle_index.is_some() || change.oracle_state.is_some() {
+ return reject("Oracle index policies are not supported for OceanBase Oracle.");
+ }
+ let known_original: HashSet<_> = options
+ .columns
+ .iter()
+ .filter_map(|column| column.original.as_ref())
+ .filter(|column| column.is_primary_key)
+ .map(|column| &column.name)
+ .collect();
+ if original != known_original {
+ return reject("The original primary key does not match the loaded columns. Refresh the table definition.");
+ }
+ if change.columns.iter().any(|name| {
+ !options.columns.iter().any(|column| {
+ !column.marked_for_drop
+ && &column.name == name
+ && column.original.as_ref().is_some_and(|old| &old.name == name)
+ })
+ }) {
+ return reject("Primary key columns must be existing, unchanged columns.");
+ }
+ // Reuse the ordinary structure diff to reject combined edits. The explicit
+ // ordered draft owns the key; the column membership flags remain unchanged.
+ let ordinary = build_table_structure_change_sql(options.clone());
+ if !ordinary.statements.is_empty() || !ordinary.warnings.is_empty() {
+ return reject("Apply other table structure changes separately from an existing primary key change.");
+ }
+ if change.original_columns == change.columns {
+ return TableStructureSqlResult { statements: Vec::new(), warnings: Vec::new() };
+ }
+ let dialect = StructureDialect::Oracle;
+ let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
+ let name = quote_ident(dialect, &change.name);
+ let index_policy = change.oracle_index.as_ref().map_or("", |index| {
+ if index.policy == "keep" {
+ " KEEP INDEX"
+ } else if index.policy == "drop" {
+ " DROP INDEX"
+ } else {
+ ""
+ }
+ });
+ let mut statements = vec![format!("ALTER TABLE {table} DROP CONSTRAINT {name}{index_policy};")];
+ if !change.columns.is_empty() {
+ let columns = change.columns.iter().map(|name| quote_ident(dialect, name)).collect::<Vec<_>>().join(", ");
+ let using_index = change
+ .oracle_index
+ .as_ref()
+ .filter(|_| change.oracle_state.as_ref().is_none_or(|state| state.enabled))
+ .map_or_else(String::new, |index| {
+ if let Some(new_name) = &index.new_name {
+ let index_name = qualified_table(dialect, Some(&index.owner), new_name);
+ let unique =
+ if change.oracle_state.as_ref().is_some_and(|state| state.deferrable || !state.validated) {
+ ""
+ } else {
+ "UNIQUE "
+ };
+ format!(" USING INDEX (CREATE {unique}INDEX {index_name} ON {table} ({columns}))")
+ } else {
+ let index_name = qualified_table(dialect, Some(&index.owner), &index.name);
+ format!(" USING INDEX {index_name}")
+ }
+ });
+ let (before_index, after_index) = change.oracle_state.as_ref().map_or_else(
+ || (String::new(), String::new()),
+ |state| {
+ let before = format!(
+ " {} INITIALLY {} {}",
+ if state.deferrable { "DEFERRABLE" } else { "NOT DEFERRABLE" },
+ if state.initially_deferred { "DEFERRED" } else { "IMMEDIATE" },
+ if state.rely { "RELY" } else { "NORELY" }
+ );
+ let after = format!(
+ " {} {}",
+ if state.enabled { "ENABLE" } else { "DISABLE" },
+ if state.validated { "VALIDATE" } else { "NOVALIDATE" }
+ );
+ (before, after)
+ },
+ );
+ statements.push(format!("ALTER TABLE {table} ADD CONSTRAINT {name} PRIMARY KEY ({columns}){before_index}{using_index}{after_index};"));
+ }
+ TableStructureSqlResult { statements, warnings: Vec::new() }
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs
index 893bb3fbb1..d3280d2bb2 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs
@@ -18,6 +18,9 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
for index in &options.indexes {
if index.marked_for_drop {
+ if index.oracle_original_missing {
+ continue;
+ }
let Some(original) = &index.original else {
continue;
};
@@ -33,6 +36,10 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
statements.push(build_dameng_drop_constraint_sql(dialect, &table, &original.name));
continue;
}
+ if is_oceanbase_unique_constraint_index(options.database_type, original) {
+ warnings.push(format!("OceanBase Oracle unique index \"{}\" is paired with a UNIQUE constraint and must be changed through the constraint editor.", original.name));
+ continue;
+ }
statements.push(build_drop_index_sql(
options.database_type,
dialect,
@@ -68,9 +75,48 @@ pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut
));
continue;
}
+ if is_oceanbase_unique_constraint_index(options.database_type, original) {
+ warnings.push(format!("OceanBase Oracle unique index \"{}\" is paired with a UNIQUE constraint and must be changed through the constraint editor.", original.name));
+ continue;
+ }
let or_replace =
options.database_type == Some(DatabaseType::Dameng) && clean(&index.name) == clean(&original.name);
- if !or_replace {
+ if dialect == StructureDialect::Oracle {
+ // Oracle-family index edits may require DROP/CREATE. Validate that the
+ // complete replacement plan can be built before exposing its destructive
+ // first step; an empty/invalid target must never become a DROP-only plan.
+ let mut create_warnings = Vec::new();
+ let create_statements = build_create_index_statements(
+ options.database_type,
+ dialect,
+ &table,
+ index,
+ &mut create_warnings,
+ options.schema.as_deref(),
+ &options.table_name,
+ or_replace,
+ capabilities.index_concurrent,
+ false,
+ options.driver_profile.as_deref(),
+ );
+ if create_statements.is_empty() {
+ warnings.extend(create_warnings);
+ continue;
+ }
+ if !or_replace && !index.oracle_original_missing {
+ statements.push(build_drop_index_sql(
+ options.database_type,
+ dialect,
+ &table,
+ options.schema.as_deref(),
+ &original.name,
+ ));
+ }
+ warnings.extend(create_warnings);
+ statements.extend(create_statements);
+ continue;
+ }
+ if !or_replace && !index.oracle_original_missing {
statements.push(build_drop_index_sql(
options.database_type,
dialect,
@@ -132,6 +178,10 @@ fn is_dameng_constraint_backed(database_type: Option<DatabaseType>, original: &I
database_type == Some(DatabaseType::Dameng) && original.constraint_backed
}
+fn is_oceanbase_unique_constraint_index(database_type: Option<DatabaseType>, original: &IndexInfo) -> bool {
+ database_type == Some(DatabaseType::OceanbaseOracle) && original.is_unique
+}
+
fn build_dameng_drop_constraint_sql(dialect: StructureDialect, table: &str, constraint_name: &str) -> String {
format!("ALTER TABLE {table} DROP CONSTRAINT {};", quote_ident(dialect, constraint_name))
}
@@ -193,7 +243,8 @@ pub fn has_existing_index_change(index: &EditableStructureIndex) -> bool {
let Some(original) = &index.original else {
return false;
};
- clean(&index.name) != clean(&original.name)
+ index.oracle_original_missing
+ || clean(&index.name) != clean(&original.name)
|| index_list_changed(&index.columns, Some(&original.columns))
|| index.is_unique != original.is_unique
|| normalized_index_type(index) != clean(original.index_type.as_deref().unwrap_or("")).to_ascii_uppercase()
@@ -353,7 +404,7 @@ fn key_expression_flags(index: &EditableStructureIndex, columns: &[String]) -> V
.columns
.iter()
.enumerate()
- .find(|(i, original_column)| !consumed[*i] && *original_column == column);
+ .find(|(i, original_column)| !consumed[*i] && clean(original_column) == clean(column));
match claimed {
Some((i, _)) => {
consumed[i] = true;
@@ -365,6 +416,59 @@ fn key_expression_flags(index: &EditableStructureIndex, columns: &[String]) -> V
.collect()
}
+fn oracle_key_directions(
+ database_type: Option<DatabaseType>,
+ index: &EditableStructureIndex,
+ columns: &[String],
+ warnings: &mut Vec<String>,
+) -> Option<Vec<String>> {
+ let Some(original) = &index.original else {
+ return Some(Vec::new());
+ };
+ if !original.key_metadata_complete
+ || original.key_is_expression.len() != original.columns.len()
+ || original.key_directions.len() != original.columns.len()
+ || !matches!(original.visibility.as_deref(), Some("VISIBLE" | "INVISIBLE"))
+ || original.columns.iter().any(|column| clean(column).is_empty())
+ || original.key_directions.iter().any(|direction| !matches!(direction.as_str(), "ASC" | "DESC"))
+ {
+ warnings.push(format!(
+ "Index \"{}\" cannot be rebuilt because its expression, direction, or visibility metadata is incomplete.",
+ original.name
+ ));
+ return None;
+ }
+
+ let mut consumed = vec![false; original.columns.len()];
+ let directions = columns
+ .iter()
+ .map(|column| {
+ original
+ .columns
+ .iter()
+ .enumerate()
+ .find(|(position, original_column)| !consumed[*position] && clean(original_column) == clean(column))
+ .map(|(position, _)| {
+ consumed[position] = true;
+ original.key_directions[position].clone()
+ })
+ .unwrap_or_else(|| "ASC".to_string())
+ })
+ .collect::<Vec<_>>();
+
+ if database_type == Some(DatabaseType::OceanbaseOracle) {
+ if let Some((position, _)) = directions.iter().enumerate().find(|(_, direction)| *direction == "DESC") {
+ warnings.push(format!(
+ "OceanBase Oracle does not support descending index key {} on index \"{}\"; no DDL was generated.",
+ position + 1,
+ original.name
+ ));
+ return None;
+ }
+ }
+ Some(directions)
+}
+
/// Per-key operator class provenance for `columns` (the edited/current key list).
///
/// Honors explicit per-key opclasses (`index.column_opclasses`) positionally when
@@ -460,6 +564,18 @@ pub(super) fn build_create_index_statements(
if name.is_empty() || columns.is_empty() {
return Vec::new();
}
+ let oracle_directions = if matches!(database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle)) {
+ if index.original.as_ref().is_some_and(|_| columns.len() != index.columns.len()) {
+ warnings.push(format!("Index \"{}\" contains an empty key and cannot be rebuilt.", name));
+ return Vec::new();
+ }
+ match oracle_key_directions(database_type, index, &columns, warnings) {
+ Some(directions) => directions,
+ None => return Vec::new(),
+ }
+ } else {
+ Vec::new()
+ };
// `CREATE INDEX CONCURRENTLY` is PostgreSQL-only: the flag is honored only when
// the caller's real database type advertises the capability, so a stale or
@@ -477,16 +593,23 @@ pub(super) fn build_create_index_statements(
.iter()
.enumerate()
.map(|(i, column)| {
- if dialect == StructureDialect::Mysql {
+ let key = if dialect == StructureDialect::Mysql {
mysql_index_column_sql(column)
} else if dialect == StructureDialect::GaussdbM {
gaussdbm_index_column_sql(column, key_is_expression[i])
} else if dialect == StructureDialect::Postgres {
postgres_index_column_sql(column, key_is_expression[i], key_opclasses[i].as_deref())
+ } else if dialect == StructureDialect::Oracle && key_is_expression[i] {
+ column.trim().to_string()
} else if for_new_table {
quote_new_ident(database_type, dialect, column)
} else {
quote_ident(dialect, column)
+ };
+ if oracle_directions.is_empty() {
+ key
+ } else {
+ format!("{key} {}", oracle_directions[i])
}
})
.collect::<Vec<_>>()
@@ -548,6 +671,13 @@ pub(super) fn build_create_index_statements(
} else {
String::new()
};
+ let visibility_clause = if dialect == StructureDialect::Oracle
+ && index.original.as_ref().is_some_and(|original| original.visibility.as_deref() == Some("INVISIBLE"))
+ {
+ " INVISIBLE"
+ } else {
+ ""
+ };
let filter = clean(&index.filter);
let supports_where = capabilities.index_filter
&& matches!(dialect, StructureDialect::Postgres | StructureDialect::SqlServer | StructureDialect::Sqlite);
@@ -570,7 +700,7 @@ pub(super) fn build_create_index_statements(
)
} else {
format!(
- "CREATE {replace}{unique}{type_prefix}INDEX {index_name}{using_clause} ON {create_table} ({cols}){include_clause}{where_clause}{comment_clause};"
+ "CREATE {replace}{unique}{type_prefix}INDEX {index_name}{using_clause} ON {create_table} ({cols}){include_clause}{where_clause}{comment_clause}{visibility_clause};"
)
};
let mut statements = vec![create_sql];
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/oracle_constraints.rs b/crates/dbx-sql-schema/src/table_structure_sql/oracle_constraints.rs
new file mode 100644
index 0000000000..9493d50e93
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/oracle_constraints.rs
@@ -0,0 +1,552 @@
+use std::ops::ControlFlow;
+
+use sqlparser::ast::{Expr, Visitor};
+use sqlparser::dialect::OracleDialect;
+use sqlparser::parser::Parser;
+use sqlparser::tokenizer::{Token, Tokenizer};
+
+use super::dialect::StructureDialect;
+use super::util::{qualified_table, quote_ident};
+use super::{
+ OracleCheckConstraint, OracleConstraintChange, OracleConstraintDefinition, TableStructureSqlOptions,
+ TableStructureSqlResult,
+};
+use crate::models::connection::DatabaseType;
+
+pub(super) fn build_changes(options: TableStructureSqlOptions) -> TableStructureSqlResult {
+ let changes = options.oracle_constraint_changes.as_deref().unwrap_or_default();
+ let reject = |message: &str| TableStructureSqlResult { statements: vec![], warnings: vec![message.into()] };
+ let Some(database_type @ (DatabaseType::Oracle | DatabaseType::OceanbaseOracle)) = options.database_type else {
+ return reject("CHECK and UNIQUE changes require Oracle or OceanBase Oracle.");
+ };
+ if options.is_gaussdb_m_mode {
+ return reject("Apply CHECK or UNIQUE changes separately from other table structure drafts.");
+ }
+ let mut ordinary_options = options.clone();
+ ordinary_options.oracle_constraint_changes = None;
+ let ordinary = super::build_table_structure_change_sql(ordinary_options);
+ if !ordinary.statements.is_empty() || !ordinary.warnings.is_empty() {
+ return reject("Apply CHECK or UNIQUE changes separately from other table structure drafts.");
+ }
+
+ let mut names = std::collections::HashSet::new();
+ for change in changes {
+ let (original, target) = match (&change.original, &change.target) {
+ (None, None) => return reject("A constraint change must have an original or target definition."),
+ (original, target) => (original, target),
+ };
+ if database_type == DatabaseType::Oracle {
+ if let Some(OracleConstraintDefinition::Unique(old)) = original {
+ let requires_drop = match target {
+ None => true,
+ Some(OracleConstraintDefinition::Unique(new)) => {
+ old.columns != new.columns || old.state.deferrable != new.state.deferrable
+ }
+ Some(_) => true,
+ };
+ if requires_drop && !matches!(change.index_policy.as_str(), "keep" | "drop") {
+ return reject("Oracle UNIQUE rebuilds require an explicit KEEP INDEX or DROP INDEX choice.");
+ }
+ if old.state.enabled
+ && target.as_ref().is_some_and(
+ |value| matches!(value, OracleConstraintDefinition::Unique(new) if !new.state.enabled),
+ )
+ && !matches!(change.index_policy.as_str(), "keep" | "drop")
+ {
+ return reject(
+ "Disabling an Oracle UNIQUE constraint requires an explicit KEEP INDEX or DROP INDEX choice.",
+ );
+ }
+ }
+ }
+ for (is_original, definition) in [(true, original.as_ref()), (false, target.as_ref())] {
+ let Some(definition) = definition else { continue };
+ let name = match definition {
+ OracleConstraintDefinition::Check(check) => &check.name,
+ OracleConstraintDefinition::Unique(unique) => &unique.name,
+ };
+ if name.trim().is_empty() {
+ return reject("Constraint names must not be empty.");
+ }
+ match definition {
+ OracleConstraintDefinition::Check(check) => {
+ if let Err(message) = validate_check(check, database_type == DatabaseType::Oracle) {
+ return reject(message);
+ }
+ }
+ OracleConstraintDefinition::Unique(unique) => {
+ if let Err(message) = validate_unique(
+ unique,
+ database_type,
+ options.schema.as_deref(),
+ &options.table_name,
+ is_original,
+ &change.index_policy,
+ ) {
+ return reject(message);
+ }
+ }
+ }
+ }
+ if let Some(target) = target.as_ref() {
+ let name = match target {
+ OracleConstraintDefinition::Check(check) => &check.name,
+ OracleConstraintDefinition::Unique(unique) => &unique.name,
+ };
+ if !names.insert(name.clone()) {
+ return reject("Target constraint names must not repeat.");
+ }
+ }
+ }
+
+ let dialect = StructureDialect::Oracle;
+ let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
+ let mut statements = Vec::new();
+ let mut validated_statements = Vec::new();
+ for OracleConstraintChange { original, target, index_policy } in changes {
+ if original == target {
+ continue;
+ }
+ match (original, target) {
+ (None, Some(OracleConstraintDefinition::Check(check))) => {
+ statements.push(add_check(&table, check, database_type))
+ }
+ (Some(OracleConstraintDefinition::Check(old)), None) => statements.push(drop_constraint(&table, &old.name)),
+ (Some(OracleConstraintDefinition::Check(old)), Some(OracleConstraintDefinition::Check(new))) => {
+ if old.expression != new.expression
+ || old.state.deferrable != new.state.deferrable
+ || (database_type == DatabaseType::OceanbaseOracle && old.name != new.name)
+ {
+ statements.push(drop_constraint(&table, &old.name));
+ statements.push(add_check(&table, new, database_type));
+ } else if old.name != new.name && old.state == new.state {
+ if database_type == DatabaseType::Oracle {
+ statements.push(format!(
+ "ALTER TABLE {table} RENAME CONSTRAINT {} TO {};",
+ quote_ident(dialect, &old.name),
+ quote_ident(dialect, &new.name)
+ ));
+ } else {
+ statements.push(drop_constraint(&table, &old.name));
+ statements.push(add_check(&table, new, database_type));
+ }
+ } else if old.state != new.state {
+ if old.state.deferrable != new.state.deferrable {
+ statements.push(drop_constraint(&table, &old.name));
+ statements.push(add_check(&table, new, database_type));
+ } else {
+ let name = quote_ident(dialect, &old.name);
+ if old.state.enabled != new.state.enabled || old.state.validated != new.state.validated {
+ let enabled = if new.state.enabled { "ENABLE" } else { "DISABLE" };
+ let validated = if new.state.validated { "VALIDATE" } else { "NOVALIDATE" };
+ statements.push(format!("ALTER TABLE {table} {enabled} {validated} CONSTRAINT {name};"));
+ }
+ if old.state.rely != new.state.rely {
+ statements.push(format!(
+ "ALTER TABLE {table} MODIFY CONSTRAINT {name} {};",
+ if new.state.rely { "RELY" } else { "NORELY" }
+ ));
+ }
+ if old.state.initially_deferred != new.state.initially_deferred {
+ statements.push(format!(
+ "ALTER TABLE {table} MODIFY CONSTRAINT {name} INITIALLY {};",
+ if new.state.initially_deferred { "DEFERRED" } else { "IMMEDIATE" }
+ ));
+ }
+ if old.name != new.name {
+ statements.push(format!(
+ "ALTER TABLE {table} RENAME CONSTRAINT {} TO {};",
+ quote_ident(dialect, &old.name),
+ quote_ident(dialect, &new.name)
+ ));
+ }
+ }
+ }
+ }
+ (None, Some(OracleConstraintDefinition::Unique(unique))) => {
+ if let Some(statement) = add_unique(&table, unique, database_type, index_policy) {
+ statements.push(statement);
+ } else {
+ return reject("A verified supporting index or a collision-free new index name is required.");
+ }
+ }
+ (Some(OracleConstraintDefinition::Unique(old)), None) => {
+ statements.push(drop_unique(&table, old, database_type, index_policy));
+ }
+ (Some(OracleConstraintDefinition::Unique(old)), Some(OracleConstraintDefinition::Unique(new))) => {
+ if database_type == DatabaseType::Oracle
+ && old.columns == new.columns
+ && old.name != new.name
+ && old.state == new.state
+ {
+ statements.push(format!(
+ "ALTER TABLE {table} RENAME CONSTRAINT {} TO {};",
+ quote_ident(dialect, &old.name),
+ quote_ident(dialect, &new.name)
+ ));
+ } else if old.columns == new.columns && (old.name == new.name || database_type == DatabaseType::Oracle)
+ {
+ if old.state != new.state {
+ if old.state.deferrable != new.state.deferrable {
+ statements.push(drop_unique(&table, old, database_type, index_policy));
+ if let Some(statement) = add_unique(&table, new, database_type, index_policy) {
+ statements.push(statement);
+ } else {
+ return reject(
+ "A verified supporting index or a collision-free new index name is required.",
+ );
+ }
+ } else {
+ let name = quote_ident(dialect, &old.name);
+ if database_type == DatabaseType::Oracle
+ && !old.state.enabled
+ && new.state.enabled
+ && old.index.name.is_empty()
+ {
+ if let Some(statement) = add_unique(&table, new, database_type, index_policy) {
+ statements.push(drop_unique(&table, old, database_type, "keep"));
+ statements.push(statement);
+ } else {
+ return reject("Re-enabling a UNIQUE constraint without an index requires a collision-free supporting-index name.");
+ }
+ continue;
+ }
+ if old.state.enabled != new.state.enabled || old.state.validated != new.state.validated {
+ let enabled = if new.state.enabled { "ENABLE" } else { "DISABLE" };
+ let validated = if new.state.validated { "VALIDATE" } else { "NOVALIDATE" };
+ let index_clause =
+ if database_type == DatabaseType::Oracle && old.state.enabled && !new.state.enabled
+ {
+ match index_policy.as_str() {
+ "keep" => " KEEP INDEX",
+ "drop" => " DROP INDEX",
+ _ => return reject(
+ "Disabling an Oracle UNIQUE constraint requires KEEP INDEX or DROP INDEX.",
+ ),
+ }
+ } else {
+ ""
+ };
+ statements.push(format!(
+ "ALTER TABLE {table} {enabled} {validated} CONSTRAINT {name}{index_clause};"
+ ));
+ }
+ if old.state.rely != new.state.rely {
+ statements.push(format!(
+ "ALTER TABLE {table} MODIFY CONSTRAINT {name} {};",
+ if new.state.rely { "RELY" } else { "NORELY" }
+ ));
+ }
+ if old.state.initially_deferred != new.state.initially_deferred {
+ statements.push(format!(
+ "ALTER TABLE {table} MODIFY CONSTRAINT {name} INITIALLY {};",
+ if new.state.initially_deferred { "DEFERRED" } else { "IMMEDIATE" }
+ ));
+ }
+ if old.name != new.name {
+ statements.push(format!(
+ "ALTER TABLE {table} RENAME CONSTRAINT {} TO {};",
+ quote_ident(dialect, &old.name),
+ quote_ident(dialect, &new.name)
+ ));
+ }
+ }
+ }
+ } else {
+ statements.push(drop_unique(&table, old, database_type, index_policy));
+ if let Some(statement) = add_unique(&table, new, database_type, index_policy) {
+ statements.push(statement);
+ } else {
+ return reject("A verified supporting index or a collision-free new index name is required.");
+ }
+ }
+ }
+ _ => return reject("This CHECK/UNIQUE change shape is not supported yet."),
+ }
+ }
+ for statement in statements {
+ if statement.to_ascii_uppercase().contains(" CHECK (") {
+ let tokens = match Tokenizer::new(&OracleDialect, &statement).tokenize() {
+ Ok(tokens) => tokens,
+ Err(_) => return reject("Generated CHECK DDL failed structural validation."),
+ };
+ let check_token = tokens
+ .iter()
+ .position(|token| matches!(token, Token::Word(word) if word.value.eq_ignore_ascii_case("CHECK")));
+ let Some(check_token) = check_token else {
+ return reject("Generated CHECK DDL failed structural validation.");
+ };
+ let open = tokens
+ .iter()
+ .enumerate()
+ .skip(check_token + 1)
+ .find(|(_, token)| matches!(token, Token::LParen))
+ .map(|(index, _)| index);
+ let Some(open) = open else {
+ return reject("Generated CHECK DDL failed structural validation.");
+ };
+ let mut depth = 0usize;
+ let mut close = None;
+ for (index, token) in tokens.iter().enumerate().skip(open) {
+ match token {
+ Token::LParen => depth += 1,
+ Token::RParen => {
+ depth -= 1;
+ if depth == 0 {
+ close = Some(index);
+ break;
+ }
+ }
+ _ => {}
+ }
+ }
+ let Some(close) = close else {
+ return reject("Generated CHECK DDL failed structural validation.");
+ };
+ if close <= open {
+ return reject("Generated CHECK DDL failed structural validation.");
+ }
+ }
+ validated_statements.push(statement);
+ }
+ TableStructureSqlResult { statements: validated_statements, warnings: vec![] }
+}
+
+fn validate_unique(
+ unique: &super::OracleUniqueConstraint,
+ database_type: DatabaseType,
+ schema: Option<&str>,
+ table_name: &str,
+ is_original: bool,
+ index_policy: &str,
+) -> Result<(), &'static str> {
+ if unique.columns.is_empty() || unique.columns.iter().any(|column| column.trim().is_empty()) {
+ return Err("UNIQUE constraints require nonempty ordered columns.");
+ }
+ if unique.columns.iter().collect::<std::collections::HashSet<_>>().len() != unique.columns.len() {
+ return Err("UNIQUE constraint columns must not repeat.");
+ }
+ if unique.state.initially_deferred && !unique.state.deferrable {
+ return Err("Initially deferred UNIQUE constraints must be deferrable.");
+ }
+ if database_type == DatabaseType::OceanbaseOracle
+ && (!unique.state.enabled
+ || !unique.state.validated
+ || unique.state.deferrable
+ || unique.state.initially_deferred
+ || unique.state.rely
+ || (is_original && unique.rely_raw != "NULL"))
+ {
+ return Err("OceanBase Oracle UNIQUE changes require the verified ENABLED, VALIDATED, NOT DEFERRABLE, IMMEDIATE, RELY NULL state.");
+ }
+ if database_type == DatabaseType::OceanbaseOracle && index_policy != "none" {
+ return Err("OceanBase Oracle manages a UNIQUE constraint and its paired index as one object.");
+ }
+ if database_type == DatabaseType::Oracle && !matches!(index_policy, "keep" | "drop" | "none") {
+ return Err("UNIQUE supporting index policy is not supported.");
+ }
+ if index_policy == "drop" && unique.index.sharing != "exclusive" {
+ return Err("A supporting index cannot be dropped when sharing is known or unknown.");
+ }
+ if is_original && unique.index.name.trim().is_empty() {
+ if !unique.index.metadata_complete || unique.state.enabled {
+ return Err("An enabled UNIQUE constraint requires a complete supporting-index identity.");
+ }
+ } else if !unique.index.name.trim().is_empty() {
+ let index = &unique.index;
+ if !index.metadata_complete
+ || index.owner.trim().is_empty()
+ || index.name.trim().is_empty()
+ || index.owner != schema.unwrap_or_default()
+ || index.table_owner != schema.unwrap_or_default()
+ || index.table_name != table_name
+ || index.index_type != "NORMAL"
+ || (unique.state.deferrable && index.uniqueness != "NONUNIQUE")
+ || !matches!(index.uniqueness.as_str(), "UNIQUE" | "NONUNIQUE")
+ || index.status != "VALID"
+ || index.partitioned
+ || index.visibility != "VISIBLE"
+ || match database_type {
+ DatabaseType::Oracle => index.secondary.as_deref().is_some_and(|value| value != "N"),
+ DatabaseType::OceanbaseOracle => index.secondary.is_some(),
+ _ => true,
+ }
+ || index.columns.len() != unique.columns.len()
+ || !same_identifier_set(&index.columns, &unique.columns)
+ || index.directions.len() != index.columns.len()
+ || index.directions.iter().any(|direction| direction != "ASC")
+ || index.key_is_expression.len() != index.columns.len()
+ || index.key_is_expression.iter().any(|is_expression| *is_expression)
+ || !index.included_columns.is_empty()
+ {
+ return Err("UNIQUE supporting index metadata is incomplete or outside the verified ordinary-index shape.");
+ }
+ } else if database_type == DatabaseType::Oracle
+ && unique.state.enabled
+ && (unique.index.new_name.as_deref().is_none_or(str::is_empty)
+ || !unique.index.new_name_available
+ || unique.index.owner != schema.unwrap_or_default())
+ {
+ return Err("A collision-free new UNIQUE index name is required.");
+ }
+ if unique.index.new_name.as_deref().is_some_and(str::is_empty)
+ || (unique.index.new_name.is_some() && !unique.index.new_name_available)
+ || (unique.index.new_name.is_some() && unique.index.owner != schema.unwrap_or_default())
+ {
+ return Err("The replacement UNIQUE index name is missing or already in use.");
+ }
+ Ok(())
+}
+
+fn validate_check(check: &OracleCheckConstraint, oracle: bool) -> Result<(), &'static str> {
+ if check.expression.trim().is_empty() {
+ return Err("CHECK expression must not be empty.");
+ }
+ let mut parser = Parser::new(&OracleDialect)
+ .try_with_sql(&check.expression)
+ .map_err(|_| "CHECK expression is not supported by the Oracle expression parser.")?;
+ let expression =
+ parser.parse_expr().map_err(|_| "CHECK expression is not supported by the Oracle expression parser.")?;
+ if !matches!(parser.peek_token().token, Token::EOF) {
+ return Err("CHECK expression must contain exactly one expression.");
+ }
+ struct SubqueryGuard(bool);
+ impl Visitor for SubqueryGuard {
+ type Break = ();
+ fn pre_visit_expr(&mut self, expression: &Expr) -> ControlFlow<Self::Break> {
+ if matches!(expression, Expr::Subquery(_) | Expr::InSubquery { .. } | Expr::Exists { .. }) {
+ self.0 = true;
+ ControlFlow::Break(())
+ } else {
+ ControlFlow::Continue(())
+ }
+ }
+ }
+ let mut guard = SubqueryGuard(false);
+ let _ = sqlparser::ast::Visit::visit(&expression, &mut guard);
+ if guard.0 {
+ return Err("Subqueries are not supported in CHECK expressions.");
+ }
+ if (check.state.initially_deferred && !check.state.deferrable)
+ || (!oracle && (check.state.deferrable || check.state.initially_deferred || check.state.rely))
+ {
+ return Err("This CHECK constraint state is not supported.");
+ }
+ Ok(())
+}
+
+fn add_check(table: &str, check: &OracleCheckConstraint, database_type: DatabaseType) -> String {
+ format!(
+ "ALTER TABLE {table} ADD CONSTRAINT {} CHECK (\n{}\n){};",
+ quote_ident(StructureDialect::Oracle, &check.name),
+ check.expression,
+ constraint_state_suffix(&check.state, database_type)
+ )
+}
+
+fn add_unique(
+ table: &str,
+ unique: &super::OracleUniqueConstraint,
+ database_type: DatabaseType,
+ index_policy: &str,
+) -> Option<String> {
+ let dialect = StructureDialect::Oracle;
+ let columns = unique.columns.iter().map(|column| quote_ident(dialect, column)).collect::<Vec<_>>().join(", ");
+ let index = &unique.index;
+ let using_index = if !unique.state.enabled || database_type == DatabaseType::OceanbaseOracle {
+ String::new()
+ } else if !index.name.is_empty()
+ && index.metadata_complete
+ && index_policy != "drop"
+ && index.sharing == "exclusive"
+ && if unique.state.deferrable {
+ index.uniqueness == "NONUNIQUE"
+ } else {
+ matches!(index.uniqueness.as_str(), "UNIQUE" | "NONUNIQUE")
+ }
+ && same_identifier_set(&index.columns, &unique.columns)
+ {
+ format!(" USING INDEX {}", qualified_table(dialect, Some(&index.owner), &index.name))
+ } else {
+ let new_name = index.new_name.as_deref()?;
+ let index_ref = qualified_table(dialect, Some(&index.owner), new_name);
+ let kind = if unique.state.deferrable || !unique.state.validated { "INDEX" } else { "UNIQUE INDEX" };
+ format!(" USING INDEX (CREATE {kind} {index_ref} ON {table} ({columns}))")
+ };
+ let (before_index, after_index) = constraint_state_parts(&unique.state, database_type);
+ Some(format!(
+ "ALTER TABLE {table} ADD CONSTRAINT {} UNIQUE ({columns}){before_index}{using_index}{after_index};",
+ quote_ident(dialect, &unique.name),
+ ))
+}
+
+fn drop_unique(
+ table: &str,
+ unique: &super::OracleUniqueConstraint,
+ database_type: DatabaseType,
+ index_policy: &str,
+) -> String {
+ let index_clause = match (database_type, index_policy) {
+ (DatabaseType::Oracle, "keep") => " KEEP INDEX",
+ (DatabaseType::Oracle, "drop") => " DROP INDEX",
+ _ => "",
+ };
+ format!(
+ "ALTER TABLE {table} DROP CONSTRAINT {}{index_clause};",
+ quote_ident(StructureDialect::Oracle, &unique.name)
+ )
+}
+
+fn constraint_state_parts(state: &super::OraclePrimaryKeyState, database_type: DatabaseType) -> (String, String) {
+ let enabled = if state.enabled { "ENABLE" } else { "DISABLE" };
+ let validated = if state.validated { "VALIDATE" } else { "NOVALIDATE" };
+ let rely = if state.rely { "RELY" } else { "NORELY" };
+ if database_type == DatabaseType::Oracle {
+ (
+ format!(
+ " {} INITIALLY {} {rely}",
+ if state.deferrable { "DEFERRABLE" } else { "NOT DEFERRABLE" },
+ if state.initially_deferred { "DEFERRED" } else { "IMMEDIATE" }
+ ),
+ format!(" {enabled} {validated}"),
+ )
+ } else {
+ (String::new(), format!(" {enabled} {validated}"))
+ }
+}
+
+fn constraint_state_suffix(state: &super::OraclePrimaryKeyState, database_type: DatabaseType) -> String {
+ let (before_index, after_index) = constraint_state_parts(state, database_type);
+ format!("{before_index}{after_index}")
+}
+
+fn same_identifier_set(left: &[String], right: &[String]) -> bool {
+ left.len() == right.len() && left.iter().all(|left| right.iter().any(|right| left == right))
+}
+
+fn drop_constraint(table: &str, name: &str) -> String {
+ format!("ALTER TABLE {table} DROP CONSTRAINT {};", quote_ident(StructureDialect::Oracle, name))
+}
+
+#[cfg(test)]
+mod additional_tests {
+ use super::*;
+
+ #[test]
+ fn check_add_keeps_closing_parenthesis_outside_line_comment() {
+ let check = OracleCheckConstraint {
+ name: "CK_T".into(),
+ expression: "A > 0 -- tail comment".into(),
+ state: super::super::OraclePrimaryKeyState {
+ enabled: true,
+ validated: true,
+ deferrable: false,
+ initially_deferred: false,
+ rely: false,
+ },
+ };
+ let sql = add_check("\"APP\".\"T\"", &check, DatabaseType::Oracle);
+ assert!(sql
+ .contains("CHECK (\nA > 0 -- tail comment\n) NOT DEFERRABLE INITIALLY IMMEDIATE NORELY ENABLE VALIDATE;"));
+ }
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/oracle_foreign_keys.rs b/crates/dbx-sql-schema/src/table_structure_sql/oracle_foreign_keys.rs
new file mode 100644
index 0000000000..0ebe03f3c2
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/oracle_foreign_keys.rs
@@ -0,0 +1,242 @@
+use std::collections::HashSet;
+
+use super::dialect::StructureDialect;
+use super::util::{qualified_new_table, qualified_table, quote_ident, quote_new_ident};
+use super::{
+ build_table_structure_change_sql, OracleForeignKeyDefinition, TableStructureSqlOptions, TableStructureSqlResult,
+};
+use crate::models::connection::DatabaseType;
+
+pub(super) fn build_changes(mut options: TableStructureSqlOptions) -> TableStructureSqlResult {
+ let changes = options.oracle_foreign_key_changes.take().expect("Oracle foreign key changes");
+ let reject = |message: &str| TableStructureSqlResult { statements: vec![], warnings: vec![message.into()] };
+ let oracle = options.database_type == Some(DatabaseType::Oracle);
+ if !matches!(options.database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle))
+ || options.is_gaussdb_m_mode
+ {
+ return reject("Ordered foreign key changes require Oracle or OceanBase Oracle.");
+ }
+ if options.primary_key_change.is_some() || !options.foreign_keys.is_empty() {
+ return reject("Apply other table structure changes separately from Oracle foreign key changes.");
+ }
+ let ordinary = build_table_structure_change_sql(options.clone());
+ if !ordinary.statements.is_empty() || !ordinary.warnings.is_empty() {
+ return reject("Apply other table structure changes separately from Oracle foreign key changes.");
+ }
+ let mut original_names = HashSet::new();
+ let mut target_names = HashSet::new();
+ for change in &changes {
+ if change.original.is_none() && change.target.is_none() {
+ return reject("A foreign key change must have an original or target definition.");
+ }
+ for definition in [&change.original, &change.target].into_iter().flatten() {
+ if let Err(message) = validate(definition, oracle) {
+ return reject(message);
+ }
+ }
+ if let Some(original) = &change.original {
+ if !original_names.insert(&original.name) {
+ return reject("Original foreign key names must not repeat.");
+ }
+ }
+ if let Some(target) = &change.target {
+ if !target_names.insert(&target.name) {
+ return reject("Target foreign key names must not repeat.");
+ }
+ }
+ }
+ for change in &changes {
+ if let Some(target) = &change.target {
+ if original_names.contains(&target.name)
+ && change.original.as_ref().is_none_or(|old| old.name != target.name)
+ {
+ return reject("Foreign key name exchanges are not supported in one plan.");
+ }
+ }
+ }
+ let table = qualified_table(StructureDialect::Oracle, options.schema.as_deref(), &options.table_name);
+ let mut statements = vec![];
+ for change in changes {
+ if change.original == change.target {
+ continue;
+ }
+ match (change.original, change.target) {
+ (None, Some(target)) => statements.push(add_sql(&table, &target, oracle)),
+ (Some(original), None) => statements.push(drop_sql(&table, &original.name)),
+ (Some(original), Some(target)) => {
+ let mut definition = original.clone();
+ definition.name = target.name.clone();
+ definition.state = target.state.clone();
+ let same_definition = definition == target && original.state.deferrable == target.state.deferrable;
+ if same_definition && (oracle || original.name == target.name) {
+ let name = quote_ident(StructureDialect::Oracle, &original.name);
+ if original.state.enabled != target.state.enabled
+ || original.state.validated != target.state.validated
+ {
+ let enabled = if target.state.enabled { "ENABLE" } else { "DISABLE" };
+ let validated = if target.state.validated { "VALIDATE" } else { "NOVALIDATE" };
+ statements.push(format!("ALTER TABLE {table} {enabled} {validated} CONSTRAINT {name};"));
+ }
+ if original.state.rely != target.state.rely {
+ let rely = if target.state.rely { "RELY" } else { "NORELY" };
+ statements.push(format!("ALTER TABLE {table} MODIFY CONSTRAINT {name} {rely};"));
+ }
+ if original.state.initially_deferred != target.state.initially_deferred {
+ let deferred = if target.state.initially_deferred { "DEFERRED" } else { "IMMEDIATE" };
+ statements.push(format!("ALTER TABLE {table} MODIFY CONSTRAINT {name} INITIALLY {deferred};"));
+ }
+ if original.name != target.name {
+ statements.push(format!(
+ "ALTER TABLE {table} RENAME CONSTRAINT {name} TO {};",
+ quote_ident(StructureDialect::Oracle, &target.name)
+ ));
+ }
+ } else {
+ statements.push(drop_sql(&table, &original.name));
+ statements.push(add_sql(&table, &target, oracle));
+ }
+ }
+ (None, None) => unreachable!(),
+ }
+ }
+ TableStructureSqlResult { statements, warnings: vec![] }
+}
+
+fn validate(key: &OracleForeignKeyDefinition, oracle: bool) -> Result<(), &'static str> {
+ if key.name.is_empty()
+ || key.ref_schema.is_empty()
+ || key.ref_table.is_empty()
+ || key.columns.is_empty()
+ || key.columns.len() != key.ref_columns.len()
+ || key.columns.iter().chain(&key.ref_columns).any(String::is_empty)
+ {
+ return Err("Foreign key identity and equal nonempty ordered column lists are required.");
+ }
+ for columns in [&key.columns, &key.ref_columns] {
+ if columns.iter().collect::<HashSet<_>>().len() != columns.len() {
+ return Err("Foreign key columns must not repeat.");
+ }
+ }
+ if !matches!(key.on_delete.as_str(), "NO ACTION" | "CASCADE" | "SET NULL") {
+ return Err("Unsupported Oracle foreign key delete action.");
+ }
+ if (!key.state.deferrable && key.state.initially_deferred)
+ || (key.state.validated && key.state.rely)
+ || (!oracle && (key.state.deferrable || key.state.initially_deferred))
+ {
+ return Err("The foreign key state is invalid or unsupported by this engine.");
+ }
+ Ok(())
+}
+
+fn drop_sql(table: &str, name: &str) -> String {
+ format!("ALTER TABLE {table} DROP CONSTRAINT {};", quote_ident(StructureDialect::Oracle, name))
+}
+
+pub(super) fn build_new_table_keys(options: &TableStructureSqlOptions) -> Result<Vec<String>, &'static str> {
+ let Some(changes) = &options.oracle_foreign_key_changes else {
+ return Ok(vec![]);
+ };
+ if !matches!(options.database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle))
+ || options.is_gaussdb_m_mode
+ {
+ return Err("Ordered foreign key changes require Oracle or OceanBase Oracle.");
+ }
+ if !options.foreign_keys.is_empty() || options.primary_key_change.is_some() {
+ return Err("New Oracle foreign keys must use only the ordered creation definitions.");
+ }
+ let oracle = options.database_type == Some(DatabaseType::Oracle);
+ let dialect = StructureDialect::Oracle;
+ let table = qualified_new_table(options.database_type, dialect, options.schema.as_deref(), &options.table_name);
+ let source_columns: HashSet<_> =
+ options.columns.iter().filter(|column| !column.marked_for_drop).map(|column| &column.name).collect();
+ let primary_key_columns: Vec<_> = options
+ .columns
+ .iter()
+ .filter(|column| !column.marked_for_drop && column.is_primary_key)
+ .map(|column| &column.name)
+ .collect();
+ let mut names = HashSet::new();
+ let name_identity = |name: &str| {
+ let reference = quote_new_ident(options.database_type, dialect, name);
+ if oracle && !reference.starts_with('"') {
+ reference.to_ascii_uppercase()
+ } else {
+ reference
+ }
+ };
+ if let Some(name) = &options.primary_key_name {
+ names.insert(name_identity(name));
+ }
+ let mut statements = vec![];
+ for change in changes {
+ if change.original.is_some() {
+ return Err("A new table cannot replace an existing foreign key.");
+ }
+ let Some(key) = &change.target else {
+ return Err("A new foreign key requires a target definition.");
+ };
+ validate(key, oracle)?;
+ if !names.insert(name_identity(&key.name)) {
+ return Err("New constraint names must not repeat.");
+ }
+ if key.columns.iter().any(|name| !source_columns.contains(name)) {
+ return Err("Foreign key source columns must exist in the new table draft.");
+ }
+ let self_reference =
+ options.schema.as_deref().is_some_and(|schema| name_identity(schema) == name_identity(&key.ref_schema))
+ && name_identity(&options.table_name) == name_identity(&key.ref_table);
+ if self_reference && key.ref_columns.iter().any(|name| !source_columns.contains(name)) {
+ return Err("Self-referenced columns must exist in the new table draft.");
+ }
+ if self_reference
+ && (key.ref_columns.len() != primary_key_columns.len()
+ || key.ref_columns.iter().any(|name| !primary_key_columns.contains(&name)))
+ {
+ return Err("Self-referenced columns must match the new table primary key.");
+ }
+ let source_quote = |name: &str| quote_new_ident(options.database_type, dialect, name);
+ let columns = key.columns.iter().map(|name| source_quote(name)).collect::<Vec<_>>().join(", ");
+ let ref_columns = key
+ .ref_columns
+ .iter()
+ .map(|name| if self_reference { source_quote(name) } else { quote_ident(dialect, name) })
+ .collect::<Vec<_>>()
+ .join(", ");
+ let ref_target = if self_reference {
+ table.clone()
+ } else {
+ format!("{}.{}", quote_ident(dialect, &key.ref_schema), quote_ident(dialect, &key.ref_table))
+ };
+ statements.push(format!(
+ "ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({columns}) REFERENCES {ref_target} ({ref_columns}){};",
+ source_quote(&key.name),
+ suffix(key, oracle)
+ ));
+ }
+ Ok(statements)
+}
+
+fn add_sql(table: &str, key: &OracleForeignKeyDefinition, oracle: bool) -> String {
+ let quote = |name: &str| quote_ident(StructureDialect::Oracle, name);
+ let columns = key.columns.iter().map(|name| quote(name)).collect::<Vec<_>>().join(", ");
+ let ref_columns = key.ref_columns.iter().map(|name| quote(name)).collect::<Vec<_>>().join(", ");
+ format!(
+ "ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({columns}) REFERENCES {}.{} ({ref_columns}){};",
+ quote(&key.name),
+ quote(&key.ref_schema),
+ quote(&key.ref_table),
+ suffix(key, oracle)
+ )
+}
+
+fn suffix(key: &OracleForeignKeyDefinition, oracle: bool) -> String {
+ let action = if key.on_delete == "NO ACTION" { String::new() } else { format!(" ON DELETE {}", key.on_delete) };
+ let deferrable = if key.state.deferrable { "DEFERRABLE" } else { "NOT DEFERRABLE" };
+ let initially = if key.state.initially_deferred { "DEFERRED" } else { "IMMEDIATE" };
+ let deferred_clause = if oracle { format!(" {deferrable} INITIALLY {initially}") } else { String::new() };
+ let rely = if key.state.rely { "RELY" } else { "NORELY" };
+ let enabled = if key.state.enabled { "ENABLE" } else { "DISABLE" };
+ let validated = if key.state.validated { "VALIDATE" } else { "NOVALIDATE" };
+ format!("{action}{deferred_clause} {rely} {enabled} {validated}")
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
index ba57e413e5..518694bc68 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
@@ -69,9 +69,209 @@ fn structure_change_options(
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
}
}
+#[test]
+fn oceanbase_existing_primary_key_ordered_change_payload() {
+ let options = structure_change_options(
+ DatabaseType::OceanbaseOracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true), existing_pk_column("V", "NUMBER", true, true)],
+ );
+ let mut payload = serde_json::to_value(options).unwrap();
+ payload["primaryKeyChange"] = serde_json::json!({
+ "name": "PK_SOURCE",
+ "originalColumns": ["ID", "V"],
+ "columns": ["V", "ID"]
+ });
+ let result = build_table_structure_change_sql(serde_json::from_value(payload).unwrap());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE \"APP\".\"SOURCE\" DROP CONSTRAINT \"PK_SOURCE\";",
+ "ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"PK_SOURCE\" PRIMARY KEY (\"V\", \"ID\");",
+ ]
+ );
+}
+
+#[test]
+fn oceanbase_existing_primary_key_delete_payload() {
+ let options = structure_change_options(
+ DatabaseType::OceanbaseOracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true)],
+ );
+ let mut payload = serde_json::to_value(options).unwrap();
+ payload["primaryKeyChange"] = serde_json::json!({
+ "name": "PK_SOURCE",
+ "originalColumns": ["ID"],
+ "columns": []
+ });
+ let result = build_table_structure_change_sql(serde_json::from_value(payload).unwrap());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE \"APP\".\"SOURCE\" DROP CONSTRAINT \"PK_SOURCE\";"]);
+}
+
+#[test]
+fn oracle_existing_primary_key_explicit_index_policy() {
+ let options = structure_change_options(
+ DatabaseType::Oracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true), existing_pk_column("V", "NUMBER", true, true)],
+ );
+ for (policy, columns, new_name, expected_add) in [
+ ("keep", vec!["V", "ID"], None, Some("ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"PK_SOURCE\" PRIMARY KEY (\"V\", \"ID\") USING INDEX \"APP\".\"ORIGINAL_IDX\";")),
+ ("keep", vec!["V"], Some("SOURCE_V_IDX"), Some("ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"PK_SOURCE\" PRIMARY KEY (\"V\") USING INDEX (CREATE UNIQUE INDEX \"APP\".\"SOURCE_V_IDX\" ON \"APP\".\"SOURCE\" (\"V\"));")),
+ ("drop", vec!["V", "ID"], Some("SOURCE_V_ID_IDX"), Some("ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"PK_SOURCE\" PRIMARY KEY (\"V\", \"ID\") USING INDEX (CREATE UNIQUE INDEX \"APP\".\"SOURCE_V_ID_IDX\" ON \"APP\".\"SOURCE\" (\"V\", \"ID\"));")),
+ ("keep", vec![], None, None),
+ ("drop", vec![], None, None),
+ ] {
+ let mut payload = serde_json::to_value(&options).unwrap();
+ payload["primaryKeyChange"] = serde_json::json!({
+ "name": "PK_SOURCE", "originalColumns": ["ID", "V"], "columns": columns,
+ "oracleIndex": { "policy": policy, "owner": "APP", "name": "ORIGINAL_IDX", "newName": new_name }
+ });
+ let result = build_table_structure_change_sql(serde_json::from_value(payload).unwrap());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ let mut expected = vec![format!("ALTER TABLE \"APP\".\"SOURCE\" DROP CONSTRAINT \"PK_SOURCE\" {} INDEX;", policy.to_uppercase())];
+ if let Some(add) = expected_add { expected.push(add.to_string()); }
+ assert_eq!(result.statements, expected);
+ }
+}
+
+#[test]
+fn oracle_existing_primary_key_rejects_unverified_index_plan() {
+ let options = structure_change_options(
+ DatabaseType::Oracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true), existing_pk_column("V", "NUMBER", false, false)],
+ );
+ let mut payload = serde_json::to_value(options).unwrap();
+ payload["primaryKeyChange"] = serde_json::json!({
+ "name": "PK_SOURCE", "originalColumns": ["ID"], "columns": ["V"],
+ "oracleIndex": {"policy": "keep", "owner": "APP", "name": "PK_SOURCE", "newName": "SOURCE_V_IDX"}
+ });
+ for (pointer, value) in [
+ ("/primaryKeyChange/oracleIndex", serde_json::Value::Null),
+ ("/primaryKeyChange/oracleIndex/policy", serde_json::json!("cascade")),
+ ("/primaryKeyChange/oracleIndex/owner", serde_json::json!("OTHER")),
+ ("/primaryKeyChange/oracleIndex/name", serde_json::json!("")),
+ ("/primaryKeyChange/oracleIndex/newName", serde_json::Value::Null),
+ ("/primaryKeyChange/oracleIndex/newName", serde_json::json!("PK_SOURCE")),
+ ("/primaryKeyChange/oracleIndex/newName", serde_json::json!("INVALID; DROP TABLE X")),
+ ("/databaseType", serde_json::json!("oceanbase-oracle")),
+ ] {
+ let mut invalid = payload.clone();
+ *invalid.pointer_mut(pointer).unwrap() = value;
+ let result = build_table_structure_change_sql(serde_json::from_value(invalid).unwrap());
+ assert!(result.statements.is_empty(), "{pointer}: {:?}", result.statements);
+ assert!(!result.warnings.is_empty(), "{pointer}");
+ }
+}
+
+#[test]
+fn oracle_existing_primary_key_preserves_disabled_state_without_index() {
+ let options = structure_change_options(
+ DatabaseType::Oracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true), existing_pk_column("V", "NUMBER", true, true)],
+ );
+ let mut payload = serde_json::to_value(options).unwrap();
+ payload["primaryKeyChange"] = serde_json::json!({
+ "name":"PK_SOURCE", "originalColumns":["ID","V"], "columns":["V","ID"],
+ "oracleIndex":{"policy":"none","owner":"APP","name":""},
+ "oracleState":{"enabled":false,"validated":false,"deferrable":false,"initiallyDeferred":false,"rely":true}
+ });
+ let result = build_table_structure_change_sql(serde_json::from_value(payload).unwrap());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec![
+ "ALTER TABLE \"APP\".\"SOURCE\" DROP CONSTRAINT \"PK_SOURCE\";",
+ "ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"PK_SOURCE\" PRIMARY KEY (\"V\", \"ID\") NOT DEFERRABLE INITIALLY IMMEDIATE RELY DISABLE NOVALIDATE;",
+ ]);
+}
+
+#[test]
+fn oracle_existing_primary_key_preserves_deferred_state_with_nonunique_index() {
+ let options = structure_change_options(
+ DatabaseType::Oracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true), existing_pk_column("V", "NUMBER", true, true)],
+ );
+ let mut payload = serde_json::to_value(options).unwrap();
+ payload["primaryKeyChange"] = serde_json::json!({
+ "name":"PK_SOURCE", "originalColumns":["ID","V"], "columns":["V","ID"],
+ "oracleIndex":{"policy":"drop","owner":"APP","name":"OLD_INDEX","newName":"NEW_INDEX"},
+ "oracleState":{"enabled":true,"validated":true,"deferrable":true,"initiallyDeferred":true,"rely":false}
+ });
+ let result = build_table_structure_change_sql(serde_json::from_value(payload).unwrap());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec![
+ "ALTER TABLE \"APP\".\"SOURCE\" DROP CONSTRAINT \"PK_SOURCE\" DROP INDEX;",
+ "ALTER TABLE \"APP\".\"SOURCE\" ADD CONSTRAINT \"PK_SOURCE\" PRIMARY KEY (\"V\", \"ID\") DEFERRABLE INITIALLY DEFERRED NORELY USING INDEX (CREATE INDEX \"APP\".\"NEW_INDEX\" ON \"APP\".\"SOURCE\" (\"V\", \"ID\")) ENABLE VALIDATE;",
+ ]);
+}
+
+#[test]
+fn oceanbase_existing_primary_key_rejects_invalid_or_combined_drafts() {
+ let options = structure_change_options(
+ DatabaseType::OceanbaseOracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true), existing_pk_column("V", "NUMBER", false, false)],
+ );
+ let mut payload = serde_json::to_value(options).unwrap();
+ payload["primaryKeyChange"] =
+ serde_json::json!({ "name": "PK_SOURCE", "originalColumns": ["ID"], "columns": ["V"] });
+ for (pointer, value) in [
+ ("/databaseType", serde_json::json!("oracle")),
+ ("/databaseType", serde_json::json!("saphana")),
+ ("/databaseType", serde_json::json!("mysql")),
+ ("/primaryKeyChange/name", serde_json::json!("")),
+ ("/primaryKeyChange/columns", serde_json::json!(["V", "V"])),
+ ("/primaryKeyChange/columns", serde_json::json!(["UNKNOWN"])),
+ ("/primaryKeyChange/originalColumns", serde_json::json!(["V"])),
+ ("/columns/0/comment", serde_json::json!("changed comment")),
+ ("/columns/1/markedForDrop", serde_json::json!(true)),
+ ] {
+ let mut invalid = payload.clone();
+ *invalid.pointer_mut(pointer).unwrap() = value;
+ let result = build_table_structure_change_sql(serde_json::from_value(invalid).unwrap());
+ assert!(result.statements.is_empty(), "{pointer}: {:?}", result.statements);
+ assert!(!result.warnings.is_empty(), "{pointer}");
+ }
+}
+
+#[test]
+fn oceanbase_existing_primary_key_unchanged_order_is_a_noop() {
+ let mut options = structure_change_options(
+ DatabaseType::OceanbaseOracle,
+ Some("APP"),
+ "SOURCE",
+ vec![existing_pk_column("ID", "NUMBER", true, true)],
+ );
+ options.primary_key_change = Some(ExistingPrimaryKeyChange {
+ name: "PK_SOURCE".to_string(),
+ original_columns: vec!["ID".to_string()],
+ columns: vec!["ID".to_string()],
+ oracle_index: None,
+ oracle_state: None,
+ });
+ let result = build_table_structure_change_sql(options);
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.is_empty());
+}
+
#[test]
fn mysql_table_engine_change_generates_alter_table() {
let mut options = structure_change_options(DatabaseType::Mysql, Some("dbx_test"), "remote_orders", Vec::new());
@@ -401,6 +601,7 @@ fn index(name: &str, columns: &[&str]) -> EditableStructureIndex {
comment: String::new(),
concurrently: false,
original: None,
+ oracle_original_missing: false,
marked_for_drop: false,
}
}
@@ -418,6 +619,9 @@ fn existing_index(name: &str, columns: &[&str], is_unique: bool) -> EditableStru
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -464,6 +668,9 @@ fn index_change_options(
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
}
}
@@ -526,6 +733,9 @@ fn builds_mysql_column_and_index_changes() {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -551,6 +761,9 @@ fn builds_mysql_column_and_index_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -847,6 +1060,13 @@ fn non_dameng_index_rebuilds_do_not_use_or_replace() {
] {
let mut changed = existing_index("IDX_USERS_EMAIL", &["EMAIL"], false);
changed.is_unique = true;
+ if database_type == DatabaseType::Oracle {
+ let original = changed.original.as_mut().unwrap();
+ original.key_is_expression = vec![false];
+ original.key_directions = vec!["ASC".to_string()];
+ original.visibility = Some("VISIBLE".to_string());
+ original.key_metadata_complete = true;
+ }
let result = build_table_structure_change_sql(index_change_options(database_type, None, changed));
assert_eq!(result.warnings, Vec::<String>::new(), "database type: {database_type:?}");
@@ -917,6 +1137,9 @@ fn builds_xugu_type_change_with_native_syntax() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -948,6 +1171,20 @@ fn builds_xugu_type_change_with_native_syntax() {
);
}
+#[test]
+fn oracle_dialect_indexes_without_oracle_family_metadata_keep_existing_rebuild_behavior() {
+ for database_type in [DatabaseType::Iris, DatabaseType::Yashandb, DatabaseType::Xugu] {
+ let mut changed = existing_index("IDX_USERS_EMAIL", &["EMAIL"], false);
+ changed.is_unique = true;
+ let result = build_table_structure_change_sql(index_change_options(database_type, None, changed));
+
+ assert_eq!(result.warnings, Vec::<String>::new(), "{database_type:?}: {result:?}");
+ assert_eq!(result.statements.len(), 2, "{database_type:?}: {result:?}");
+ assert!(result.statements[0].starts_with("DROP INDEX "), "{database_type:?}: {result:?}");
+ assert!(result.statements[1].starts_with("CREATE UNIQUE INDEX "), "{database_type:?}: {result:?}");
+ }
+}
+
#[test]
fn builds_postgres_explicit_type_cast_for_renamed_column() {
let mut code = column("new code");
@@ -1187,6 +1424,9 @@ fn builds_mysql_unsigned_integer_column_with_length_before_attribute() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1228,6 +1468,9 @@ fn doris_table_editor_renames_column_without_mysql_change_syntax() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1294,6 +1537,9 @@ fn dameng_integer_column_omits_mysql_display_width() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1342,6 +1588,9 @@ fn builds_highgo_foreign_key_changes_with_postgres_syntax() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1396,6 +1645,9 @@ fn builds_informix_column_and_index_changes() {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -1421,6 +1673,9 @@ fn builds_informix_column_and_index_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1483,6 +1738,9 @@ fn oracle_does_not_generate_drop_sql_for_all_columns() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -1561,6 +1819,9 @@ fn oracle_create_table_places_default_before_not_null() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1633,6 +1894,9 @@ fn oracle_create_table_preserves_character_length_units() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert!(result.statements[0].contains("BYTE_COL VARCHAR2(12 BYTE)"));
@@ -1674,6 +1938,9 @@ fn oracle_create_table_uses_unquoted_identifiers_for_new_objects() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1716,6 +1983,9 @@ fn oracle_create_table_leaves_uppercase_regular_identifier_unquoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1757,6 +2027,9 @@ fn oracle_create_table_quotes_special_and_reserved_identifiers() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1801,6 +2074,9 @@ fn oracle_create_table_distinguishes_new_and_referenced_foreign_key_identifiers(
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1846,6 +2122,9 @@ fn oracle_create_table_extracts_single_line_trigger_source_into_the_body() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1883,6 +2162,9 @@ fn oracle_create_table_warns_instead_of_emitting_an_unparsed_trigger_declaration
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, vec!["CREATE TABLE \"APP\".dbx_copy (\n \"id\" NUMBER\n);"]);
@@ -1924,6 +2206,9 @@ fn oracle_existing_quoted_identifiers_keep_exact_spelling() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -1962,6 +2247,9 @@ fn oracle_new_identifier_formatting_does_not_change_other_dialects() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new(), "{database_type:?}");
@@ -2039,6 +2327,9 @@ fn iris_drop_index_includes_table_name() {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -2062,6 +2353,9 @@ fn iris_drop_index_includes_table_name() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2109,6 +2403,9 @@ fn iris_ignores_comment_changes_but_keeps_supported_column_alters() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(
@@ -2197,6 +2494,9 @@ fn oracle_compatible_databases_keep_comment_on_sql() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new(), "{database_type:?}");
@@ -2237,6 +2537,9 @@ fn mysql_create_index_with_comment() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2276,6 +2579,9 @@ fn manticoresearch_builds_create_table_sql_only() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2325,6 +2631,9 @@ fn manticoresearch_builds_add_and_drop_column_sql() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2376,6 +2685,9 @@ fn gbase8a_uses_limited_mysql_ddl() {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -2399,6 +2711,9 @@ fn gbase8a_uses_limited_mysql_ddl() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(
@@ -2475,6 +2790,9 @@ fn gbase8a_allows_mysql_style_column_reorder() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2522,6 +2840,9 @@ fn gbase8s_uses_informix_ddl_not_mysql() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2561,6 +2882,9 @@ fn gbase_without_driver_profile_still_uses_mysql_ddl() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2602,6 +2926,9 @@ fn manticoresearch_does_not_drop_id_column() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -2676,6 +3003,9 @@ fn manticoresearch_warns_when_existing_column_properties_change() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -2717,6 +3047,9 @@ fn manticoresearch_ignores_mysql_column_options() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2761,6 +3094,9 @@ fn manticoresearch_builds_text_column_properties() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2797,6 +3133,9 @@ fn manticoresearch_builds_json_secondary_index_property() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2829,6 +3168,9 @@ fn mysql_create_unique_index_with_comment_and_btree() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2863,6 +3205,9 @@ fn mysql_create_functional_index_preserves_key_part_syntax() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2897,6 +3242,9 @@ fn mysql_add_timestamp_column_drops_invalid_precision() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2931,6 +3279,9 @@ fn mysql_add_timestamp_column_preserves_valid_precision() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -2972,6 +3323,9 @@ fn builds_postgres_create_table_with_comments_and_index() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3010,6 +3364,9 @@ fn quotes_expression_like_new_index_columns_without_provenance() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3088,6 +3445,9 @@ fn create_table_trims_table_name_whitespace_for_all_statements() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3131,6 +3491,9 @@ fn warns_for_sqlite_unsafe_column_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -3156,6 +3519,9 @@ fn qualifies_attached_sqlite_table_and_index_changes() {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -3180,6 +3546,9 @@ fn qualifies_attached_sqlite_table_and_index_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3255,6 +3624,9 @@ fn builds_rqlite_changes_with_sqlite_dialect() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3291,6 +3663,9 @@ fn builds_kingbase_add_column_without_column_keyword() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3362,6 +3737,9 @@ fn builds_mysql_column_reorder_statements() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3424,6 +3802,9 @@ fn mysql_add_column_before_existing_column_does_not_reorder_shifted_column() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3493,6 +3874,9 @@ fn mysql_existing_column_reorder_does_not_reorder_columns_shifted_by_prior_move(
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3574,6 +3958,9 @@ fn mysql_moving_first_column_to_end_uses_single_reorder_statement() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3605,6 +3992,9 @@ fn builds_sql_server_quoted_column_and_index_statements() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3642,6 +4032,9 @@ fn sqlserver_strips_mysql_display_width_from_fixed_integer_types() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3673,6 +4066,9 @@ fn sqlserver_strips_scale_from_float() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3704,6 +4100,9 @@ fn sqlserver_preserves_float_mantissa_bits() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3760,6 +4159,9 @@ fn sqlserver_default_changes_drop_old_constraints_with_isolated_batches() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -3983,6 +4385,9 @@ fn sqlserver_unchanged_foreign_key_does_not_warn_when_saving_other_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4019,6 +4424,9 @@ fn sqlserver_add_column_with_identity() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4056,6 +4464,9 @@ fn sqlserver_legacy_column_comment_change_uses_legacy_extended_properties() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4096,6 +4507,9 @@ fn dameng_add_column_with_identity() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4126,6 +4540,9 @@ fn dameng_uppercases_lowercase_column_type() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4163,6 +4580,9 @@ fn dameng_rejects_identity_on_incompatible_type() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -4202,6 +4622,9 @@ fn sqlserver_rejects_identity_on_incompatible_type() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -4244,6 +4667,9 @@ fn sqlserver_changed_foreign_key_still_warns_as_unsupported() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -4291,6 +4717,9 @@ fn sqlserver_unchanged_identity_extra_does_not_mark_existing_column_changed() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4338,6 +4767,9 @@ fn dameng_unchanged_identity_extra_does_not_mark_existing_column_changed() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4598,6 +5030,9 @@ fn dameng_rejects_adding_second_identity_column() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -4657,6 +5092,9 @@ fn sqlserver_existing_column_identity_change_warns_without_unchanged_foreign_key
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.statements, Vec::<String>::new());
@@ -4695,6 +5133,9 @@ fn builds_duckdb_create_table_statements() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4822,6 +5263,9 @@ fn builds_clickhouse_nullable_comment_and_reorder_statements() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -4875,6 +5319,9 @@ fn builds_h2_schema_qualified_existing_column_statements() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6058,6 +6505,9 @@ fn mysql_create_table_with_auto_increment() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6092,6 +6542,9 @@ fn mysql_create_table_keeps_column_charset_collation_and_comment() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6130,6 +6583,9 @@ fn mysql_compatible_databases_do_not_emit_mysql_column_charset_clauses() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6165,6 +6621,9 @@ fn mysql_create_table_with_on_update_current_timestamp() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6332,6 +6791,9 @@ fn postgres_create_table_with_identity() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6567,6 +7029,9 @@ fn dameng_create_table_with_identity() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6600,6 +7065,9 @@ fn dameng_create_table_preserves_character_length_units() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6641,6 +7109,9 @@ fn dameng_alter_column_preserves_character_length_unit() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6683,6 +7154,9 @@ fn dameng_rejects_multiple_identity_columns() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert!(result.statements.is_empty());
@@ -6718,6 +7192,9 @@ fn dameng_rejects_zero_identity_increment() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert!(result.statements.is_empty());
@@ -6754,6 +7231,9 @@ fn sqlserver_create_table_with_identity() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6785,6 +7265,9 @@ fn mysql_quotes_datetime_literal_default() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6816,6 +7299,9 @@ fn mysql_does_not_quote_current_timestamp() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6848,6 +7334,9 @@ fn mysql_does_not_quote_temporal_function_with_parens() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6879,6 +7368,9 @@ fn mysql_date_literal_default_is_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6910,6 +7402,9 @@ fn mysql_time_literal_default_is_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -6941,6 +7436,9 @@ fn non_temporal_types_are_not_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7076,6 +7574,9 @@ fn builds_mysql_foreign_key_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7112,6 +7613,9 @@ fn builds_mysql_composite_foreign_key() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7151,6 +7655,9 @@ fn builds_oracle_foreign_key_with_supported_actions() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7194,6 +7701,9 @@ fn builds_oracle_foreign_key_replacement() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7237,6 +7747,9 @@ fn builds_mysql_trigger_changes() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7270,6 +7783,9 @@ fn builds_sqlserver_trigger_with_multiple_events() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7320,6 +7836,9 @@ fn rebuilds_changed_sqlserver_trigger_from_complete_metadata_source() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7364,6 +7883,9 @@ fn sqlserver_trigger_edit_restores_disabled_state() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(
@@ -7414,6 +7936,9 @@ fn unchanged_postgres_trigger_does_not_block_column_rename() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7451,6 +7976,9 @@ fn changed_postgres_trigger_remains_unsupported() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert!(result.statements.is_empty());
@@ -7482,6 +8010,9 @@ fn trigger_change_sql(
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
})
}
@@ -7716,6 +8247,9 @@ fn allows_editing_existing_oracle_trigger() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(
@@ -7748,6 +8282,9 @@ fn builds_oracle_statement_trigger_without_row_clause() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7791,6 +8328,9 @@ fn drops_existing_oracle_trigger_without_reconstructing_it() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7818,6 +8358,9 @@ fn rejects_unsupported_oracle_compound_trigger_shape() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert!(result.statements.is_empty());
@@ -7849,6 +8392,9 @@ fn mysql_varchar_default_is_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7881,6 +8427,9 @@ fn mysql_char_default_is_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7914,6 +8463,9 @@ fn mysql_text_default_is_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7945,6 +8497,9 @@ fn mysql_enum_default_is_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -7976,6 +8531,9 @@ fn mysql_int_default_is_not_quoted() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8117,6 +8675,9 @@ fn mysql_character_column_add_with_charset_collation() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8238,6 +8799,9 @@ fn mysql_numeric_column_omits_charset_collation_in_column_definition() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8287,6 +8851,9 @@ fn mysql_numeric_column_ignores_charset_collation_in_change_detection() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
// No ALTER should be emitted — charset/collation changes on
@@ -8331,6 +8898,9 @@ fn mysql_character_column_detects_charset_collation_change() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8380,6 +8950,9 @@ fn mysql_character_column_preserves_charset_collation_on_other_change() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8462,6 +9035,9 @@ fn mysql_inherited_column_charset_is_omitted_from_generated_ddl() {
is_gaussdb_m_mode: false,
table_collation: Some("utf8mb4_0900_ai_ci".to_string()),
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8512,6 +9088,9 @@ fn mysql_explicit_column_charset_survives_the_table_default_comparison() {
is_gaussdb_m_mode: false,
table_collation: Some("utf8mb4_0900_ai_ci".to_string()),
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8563,6 +9142,9 @@ fn mysql_inherited_column_charset_does_not_register_as_a_change() {
is_gaussdb_m_mode: false,
table_collation: Some("utf8mb4_0900_ai_ci".to_string()),
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8607,6 +9189,9 @@ fn mysql_collation_switched_away_from_the_table_default_is_emitted() {
is_gaussdb_m_mode: false,
table_collation: Some("utf8mb4_0900_ai_ci".to_string()),
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8656,6 +9241,9 @@ fn mysql_column_charset_switched_to_the_table_default_drops_the_clause() {
is_gaussdb_m_mode: false,
table_collation: Some("utf8mb4_0900_ai_ci".to_string()),
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8702,6 +9290,9 @@ fn mysql_column_charset_is_kept_when_the_table_default_is_unknown() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -8743,6 +9334,9 @@ fn mysql_create_table_omits_inherited_column_charset() {
is_gaussdb_m_mode: false,
table_collation: Some("utf8mb4_0900_ai_ci".to_string()),
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -9453,6 +10047,9 @@ fn mysql_create_table_with_generated_column() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
foreign_table: false,
});
@@ -9500,6 +10097,9 @@ fn oscar_create_table_with_primary_key_and_comments() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -9678,6 +10278,9 @@ fn oscar_drop_index_with_schema_qualifier() {
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -9701,6 +10304,9 @@ fn oscar_drop_index_with_schema_qualifier() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -9728,6 +10334,9 @@ fn oscar_table_comment_uses_comment_on_table() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -9817,6 +10426,9 @@ fn postgres_partitioned_parent_concurrent_request_rejected() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
// Fail closed: PostgreSQL rejects CREATE INDEX CONCURRENTLY on a
@@ -9854,6 +10466,9 @@ fn postgres_partitioned_parent_plain_index_unchanged() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -9903,6 +10518,9 @@ fn postgres_create_table_partitioned_concurrent_request_rejected() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(
@@ -10036,6 +10654,9 @@ fn postgres_create_table_concurrent_index() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -10158,6 +10779,9 @@ fn gaussdb_m_options(columns: Vec<EditableStructureColumn>) -> TableStructureSql
is_gaussdb_m_mode: true,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
}
}
@@ -10175,6 +10799,7 @@ fn gaussdb_m_index(name: &str, columns: &[&str]) -> EditableStructureIndex {
comment: String::new(),
concurrently: false,
original: None,
+ oracle_original_missing: false,
marked_for_drop: false,
}
}
@@ -10198,6 +10823,9 @@ fn gaussdb_m_existing_index(
included_columns: None,
comment: None,
key_is_expression: Vec::new(),
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![],
constraint_backed: false,
});
@@ -10398,6 +11026,9 @@ fn gaussdb_m_rebuild_index_unchanged_type_does_not_rebuild() {
is_gaussdb_m_mode: true,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
};
let result = build_table_structure_change_sql(options);
assert!(result.warnings.is_empty());
@@ -10451,6 +11082,9 @@ fn mysql_create_table_nullable_timestamp_without_default_gets_explicit_null() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -10486,6 +11120,9 @@ fn mysql_create_table_nullable_timestamp_with_default_still_gets_explicit_null()
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -10519,6 +11156,9 @@ fn mysql_create_table_nullable_datetime_does_not_gain_null_keyword() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -10552,6 +11192,9 @@ fn mysql_add_column_nullable_timestamp_without_default_gets_explicit_null() {
is_gaussdb_m_mode: false,
table_collation: None,
primary_key_name: None,
+ primary_key_change: None,
+ oracle_constraint_changes: None,
+ oracle_foreign_key_changes: None,
});
assert_eq!(result.warnings, Vec::<String>::new());
@@ -10590,6 +11233,9 @@ fn postgres_index_opclass_from_original_when_editable_empty() {
included_columns: None,
comment: None,
key_is_expression: vec![false],
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![Some("gin_trgm_ops".to_string())],
constraint_backed: false,
});
@@ -10617,6 +11263,9 @@ fn postgres_index_no_rebuild_when_original_has_opclass_and_edit_is_identical() {
included_columns: None,
comment: None,
key_is_expression: vec![false],
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![Some("gin_trgm_ops".to_string())],
constraint_backed: false,
});
@@ -10643,6 +11292,9 @@ fn postgres_index_rebuild_when_opclass_changed() {
included_columns: None,
comment: None,
key_is_expression: vec![false],
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![None], // was default, now gin_trgm_ops
constraint_backed: false,
});
@@ -10742,6 +11394,9 @@ fn postgres_expression_index_appends_opclass() {
included_columns: None,
comment: None,
key_is_expression: vec![true],
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![None],
constraint_backed: false,
});
@@ -10788,6 +11443,9 @@ fn postgres_expression_index_opclass_round_trips_from_indclass() {
included_columns: None,
comment: None,
key_is_expression: vec![true],
+ key_directions: Vec::new(),
+ visibility: None,
+ key_metadata_complete: false,
column_opclasses: vec![Some("public.gin_trgm_ops".to_string())],
constraint_backed: false,
});
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/types.rs b/crates/dbx-sql-schema/src/table_structure_sql/types.rs
index c8d8737077..2fadd335ab 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/types.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/types.rs
@@ -125,6 +125,9 @@ pub struct EditableStructureIndex {
pub concurrently: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub original: Option<IndexInfo>,
+ /// Oracle-family partial-rebuild recovery: preserve `original` as key metadata but skip its already-committed DROP.
+ #[serde(default)]
+ pub oracle_original_missing: bool,
#[serde(default)]
pub marked_for_drop: bool,
}
@@ -150,6 +153,15 @@ pub struct IndexInfo {
/// (e.g. sourced from `pg_get_indexdef`), not a plain column name.
#[serde(default)]
pub key_is_expression: Vec<bool>,
+ /// Parallel to `columns`: Oracle-family key order (`ASC` or `DESC`).
+ #[serde(default)]
+ pub key_directions: Vec<String>,
+ /// Oracle-family index visibility (`VISIBLE` or `INVISIBLE`).
+ #[serde(default)]
+ pub visibility: Option<String>,
+ /// True only when expression, direction and visibility metadata are aligned and complete.
+ #[serde(default)]
+ pub key_metadata_complete: bool,
/// Parallel to `columns`: operator class name for each key column, if non-default.
#[serde(default)]
pub column_opclasses: Vec<Option<String>>,
@@ -299,6 +311,131 @@ pub struct TableStructureSqlOptions {
/// that did not exist before; replacing an existing key never renames it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub primary_key_name: Option<String>,
+ /// An ordered change to an existing Oracle-family primary key.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub primary_key_change: Option<ExistingPrimaryKeyChange>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub oracle_foreign_key_changes: Option<Vec<OracleForeignKeyChange>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub oracle_constraint_changes: Option<Vec<OracleConstraintChange>>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleConstraintChange {
+ pub original: Option<OracleConstraintDefinition>,
+ pub target: Option<OracleConstraintDefinition>,
+ #[serde(default)]
+ pub index_policy: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind", content = "definition")]
+#[allow(clippy::large_enum_variant)]
+pub enum OracleConstraintDefinition {
+ Check(OracleCheckConstraint),
+ Unique(OracleUniqueConstraint),
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleCheckConstraint {
+ pub name: String,
+ pub expression: String,
+ pub state: OraclePrimaryKeyState,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleUniqueConstraint {
+ pub name: String,
+ pub columns: Vec<String>,
+ pub state: OraclePrimaryKeyState,
+ #[serde(default)]
+ pub rely_raw: String,
+ pub index: OracleConstraintIndex,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleConstraintIndex {
+ pub owner: String,
+ pub name: String,
+ pub table_owner: String,
+ pub table_name: String,
+ pub sharing: String,
+ pub metadata_complete: bool,
+ pub index_type: String,
+ pub uniqueness: String,
+ pub status: String,
+ pub partitioned: bool,
+ pub visibility: String,
+ /// `None` is a catalog NULL only when `metadata_complete` is true.
+ pub secondary: Option<String>,
+ #[serde(default)]
+ pub columns: Vec<String>,
+ #[serde(default)]
+ pub directions: Vec<String>,
+ #[serde(default)]
+ pub key_is_expression: Vec<bool>,
+ #[serde(default)]
+ pub included_columns: Vec<String>,
+ #[serde(default)]
+ pub new_name_available: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub new_name: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleForeignKeyChange {
+ pub original: Option<OracleForeignKeyDefinition>,
+ pub target: Option<OracleForeignKeyDefinition>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleForeignKeyDefinition {
+ pub name: String,
+ pub columns: Vec<String>,
+ pub ref_schema: String,
+ pub ref_table: String,
+ pub ref_columns: Vec<String>,
+ pub on_delete: String,
+ pub state: OraclePrimaryKeyState,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExistingPrimaryKeyChange {
+ pub name: String,
+ pub original_columns: Vec<String>,
+ /// Empty means remove the existing key.
+ pub columns: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub oracle_index: Option<OraclePrimaryKeyIndex>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub oracle_state: Option<OraclePrimaryKeyState>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OraclePrimaryKeyState {
+ pub enabled: bool,
+ pub validated: bool,
+ pub deferrable: bool,
+ pub initially_deferred: bool,
+ pub rely: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OraclePrimaryKeyIndex {
+ pub policy: String,
+ pub owner: String,
+ pub name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub new_name: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
diff --git a/crates/dbx-sql-schema/tests/oracle_constraint_editor.rs b/crates/dbx-sql-schema/tests/oracle_constraint_editor.rs
new file mode 100644
index 0000000000..31445112b0
--- /dev/null
+++ b/crates/dbx-sql-schema/tests/oracle_constraint_editor.rs
@@ -0,0 +1,203 @@
+use dbx_sql_schema::table_structure_sql::{
+ build_table_structure_change_sql, build_table_structure_change_sql_with_context, StarRocksAlterOptions,
+ TableStructureSqlOptions,
+};
+use serde_json::{json, Value};
+
+fn options(engine: &str, expression: &str) -> TableStructureSqlOptions {
+ serde_json::from_value(json!({
+ "databaseType": engine,
+ "schema": "APP",
+ "tableName": "CONTACTS",
+ "columns": [],
+ "indexes": [],
+ "oracleConstraintChanges": [{
+ "original": Value::Null,
+ "target": {
+ "kind": "check",
+ "definition": {
+ "name": "CK_CONTACTS_AGE",
+ "expression": expression,
+ "state": { "enabled": true, "validated": true, "deferrable": false, "initiallyDeferred": false, "rely": false }
+ }
+ }
+ }]
+ }))
+ .unwrap()
+}
+
+fn rename_with_state_options(engine: &str) -> TableStructureSqlOptions {
+ serde_json::from_value(json!({
+ "databaseType": engine,
+ "schema": "APP",
+ "tableName": "CONTACTS",
+ "columns": [],
+ "indexes": [],
+ "oracleConstraintChanges": [{
+ "original": { "kind": "check", "definition": {
+ "name": "CK_OLD", "expression": "AGE > 0",
+ "state": { "enabled": true, "validated": true, "deferrable": false, "initiallyDeferred": false, "rely": false }
+ } },
+ "target": { "kind": "check", "definition": {
+ "name": "CK_NEW", "expression": "AGE > 0",
+ "state": { "enabled": false, "validated": false, "deferrable": false, "initiallyDeferred": false, "rely": false }
+ } }
+ }]
+ }))
+ .unwrap()
+}
+
+fn unique_state_options() -> TableStructureSqlOptions {
+ serde_json::from_value(json!({
+ "databaseType": "oracle", "schema": "APP", "tableName": "CONTACTS", "columns": [], "indexes": [],
+ "oracleConstraintChanges": [{
+ "indexPolicy": "keep",
+ "original": { "kind": "unique", "definition": {
+ "name": "UQ_CONTACTS", "columns": ["ID"], "relyRaw": "NULL",
+ "state": { "enabled": true, "validated": true, "deferrable": false, "initiallyDeferred": false, "rely": false },
+ "index": { "owner": "APP", "name": "UQ_CONTACTS", "tableOwner": "APP", "tableName": "CONTACTS", "sharing": "exclusive", "metadataComplete": true, "indexType": "NORMAL", "uniqueness": "UNIQUE", "status": "VALID", "partitioned": false, "visibility": "VISIBLE", "secondary": "N", "columns": ["ID"], "directions": ["ASC"], "keyIsExpression": [false], "includedColumns": [], "newNameAvailable": false }
+ } },
+ "target": { "kind": "unique", "definition": {
+ "name": "UQ_CONTACTS", "columns": ["ID"], "relyRaw": "NULL",
+ "state": { "enabled": false, "validated": true, "deferrable": false, "initiallyDeferred": false, "rely": false },
+ "index": { "owner": "APP", "name": "UQ_CONTACTS", "tableOwner": "APP", "tableName": "CONTACTS", "sharing": "exclusive", "metadataComplete": true, "indexType": "NORMAL", "uniqueness": "UNIQUE", "status": "VALID", "partitioned": false, "visibility": "VISIBLE", "secondary": "N", "columns": ["ID"], "directions": ["ASC"], "keyIsExpression": [false], "includedColumns": [], "newNameAvailable": false }
+ } }
+ }]
+ })).unwrap()
+}
+
+#[test]
+fn starrocks_alter_rejects_oracle_only_changes_before_generating_ddl() {
+ for (field, value) in [
+ ("oracleConstraintChanges", json!([])),
+ ("oracleForeignKeyChanges", json!([])),
+ ("primaryKeyChange", json!({ "name": "PK_EVENTS", "originalColumns": ["id"], "columns": ["id"] })),
+ ] {
+ let mut payload = json!({
+ "databaseType": "starrocks",
+ "tableName": "events",
+ "columns": [],
+ "indexes": [],
+ "tableComment": "must not be emitted"
+ });
+ payload[field] = value;
+ let options: TableStructureSqlOptions = serde_json::from_value(payload).unwrap();
+ let context: StarRocksAlterOptions = serde_json::from_value(json!({ "serverVersion": "3.5.0" })).unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty(), "{field}: {:?}", result.statements);
+ assert!(!result.warnings.is_empty(), "{field} should be rejected for StarRocks");
+ }
+}
+
+#[test]
+fn starrocks_alter_still_generates_native_table_comment_without_oracle_changes() {
+ let options: TableStructureSqlOptions = serde_json::from_value(json!({
+ "databaseType": "starrocks",
+ "tableName": "events",
+ "columns": [],
+ "indexes": [],
+ "tableComment": "native comment"
+ }))
+ .unwrap();
+ let context: StarRocksAlterOptions = serde_json::from_value(json!({ "serverVersion": "3.5.0" })).unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(!result.statements.is_empty());
+}
+
+#[test]
+fn check_expression_line_comment_cannot_swallow_generated_ddl() {
+ for engine in ["oracle", "oceanbase-oracle"] {
+ let result = build_table_structure_change_sql(options(engine, "\"AGE\" >= 0 -- trailing note"));
+ assert!(result.warnings.is_empty(), "{engine}: {:?}", result.warnings);
+ let state = if engine == "oracle" { " NOT DEFERRABLE INITIALLY IMMEDIATE NORELY" } else { "" };
+ assert_eq!(
+ result.statements,
+ vec![format!("ALTER TABLE \"APP\".\"CONTACTS\" ADD CONSTRAINT \"CK_CONTACTS_AGE\" CHECK (\n\"AGE\" >= 0 -- trailing note\n){state} ENABLE VALIDATE;")],
+ "{engine}"
+ );
+ }
+}
+
+#[test]
+fn check_expression_keeps_comment_markers_inside_literals_and_quoted_names() {
+ let result =
+ build_table_structure_change_sql(options("oracle", "\"A;B\" = 'x;--y' /* note */ AND \"A;B\" IS NOT NULL"));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains("CHECK (\n\"A;B\" = 'x;--y' /* note */ AND \"A;B\" IS NOT NULL\n)"));
+}
+
+#[test]
+fn check_expression_with_check_marker_inside_string_literal_is_validated() {
+ let result = build_table_structure_change_sql(options("oracle", "TEXT = ' CHECK ('"));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains("TEXT = ' CHECK ('"));
+}
+
+#[test]
+fn check_expression_with_trailing_statement_is_rejected_before_any_ddl() {
+ for expression in ["\"AGE\" >= 0; DROP TABLE CONTACTS", "\"AGE\" >= 0) ENABLE VALIDATE"] {
+ let result = build_table_structure_change_sql(options("oracle", expression));
+ assert!(result.statements.is_empty(), "unexpected DDL for {expression}: {:?}", result.statements);
+ assert!(!result.warnings.is_empty());
+ }
+}
+
+#[test]
+fn rename_with_state_change_keeps_both_changes_for_each_engine() {
+ let oracle = build_table_structure_change_sql(rename_with_state_options("oracle"));
+ assert!(oracle.warnings.is_empty(), "{:?}", oracle.warnings);
+ assert_eq!(
+ oracle.statements,
+ vec![
+ "ALTER TABLE \"APP\".\"CONTACTS\" DISABLE NOVALIDATE CONSTRAINT \"CK_OLD\";",
+ "ALTER TABLE \"APP\".\"CONTACTS\" RENAME CONSTRAINT \"CK_OLD\" TO \"CK_NEW\";"
+ ]
+ );
+
+ let oceanbase = build_table_structure_change_sql(rename_with_state_options("oceanbase-oracle"));
+ assert!(oceanbase.warnings.is_empty(), "{:?}", oceanbase.warnings);
+ assert_eq!(oceanbase.statements.len(), 2);
+ assert!(oceanbase.statements[0].contains("DROP CONSTRAINT \"CK_OLD\""));
+ assert!(oceanbase.statements[1].contains("ADD CONSTRAINT \"CK_NEW\" CHECK (\nAGE > 0\n) DISABLE NOVALIDATE"));
+}
+
+#[test]
+fn oracle_unique_disable_uses_explicit_index_policy() {
+ let result = build_table_structure_change_sql(unique_state_options());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec!["ALTER TABLE \"APP\".\"CONTACTS\" DISABLE VALIDATE CONSTRAINT \"UQ_CONTACTS\" KEEP INDEX;"]
+ );
+}
+#[test]
+fn oracle_enabling_novalidate_unique_without_an_index_creates_a_nonunique_index() {
+ let options: TableStructureSqlOptions = serde_json::from_value(json!({
+ "databaseType": "oracle", "schema": "APP", "tableName": "CONTACTS", "columns": [], "indexes": [],
+ "oracleConstraintChanges": [{
+ "indexPolicy": "keep",
+ "original": { "kind": "unique", "definition": {
+ "name": "UQ_CONTACTS", "columns": ["ID"], "relyRaw": "NULL",
+ "state": { "enabled": false, "validated": false, "deferrable": false, "initiallyDeferred": false, "rely": false },
+ "index": { "owner": "APP", "name": "", "tableOwner": "APP", "tableName": "CONTACTS", "sharing": "exclusive", "metadataComplete": true, "indexType": "NORMAL", "uniqueness": "UNIQUE", "status": "VALID", "partitioned": false, "visibility": "VISIBLE", "secondary": "N", "columns": [], "directions": [], "keyIsExpression": [], "includedColumns": [], "newNameAvailable": false }
+ } },
+ "target": { "kind": "unique", "definition": {
+ "name": "UQ_CONTACTS", "columns": ["ID"], "relyRaw": "NULL",
+ "state": { "enabled": true, "validated": false, "deferrable": false, "initiallyDeferred": false, "rely": false },
+ "index": { "owner": "APP", "name": "", "newName": "IX_UQ_CONTACTS", "newNameAvailable": true, "tableOwner": "APP", "tableName": "CONTACTS", "sharing": "exclusive", "metadataComplete": false, "indexType": "NORMAL", "uniqueness": "UNIQUE", "status": "VALID", "partitioned": false, "visibility": "VISIBLE", "secondary": "N", "columns": ["ID"], "directions": ["ASC"], "keyIsExpression": [false], "includedColumns": [] }
+ } }
+ }]
+ })).unwrap();
+
+ let result = build_table_structure_change_sql(options);
+
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE \"APP\".\"CONTACTS\" DROP CONSTRAINT \"UQ_CONTACTS\" KEEP INDEX;",
+ "ALTER TABLE \"APP\".\"CONTACTS\" ADD CONSTRAINT \"UQ_CONTACTS\" UNIQUE (\"ID\") NOT DEFERRABLE INITIALLY IMMEDIATE NORELY USING INDEX (CREATE INDEX \"APP\".\"IX_UQ_CONTACTS\" ON \"APP\".\"CONTACTS\" (\"ID\")) ENABLE NOVALIDATE;"
+ ]
+ );
+}
diff --git a/crates/dbx-sql-schema/tests/oracle_foreign_key_editor.rs b/crates/dbx-sql-schema/tests/oracle_foreign_key_editor.rs
new file mode 100644
index 0000000000..dce17fd39a
--- /dev/null
+++ b/crates/dbx-sql-schema/tests/oracle_foreign_key_editor.rs
@@ -0,0 +1,200 @@
+use dbx_sql_schema::table_structure_sql::{
+ build_create_table_sql, build_table_structure_change_sql, TableStructureSqlOptions,
+};
+use serde_json::{json, Value};
+
+fn definition(name: &str) -> Value {
+ json!({
+ "name": name, "columns": ["B", "A,quoted"],
+ "refSchema": "Parent Owner", "refTable": "Parent,Table", "refColumns": ["V", "ID\"quoted"],
+ "onDelete": "CASCADE",
+ "state": { "enabled": true, "validated": false, "deferrable": false, "initiallyDeferred": false, "rely": false }
+ })
+}
+
+fn options(engine: &str, original: Value, target: Value) -> TableStructureSqlOptions {
+ serde_json::from_value(json!({
+ "databaseType": engine, "schema": "App Owner", "tableName": "Child,Table",
+ "columns": [], "indexes": [],
+ "oracleForeignKeyChanges": [{ "original": original, "target": target }]
+ }))
+ .unwrap()
+}
+
+#[test]
+fn ordered_quoted_composite_add_reaches_real_builder() {
+ for engine in ["oracle", "oceanbase-oracle"] {
+ let result = build_table_structure_change_sql(options(engine, Value::Null, definition("FK\"name")));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ let deferred = if engine == "oracle" { " NOT DEFERRABLE INITIALLY IMMEDIATE" } else { "" };
+ assert_eq!(
+ result.statements,
+ vec![format!(
+ "ALTER TABLE \"App Owner\".\"Child,Table\" ADD CONSTRAINT \"FK\"\"name\" FOREIGN KEY (\"B\", \"A,quoted\") REFERENCES \"Parent Owner\".\"Parent,Table\" (\"V\", \"ID\"\"quoted\") ON DELETE CASCADE{deferred} NORELY ENABLE NOVALIDATE;"
+ )],
+ "{engine}"
+ );
+ }
+}
+
+#[test]
+fn invalid_replacement_never_returns_original_drop() {
+ let mut invalid = definition("FK_NEW");
+ invalid["refColumns"] = json!(["V"]);
+ let result = build_table_structure_change_sql(options("oracle", definition("FK_OLD"), invalid));
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+}
+
+#[test]
+fn unsupported_engine_cannot_consume_oracle_changes() {
+ let result = build_table_structure_change_sql(options("postgres", Value::Null, definition("FK_NEW")));
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+}
+
+#[test]
+fn oracle_name_and_state_edit_preserves_existing_key() {
+ let original = definition("FK_OLD");
+ let mut target = definition("FK_NEW");
+ target["state"]["enabled"] = json!(false);
+ let result = build_table_structure_change_sql(options("oracle", original, target));
+ assert!(result.warnings.is_empty());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE \"App Owner\".\"Child,Table\" DISABLE NOVALIDATE CONSTRAINT \"FK_OLD\";",
+ "ALTER TABLE \"App Owner\".\"Child,Table\" RENAME CONSTRAINT \"FK_OLD\" TO \"FK_NEW\";"
+ ]
+ );
+}
+
+#[test]
+fn oceanbase_name_edit_rebuilds_but_state_edit_is_in_place() {
+ let original = definition("FK_OLD");
+ let mut target = original.clone();
+ target["state"]["enabled"] = json!(false);
+ let result = build_table_structure_change_sql(options("oceanbase-oracle", original.clone(), target));
+ assert_eq!(
+ result.statements,
+ vec!["ALTER TABLE \"App Owner\".\"Child,Table\" DISABLE NOVALIDATE CONSTRAINT \"FK_OLD\";"]
+ );
+ let renamed = build_table_structure_change_sql(options("oceanbase-oracle", original, definition("FK_NEW")));
+ assert!(renamed.warnings.is_empty());
+ assert_eq!(renamed.statements.len(), 2);
+ assert_eq!(renamed.statements[0], "ALTER TABLE \"App Owner\".\"Child,Table\" DROP CONSTRAINT \"FK_OLD\";");
+ assert!(renamed.statements[1].contains("ADD CONSTRAINT \"FK_NEW\""));
+}
+
+#[test]
+fn duplicate_columns_and_illegal_actions_are_rejected_before_drop() {
+ for (field, value) in [("columns", json!(["B", "B"])), ("onDelete", json!("RESTRICT"))] {
+ let mut target = definition("FK_NEW");
+ target[field] = value;
+ let result = build_table_structure_change_sql(options("oracle", definition("FK_OLD"), target));
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+ }
+}
+
+fn new_table_options(engine: &str) -> TableStructureSqlOptions {
+ serde_json::from_value(json!({
+ "databaseType": engine, "schema": "APP", "tableName": "child",
+ "columns": [{"id":"id", "name":"key_id", "dataType":"NUMBER", "isNullable":false, "isPrimaryKey":true},
+ {"id":"pid", "name":"parent_id", "dataType":"NUMBER", "isNullable":true}],
+ "oracleForeignKeyChanges": [{"original":null,"target":{
+ "name":"fk_self", "columns":["parent_id"], "refSchema":"APP", "refTable":"child", "refColumns":["key_id"],
+ "onDelete":"NO ACTION", "state":{"enabled":true,"validated":true,"deferrable":false,"initiallyDeferred":false,"rely":false}
+ }}]
+ })).unwrap()
+}
+
+#[test]
+fn new_table_foreign_key_uses_existing_create_identity_rules() {
+ for engine in ["oracle", "oceanbase-oracle"] {
+ let result = build_create_table_sql(new_table_options(engine));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements.len(), 2, "{engine}: {:?}", result.statements);
+ if engine == "oracle" {
+ assert!(result.statements[0].contains("CREATE TABLE \"APP\".child"));
+ assert!(result.statements[1].contains("ALTER TABLE \"APP\".child ADD CONSTRAINT fk_self FOREIGN KEY (parent_id) REFERENCES \"APP\".child (key_id)"), "{:?}", result.statements);
+ } else {
+ assert!(result.statements[1].contains("ALTER TABLE \"APP\".\"child\" ADD CONSTRAINT \"fk_self\" FOREIGN KEY (\"parent_id\") REFERENCES \"APP\".\"child\" (\"key_id\")"));
+ }
+ }
+}
+
+#[test]
+fn self_reference_preserves_reverse_composite_parent_key_order() {
+ let options = serde_json::from_value::<TableStructureSqlOptions>(json!({
+ "databaseType": "oracle", "schema": "APP", "tableName": "child",
+ "columns": [
+ {"id":"a", "name":"A", "dataType":"NUMBER", "isNullable":false, "isPrimaryKey":true},
+ {"id":"b", "name":"B", "dataType":"NUMBER", "isNullable":false, "isPrimaryKey":true},
+ {"id":"x", "name":"X", "dataType":"NUMBER", "isNullable":true},
+ {"id":"y", "name":"Y", "dataType":"NUMBER", "isNullable":true}
+ ],
+ "oracleForeignKeyChanges": [{"original":null,"target":{
+ "name":"FK_SELF", "columns":["X","Y"], "refSchema":"APP", "refTable":"child", "refColumns":["B","A"],
+ "onDelete":"NO ACTION", "state":{"enabled":true,"validated":true,"deferrable":false,"initiallyDeferred":false,"rely":false}
+ }}]
+ })).unwrap();
+ let result = build_create_table_sql(options.clone());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[1].contains("FOREIGN KEY (X, Y) REFERENCES \"APP\".child (B, A)"));
+}
+
+#[test]
+fn invalid_new_foreign_key_returns_zero_create_statements() {
+ let mut options = new_table_options("oracle");
+ options.oracle_foreign_key_changes.as_mut().unwrap()[0].target.as_mut().unwrap().columns = vec!["missing".into()];
+ let result = build_create_table_sql(options);
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+}
+
+#[test]
+fn self_reference_must_target_the_new_primary_key_before_create() {
+ let mut options = new_table_options("oracle");
+ options.oracle_foreign_key_changes.as_mut().unwrap()[0].target.as_mut().unwrap().ref_columns =
+ vec!["parent_id".into()];
+ let result = build_create_table_sql(options);
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+}
+
+#[test]
+fn oracle_self_reference_uses_unquoted_identifier_folding() {
+ let mut options = new_table_options("oracle");
+ options.oracle_foreign_key_changes.as_mut().unwrap()[0].target.as_mut().unwrap().ref_table = "CHILD".into();
+ let result = build_create_table_sql(options);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[1].contains("REFERENCES \"APP\".child (key_id)"));
+}
+
+#[test]
+fn new_foreign_keys_preserve_special_source_and_existing_parent_names() {
+ let mut options = new_table_options("oracle");
+ options.table_name = "Child,Quoted".into();
+ options.columns[1].name = " parent\"column ".into();
+ let target = options.oracle_foreign_key_changes.as_mut().unwrap()[0].target.as_mut().unwrap();
+ target.name = "FK,Quoted".into();
+ target.columns = vec![" parent\"column ".into()];
+ target.ref_schema = "Parent Owner".into();
+ target.ref_table = "MixedCaseParent".into();
+ target.ref_columns = vec![" Key,One ".into()];
+ let result = build_create_table_sql(options);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[1].contains("ALTER TABLE \"APP\".\"Child,Quoted\" ADD CONSTRAINT \"FK,Quoted\" FOREIGN KEY (\" parent\"\"column \") REFERENCES \"Parent Owner\".\"MixedCaseParent\" (\" Key,One \")"), "{:?}", result.statements);
+}
+
+#[test]
+fn ordinary_oracle_new_constraint_names_cannot_collide_after_folding() {
+ let mut options = new_table_options("oracle");
+ let mut second = options.oracle_foreign_key_changes.as_ref().unwrap()[0].clone();
+ second.target.as_mut().unwrap().name = "FK_SELF".into();
+ options.oracle_foreign_key_changes.as_mut().unwrap().push(second);
+ let result = build_create_table_sql(options);
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+}
diff --git a/crates/dbx-sql-schema/tests/oracle_index_fidelity.rs b/crates/dbx-sql-schema/tests/oracle_index_fidelity.rs
new file mode 100644
index 0000000000..cd5de728e8
--- /dev/null
+++ b/crates/dbx-sql-schema/tests/oracle_index_fidelity.rs
@@ -0,0 +1,156 @@
+use dbx_sql_schema::models::connection::DatabaseType;
+use dbx_sql_schema::table_structure_sql::{build_table_structure_change_sql, TableStructureSqlOptions};
+use serde_json::{json, Value};
+
+fn options(columns: Value) -> TableStructureSqlOptions {
+ serde_json::from_value(json!({
+ "databaseType": "oracle",
+ "schema": "APP",
+ "tableName": "EVENTS",
+ "columns": [],
+ "indexes": [columns]
+ }))
+ .unwrap()
+}
+
+fn existing_index(columns: Vec<&str>) -> Value {
+ json!({
+ "id": "existing:IX_EVENT",
+ "name": "IX_EVENT_RENAMED",
+ "columns": columns,
+ "isUnique": false,
+ "isPrimary": false,
+ "original": {
+ "name": "IX_EVENT",
+ "columns": ["LOWER(EVENT_NAME)", "EVENT_TS"],
+ "is_unique": false,
+ "is_primary": false,
+ "key_is_expression": [true, false],
+ "key_directions": ["DESC", "ASC"],
+ "visibility": "INVISIBLE",
+ "key_metadata_complete": true
+ }
+ })
+}
+
+#[test]
+fn oracle_expression_index_rename_keeps_raw_expression_and_key_semantics() {
+ let result = build_table_structure_change_sql(options(existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"])));
+
+ assert_eq!(result.statements.len(), 2, "{result:?}");
+ assert!(result.statements[0].starts_with("DROP INDEX"), "{result:?}");
+ assert!(result.statements[1].contains("LOWER(EVENT_NAME)"), "{result:?}");
+ assert!(!result.statements[1].contains("\"LOWER(EVENT_NAME)\""), "{result:?}");
+ assert!(result.statements[1].contains("DESC"), "{result:?}");
+ assert!(result.statements[1].contains("EVENT_TS\" ASC"), "{result:?}");
+ assert!(result.statements[1].contains("INVISIBLE"), "{result:?}");
+}
+
+#[test]
+fn oracle_retry_after_drop_creates_only_and_keeps_original_key_semantics() {
+ let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);
+ input["oracleOriginalMissing"] = json!(true);
+
+ let result = build_table_structure_change_sql(options(input));
+
+ assert_eq!(result.statements.len(), 1, "{result:?}");
+ assert!(result.statements[0].starts_with("CREATE INDEX"), "{result:?}");
+ assert!(result.statements[0].contains("LOWER(EVENT_NAME) DESC"), "{result:?}");
+ assert!(result.statements[0].contains("EVENT_TS\" ASC"), "{result:?}");
+ assert!(result.statements[0].contains("INVISIBLE"), "{result:?}");
+}
+
+#[test]
+fn oracle_retry_after_drop_creates_only_when_target_matches_original_definition() {
+ let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);
+ input["name"] = json!("IX_EVENT");
+ input["oracleOriginalMissing"] = json!(true);
+
+ let result = build_table_structure_change_sql(options(input));
+
+ assert_eq!(result.statements.len(), 1, "{result:?}");
+ assert!(result.statements[0].starts_with("CREATE INDEX \"IX_EVENT\""), "{result:?}");
+ assert!(result.statements[0].contains("LOWER(EVENT_NAME) DESC"), "{result:?}");
+ assert!(result.statements[0].contains("INVISIBLE"), "{result:?}");
+}
+
+#[test]
+fn dropping_a_missing_oracle_index_draft_generates_no_ddl() {
+ let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);
+ input["oracleOriginalMissing"] = json!(true);
+ input["markedForDrop"] = json!(true);
+
+ let result = build_table_structure_change_sql(options(input));
+
+ assert!(result.statements.is_empty(), "{result:?}");
+}
+
+#[test]
+fn oracle_reordered_keys_keep_their_individual_directions() {
+ let result = build_table_structure_change_sql(options(existing_index(vec!["EVENT_TS", "LOWER(EVENT_NAME)"])));
+
+ assert_eq!(result.statements.len(), 2, "{result:?}");
+ assert!(result.statements[1].contains("EVENT_TS\" ASC, LOWER(EVENT_NAME) DESC"), "{result:?}");
+}
+
+#[test]
+fn oceanbase_descending_rebuild_is_rejected_before_drop() {
+ let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);
+ input["original"]["key_directions"] = json!(["DESC", "ASC"]);
+ let mut options = options(input);
+ options.database_type = Some(DatabaseType::OceanbaseOracle);
+
+ let result = build_table_structure_change_sql(options);
+
+ assert!(result.statements.is_empty(), "{result:?}");
+ assert!(result.warnings.iter().any(|warning| warning.contains("descending index key 1")), "{result:?}");
+}
+
+#[test]
+fn oceanbase_ascending_invisible_rebuild_preserves_supported_options() {
+ let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);
+ input["original"]["key_directions"] = json!(["ASC", "ASC"]);
+ let mut options = options(input);
+ options.database_type = Some(DatabaseType::OceanbaseOracle);
+
+ let result = build_table_structure_change_sql(options);
+
+ assert_eq!(result.statements.len(), 2, "{result:?}");
+ assert!(result.statements[1].contains("LOWER(EVENT_NAME) ASC"), "{result:?}");
+ assert!(result.statements[1].contains("EVENT_TS\" ASC"), "{result:?}");
+ assert!(result.statements[1].contains("INVISIBLE"), "{result:?}");
+}
+
+#[test]
+fn oracle_unknown_index_metadata_blocks_rebuild() {
+ let mut input = existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]);
+ input["original"]["key_metadata_complete"] = json!(false);
+
+ let result = build_table_structure_change_sql(options(input));
+
+ assert!(result.statements.is_empty(), "{result:?}");
+ assert!(result.warnings.iter().any(|warning| warning.contains("metadata is incomplete")), "{result:?}");
+}
+
+#[test]
+fn oracle_invalid_rebuild_does_not_drop_without_a_complete_create() {
+ let result = build_table_structure_change_sql(options(existing_index(Vec::new())));
+
+ assert!(result.statements.is_empty(), "{result:?}");
+ assert!(!result.warnings.is_empty(), "{result:?}");
+}
+
+#[test]
+fn indexes_on_other_oracle_dialect_engines_keep_existing_rebuild_behavior() {
+ for database_type in [DatabaseType::Iris, DatabaseType::Yashandb, DatabaseType::Xugu] {
+ let mut options = options(existing_index(vec!["LOWER(EVENT_NAME)", "EVENT_TS"]));
+ options.database_type = Some(database_type);
+
+ let result = build_table_structure_change_sql(options);
+
+ assert_eq!(result.warnings, Vec::<String>::new(), "{database_type:?}: {result:?}");
+ assert_eq!(result.statements.len(), 2, "{database_type:?}: {result:?}");
+ assert!(result.statements[0].starts_with("DROP INDEX"), "{database_type:?}: {result:?}");
+ assert!(result.statements[1].starts_with("CREATE INDEX"), "{database_type:?}: {result:?}");
+ }
+}
diff --git a/crates/dbx-types/src/types.rs b/crates/dbx-types/src/types.rs
index 25e7dd7b50..e6bdef9f15 100644
--- a/crates/dbx-types/src/types.rs
+++ b/crates/dbx-types/src/types.rs
@@ -789,6 +789,16 @@ pub struct IndexInfo {
/// introspection source doesn't track this (provenance unknown for that dialect/path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_is_expression: Vec<bool>,
+ /// Parallel to `columns`: Oracle-family key order (`ASC` or `DESC`). Empty when
+ /// the source does not expose direction metadata.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub key_directions: Vec<String>,
+ /// Oracle-family index visibility (`VISIBLE` or `INVISIBLE`), when available.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub visibility: Option<String>,
+ /// True only when the source returned aligned expression, direction and visibility metadata.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub key_metadata_complete: bool,
/// Parallel to `columns`: operator class name for each key column, if non-default.
/// For example, a GIN trigram index on a varchar column will have `"gin_trgm_ops"`.
/// `None` means the default operator class is used (can be omitted in DDL).
@@ -873,6 +883,44 @@ pub struct ConstraintInfo {
pub enabled: Option<bool>,
#[serde(default)]
pub valid: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub oracle_metadata: Option<OracleConstraintMetadata>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleConstraintMetadata {
+ pub metadata_complete: bool,
+ pub owner: String,
+ pub constraint_type: Option<String>,
+ pub status: Option<String>,
+ pub validated: Option<String>,
+ pub deferrable: Option<String>,
+ pub deferred: Option<String>,
+ pub rely: Option<String>,
+ pub index_owner: Option<String>,
+ pub index_name: Option<String>,
+ pub index_sharing: Option<String>,
+ pub index: Option<OracleConstraintIndexMetadata>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OracleConstraintIndexMetadata {
+ pub metadata_complete: bool,
+ pub owner: String,
+ pub table_owner: String,
+ pub table_name: String,
+ pub index_type: String,
+ pub uniqueness: String,
+ pub status: String,
+ pub partitioned: bool,
+ pub visibility: String,
+ pub secondary: Option<String>,
+ pub columns: Vec<String>,
+ pub directions: Vec<String>,
+ pub key_is_expression: Vec<bool>,
+ pub included_columns: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/docs/content/docs/table-structure.cn.mdx b/docs/content/docs/table-structure.cn.mdx
index 3d55bf4a46..ec7a694bdf 100644
--- a/docs/content/docs/table-structure.cn.mdx
+++ b/docs/content/docs/table-structure.cn.mdx
@@ -45,6 +45,29 @@ description: 可视化查看和修改字段、索引、外键与触发器,并
创建新表时,可以使用设置中的预设字段快速加入常见主键、时间戳或审计字段。
+### 修改 OceanBase Oracle 已有主键
+
+OceanBase Oracle 的已有主键可从约束卡片编辑或删除。当前支持普通表上已启用、已验证且不可延迟的主键,支撑索引须为有效、可见、非分区的普通唯一索引,列序与主键一致且未被其他约束共享。
+
+<Callout type="warn">修改主键会先删除原主键及其支撑索引,再创建新主键。两条 DDL 独立提交,期间表没有主键;新增失败后也可能保持无主键状态。删除主键只执行删除步骤。</Callout>
+
+1. 在已有主键的约束卡片选择**编辑**,选择目标列并用**上移**、**下移**调整复合主键列序;删除整个主键时选择**删除**。
+2. 将其他表结构修改分开保存,然后预览本次主键 SQL。DBX 检查最新定义、支撑索引、外键引用,以及目标列中的空值和重复键值。存在引用(包括禁用的外键)、元数据不完整或不支持的状态时,预检拒绝执行。
+3. 核对预览中的表、主键名称和列序后保存。执行前会再次核对定义;定义已变化时,刷新后重新预览。
+4. 查看执行结果并核对刷新后的表结构。发生失败或结果未知时,先检查数据库状态,不要直接重复执行。
+
+如果旧主键已删除且读回确认当前没有主键,结果明细会提供人工恢复 SQL 候选。执行前须重新核对数据、名称及索引;DBX 不会自动执行恢复。该 SQL 只恢复原主键的逻辑定义,不恢复表空间、压缩或存储等物理属性。
+
+### 修改原生 Oracle 已有主键
+
+原生 Oracle 使用相同的约束卡片、列序调整、预览及保存入口。普通表主键替换会保留原有启用、验证、可延迟及初始延迟状态;未验证约束还保留 RELY 语义,不会自动启用或验证。目标列仍需通过非空及唯一检查。外部表、IOT 和临时表不在此入口的支持范围内。
+
+索引列顺序可以与约束顺序不同,但必须具有相同列集合。有效、可见、非分区的普通非唯一索引也可作为支撑索引;可延迟主键使用非唯一索引。禁用主键没有关联索引时,界面明确显示这一状态,不会猜测或删除同名独立索引,重建时也不创建索引。恢复候选保留原约束状态;禁用约束不会因恢复而自动启用。
+
+保存前选择**保留原索引**或**删除原索引**,默认保留。保留唯一索引后,旧列组合的唯一性限制仍生效;例如从单列改为复合主键,并不会自动解除原单列的唯一性。选择删除会丢失旧索引的物理属性,预览会列出确切索引。目标列集合变化时使用新索引名称,避免与保留的索引重名。
+
+DBX 阻止已知引用,数据库还会拒绝未可见或并发新增的引用;不会使用级联删除。两条 DDL 独立提交,部分失败需要核对主键和索引的实际状态。人工恢复只有在旧索引定义完整一致时才推荐复用;同名索引已变化或状态未知时,候选保持注释状态,须人工核实后处理。原生 Oracle 实库验收尚未完成,不能将 OceanBase 验证结果视为原生 Oracle 验证。
+
## 索引、外键与触发器
索引能力按数据库方言开放,例如:
@@ -55,7 +78,15 @@ description: 可视化查看和修改字段、索引、外键与触发器,并
- 索引注释(数据库支持时)
- 自动生成新索引名称,并允许修改
-外键编辑包括字段映射和更新/删除动作。触发器编辑依赖数据库源码读取和安全 DDL 生成能力;不支持直接修改时仍可以查看源码或复制 DDL。
+原生 Oracle 与 OceanBase Oracle 均在已有表与新表入口中提供外键创建、编辑和删除。编辑已有外键前,DBX 会读取并核对原定义;定义不完整或不可读时,卡片保持只读。
+
+复合外键按行保存本地列与引用列的配对顺序。移动一行会同时移动两侧列。`ON DELETE` 支持 `NO ACTION`、`CASCADE` 和 `SET NULL`;Oracle 外键不显示 `ON UPDATE`。两种数据库都可设置启用、验证和 `RELY` 状态;可延迟状态仅在原生 Oracle 中提供。
+
+已有表的外键变更需要单独保存,不能与字段、主键、索引、触发器、分区、表注释或手写 DDL 草稿混合。新表可以在同一创建计划中包含字段、主键和外键,包括自引用外键。保存前,DBX 会重新检查源定义、父键、权限和适用的数据条件;必要元数据不可读或验证数据不通过时,不会先删除原外键。单条新增操作所需权限仍由数据库最终判定。
+
+外键 DDL 按语句逐条提交。新表的 CREATE 成功而后续外键失败时,表和已成功步骤会保留,DBX 会停止剩余步骤,不自动删除表、重试或回滚。已有外键重建也可能在失败后缺少原外键。重试前先刷新并检查实际定义;结果明细可能提供需要人工复核的恢复 SQL。
+
+其他数据库的外键编辑能力依赖对应方言实现。触发器编辑依赖数据库源码读取和安全 DDL 生成能力;不支持直接修改时仍可以查看源码或复制 DDL。
## DDL 预览
diff --git a/docs/content/docs/table-structure.mdx b/docs/content/docs/table-structure.mdx
index 6d7596878c..47a21ec8eb 100644
--- a/docs/content/docs/table-structure.mdx
+++ b/docs/content/docs/table-structure.mdx
@@ -45,6 +45,29 @@ Column reorder has two meanings:
New-table creation can use preset fields from settings for common primary keys, timestamps, or audit columns.
+### Edit an Existing OceanBase Oracle Primary Key
+
+Use the existing primary key's constraint card to edit or drop it in OceanBase Oracle. This operation supports ordinary tables with an enabled, validated, non-deferrable primary key. Its supporting index must be a valid, visible, non-partitioned normal unique index with the same column order and no other constraints sharing it.
+
+<Callout type="warn">Changing a primary key drops the original key and its supporting index before creating the new key. The two DDL statements commit independently, leaving the table without a primary key between them and possibly after a failed add. Dropping a key runs only the drop step.</Callout>
+
+1. Choose **Edit** on the primary key's constraint card, select the target columns, and use **Move up** and **Move down** to set their order. Choose **Delete** to remove the entire key.
+2. Save other structure changes separately, then preview the primary key SQL. DBX checks the latest definition, supporting index, foreign-key references, and null or duplicate target values. References, including disabled foreign keys, incomplete metadata, and unsupported states prevent execution.
+3. Review the table, constraint name, and column order before saving. DBX checks the definition again before execution. If it changed, refresh and preview again.
+4. Review the execution result and reloaded structure. If a statement fails or its outcome is unknown, inspect the database before attempting another change.
+
+When the original key was dropped and a subsequent read confirms that the table has no primary key, the result details include candidate SQL for manual recovery. Recheck the data, names, and indexes before running it. DBX never executes recovery automatically. This SQL restores only the original logical primary key, not physical properties such as tablespace, compression, or storage settings.
+
+### Edit an Existing Native Oracle Primary Key
+
+Native Oracle uses the same constraint card, ordered column selection, preview, and save entry points. Replacement on ordinary tables preserves the original enabled, validated, deferrable, and initially deferred state, including meaningful RELY settings for unvalidated constraints. It does not automatically enable or validate the key. Target columns must still pass null and duplicate checks. External, index-organized, and temporary tables are excluded from this entry point.
+
+Index columns may have a different order from the constraint, but must contain the same set of columns. Valid, visible, non-partitioned normal nonunique indexes are also supported; deferrable keys use nonunique indexes. A disabled key without an associated index is shown explicitly: DBX does not infer or delete a same-named independent index, or create an index for the replacement. Manual recovery candidates retain the original constraint state without automatically enabling a disabled key.
+
+Choose **Keep the original index** or **Drop the original index** before saving. Keeping it is the default and preserves the old uniqueness rules. For example, changing a single-column key to a composite key does not remove the original column's uniqueness when its unique index is retained. Dropping the index loses its physical settings; preview identifies the affected index. A changed column set uses a new index name to avoid colliding with the retained index.
+
+DBX blocks known references, and the database rejects references that are invisible or added concurrently. No cascade is used. The two DDL statements commit independently; after partial failure, inspect the actual key and index states. Manual recovery recommends reusing an old index only when its complete definition still matches. If a same-name index changed or its state is unknown, the candidate remains commented out for manual inspection. Native Oracle live-database acceptance is still pending; OceanBase results do not establish native Oracle acceptance.
+
## Indexes, Foreign Keys, and Triggers
Index capabilities vary by dialect and can include:
@@ -55,7 +78,15 @@ Index capabilities vary by dialect and can include:
- Index comments where supported
- Automatic names for new indexes with editable values
-Foreign-key editing covers column mappings and update/delete actions. Trigger editing depends on source retrieval and safe DDL generation; unsupported databases can still expose source or copyable DDL.
+Native Oracle and OceanBase Oracle both provide foreign-key create, edit, and drop actions for existing and new tables. DBX reads and verifies an existing definition before enabling its editor. Incomplete or unreadable definitions remain read-only.
+
+Composite foreign keys store each local and referenced column as an ordered pair. Moving a row moves both columns. `ON DELETE` supports `NO ACTION`, `CASCADE`, and `SET NULL`; Oracle does not expose `ON UPDATE`. Both databases expose enabled, validated, and `RELY` states. Deferrability is available only for native Oracle.
+
+Save existing-table foreign-key changes separately from columns, primary keys, indexes, triggers, partitions, table comments, or handwritten DDL. A new-table plan can include columns, a primary key, and foreign keys, including a self-reference. Before saving, DBX rechecks the source definition, parent key, permissions, and applicable data conditions. If required metadata is unreadable or validation data fails, DBX does not drop the original foreign key first. The database makes the final permission decision for a single ADD statement.
+
+Foreign-key DDL statements commit one at a time. If CREATE succeeds and a later foreign-key statement fails, the table and completed steps remain. DBX stops the remaining steps and does not drop the table, retry, or roll back automatically. A failed existing-key rebuild can also leave the original key absent. Refresh and inspect the actual definitions before retrying. Result details may include recovery SQL that requires manual review.
+
+Foreign-key editing on other databases depends on the implementation for that dialect. Trigger editing depends on source retrieval and safe DDL generation; unsupported databases can still expose source or copyable DDL.
## DDL Preview
diff --git a/flake.nix b/flake.nix
index a58d5338a9..a8d5ec0748 100644
--- a/flake.nix
+++ b/flake.nix
@@ -75,10 +75,16 @@
]
);
+ # Match the package manager version declared by package.json.
+ pnpmTool = pkgs.pnpm_10.override {
+ version = "10.34.7";
+ hash = "sha512-upirxYVTmTM3W1lx9LxtbHOhtLftxKh559EC/lQj0eAjCdZ8YKEfBJVQk6luUhrZw7E4zdZUylvlY/N4s65IvQ==";
+ };
+
# Node / frontend tooling
nodeDeps = with pkgs; [
nodejs_22
- pnpm
+ pnpmTool
# Optional: for building native node addons (better-sqlite3 etc.)
python3
gnumake
@@ -193,11 +199,11 @@
# a content-addressed store path so the build sandbox has no network. #
pnpmDeps = pkgs.fetchPnpmDeps {
inherit (finalAttrs) pname version src;
- # `fetcherVersion = 4` is supported for `pnpm_11`
+ pnpm = pnpmTool;
fetcherVersion = 4;
# Update with the hash reported by a failed fixed-output build:
# nix build .#dbx-pnpm-deps 2>&1 | grep 'got:'
- hash = "sha256-Bo0dVkNR2jupcSthmcrjJw2aAsJ+fMhe3g82T4H8u2M=";
+ hash = "sha256-AUHM0u41ObqzcAvJ/Kx6uLc/SAehBFjTYEJW0IKEPAM=";
};
# ── Step 2: vendor Cargo dependencies ───────────────────────────── #
@@ -221,7 +227,7 @@
[
rustToolchain
pkgs.nodejs_22
- pkgs.pnpm
+ pnpmTool
pkgs.pkg-config
pkgs.perl
pkgs.jq # used by preConfigure to strip packageManager