Git Product home page Git Product logo

Comments (2)

a-0-dev avatar a-0-dev commented on June 15, 2024

That sounds very useful indeed. I've been trying to use cozo in a project of mine (rusty, of course) for the past few months. It kind of works, but I have thought about writing some wrapper myself multiple times because it's not very pretty and feels error-prone (if you want to stay type-safe, you need to if let-unwrap anything the DB returns several times - that could be way nicer if there were inherent type guarantees for returns of fixed queries etc.)

My current (also ugly) workaround are these two macros, which provide some assistance for very basic DB operations and nothing else. I think the existence of this illustrates the pain one currently goes through when using cozo in some project:

#[macro_export]
macro_rules! build_query {
    ($payload:expr, $params:expr) => {{
        use cozo::DataValue;
        use std::collections::BTreeMap;
        // Build parameters map
        let mut params_map: BTreeMap<String, DataValue> = Default::default();
        let mut parameters_init = String::new();

        if $params.len() > 0 {
            for (name, value) in $params {
                let _: &str = name; // only for type annotation
                params_map.insert(name.to_string(), value);
            }

            // First line: Initialize parameters, make them available in CozoScript
            use itertools::Itertools;
            parameters_init += "?[";
            parameters_init += &params_map
                .iter()
                .map(|(name, _)| name)
                .format(", ")
                .to_string();
            parameters_init += "] <- [[";
            parameters_init += &params_map
                .iter()
                .map(|(name, _)| format!("${}", name))
                .format(", ")
                .to_string();
            parameters_init += "]]";
        }

        // Return query string and parameters map
        (format!("{}\n\n{}", parameters_init, $payload), params_map)
    }};
}

use build_query;

#[macro_export]
macro_rules! run_query {
    ($db:expr, $payload:expr, $params:expr, $mutability:expr) => {{
        let (query, parameters) = crate::state::queries::build_query!($payload, $params);
        $db.run_script(query.as_str(), parameters, $mutability)
    }};
}

An example insert-query wrapper function now looks like this:

pub fn add(
    db: &DbInstance,
    id: &AppId,
    last_access: &DateTime<Utc>,
    name: &str,
    description: &str,
) -> anyhow::Result<()> {
    let params = vec![
        (
            "id",
            DataValue::Str(serde_json::to_string(&id).unwrap().into()),
        ),
        (
            "last_access",
            DataValue::Num(Num::Int(last_access.timestamp())),
        ),
        ("name", DataValue::Str(name.into())),
        ("description", DataValue::Str(description.into())),
    ];

    match run_query!(
        &db,
        ":insert apps {id => last_access, name, description}",
        params,
        cozo::ScriptMutability::Mutable
    ) {
        Ok(_) => Ok(()),
        Err(report) => bail!(report),
    }
}

As I said, I'm still rather new to cozo so I don't want to judge any of the dev's decision and I'm grateful for their (your) work. Maybe there are better ways already. But to me as a novice, it's at least not ergonomic ;)

from cozo.

andrewbaxter avatar andrewbaxter commented on June 15, 2024

I'm not sure if this is a bad idea, but I'd like to do some security filtering on user queries:

  • Restricting queried relations
  • Adding membership clauses to relationship atoms

AFAICT recursing the datalog and making changes should be pretty simple and comprehensive, if it's basically a typed tree of enums/structs.

I'd be happy with something explicitly unstable.

from cozo.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.