The hierarchy is three levels and worth getting straight immediately, because almost every authentication and permission question later refers to it. A namespace contains databases; a database contains tables; a table contains records. A connection selects a namespace and a database before it can do anything useful. Users and access methods can be defined at root, namespace or database level, and which level you define them at is the tenancy decision - a namespace per customer is a real isolation boundary, a table per customer is not.
A record identifier is a first-class value and this is the idea the whole engine is built on. An identifier is table:key - user:ashton, task:01HQ3M, project:atlas. It is not a string that happens to look like a reference; it is a typed value the engine understands. Two consequences follow, and they are what makes SurrealQL feel different from SQL.
A field holding a record identifier is a link you traverse with a dot. task:01HQ3M.assignee.email fetches the task, follows the link to the user and reads the email. No join, no $lookup, no explicit dereference. You can chain it, and you can traverse through arrays of links with .*. This is the most pleasant thing about the engine and it removes a large amount of the plumbing that document databases make you write.
And you can choose your identifiers, which is a modelling tool rather than a convenience. A deterministic identifier - membership:[$user, $project] built from a composite - gives you idempotent upserts for free, because the second write to the same identifier updates the same record. Use that deliberately: it is the cleanest way to make an ingestion path safe to retry, and it is the same property the time-series courses relied on for replay.
SurrealQL is SQL-shaped and then diverges usefully. SELECT ... FROM ... WHERE works as you expect. Beyond that: SELECT can project nested paths and traverse links; CREATE, UPDATE, UPSERT and DELETE operate on tables or on specific records; CONTENT replaces a record while MERGE and PATCH modify it; arrays and objects are native rather than encoded; and FETCH dereferences links in the result so the client gets whole objects rather than identifiers. The one that catches people is UPDATE with CONTENT, which replaces the record entirely - exactly the trap $set against a whole document is in MongoDB, with a different name.
The storage backend decision comes before everything else and determines what kind of system you have. The practical options: in-memory, which loses everything on restart and is for tests only; a local embedded file store - RocksDB or SurrealDB's own SurrealKV - which gives you a durable single node, the right default for learning and for a great many real deployments; and a distributed key-value store underneath, which is what gives you a cluster, with that store's own operational burden and expertise requirement. Choose knowing that this determines your durability, your backup method, whether you have a cluster, and what a node failure means - and that it is not a setting you flip later.
The limits to know now. Verify each of these against your version rather than taking them from here, which is itself the lesson: the query planner's sophistication is well short of a mature relational optimiser, so you cannot rely on it to rescue a bad query; EXPLAIN exists and its coverage is partial; transaction isolation and conflict behaviour depend on the backend and version, so test the semantics you depend on; unbounded graph traversal has no cost-based brake, so your limits are your protection; and permissions are evaluated per record, which means a permission clause containing a subquery is a per-row cost on every query that touches the table.
Laboratory exercise 1 - provision, model and write down what is true.
Stand up SurrealDB in Docker with the file-backed store, and record the exact version. Create a namespace and database, and a root user. Then stand up a second instance in memory and keep it for the durability demonstration below.
Write the project tracker dataset generator that the rest of the course depends on: organisations, users, projects, tasks with parent and child links, comments, attachments and an activity stream, at a configurable scale with realistic graph density, and able to drive concurrent mutations on demand. Everything later needs that last capability.
Load at least 5 million records and verify reads and writes.
Then build the version behaviour log, which is this course's running artefact. Write a small test for each of these and record the result with your version number: does UPDATE ... CONTENT replace or merge; does a failed statement inside a transaction roll back the whole transaction; what does a duplicate write to an existing record identifier do; does EXPLAIN report index use for a simple equality filter; what happens on an unbounded traversal over your densest edge. Those five answers, dated and versioned, are worth more than any amount of reading.
Demonstrate the backend difference: write records to both instances, restart both, and show the in-memory one empty. Trivial, and it makes the decision concrete.
Deliverable: the Docker setup with the version recorded, the generator as reusable code, the loaded dataset, the five-entry version behaviour log, the durability demonstration, and a stated backend choice with what it commits you to.
-- ==================================================================
-- THE HIERARCHY. Three levels, and almost every auth and permission
-- question later refers to them.
-- ==================================================================
-- NAMESPACE -> DATABASE -> TABLE -> RECORD
DEFINE NAMESPACE acme;
USE NS acme;
DEFINE DATABASE tracker;
USE NS acme DB tracker;
--
-- *** WHICH LEVEL YOU DEFINE USERS AND ACCESS AT IS THE TENANCY
-- *** DECISION: a NAMESPACE PER CUSTOMER IS A REAL ISOLATION
-- *** BOUNDARY; A TABLE PER CUSTOMER IS NOT. *** Decide in Module 6,
-- but notice it now.
-- surreal start --user root --pass root \
-- surrealkv://data/tracker.db # DURABLE single node
-- surreal start memory # *** TESTS ONLY ***
-- ==================================================================
-- *** A RECORD IDENTIFIER IS A FIRST-CLASS VALUE. The idea the whole
-- *** engine is built on. ***
-- ==================================================================
-- table:key -> user:ashton task:01HQ3M project:atlas
-- NOT a string that looks like a reference - a TYPED VALUE THE
-- ENGINE UNDERSTANDS.
CREATE user:ashton CONTENT {
name: "Ashton Reyes",
email: "ashton@example.com",
role: "maintainer",
joined: time::now()
};
CREATE project:atlas CONTENT {
name: "Atlas", key: "ATL", status: "active",
lead: user:ashton -- *** A LINK, not a string ***
};
CREATE task:01HQ3M CONTENT {
title: "Rework the ingest path",
project: project:atlas, -- a LINK
assignee: user:ashton, -- a LINK
watchers: [user:ashton, user:dana], -- an ARRAY of links
state: "in_progress", points: 5,
labels: ["ingest", "perf"] -- arrays are NATIVE
};
-- *** CONSEQUENCE 1: A LINK IS TRAVERSED WITH A DOT. NO JOIN. ***
SELECT title, assignee.name, assignee.email, project.name
FROM task:01HQ3M;
SELECT title, watchers.*.name AS watcher_names FROM task;
SELECT title, project.lead.email AS escalate_to FROM task; -- CHAINED
-- *** THIS IS THE MOST PLEASANT THING ABOUT THE ENGINE *** and it
-- removes a lot of the plumbing a document database makes you write.
--
-- FETCH dereferences links in the RESULT, so the client gets whole
-- objects rather than identifiers:
SELECT * FROM task WHERE state = "in_progress" FETCH assignee, project;
-- *** CONSEQUENCE 2: YOU CHOOSE YOUR IDENTIFIERS - a MODELLING TOOL,
-- *** not a convenience. ***
-- A DETERMINISTIC identifier gives you IDEMPOTENT UPSERTS FOR FREE:
UPSERT membership:[user:ashton, project:atlas] CONTENT {
user: user:ashton, project: project:atlas,
role: "owner", since: time::now()
};
-- -> run it twice, ONE RECORD. *** THE CLEANEST WAY TO MAKE AN
-- *** INGESTION PATH SAFE TO RETRY *** - the same property the
-- time-series courses relied on for replay. Use it DELIBERATELY.
-- ==================================================================
-- SURREALQL: SQL-shaped, then diverges usefully.
-- ==================================================================
SELECT title, points, assignee.name AS who
FROM task
WHERE project = project:atlas AND state != "done" AND points > 3
ORDER BY points DESC LIMIT 20;
SELECT state, count() AS n, math::sum(points) AS pts,
math::mean(points) AS avg_pts
FROM task WHERE project = project:atlas
GROUP BY state;
-- *** THE ONE THAT CATCHES PEOPLE: ***
UPDATE task:01HQ3M CONTENT { state: "done" };
-- -> *** REPLACES THE RECORD ENTIRELY. title, project, assignee,
-- watchers, points, labels: ALL GONE. *** Exactly the trap a
-- whole-document $set is in MongoDB, with a different name.
UPDATE task:01HQ3M MERGE { state: "done", closed: time::now() }; -- merges
UPDATE task:01HQ3M SET state = "done"; -- one field
UPDATE task:01HQ3M PATCH [{ op: "replace", path: "/state",
value: "done" }]; -- JSON Patch
-- *** PUT THIS IN YOUR VERSION BEHAVIOUR LOG. *** It is the first
-- entry for a reason.
-- ==================================================================
-- *** THE STORAGE BACKEND DECISION COMES BEFORE EVERYTHING ELSE AND
-- *** DETERMINES WHAT KIND OF SYSTEM YOU HAVE. ***
-- ==================================================================
-- IN-MEMORY loses everything on restart. *** TESTS
-- ONLY. *** Demonstrate it once.
-- *** LOCAL EMBEDDED FILE STORE *** (SurrealKV / RocksDB)
-- a DURABLE SINGLE NODE. The right default
-- for learning and for a great many real
-- deployments. Backup = EXPORT + FILESYSTEM
-- SNAPSHOT.
-- DISTRIBUTED KV UNDERNEATH
-- what gives you a CLUSTER - with THAT
-- STORE'S OWN operational burden and
-- expertise requirement, which is not small.
--
-- *** IT DETERMINES YOUR DURABILITY, YOUR BACKUP METHOD, WHETHER YOU
-- *** HAVE A CLUSTER, AND WHAT A NODE FAILURE MEANS. IT IS NOT A
-- *** SETTING YOU FLIP LATER. ***
INFO FOR ROOT;
INFO FOR NS;
INFO FOR DB; -- tables, indexes, functions, events, access
-- ==================================================================
-- *** THE LIMITS - AND VERIFY EACH AGAINST YOUR VERSION RATHER THAN
-- *** TAKING IT FROM HERE. That instruction IS the lesson. ***
-- ==================================================================
-- * the QUERY PLANNER is well short of a mature relational
-- optimiser, so *** YOU CANNOT RELY ON IT TO RESCUE A BAD
-- QUERY. *** Your indexes and your query shape are the plan.
-- * EXPLAIN exists and its *** COVERAGE IS PARTIAL. ***
-- * TRANSACTION ISOLATION AND CONFLICT BEHAVIOUR DEPEND ON THE
-- BACKEND AND VERSION. *** TEST THE SEMANTICS YOU DEPEND ON. ***
-- * UNBOUNDED GRAPH TRAVERSAL HAS NO COST-BASED BRAKE. *** YOUR
-- LIMITS ARE YOUR PROTECTION. ***
-- * *** PERMISSIONS ARE EVALUATED PER RECORD ***, so a permission
-- clause containing a SUBQUERY is a PER-ROW COST on every query
-- that touches the table (Module 3).
-- * SurrealQL is its OWN LANGUAGE: no PostgreSQL wire protocol, no
-- existing SQL tooling, no ORM you already use. Budget for it.
-- ==================================================================
-- *** THE VERSION BEHAVIOUR LOG - this course's running artefact.
-- *** Five tests, dated, with your version number. ***
-- ==================================================================
-- version tested: _______ date: _______
--
-- 1. UPDATE ... CONTENT: replaces or merges? ______
-- 2. a failed statement inside BEGIN ... COMMIT:
-- does the WHOLE transaction roll back? ______
-- 3. CREATE on an EXISTING record identifier: error,
-- overwrite, or merge? ______
-- 4. does EXPLAIN report index use for a simple
-- equality filter? ______
-- 5. an UNBOUNDED traversal over your densest edge:
-- what happens, and how long? ______
--
-- *** THOSE FIVE ANSWERS, DATED AND VERSIONED, ARE WORTH MORE THAN
-- *** ANY AMOUNT OF READING *** - and they are the start of the test
-- suite that makes your eventual upgrade survivable.
Discussion
No questions on this topic yet. Sign in to ask the first one.