diff --git a/Cargo.lock b/Cargo.lock index b9dc418..7448130 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -400,7 +400,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -906,6 +906,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "json5" +version = "1.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348cde6df2b507ba3c3753beba226baba8567af588d6568cdb9877f02c75b60" +dependencies = [ + "serde", + "ucd-trie", +] + [[package]] name = "leb128fmt" version = "0.1.0" @@ -1671,6 +1681,7 @@ version = "0.2.1" dependencies = [ "bson", "futures", + "json5", "log", "mongodb", "serde", @@ -1909,6 +1920,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -2124,7 +2141,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1776343..73c2d24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,3 +11,4 @@ bson = "2" tokio = { version = "1", features = ["rt", "rt-multi-thread"] } futures = "0.3" log = "0.4" +json5 = "1.3.7" diff --git a/src/main.rs b/src/main.rs index ce3a9d1..2c2f6d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,8 @@ use serde_json::{json, Value as JsonValue}; use std::collections::{HashMap, HashSet}; use std::io::{self, BufRead, Write}; +mod query_text; + /// Documents inspected when inferring the shape of a collection. const SAMPLE_SIZE: i64 = 100; @@ -1086,11 +1088,10 @@ fn parse_filter_str(s: &str) -> Result { if s.is_empty() || s == "{}" { return Ok(doc! {}); } - let json_val: JsonValue = - serde_json::from_str(s).map_err(|e| format!("Invalid filter JSON: {}", e))?; + let json_val = query_text::parse_relaxed(s).map_err(|e| format!("Invalid filter: {}", e))?; match json_to_bson(&json_val) { Bson::Document(doc) => Ok(doc), - _ => Err("Filter must be a JSON object".to_string()), + _ => Err("Filter must be a query document, e.g. { status: 'active' }".to_string()), } } @@ -1100,8 +1101,7 @@ fn parse_pipeline_str(s: &str) -> Result, String> { if s.is_empty() { return Ok(vec![]); } - let json_val: JsonValue = - serde_json::from_str(s).map_err(|e| format!("Invalid pipeline JSON: {}", e))?; + let json_val = query_text::parse_relaxed(s).map_err(|e| format!("Invalid pipeline: {}", e))?; match json_val { JsonValue::Array(arr) => arr .iter() @@ -1158,6 +1158,70 @@ fn parse_sql_from_clause(query: &str) -> Option { } } +/// A `SELECT * FROM collection [WHERE ...] [ORDER BY ...]` statement, as the host builds +/// it for a table tab. The filter and sort are query documents, not SQL conditions: +/// `WHERE { status: 'active' } ORDER BY { _id: -1 }`. +struct SqlSelect { + collection: String, + filter: Option, + sort: Option, +} + +fn parse_sql_select(query: &str) -> Option { + let query = query.trim().trim_end_matches(';'); + let from_pos = query.to_ascii_uppercase().find(" FROM ")?; + let rest = query[from_pos + 6..].trim_start(); + + // The host quotes identifiers (`"plans"`, backticks); a quoted name may hold spaces. + let (collection, after) = match rest.chars().next()? { + quote @ ('"' | '`' | '\'') => { + let inner = &rest[1..]; + let close = inner.find(quote)?; + (inner[..close].to_string(), &inner[close + 1..]) + } + _ => { + let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); + (rest[..end].to_string(), &rest[end..]) + } + }; + if collection.is_empty() { + return None; + } + + let clauses = query_text::split_sql_clauses(after); + Some(SqlSelect { + collection, + filter: clauses.filter, + sort: clauses.sort, + }) +} + +/// The inner statement of the row-count wrapper the host builds for "load row count": +/// `SELECT COUNT(*) FROM () as count_wrapper`. +fn unwrap_count_wrapper(query: &str) -> Option<&str> { + let query = query.trim().trim_end_matches(';').trim_end(); + let upper = query.to_ascii_uppercase(); + let head = "SELECT COUNT(*) FROM ("; + let tail = ") AS COUNT_WRAPPER"; + if !upper.starts_with(head) || !upper.ends_with(tail) { + return None; + } + Some(query[head.len()..query.len() - tail.len()].trim()) +} + +/// Parses the text of a filter or sort field into a query document. +fn parse_query_document(text: &str, what: &str, example: &str) -> Result { + let value = query_text::parse_relaxed(text).map_err(|e| { + format!("Invalid {what}: {e}. Write it as a query document, e.g. {example}") + })?; + match json_to_bson(&value) { + Bson::Document(doc) => Ok(doc), + _ => Err(format!( + "The {what} must be a query document, e.g. {example}" + )), + } +} + /// Tries to extract a collection name from `db.createCollection("name")`, /// which is what the host runs when a table is created. fn parse_create_collection(query: &str) -> Option { @@ -1332,13 +1396,45 @@ async fn execute_query( return dispatch_shell_query(client, db_name, parsed, limit, page).await; } - if let Some(collection_name) = parse_sql_from_clause(q) { + if let Some(inner) = unwrap_count_wrapper(q) { + let select = + parse_sql_select(inner).ok_or_else(|| "Cannot count this query".to_string())?; + let filter = match select.filter.as_deref() { + Some(text) => parse_query_document(text, "filter", "{ status: 'active' }")?, + None => doc! {}, + }; + let collection: mongodb::Collection = + client.database(db_name).collection(&select.collection); + let count = collection + .count_documents(filter) + .await + .map_err(safe_mongo_error)?; + return Ok(json!({ + "columns": ["count"], + "rows": [[count]], + "affected_rows": 0, + "truncated": false, + "has_more": false, + "pagination": null, + })); + } + + if let Some(select) = parse_sql_select(q) { + let filter = match select.filter.as_deref() { + Some(text) => parse_query_document(text, "filter", "{ status: 'active' }")?, + None => doc! {}, + }; + let sort = match select.sort.as_deref() { + Some(text) => Some(parse_query_document(text, "sort", "{ _id: -1 }")?), + None => None, + }; return execute_find( client, db_name, - &collection_name, - doc! {}, + &select.collection, + filter, None, + sort, limit, page, ) @@ -1369,11 +1465,11 @@ async fn dispatch_shell_query( } else { None }; - execute_find(client, db_name, coll, filter, projection, limit, page).await + execute_find(client, db_name, coll, filter, projection, None, limit, page).await } "findOne" => { let filter = parse_arg_as_doc(args.first())?; - execute_find(client, db_name, coll, filter, None, Some(1), 1).await + execute_find(client, db_name, coll, filter, None, None, Some(1), 1).await } "aggregate" => { let pipeline = parse_arg_as_pipeline(args.first())?; @@ -1538,6 +1634,7 @@ async fn execute_find( collection_name: &str, filter: Document, projection: Option, + sort: Option, limit: Option, page: u32, ) -> Result { @@ -1555,6 +1652,7 @@ async fn execute_find( if let Some(proj) = projection { options.projection = Some(proj); } + options.sort = sort; let mut cursor = collection .find(filter) @@ -1817,9 +1915,13 @@ fn bson_type_name(bson: &Bson) -> &'static str { } /// Converts a BSON value to a JSON value for transport. +/// +/// Types JSON cannot express (ObjectId, dates, UUIDs, binary, decimals, +/// timestamps, regular expressions) are sent as MongoDB Extended JSON v2 +/// (relaxed), e.g. `{"$oid": "..."}`, so the host can tell them from plain +/// strings and numbers. UUIDs (binary subtype 4) use the `$uuid` form. fn bson_to_json(bson: &Bson) -> JsonValue { match bson { - Bson::Double(f) => json!(f), Bson::String(s) => json!(s), Bson::Array(arr) => JsonValue::Array(arr.iter().map(bson_to_json).collect()), Bson::Document(doc) => { @@ -1831,18 +1933,27 @@ fn bson_to_json(bson: &Bson) -> JsonValue { } Bson::Boolean(b) => json!(b), Bson::Null => JsonValue::Null, - Bson::RegularExpression(re) => json!(format!("/{}/{}", re.pattern, re.options)), - Bson::JavaScriptCode(code) => json!(code), Bson::Int32(i) => json!(i), Bson::Int64(i) => json!(i), - Bson::Timestamp(ts) => json!(ts.time), - Bson::Binary(b) => json!(format!("Binary({} bytes)", b.bytes.len())), - Bson::ObjectId(oid) => json!(oid.to_hex()), - Bson::DateTime(dt) => json!(dt.timestamp_millis()), - Bson::Symbol(s) => json!(s), - Bson::Decimal128(d) => json!(d.to_string()), - Bson::Undefined | Bson::MinKey | Bson::MaxKey => JsonValue::Null, - _ => json!(bson.to_string()), + Bson::Binary(binary) if binary.subtype == bson::spec::BinarySubtype::Uuid => { + match binary.to_uuid() { + Ok(uuid) => json!({ "$uuid": uuid.to_string() }), + Err(_) => bson.clone().into_relaxed_extjson(), + } + } + other => other.clone().into_relaxed_extjson(), + } +} + +/// Reads an Extended JSON wrapper (`{"$oid": ...}`, `{"$date": ...}`, `{"$uuid": ...}`...) +/// back into the BSON value it stands for. Plain objects return `None`. +fn extended_json_to_bson(obj: &serde_json::Map) -> Option { + if !obj.keys().any(|key| key.starts_with('$')) { + return None; + } + match Bson::try_from(JsonValue::Object(obj.clone())) { + Ok(Bson::Document(_)) | Err(_) => None, + Ok(value) => Some(value), } } @@ -1863,6 +1974,9 @@ fn json_to_bson(val: &JsonValue) -> Bson { JsonValue::String(s) => Bson::String(s.clone()), JsonValue::Array(arr) => Bson::Array(arr.iter().map(json_to_bson).collect()), JsonValue::Object(obj) => { + if let Some(value) = extended_json_to_bson(obj) { + return value; + } let doc: Document = obj .iter() .map(|(k, v)| (k.clone(), json_to_bson(v))) @@ -1950,11 +2064,13 @@ fn coerce_to_field_type(new_val: &JsonValue, current: Option<&Bson>) -> Result Ok(Bson::Boolean(false)), _ => Err(invalid("Boolean")), }, - Bson::DateTime(_) => text - .trim() - .parse::() - .map(|millis| Bson::DateTime(bson::DateTime::from_millis(millis))) - .map_err(|_| invalid("Date")), + // Dates are shown as ISO 8601 text; epoch milliseconds are still accepted. + Bson::DateTime(_) => match text.trim().parse::() { + Ok(millis) => Ok(Bson::DateTime(bson::DateTime::from_millis(millis))), + Err(_) => bson::DateTime::parse_rfc3339_str(text.trim()) + .map(Bson::DateTime) + .map_err(|_| invalid("Date")), + }, Bson::Decimal128(_) => text .trim() .parse::() @@ -2031,6 +2147,211 @@ mod tests { ); } + #[test] + fn select_from_the_host_carries_filter_and_sort_documents() { + let select = parse_sql_select( + r#"SELECT * FROM "commercial_product_v10" WHERE { status: 'active' } ORDER BY { _id: -1 } LIMIT 100"#, + ) + .unwrap(); + + assert_eq!(select.collection, "commercial_product_v10"); + assert_eq!(select.filter.as_deref(), Some("{ status: 'active' }")); + assert_eq!(select.sort.as_deref(), Some("{ _id: -1 }")); + } + + #[test] + fn select_without_clauses_has_no_filter_or_sort() { + let select = parse_sql_select("SELECT * FROM `plans` LIMIT 10").unwrap(); + + assert_eq!(select.collection, "plans"); + assert_eq!(select.filter, None); + assert_eq!(select.sort, None); + } + + #[test] + fn select_accepts_unquoted_and_spaced_collection_names() { + assert_eq!( + parse_sql_select("select * from plans").unwrap().collection, + "plans" + ); + assert_eq!( + parse_sql_select("SELECT * FROM \"my plans\" WHERE { a: 1 }") + .unwrap() + .collection, + "my plans" + ); + } + + #[test] + fn the_host_row_count_wrapper_is_unwrapped() { + let inner = unwrap_count_wrapper( + "SELECT COUNT(*) FROM (SELECT * FROM \"plans\" WHERE { a: 1 }) as count_wrapper", + ) + .unwrap(); + + assert_eq!(inner, "SELECT * FROM \"plans\" WHERE { a: 1 }"); + assert!(unwrap_count_wrapper("SELECT * FROM plans").is_none()); + } + + #[test] + fn non_select_text_is_not_a_select() { + assert!(parse_sql_select("db.plans.find({})").is_none()); + assert!(parse_sql_select("SELECT * FROM ").is_none()); + } + + #[test] + fn query_documents_accept_the_shell_syntax() { + let doc = parse_query_document( + "{ status: 'active', _id: UUID('00f5cca7-0987-4c5f-87d4-5671e95697c8') }", + "filter", + "{ status: 'active' }", + ) + .unwrap(); + let uuid = bson::Uuid::parse_str("00f5cca7-0987-4c5f-87d4-5671e95697c8").unwrap(); + + assert_eq!(doc, bson::doc! { "status": "active", "_id": uuid }); + } + + #[test] + fn a_sort_document_keeps_its_key_order() { + let doc = parse_query_document("{ b: -1, a: 1 }", "sort", "{ _id: -1 }").unwrap(); + + assert_eq!(doc.keys().collect::>(), ["b", "a"]); + } + + #[test] + fn sql_style_conditions_are_rejected_with_a_hint_not_ignored() { + let error = parse_query_document("status = 'active'", "filter", "{ status: 'active' }") + .unwrap_err(); + + assert!(error.starts_with("Invalid filter:"), "{error}"); + assert!(error.contains("e.g. { status: 'active' }"), "{error}"); + } + + #[test] + fn a_non_object_filter_is_rejected() { + let error = parse_query_document("[1, 2]", "filter", "{ status: 'active' }").unwrap_err(); + + assert!(error.contains("must be a query document"), "{error}"); + } + + #[test] + fn shell_find_filters_accept_the_same_relaxed_syntax() { + let parsed = parse_shell_query("db.plans.find({ status: 'active' })").unwrap(); + + assert_eq!( + parse_arg_as_doc(parsed.args.first()).unwrap(), + bson::doc! { "status": "active" } + ); + } + + #[test] + fn uuid_binary_is_sent_as_an_extended_json_uuid() { + let uuid = bson::Uuid::parse_str("00f5cca7-0987-4c5f-87d4-5671e95697c8").unwrap(); + + assert_eq!( + bson_to_json(&Bson::from(uuid)), + json!({ "$uuid": "00f5cca7-0987-4c5f-87d4-5671e95697c8" }) + ); + } + + #[test] + fn other_binary_keeps_its_subtype_and_content() { + let binary = Bson::Binary(bson::Binary { + subtype: bson::spec::BinarySubtype::Generic, + bytes: vec![1, 2, 3], + }); + + assert_eq!( + bson_to_json(&binary), + json!({ "$binary": { "base64": "AQID", "subType": "00" } }) + ); + } + + #[test] + fn object_id_and_date_are_tagged_not_flattened() { + let oid = bson::oid::ObjectId::parse_str("65f0c0ffee0123456789abcd").unwrap(); + let date = bson::DateTime::from_millis(1_777_068_224_845); + + assert_eq!( + bson_to_json(&Bson::ObjectId(oid)), + json!({ "$oid": "65f0c0ffee0123456789abcd" }) + ); + assert_eq!( + bson_to_json(&Bson::DateTime(date)), + json!({ "$date": "2026-04-24T22:03:44.845Z" }) + ); + } + + #[test] + fn nested_values_are_tagged_at_any_depth() { + let uuid = bson::Uuid::parse_str("00f5cca7-0987-4c5f-87d4-5671e95697c8").unwrap(); + let doc = bson::doc! { "owners": [ { "id": uuid } ], "n": 3_i32, "s": "x" }; + + assert_eq!( + bson_to_json(&Bson::Document(doc)), + json!({ + "owners": [ { "id": { "$uuid": "00f5cca7-0987-4c5f-87d4-5671e95697c8" } } ], + "n": 3, + "s": "x" + }) + ); + } + + #[test] + fn scalars_that_json_can_express_stay_plain() { + assert_eq!(bson_to_json(&Bson::Int64(7)), json!(7)); + assert_eq!(bson_to_json(&Bson::Double(1.5)), json!(1.5)); + assert_eq!(bson_to_json(&Bson::Boolean(true)), json!(true)); + assert_eq!(bson_to_json(&Bson::Null), JsonValue::Null); + } + + #[test] + fn tagged_values_round_trip_back_to_bson() { + let uuid = bson::Uuid::parse_str("00f5cca7-0987-4c5f-87d4-5671e95697c8").unwrap(); + let oid = bson::oid::ObjectId::parse_str("65f0c0ffee0123456789abcd").unwrap(); + let date = bson::DateTime::from_millis(1_777_068_224_845); + + for original in [Bson::from(uuid), Bson::ObjectId(oid), Bson::DateTime(date)] { + assert_eq!(json_to_bson(&bson_to_json(&original)), original); + } + } + + #[test] + fn a_plain_object_with_dollar_free_keys_stays_a_document() { + let value = json!({ "a": 1, "b": { "c": "d" } }); + + assert!(matches!(json_to_bson(&value), Bson::Document(_))); + } + + #[test] + fn pk_filter_accepts_a_tagged_uuid_id() { + let params = json!({ + "pk_map": { "_id": { "$uuid": "00f5cca7-0987-4c5f-87d4-5671e95697c8" } } + }); + let uuid = bson::Uuid::parse_str("00f5cca7-0987-4c5f-87d4-5671e95697c8").unwrap(); + + assert_eq!( + build_pk_filter(¶ms).unwrap(), + bson::doc! { "_id": uuid } + ); + } + + #[test] + fn date_edits_accept_iso_text_and_epoch_millis() { + let current = Bson::DateTime(bson::DateTime::from_millis(0)); + + assert_eq!( + coerce_to_field_type(&json!("2026-04-24T22:03:44.845Z"), Some(¤t)).unwrap(), + Bson::DateTime(bson::DateTime::from_millis(1_777_068_224_845)) + ); + assert_eq!( + coerce_to_field_type(&json!("1000"), Some(¤t)).unwrap(), + Bson::DateTime(bson::DateTime::from_millis(1000)) + ); + assert!(coerce_to_field_type(&json!("yesterday"), Some(¤t)).is_err()); + } + #[test] fn socks5_proxy_is_appended_to_an_srv_uri_with_options() { let params = json!({ diff --git a/src/query_text.rs b/src/query_text.rs new file mode 100644 index 0000000..db3574d --- /dev/null +++ b/src/query_text.rs @@ -0,0 +1,337 @@ +//! Reads the query text a user types the way the Mongo +//! shell accepts it: `{ status: 'active', createdAt: { $gt: ISODate('2026-01-01') } }`. +//! +//! The text is rewritten into Extended JSON (shell helpers such as `ObjectId(...)` +//! and regex literals become `{"$oid": ...}` / `{"$regularExpression": ...}`) and +//! parsed as JSON5, which allows unquoted keys, single quotes and trailing commas. + +use serde_json::{json, Value as JsonValue}; + +/// Parses relaxed query text into JSON, with shell helpers turned into Extended JSON. +pub fn parse_relaxed(text: &str) -> Result { + let rewritten = rewrite_shell_syntax(text)?; + json5::from_str::(&rewritten).map_err(|e| clean_json5_error(&e.to_string())) +} + +fn clean_json5_error(message: &str) -> String { + // json5 prefixes its position with " --> 1:5"; keep it, drop the noise around it. + message.lines().next().unwrap_or(message).trim().to_string() +} + +/// The `WHERE`, `ORDER BY` and `LIMIT` parts of a `SELECT * FROM coll ...` statement. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct SqlClauses { + pub filter: Option, + pub sort: Option, + pub limit: Option, +} + +/// Splits what follows the collection name in a `SELECT` into its clauses. A +/// keyword only counts at the top level, outside strings and brackets, so +/// `{ note: 'order by me' }` stays in one piece. +pub fn split_sql_clauses(rest: &str) -> SqlClauses { + #[derive(Clone, Copy, PartialEq)] + enum Clause { + Filter, + Sort, + Limit, + } + + let chars: Vec = rest.chars().collect(); + let mut found: Vec<(usize, usize, Clause)> = Vec::new(); // (keyword start, text start, kind) + let mut depth = 0i32; + let mut quote: Option = None; + let mut escaped = false; + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if let Some(q) = quote { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == q { + quote = None; + } + i += 1; + continue; + } + match c { + '\'' | '"' => quote = Some(c), + '{' | '[' | '(' => depth += 1, + '}' | ']' | ')' => depth = (depth - 1).max(0), + _ if depth == 0 && is_word_start(&chars, i) => { + for (keyword, kind) in [ + ("WHERE", Clause::Filter), + ("ORDER BY", Clause::Sort), + ("LIMIT", Clause::Limit), + ] { + if let Some(end) = keyword_end(&chars, i, keyword) { + found.push((i, end, kind)); + i = end - 1; + break; + } + } + } + _ => {} + } + i += 1; + } + + let mut clauses = SqlClauses::default(); + for (index, (_, text_start, kind)) in found.iter().enumerate() { + let text_end = found + .get(index + 1) + .map(|(keyword_start, _, _)| *keyword_start) + .unwrap_or(chars.len()); + let text: String = chars[*text_start..text_end].iter().collect(); + let text = text.trim(); + if text.is_empty() { + continue; + } + let slot = match kind { + Clause::Filter => &mut clauses.filter, + Clause::Sort => &mut clauses.sort, + Clause::Limit => &mut clauses.limit, + }; + *slot = Some(text.to_string()); + } + clauses +} + +fn is_word_start(chars: &[char], i: usize) -> bool { + chars[i].is_ascii_alphabetic() && (i == 0 || !is_word_char(chars[i - 1])) +} + +fn is_word_char(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '_' +} + +/// The index just after `keyword` (case-insensitive, spaces inside it may repeat) +/// when it starts at `i` and is followed by a non-word character. +fn keyword_end(chars: &[char], i: usize, keyword: &str) -> Option { + let mut at = i; + let mut first = true; + for word in keyword.split(' ') { + if !first { + let start = at; + while at < chars.len() && chars[at].is_whitespace() { + at += 1; + } + if at == start { + return None; + } + } + first = false; + for expected in word.chars() { + if at >= chars.len() || !chars[at].eq_ignore_ascii_case(&expected) { + return None; + } + at += 1; + } + } + if at < chars.len() && is_word_char(chars[at]) { + return None; + } + Some(at) +} + +/// Rewrites shell helpers and regex literals outside strings into Extended JSON. +fn rewrite_shell_syntax(text: &str) -> Result { + let chars: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + + while i < chars.len() { + let c = chars[i]; + match c { + '\'' | '"' => { + let end = string_end(&chars, i)?; + out.extend(&chars[i..end]); + i = end; + } + '/' if matches!(chars.get(i + 1), Some('*') | Some('/')) => { + let end = comment_end(&chars, i); + out.extend(&chars[i..end]); + i = end; + } + '/' if starts_regex_literal(&out) => { + let (pattern, options, end) = read_regex(&chars, i)?; + out.push_str( + &json!({ "$regularExpression": { "pattern": pattern, "options": options } }) + .to_string(), + ); + i = end; + } + _ if is_word_start(&chars, i) => { + let name_end = (i..chars.len()) + .find(|&j| !is_word_char(chars[j])) + .unwrap_or(chars.len()); + let name: String = chars[i..name_end].iter().collect(); + let after = skip_spaces(&chars, name_end); + if let Some(helper) = Helper::from_name(&name) { + if chars.get(after) == Some(&'(') { + let (args, end) = read_call_args(&chars, after)?; + out.push_str(&helper.to_extended_json(&name, &args)?); + i = end; + continue; + } + } + if name == "new" { + // `new Date(...)`: drop the keyword and let `Date(...)` take over. + i = after; + continue; + } + out.push_str(&name); + i = name_end; + } + _ => { + out.push(c); + i += 1; + } + } + } + Ok(out) +} + +enum Helper { + ObjectId, + Uuid, + Date, + NumberLong, + NumberInt, + NumberDecimal, +} + +impl Helper { + fn from_name(name: &str) -> Option { + match name { + "ObjectId" => Some(Self::ObjectId), + "UUID" => Some(Self::Uuid), + "ISODate" | "Date" => Some(Self::Date), + "NumberLong" => Some(Self::NumberLong), + "NumberInt" => Some(Self::NumberInt), + "NumberDecimal" => Some(Self::NumberDecimal), + _ => None, + } + } + + fn to_extended_json(&self, name: &str, args: &str) -> Result { + let arg = args.trim(); + if arg.is_empty() { + return Err(format!("{name}() needs a value")); + } + // The argument is a string or number literal; json5 normalises either. + let value = json5::from_str::(arg) + .map_err(|_| format!("{name}({arg}) is not a valid value"))?; + let text = match &value { + JsonValue::String(s) => s.clone(), + JsonValue::Number(n) => n.to_string(), + _ => return Err(format!("{name}({arg}) needs a string or a number")), + }; + Ok(match self { + Self::ObjectId => json!({ "$oid": text }), + Self::Uuid => json!({ "$uuid": text }), + Self::Date => json!({ "$date": text }), + Self::NumberLong => json!({ "$numberLong": text }), + Self::NumberDecimal => json!({ "$numberDecimal": text }), + Self::NumberInt => value, + } + .to_string()) + } +} + +/// The index just after the `//` or `/* */` comment that starts at `start`. +fn comment_end(chars: &[char], start: usize) -> usize { + if chars[start + 1] == '/' { + return (start..chars.len()) + .find(|&j| chars[j] == '\n') + .unwrap_or(chars.len()); + } + (start + 2..chars.len().saturating_sub(1)) + .find(|&j| chars[j] == '*' && chars[j + 1] == '/') + .map(|j| j + 2) + .unwrap_or(chars.len()) +} + +fn skip_spaces(chars: &[char], mut i: usize) -> usize { + while i < chars.len() && chars[i].is_whitespace() { + i += 1; + } + i +} + +/// The index just after the string that starts at `start`. +fn string_end(chars: &[char], start: usize) -> Result { + let quote = chars[start]; + let mut i = start + 1; + while i < chars.len() { + match chars[i] { + '\\' => i += 2, + c if c == quote => return Ok(i + 1), + _ => i += 1, + } + } + Err("Unterminated string".to_string()) +} + +/// The text between the parentheses of a call that opens at `open`, and the index after `)`. +fn read_call_args(chars: &[char], open: usize) -> Result<(String, usize), String> { + let mut i = open + 1; + let start = i; + while i < chars.len() { + match chars[i] { + '\'' | '"' => i = string_end(chars, i)?, + ')' => return Ok((chars[start..i].iter().collect(), i + 1)), + _ => i += 1, + } + } + Err("Missing closing parenthesis".to_string()) +} + +/// A `/` starts a regex literal where a value can start: after `:`, `,`, `[` or `(`. +fn starts_regex_literal(written: &str) -> bool { + matches!( + written.trim_end().chars().last(), + Some(':') | Some(',') | Some('[') | Some('(') + ) +} + +/// Reads `/pattern/flags` starting at `start`, and returns the pattern, the flags and the end index. +fn read_regex(chars: &[char], start: usize) -> Result<(String, String, usize), String> { + let mut i = start + 1; + let mut in_class = false; + let mut pattern = String::new(); + while i < chars.len() { + match chars[i] { + '\\' if i + 1 < chars.len() => { + pattern.push('\\'); + pattern.push(chars[i + 1]); + i += 2; + continue; + } + '/' if !in_class => { + let mut end = i + 1; + let mut options = String::new(); + while end < chars.len() && "imsxu".contains(chars[end]) { + options.push(chars[end]); + end += 1; + } + return Ok((pattern, options, end)); + } + c => { + match c { + '[' => in_class = true, + ']' => in_class = false, + _ => {} + } + pattern.push(c); + } + } + i += 1; + } + Err("Unterminated regular expression".to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/src/query_text/tests.rs b/src/query_text/tests.rs new file mode 100644 index 0000000..dc63564 --- /dev/null +++ b/src/query_text/tests.rs @@ -0,0 +1,168 @@ +use super::*; + +fn parse(text: &str) -> JsonValue { + parse_relaxed(text).unwrap() +} + +#[test] +fn strict_json_still_parses() { + assert_eq!( + parse(r#"{"status": "active", "n": 1}"#), + json!({"status": "active", "n": 1}) + ); +} + +#[test] +fn unquoted_keys_and_single_quotes_parse() { + assert_eq!( + parse("{ status: 'active', $or: [ { n: { $gt: 5 } } ] }"), + json!({"status": "active", "$or": [{"n": {"$gt": 5}}]}) + ); +} + +#[test] +fn trailing_commas_and_comments_are_tolerated() { + assert_eq!(parse("{ a: 1, /* note */ b: 2, }"), json!({"a": 1, "b": 2})); +} + +#[test] +fn key_order_is_kept() { + let value = parse("{ z: 1, a: 1, m: -1 }"); + let keys: Vec<&String> = value.as_object().unwrap().keys().collect(); + assert_eq!(keys, ["z", "a", "m"]); +} + +#[test] +fn object_id_and_uuid_helpers_become_extended_json() { + assert_eq!( + parse("{ _id: ObjectId('65f0c0ffee0123456789abcd') }"), + json!({"_id": {"$oid": "65f0c0ffee0123456789abcd"}}) + ); + assert_eq!( + parse(r#"{ _id: UUID("00f5cca7-0987-4c5f-87d4-5671e95697c8") }"#), + json!({"_id": {"$uuid": "00f5cca7-0987-4c5f-87d4-5671e95697c8"}}) + ); +} + +#[test] +fn date_helpers_all_mean_a_date() { + let expected = json!({"at": {"$date": "2026-01-01T00:00:00Z"}}); + assert_eq!(parse("{ at: ISODate('2026-01-01T00:00:00Z') }"), expected); + assert_eq!(parse("{ at: new Date('2026-01-01T00:00:00Z') }"), expected); + assert_eq!(parse("{ at: Date('2026-01-01T00:00:00Z') }"), expected); +} + +#[test] +fn number_helpers() { + assert_eq!( + parse("{ n: NumberLong('9007199254740993') }"), + json!({"n": {"$numberLong": "9007199254740993"}}) + ); + assert_eq!( + parse("{ n: NumberLong(5) }"), + json!({"n": {"$numberLong": "5"}}) + ); + assert_eq!(parse("{ n: NumberInt(5) }"), json!({"n": 5})); + assert_eq!( + parse("{ p: NumberDecimal('1.50') }"), + json!({"p": {"$numberDecimal": "1.50"}}) + ); +} + +#[test] +fn regex_literals_become_regular_expressions() { + assert_eq!( + parse("{ name: /^ana/i }"), + json!({"name": {"$regularExpression": {"pattern": "^ana", "options": "i"}}}) + ); + assert_eq!( + parse(r"{ $or: [ { a: /x\/y/ }, { b: /[/]/ } ] }"), + json!({"$or": [ + {"a": {"$regularExpression": {"pattern": r"x\/y", "options": ""}}}, + {"b": {"$regularExpression": {"pattern": "[/]", "options": ""}}} + ]}) + ); +} + +#[test] +fn helpers_and_slashes_inside_strings_are_left_alone() { + assert_eq!( + parse("{ note: 'call ObjectId(1) or /x/ now', url: 'a/b/c' }"), + json!({"note": "call ObjectId(1) or /x/ now", "url": "a/b/c"}) + ); +} + +#[test] +fn an_identifier_that_only_starts_like_a_helper_is_untouched() { + assert_eq!( + parse("{ ObjectIdx: 1, Dates: 2 }"), + json!({"ObjectIdx": 1, "Dates": 2}) + ); +} + +#[test] +fn bad_input_is_an_error_with_a_reason() { + assert!(parse_relaxed("status = 'active'").is_err()); + assert!(parse_relaxed("{ a: ").is_err()); + assert!(parse_relaxed("{ a: ObjectId() }") + .unwrap_err() + .contains("needs a value")); + assert!(parse_relaxed("{ a: ObjectId({}) }") + .unwrap_err() + .contains("string or a number")); + assert!(parse_relaxed("{ a: ObjectId('x' }") + .unwrap_err() + .contains("closing parenthesis")); + assert!(parse_relaxed("{ a: 'open }") + .unwrap_err() + .contains("Unterminated string")); + assert!(parse_relaxed("{ a: /open }") + .unwrap_err() + .contains("Unterminated regular")); +} + +#[test] +fn sql_clauses_are_split_in_any_order_and_case() { + let clauses = split_sql_clauses(" where { a: 1 } order by { b: -1 } limit 10"); + assert_eq!(clauses.filter.as_deref(), Some("{ a: 1 }")); + assert_eq!(clauses.sort.as_deref(), Some("{ b: -1 }")); + assert_eq!(clauses.limit.as_deref(), Some("10")); +} + +#[test] +fn sql_clauses_may_be_missing() { + assert_eq!(split_sql_clauses(""), SqlClauses::default()); + let only_sort = split_sql_clauses(" ORDER BY { b: 1 }"); + assert_eq!(only_sort.filter, None); + assert_eq!(only_sort.sort.as_deref(), Some("{ b: 1 }")); +} + +#[test] +fn keywords_inside_strings_and_brackets_do_not_split() { + let clauses = + split_sql_clauses(" WHERE { note: 'order by me', q: \"limit 5\", a: [ 'WHERE' ] } LIMIT 3"); + assert_eq!( + clauses.filter.as_deref(), + Some("{ note: 'order by me', q: \"limit 5\", a: [ 'WHERE' ] }") + ); + assert_eq!(clauses.sort, None); + assert_eq!(clauses.limit.as_deref(), Some("3")); +} + +#[test] +fn a_field_named_like_a_keyword_is_not_a_clause() { + let clauses = split_sql_clauses(" WHERE { limit: 1, where: 2, orderly: 3 }"); + assert_eq!( + clauses.filter.as_deref(), + Some("{ limit: 1, where: 2, orderly: 3 }") + ); + assert_eq!(clauses.limit, None); +} + +#[test] +fn spaces_inside_order_by_may_repeat() { + assert_eq!( + split_sql_clauses(" ORDER BY { a: 1 }").sort.as_deref(), + Some("{ a: 1 }") + ); +}