#surrealdb #sql #garbage-collection #json-toml #sqlbuilder

surrealism

Rust's extension of SurrealDB's official library aims to facilitate and unify various operations

7 releases

0.3.1 Nov 4, 2023
0.3.0 Oct 24, 2023
0.2.2 Sep 22, 2023
0.2.0 Aug 30, 2023
0.1.1 Jun 17, 2023

#150 in Database interfaces

MIT license

310KB
6K SLoC

Surrealism

LICEMSE

MIT

Surrealism Introduction

Surrealism依托于Surrealdb提供的Rust官方标准库:surrealdb,目的是构建一种更加统一,简单的方式对Surrealdb数据库进行各类操作

Surrealism relies on Surrealdb's official Rust standard library:surrealdb,The purpose is to build a more unified and simple way to perul various operations on Surrealdb database

QuickStart

add dependencies

[dependencies]
surrealism = {version="0.3.1"}
tokio = { version = "1.28.0", features = ["macros", "rt-multi-thread"] }

add configuration

配置:

username:用户名
password:密码
local:本机连接(本机使用ws,远程使用wss)
bind: 连接地址,
auth:开启权限认证
tick_interval:运行节点代理tick的间隔(包括垃圾收集),默认为10秒
strict:严格模式
mode:连接模式(Memory表示内存File表示存到文件中,Tikv表示tikv集群地址)
path:存储到文件中的文件地址,使用Memory则无需设置
log:日志级别
query_timeout:设置查询超时时间
transaction_timeout: 事务超时时间
no_banner: 打印Banner
db_connection: 数据库连接行为
http_server: 服务器行为
capabilities: 能力

可采用JSON或TOML两种配置文件方式

设置配置文件地址可以是:

  • ./Surrealism.toml
  • ./configs/Surrealism.toml
  • ./templates/Surrealism.toml

configuration:

username: db username
password: db password
local: Local connection (using ws locally, using wss remotely)
bind: Connection address,
auth:Enable permission authentication
tick_interval:The interval between running node agent tickets (including garbage collection), which defaults to 10 seconds
strict:strict mode
mode:Connection mode (Memory represents memory, File represents storage to file, Tikv represents Tikv cluster address)
path:The file address stored in the file, which does not need to be set when using Memory
log:log level
query_timeout:Set query timeout time
transaction_timeout: Transaction timeout time
no_banner: Print Banner
db_connection: database connection behavior
http_server: server behavior
capabilities: db Capabilities

Two configuration file methods can be used: JSON or TOML

The configuration file address can be set to:

  • ./Surrealism.toml
  • ./configs/Surrealism.toml
  • ./templates/Surrealism.toml

Surrealism.json(JSON)

{
	"username" : "root",
	"password" : "syf20020816",
	"bind" : "127.0.0.1:10086",
	"mode" : "Memory",
	"log" : "Info",
    "local": true,
}

Surrealism.toml(TOML)

[default]
username = "root"
password = "syf20020816"
bind = "127.0.0.1:10086"
mode = "Memory"
log = "Info"
local = true

surrealdb

open surrealdb

image-20231024165545355

define ns,db,table first

image-20231024165607517

main.rs

use surrealism::db::{SurrealID, Table};
use surrealism::builder::{BaseWrapperImpl, SQLBuilderFactory, TableImpl};
use surrealism::builder::create::{CreateWrapper, CreateWrapperImpl};
use serde::{Serialize, Deserialize};
use surrealism::builder::select::SelectWrapperImpl;
use surrealism::surreal::{parse_response, SurrealismRes,DefaultInitService,UseNSDB,InitService,SurrealismCommit};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
    username: String,
    pwd: String,
    male: bool,
    age: u8,
}

/// create a new user table
/// table_name:user
/// table_id:surrealism
pub fn crate_user_table() -> CreateWrapper {
    // create a user data
    let user = User {
        username: "Tobie".to_string(),
        pwd: "Tobie001".to_string(),
        male: true,
        age: 23,
    };
    // create table with content
    let user_table = SQLBuilderFactory::create()
        .table("user")
        .id("surrealism".into())
        .content(&user)
        .deref_mut();
    user_table
}

