Skip to main content

Crate surrealdb_types

Crate surrealdb_types 

Source
Expand description

§SurrealDB Types

This crate provides the shared public value type system for SurrealDB. It serves as a foundational layer that defines all the data types that can be stored and manipulated in SurrealDB.

§Purpose

The surrealdb-types crate acts as a shared public value type system that:

  • Provides type safety: Offers strongly-typed representations of all SurrealDB data types
  • Enables serialization: Supports serialization/deserialization of values
  • Facilitates type conversion: Provides traits and methods for converting between Rust types and SurrealDB values

§Core Types

§Value Types

The main Value enum represents all possible data types in SurrealDB:

use surrealdb_types::{Array, Datetime, Number, Object, Value};
use std::collections::BTreeMap;

// Basic types
let bool_val = Value::Bool(true);
let string_val = Value::String("hello".to_string());
let number_val = Value::Number(Number::Int(42));

// Complex types
let array_val = Value::Array(Array::from(vec![Value::String("item".to_string())]));
let object_val = Value::Object(Object::new());
let datetime_val = Value::Datetime(Datetime::now());

§Type System

The Kind enum represents the type system used for schema validation and type checking:

use surrealdb_types::Kind;

// Basic kinds
let string_kind = Kind::String;
let number_kind = Kind::Number;
let array_kind = Kind::Array(Box::new(Kind::String), Some(10)); // Array of strings, max 10 items

§Key Features

§Type Conversion

The SurrealValue trait provides type-safe conversion between Rust types and SurrealDB values:

use surrealdb_types::{SurrealValue, Value};

// Convert from Rust type to SurrealDB value
let value: Value = "hello".to_string().into_value();

// Check if a value is of a specific type
if value.is::<String>() {
    println!("Value is a string");
}

// Convert from SurrealDB value to Rust type
let string = value.into_t::<String>().unwrap();
println!("Extracted string: {}", string);

§Geometric Types

Support for spatial data types using the geo crate:

use surrealdb_types::{Geometry, Value};
use geo::Point;

let point = Point::new(1.0, 2.0);
let geometry_val = Value::Geometry(Geometry::Point(point));

§Record Identifiers

Type-safe representation of SurrealDB record identifiers:

use surrealdb_types::{RecordId, RecordIdKey, Value};

let record_id = RecordId {
    table: "person".into(),
    key: RecordIdKey::String("john".to_string()),
};
let record_val = Value::RecordId(record_id);

§Usage

§Basic Usage

use surrealdb_types::{Value, Number, Array, Object};
use std::collections::BTreeMap;

// Create values
let values = vec![
    Value::Bool(true),
    Value::Number(Number::Int(42)),
    Value::String("hello".to_string()),
    Value::Array(Array::from(vec![Value::String("item".to_string())])),
];

// Work with objects
let mut map = BTreeMap::new();
map.insert("key".to_string(), Value::String("value".to_string()));
let object = Value::Object(Object::from(map));

§Macros for object & array values

This library provides two macros to easily create object and array values. All values you pass to the macro must implement the SurrealValue trait.

use surrealdb_types::{object, array};

let values = array![
    true,
    42,
    "hello".to_string(),
    array!["item1".to_string()],
];

let map = object! {
    key: "value".to_string(),
};

§Deriving the SurrealValue trait

§Requirements
  • All fields must implement the SurrealValue trait
use surrealdb_types::SurrealValue;

#[derive(SurrealValue)]
struct Person {
    name: String,
    age: i64,
}

let person = Person {
    name: "John".to_string(),
    age: 30,
};

let value = person.into_value();
let person2 = Person::from_value(value).unwrap();

assert_eq!(person2.name, "John");
assert_eq!(person2.age, 30);

§Type Checking

use surrealdb_types::{Value, SurrealValue};

fn process_value(value: &Value) {
    match value {
        Value::String(s) => println!("String: {}", s),
        Value::Number(n) => println!("Number: {:?}", n),
        Value::Array(arr) => println!("Array with {} items", arr.len()),
        _ => println!("Other type"),
    }
}

§Dependencies

This crate has minimal external dependencies:

  • serde: For serialization/deserialization
  • chrono: For datetime handling
  • uuid: For UUID support
  • rust_decimal: For decimal number support
  • regex: For regular expression support
  • geo: For geometric types
  • surrealdb-types-derive: For deriving the SurrealValue trait
  • surrealdb-protocol: For the SurrealDB protocol
  • flatbuffers: For the FlatBuffers protocol
  • bytes: For the Bytes type
  • anyhow: For error handling
  • geo: For geometric types
  • regex: For regular expression support
  • rust_decimal: For decimal number support
  • uuid: For UUID support
  • rstest: For testing
  • hex: For hex encoding

§License

This crate is part of SurrealDB and follows the same licensing terms.

Modules§

