Aragog
aragog is a simple lightweight ODM/OGM library for ArangoDB using the arangors driver.
The main concept is to provide behaviors allowing to synchronize documents and structs as simply an lightly as possible.
The crate also provides a powerful AQL querying tool allowing complex graph queries in Rust
Features
By now the available features are:
- Creating a database connection pool from a defined
schema.json - Structures can implement different behaviors:
Record: The structure can be written into a ArangoDB collection as well as retrieved, from its_keyor other query arguments.New: The structure can be initialized from an other type (a form for example). It allows to maintain a privacy level in the model and to use different data formats.Update: The structure can be updated from an other type (a form for example). It allows to maintain a privacy level in the model and to use different data formats.Validate: The structure can perform simple validations before being created or saved into the database.Authenticate: The structure can define a authentication behaviour from asecret(a password for example) (seepassword_hashingsection)AuthorizeAction: The structure can define authorization behavior on a target record with custom Action type.Link: The structure can define relations with other models based on defined queries.ForeignLink: The structure can define relations with other models based on defined foreign key.
- Different operations can return a
ServiceErrorerror that can easily be transformed into a Http Error (can be used for the actix framework)
Cargo features
Actix and Open API
If you use this crate with the actix-web framework, you may want the aragog errors to be usable as http errors.
To do so you can add to your cargo.toml the following feature: actix. This will add Actix 3 dependency and compatibility
= { = "^0.5", = ["actix"] }
If you also want to be able to use paperclip, you may want aragog elements to be compatible.
To do so you can add to your cargo.toml the following feature: open-api.
= { = "^0.5", = ["actix", "open-api"] }
Password hashing
You may want aragog to provide a more complete Authenticate trait allowing to hash and verify passwords.
To do so you can add to your cargo.toml the following feature: password_hashing.
= { = "^0.5", = ["password_hashing"] }
It will add two functions in the Authenticate trait:
;
;
hash_passwordwill return a Argon2 encrypted password hash you can safely store to your databaseverify_passwordwill check if the providedpasswordmatches the Argon2 encrypted hash you stored.
The Argon2 encryption is based on the argonautica crate.
That crate requires the clang lib, so if you deploy on docker you will need to install it or define a custom image.
Schema and collections
In order for everything yo work you need to specify a schema.json file. The path of the schema must be set in SCHEMA_PATH environment variable or by default the pool will look for it in src/config/db/schema.json.
There are example
schema.jsonfiles in /examples/
The json must look like this:
When initializing the DatabaseConnectionPool every collection name will be searched in the database and if not found the collection will be automatically created.
You don't need to create the collections yourself
Indexes
The array of Index in indexes must have that exact format:
name: the index name,fields: an array of the fields concerned on that compound index,settings: this json bloc must be the serialized version of an IndexSettings variant from arangors driver.
There is no indexing for
edge_collections
Record
The global architecture is simple, every model you define that can be synced with the database must implement serde::Serialize, serde::Deserialize and Clone.
To declare a struct as a Model it must derive from aragog::Record (the collection name must be the same as the struct)
The model needs to have Validations so you'll need to either:
- Implement
aragog::Validateand specify validations - Derive
aragog::Validateand validations will be empty.
If you want any of the other behaviors you can implement the associated trait
The final model structure will be an Exact representation of the content of a ArangoDB document, so without its _key, _id and _rev.
Your project should contain some models folder with every struct representation of your database documents.
The real representation of a complete document is DatabaseRecord<T> where T is your model structure.
Example:
use ;
use ;
use tokio;
async
Edge Record
You can declare Edge collection models by deriving from aragog::EdgeRecord, the structure requires two string fields: _from and _to.
When deriving from EdgeRecord the struct will also automatically derive from Record so you'll need to implement Validate as well.
Example:
async
Querying
You can retrieve a document from the database as simply as it gets, from the unique ArangoDB _key or from multiple conditions.
The example below show different ways to retrieve records, look at each function documentation for more exhaustive explanations.
Example
// User creation
let record = create.await.unwrap;
// Find with the primary key or..
let user_record = find.await.unwrap;
// .. Generate a query and..
let query = query.filter;
// get the only record (fails if no or multiple records)
let user_record = get.await.unwrap.uniq.unwrap;
// Find all users with multiple conditions
let query = query.filter;
let clone_query = query.clone; // we clone the query
// This syntax is valid...
let user_records = get.await.unwrap;
// ... This one too
let user_records = clone_query.call.await.unwrap.;
You can simplify the previous queries with some tweaks and macros:
extern crate aragog;
// Find a user with multiple conditions
let query = query!.filter;
let records = get.await.unwrap;
The querying system hierarchy works this way:
new.filter.and.or.sort.limit.distinct;
Query Object
You can intialize a query in the following ways:
Query::new("CollectionName")Object.query()(only works ifObjectimplementsRecord)query!("CollectionName")
You can customize the query with the following operations:
filter()you can specify AQL comparisonsprune()you can specify blocking AQL comparisons for traversal queriessort()you can specify fields to sort withlimit()you can skip and limit the query resultsdistinct()you can skip duplicate documents
The order of operations will be respected in the rendered AQL query (except for
distinct)
you can then call a query in the following ways:
query.call::<Object>(&database_connection_pool)Object::get(query, &database_connection_pool
Which will return a JsonQueryResult containing a Vec of serde_json::Value.
JsonQueryResult can return deserialized models as DatabaseRecord by calling .get_records::<T>()
If you want to receive a unique record and render an error in case of multiple record you can use uniq().
Filter
You can initialize a Filter with Filter::new(comparison)
Each comparison is a Comparison struct built via ComparisonBuilder:
// for a simple field comparison
// Explicit
field.some_comparison;
// Macro
compare!.some_comparison;
// for field arrays (see ArangoDB operators)
// Explicit
all.some_comparison;
// Macro
compare!.some_comparison;
// Explicit
any.some_comparison;
// Macro
compare!.some_comparison;
// Explicit
none.some_comparison;
// Macro
compare!.some_comparison;
All the currently implemented comparison methods are listed under ComparisonBuilder documentation page.
Filters can be defined explicitely like this:
let filter = new;
or
let filter :Filter = field.equals_str.into;
Traversal Querying
You can use graph features with sub-queries with different ways:
Straightforward traversal query
- Explicit way
use Query;
let query = outbound;
let query = inbound;
let query = any;
// Named graph
let query = outbound_graph;
let query = inbound_graph;
let query = any_graph;
- Implicit way from a
DatabaseRecord<T>
# use Query;
let query = user_record.outbound_query;
let query = user_record.inbound_query;
Sub queries
Queries can be joined together through
- Edge traversal:
# use Query;
let query = new
.join_inbound;
- Named Graph traversal:
# use Query;
let query = new
.join_inbound;
It works with complex queries:
# use ;
let query = new
.filter
.join_inbound;
TODO
- Query system:
- Simple and modular query system
- Advanced query system supporting:
- Array variant querying (
ANY,NONE,ALL) - Sort, limit and distinct methods
- Custom return system
-
PRUNEoperation - Procedural Macros for syntax simplification and field presence validation at compile time
- ArangoDB functions (
LENGTH,ABS, etc.)
- Array variant querying (
- ORM and OGM
- Pundit like authorizations (authorize actions on model)
- Relations
- Handle graph vertices and edges
- Handle SQL-like relations (foreign keys)
- Handle queried relations
- Handle key-value pair system (redis like)
- Middle and long term:
- Handle revisions/concurrency correctly
- Code Generation
- Record
derivemacro - EdgeRecord
derivemacro checking_fromand_topresence at compile time - Handle a
attributemacro for indexes and generate the schema at compile time - Handle a
attributemacro for relations to provide the link methods automatically - Handle Migrations
- Record
- Define possible
asyncvalidations for database advance state check
Arango db setup
Installation (See official documentation Here)
- Download Link
- Run it with
/usr/local/sbin/arangodThe default installation contains one database_systemand a user namedroot - Create a user and database for the project with the
arangoshshell
arangosh> db._createDatabase("DB_NAME");
arangosh> var users = require("@arangodb/users");
arangosh> users.save("DB_USER", "DB_PASSWORD");
arangosh> users.grantDatabase("DB_USER", "DB_NAME");
It is a good practice to create a test db and a development db.
- you can connect to the new created db with
$> arangosh --server.username $DB_USER --server.database $DB_NAME
Q&A
- How can I customize the
collection_nameof myRecord?
Instead of deriving from
aragog::Recordyou can implementaragog::Recorddirectly and declarecollection_name()as a string litteral This is not recommended as it will not be possible in the future with automatic schema generation
- How can I customize the
collection_nameof myEdgeRecord?
Instead of deriving from
aragog::EdgeRecordyou can implementaragog::EdgeRecordandaragog::Recorddirectly and declarecollection_name()as a string litteral. This is not recommended as it will not be possible in the future with automatic schema generation
License
aragog is provided under the MIT license. See LICENSE.
An simple lightweight ODM for ArangoDB based on arangors.