This crate allows you to send cypher queries to the REST endpoint of a neo4j database

Overview

rusted_cypher

Rust crate for accessing the cypher endpoint of a neo4j server

This crate allows you to send cypher queries to the REST endpoint of a neo4j database. You can execute queries inside a transaction or simply send queries that commit immediately.

Examples

Connecting to a Neo4j database

use rusted_cypher::GraphClient;
let graph = GraphClient::connect(
    "http://neo4j:neo4j@localhost:7474/db/data");

Performing Queries

let mut query = graph.query();

// Statement implements From<&str>
query.add_statement(
    "CREATE (n:LANG { name: 'Rust', level: 'low', safe: true })");

let statement = Statement::new(
    "CREATE (n:LANG { name: 'C++', level: 'low', safe: {safeness} })")
    .with_param("safeness", false)?;

query.add_statement(statement);

query.send()?;

graph.exec(
    "CREATE (n:LANG { name: 'Python', level: 'high', safe: true })")?;

let result = graph.exec(
    "MATCH (n:LANG) RETURN n.name, n.level, n.safe")?;

assert_eq!(result.data.len(), 3);

for row in result.rows() {
    let name: String = row.get("n.name")?;
    let level: String = row.get("n.level")?;
    let safeness: bool = row.get("n.safe")?;
    println!("name: {}, level: {}, safe: {}", name, level, safeness);
}

graph.exec("MATCH (n:LANG) DELETE n")?;

With Transactions

let transaction = graph
    .transaction()
    .with_statement(
        "CREATE (n:IN_TRANSACTION { name: 'Rust', level: 'low', safe: true })");

let (mut transaction, results) = transaction.begin().unwrap();

// Use `exec` to execute a single statement
transaction.exec("CREATE (n:IN_TRANSACTION { name: 'Python', level: 'high', safe: true })")?;

// use `add_statement` (or `with_statement`) and `send` to executes multiple statements
let stmt = Statement::new(
    "MATCH (n:IN_TRANSACTION) WHERE (n.safe = {safeness}) RETURN n")
    .with_param("safeness", true)?;

transaction.add_statement(stmt);
let results = transaction.send()?;

assert_eq!(results[0].data.len(), 2);

transaction.rollback()?;
}

Statements with Macro

There is a macro to help building statements

"Rust", "level" => "low", "safe" => true } )?; graph.exec(statement)?; let statement = cypher_stmt!( "MATCH (n:WITH_MACRO) WHERE n.name = {name} RETURN n", { "name" => "Rust" } )?; let results = graph.exec(statement)?; assert_eq!(results.data.len(), 1); let statement = cypher_stmt!("MATCH (n:WITH_MACRO) DELETE n")?; graph.exec(statement)?;">
let statement = cypher_stmt!(
    "CREATE (n:WITH_MACRO { name: {name}, level: {level}, safe: {safe} })", {
        "name" => "Rust",
        "level" => "low",
        "safe" => true
    }
)?;
graph.exec(statement)?;

let statement = cypher_stmt!(
    "MATCH (n:WITH_MACRO) WHERE n.name = {name} RETURN n", {
        "name" => "Rust"
    }
)?;

let results = graph.exec(statement)?;
assert_eq!(results.data.len(), 1);

