From 9acfa0ffa35d39da2f5c38221bcba4450e6d33b0 Mon Sep 17 00:00:00 2001 From: Steven McCanne Date: Sat, 21 Nov 2026 06:58:10 -0800 Subject: [PATCH 1/4] Document SuperSQL statements and bring back the Database section. New Statements pages under SuperSQL: scripts and status records, CREATE TABLE, CREATE SUPER TABLE, DROP TABLE, and INSERT, with tested examples. Show the Database section again, with the intro rewritten for current behavior, an API reference updated from a live server (adds create branch, compact, vacate, stats, describe, compile, events), and format docs updated (UUIDv7 IDs, snapshots). super db docs: add create -type and links to the statements. The /compile docs depend on #, so merge that first. --- book/src/SUMMARY.md | 11 +- book/src/command/db.md | 40 +- book/src/database/api.md | 489 +++++++++++++---- book/src/database/format.md | 67 ++- book/src/database/intro.md | 513 ++++++------------ book/src/super-sql/queries.md | 3 + .../statements/create-super-table.md | 120 ++++ book/src/super-sql/statements/create-table.md | 130 +++++ book/src/super-sql/statements/drop-table.md | 44 ++ book/src/super-sql/statements/insert.md | 116 ++++ book/src/super-sql/statements/intro.md | 119 ++++ 11 files changed, 1155 insertions(+), 497 deletions(-) create mode 100644 book/src/super-sql/statements/create-super-table.md create mode 100644 book/src/super-sql/statements/create-table.md create mode 100644 book/src/super-sql/statements/drop-table.md create mode 100644 book/src/super-sql/statements/insert.md create mode 100644 book/src/super-sql/statements/intro.md diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index ef5d49282..8cb3d7226 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -18,6 +18,11 @@ - [Formats](command/formats.md) - [SuperSQL](super-sql/intro.md) - [Queries](super-sql/queries.md) + - [Statements](super-sql/statements/intro.md) + - [CREATE TABLE](super-sql/statements/create-table.md) + - [CREATE SUPER TABLE](super-sql/statements/create-super-table.md) + - [DROP TABLE](super-sql/statements/drop-table.md) + - [INSERT](super-sql/statements/insert.md) - [Declarations](super-sql/declarations/intro.md) - [Constants](super-sql/declarations/constants.md) - [Types](super-sql/declarations/types.md) @@ -212,9 +217,9 @@ - [Data Model](formats/model.md) - [Super (SUP)](formats/sup.md) - [Super Binary (BSUP)](formats/bsup.md) -!!- [Database](database/intro.md) -!! - [API](database/api.md) -!! - [Format](database/format.md) +- [Database](database/intro.md) + - [API](database/api.md) + - [Format](database/format.md) - [Developer](dev/intro.md) - [Libraries](dev/libraries/intro.md) - [Go](dev/libraries/go.md) diff --git a/book/src/command/db.md b/book/src/command/db.md index 8f721d722..f74506f92 100644 --- a/book/src/command/db.md +++ b/book/src/command/db.md @@ -3,10 +3,9 @@ `super db` is a sub-command of [super](super.md) to manage and query SuperDB databases. >[!NOTE] -> The database portion of SuperDB is early in development. While previous versions -> have been deployed in production at non-trivial scale, the current version -> is somewhat out of date with recent changes to the runtime. This will be remedied -> in forthcoming releases. +> The database portion of SuperDB is earlier in development than `super` +> and its formats. See the [Database](../database/intro.md) section for +> an overview of how a database works. The `super db` command is invoked either by itself to run a query: ``` @@ -139,6 +138,11 @@ If a table is provided to `from` without a branch name, then branch Output is sent to a [file or stdout](output.md). +The query text may also be a [script](../super-sql/statements/intro.md) +of statements separated by semicolons, including commands like +[CREATE TABLE](../super-sql/statements/create-table.md) and +[INSERT](../super-sql/statements/insert.md) that modify the database. + If the single argument `-` follows the query, then the lines of standard input are assembled into a string array called `args` as a [constant](../super-sql/declarations/constants.md) @@ -330,11 +334,12 @@ creates a commit on HEAD replacing the old objects with the new ones. ### super db create ``` -super db create [-orderby key[,key...][:asc|:desc]] +super db create [-orderby key[,key...][:asc|:desc]] [-type type] ``` * `-framecap n` target number of values in each BSUP frame of a data object (default 20000) * `-objectcap n` target number of values in each data object (default 1048576) * `-orderby key` sort key with optional :asc or :desc suffix to organize data in the table (cannot be changed) +* `-type type` [SUP](../formats/sup.md) type to which all values loaded into the table are cast (cannot be changed) * `-use` select created table as the current working table (default "false") * [Global](options.md#global) * [Database](options.md#database) @@ -348,6 +353,17 @@ the data in the table, which may be in ascending or descending order. If a sort key is not specified, the table is unsorted. +The `-type` option gives the table a type, e.g., `-type '{a:int64,b:string}'`, +to which every value loaded into the table is cast, as with +[CREATE SUPER TABLE](../super-sql/statements/create-super-table.md). +A value that can't be cast fails the load. Without `-type`, a table +holds values of any type. + +Tables may also be created with the +[CREATE TABLE](../super-sql/statements/create-table.md) and +[CREATE SUPER TABLE](../super-sql/statements/create-super-table.md) +statements. + The `-objectcap` option sets the target number of values in each of the table's data objects, which [manage](#super-db-manage) uses when compacting the table. @@ -409,7 +425,8 @@ super db drop [options] | * [Database](options.md#database) * [Output](options.md#output) -The `drop` command deletes a table and all of its constituent data. +The `drop` command deletes a table and all of its constituent data, +as does the [DROP TABLE](../super-sql/statements/drop-table.md) statement. **DANGER ZONE.** You must confirm that you want to delete the table to proceed. The `-f` option can be used to force the deletion @@ -448,10 +465,13 @@ The `load` command commits new data to a branch of a table. Run `super db load -h` for a list of command-line options. -Note that there is no need to define a schema or insert data into -a "table" as all super-structured data is _self describing_ and can be queried in a -schema-agnostic fashion. Data of any _shape_ can be stored in any table -and arbitrary data _shapes_ can coexist side by side. +Note that there is no need to define a schema before loading data +as all super-structured data is _self describing_ and can be queried in a +schema-agnostic fashion. Data of any _shape_ can be stored in a table +without a type and arbitrary data _shapes_ can coexist side by side. +If the table has a [type](../database/intro.md#tables), each value is +cast to it, and if any value can't be cast, the load fails and nothing +is committed. As with [super](super.md), the [input arguments](super.md#options) can be in diff --git a/book/src/database/api.md b/book/src/database/api.md index 44949ed0a..25d906318 100644 --- a/book/src/database/api.md +++ b/book/src/database/api.md @@ -1,18 +1,27 @@ # SuperDB API -## Status +A database service started with [`super db serve`](../command/db.md#super-db-serve) +exposes the database over HTTP with the API described here. +The [`super db`](../command/db.md) command uses this API when it is +[attached](intro.md#accessing-a-database) to a service URL. >[!NOTE] -> This is a brief sketch of the functionality exposed in the -> SuperDB API. More detailed documentation of the API will be forthcoming. +> The API may change between releases while the database matures. + +The examples below use [curl](https://curl.se/) with a service +listening on its default port, 9867, e.g., as started by +``` +super db init mydb +super db serve mydb +``` ## Endpoints ### Tables -#### Create table +#### Create Table -Create a new database table. +Create a new table. ``` POST /table @@ -23,8 +32,10 @@ POST /table | Name | Type | In | Description | | ---- | ---- | -- | ----------- | | name | string | body | **Required.** Name of the table. Must be unique. | -| layout.order | string | body | Order of storage by sort key(s) in table. Possible values: desc, asc. Default: asc. | -| layout.keys | [[string]] | body | Sort key(s) of table. The element of each inner string array should reflect the hierarchical ordering of named fields within indexed records. Default: [[ts]]. | +| sort_keys | [{order:string,path:[string]}] | body | Sort key of the table, where `order` is `asc` or `desc` and `path` is a field path, e.g., `["ts"]` or `["product","serial_number"]`. Default: unsorted. | +| type | string | body | A [type value](../super-sql/types/type.md) in [SUP](../formats/sup.md) format, e.g., `"<{a:int64}>"`, to which all values loaded into the table are cast as with [CREATE SUPER TABLE](../super-sql/statements/create-super-table.md). Default: no type. | +| object_cap | number | body | Target number of values in each data object. Default: 1048576. | +| frame_cap | number | body | Target number of values in each BSUP frame of a data object. Default: 20000. | | Content-Type | string | header | [MIME type](#mime-types) of the request payload. | | Accept | string | header | Preferred [MIME type](#mime-types) of the response. | @@ -34,41 +45,27 @@ POST /table curl -X POST \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ - -d '{"name": "inventory", "layout": {"keys": [["product","serial_number"]]}}' \ + -d '{"name": "inventory", "sort_keys": [{"order": "asc", "path": ["product"]}]}' \ http://localhost:9867/table ``` **Example Response** ``` -{ - "table": { - "ts": "2022-07-13T21:23:05.323016Z", - "name": "inventory", - "id": "0x0f5ce9b9b6202f3883c9db8ff58d8721a075d1e4", - "layout": { - "order": "asc", - "keys": [ - [ - "product", - "serial_number" - ] - ] - }, - "seek_stride": 65536, - "threshold": 524288000 - }, - "branch": { - "ts": "2022-07-13T21:23:05.367365Z", - "name": "main", - "commit": "0x0000000000000000000000000000000000000000" - } -} +{"table":{"ts":"2026-11-21T14:28:00.818576616Z","name":"inventory","id":"01a1fe81-c8b2-793a-aab3-383076bc5d23","sortkeys":[{"order":"asc","path":["product"]}],"objectcap":1048576,"framecap":20000,"type":"0x","sql":false},"branch":{"ts":"2026-11-21T14:28:00.818741489Z","name":"main","commit":"00000000-0000-0000-0000-000000000000"}} ``` +In the response, `type` is the binary encoding of the table's type, which is +empty for a table without a type, and `sql` is true for a table created +by [CREATE TABLE](../super-sql/statements/create-table.md) with columns. + +Tables may also be created with a [CREATE TABLE](../super-sql/statements/create-table.md) +or [CREATE SUPER TABLE](../super-sql/statements/create-super-table.md) +statement sent to the [query](#query) endpoint. + --- -#### Rename table +#### Rename Table Change a table's name. @@ -80,8 +77,8 @@ PUT /table/{table} | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| table | string | path | **Required.** ID or name of the requested table. | -| name | string | body | **Required.** The desired new name of the table. Must be unique. | +| table | string | path | **Required.** ID or name of the table. | +| name | string | body | **Required.** The new name of the table. Must be unique. | | Content-Type | string | header | [MIME type](#mime-types) of the request payload. | **Example Request** @@ -90,16 +87,16 @@ PUT /table/{table} curl -X PUT \ -H 'Content-Type: application/json' \ -d '{"name": "catalog"}' \ - http://localhost:9867/table/inventory + http://localhost:9867/table/parts ``` On success, HTTP 204 is returned with no response payload. --- -#### Delete table +#### Delete Table -Permanently delete a table. +Permanently delete a table and all of its data. ``` DELETE /table/{table} @@ -109,23 +106,55 @@ DELETE /table/{table} | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| table | string | path | **Required.** ID or name of the requested table. | +| table | string | path | **Required.** ID or name of the table. | **Example Request** ``` curl -X DELETE \ - http://localhost:9867/table/inventory + http://localhost:9867/table/catalog ``` On success, HTTP 204 is returned with no response payload. --- -#### Vacuum table +#### Table Stats + +Get the total size in bytes of the data objects in a table's `main` branch +and, for a table sorted by a timestamp, the span of time the data covers. + +``` +GET /table/{table}/stats +``` + +**Params** + +| Name | Type | In | Description | +| ---- | ---- | -- | ----------- | +| table | string | path | **Required.** ID or name of the table. | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | + +**Example Request** + +``` +curl -X GET \ + -H 'Accept: application/json' \ + http://localhost:9867/table/inventory/stats +``` + +**Example Response** + +``` +{"size":213,"span":null} +``` + +--- + +#### Vacuum Table -Free storage space by permanently removing underlying data objects that have -previously been subject to a delete operation. +Free storage space by permanently removing data objects that are no longer +referenced by a branch, e.g., because they were deleted or compacted. ``` POST /table/{table}/revision/{revision}/vacuum @@ -135,9 +164,10 @@ POST /table/{table}/revision/{revision}/vacuum | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| table | string | path | **Required.** ID or name of the requested table. | -| revision | string | path | **Required.** The starting point for locating objects that can be vacuumed. Can be the name of a branch (whose tip would be used) or a commit ID. | -| dryrun | string | query | Set to "T" to return the list of objects that could be vacuumed, but don't actually remove them. Defaults to "F". | +| table | string | path | **Required.** ID or name of the table. | +| revision | string | path | **Required.** The starting point for locating objects that can be vacuumed. Can be the name of a branch (whose tip is used) or a commit ID. | +| dryrun | string | query | Set to "T" to return the list of objects that could be vacuumed without removing them. Defaults to "F". | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | **Example Request** @@ -150,16 +180,88 @@ curl -X POST \ **Example Response** ``` -{"object_ids":["0x10f5a24253887eaf179ee385532ee411c2ed8050","0x10f5a2410ccd08f72e5d98f6d054477173b4f13f"]} +{"object_ids":["01a1fe81-c8cb-769c-af2f-918d01841e68"]} +``` + +--- + +#### Vacate Table + +Truncate a table's commit history by removing the commits older than a +given time. See [`super db vacate`](../command/db.md#super-db-vacate). + +``` +POST /table/{table}/vacate +``` + +**Params** + +| Name | Type | In | Description | +| ---- | ---- | -- | ----------- | +| table | string | path | **Required.** ID or name of the table. | +| ts | string | query | **Required.** An RFC 3339 timestamp. Commits older than this time are removed. | +| dryrun | string | query | Set to "T" to return the list of commits that would be removed without removing them. Defaults to "F". | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | + +**Example Request** + +``` +curl -X POST \ + -H 'Accept: application/json' \ + 'http://localhost:9867/table/inventory/vacate?ts=2026-11-21T14:28:20Z&dryrun=T' +``` + +**Example Response** + +``` +{"commit_ids":["01a1fe81-f08a-7e86-99a1-8428cd2d4d78","01a1fe81-f048-7a41-95e5-0809f98ef7bc","01a1fe81-f03d-7143-9881-c32cb60a0865","01a1fe81-c8cb-7a7a-882d-c0685ab961a7"]} ``` --- ### Branches +#### Create Branch + +Create a new branch of a table that points to a commit. + +``` +POST /table/{table} +``` + +**Params** + +| Name | Type | In | Description | +| ---- | ---- | -- | ----------- | +| table | string | path | **Required.** ID or name of the table. | +| name | string | body | **Required.** Name of the new branch. | +| commit | string | body | **Required.** ID of the commit the branch points to, e.g., the commit at the tip of another branch as returned by [Get Branch](#get-branch). | +| Content-Type | string | header | [MIME type](#mime-types) of the request payload. | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | + +**Example Request** + +``` +curl -X POST \ + -H 'Accept: application/json' \ + -H 'Content-Type: application/json' \ + -d '{"name": "staging", "commit": "01a1fe81-c8cb-7a7a-882d-c0685ab961a7"}' \ + http://localhost:9867/table/inventory +``` + +**Example Response** + +``` +{"ts":"2026-11-21T14:28:10.924125921Z","name":"staging","commit":"01a1fe81-c8cb-7a7a-882d-c0685ab961a7"} +``` + +--- + #### Load Data -Add data to a table and return a reference commit ID. +Add data to a branch in a new commit and return the commit's ID. +If the table has a type, every value is cast to it, and if any value +can't be cast, the load fails and nothing is committed. ``` POST /table/{table}/branch/{branch} @@ -173,7 +275,8 @@ POST /table/{table}/branch/{branch} | branch | string | path | **Required.** Name of branch to which data will be loaded. | | | various | body | **Required.** Contents of the posted data. | | csv.delim | string | query | Exactly one character specifying the field delimiter for CSV data. Defaults to ",". | -| Content-Type | string | header | [MIME type](#mime-types) of the posted content. If undefined, the service will attempt to introspect the data and determine type automatically. | +| SuperDB-Commit | string | header | A JSON object with optional `author`, `body`, and `meta` strings describing the commit, where `meta` is a value in [SUP](../formats/sup.md) format. | +| Content-Type | string | header | [MIME type](#mime-types) of the posted content. If undefined, the service will attempt to introspect the data and determine the format automatically. | | Accept | string | header | Preferred [MIME type](#mime-types) of the response. | **Example Request** @@ -182,23 +285,24 @@ POST /table/{table}/branch/{branch} curl -X POST \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ - -d '{"product": {"serial_number": 12345, "name": "widget"}, "warehouse": "chicago"} - {"product": {"serial_number": 12345, "name": "widget"}, "warehouse": "miami"} - {"product": {"serial_number": 12346, "name": "gadget"}, "warehouse": "chicago"}' \ + -H 'SuperDB-Commit: {"author": "alice", "body": "initial inventory"}' \ + -d '{"product": "widget", "warehouse": "chicago"} + {"product": "gadget", "warehouse": "miami"} + {"product": "widget", "warehouse": "miami"}' \ http://localhost:9867/table/inventory/branch/main ``` **Example Response** ``` -{"commit":"0x0ed4f42da5763a9500ee71bc3fa5c69f306872de","warnings":[]} +{"commit":"01a1fe81-c8cb-7a7a-882d-c0685ab961a7","warnings":[]} ``` --- #### Get Branch -Get information about a branch. +Get the ID of the commit at the tip of a branch. ``` GET /table/{table}/branch/{branch} @@ -223,7 +327,7 @@ curl -X GET \ **Example Response** ``` -{"commit":"0x0ed4fa21616ecd8fec9d6fd395ad876db98a5dae","warnings":null} +{"commit":"01a1fe81-c8cb-7a7a-882d-c0685ab961a7","warnings":[]} ``` --- @@ -256,15 +360,14 @@ On success, HTTP 204 is returned with no response payload. #### Delete Data -Create a commit that reflects the deletion of some data in the branch. The data -to delete can be specified via a list of object IDs or -as a filter expression (see [limitations](../command/db.md#super-db-delete)). +Create a commit that deletes data from a branch. The data +to delete is given as either a list of data object IDs or +a filter expression (see [limitations](../command/db.md#super-db-delete)). -This simply removes the data from the branch without actually removing the -underlying data objects thereby allowing [time travel](intro.md#time-travel) -to work in the face -of deletes. Permanent removal of underlying data objects is handled by a -separate [vacuum](#vacuum-table) operation. +This removes the data from the branch without removing the +underlying data objects, so that [time travel](intro.md#time-travel) +still works after a delete. Data objects are permanently removed by +a separate [vacuum](#vacuum-table) operation. ``` POST /table/{table}/branch/{branch}/delete @@ -274,10 +377,11 @@ POST /table/{table}/branch/{branch}/delete | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| table | string | path | **Required.** ID of the table. | +| table | string | path | **Required.** ID or name of the table. | | branch | string | path | **Required.** Name of branch. | -| object_ids | [string] | body | Object IDs to be deleted. | -| where | string | body | Filter expression (see [limitations](../command/db.md#super-db-delete)). | +| object_ids | [string] | body | IDs of the data objects to delete. | +| where | string | body | Filter expression selecting the values to delete (see [limitations](../command/db.md#super-db-delete)). | +| SuperDB-Commit | string | header | A JSON object describing the commit as for [Load Data](#load-data). | | Content-Type | string | header | [MIME type](#mime-types) of the request payload. | | Accept | string | header | Preferred [MIME type](#mime-types) of the response. | @@ -287,14 +391,14 @@ POST /table/{table}/branch/{branch}/delete curl -X POST \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ - -d '{"object_ids": ["274Eb1Kn8MTM6qxPyBpVTvYhLLa", "274EavbXt546VNelRLNXrzWShNh"]}' \ + -d '{"where": "product == \"gadget\""}' \ http://localhost:9867/table/inventory/branch/main/delete ``` **Example Response** ``` -{"commit":"0x0ed4fee861e8fb61568783205a46a218182eba6c","warnings":null} +{"commit":"01a1fe81-f048-7a41-95e5-0809f98ef7bc","warnings":[]} ``` **Example Request** @@ -303,22 +407,63 @@ curl -X POST \ curl -X POST \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ - -d '{"where": "product.serial_number > 12345"}' \ + -d '{"object_ids": ["01a1fe81-f033-7127-b956-9fff957f4bbe"]}' \ http://localhost:9867/table/inventory/branch/main/delete ``` **Example Response** ``` -{"commit":"0x0f5ceaeaaec7b4c33cfdece9f2e8577ad89d21e2","warnings":null} +{"commit":"01a1fe81-f08a-7e86-99a1-8428cd2d4d78","warnings":[]} +``` + +--- + +#### Compact Data + +Create a commit that replaces data objects in a branch with new objects +holding the same data, merged in sort-key order. See +[`super db compact`](../command/db.md#super-db-compact). + +``` +POST /table/{table}/branch/{branch}/compact +``` + +**Params** + +| Name | Type | In | Description | +| ---- | ---- | -- | ----------- | +| table | string | path | **Required.** ID or name of the table. | +| branch | string | path | **Required.** Name of branch. | +| object_ids | [uuid] | body | **Required.** IDs of the data objects to compact. | +| SuperDB-Commit | string | header | A JSON object describing the commit as for [Load Data](#load-data). | +| Content-Type | string | header | [MIME type](#mime-types) of the request payload. | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | + +Since `object_ids` are UUID values, this request is most easily sent +in [SUP](../formats/sup.md) format, where UUIDs are written unquoted. + +**Example Request** + +``` +curl -X POST \ + -H 'Accept: application/json' \ + -H 'Content-Type: application/x-sup' \ + -d '{object_ids:[01a1fe81-f033-7127-b956-9fff957f4bbe,01a1fe81-f048-7624-8355-7347349b095e]}' \ + http://localhost:9867/table/inventory/branch/main/compact +``` + +**Example Response** + +``` +{"commit":"01a1fe82-1260-71b6-bcfa-93d596a6cff9","warnings":[]} ``` --- #### Merge Branches -Create a commit with the difference of the child branch added to the selected -branch. +Create a commit that adds the changes in a child branch to another branch. ``` POST /table/{table}/branch/{branch}/merge/{child} @@ -328,9 +473,10 @@ POST /table/{table}/branch/{branch}/merge/{child} | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| table | string | path | **Required.** ID of the table. | -| branch | string | path | **Required.** Name of branch selected as merge destination. | -| child | string | path | **Required.** Name of child branch selected as source of merge. | +| table | string | path | **Required.** ID or name of the table. | +| branch | string | path | **Required.** Name of the branch to merge into. | +| child | string | path | **Required.** Name of the branch to merge from. | +| SuperDB-Commit | string | header | A JSON object describing the commit as for [Load Data](#load-data). | | Accept | string | header | Preferred [MIME type](#mime-types) of the response. | **Example Request** @@ -344,14 +490,14 @@ curl -X POST \ **Example Response** ``` -{"commit":"0x0ed4ffc2566b423ee444c1c8e6bf964515290f4c","warnings":null} +{"commit":"01a1fe81-f03d-7143-9881-c32cb60a0865","warnings":[]} ``` --- #### Revert -Create a revert commit of the specified commit. +Create a commit that reverses the changes made by an earlier commit. ``` POST /table/{table}/branch/{branch}/revert/{commit} @@ -361,9 +507,10 @@ POST /table/{table}/branch/{branch}/revert/{commit} | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| table | string | path | **Required.** ID of the table. | -| branch | string | path | **Required.** Name of branch on which to revert commit. | -| commit | string | path | **Required.** ID of commit to be reverted. | +| table | string | path | **Required.** ID or name of the table. | +| branch | string | path | **Required.** Name of the branch on which to revert the commit. | +| commit | string | path | **Required.** ID of the commit to revert. | +| SuperDB-Commit | string | header | A JSON object describing the commit as for [Load Data](#load-data). | | Accept | string | header | Preferred [MIME type](#mime-types) of the response. | **Example Request** @@ -371,13 +518,13 @@ POST /table/{table}/branch/{branch}/revert/{commit} ``` curl -X POST \ -H 'Accept: application/json' \ - http://localhost:9867/table/inventory/branch/main/revert/27D22ifDw3Ms2NMzo8jXpDfpgjc + http://localhost:9867/table/inventory/branch/main/revert/01a1fe81-f08a-7e86-99a1-8428cd2d4d78 ``` **Example Response** ``` -{"commit":"0x0ed500ab6f80e5ac8a1b871bddd88c57fe963ab1","warnings":null} +{"commit":"01a1fe81-f0a5-7da1-8616-e5057713b5e9","warnings":[]} ``` --- @@ -386,7 +533,8 @@ curl -X POST \ #### Query -Execute a query on a database. +Run a query or a [script](../super-sql/statements/intro.md) of statements +on the database. ``` POST /query @@ -396,10 +544,9 @@ POST /query | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| query | string | body | Zed query to execute. All data is returned if not specified. || -| head.table | string | body | Table to query against Not required if table is specified in query. | -| head.branch | string | body | Branch to query against. Defaults to "main". | -| ctrl | string | query | Set to "T" to include control messages in BSUP or ZJSON responses. Defaults to "F". | +| query | string | body | **Required.** The query or script to run. | +| args | [string] | body | Strings bound to the `args` [constant](../super-sql/declarations/constants.md) in the query's main scope. | +| ctrl | string | query | Set to "T" to include control messages in BSUP responses. Defaults to "F". | | Content-Type | string | header | [MIME type](#mime-types) of the request payload. | | Accept | string | header | Preferred [MIME type](#mime-types) of the response. | @@ -409,7 +556,8 @@ POST /query curl -X POST \ -H 'Accept: application/x-sup' \ -H 'Content-Type: application/json' \ - http://localhost:9867/query -d '{"query":"from inventory@main | count() by warehouse"}' + -d '{"query": "from inventory | count() by warehouse | sort warehouse"}' \ + http://localhost:9867/query ``` **Example Response** @@ -423,25 +571,58 @@ curl -X POST \ ``` curl -X POST \ - -H 'Accept: application/x-zjson' \ + -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ - http://localhost:9867/query?ctrl=T -d '{"query":"from inventory@main | count() by warehouse"}' + -d '{"query": "from inventory | where warehouse in args | count()", "args": ["miami"]}' \ + http://localhost:9867/query ``` **Example Response** ``` -{"type":"QueryChannelSet","value":{"channel":"main"}} -{"type":{"kind":"record","id":30,"fields":[{"name":"warehouse","type":{"kind":"primitive","name":"string"}},{"name":"count","type":{"kind":"primitive","name":"int64"}}]},"value":["miami","1"]} -{"type":{"kind":"ref","id":30},"value":["chicago","2"]} -{"type":"QueryChannelEnd","value":{"channel":"main"}} -{"type":"QueryStats","value":{"start_time":{"sec":1658193276,"ns":964207000},"update_time":{"sec":1658193276,"ns":964592000},"bytes_read":55,"bytes_matched":55,"records_read":3,"records_matched":3}} +[1] ``` +**Example Request** + +``` +curl -X POST \ + -H 'Accept: application/x-sup' \ + -H 'Content-Type: application/json' \ + -d '{"query": "create table t (x int64); insert into t values (1); select * from t"}' \ + http://localhost:9867/query +``` + +**Example Response** + +``` +{kind:"create_table",stmt:"create table t (x int64)",start:2026-11-21T14:28:19.745488455Z,end:2026-11-21T14:28:19.746648429Z,info:{table:"t",id:01a1fe82-12a1-7ef0-8fc7-f1d4652c7ae2,created:true},error:null} +{kind:"insert",stmt:"insert into t values (1)",start:2026-11-21T14:28:19.746684832Z,end:2026-11-21T14:28:19.747823178Z,info:{table:"t",values:1::uint64,commit:01a1fe82-12a3-76da-8a3a-fe5c09377b49},error:null} +{x:1} +{kind:"query",stmt:"select * from t",start:2026-11-21T14:28:19.747850829Z,end:2026-11-21T14:28:19.748818657Z,info:{values:1::uint64},error:null} +``` + +With `ctrl=T` and a BSUP response, the results are accompanied by control +messages marking the start and end of each output channel and reporting +query statistics, e.g., in SUP: +``` +{channel:"main"}::QueryChannelSet +{warehouse:"chicago",count:2} +{warehouse:"miami",count:1} +{channel:"main"}::QueryChannelEnd +{start_time:2026-11-21T14:15:22.978387144Z,update_time:2026-11-21T14:15:22.978817913Z,Progress:{bytes_scanned:209,values_scanned:3,...}}::QueryStats +``` + +An error found before a query starts to run, e.g., a syntax error, is +returned as a non-2xx response. Since the response status is sent when +results begin to flow, an error that occurs while a query is running is +instead available from the [Query Status](#query-status) endpoint. + #### Query Status -Retrieve any runtime errors from a specific query. This endpoint only responds -after the query has exited and is only available for a limited time afterwards. +Retrieve the error, if any, from a query that has finished running. +This endpoint responds only after the query has exited and is only available +for a limited time afterwards. ``` GET /query/status/{request_id} @@ -451,30 +632,107 @@ GET /query/status/{request_id} | Name | Type | In | Description | | ---- | ---- | -- | ----------- | -| request_id | string | path | **Required.** The value of the response header `X-Request-Id` of the target query. | +| request_id | string | path | **Required.** The value of the response header `X-Request-Id` of the query. | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | **Example Request** ``` curl -X GET \ -H 'Accept: application/json' \ - http://localhost:9867/query/status/2U1oso7btnCXfDenqFOSExOBEIv + http://localhost:9867/query/status/01a1fe82-29a7-7d3b-a1a2-0f5e8a1c6d20 +``` + +**Example Response** + +``` +{"error":"INSERT column \"x\": error({message:\"cannot cast to int64\",on:\"x\"})"} +``` + +#### Describe Query + +Describe a query without running it: the tables it reads and, for each +output channel, its aggregation keys and sort order. + +``` +POST /query/describe +``` + +**Params** + +| Name | Type | In | Description | +| ---- | ---- | -- | ----------- | +| query | string | body | **Required.** The query to describe. | +| Content-Type | string | header | [MIME type](#mime-types) of the request payload. | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | + +**Example Request** + +``` +curl -X POST \ + -H 'Accept: application/json' \ + -H 'Content-Type: application/json' \ + -d '{"query": "from inventory | count() by warehouse"}' \ + http://localhost:9867/query/describe ``` **Example Response** ``` -{"error":"parquetio: unsupported type: empty record"} +{"sources":[{"kind":"Table","name":"inventory","id":"01a1fe81-c8b2-793a-aab3-383076bc5d23"}],"channels":[{"name":"main","aggregation_keys":[["warehouse"]],"sort":[]}]} +``` + +#### Compile Query + +Parse a query without running it and return its abstract syntax tree (AST), +as displayed by [`super compile`](../command/compile.md). The query is +only parsed, so a reference to a table that doesn't exist is not an error. + +``` +POST /compile +``` + +**Params** + +| Name | Type | In | Description | +| ---- | ---- | -- | ----------- | +| query | string | body | **Required.** The query to parse. | +| Content-Type | string | header | [MIME type](#mime-types) of the request payload. | +| Accept | string | header | Preferred [MIME type](#mime-types) of the response. | + +**Example Request** + +``` +curl -X POST \ + -H 'Accept: application/json' \ + -H 'Content-Type: application/json' \ + -d '{"query": "from inventory | head 1"}' \ + http://localhost:9867/compile +``` + +**Example Response** + +``` +[{"kind":"FromOp","item":{"source":{"kind":"Text","value":"inventory","loc":{"first":5,"last":13}},"args":[],"loc":{"first":5,"last":13}},"loc":{"first":0,"last":13}},{"kind":"HeadOp","count":{"kind":"Primitive","type":"int64","text":"1","loc":{"first":22,"last":22}},"loc":{"first":17,"last":22}}] +``` + +A query with a syntax error returns HTTP 400 with the error and its +position in `compilation_errors`, e.g., +``` +{"type":"Error","kind":"invalid operation","error":"parse error at line 1, column 23:\nfrom inventory | head(\n === ^ ===","compilation_errors":[{"Msg":"parse error","Pos":22,"End":-1}]} ``` --- ### Events -Subscribe to an events feed, which returns an event stream in the format of +Subscribe to a feed of database events in the format of [server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html). -The [MIME type](#mime-types) specified in the request's Accept HTTP header determines the format -of `data` field values in the event stream. +The [MIME type](#mime-types) in the request's Accept header determines the format +of the `data` field values in the event stream. + +The events are `table-new`, `table-update`, `table-delete`, +`branch-commit`, `branch-update`, and `branch-delete`. ``` GET /events @@ -496,20 +754,32 @@ curl -X GET \ ``` event: table-new -data: {"table_id": "1sMDXpVwqxm36Rc2vfrmgizc3jz"} +data: {"table_id":"01a1fe82-45e7-70f5-9a02-f4f793350aee"} -event: table-update -data: {"table_id": "1sMDXpVwqxm36Rc2vfrmgizc3jz"} +event: branch-commit +data: {"commit_id":"01a1fe82-45f1-7ab7-87c7-0e980e3c1623","table_id":"01a1fe82-45e7-70f5-9a02-f4f793350aee","branch":"main","parent":""} -event: table-commit -data: {"table_id": "1sMDXpVwqxm36Rc2vfrmgizc3jz", "commit_id": "1tisISpHoWI7MAZdFBiMERXeA2X"} +event: table-update +data: {"table_id":"01a1fe82-45e7-70f5-9a02-f4f793350aee"} event: table-delete -data: {"table_id": "1sMDXpVwqxm36Rc2vfrmgizc3jz"} +data: {"table_id":"01a1fe82-45e7-70f5-9a02-f4f793350aee"} ``` --- +### Service + +| Endpoint | Description | +| -------- | ----------- | +| `GET /version` | The version of the service, e.g., `{"version":"v0.5.0"}` | +| `GET /status` | The text `ok` if the service is running | +| `GET /auth/method` | The authentication method the service requires, if any | +| `GET /auth/identity` | The tenant and user IDs of the authenticated caller | +| `POST /mcp` | The [Model Context Protocol](../command/db.md#super-db-mcp) endpoint, when the service is started with `-mcp` | + +--- + ## Media Types For both request and response payloads, the service supports a variety of @@ -519,7 +789,8 @@ formats. When sending request payloads, include the MIME type of the format in the request's Content-Type header. If the Content-Type header is not specified, the -service will expect SUP as the payload format. +service will expect SUP as the payload format. Since JSON is a subset of +SUP, request bodies may be written in JSON. An exception to this is when [loading data](#load-data) and Content-Type is not specified. In this case the service will attempt to introspect the data and may diff --git a/book/src/database/format.md b/book/src/database/format.md index e07653cc6..c58bd69a8 100644 --- a/book/src/database/format.md +++ b/book/src/database/format.md @@ -1,9 +1,8 @@ # Database Format >[!NOTE] ->This document is a rough draft and work in progress. We plan to ->soon bring it up to date with the current implementation and maintain it ->as we add new capabilities to the system. +>This document describes the current implementation, which may change +>between releases as the database matures. ## Introduction @@ -11,24 +10,18 @@ To support the client-facing SuperDB access implemented by the [`super db` command](../command/db.md), we are developing an open specification for the database format described in this document. -This format is somewhat analogous to the emerging -cloud table formats like [Iceberg](https://iceberg.apache.org/spec/), -but differs but differs in a fundamental way: there are no tables in SuperDB. +This format is somewhat analogous to cloud table formats like +[Iceberg](https://iceberg.apache.org/spec/), +but differs in a fundamental way: it is organized around a type system +rather than relational schemas. -On the contrary, we believe a better approach for organizing modern, eclectic -data is based on a type system rather than a collection of tables -and relational schemas. Since relations, tables, schemas, data frames, -Parquet files, Avro files, JSON, CSV, XML, and so forth are all subsets of the -SuperDB's super-structured type system, SuperDB holds the promise -to provide a universal data representation for all of these different approaches to data. - -> **TODO: update this to emphasize tables are just a special case... not that they -> aren't present in the database** - -Also, while we are not currently focused on building a SQL engine for the SuperDB database, -it is most certainly possible to do so, as a Super record type is analogous to -a SQL table definition. SQL tables can essentially be dynamically projected -via a table virtualization layer built on top of the SuperDB model. +A SuperDB table holds super-structured data, and a relational table is +just a special case, i.e., a table whose values all have the same record +type. Since relations, schemas, data frames, +Parquet files, Avro files, JSON, CSV, and so forth are all subsets of +SuperDB's super-structured type system, the same format can represent +all of these different approaches to data, whether a table has columns, +a type of any kind, or [no type at all](intro.md#tables). All data and metadata in a database conforms to the super-structured data model, which materially simplifies development, test, introspection, and so forth. @@ -44,16 +37,13 @@ Every data element in a database is either of two fundamental object types: All imported table data is composed of immutable objects, which are organized around a primary data object. Each data object is composed of one or more immutable objects all of which share a common, globally unique identifier, -which is referred to below generically as `` below. +which is referred to below generically as ``. -TODO: change text to foreshadow KSUID swap out - -These identifiers are [KSUIDs](https://github.com/segmentio/ksuid). -The KSUID allocation scheme -provides a decentralized solution for creating globally unique IDs. -KSUIDs have embedded timestamps so the creation time of +These identifiers are version 7 [UUIDs](https://www.rfc-editor.org/rfc/rfc9562), +which provide a decentralized means of creating globally unique IDs. +A version 7 UUID begins with a timestamp so the creation time of any object named in this way can be derived. Also, a simple lexicographic -sort of the KSUIDs results in a creation-time ordering (though this ordering +sort of the IDs results in a creation-time ordering (though this ordering is not relied on for causal relationships since clock skew can violate such an assumption). @@ -66,7 +56,7 @@ such an assumption). #### Data Objects A data object is created by a single writer using a globally unique name -with an embedded KSUID. +with an embedded ID. New objects are written in their entirety. No updates, appends, or modifications may be made once an object exists. Given these semantics, any such object may be @@ -87,7 +77,7 @@ Immutable objects are named as follows: |-----------|----| |data|`/data/.bsup`| -`` is the KSUID of the data object. +`` is the ID of the data object. #### Commit History @@ -115,6 +105,11 @@ Each commit object contains a sequence of _actions_: The actions are not grouped directly by their commit ID but instead each action serialization includes its commit ID. +Commit objects are stored as `/commits/.bsup`. Alongside a +commit object, a _snapshot_ of the complete set of data objects as of that +commit may be cached as `/commits/.snap.bsup` so that the +data of a branch can be found without reading its entire commit log. + The chain of commit objects starting at any commit and following the parent pointers to the original commit is called the "commit log". This log represents the definitive record of a branch's present @@ -184,7 +179,7 @@ the HEAD of the journal is accessed. > a successful open. Second, strong read/write ordering semantics (as exists in -[Amazon S3](../dev/integrations/s3.md) +[Amazon S3](../dev/integrations/s3.md)) can be used to implement transactional journal updates as follows: * _TBD: this is worked out but needs to be written up_ @@ -197,7 +192,7 @@ a mutex lock for each table's journal. Configuration state describing a database or table is also stored in mutable objects. The database uses a commit journal to store configuration like the -list of tables and tablea attributes. +list of tables and table attributes. Here, a generic interface to a commit journal manages any configuration state simply as a key-value store of snapshots providing time travel over the configuration history. @@ -206,11 +201,11 @@ the configuration history. To support _sorted scans_, data objects are stored in an (optionally) sorted order defined by the table's sort key. -The sort key may be a composite key compised of primary, secondary, etc +The sort key may be a composite key comprised of primary, secondary, etc component keys. When the key range of objects overlap, they may be read in parallel -in merged in sorted order. +and merged in sorted order. This is called the _merge scan_. If many overlapping data objects arise, performing a merge scan @@ -232,6 +227,9 @@ do not overlap. This is just the basic LSM algorithm at work. ### Object Naming +The objects of a database are laid out under its storage path as follows, +where `superdb.bsup` identifies the directory as a database and records +the version of the format: ``` / superdb.bsup @@ -250,6 +248,7 @@ do not overlap. This is just the basic LSM algorithm at work. ... commits/ .bsup + .snap.bsup .bsup ... data/ diff --git a/book/src/database/intro.md b/book/src/database/intro.md index 006f700fd..772ccd849 100644 --- a/book/src/database/intro.md +++ b/book/src/database/intro.md @@ -1,352 +1,183 @@ # Database -> **TODO: update and simplify. add note about readiness** - -## Data Tables - -## Committish +A SuperDB database stores super-structured data persistently in _tables_. +You manage and query a database with the [`super db`](../command/db.md) +command, with SuperSQL [statements](../super-sql/statements/intro.md) +like `CREATE TABLE` and `INSERT`, or over HTTP with the database +[API](api.md). >[!NOTE] -> While `super` and its accompanying formats -> are production quality, SuperDB's persistent database is still fairly early in development -> and alpha quality. -> That said, SuperDB databases can be utilized quite effectively at small scale, -> or at larger scales when scripted automation -> is deployed to manage the database's data layout via the database -> [API](../database/api.md). -> -> Enhanced scalability with self-tuning configuration is under development. - -## Design Philosophy - -XXX this section pasted in...fix - -The design philosophy for SuperDB is based on composable building blocks -built from self-describing data structures. Everything in a SuperDB database -is built from super-structured data and each system component can be run and tested in isolation. - -Since super-structured data is self-describing, this approach makes stream composition -very easy. Data from a query can trivially be piped to a local -instance of `super` by feeding the resulting output stream to stdin of `super`, for example, +> While `super` and its accompanying formats are production quality, +> SuperDB's database is earlier in development. It works well at small +> scale and at larger scales when automation manages the layout of the +> data through the [API](api.md), but its storage format and API may +> still change between releases. + +A database lives entirely at its _storage path_, which is a directory +on a local file system or a location in cloud storage (currently +[Amazon S3](../dev/integrations/s3.md)). All of its data and metadata +are stored there as [BSUP](../formats/bsup.md) objects, so there is no +catalog, metastore, or other service to set up, and a copy of the storage +path is a complete copy of the database. + +## Getting Started + +Create a database with [`super db init`](../command/db.md#super-db-init) and +[attach](../command/db.md#super-db-attach) to it so later `super db` +commands use it: +```mdtest-command +super db init -q mydb +super db attach -q mydb +super db -c "create table people (name string not null, city string)" > /dev/null +echo '{name:"alice",city:"Berkeley"} {name:"bob",city:"Oakland"}' | + super db load -q -use people - +super db -s -c "insert into people values ('carol', 'Berkeley')" > /dev/null +super db -s -c "select city, count(*) as n from people group by city order by city" ``` -super db query "from table | ...remote query..." | super -c "...local query..." - +```mdtest-output +{city:"Berkeley",n:2} +{city:"Oakland",n:1} ``` -There is no need to configure the SuperDB entities with schema information -like [protobuf configs](https://developers.google.com/protocol-buffers/docs/proto3) -or connections to -[schema registries](https://docs.confluent.io/platform/current/schema-registry/index.html). - -A SuperDB database is completely self-contained, requiring no auxiliary databases -(like the [Hive metastore](https://hive.apache.org/development/gettingstarted)) -or other third-party services to interpret the database internals. -Once copied, a new service can be instantiated by pointing a `super db serve` -at the copy of the database. - -Functionality like [data compaction](../command/db.md#super-db-manage) and retention are all API-driven. - -Bite-sized components are unified by the super-structured data, usually in the BSUP format: -* All database meta-data is available via meta-queries. -* All database operations available through the service API are also available -directly via the `super db` command. -* Database management is agent-driven through the API. For example, instead of complex policies -like data compaction being implemented in the core with some fixed set of -algorithms and policies, an agent can simply hit the API to obtain the meta-data -of the objects in the database, analyze the objects (e.g., looking for too much -key space overlap) and issue API commands to merge overlapping objects -and delete the old fragmented objects, all with the transactional consistency -of the commit log. -* Components are easily tested and debugged in isolation. - -## The Database Model - -A SuperDB database is a cloud-native arrangement of data, optimized for search, -analytics, ETL, data discovery, and data preparation -at scale based on data represented in accordance -with the [super-structured data model](../formats/model.md). - -A database is organized into a collection of data tables forming a single -administrative domain. The current implementation supports -ACID append and delete semantics at the commit level while -we have plans to support CRUD updates at the primary-key level -in the near future. - -TODO: make tables independent entities then tie them together with a separate -layer of administrative glue (i.e., there should be no dependencies in a table -that are required to interpret and query it outside of the table entity) - -TODO: back off on github metaphor? - -The semantics of a SuperDB database loosely follows the nomenclature and -design patterns of [`git`](https://git-scm.com/). In this approach, -* a _database_ is like a GitHub organization, -* a _table_ is like a `git` repository, -* a _branch_ of a _table_ is like a `git` branch, -* the _use_ command is like a `git checkout`, and -* the _load_ command is like a `git add/commit/push`. - -A core theme of the SuperDB database design is _ergonomics_. Given the Git metaphor, -our goal here is that the database tooling be as easy and familiar as Git is -to a technical user. - -Since databases are built upon the super-structured data model, -getting different kinds of data into and out of a database is easy. -There is no need to define schemas or tables and then fit -semi-structured data into schemas before loading data into a database. -And because SuperDB supports a large family of formats and the load endpoint -automatically detects most formats, it's easy to just load data into a database -without thinking about how to convert it into the right format. - -### CLI-First Approach - -The SuperDB project has taken a _CLI-first approach_ to designing and implementing -the system. Any time a new piece of functionality is added to the database, -it is first implemented as a `super db` command. This is particularly convenient -for testing and continuous integration as well as providing intuitive, -bite-sized chunks for learning how the system works and how the different -components come together. - -While the CLI-first approach provides these benefits, -all of the functionality is also exposed through an [API](../database/api.md) to -a database service. Many use cases involve an application like -[SuperDB Desktop](https://zui.brimdata.io/) or a -programming environment like Python/Pandas interacting -with the service API in place of direct use with `super db`. - -### Storage Layer - -The storage model is designed to leverage modern cloud object stores -and separates compute from storage. - -A database is entirely defined by a collection of cloud objects stored -at a configured object-key prefix. This prefix is called the _storage path_. -All of the meta-data describing the tables, branches, commit history, -and so forth is stored as cloud objects inside of the database. There is no need -to set up and manage an auxiliary metadata store. - -Data is arranged in a database as a set of tables, which are comprised of one -or more branches, which consist of a sequence of data [commit objects](#commit-objects) -that point to cloud data objects. - -Cloud objects and commits are immutable and named with UUIDs, -and many commands may reference various database entities by their ID, e.g., -* _Table ID_ - the UUID of a table -* _Commit object ID_ - the UUID of a commit object -* _Data object ID_ - the UUID of a committed data object - -Data is added and deleted from the database only with new commits that -are implemented in a transactionally consistent fashion. Thus, each -commit object (identified by its globally-unique ID) provides a completely -consistent view of an arbitrarily large amount of committed data -at a specific point in time. - -While this commit model may sound heavyweight, excellent live ingest performance -can be achieved by micro-batching commits. - -Because the database represents all state transitions with immutable objects, -the caching of any cloud object (or byte ranges of cloud objects) -is easy and effective since a cached object is never invalid. -This design makes backup/restore, data migration, archive, and -replication easy to support and deploy. - -The cloud objects that comprise a database, e.g., data objects, -commit history, transaction journals, partial aggregations, etc., -are stored as super-structured data in [Super Binary (BSUP)](../formats/bsup.md). -This makes introspection of the database structure straightforward as many key -database data structures can be queried with metadata queries and presented -to a client for further processing by downstream tooling. - -The implementation also includes a storage abstraction that maps the cloud object -model onto a file system so that databases can also be deployed on standard file systems. - -### Command Personalities - -The `super db` command provides a single command-line interface to SuperDB databases, but -different personalities are taken on by `super db` depending on the particular -sub-command executed and the database [connection](../command/db.md#database-connection). - -To this end, `super db` can take on one of three personalities: - -* _Direct Access_ - When the database is a storage path (`file` or `s3` URI), -then the `super db` commands (except for `serve`) all operate directly on the -database located at that path. -* _Client Personality_ - When the database is an HTTP or HTTPS URL, then the -database is presumed to be a service endpoint and the client -commands are directed to the service managing the database. -* _Server Personality_ - When the [`super db serve`](../command/db.md#super-db-serve) command is executed, then -the personality is always the server personality and the database must be -a storage path. This command initiates a continuous server process -that serves client requests for the database at the configured storage path. - -Note that a storage path on the file system is a standard -file system path, relative or absolute, e.g., `/databases/test`. -A fully qualified file URI of the form `file://` is also accepted. - -Concurrent access to any database storage, of course, preserves -data consistency. You can run multiple `super db serve` processes while also -running any `super db` command all pointing at the same storage endpoint -and the database's data footprint will always remain consistent as the endpoints -all adhere to the consistency semantics of the database. - ->[!NOTE] -> Transactional data consistency is not fully implemented yet for -> the S3 endpoint so only single-node access to S3 is available right now, -> though support for multi-node access is forthcoming. -> For a shared file system, the close-to-open cache consistency -> semantics of [NFS](https://en.wikipedia.org/wiki/Network_File_System) should provide the -> necessary consistency guarantees needed by -> the database though this has not been tested. Multi-process, single-node -> access to a local file system has been thoroughly tested and should be -> deemed reliable, i.e., you can run a direct-access instance of `super db` alongside -> a server instance of `super db` on the same file system and data consistency will -> be maintained. - -### Locating the Database - -`super db` commands locate the database in one of two ways: - -1. The database given by the `-attach` option, which applies to that - command only, or otherwise -2. The currently attached database in `~/.super_attach`, which is written by - [super db attach](../command/db.md#super-db-attach). - -If neither is present, the command reports that no database is attached. -There is no default location. - -The [init](../command/db.md#super-db-init) and -[serve](../command/db.md#super-db-serve) commands do not locate a database -this way. Each takes the path to the root of the database as an argument. -### Tables - -A database is made up of _tables_, which are based on super-structured data -and simultaneously resemble relational tables as well -"collections" in NoSQL document stores but in SuperDB all data is strongly typed. -Tables may have one or more branches and every table always -has a branch called `main`. - -A table is created with the [`create` command](../command/db.md#super-db-create) -and a branch of a table is created with the [`branch` command](../command/db.md#super-db-branch). - -A table name can be any valid UTF-8 string and is allocated a unique ID -when created. The table can be referred to by its name or by its ID. -A table may be renamed but the unique ID is always fixed. - -#### Commit Objects - -Data is added into a table in atomic units called _commit objects_. - -Each commit object is assigned a global ID. -Similar to Git, commit objects are arranged into a tree and -represent the entire commit history of the database. - ->[!NOTE] -> Technically speaking, Git can merge from multiple parents and thus -> Git commits form a directed acyclic graph instead of a tree; -> SuperDB does not currently support multiple parents in the commit object history. - -A branch is simply a named pointer to a commit object in the database -and like a table, a branch name can be any valid UTF-8 string. -Consistent updates to a branch are made by writing a new commit object that -points to the previous tip of the branch and updating the branch to point at -the new commit object. This update may be made with a transaction constraint -(e.g., requiring that the previous branch tip is the same as the -commit object's parent); if the constraint is violated, then the transaction -is aborted. - -The _working branch_ of a table may be selected on any command with the `-use` option -or may be persisted across commands with the [`use` command](../command/db.md#super-db-use) so that -`-use` does not have to be specified on each command-line. For interactive -workflows, the `use` command is convenient but for automated workflows -in scripts, it is good practice to explicitly specify the branch in each -command invocation with the `-use` option. - -#### Committish - -Many `super db` commands operate with respect to a commit object. -While commit objects are always referenceable by their commit ID, it is also convenient -to refer to the commit object at the tip of a branch. - -The entity that represents either a commit ID or a branch is called a _committish_. -A committish is always relative to the table and has the form: -* `@` or -* `
@` - -where `
` is a table name or table ID, `` is a commit object ID, -and `` is a branch name. - -In particular, the working branch set by the [`use` command](../command/db.md#super-db-use) is a committish. - -A committish may be abbreviated in several ways where the missing detail is -obtained from the working-branch committish, e.g., -* `
` - When just a table name is given, then the committish is assumed to be -`
@main`. -* `@` or ``- When an ID is given (optionally with the `@` prefix), then the committish is assumed to be `
@` where `
` is obtained from the working-branch committish. -* `@
` - When a branch name is given with the `@` prefix, then the committish is assumed to be `
@` where `
` is obtained from the working-branch committish. - -An argument to a command that takes a commit object is called a _committish_ -since it can be expressed as a branch or as a commit ID. - -#### Table Sort Key - -Each table is organized according to its configured _sort key_, -As table data is often comprised of [records](../formats/model.md#21-record) (analogous to JSON objects), -the sort key is typically a field of the stored records. -When table data is not structured as records/objects (e.g., scalar or arrays or other -non-record types), then the sort key is sometimes be configured -as the special value [`this`](../super-sql/intro.md#pipe-scoping). - -Data can be efficiently scanned if a query has a filter operating on the sort key. -For example, on a table with sort key `ts`, the query `ts == 100` -will be optimized to scan only the data objects where the value `100` could be -present. - -A table also has a configured sort order, either ascending or descending -and data is organized in the table in accordance with this order. -Data scans may be either ascending or descending, and scans that -follow the configured order are generally more efficient than -scans that run in the opposing order. - -Scans may also be range-limited but unordered. - -Any data loaded into a table that lacks the sort key is presumed -to have a null value with regard to range scans. If large amounts -of such "keyless data" are loaded into a table, the ability to -optimize scans over such data is impaired. - -### Time Travel - -Because commits are transactional and immutable, a query -sees its entire data scan as a fixed "snapshot" with respect to the -commit history. In fact, the [`from` operator](../super-sql/operators/from.md) -allows a commit object to be specified with the `@` suffix to a -table reference, e.g., +Here, [`CREATE TABLE`](../super-sql/statements/create-table.md) created a table, +[`super db load`](../command/db.md#super-db-load) loaded data into it +from standard input, [`INSERT`](../super-sql/statements/insert.md) added +another row, and a SQL query read it back. Queries on a database +read tables with [FROM](../super-sql/sql/from.md) or the +[from](../super-sql/operators/from.md) operator. + +## Tables + +A database is made up of tables. A table has a name, which can be any +UTF-8 string, and a unique ID assigned when it is created. +A table can be referred to by either and can be +[renamed](../command/db.md#super-db-rename) while its ID stays the same. + +Unlike a relational table, a table need not have a schema. There are +three kinds of tables, which differ in what values they accept: + +* A table created by [`CREATE TABLE`](../super-sql/statements/create-table.md) + with columns has a record type and behaves like a SQL table: + values are cast to the columns' types and missing nullable columns are null. +* A table created by [`CREATE SUPER TABLE`](../super-sql/statements/create-super-table.md) + or [`super db create -type`](../command/db.md#super-db-create) has a + type of any kind, e.g., a union of record types, and values are cast to it. +* A table created by `CREATE TABLE` without columns or by `super db create` + without `-type` has no type and holds values of any type as they are. + +In a table with a type, a value that cannot be cast to the type +fails the whole load and nothing is committed. + +### Sort Key + +A table may be organized by a _sort key_, which is set when the table is +created with the `ORDER BY` clause of `CREATE TABLE` or the `-orderby` option +of `super db create`, and cannot be changed. +The sort key is typically a field of the table's records, e.g., a timestamp +`ts` for time series data, and may be ascending or descending. + +A query with a filter on the sort key scans only the data objects that +could hold matching values. For example, on a table with sort key `ts`, +the query `ts >= 2026-01-01T00:00:00Z` skips objects whose values of +`ts` are all earlier. Scans that follow the table's sort order are +generally more efficient than scans in the opposite order. + +Values that lack the sort key are treated as having a null key and +can't benefit from range scans. A table without a sort key is unsorted. + +## Branches and Commits + +A database follows a model loosely based on [Git](https://git-scm.com/): +* a _table_ is like a repository, +* a _branch_ of a table is like a Git branch, +* [`super db use`](../command/db.md#super-db-use) is like `git checkout`, and +* [`super db load`](../command/db.md#super-db-load) or `INSERT` is like + `git add`, `git commit`, and `git push` in one step. + +Every table has a branch called `main`, which is used whenever a branch +isn't given, so you can ignore branches entirely until you need them. +New branches are created with [`super db branch`](../command/db.md#super-db-branch) +and merged with [`super db merge`](../command/db.md#super-db-merge). + +### Commit Objects + +Data is added to and deleted from a branch in atomic units called +_commits_. Each commit is identified by a unique ID and points to its +parent, so the commits of a table form a tree, and a branch is a named +pointer to a commit. A commit is transactionally consistent: each commit +provides a consistent view of an arbitrary amount of data at a point in time. + +Many commands refer to a commit or a branch with a +[_committish_](../command/db.md#committish) of the form `
@` +or `
@`. + +The commit history of a branch can be displayed with +[`super db log`](../command/db.md#super-db-log) or queried with the +[meta-query](../command/db.md#meta-queries) `from
:log`. + +## Time Travel + +Because commits are immutable, a query sees its data as a fixed snapshot +as of the commit it reads. If a writer commits data while a reader is +scanning, the reader does not see the new data. + +A query can read any past commit by giving its ID after the table name +in [from](../super-sql/operators/from.md). Continuing the example above, +the first commit has only the two loaded rows: +```mdtest-command +first=$(super db -f line -c 'from people:log | tail 1 | values id') +super db -s -c "from people@$first | sort name" ``` -super db query 'from logs@1tRxi7zjT7oKxCBwwZ0rbaiLRxb | ...' +```mdtest-output +{name:"alice",city:"Berkeley"} +{name:"bob",city:"Oakland"} ``` -In this way, a query can time-travel through the commit history. As long as the -underlying data has not been deleted, arbitrarily old snapshots of the -database can be easily queried. - -If a writer commits data after or while a reader is scanning, then the reader -does not see the new data since it's scanning the snapshot that existed -before these new writes occurred. - -Also, arbitrary metadata can be [committed to the log](../command/db.md#super-db-log), -e.g., to associate derived analytics to a specific -journal commit point potentially across different tables in -a transactionally consistent fashion. - -While time travel through commit history provides one means to explore -past snapshots of the commit history, another means is to use a timestamp. -Because the entire history of branch updates is stored in a transaction journal -and each entry contains a timestamp, branch references can be easily -navigated by time. For example, a list of branches of a table's past -can be created by scanning the internal "tables log" and stopping at the largest -timestamp less than or equal to the desired timestamp. Then using that -historical snapshot of the tables, a branch can be located within the table -using that table's "branches log" in a similar fashion, then its corresponding -commit object can be used to construct the data of that branch at that -past point in time. +As long as its data has not been [vacuumed](../command/db.md#super-db-vacuum), +any past snapshot can be queried. + +## Storage + +The storage layer is designed for cloud object stores and separates +compute from storage. All of the objects that make up a database, +i.e., data objects, commits, and the journals that track tables and +branches, are immutable and stored as BSUP, so caching them is easy +and backup, migration, and replication are simple copies. +The [format](format.md) section describes the layout in detail. + +Data accumulates in a table as a set of data objects. Over time, many +small or overlapping objects can make scans less efficient, so +[`super db manage`](../command/db.md#super-db-manage) (or +`super db serve -manage`) compacts them, and +[`super db vacuum`](../command/db.md#super-db-vacuum) removes objects that +are no longer referenced. + +## Accessing a Database + +`super db` finds the database to use in one of two ways: +1. the `-attach` option, which applies to that command only, or otherwise +2. the database most recently attached with + [`super db attach`](../command/db.md#super-db-attach). + +There is no default database. The [init](../command/db.md#super-db-init) and +[serve](../command/db.md#super-db-serve) commands instead take the +database's storage path as an argument. + +Depending on the database it is attached to, `super db` acts in one of +three ways: + +* _Direct access_ - When the database is a storage path (a file system path + or an `s3` URL), `super db` commands operate directly on the storage. +* _Client_ - When the database is an HTTP or HTTPS URL, `super db` commands + are sent to a database service at that URL. +* _Server_ - [`super db serve`](../command/db.md#super-db-serve) runs a + service that handles [API](api.md) requests for the database at a + storage path. + +Any number of processes can access the same storage at once, e.g., +a `super db serve` along with direct-access `super db` commands, and the +database remains consistent. >[!NOTE] -> Time travel using timestamps is a forthcoming feature. +> Transactional consistency is not yet fully implemented for S3, so only +> single-node access to S3 is supported for now. Multi-process, +> single-node access to a local file system is well tested. diff --git a/book/src/super-sql/queries.md b/book/src/super-sql/queries.md index 4536f4762..b83e422ba 100644 --- a/book/src/super-sql/queries.md +++ b/book/src/super-sql/queries.md @@ -12,6 +12,9 @@ called a [SQL operator](sql/intro.md#sql-operator). Operator sequences may be parenthesized and nested to form lexical [scopes](#scope). +Queries may be combined with commands like `CREATE TABLE` and `INSERT` +into a script of [statements](statements/intro.md) separated by semicolons. + Operators utilize expressions in composable variations to perform their computations and all expressions share a common [expression syntax](expressions/intro.md). diff --git a/book/src/super-sql/statements/create-super-table.md b/book/src/super-sql/statements/create-super-table.md new file mode 100644 index 000000000..aa30f2b64 --- /dev/null +++ b/book/src/super-sql/statements/create-super-table.md @@ -0,0 +1,120 @@ +# CREATE SUPER TABLE + +``` +CREATE SUPER TABLE [ IF NOT EXISTS ] + [ ORDER BY [ ASC | DESC ] [ , ... ] ] +``` + +## Description + +`CREATE SUPER TABLE` creates a table called `` whose values all have +the super-structured type ``, which may be any +[SuperSQL type](../types/intro.md), not just a record of columns. +A union type, for example, lets a single table hold values of different +shapes while still giving every value a precise type. +`` may refer to [named types](../types/named.md) declared at the +top of the script, including types computed from data. + +As with [CREATE TABLE](create-table.md), `` is an identifier or a +quoted string, `IF NOT EXISTS` makes the statement do nothing if the +table already exists, and `ORDER BY` sets the table's +[sort key](../../database/intro.md#sort-key). + +Every value added to the table, whether by [INSERT](insert.md), +[`super db load`](../../command/db.md#super-db-load), +or the [load](../operators/load.md) operator, is +[cast](../expressions/cast.md) to `` with SuperSQL semantics. +Unlike a table created with `CREATE TABLE`, a missing field is not +filled in with null: the value must cast to ``. A field not +in `` is an error. + +A value that cannot be cast to the table's type fails the whole `INSERT` +or load and nothing is committed. + +`CREATE SUPER TABLE` is equivalent to +[`super db create -type`](../../command/db.md#super-db-create). + +## Examples + +The first example creates a database in the current directory with +[`super db init`](../../command/db.md#super-db-init) and +[attaches](../../command/db.md#super-db-attach) to it, and the +examples that follow use it. + +--- + +_A table whose values are either a record or a string_ + +```mdtest-command +super db init -q db +super db attach -q db +super db -c " + create super table mixed {a:int64}|string; + insert into mixed values {a:'1'}, 'hi' +" > /dev/null +super db -s -c 'from mixed | sort this' +``` +```mdtest-output +"hi"::(string|{a:int64}) +{a:1}::(string|{a:int64}) +``` + +--- + +_A value that doesn't fit the type is rejected_ + +```mdtest-command fails +super db -c "insert into mixed values {a:1,b:2}" > /dev/null +``` +```mdtest-output +value {a:1,b:2} cannot be cast to table type string|{a:int64} +``` + +--- + +_A table whose type is a sum type computed from the data in another table_ + +Given some messy event data: +```mdtest-input events.json +{"type":"PushEvent","ref":"main","commits":[{"sha":"a1"}]} +{"type":"WatchEvent","action":"started"} +{"type":"PushEvent","ref":"dev"} +{"type":"IssuesEvent","action":"opened","issue":{"number":1}} +``` +we can load it into a table without a type, then compute a +[sum type](../functions/types/sum_type.md) with one named type for each +kind of event by [fusing](../type-fusion.md) the types of each kind, +and create a table of that type: +```mdtest-command +super db -c "create table raw" > /dev/null +super db load -q -use raw events.json +super db -c " + type Event = ( + from raw + | fuse(this) by type + | collect_map(map{type:optionize(fuse)}) + | sum_type(this) + ); + create super table events Event; + insert into events from raw +" > /dev/null +super db -s -c 'from events | sort type, this' +``` +```mdtest-output +type IssuesEvent={type:string,action:string,issue:{number:int64}} +type PushEvent={type:string,ref:string,commits?:[{sha:string}]} +type WatchEvent={type:string,action:string} +type Event=IssuesEvent|PushEvent|WatchEvent +{type:"IssuesEvent",action:"opened",issue:{number:1}}::IssuesEvent::Event +{type:"PushEvent",ref:"dev"}::PushEvent::Event +{type:"PushEvent",ref:"main",commits?:[{sha:"a1"}]}::PushEvent::Event +{type:"WatchEvent",action:"started"}::WatchEvent::Event +``` +Each value is now tagged with the kind of event it is, and a value that +fits none of them can't be added: +```mdtest-command fails +super db -c "insert into events values {type:'ForkEvent'}" > /dev/null +``` +```mdtest-output +value {type:"ForkEvent"} cannot be cast to table type Event +``` diff --git a/book/src/super-sql/statements/create-table.md b/book/src/super-sql/statements/create-table.md new file mode 100644 index 000000000..53936a439 --- /dev/null +++ b/book/src/super-sql/statements/create-table.md @@ -0,0 +1,130 @@ +# CREATE TABLE + +``` +CREATE TABLE [ IF NOT EXISTS ] + [ ( [ NOT NULL | NULL ] [ , ... ] ) ] + [ ORDER BY [ ASC | DESC ] [ , ... ] ] +``` + +## Description + +`CREATE TABLE` creates a table called `` in the database +with a `main` branch and no data. `` is an identifier or a +quoted string. It is an error if the table already exists unless +`IF NOT EXISTS` is given, in which case the statement does nothing. + +When columns are given, the table has a _table type_, which is a +[record type](../types/record.md) with a field for each column, in order. +A `` may be any [SuperSQL type](../types/intro.md), including +the SQL type names (e.g., `INTEGER` or `VARCHAR`), unions, and +[named types](../types/named.md) declared at the top of the script. +A length on a type, as in `VARCHAR(20)`, is accepted and ignored. + +A column is nullable unless it is declared `NOT NULL`, i.e., the type +of a nullable column ` ` is `|null`. +`NULL` explicitly declares a column nullable. + +Every value added to a table with a table type, whether by +[INSERT](insert.md), [`super db load`](../../command/db.md#super-db-load), +or the [load](../operators/load.md) operator, +is [cast](../expressions/cast.md) to the table type as in SQL: +* a column missing from a value is null if the column is nullable, + and is otherwise an error, +* a field of a value that is not a column is an error, and +* a column value that cannot be cast to the column's type is an error. + +A value that cannot be cast to the table type fails the whole `INSERT` or +load and nothing is committed. + +When no columns are given, the table has no table type and values of +any type are added to it as is, just like a table created by +[`super db create`](../../command/db.md#super-db-create). +To create a table whose values must conform to a type other than a +record of columns, use [CREATE SUPER TABLE](create-super-table.md). + +The optional `ORDER BY` clause sets the table's +[sort key](../../database/intro.md#sort-key), which organizes the +table's data for efficient range scans. Each `` is a field path +and is ascending unless `DESC` is given. `NULLS FIRST` and `NULLS LAST` +are not supported here. A table without `ORDER BY` is unsorted. +The sort key cannot be changed after the table is created. + +## Examples + +The first example creates a database in the current directory with +[`super db init`](../../command/db.md#super-db-init) and +[attaches](../../command/db.md#super-db-attach) to it, and the +examples that follow use it. + +--- + +_A table with typed columns, including a named type, sorted by `src` in descending order_ + +```mdtest-command +super db init -q db +super db attach -q db +super db -c " + type port = uint16; + create table conns (src ip not null, dport port, note varchar(20)) order by src desc; + insert into conns values (10.0.0.1, 80, 'web'), (10.0.0.2, 443); + insert into conns (note, src) values ('dns', 10.0.0.3) +" > /dev/null +super db -s -c 'from conns' +``` +```mdtest-output +{src:10.0.0.3,dport:null,note:"dns"} +type port=uint16 +{src:10.0.0.2,dport:443::port,note:null} +{src:10.0.0.1,dport:80::port,note:"web"} +``` + +--- + +_A NOT NULL column must have a value_ + +```mdtest-command fails +super db -c "insert into conns (dport) values (22)" > /dev/null +``` +```mdtest-output +INSERT has no value for NOT NULL column "src" +``` + +--- + +_A field that isn't a column can't be added_ + +```mdtest-command fails +super db -c "insert into conns values {src:10.0.0.9,proto:'tcp'}" > /dev/null +``` +```mdtest-output +value {src:10.0.0.9,proto:"tcp"} cannot be cast to table type {src:ip,dport:port|null,note:string|null}: no field proto in type +``` + +--- + +_A table without columns holds values of any type_ + +```mdtest-command +super db -c " + create table misc; + insert into misc values 1, 'two', {three:3} +" > /dev/null +super db -s -c 'from misc' +``` +```mdtest-output +1 +"two" +{three:3} +``` + +--- + +_`IF NOT EXISTS` leaves an existing table alone_ + +```mdtest-command +super db -s -c "create table if not exists misc (x int64)" | + super -s -c 'values info.created' - +``` +```mdtest-output +false +``` diff --git a/book/src/super-sql/statements/drop-table.md b/book/src/super-sql/statements/drop-table.md new file mode 100644 index 000000000..f644b6175 --- /dev/null +++ b/book/src/super-sql/statements/drop-table.md @@ -0,0 +1,44 @@ +# DROP TABLE + +``` +DROP TABLE [ IF EXISTS ] +``` + +## Description + +`DROP TABLE` removes the table ``, along with all of its branches, +commit history, and data, from the database. This cannot be undone. `` is an identifier or a quoted string. +It is an error if the table does not exist unless `IF EXISTS` is given, +in which case the statement does nothing. + +`DROP TABLE` is equivalent to +[`super db drop`](../../command/db.md#super-db-drop). + +## Examples + +--- + +_Drop a table, then drop it again with `IF EXISTS`_ + +```mdtest-command +super db init -q db +super db attach -q db +super db -c "create table t" > /dev/null +super db -s -c "drop table t; drop table if exists t" | + super -s -c 'values {stmt,dropped:info.dropped}' - +``` +```mdtest-output +{stmt:"drop table t",dropped:true} +{stmt:"drop table if exists t",dropped:false} +``` + +--- + +_Dropping a table that doesn't exist is an error_ + +```mdtest-command fails +super db -c "drop table t" > /dev/null +``` +```mdtest-output +t: table not found +``` diff --git a/book/src/super-sql/statements/insert.md b/book/src/super-sql/statements/insert.md new file mode 100644 index 000000000..5ab51aeba --- /dev/null +++ b/book/src/super-sql/statements/insert.md @@ -0,0 +1,116 @@ +# INSERT + +``` +INSERT INTO [ ( [ , ... ] ) ] +``` + +## Description + +`INSERT` runs `` and adds its results to the `main` branch of the +table `` in a single commit. `` is an identifier or a quoted +string. `` may be any [query](../queries.md): a SQL +[VALUES](../sql/values.md) clause, a [SELECT](../sql/select.md), or a pipe +query. As in SQL, a parenthesized query that is the entire body of the +`INSERT` is the query itself rather than a subquery expression. + +The results are added to the table in one of two ways: + +* When a column list is given or `` is a SQL query + (e.g., `VALUES` tuples or `SELECT`), the result columns are assigned + _by position_ to the listed columns, or to all of the table's columns + in order if there is no list. Each value is cast to its column's + type and columns without a value are null. + It is an error if there are more result columns than target columns, + if a listed column is not in the table, or if a `NOT NULL` column + gets no value or a null value. + This requires a table whose type is a record of columns as created by + [CREATE TABLE](create-table.md). +* Otherwise, the results are added as values, just as + [`super db load`](../../command/db.md#super-db-load) adds them: + each value is cast to the table's type _by field name_ as described + for [CREATE TABLE](create-table.md) and + [CREATE SUPER TABLE](create-super-table.md), + or added as is if the table has no type. + +If any value can't be added, the `INSERT` fails and nothing is committed. + +To add data to a branch other than `main`, use the +[load](../operators/load.md) operator or `super db load`. + +## Examples + +The examples below use a database with a `pets` table created like this: +```mdtest-command +super db init -q db +super db attach -q db +super db -c "create table pets (name string not null, species string, age int64)" > /dev/null +super db -f line -c 'from :tables | values name' +``` +```mdtest-output +pets +``` + +--- + +_Insert `VALUES` tuples into all columns or into listed columns_ + +```mdtest-command +super db -c " + insert into pets values ('rex', 'dog', 3), ('tom', 'cat', 7); + insert into pets (name, age) values ('nemo', 1) +" > /dev/null +super db -s -c 'from pets | sort name' +``` +```mdtest-output +{name:"nemo",species:null,age:1} +{name:"rex",species:"dog",age:3} +{name:"tom",species:"cat",age:7} +``` + +--- + +_Insert the results of a `SELECT`, assigned to columns by position_ + +```mdtest-command +super db -c " + insert into pets select name || ' jr', species, 0 from pets where species = 'dog' +" > /dev/null +super db -s -c 'select * from pets where age = 0' +``` +```mdtest-output +{name:"rex jr",species:"dog",age:0} +``` + +--- + +_Insert records from a pipe query, matched to columns by field name_ + +```mdtest-command +super db -c "insert into pets values {age:2,species:'bird',name:'polly'}" > /dev/null +super db -s -c "from pets | where species=='bird'" +``` +```mdtest-output +{name:"polly",species:"bird",age:2} +``` + +--- + +_Too many values for the table's columns_ + +```mdtest-command fails +super db -c "insert into pets values ('max', 'dog', 4, 'extra')" > /dev/null +``` +```mdtest-output +INSERT has more expressions (4) than target columns (3) +``` + +--- + +_A `NOT NULL` column must get a value_ + +```mdtest-command fails +super db -c "insert into pets (species) values ('fish')" > /dev/null +``` +```mdtest-output +INSERT has no value for NOT NULL column "name" +``` diff --git a/book/src/super-sql/statements/intro.md b/book/src/super-sql/statements/intro.md new file mode 100644 index 000000000..39f1c04f3 --- /dev/null +++ b/book/src/super-sql/statements/intro.md @@ -0,0 +1,119 @@ +# Statements + +A SuperSQL _script_ is a sequence of statements separated by semicolons. +A statement is either a [query](../queries.md) or one of these commands: + +* [CREATE TABLE](create-table.md) creates a table whose rows have typed columns, +* [CREATE SUPER TABLE](create-super-table.md) creates a table whose values + have any super-structured type, +* [DROP TABLE](drop-table.md) removes a table, and +* [INSERT](insert.md) adds the results of a query to a table. + +The commands operate on the tables of a [database](../../database/intro.md) +and so run only with [`super db`](../../command/db.md), or through the +database's [API](../../database/api.md). Queries may appear in a script +run by either `super` or `super db`. + +[Declarations](../declarations/intro.md) at the top of a script +are in scope for every statement in the script, e.g., a named type declared +at the top may be used as a column type in `CREATE TABLE`. A declaration +may be followed by a semicolon. + +## Execution + +The statements of a script run one after the other, each to completion +before the next begins, so a statement sees the effects of the statements +before it. + +A script stops at the first statement that fails. The effects of the +statements that ran before it remain, as each `INSERT` commits its data +when it completes. A script is not a transaction. + +## Status Records + +When a script comprises more than one statement or includes a command, +each statement is followed by a _status record_ in the output, after +any values the statement itself produces. A status record has the form +``` +{ + kind: string, + stmt: string, + start: time, + end: time, + info: , + error: string +} +``` +where +* `kind` is `create_table`, `drop_table`, `insert`, or `query`, +* `stmt` is the text of the statement, +* `start` and `end` are the times the statement started and finished, +* `info` is a record describing what the statement did, or null if it failed, and +* `error` is the error message if the statement failed and null otherwise. + +The fields of `info` depend on the kind of statement: + +| kind | info | +|------|------| +| `create_table` | `table` name, table `id`, and `created`, which is false if the table already existed and `IF NOT EXISTS` was given | +| `drop_table` | `table` name, table `id`, and `dropped`, which is false if the table did not exist and `IF EXISTS` was given | +| `insert` | `table` name, number of `values` inserted, and the ID of the `commit` | +| `query` | number of `values` produced | + +The error of a failed statement is also reported on standard error and +`super db` exits with a non-zero status. + +A script consisting of a single query produces just the query's results +without a status record. + +## Examples + +The examples in this section create a database in the current directory +with [`super db init`](../../command/db.md#super-db-init) and then +[attach](../../command/db.md#super-db-attach) to it so that subsequent +`super db` commands use it. + +--- + +_A script that creates a table, inserts into it, and queries it_ + +The start and end times and the IDs vary from run to run so they are +dropped from the status records here. +```mdtest-command +super db init -q db +super db attach -q db +super db -s -c " + create table people (name string not null, age int64); + insert into people values ('alice', 33), ('bob', 41); + select name from people where age > 35 +" | super -s -c 'drop start,end,info.id,info.commit' - +``` +```mdtest-output +{kind:"create_table",stmt:"create table people (name string not null, age int64)",info:{table:"people",created:true},error:null} +{kind:"insert",stmt:"insert into people values ('alice', 33), ('bob', 41)",info:{table:"people",values:2::uint64},error:null} +{name:"bob"} +{kind:"query",stmt:"select name from people where age > 35",info:{values:1::uint64},error:null} +``` + +--- + +_A script stops at the first statement that fails_ + +```mdtest-command fails +super db -c " + create table t (x int64); + insert into t values (1); + insert into t values ('one'); + insert into t values (2) +" > /dev/null +``` +```mdtest-output +INSERT column "x": error({message:"cannot cast to int64",on:"one"}) +``` +The first `INSERT` committed its value but the last never ran: +```mdtest-command +super db -s -c 'from t' +``` +```mdtest-output +{x:1} +``` From e0244deb6e5f8c1fc867bacc559bdcd29e733de8 Mon Sep 17 00:00:00 2001 From: Steven McCanne Date: Sat, 21 Nov 2026 08:39:01 -0800 Subject: [PATCH 2/4] remove comments implied by early nature of project --- book/src/command/db.md | 8 ++------ book/src/database/format.md | 6 ------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/book/src/command/db.md b/book/src/command/db.md index f74506f92..1f338fdd3 100644 --- a/book/src/command/db.md +++ b/book/src/command/db.md @@ -1,11 +1,7 @@ # super db -`super db` is a sub-command of [super](super.md) to manage and query SuperDB databases. - ->[!NOTE] -> The database portion of SuperDB is earlier in development than `super` -> and its formats. See the [Database](../database/intro.md) section for -> an overview of how a database works. +`super db` is a sub-command of [super](super.md) to manage and query SuperDB +[databases](../database/intro.md). The `super db` command is invoked either by itself to run a query: ``` diff --git a/book/src/database/format.md b/book/src/database/format.md index c58bd69a8..90f1efc9d 100644 --- a/book/src/database/format.md +++ b/book/src/database/format.md @@ -1,11 +1,5 @@ # Database Format ->[!NOTE] ->This document describes the current implementation, which may change ->between releases as the database matures. - -## Introduction - To support the client-facing SuperDB access implemented by the [`super db` command](../command/db.md), we are developing an open specification for the database format described in this document. From ccc977ddccb88dd6926abfb7eb6924cd9d77977e Mon Sep 17 00:00:00 2001 From: Steven McCanne Date: Sat, 21 Nov 2026 08:45:08 -0800 Subject: [PATCH 3/4] deep review --- book/src/super-sql/statements/drop-table.md | 3 ++- book/src/super-sql/statements/insert.md | 11 +++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/book/src/super-sql/statements/drop-table.md b/book/src/super-sql/statements/drop-table.md index f644b6175..a6c0cc181 100644 --- a/book/src/super-sql/statements/drop-table.md +++ b/book/src/super-sql/statements/drop-table.md @@ -12,7 +12,8 @@ It is an error if the table does not exist unless `IF EXISTS` is given, in which case the statement does nothing. `DROP TABLE` is equivalent to -[`super db drop`](../../command/db.md#super-db-drop). +[`super db drop`](../../command/db.md#super-db-drop) except that it +does not ask for confirmation. ## Examples diff --git a/book/src/super-sql/statements/insert.md b/book/src/super-sql/statements/insert.md index 5ab51aeba..10662cb37 100644 --- a/book/src/super-sql/statements/insert.md +++ b/book/src/super-sql/statements/insert.md @@ -21,10 +21,13 @@ The results are added to the table in one of two ways: in order if there is no list. Each value is cast to its column's type and columns without a value are null. It is an error if there are more result columns than target columns, - if a listed column is not in the table, or if a `NOT NULL` column - gets no value or a null value. - This requires a table whose type is a record of columns as created by - [CREATE TABLE](create-table.md). + if a listed column is not in the table, or if a column that isn't + nullable (e.g., a `NOT NULL` column) gets no value or a null value. + For a table without a type, a column list names the fields of the + inserted records, and without one, the results of a SQL query are + added as is (e.g., with fields `column1`, `column2`, etc. for `VALUES`). + A column list is an error for a table whose type isn't a record type, + and without one, the results are added as values as described next. * Otherwise, the results are added as values, just as [`super db load`](../../command/db.md#super-db-load) adds them: each value is cast to the table's type _by field name_ as described From c4daabb5a7a4e36c1c95dc65dfdd03e768296566 Mon Sep 17 00:00:00 2001 From: Steven McCanne Date: Sun, 22 Nov 2026 13:50:07 -0800 Subject: [PATCH 4/4] address PR feedback --- book/src/database/api.md | 25 ++++++++++++++++++- book/src/database/intro.md | 6 ++--- .../statements/create-super-table.md | 3 ++- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/book/src/database/api.md b/book/src/database/api.md index 25d906318..279aeb49f 100644 --- a/book/src/database/api.md +++ b/book/src/database/api.md @@ -52,7 +52,30 @@ curl -X POST \ **Example Response** ``` -{"table":{"ts":"2026-11-21T14:28:00.818576616Z","name":"inventory","id":"01a1fe81-c8b2-793a-aab3-383076bc5d23","sortkeys":[{"order":"asc","path":["product"]}],"objectcap":1048576,"framecap":20000,"type":"0x","sql":false},"branch":{"ts":"2026-11-21T14:28:00.818741489Z","name":"main","commit":"00000000-0000-0000-0000-000000000000"}} +{ + table: { + ts: "2026-11-21T14:28:00.818576616Z", + name: "inventory", + id: "01a1fe81-c8b2-793a-aab3-383076bc5d23", + sortkeys: [ + { + order: "asc", + path: [ + "product" + ] + } + ], + objectcap: 1048576, + framecap: 20000, + type: "0x", + sql: false + }, + branch: { + ts: "2026-11-21T14:28:00.818741489Z", + name: "main", + commit: "00000000-0000-0000-0000-000000000000" + } +} ``` In the response, `type` is the binary encoding of the table's type, which is diff --git a/book/src/database/intro.md b/book/src/database/intro.md index 772ccd849..6497e5531 100644 --- a/book/src/database/intro.md +++ b/book/src/database/intro.md @@ -53,12 +53,12 @@ UTF-8 string, and a unique ID assigned when it is created. A table can be referred to by either and can be [renamed](../command/db.md#super-db-rename) while its ID stays the same. -Unlike a relational table, a table need not have a schema. There are -three kinds of tables, which differ in what values they accept: +Unlike a relational table in traditional SQL, a table in SuperDB need not have a schema. +There are three kinds of tables, which differ in what values they accept: * A table created by [`CREATE TABLE`](../super-sql/statements/create-table.md) with columns has a record type and behaves like a SQL table: - values are cast to the columns' types and missing nullable columns are null. + values are cast to the columns' types and missing values in nullable columns are null. * A table created by [`CREATE SUPER TABLE`](../super-sql/statements/create-super-table.md) or [`super db create -type`](../command/db.md#super-db-create) has a type of any kind, e.g., a union of record types, and values are cast to it. diff --git a/book/src/super-sql/statements/create-super-table.md b/book/src/super-sql/statements/create-super-table.md index aa30f2b64..b3788eb73 100644 --- a/book/src/super-sql/statements/create-super-table.md +++ b/book/src/super-sql/statements/create-super-table.md @@ -9,7 +9,8 @@ CREATE SUPER TABLE [ IF NOT EXISTS ] `CREATE SUPER TABLE` creates a table called `` whose values all have the super-structured type ``, which may be any -[SuperSQL type](../types/intro.md), not just a record of columns. +[SuperSQL type](../types/intro.md), not just a relational schema (i.e., +a record of comprising columns). A union type, for example, lets a single table hold values of different shapes while still giving every value a precise type. `` may refer to [named types](../types/named.md) declared at the