//strict!
#[tokio::main]
async fn main() -> SurrealismRes<()> {
    // init service
    let mut service = DefaultInitService::new().init();
    // you have already define test namespace and test database!
    // use ns:test and db:test
    let _ = service.use_commit("test", "test").await?;
    // get info from surrealdb
    // let info = SQLBuilderFactory::info().db().build();
    // let info_res = service.commit_sql(&info).await?;
    // dbg!(info_res);
    // create a table (you should define user table first!)
    let create_stmt = crate_user_table().build();
    let _ = service.commit_sql(&create_stmt).await?;
    // dbg!(create_res);
    // select user::surrealism table
    let select = SQLBuilderFactory::select().table("user").id("surrealism".into()).column("*", None).build();
    let select_res = service.commit_sql(&select).await?;
    //parse response to any type you want
    let res: User = parse_response(select_res);
    // [tests\src\main.rs:55] res = User {
    //     username: "Tobie",
    //     pwd: "Tobie001",
    //     male: true,
    //     age: 23,
    // }
    dbg!(&res);
    Ok(())
}

terminal res

   ▄▄▄▄                                                      ▄▄▄▄         ██
 ▄█▀▀▀▀█                                                     ▀▀██         ▀▀
 ██▄       ██    ██   ██▄████   ██▄████   ▄████▄    ▄█████▄    ██       ████     ▄▄█████▄  ████▄██▄
  ▀████▄   ██    ██   ██▀       ██▀      ██▄▄▄▄██   ▀ ▄▄▄██    ██         ██     ██▄▄▄▄ ▀  ██ ██ ██
      ▀██  ██    ██   ██        ██       ██▀▀▀▀▀▀  ▄██▀▀▀██    ██         ██      ▀▀▀▀██▄  ██ ██ ██
 █▄▄▄▄▄█▀  ██▄▄▄███   ██        ██       ▀██▄▄▄▄█  ██▄▄▄███    ██▄▄▄   ▄▄▄██▄▄▄  █▄▄▄▄▄██  ██ ██ ██
  ▀▀▀▀▀     ▀▀▀▀ ▀▀   ▀▀        ▀▀         ▀▀▀▀▀    ▀▀▀▀ ▀▀     ▀▀▀▀   ▀▀▀▀▀▀▀▀   ▀▀▀▀▀▀   ▀▀ ▀▀ ▀▀

2023-10-24T08:54:49.323Z INFO  [surrealism::core::surreal::config::init::default] Welcome to use Surrealism!
2023-10-24T08:54:49.323Z INFO  [surrealism::core::surreal::config::init::default] Init Service : `Config Service` Successfully!
2023-10-24T08:54:49.329Z INFO  [surrealism::core::surreal::config::init::default] Please focus following print to check!
Version {
    router: Ok(
        Router {
            conn: PhantomData<surrealdb::api::engine::remote::ws::Client>,
            sender: Sender,
            last_id: 1,
            features: {},
        },
    ),
}
2023-10-24T08:54:49.329Z INFO  [surrealism::core::surreal::config::init::default] Init Service : `Connection Service` Successfully!
[tests\src\main.rs:63] &res = User {
    username: "Tobie",
    pwd: "Tobie001",
    male: true,
    age: 23,
}

Surrealism ALL Supports

Features

default = ["builder"]
row = []
builder = []
surreal = ["builder"]
full = ["row", "builder", "surreal"]

Configuration配置文件

  • Surrealism.json支持
  • Surrealism.toml支持
  • 自定义构建支持(SurrealismConfig)

Init 初始化服务

  • DefaultInitService 默认初始化服务的支持
  • 自定义初始化服务的支持

ID 表ID

  • SurrealID::Default的支持
  • SurrealID::Int的支持
  • SurrealID::Float的支持
  • SurrealID::String的支持
  • SurrealID::Array的支持
  • SurrealID::UUID的支持
  • SurrealID::ULID的支持
  • SurrealID::RAND的支持
  • SurrealID::Range的支持