array
Array value types for SurrealDB
bytes
Binary data value types for SurrealDB
datetime
Datetime value types for SurrealDB
duration
Duration value types for SurrealDB
file
File reference value types for SurrealDB
geometry
Geometric value types for SurrealDB
into_json
JSON value types for SurrealDB
number
Numeric value types for SurrealDB
object
Object value types for SurrealDB
range
Range value types for SurrealDB
record_id
Record identifier value types for SurrealDB
regex
Regular expression value types for SurrealDB
set
Set value types for SurrealDB
table
Table value types for SurrealDB
uuid
UUID value types for SurrealDB

Macros§

array
Macro for creating a SurrealDB array.
kind
A procedural macro for creating Kind values with a convenient DSL syntax.
object
Macro for creating a SurrealDB object.
set
Macro for creating a SurrealDB set.
vars
Macro for creating a SurrealDB variables struct.
write_sql
A procedural macro for writing SQL strings with automatic ToSql formatting.

Structs§

Array
Represents an array of values in SurrealDB
Bytes
Represents binary data in SurrealDB
ConversionError
Error when converting between types
Datetime
Represents a datetime value in SurrealDB
Decimal
Decimal represents a 128 bit representation of a fixed-precision decimal number. The finite set of values of type Decimal are of the form m / 10e, where m is an integer such that -296 < m < 296, and e is an integer between 0 and 28 inclusive.
Duration
Represents a duration value in SurrealDB
Error
Represents an error in SurrealDB
File
Represents a file reference in SurrealDB
HashMap
A concurrent hashmap wrapper around papaya’s HashMap.
LengthMismatchError
Error when an array or tuple has the wrong length
Notification
A live query notification.
Object
Represents an object with key-value pairs in SurrealDB
OutOfRangeError
Error when a value is out of range for the target type
Range
Represents a range of values in SurrealDB
RecordId
Represents a record identifier in SurrealDB
RecordIdKeyRange
Represents a range of record identifier keys in SurrealDB
Regex
Represents a regular expression in SurrealDB
Set
A set of unique values in SurrealDB
SurrealNone
Marker type for value conversions from Value::None
SurrealNull
Marker type for value conversions from Value::Null
Table
A value type referencing a specific table.
Uuid
Represents a UUID value in SurrealDB
Variables
Represents a set of variables that can be used in a query.

Enums§

Action
The action that caused the notification
AlreadyExistsError
Already-exists reason for [ErrorKind::AlreadyExists] errors.
AuthError
Auth failure reason for [ErrorKind::NotAllowed] errors.
ConfigurationError
Configuration failure reason for [ErrorKind::Configuration] errors.
ConnectionError
Connection failure reason for [ErrorKind::Connection] errors. Used in the SDK for client-side connection state errors.
Either2
Create an either of the given types
Either3
Create an either of the given types
Either4
Create an either of the given types
Either5
Create an either of the given types
Either6
Create an either of the given types
Either7
Create an either of the given types
Either8
Create an either of the given types
Either9
Create an either of the given types
Either10
Create an either of the given types
ErrorDetails
Typed error details. Each variant represents an error kind and optionally wraps the detail enum for that kind. This replaces the separate kind field on Error – the kind is derived from the variant.
Geometry
Represents geometric shapes in SurrealDB
GeometryKind
Represents different types of geometric shapes in SurrealDB’s type system
Kind
The kind of a SurrealDB value.
KindLiteral
Represents literal values in SurrealDB’s type system
NotAllowedError
Not-allowed reason for [ErrorKind::NotAllowed] errors.
NotFoundError
Not-found reason for [ErrorKind::NotFound] errors.
Number
Represents a numeric value in SurrealDB
QueryError
Query failure reason for [ErrorKind::Query] errors.
RecordIdKey
Represents a key component of a record identifier in SurrealDB
SerializationError
Serialisation failure reason for [ErrorKind::Serialization] errors.
SqlFormat
SQL formatting mode for pretty printing.
TypeError
Errors that can occur when working with SurrealDB types
ValidationError
Validation failure reason for [ErrorKind::Validation] errors.
Value
Represents a value in SurrealDB

Traits§

FromFlatbuffers
Trait for converting a flatbuffers builder type to a type.
Indexable
Trait for values that can be indexed
SurrealValue
Trait for converting between SurrealDB values and Rust types
ToFlatbuffers
Trait for converting a type to a flatbuffers builder type.
ToSql
Trait for types that can be converted to SQL representation.

Functions§

conversion_error
Helper function to create a conversion error
decode
Decode a flatbuffers vector to a public value.
decode_kind
Decode a flatbuffers vector to a public kind.
encode
Encode a value to a flatbuffers vector.
encode_kind
Encode a kind to a flatbuffers vector.
length_mismatch_error
Helper function to create a length mismatch error
out_of_range_error
Helper function to create an out of range error
union_conversion_error
Helper function to create a conversion error for union types (Either) where the value doesn’t match any of the possible types

Derive Macros§

SurrealValue
Derives the SurrealValue trait for a struct or enum.