Getting Started

This page stores, reads and queries entities with MLambda.Data from an Aleph program, then runs the database as a service.

1. Install

You need the Aleph compiler (aleph, from MLambda.Aleph’s installers). Add MLambda.Data to your project’s aleph.toml:

[dependencies]
mlambda-data = { path = "../MLambda.Data/MLambda.Data" }

2. Define your entity

An entity is a type and an instance of Entity: how it maps to a table, how it becomes columns and back, and its key.

import Prelude
import Data.Maybe
import Data.List as L
import Data.Bytes as B
import Format.Columns
import Table.Schema
import Table.Builder
import Orm.Entity

data User = User { userId :: String, name :: String, email :: Maybe String, age :: Int }

instance Entity User where
  mapping = mappedTo "app"
    (btreeIndex "ix_age" ["age"]
      (partitionKey ["id"]
        (column "age" Int64Type
          (nullableColumn "email" TextType
            (column "name" TextType
              (column "id" TextType (tableBuilder "users")))))))
  toColumns u = Columns (withEmail u.email [fieldOf "id" u.userId, fieldOf "name" u.name, fieldOf "age" u.age])
  fromColumns cs = case fieldValue "id" cs of
    Nothing -> Nothing
    Just i -> case fieldValue "name" cs of
      Nothing -> Nothing
      Just n -> case fieldValue "age" cs of
        Nothing -> Nothing
        Just a -> Just (User i n (fieldValue "email" cs) a)
  keyOf u = B.bytesFromString u.userId

withEmail :: Maybe String -> [Column] -> [Column]
withEmail e cs = case e of
  Just v  -> L.append cs [fieldOf "email" v]
  Nothing -> cs
  • mappedTo "app" builder: the database, and the table the builder describes.
  • tableBuilder "users" with column, nullableColumn, partitionKey, clusteringKey, indexes and replicas. The mapping is checked when a repository opens; a key or index on a missing column is refused.
  • fieldOf name value and fieldValue name columns convert values through ColumnValue: an Int is an Int64, a String its UTF-8, a Bool one byte.

3. Start an engine

The engine is an actor that keeps each table’s store under a data root:

import System.Fs as Fs
import Actor.Class
import Actor.System as Sys
import Engine.DataEngine

engineAt :: ActorSystem -> String -> Address DataEngine
engineAt system root = case Fs.makeDir root of
  _ -> actorOf system (parameters [("root", root)])

Without a root parameter the engine uses MLAMBDA_DATA_PATH, else the current folder.

4. CRUD operations

import Orm.Repository

case openRepository (engineAt (Sys.actorSystem ()) "data") of
  Left fault  -> ...                                                         -- the mapping did not build
  Right users ->
    case save users (User "u-1" "Alice" (Just "[email protected]") 30) of   -- insert
      _ -> case save users (User "u-1" "Alice Smith" (Just "[email protected]") 31) of   -- update: same key
        _ -> case find users (B.bytesFromString "u-1") of                    -- Right (Just (User ... "Alice Smith" ... 31))
          _ -> remove users (B.bytesFromString "u-1")                        -- then find answers Right Nothing

save writes the whole row under its key (a second save replaces it). Every call answers Either Fault _: a write the table’s constraints refuse, a missing table or a storage failure is a Left.

5. Queries with specifications

A specification says which rows a query wants:

import Engine.Query
import Orm.Spec

olderThan :: Int -> Spec
olderThan n = Where (Filter "age" OpGt (toValue n))

namedLike :: String -> Spec
namedLike prefix = Where (Filter "name" OpPrefix (B.bytesFromString prefix))

select users (selecting (olderThan 30))                                       -- Dave, Eve
select users (selecting (Both (olderThan 20) (Negated (namedLike "D"))))       -- Carol, Eve
select users (withPage 1 2 (orderedBy "age" True (selecting Everything)))      -- Dave, Carol
Piece Meaning
Filter column op value OpEq, OpGt, OpGte, OpLt, OpLte, OpPrefix
Where filter Rows passing the filter
Both a b, OneOf a b, Negated a And, or, not
Everything Every row
orderedBy column descending The order (True: descending)
withPage skip limit Skip rows, then at most limit (0: all)

The filters joined by Both alone go to the engine, which answers them through an index when one fits; the whole specification is then checked on each row, so OneOf and Negated hold exactly.

6. Joins

data Order = Order { orderId :: String, buyer :: String, total :: Int }
-- instance Entity Order: table "orders", columns id, user, total

joinWith orders users "user" []      -- Right [(Order "o-1" "b" 120, Dave), (Order "o-2" "c" 80, Eve)]

joinWith left right column filters matches each left row’s column with the right rows’ keys, inside the engine (the right side bucketed by key).

7. Run it as a service

The database also runs as its own process, MLambda.Data.Service, with a REST API and live channels:

cd MLambda.Data.Service
docker build -f Dockerfile -t mlambda-data ../../..        # the build context is the repositories' root
docker run --rm -p 8080:8080 -v mlambda-data:/data mlambda-data
curl http://localhost:8080/health

See Deployment for the cluster topologies and API Spec for the REST API.

Next steps

Data Admin

MLambda.Data.Admin is the administration app of a running node, a Sapphire window that talks to the node only through its API (MLambda.Data.Client). Sign in with your user and password (DATA_NODE is the address it starts with, localhost:8080 when not set); the workspaces you see are those your profile’s roles may use: Overview, Query, Schema, Backups, Cluster, Security, Activity.

cd MLambda.Data.Admin && aleph run --project "$(pwd)"     # from its folder: it reads fonts/

Its stories (MLambda.Data.Admin.Stories, in Dream) run against its testing build, which talks to a node of its own in the same process. The desk that came before it (MLambda.Data.App, which signed in by role without a password) is kept in old/.