Value 数据类型

  • SurrealValue::None的支持
  • SurrealValue::Null的支持
  • SurrealValue::Int的支持
  • SurrealValue::Float的支持
  • SurrealValue::Decimal的支持
  • SurrealValue::String的支持
  • SurrealValue::Object的支持
  • SurrealValue::Datetime的支持(DatetimeAdapter)
  • SurrealValue::Duration的支持(DurationAdapter)
  • SurrealValue::Array的支持
  • SurrealValue::Set的支持
  • SurrealValue::Option的支持
  • SurrealValue::Geo的支持
  • SurrealValue::Record的支持
  • SurrealValue::Future的支持
  • 数学常数构建
  • 数学常数支持

Builder

  • USE STMT (In Connection)
  • CREATE STMT
  • SELECT STMT
  • LIVE SELECT STMT
  • RELATE STMT
  • UPDATE STMT
  • INSERT STMT
  • DELETE STMT
  • INFO STMT
  • TRANSACTION STMT
  • DEFINE STMT
  • REMOVE STMT
  • SLEEP STMT
  • LET STMT
  • BEGIN STMT
  • CANCEL STMT
  • COMMIT STMT
  • IF ELSE STMT
  • FOR STMT
  • BREAK STMT
  • CONTINUE STMT
  • KILL STMT
  • THROW STMT
  • RETURN STMT

Use

  • USE NS STMT
  • USE DB STMT

Create

  • CREATE CONTENT STMT
  • CREATE SET STMT
  • RETURN STMT
  • TIMEOUT STMT
  • PARALLEL STMT

Insert

  • INSERT INTO STMT
  • ON DUPLICATE KEY UPDATE STMT

Select

  • FIELD
  • OMIT
  • WITH INDEX|NOINDEX
  • FROM
  • WHERE
  • SPLIT
  • GROUP
  • ORDER
  • LIMIT
  • START
  • FETCH
  • TIMEOUT
  • PARALLEL
  • EXPLAIN [FULL]

Live Select

  • FIELD
  • FROM
  • WHERE
  • FETCH

Delete

  • DELETE WHERE
  • RETURN
  • TIMEOUT
  • PARALLEL
  • DELETE WITH RELETE

Remove

  • NAMESPACE
  • DATABASE
  • USER
  • LOGIN
  • TOKEN
  • SCOPE
  • TABLE
  • EVENT
  • FUNCTION
  • FIELD
  • INDEX
  • PARAM

Update

  • CONTENT
  • MERGE
  • PATCH
  • SET
  • WHERE
  • RETURN
  • TIMEOUT
  • PARALLEL

Define

  • NAMESPACE
  • DATABASE
  • USER
  • LOGIN
  • TOKEN
  • SCOPE
  • TABLE
  • EVENT
  • FUNCTION
  • FIELD
  • INDEX
  • PARAM
  • ANALYZER

Info

  • KV
  • NS
  • DB
  • SCOPE
  • TABLE

Show

  • SINCE
  • LIMIT

Sleep

  • Duration

Assert

  • ASSERT
  • WHERE
  • Condition
  • Criteria

Functions

  • Array
  • Count
  • Crypto
  • Duration
  • Geo
  • HTTP
  • Math
  • Meta
  • Parse
  • Rand
  • Search
  • Session
  • Sleep
  • String
  • Time
  • Type
  • Scripting
  • Vector

Row

  • RowSql的支持
  • row_sql!宏

Operators

Operator Description Finish
&& or AND Checks whether both of two values are truthy
|| or OR Checks whether either of two values is truthy
?? Check whether either of two values are truthy and not NULL
?: Check whether either of two values are truthy
= or IS Check whether two values are equal
!= or IS NOT Check whether two values are not equal
== Check whether two values are exactly equal
?= Check whether any value in a set is equal to a value
*= Check whether all values in a set are equal to a value
~ Compare two values for equality using fuzzy matching
!~ Compare two values for inequality using fuzzy matching
?~ Check whether any value in a set is equal to a value using fuzzy matching
*~ Check whether all values in a set are equal to a value using fuzzy matching
< Check whether a value is less than another value
<= Check whether a value is less than or equal to another value
> Check whether a value is greater than another value
>= Check whether a value is greater than or equal to another value
+ Add two values together
- Subtract a value from another value
* or × Multiply two values together
/ or ÷ Divide a value by another value
** Raises a base value by another value
IN Checks whether a value is contained within another value
NOT IN Checks whether a value is not contained within another value
CONTAINS Checks whether a value contains another value
CONTAINSNOT Checks whether a value does not contain another value
CONTAINSALL Checks whether a value contains all other values
CONTAINSANY Checks whether a value contains any other value
CONTAINSNONE Checks whether a value contains none of the following values
INSIDE Checks whether a value is contained within another value
NOTINSIDE Checks whether a value is not contained within another value
ALLINSIDE Checks whether all values are contained within other values
ANYINSIDE Checks whether any value is contained within other values
NONEINSIDE Checks whether no value is contained within other values
OUTSIDE Checks whether a geometry type is outside of another geometry type
INTERSECTS Checks whether a geometry type intersects another geometry type
@@ Checks whether the terms are found in a full-text indexed field

