Skip to main content

quickstart/
quickstart.rs

1//! Quickstart — register a schema, plan a GQL query, translate the plan to SQL.
2//!
3//! Run with `cargo run -p rust-store-core --example quickstart`.
4//!
5//! Nothing in this file opens a connection: `plan_query` and `translate` are pure
6//! functions, which is what makes the core reusable from any host.
7
8use serde_json::{json, Map};
9
10use rust_store_core::command::plan_query;
11use rust_store_core::dialect::{translate, Backend};
12use rust_store_core::schema::Registry;
13
14fn main() -> Result<(), String> {
15    // 1. A model is plain JSON — defined once, usable against every backend.
16    let mut registry = Registry::new();
17    registry.register(&json!({
18        "name": "Post",
19        "collection": "posts",
20        "timestamps": true,
21        "fields": {
22            "title":  { "type": "string" },
23            "status": { "type": "string", "default": "draft" },
24            "views":  { "type": "int" }
25        },
26        "relations": {}
27    }))?;
28
29    // 2. GQL in, MongoDB command JSON out. Values are referenced by `@key`.
30    let gql = "Post($condition:@c0,$sort:@s1,$limit:@l0){title, status, views}";
31    let mut params = Map::new();
32    params.insert("c0".to_string(), json!({ "status": "published" }));
33    params.insert("s1".to_string(), json!({ "views": -1 }));
34    params.insert("l0".to_string(), json!(20));
35
36    let plan = plan_query(gql, &params, &registry, None)?;
37
38    println!("collection = {}", plan.collection);
39    println!("mode       = {}", plan.mode.as_str());
40
41    for cmd in &plan.commands {
42        println!("command    = {}", serde_json::to_string(cmd).unwrap());
43
44        // 3. The host runs `cmd` against MongoDB — or, for a SQL backend, asks the
45        //    core for parameterized SQL and binds it with its own driver.
46        let sql = translate(Backend::Postgres, cmd, &registry)?;
47        println!("sql        = {}", serde_json::to_string(&sql).unwrap());
48    }
49
50    Ok(())
51}