fix(neo4j): correct label grids typed saves and menus
This commit is contained in:
1 parent
8d9e2dc49f
commit
6a2a15796e
14 files changed
+394
-112
No files matched your search
@@ -4,7 +4,9 @@ use super::*;
|
||||
use crate::models::connection::DatabaseType;
|
||||
use crate::sql_dialect::{neo4j_element_id_function, NEO4J_LEGACY_ELEMENT_ID_FUNCTION};
|
||||
|
||||
pub(super) fn build_neo4j_data_grid_save_statements(options: &DataGridSaveStatementOptions) -> Vec<String> {
|
||||
pub(super) fn build_neo4j_data_grid_save_statements(
|
||||
options: &DataGridSaveStatementOptions,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let label = quote_ident(Some(DatabaseType::Neo4j), &options.table_meta.table_name);
|
||||
let element_id_function = neo4j_element_id_function(options.server_version.as_deref());
|
||||
let mut statements = Vec::new();
|
||||
@@ -20,13 +22,12 @@ pub(super) fn build_neo4j_data_grid_save_statements(options: &DataGridSaveStatem
|
||||
if is_neo4j_element_id(Some(DatabaseType::Neo4j), Some(column)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"n.{} = {}",
|
||||
quote_ident(Some(DatabaseType::Neo4j), column),
|
||||
format_grid_sql_literal(value, Some(DatabaseType::Neo4j), None)
|
||||
))
|
||||
Some(
|
||||
property_literal(options, column, value)
|
||||
.map(|literal| format!("n.{} = {}", quote_ident(Some(DatabaseType::Neo4j), column), literal)),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join(", ");
|
||||
if sets.is_empty() {
|
||||
continue;
|
||||
@@ -58,13 +59,12 @@ pub(super) fn build_neo4j_data_grid_save_statements(options: &DataGridSaveStatem
|
||||
if value.is_null() {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{}: {}",
|
||||
quote_ident(Some(DatabaseType::Neo4j), column),
|
||||
format_grid_sql_literal(value, Some(DatabaseType::Neo4j), None)
|
||||
))
|
||||
Some(
|
||||
property_literal(options, column, value)
|
||||
.map(|literal| format!("{}: {}", quote_ident(Some(DatabaseType::Neo4j), column), literal)),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join(", ");
|
||||
statements.push(if props.is_empty() {
|
||||
format!("CREATE (n:{label});")
|
||||
@@ -73,52 +73,21 @@ pub(super) fn build_neo4j_data_grid_save_statements(options: &DataGridSaveStatem
|
||||
});
|
||||
}
|
||||
|
||||
statements
|
||||
Ok(statements)
|
||||
}
|
||||
|
||||
pub(super) fn build_neo4j_data_grid_rollback_statements(options: &DataGridSaveStatementOptions) -> Vec<String> {
|
||||
pub(super) fn build_neo4j_data_grid_rollback_statements(
|
||||
options: &DataGridSaveStatementOptions,
|
||||
) -> Result<Vec<String>, String> {
|
||||
// Matching inserted properties can delete other nodes, and recreating a
|
||||
// detached node cannot restore its identity or relationships.
|
||||
if !options.new_rows.is_empty() || !options.deleted_rows.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let label = quote_ident(Some(DatabaseType::Neo4j), &options.table_meta.table_name);
|
||||
let element_id_function = neo4j_element_id_function(options.server_version.as_deref());
|
||||
let mut statements = Vec::new();
|
||||
|
||||
for row in &options.new_rows {
|
||||
let where_clause = neo4j_row_property_where(&options.columns, row);
|
||||
statements.push(if where_clause.is_empty() {
|
||||
format!("MATCH (n:{label}) DETACH DELETE n;")
|
||||
} else {
|
||||
format!("MATCH (n:{label}) WHERE {where_clause} DETACH DELETE n;")
|
||||
});
|
||||
}
|
||||
|
||||
for row_index in &options.deleted_rows {
|
||||
let Some(row) = options.rows.get(*row_index) else {
|
||||
continue;
|
||||
};
|
||||
let props = options
|
||||
.columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, column)| !is_neo4j_element_id(Some(DatabaseType::Neo4j), Some(column)))
|
||||
.filter_map(|(index, column)| {
|
||||
let value = row.get(index).unwrap_or(&Value::Null);
|
||||
if value.is_null() {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{}: {}",
|
||||
quote_ident(Some(DatabaseType::Neo4j), column),
|
||||
format_grid_sql_literal(value, Some(DatabaseType::Neo4j), None)
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
statements.push(if props.is_empty() {
|
||||
format!("CREATE (n:{label});")
|
||||
} else {
|
||||
format!("CREATE (n:{label} {{{props}}});")
|
||||
});
|
||||
}
|
||||
|
||||
for (row_index, changes) in &options.dirty_rows {
|
||||
let Some(row) = options.rows.get(*row_index) else {
|
||||
continue;
|
||||
@@ -130,17 +99,12 @@ pub(super) fn build_neo4j_data_grid_rollback_statements(options: &DataGridSaveSt
|
||||
if is_neo4j_element_id(Some(DatabaseType::Neo4j), Some(column)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"n.{} = {}",
|
||||
quote_ident(Some(DatabaseType::Neo4j), column),
|
||||
format_grid_sql_literal(
|
||||
row.get(*column_index).unwrap_or(&Value::Null),
|
||||
Some(DatabaseType::Neo4j),
|
||||
None
|
||||
)
|
||||
))
|
||||
Some(
|
||||
property_literal(options, column, row.get(*column_index).unwrap_or(&Value::Null))
|
||||
.map(|literal| format!("n.{} = {}", quote_ident(Some(DatabaseType::Neo4j), column), literal)),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join(", ");
|
||||
if sets.is_empty() {
|
||||
continue;
|
||||
@@ -151,7 +115,7 @@ pub(super) fn build_neo4j_data_grid_rollback_statements(options: &DataGridSaveSt
|
||||
));
|
||||
}
|
||||
|
||||
statements
|
||||
Ok(statements)
|
||||
}
|
||||
|
||||
fn neo4j_element_id_predicate(columns: &[String], row: &[Value], element_id_function: &str) -> String {
|
||||
@@ -182,22 +146,76 @@ fn neo4j_legacy_element_id_literal(value: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn neo4j_row_property_where(columns: &[String], row: &[Value]) -> String {
|
||||
columns
|
||||
fn property_literal(options: &DataGridSaveStatementOptions, column: &str, value: &Value) -> Result<String, String> {
|
||||
// Cypher property names are case-sensitive, unlike relational metadata lookups.
|
||||
let data_type = options
|
||||
.table_meta
|
||||
.columns
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, column)| {
|
||||
if is_neo4j_element_id(Some(DatabaseType::Neo4j), Some(column)) {
|
||||
return None;
|
||||
.find(|info| info.name == column)
|
||||
.map(|info| info.data_type.as_str())
|
||||
.unwrap_or("");
|
||||
typed_property_literal(value, data_type)
|
||||
.map_err(|error| format!("Cannot save Neo4j property `{column}` ({data_type}): {error}"))
|
||||
}
|
||||
|
||||
fn typed_property_literal(value: &Value, data_type: &str) -> Result<String, &'static str> {
|
||||
if value.is_null() {
|
||||
return Ok("NULL".to_string());
|
||||
}
|
||||
let kind = data_type.trim().to_ascii_lowercase();
|
||||
if let Some(element_type) = kind.strip_suffix("array").or_else(|| kind.strip_suffix("[]")) {
|
||||
let parsed;
|
||||
let items = if let Some(items) = value.as_array() {
|
||||
items
|
||||
} else {
|
||||
parsed = serde_json::from_str::<Value>(value.as_str().ok_or("expected a JSON array")?)
|
||||
.map_err(|_| "expected a JSON array")?;
|
||||
parsed.as_array().ok_or("expected a JSON array")?
|
||||
};
|
||||
let values = items
|
||||
.iter()
|
||||
.map(|item| {
|
||||
if item.is_null() {
|
||||
return Err("property arrays cannot contain null");
|
||||
}
|
||||
typed_property_literal(item, element_type)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
return Ok(format!("[{}]", values.join(", ")));
|
||||
}
|
||||
let text = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
|
||||
let quoted = || format_grid_sql_literal(&Value::String(text.clone()), Some(DatabaseType::Neo4j), None);
|
||||
match kind.as_str() {
|
||||
"long" | "integer" | "int" => {
|
||||
let number = text.trim().parse::<i64>().map_err(|_| "expected a signed 64-bit integer")?;
|
||||
// Keep exact integers out of JavaScript floating-point conversions and
|
||||
// support the full signed range, including the minimum integer literal.
|
||||
Ok(format!("toInteger('{number}')"))
|
||||
}
|
||||
"double" | "float" => {
|
||||
let number = text.trim().parse::<f64>().map_err(|_| "expected a finite float")?;
|
||||
if !number.is_finite() {
|
||||
return Err("expected a finite float");
|
||||
}
|
||||
let value = row.get(index).unwrap_or(&Value::Null);
|
||||
let ident = format!("n.{}", quote_ident(Some(DatabaseType::Neo4j), column));
|
||||
if value.is_null() {
|
||||
Some(format!("{ident} IS NULL"))
|
||||
} else {
|
||||
Some(format!("{ident} = {}", format_grid_sql_literal(value, Some(DatabaseType::Neo4j), None)))
|
||||
Ok(format!("toFloat({})", quoted()))
|
||||
}
|
||||
"boolean" | "bool" => match text.trim().to_ascii_lowercase().as_str() {
|
||||
"true" => Ok("true".to_string()),
|
||||
"false" => Ok("false".to_string()),
|
||||
_ => Err("expected true or false"),
|
||||
},
|
||||
"string" => {
|
||||
if !value.is_string() {
|
||||
return Err("expected a string");
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" AND ")
|
||||
Ok(quoted())
|
||||
}
|
||||
"date" => Ok(format!("date({})", quoted())),
|
||||
"duration" => Ok(format!("duration({})", quoted())),
|
||||
// A mixed or unsupported property type must not silently become a string.
|
||||
_ => Err("this property type requires an explicit Cypher query"),
|
||||
}
|
||||
}
|
||||
@@ -403,6 +403,22 @@ pub fn prepare_data_grid_save_for_driver_profile(
|
||||
}
|
||||
|
||||
let mut keyless_guards = Vec::new();
|
||||
if options.database_type == Some(DatabaseType::Neo4j) {
|
||||
let generated = build_neo4j_data_grid_save_statements(&options).and_then(|statements| {
|
||||
build_neo4j_data_grid_rollback_statements(&options).map(|rollback| (statements, rollback))
|
||||
});
|
||||
let (validation_error, statements, rollback_statements) = match generated {
|
||||
Ok((statements, rollback)) => (None, statements, rollback),
|
||||
Err(error) => (Some(error), Vec::new(), Vec::new()),
|
||||
};
|
||||
return DataGridSavePreparation {
|
||||
validation_error,
|
||||
statements,
|
||||
rollback_statements,
|
||||
execution_schema: None,
|
||||
keyless_guards,
|
||||
};
|
||||
}
|
||||
let statements = build_data_grid_save_statements(&options, driver_profile, &mut keyless_guards);
|
||||
DataGridSavePreparation {
|
||||
validation_error: None,
|
||||
@@ -1093,6 +1109,12 @@ fn is_sqlserver_legacy_profile(driver_profile: Option<&str>) -> bool {
|
||||
}
|
||||
|
||||
pub fn build_data_grid_count_sql(options: DataGridCountSqlOptions) -> String {
|
||||
if options.database_type == Some(DatabaseType::Neo4j) {
|
||||
let label = quote_ident(Some(DatabaseType::Neo4j), &options.table_name);
|
||||
let predicate = crate::sql_dialect::normalize_where_input(options.where_input.as_deref());
|
||||
let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") };
|
||||
return format!("MATCH (n:{label}){where_clause} RETURN count(n) AS cnt");
|
||||
}
|
||||
// Keep the reference identical to the one the grid's SELECT uses: Caché/IRIS
|
||||
// reject quoted ordinary names when delimited identifiers are disabled, so
|
||||
// the count must not be the only statement that quotes them (#8929).
|
||||
@@ -1585,9 +1607,6 @@ fn build_data_grid_save_statements(
|
||||
driver_profile: Option<&str>,
|
||||
keyless_guards: &mut Vec<DataGridSaveGuard>,
|
||||
) -> Vec<String> {
|
||||
if options.database_type == Some(DatabaseType::Neo4j) {
|
||||
return build_neo4j_data_grid_save_statements(options);
|
||||
}
|
||||
if options.database_type == Some(DatabaseType::Tdengine) {
|
||||
return build_tdengine_data_grid_save_statements(options);
|
||||
}
|
||||
@@ -1787,9 +1806,6 @@ fn build_data_grid_rollback_statements(
|
||||
options: &DataGridSaveStatementOptions,
|
||||
driver_profile: Option<&str>,
|
||||
) -> Vec<String> {
|
||||
if options.database_type == Some(DatabaseType::Neo4j) {
|
||||
return build_neo4j_data_grid_rollback_statements(options);
|
||||
}
|
||||
if options.database_type == Some(DatabaseType::Tdengine) {
|
||||
return build_tdengine_data_grid_rollback_statements(options);
|
||||
}
|
||||
@@ -4274,6 +4290,113 @@ mod tests {
|
||||
assert_eq!(without_version.statements, on_neo4j_5.statements);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neo4j_property_writes_preserve_types_and_exact_integers() {
|
||||
for (kind, value, expected) in [
|
||||
("Long", json!("9223372036854775807"), "toInteger('9223372036854775807')"),
|
||||
("Integer", json!("-9223372036854775808"), "toInteger('-9223372036854775808')"),
|
||||
("Double", json!(2), "toFloat('2')"),
|
||||
("Boolean", json!("false"), "false"),
|
||||
("Date", json!("2026-09-30"), "date('2026-09-30')"),
|
||||
("Duration", json!("P1D"), "duration('P1D')"),
|
||||
("StringArray", json!("[\"A\",\"B\"]"), "['A', 'B']"),
|
||||
("LongArray", json!("[9007199254740997]"), "[toInteger('9007199254740997')]"),
|
||||
("BooleanArray", json!([true, false]), "[true, false]"),
|
||||
("String", json!("a'b\\c"), "'a\\'b\\\\c'"),
|
||||
] {
|
||||
let prepared = prepare_data_grid_save(neo4j_property_save_options(kind, value));
|
||||
assert_eq!(prepared.validation_error, None, "{kind}");
|
||||
assert_eq!(
|
||||
prepared.statements,
|
||||
vec![format!("MATCH (n:`Person`) WHERE elementId(n) = 'sample-id' SET n.`value` = {expected};")]
|
||||
);
|
||||
assert_eq!(prepared.rollback_statements, prepared.statements);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neo4j_property_writes_reject_invalid_and_ambiguous_types_before_execution() {
|
||||
for (kind, value) in [
|
||||
("Long", json!("9223372036854775808")),
|
||||
("Long", json!("1.5")),
|
||||
("Long", json!("1); MATCH (n) DELETE n")),
|
||||
("Double", json!("NaN")),
|
||||
("Double", json!("Infinity")),
|
||||
("Boolean", json!("not-a-boolean")),
|
||||
("LongArray", json!("[null]")),
|
||||
("StringArray", json!("[1]")),
|
||||
("LongArray", json!("[1.5]")),
|
||||
("StringArray", json!("invalid JSON")),
|
||||
("Long | String", json!("12")),
|
||||
("Unknown", json!("12")),
|
||||
("Point", json!("{x:1,y:2}")),
|
||||
] {
|
||||
let prepared = prepare_data_grid_save(neo4j_property_save_options(kind, value));
|
||||
assert!(prepared.validation_error.is_some(), "{kind}");
|
||||
assert!(prepared.statements.is_empty(), "{kind}");
|
||||
assert!(prepared.rollback_statements.is_empty(), "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neo4j_insert_and_delete_do_not_generate_unsafe_history_reversals() {
|
||||
let mut options = neo4j_property_save_options("Long", json!("9007199254740997"));
|
||||
options.dirty_rows.clear();
|
||||
options.new_rows = vec![vec![Value::Null, json!("9007199254740997")]];
|
||||
let prepared = prepare_data_grid_save(options.clone());
|
||||
assert_eq!(prepared.validation_error, None);
|
||||
assert_eq!(prepared.statements, vec!["CREATE (n:`Person` {`value`: toInteger('9007199254740997')});"]);
|
||||
assert!(prepared.rollback_statements.is_empty());
|
||||
options.new_rows.clear();
|
||||
options.deleted_rows = vec![0];
|
||||
let prepared = prepare_data_grid_save(options);
|
||||
assert_eq!(prepared.statements, vec!["MATCH (n:`Person`) WHERE elementId(n) = 'sample-id' DETACH DELETE n;"]);
|
||||
assert!(prepared.rollback_statements.is_empty());
|
||||
}
|
||||
|
||||
fn neo4j_property_save_options(kind: &str, value: Value) -> DataGridSaveStatementOptions {
|
||||
DataGridSaveStatementOptions {
|
||||
database_type: Some(DatabaseType::Neo4j),
|
||||
identifier_quote: None,
|
||||
server_version: Some("Neo4j/5.26.0".to_string()),
|
||||
table_meta: DataGridTableMeta {
|
||||
catalog: None,
|
||||
database: None,
|
||||
schema: None,
|
||||
table_name: "Person".to_string(),
|
||||
primary_keys: vec![DBX_NEO4J_ELEMENT_ID_COLUMN.to_string()],
|
||||
columns: Some(vec![column("value", kind, true, None)]),
|
||||
},
|
||||
columns: vec![DBX_NEO4J_ELEMENT_ID_COLUMN.to_string(), "value".to_string()],
|
||||
source_columns: None,
|
||||
rows: vec![vec![json!("sample-id"), value.clone()]],
|
||||
dirty_rows: vec![(0, vec![(1, value)])],
|
||||
deleted_rows: vec![],
|
||||
new_rows: vec![],
|
||||
include_database_name: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neo4j_counts_use_cypher_and_keep_the_grid_predicate() {
|
||||
for (where_input, where_clause) in [(None, ""), (Some("WHERE n.`age` > 10"), " WHERE (n.`age` > 10)")] {
|
||||
let options = DataGridCountSqlOptions {
|
||||
database_type: Some(DatabaseType::Neo4j),
|
||||
identifier_quote: None,
|
||||
catalog: None,
|
||||
database: Some("neo4j".to_string()),
|
||||
schema: Some("neo4j".to_string()),
|
||||
table_name: "P`erson".to_string(),
|
||||
where_input: where_input.map(str::to_string),
|
||||
count_hint: None,
|
||||
};
|
||||
assert_eq!(
|
||||
build_data_grid_count_sql(options),
|
||||
format!("MATCH (n:`P``erson`){where_clause} RETURN count(n) AS cnt")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iris_cache_data_grid_save_uses_unquoted_ordinary_identifiers() {
|
||||
let result = prepare_data_grid_save(DataGridSaveStatementOptions {
|
||||
|
||||
Reference in new issue
Block a user