Update Des

  • 0.3.1:

    • 重构Define语句且补全DEFINE ANALYSIS (Refactoring the Define statement and completing DEFINE ANALYSIS)
    • 支持Return语句 (Support for Return statements)
    • 支持Kill语句 (Support for Kill statements)
    • 支持Throw语句 (Support for Throw statements)
    • 支持所有SurrealDB的Operators,见CriteriaSign (Supports all SurrealDB Operators ,see CriteriaSign)
  • 0.3.0:

    • 重构init Service 和 config Service(Refactoring init service and config service)
    • 优化SurrealValue(Optimize SurrealValue)
    • 优化Field(Optimize Field)
    • 增加With(Add With)
    • 增加ShowWrapper(Add ShowWrapper)
    • 优化SurrealDB 0.1.0版本更新的基础语句语法(Optimize the basic statement syntax for SurrealDB version 0.1.0 update)
  • 0.2.2:

    • 添加SelectWrapper向LiveSelectWrapper的转变 (Add the transition from SelectWrapper to LiveSelectWrapper)
    • 添加Field::Diff,针对LiveSelect语句的构建 (Add Field:: Diff to build the LiveSelect statement)
    • 添加SurrealValue对Geometries的支持,GeoJSON (Add SurrealValue support for Geometrics, GeoJSON)
    • 添加所有内置方法Function(突然有些困惑,延迟至下个版本) (Add all built-in method functions (suddenly confused, delayed to the next version))
    • 补充ValueTyped类型Geometries,Decimal,Option (Supplementing ValueTyped Types Geometry, Decimal, Option)
    • 添加ValueConstructor的new_infer()用于通过默认值推测值类型 (Add ValueConstructor::new_Infer() is used to infer the value type from the default value)
  • 0.2.1:

    • 添加SurrealDB内置方法Function (Add SurrealDB built-in method Function)
      • Function::array
      • Function::count
      • Function::crypto
    • 修复 RELATE 语句构造错误的问题,感谢timlagrande <notifications@github.com> (Fix the issue of incorrect construction of the RELATE statement. Thank timlagrande <notifications@github.com>)
    • SELECT语句Column构建添加AS关键字功能 (SELECT statement Column construction adds ASkeyword )
    • SurrealDB内置加密功能,见surrealism::functions::{GenerateCompare, CryptoFunc} (SurrealDB built-in encryption function,See surrealism::functions::{GenerateCompare, CryptoFunc})
  • 0.2.0:

    • 重构了各类Wrapper,使用简单统一的构造器+工厂模式(Reconstructed various Wrappers using a simple and unified constructor+factory pattern)

    • 增加row sql进行语句构建(Add row SQL for statement construction)

    • 启动与初始化更新,你可以基于框架提供的trait和struct自己构建初始化服务(Starting and initializing updates, you can build your own initialization services based on the traits and structs provided by the framework)

    • 增加大量构建工具(Add a large number of construction tools)

    • 分离语句构造和语句提交(Separate statement construction and statement submission)

  • 0.1.1:更新配置,增加基于Namespace和Database的支持,但是基于当前SurrealDB无法支持,所以并不能使用🥲(Update the configuration and add support based on Namespace and Database, but it cannot be used due to the current SurrealDB support 🥲)

Dependencies

~44–61MB
~1M SLoC