let statement = cypher_stmt!("MATCH (n:WITH_MACRO) DELETE n")?;
graph.exec(statement)?;

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Comments
  • rustc_serialize support

    rustc_serialize support

    At the moment the library forces the user to use serde to deserialize the data. That implies a project which depends on rusted-cyper can't compile with the stable compiler unless it implements the trait for each struct or use the "syntex hack". Could we provide a function like

    pub fn get_rustc<T: rustc_serialize::Decodable>(&self, column: &str) -> Result<T, GraphError>
    

    at least as long as rust doesn't accept compiler plugins within stable releases?

    opened by flosse 15
  • working with NULL

    working with NULL

    Cypher does not allow to use null as parameter type. Unfortunately a serialized struct with a Option<T> field contains null values. So e.g. this would fail:

    struct Foo {
      id:  Option<u32>,
      name: String
    }
    
    let x = Foo{id: None, name: "foo".to_string()};
    graph.cypher()
      .exec(cypher_stmt!("CREATE (e:Entry {entry}) RETURN e.id" {
      "entry" => &x }))
    

    Do you have a recommendation for handling such a case?

    opened by flosse 5
  • Incompatibility with Serde 1.0.0

    Incompatibility with Serde 1.0.0

    After updating to the recently released 1.0.0 version of serde, serde_json, and serde_derive, I'm getting errors of this kind:

    `the trait `rusted_cypher::<unnamed>::Serialize` is not implemented for `{struct name here}``
    
    opened by manonthemat 4
  • "error: custom derive attribute panicked" compiling new project

    (Forgive me if this is something obvious, this is literally my first Rust project.)

    Steps to reproduce:

    1. create a new library project foo with cargo new
    2. cd to the project
    3. add rusted-cypher with cargo add
    4. cargo build

    Expected:

    • project compiles

    Actual:

    • compilation fails with "error: custom derive attribute panicked"
    $ cargo new foo
         Created library `foo` project
    $ cd foo
    $ cargo add rusted_cypher 
    $ cargo build
        Updating registry `https://github.com/rust-lang/crates.io-index`
       Compiling rustc-serialize v0.3.22
       Compiling regex-syntax v0.3.9
       Compiling winapi-build v0.1.1
       Compiling httparse v1.2.1
       Compiling serde v0.9.10
       Compiling itoa v0.3.1
       Compiling log v0.3.6
       Compiling dtoa v0.4.1
       Compiling libc v0.2.21
       Compiling unicode-normalization v0.1.4
       Compiling mime v0.2.2
       Compiling num-traits v0.1.37
       Compiling winapi v0.2.8
       Compiling utf8-ranges v0.1.3
       Compiling time v0.1.36
       Compiling memchr v0.1.11
       Compiling unicode-xid v0.0.4
       Compiling synom v0.11.3
       Compiling aho-corasick v0.5.3
       Compiling quick-error v1.1.0
       Compiling lazy_static v0.2.2
       Compiling typeable v0.1.2
       Compiling traitobject v0.1.0
       Compiling matches v0.1.4
       Compiling kernel32-sys v0.2.2
       Compiling unicode-bidi v0.2.5
       Compiling quote v0.3.14
       Compiling num_cpus v1.3.0
       Compiling semver v0.1.20
       Compiling language-tags v0.2.2
       Compiling thread-id v2.0.0
       Compiling thread_local v0.2.7
       Compiling syn v0.11.8
       Compiling rustc_version v0.1.7
       Compiling idna v0.1.0
       Compiling unicase v1.4.0
       Compiling hyper v0.10.5
       Compiling regex v0.1.80
       Compiling url v1.4.0
       Compiling serde_codegen_internals v0.14.1
       Compiling serde_json v0.9.8
       Compiling serde_derive v0.9.10
       Compiling semver-parser v0.6.2
       Compiling semver v0.5.1
       Compiling rusted_cypher v1.0.0
    error: custom derive attribute panicked
       --> /Users/dmoles/.cargo/registry/src/github.com-1ecc6299db9ec823/rusted_cypher-1.0.0/src/cypher/transaction.rs:115:17
        |
    115 | #[derive(Debug, Deserialize)]
        |                 ^^^^^^^^^^^
        |
        = help: message: assertion failed: !p.is_null()
    
    error: Could not compile `rusted_cypher`.
    
    To learn more, run the command again with --verbose.
    

    Running again with --verbose doesn't provide any more error output, just the full rustc commands. The cause is given as:

      process didn't exit successfully: `rustc --crate-name rusted_cypher /Users/dmoles/.cargo/registry/src/github.com-1ecc6299db9ec823/rusted_cypher-1.0.0/src/lib.rs --crate-type lib -g -C metadata=6d3ed2b8fc0765f2 -C extra-filename=-6d3ed2b8fc0765f2 --out-dir /Users/dmoles/foo/target/debug/deps --emit=dep-info,link -L dependency=/Users/dmoles/foo/target/debug/deps --extern serde_derive=/Users/dmoles/foo/target/debug/deps/libserde_derive-33957e402d840a76.dylib --extern quick_error=/Users/dmoles/foo/target/debug/deps/libquick_error-131bda12920364f4.rlib --extern log=/Users/dmoles/foo/target/debug/deps/liblog-1ce22d3a92f37841.rlib --extern serde_json=/Users/dmoles/foo/target/debug/deps/libserde_json-d68cb7971985091c.rlib --extern serde=/Users/dmoles/foo/target/debug/deps/libserde-dac34a4e26465874.rlib --extern semver=/Users/dmoles/foo/target/debug/deps/libsemver-58ba1dc30195eb36.rlib --extern time=/Users/dmoles/foo/target/debug/deps/libtime-53238cb92943b947.rlib --extern hyper=/Users/dmoles/foo/target/debug/deps/libhyper-a893baf9128f9685.rlib --cap-lints allow` (exit code: 101)
    

    This is on macOS 10.11.6 with rustc 1.15.1 and cargo 0.16.0-dev.

    opened by dmolesUC 2
  • r2d2 support

    r2d2 support

    I started with a first snippet to use your library with r2d2: https://github.com/flosse/r2d2-cypher. Do you have an idea how I can check if the connection of the GraphClient is still alive? Is there a cypher query that always works with minimal payload?

    opened by flosse 2
  • No method 'query' found

    No method 'query' found

    I have this code from the examples

    let graph = GraphClient::connect("http://neo4j:neo4j@localhost:7474/db/data"); let mut query = graph.query();

    and I'm getting this error

    error[E0599]: no method named query found for type std::result::Result<rusted_cypher::GraphClient, rusted_cypher::GraphError> in the current scope --> src/main.rs:3342:27
    |
    3342 | let mut query = graph.query();
    | ^^^^^

    opened by dkoch144 1
  • Fix serde dependency on syntex

    Fix serde dependency on syntex

    When trying to build rusted_cypher, I ran into a problem where syntex would fail with the error message:

       Compiling rusted_cypher v0.9.0 (file:///Users/lonkastenson/Development/rust/rusted-cypher)
    build.rs:17:32: 17:45 error: mismatched types [E0308]
    build.rs:17        serde_codegen::register(&mut registry);
                                               ^~~~~~~~~~~~~
    build.rs:17:32: 17:45 help: run `rustc --explain E0308` to see a detailed explanation
    build.rs:17:32: 17:45 note: expected type `&mut syntex::Registry`
    build.rs:17:32: 17:45 note:    found type `&mut inner::syntex::Registry`
    error: aborting due to previous error
    

    An alternative method has been implemented by the serde developers which is detailed here. I implemented that in rusted-cypher.

    https://users.rust-lang.org/t/here-is-how-to-avoid-being-broken-by-syntex-updates/6189?u=dtolnay

    Please let me know any feedback that I can make this pr any better. Thank you.

    opened by lhkastenson 1
  • add 'get_json_string' and 'get_json_string_n' functions

    add 'get_json_string' and 'get_json_string_n' functions

    This two helper methods is a dirty workaround to use rusted_cypher with rustc_serialize without depending on it. It's really dirty because rusted_cypher deserializes the result and directly serializes it again so that rustc_serialize can deserializes it! But as long as performance doesn't matter, it solves #5 ;-)

    opened by flosse 1
  • Bump dependencies

    Bump dependencies

    We're using Iron internally at product-bio for routing, at it depends on a newer version of Hyper (0.7) which, in turn, requires a newer version of the openssl library. Cargo requires that a native library can only be linked to a single Cargo package, so when integrating rusted-cypher, my project simply would not compile.

    I also took the liberty of bumping some other outdated dependencies flagged by cargo outdated. Tests seem to be passing on my end despite the updates!

    opened by afldcr 0
  • feat: Support for neo4j 4 and tokio async

    feat: Support for neo4j 4 and tokio async

    @livioribeiro I added this PR to give support for more recent versions of neo4j and updated some of the libraries, including hyper, which requires tokio async

    opened by bakjos 0
  • Not thread safe

    Not thread safe

    The way that the graph headers is implemented means that the crate is not thread safe.

    My quick solution is not to connect to neo4j in the main program, but instead to connect inside the threads. It means there is no connection pooling.

    opened by AdrianChallinorOsiris 0
  • Make tests not depend on neo4j server

    Make tests not depend on neo4j server

    Currently tests depend on a neo4j server available at http://neo4j:neo4j@localhost:7474.

    Tests should use a mock server, so they can run more easily on a CI environment.

    opened by livioribeiro 2
Releases(v0.9.1)
A Distributed SQL Database - Building the Database in the Public to Learn Database Internals

Table of Contents Overview Usage TODO MVCC in entangleDB SQL Query Execution in entangleDB entangleDB Raft Consensus Engine What I am trying to build

Sarthak Dalabehera 38 Jan 2, 2024
Distributed, version controlled, SQL database with cryptographically verifiable storage, queries and results. Think git for postgres.

SDB - SignatureDB Distributed, version controlled, SQL database with cryptographically verifiable storage, queries and results. Think git for postgres

Fremantle Industries 5 Apr 26, 2022
An async Rust client for SurrealDB's RPC endpoint

An async Rust client for SurrealDB's RPC endpoint This crate serves as a temporary yet complete implementation of an async Rust client to connect to a

Thibault H 12 Jan 21, 2023
SubZero - a standalone web server that turns your database directly into a REST/GraphQL api

What is this? This is a demo repository for the new subzero codebase implemented in Rust. subZero is a standalone web server that turns your database

subZero 82 Jan 1, 2023
🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, SQLite, and MSSQL.

SQLx ?? The Rust SQL Toolkit Install | Usage | Docs Built with ❤️ by The LaunchBadge team SQLx is an async, pure Rust† SQL crate featuring compile-tim

launchbadge 7.6k Dec 31, 2022
rust_arango enables you to connect with ArangoDB server, access to database, execute AQL query, manage ArangoDB in an easy and intuitive way, both async and plain synchronous code with any HTTP ecosystem you love.

rust_arango enables you to connect with ArangoDB server, access to database, execute AQL query, manage ArangoDB in an easy and intuitive way, both async and plain synchronous code with any HTTP ecosystem you love.

Foretag 3 Mar 24, 2022
Mycelite is a SQLite extension that allows you to synchronize changes from one instance of SQLite to another.

Mycelite What is Mycelite? Mycelite is a SQLite extension that allows you to synchronize changes from one instance of SQLite to another. Currently, it

Mycelial 16 Jan 2, 2023
An object-relational in-memory cache, supports queries with an SQL-like query language.

qlcache An object-relational in-memory cache, supports queries with an SQL-like query language. Warning This is a rather low-level library, and only p

null 3 Nov 14, 2021
Run SQL queries on CSV files

zsql run SQL queries on csv files A terminal utility to easily run SQL queries on CSV files. zsql is shipped as a small single binary powered by rust

Zizaco 9 Jul 9, 2022
Running SQL-like queries on files.

filesql Running SQL-like queries on files. Features Supported: REPL Basic SQL expressions. INSERT clause. (which inserts data into another file) WHERE

Zhang Li 1 Nov 15, 2021
A query builder that builds and typechecks queries at compile time

typed-qb: a compile-time typed "query builder" typed-qb is a compile-time, typed, query builder. The goal of this crate is to explore the gap between

ferrouille 3 Jan 22, 2022
Rust library to parse, deparse and normalize SQL queries using the PostgreSQL query parser

This Rust library uses the actual PostgreSQL server source to parse SQL queries and return the internal PostgreSQL parse tree.

pganalyze 37 Dec 18, 2022
Implementation of generic IBC queries in CosmWasm.

CosmWasm IBC Queries Implements generic IBC queries in CosmWasm. This implementation requires the same contract to be deployed on both chains wishing

Jake Hartnell 17 Oct 6, 2022
fast & easy CLI and vscode extension specialized to format MySQL INSERT queries.

insertfmt fast & easy CLI specialized to format MySQL INSERT queries. format queries so that they look like a table. NOTE: If you wanna use the VSCode

canalun 7 May 2, 2023
An implementation of the tz database for the time-rs Rust crate.

time-tz An implementation of the tz database for the time-rs Rust crate. This implementation is based off of chrono-tz

null 12 Jul 27, 2022
Grsql is a great tool to allow you set up your remote sqlite database as service and CRUD(create/read/update/delete) it using gRPC.

Grsql is a great tool to allow you set up your remote sqlite database as service and CRUD (create/ read/ update/ delete) it using gRPC. Why Create Thi

Bruce Yuan 33 Dec 16, 2022
High performance and distributed KV store w/ REST API. 🦀

About Lucid KV High performance and distributed KV store w/ REST API. ?? Introduction Lucid is an high performance, secure and distributed key-value s

Lucid ᵏᵛ 306 Dec 28, 2022
A Rust client for the ElasticSearch REST API

rs-es Introduction An ElasticSearch client for Rust via the REST API. Targetting ElasticSearch 2.0 and higher. Other clients For later versions of Ela

Ben Ashford 218 Dec 27, 2022
An Elasticsearch REST API client for Rust

elastic elastic is an efficient, modular API client for Elasticsearch written in Rust. The API is targeting the Elastic Stack 7.x. elastic provides st

null 249 Oct 18, 2022