Datascript Handbook ยท October 2025

Build faster with Datascript

A concise guide to the Datascript language - from first variables to Mongo-powered workflows. Use the sidebar to jump to the topics you need while keeping everything fresh with the latest DSL additions.

// Quick taste
using mongo from uri database "sample" {
  use collection users;
  declare const marker = time();
  users <- { marker, createdAt: time() };
  print("Inserted", marker);
}

Language Essentials

Datascript is a typed scripting language designed for data workflows. Variables are declared with declare; constants use declare const. Assignments require an initializer for constants.

declare count = 0;
declare const greeting = "hello";
count = count + 1;

Comments use //. Statements end with semicolons, except block constructs like if, while, and func bodies.

Data Types

Primitive and structural types are supported:

  • Number — double precision (42)
  • String — double quoted ("text")
  • Boolean — true or false
  • Null — null
  • Array — [1, 2, 3]
  • Object — { key: value }
declare profile = {
  name: "Ada",
  skills: ["analysis", "automation"],
  active: true,
};

Control Flow

Datascript provides the familiar branching and looping constructs plus try/catch for exception handling.

if (count > 10) {
  print("large");
} else if (count == 10) {
  print("equal");
} else {
  print("small");
}

while (count < 5) {
  count = count + 1;
}

try {
  riskyTask();
} catch (error) {
  print("Recovering:", error);
}

Functions

Functions are defined with func. Parameters can include default values and optional type annotations.

func formatUser(name: string, email: string = "n/a") {
  return name + " <" + email + ">";
}

print(formatUser("Ada", "ada@example.com"));

Anonymous functions can be assigned to variables, and native await is available inside async-aware contexts.

Objects & Arrays

Object literals support shorthand and string keys. Arrays provide the standard iteration and indexing capabilities. Utilities like entries(), keys(), values(), and len() are available as native functions.

declare metrics = [1, 3, 5];
declare index = 0;
while (index < len(metrics)) {
  print(metrics[index]);
  index = index + 1;
}

declare config = {
  "x-api-key": "demo",
  retries: 3,
};

Classes & Schemas

Schemas extend the language with lightweight data models. Declare required and optional fields, provide defaults, and even add methods. Instances automatically gain a save() helper for inspection or persistence hooks.

schema User create(username: string, email: string) {
  required username: string;
  required email: string;
  optional roles: array = ["user"];

  describe() {
    print(username, roles);
  }
}

declare admin = User({ username: "admin", email: "admin@example.com" });
admin.describe();
admin.save();

For heavier logic, use class declarations (similar syntax) to define behaviors without schema semantics.

Modules

Organize code with import and export. Modules support namespace, named, and default exports.

// math.ds
export declare answer = 42;
export func double(x) { return x * 2; }

// consumer.ds
import "./math.ds" exposing { double };
print(double(21));

The runtime caches modules, ensuring imports are evaluated once per execution.

Async & Promises

Use await to resolve promises. Native helpers like sleep(ms) return promises for timing and scheduling.

func pingService(url: string) {
  declare response = await fetch(url);
  return await response.json();
}

await sleep(500);

Error Handling

Throw values of any type. Catch blocks can optionally bind the error to an identifier.

func ensurePositive(value: number) {
  if (value <= 0) {
    throw "Value must be positive.";
  }
  return value;
}

try {
  ensurePositive(-5);
} catch (error) {
  print("Validation failed:", error);
}

Mongo DSL

The Mongo DSL adds ergonomic syntax for connections, collection defaults, CRUD operators, query pipelines, and session scopes.

Scoped Connections

using mongo from mongoUri database "analytics" as db with {
  collections: {
    users: {
      projection: { email: 1, createdAt: 1 },
      sort: { createdAt: -1 },
      limit: 25,
    },
  },
} {
  use collection users;
  users <- { email: "demo@example.com" };
}

Operators & Queries

  • <- insert
  • ? find one, ?? find many
  • ! delete one, !! delete many
  • |> aggregate pipeline
  • update where ... set ... updates
declare marker = "demo-" + toString(time());
users <- {
  email: marker + "@example.com",
  createdAt: time(),
};

declare fetched = (users ? query { email == marker + "@example.com" }).value;
users update where query { email == fetched.email } set {
  "$set": { lastSeenAt: time() },
};

Aggregation Helpers

declare summary = (activity_logs |> [
  match(eq("email", marker + "@example.com")),
  sort({ at: -1 }),
  limit(5),
  project({ email: 1, at: 1 }),
]).value;

Schemas in Mongo Workflows

schema DemoUser create(name: string, email: string) {
  required name: string;
  required email: string;
  optional tier: string = "free";
}

declare userDoc = DemoUser({
  name: "Schema Example",
  email: "schema@example.com",
  tier: "gold",
});

users <- {
  email: userDoc.email,
  name: userDoc.name,
  tier: userDoc.tier,
  createdAt: time(),
};

CLI & Tooling

Run Datascript files via deno run main.ts path/to/script.ds. Helpful native utilities:

  • print(), debug(), info() — logging
  • assert(condition, message) — runtime checks
  • time(), sleep(ms), schedule() — timing
  • clone(), deepClone() — data helpers
  • env(key) — environment variables

For linting and type checks, run deno lint and deno check at the repository root.

Reference & Files

Frontend

  • frontend/lexer.ts — tokenization
  • frontend/parser.ts — AST builder
  • frontend/ast.ts — node definitions

Runtime

  • runtime/interpreter.ts — dispatch
  • runtime/eval/expressions.ts
  • runtime/eval/statements.ts
  • runtime/mongo.ts & mongoState.ts
  • runtime/functions.ts — native APIs

Samples

  • scripts/mongo_test.ds
  • scripts/schemas.ds
  • scripts/diagnostics.ds
  • scripts/all.ds