- SCHEMAFULL
- TABLE
- FIELD
- DEFINE
SurrealDB - define field type - try to create entry with incorrect type (int, string)
- Using the DEFINE keyword we can define a table to have schema, then we can define the column and their type.
- Then if we try to insert (CREATE) an entry that does not match the type the query will fail. We need to use check to verify success.
examples/surrealdb/define-field-type/src/main.rs
use serde::{Deserialize, Serialize}; use surrealdb::engine::local::Mem; use surrealdb::sql::Thing; use surrealdb::Surreal; #[derive(Debug, Deserialize, Serialize)] struct Entry { id: Thing, number: u32, } #[tokio::main] async fn main() -> surrealdb::Result<()> { let dbh = Surreal::new::<Mem>(()).await?; dbh.use_ns("demo").use_db("demo").await?; dbh.query("DEFINE TABLE entry SCHEMAFULL").await?; dbh.query("DEFINE FIELD number ON TABLE entry TYPE int") .await?; let res = dbh .query( "CREATE entry CONTENT { number: 42, };", ) .await?; match res.check() { Ok(val) => println!("Success: {val:?}"), Err(err) => println!("Error: {err}"), } println!("---------"); let res = dbh .query( "CREATE entry CONTENT { number: 'fortytwo', };", ) .await?; match res.check() { Ok(val) => println!("Success: {val:?}"), Err(err) => println!("Error: {err}"), } println!("---------"); let mut entries = dbh.query("SELECT * FROM entry").await?; let entries: Vec<Entry> = entries.take(0)?; for entry in entries { println!("{} {}", entry.id, entry.number); } println!("---------"); Ok(()) }
Success: Response { client: Surreal { router: OnceLock(Router { sender: Sender { .. }, last_id: 4, features: {Backup, LiveQueries} }), engine: PhantomData<surrealdb::api::engine::any::Any> }, results: {0: (Stats { execution_time: Some(639.419µs) }, Ok(Array(Array([Object(Object({"id": Thing(Thing { tb: "entry", id: String("y93feg7h3xxu6ww51spz") }), "number": Number(Int(42))}))]))))}, live_queries: {} } --------- Error: Found 'fortytwo' for field `number`, with record `entry:o31e2ou83s5buvxc55yq`, but expected a int --------- entry:y93feg7h3xxu6ww51spz 42 ---------