From f7dc242790cc265719f553d58d9b5c1c8321fcd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Thu, 26 Feb 2026 15:32:28 +0100 Subject: [PATCH 01/22] [LIQ] Fix `group by`: `order by` with `select` aliases, variable binding in `having` and `nil` column ordering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Fix `order by` inability to access `select` output aliases and aggregate functions after `group by`. 2. Introduce `LUA_SQL_NULL` sentinel to preserve column ordering when `select` expressions evaluate to `nil`. Note: In Lua, setting a table key to `nil` deletes it so rows with `nil` values lose those keys and produced inconsistent insertion order across result tables. Signed-off-by: Matouš Jan Fialka --- client/markdown_renderer/result_render.ts | 4 + client/space_lua/query_collection.ts | 306 ++++++++++++++++++---- 2 files changed, 262 insertions(+), 48 deletions(-) diff --git a/client/markdown_renderer/result_render.ts b/client/markdown_renderer/result_render.ts index d27dc353..a72fbc2f 100644 --- a/client/markdown_renderer/result_render.ts +++ b/client/markdown_renderer/result_render.ts @@ -4,11 +4,15 @@ import { luaToString, } from "../space_lua/runtime.ts"; import { isTaggedFloat } from "../space_lua/numeric.ts"; +import { LUA_SQL_NULL } from "../space_lua/query_collection.ts"; export function defaultTransformer(v: any, _k: string): Promise { if (v === undefined) { return Promise.resolve(""); } + if (v === LUA_SQL_NULL) { + return Promise.resolve("*(null)*"); + } if (typeof v === "string") { return Promise.resolve(escapeRegularPipes(v.replaceAll("\n", " "))); } diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 0e197302..77d6388f 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -32,10 +32,18 @@ import { executeAggregate, getAggregateSpec } from "./aggregates.ts"; export { buildItemEnv } from "./query_env.ts"; import { buildItemEnv } from "./query_env.ts"; +// Sentinel value representing SQL NULL in query results. +export const LUA_SQL_NULL = Symbol.for("silverbullet.sqlNull"); + // Build environment for post-`group by` clauses (`having`, `select`, // `order by`). Injects `key` and `group` as top-level variables. Also // unpacks the `group by` key fields as locals so that `group by name, // tag` makes `name` and `tag` accessible. +// +// When an objectVariable is set (e.g. `from t = ...`), `t` is bound to +// the first group item so that `t.name` etc. keep working post-group, +// consistent with the non-binding path where bare field names come from +// the first item. function buildGroupItemEnv( objectVariable: string | undefined, groupByNames: string[] | undefined, @@ -44,16 +52,18 @@ function buildGroupItemEnv( sf: LuaStackFrame, ): LuaEnv { const itemEnv = new LuaEnv(env); - if (objectVariable) { - itemEnv.setLocal(objectVariable, item); - } else { - itemEnv.setLocal("_", item); - } + + // Always expose the raw group row as `_` + itemEnv.setLocal("_", item); + if (item instanceof LuaTable) { const keyVal = item.rawGet("key"); const groupVal = item.rawGet("group"); - if (!objectVariable && groupVal instanceof LuaTable) { + // Always unpack first group item's fields as locals, regardless of + // objectVariable, so bare field names (e.g. `name`) are accessible + // in having/select/order by after group by. + if (groupVal instanceof LuaTable) { const firstItem = groupVal.rawGet(1); if (firstItem) { for (const k of luaKeys(firstItem)) { @@ -63,6 +73,12 @@ function buildGroupItemEnv( ); } } + + // When objectVariable is set, bind it to the first group item + // (not the group row) so `t.name` resolves from item fields. + if (objectVariable && firstItem) { + itemEnv.setLocal(objectVariable, firstItem); + } } if (keyVal !== undefined) { @@ -331,6 +347,68 @@ export async function evalExpressionWithAggregates( return evalExpression(expr, env, sf); } +/** + * Collect the canonical key order from an array of select results. + * Finds the first LuaTable that has the maximum number of string keys + * and returns its keys in insertion order. This represents the + * "complete" column set in the order the user wrote in `select { ... }`. + */ +function collectCanonicalKeyOrder(results: any[]): string[] | null { + let best: string[] | null = null; + for (const item of results) { + if (item instanceof LuaTable) { + const keys = luaKeys(item).filter( + (k): k is string => typeof k === "string", + ); + if (!best || keys.length > best.length) { + best = keys; + } + } + } + return best; +} + +// After select, ensure every `LuaTable` result has the same string keys +// in the same insertion order. +function normalizeSelectResults(results: any[]): any[] { + if (results.length === 0) return results; + + const canonicalKeys = collectCanonicalKeyOrder(results); + if (!canonicalKeys || canonicalKeys.length === 0) return results; + + for (let i = 0; i < results.length; i++) { + const item = results[i]; + if (!(item instanceof LuaTable)) continue; + + // Check if this table is missing any canonical keys + let needsRebuild = false; + for (const k of canonicalKeys) { + const v = item.rawGet(k); + if (v === undefined || v === null) { + needsRebuild = true; + break; + } + } + if (!needsRebuild) continue; + + const rebuilt = new LuaTable(); + for (const k of canonicalKeys) { + const v = item.rawGet(k); + rebuilt.rawSet( + k, + (v === undefined || v === null) ? LUA_SQL_NULL : v, + ); + } + for (const k of luaKeys(item)) { + if (typeof k !== "string") { + rebuilt.rawSet(k, item.rawGet(k)); + } + } + results[i] = rebuilt; + } + return results; +} + /** * Applies a given query (where, order by, limit etc.) to a set of results */ @@ -457,6 +535,31 @@ export async function applyQuery( buildGroupItemEnv(ov, groupByNames, item, e, s) : buildItemEnv; + // When grouped with both select and order by, pre-evaluate select for + // each group row so that order by can reference output aliases + // (e.g., `select { tot = count() } order by tot desc`). + // Store results in a parallel array to preserve insertion order of + // the select table's keys (avoids column reordering side effects). + let selectResults: any[] | undefined; + if (grouped && query.select && query.orderBy) { + selectResults = []; + for (const item of results) { + const itemEnv = mkEnv(query.objectVariable, item, env, sf); + const groupTable = (item as LuaTable).rawGet("group"); + const selected = await evalExpressionWithAggregates( + query.select, + itemEnv, + sf, + groupTable, + query.objectVariable, + env, + ); + selectResults.push(selected); + } + // Normalize early so order by env injection also gets correct keys + selectResults = normalizeSelectResults(selectResults); + } + // Apply `order by` next if (query.orderBy) { // Retrieve from config API if not passed @@ -469,57 +572,164 @@ export async function applyQuery( // Both arguments are optional, so passing undefined is fine const collator = Intl.Collator(collation?.locale, collation?.options); - results = await asyncQuickSort(results, async (a, b) => { - // Compare each orderBy clause until we find a difference - for (const { expr, desc } of query.orderBy!) { - const aEnv = mkEnv(query.objectVariable, a, env, sf); - const bEnv = mkEnv(query.objectVariable, b, env, sf); + // Build index array for sorting so we can keep results and + // selectResults in sync without using identity-based Map lookups. + if (selectResults) { + const indices = results.map((_, i) => i); + await asyncQuickSort(indices, async (ai, bi) => { + const a = results[ai]; + const b = results[bi]; + for (const { expr, desc } of query.orderBy!) { + const aEnv = mkEnv(query.objectVariable, a, env, sf); + const bEnv = mkEnv(query.objectVariable, b, env, sf); - const aVal = await evalExpression(expr, aEnv, sf); - const bVal = await evalExpression(expr, bEnv, sf); - - if ( - collation?.enabled && - typeof aVal === "string" && - typeof bVal === "string" - ) { - const order = collator.compare(aVal, bVal); - if (order != 0) { - return desc ? -order : order; + // Inject pre-computed select output fields so `order by` can + // reference aliases like `tot` from `select { tot = count() }` + const aSelected = selectResults![ai]; + const bSelected = selectResults![bi]; + if (aSelected) { + for (const k of luaKeys(aSelected)) { + aEnv.setLocal( + k, + luaGet(aSelected, k, sf.astCtx ?? null, sf), + ); + } } - } else if (aVal < bVal) { - return desc ? 1 : -1; - } else if (aVal > bVal) { - return desc ? -1 : 1; + if (bSelected) { + for (const k of luaKeys(bSelected)) { + bEnv.setLocal( + k, + luaGet(bSelected, k, sf.astCtx ?? null, sf), + ); + } + } + + // Use aggregate-aware evaluation when grouped so that + // `order by count()` and similar expressions work + const aGroup = (a as LuaTable).rawGet("group"); + const bGroup = (b as LuaTable).rawGet("group"); + const aVal = await evalExpressionWithAggregates( + expr, + aEnv, + sf, + aGroup, + query.objectVariable, + env, + ); + const bVal = await evalExpressionWithAggregates( + expr, + bEnv, + sf, + bGroup, + query.objectVariable, + env, + ); + + if ( + collation?.enabled && + typeof aVal === "string" && + typeof bVal === "string" + ) { + const order = collator.compare(aVal, bVal); + if (order != 0) { + return desc ? -order : order; + } + } else if (aVal < bVal) { + return desc ? 1 : -1; + } else if (aVal > bVal) { + return desc ? -1 : 1; + } + // If equal, continue to next orderBy clause } - // If equal, continue to next orderBy clause - } - return 0; // All orderBy clauses were equal - }); + return 0; // All orderBy clauses were equal + }); + + // Reorder both arrays according to sorted indices + results = indices.map((i) => results[i]); + selectResults = indices.map((i) => selectResults![i]); + } else { + results = await asyncQuickSort(results, async (a, b) => { + // Compare each orderBy clause until we find a difference + for (const { expr, desc } of query.orderBy!) { + const aEnv = mkEnv(query.objectVariable, a, env, sf); + const bEnv = mkEnv(query.objectVariable, b, env, sf); + + let aVal, bVal; + if (grouped) { + // Use aggregate-aware evaluation when grouped + const aGroup = (a as LuaTable).rawGet("group"); + const bGroup = (b as LuaTable).rawGet("group"); + aVal = await evalExpressionWithAggregates( + expr, + aEnv, + sf, + aGroup, + query.objectVariable, + env, + ); + bVal = await evalExpressionWithAggregates( + expr, + bEnv, + sf, + bGroup, + query.objectVariable, + env, + ); + } else { + aVal = await evalExpression(expr, aEnv, sf); + bVal = await evalExpression(expr, bEnv, sf); + } + + if ( + collation?.enabled && + typeof aVal === "string" && + typeof bVal === "string" + ) { + const order = collator.compare(aVal, bVal); + if (order != 0) { + return desc ? -order : order; + } + } else if (aVal < bVal) { + return desc ? 1 : -1; + } else if (aVal > bVal) { + return desc ? -1 : 1; + } + // If equal, continue to next orderBy clause + } + return 0; // All orderBy clauses were equal + }); + } } // Apply the select -- aggregate-aware when grouped + // When select was already pre-evaluated for order by, reuse those results if (query.select) { - const newResult = []; - for (const item of results) { - const itemEnv = mkEnv(query.objectVariable, item, env, sf); - if (grouped) { - const groupTable = (item as LuaTable).rawGet("group"); - newResult.push( - await evalExpressionWithAggregates( - query.select, - itemEnv, - sf, - groupTable, - query.objectVariable, - env, - ), - ); - } else { - newResult.push(await evalExpression(query.select, itemEnv, sf)); + if (selectResults) { + results = selectResults; + } else { + const newResult = []; + for (const item of results) { + const itemEnv = mkEnv(query.objectVariable, item, env, sf); + if (grouped) { + const groupTable = (item as LuaTable).rawGet("group"); + newResult.push( + await evalExpressionWithAggregates( + query.select, + itemEnv, + sf, + groupTable, + query.objectVariable, + env, + ), + ); + } else { + newResult.push(await evalExpression(query.select, itemEnv, sf)); + } } + results = newResult; } - results = newResult; + + results = normalizeSelectResults(results); } // Apply distinct filter (after select to filter on selected values) From bc2ae5e46fc79b6024be43ecd99d098754c31a6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Fri, 27 Feb 2026 08:37:00 +0100 Subject: [PATCH 02/22] [LIQ] Miscellaneous bugfixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix `LUA_SQL_NULL` leaking into `order by` comparisons Note: SQL `NULLS LAST` is now default behaviour! * Fix `objectVariable` unset for empty groups * Fix non-grouped `having` used wrong environment builder Note: Queries similar to the following one now works correctly: ```sql ${query[[ from tags.page having name == 'index' ]]} ``` * Fix `generateKey` did not handle `LUA_SQL_NULL` * Refactor/deduplicate duplicated `order by` comparator * Add `isSqlNull` helper Signed-off-by: Matouš Jan Fialka --- client/markdown_renderer/result_render.ts | 7 +- client/space_lua/query_collection.ts | 320 ++++++++++++---------- 2 files changed, 181 insertions(+), 146 deletions(-) diff --git a/client/markdown_renderer/result_render.ts b/client/markdown_renderer/result_render.ts index a72fbc2f..fdf692f4 100644 --- a/client/markdown_renderer/result_render.ts +++ b/client/markdown_renderer/result_render.ts @@ -4,13 +4,13 @@ import { luaToString, } from "../space_lua/runtime.ts"; import { isTaggedFloat } from "../space_lua/numeric.ts"; -import { LUA_SQL_NULL } from "../space_lua/query_collection.ts"; +import { isSqlNull } from "../space_lua/query_collection.ts"; export function defaultTransformer(v: any, _k: string): Promise { if (v === undefined) { return Promise.resolve(""); } - if (v === LUA_SQL_NULL) { + if (isSqlNull(v)) { return Promise.resolve("*(null)*"); } if (typeof v === "string") { @@ -28,9 +28,8 @@ export function defaultTransformer(v: any, _k: string): Promise { export function refCellTransformer(v: any, k: string) { if (k === "ref") { return Promise.resolve(`[[${v}]]`); - } else { - return defaultTransformer(v, k); } + return defaultTransformer(v, k); } /** diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 77d6388f..5af8177e 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -35,6 +35,10 @@ import { buildItemEnv } from "./query_env.ts"; // Sentinel value representing SQL NULL in query results. export const LUA_SQL_NULL = Symbol.for("silverbullet.sqlNull"); +export function isSqlNull(v: any): boolean { + return v === LUA_SQL_NULL; +} + // Build environment for post-`group by` clauses (`having`, `select`, // `order by`). Injects `key` and `group` as top-level variables. Also // unpacks the `group by` key fields as locals so that `group by name, @@ -63,24 +67,23 @@ function buildGroupItemEnv( // Always unpack first group item's fields as locals, regardless of // objectVariable, so bare field names (e.g. `name`) are accessible // in having/select/order by after group by. - if (groupVal instanceof LuaTable) { - const firstItem = groupVal.rawGet(1); - if (firstItem) { - for (const k of luaKeys(firstItem)) { - itemEnv.setLocal( - k, - luaGet(firstItem, k, sf.astCtx ?? null, sf), - ); - } - } + const firstItem = (groupVal instanceof LuaTable) + ? groupVal.rawGet(1) + : undefined; - // When objectVariable is set, bind it to the first group item - // (not the group row) so `t.name` resolves from item fields. - if (objectVariable && firstItem) { - itemEnv.setLocal(objectVariable, firstItem); + if (firstItem) { + for (const k of luaKeys(firstItem)) { + itemEnv.setLocal( + k, + luaGet(firstItem, k, sf.astCtx ?? null, sf), + ); } } + if (objectVariable) { + itemEnv.setLocal(objectVariable, firstItem ?? item); + } + if (keyVal !== undefined) { itemEnv.setLocal("key", keyVal); } @@ -409,6 +412,93 @@ function normalizeSelectResults(results: any[]): any[] { return results; } +// Handles both grouped (aggregate-aware) and non-grouped evaluation, +// optional select-alias injection, and collation +async function orderByCompare( + a: any, + b: any, + orderBy: LuaOrderBy[], + mkEnv: ( + ov: string | undefined, + item: any, + e: LuaEnv, + s: LuaStackFrame, + ) => LuaEnv, + objectVariable: string | undefined, + env: LuaEnv, + sf: LuaStackFrame, + grouped: boolean, + collation: QueryCollationConfig | undefined, + collator: Intl.Collator, + aSelectRow?: any, + bSelectRow?: any, +): Promise { + for (const { expr, desc } of orderBy) { + const aEnv = mkEnv(objectVariable, a, env, sf); + const bEnv = mkEnv(objectVariable, b, env, sf); + + if (aSelectRow) { + for (const k of luaKeys(aSelectRow)) { + const v = luaGet(aSelectRow, k, sf.astCtx ?? null, sf); + aEnv.setLocal(k, isSqlNull(v) ? null : v); + } + } + if (bSelectRow) { + for (const k of luaKeys(bSelectRow)) { + const v = luaGet(bSelectRow, k, sf.astCtx ?? null, sf); + bEnv.setLocal(k, isSqlNull(v) ? null : v); + } + } + + let aVal, bVal; + if (grouped) { + const aGroup = (a as LuaTable).rawGet("group"); + const bGroup = (b as LuaTable).rawGet("group"); + aVal = await evalExpressionWithAggregates( + expr, + aEnv, + sf, + aGroup, + objectVariable, + env, + ); + bVal = await evalExpressionWithAggregates( + expr, + bEnv, + sf, + bGroup, + objectVariable, + env, + ); + } else { + aVal = await evalExpression(expr, aEnv, sf); + bVal = await evalExpression(expr, bEnv, sf); + } + + const aIsNull = aVal === null || aVal === undefined; + const bIsNull = bVal === null || bVal === undefined; + if (aIsNull && bIsNull) continue; + if (aIsNull) return desc ? -1 : 1; + if (bIsNull) return desc ? 1 : -1; + + if ( + collation?.enabled && + typeof aVal === "string" && + typeof bVal === "string" + ) { + const order = collator.compare(aVal, bVal); + if (order != 0) { + return desc ? -order : order; + } + } else if (aVal < bVal) { + return desc ? 1 : -1; + } else if (aVal > bVal) { + return desc ? -1 : 1; + } + } + return 0; +} + /** * Applies a given query (where, order by, limit etc.) to a set of results */ @@ -498,19 +588,18 @@ export async function applyQuery( } } - // Apply `having` -- aggregate-aware when grouped if (query.having) { const filteredResults = []; for (const value of results) { - const itemEnv = buildGroupItemEnv( - query.objectVariable, - groupByNames, - value, - env, - sf, - ); let condResult; if (grouped) { + const itemEnv = buildGroupItemEnv( + query.objectVariable, + groupByNames, + value, + env, + sf, + ); const groupTable = (value as LuaTable).rawGet("group"); condResult = await evalExpressionWithAggregates( query.having, @@ -521,6 +610,7 @@ export async function applyQuery( env, ); } else { + const itemEnv = buildItemEnv(query.objectVariable, value, env, sf); condResult = await evalExpression(query.having, itemEnv, sf); } if (condResult) { @@ -572,132 +662,42 @@ export async function applyQuery( // Both arguments are optional, so passing undefined is fine const collator = Intl.Collator(collation?.locale, collation?.options); - // Build index array for sorting so we can keep results and - // selectResults in sync without using identity-based Map lookups. if (selectResults) { + // Sort via index array to keep results and selectResults in sync const indices = results.map((_, i) => i); - await asyncQuickSort(indices, async (ai, bi) => { - const a = results[ai]; - const b = results[bi]; - for (const { expr, desc } of query.orderBy!) { - const aEnv = mkEnv(query.objectVariable, a, env, sf); - const bEnv = mkEnv(query.objectVariable, b, env, sf); - - // Inject pre-computed select output fields so `order by` can - // reference aliases like `tot` from `select { tot = count() }` - const aSelected = selectResults![ai]; - const bSelected = selectResults![bi]; - if (aSelected) { - for (const k of luaKeys(aSelected)) { - aEnv.setLocal( - k, - luaGet(aSelected, k, sf.astCtx ?? null, sf), - ); - } - } - if (bSelected) { - for (const k of luaKeys(bSelected)) { - bEnv.setLocal( - k, - luaGet(bSelected, k, sf.astCtx ?? null, sf), - ); - } - } - - // Use aggregate-aware evaluation when grouped so that - // `order by count()` and similar expressions work - const aGroup = (a as LuaTable).rawGet("group"); - const bGroup = (b as LuaTable).rawGet("group"); - const aVal = await evalExpressionWithAggregates( - expr, - aEnv, - sf, - aGroup, - query.objectVariable, - env, - ); - const bVal = await evalExpressionWithAggregates( - expr, - bEnv, - sf, - bGroup, - query.objectVariable, - env, - ); - - if ( - collation?.enabled && - typeof aVal === "string" && - typeof bVal === "string" - ) { - const order = collator.compare(aVal, bVal); - if (order != 0) { - return desc ? -order : order; - } - } else if (aVal < bVal) { - return desc ? 1 : -1; - } else if (aVal > bVal) { - return desc ? -1 : 1; - } - // If equal, continue to next orderBy clause - } - return 0; // All orderBy clauses were equal - }); + await asyncQuickSort(indices, (ai, bi) => + orderByCompare( + results[ai], + results[bi], + query.orderBy!, + mkEnv, + query.objectVariable, + env, + sf, + grouped, + collation, + collator, + selectResults![ai], + selectResults![bi], + )); // Reorder both arrays according to sorted indices results = indices.map((i) => results[i]); selectResults = indices.map((i) => selectResults![i]); } else { - results = await asyncQuickSort(results, async (a, b) => { - // Compare each orderBy clause until we find a difference - for (const { expr, desc } of query.orderBy!) { - const aEnv = mkEnv(query.objectVariable, a, env, sf); - const bEnv = mkEnv(query.objectVariable, b, env, sf); - - let aVal, bVal; - if (grouped) { - // Use aggregate-aware evaluation when grouped - const aGroup = (a as LuaTable).rawGet("group"); - const bGroup = (b as LuaTable).rawGet("group"); - aVal = await evalExpressionWithAggregates( - expr, - aEnv, - sf, - aGroup, - query.objectVariable, - env, - ); - bVal = await evalExpressionWithAggregates( - expr, - bEnv, - sf, - bGroup, - query.objectVariable, - env, - ); - } else { - aVal = await evalExpression(expr, aEnv, sf); - bVal = await evalExpression(expr, bEnv, sf); - } - - if ( - collation?.enabled && - typeof aVal === "string" && - typeof bVal === "string" - ) { - const order = collator.compare(aVal, bVal); - if (order != 0) { - return desc ? -order : order; - } - } else if (aVal < bVal) { - return desc ? 1 : -1; - } else if (aVal > bVal) { - return desc ? -1 : 1; - } - // If equal, continue to next orderBy clause - } - return 0; // All orderBy clauses were equal - }); + results = await asyncQuickSort(results, (a, b) => + orderByCompare( + a, + b, + query.orderBy!, + mkEnv, + query.objectVariable, + env, + sf, + grouped, + collation, + collator, + )); } } @@ -729,6 +729,8 @@ export async function applyQuery( results = newResult; } + // Normalize: ensure all result tables have the same set of keys + // in the same insertion order, using LUA_SQL_NULL for nil gaps results = normalizeSelectResults(results); } @@ -784,15 +786,49 @@ export async function queryLua( return applyQuery(results, query, env, sf); } +// Generate a stable string key for deduplication. function generateKey(value: any) { + if (isSqlNull(value)) { + return "__SQL_NULL__"; + } if (value instanceof LuaTable) { - return JSON.stringify(value.toJS()); + return JSON.stringify(luaTableToJSWithNulls(value)); } return typeof value === "object" && value !== null ? JSON.stringify(value) : value; } +function luaTableToJSWithNulls( + table: LuaTable, + sf = LuaStackFrame.lostFrame, +): any { + if (table.length > 0) { + const arr: any[] = []; + for (let i = 1; i <= table.length; i++) { + const v = table.rawGet(i); + arr.push( + isSqlNull(v) + ? "__SQL_NULL__" + : v instanceof LuaTable + ? luaTableToJSWithNulls(v, sf) + : v, + ); + } + return arr; + } + const obj: Record = {}; + for (const key of luaKeys(table)) { + const v = table.rawGet(key); + obj[key] = isSqlNull(v) + ? "__SQL_NULL__" + : v instanceof LuaTable + ? luaTableToJSWithNulls(v, sf) + : v; + } + return obj; +} + export class DataStoreQueryCollection implements LuaQueryCollection { constructor( private readonly dataStore: DataStore, From c8e541250b912e8b3d7d1a77ff4fabaee3ea1790 Mon Sep 17 00:00:00 2001 From: Laurence Tan Date: Fri, 27 Feb 2026 19:12:03 +1100 Subject: [PATCH 03/22] Fix typo in Library Manager documentation --- libraries/Library/Std/Pages/Library Manager.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Library/Std/Pages/Library Manager.md b/libraries/Library/Std/Pages/Library Manager.md index 22ce2e05..0a774f00 100644 --- a/libraries/Library/Std/Pages/Library Manager.md +++ b/libraries/Library/Std/Pages/Library Manager.md @@ -1,6 +1,6 @@ #meta -From here you can extend SilverBullet with additional functionality throught he use of [libraries](https://silverbullet.md/Libraries). +From here you can extend SilverBullet with additional functionality through the use of [libraries](https://silverbullet.md/Libraries). # Installed Libraries ${widgets.commandButton("Update All", "Library: Update All")} From cad71aa586e23eae2466f40600ff34fef43e7362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Fri, 27 Feb 2026 15:30:40 +0100 Subject: [PATCH 04/22] [LIQ] Fix: `group by` keys and collection handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix `group by` key building: populate array indices from `keyParts` instead of only from `keyRecord`, which was empty for some expressions (e.g. `tags[1]`). - Fix collection handling: treat record-like `LuaTables` (no array part) as items instead of extracting zero items. - Update test suite. Signed-off-by: Matouš Jan Fialka --- client/space_lua/eval.ts | 40 +- client/space_lua/query_collection.ts | 243 ++--- client/space_lua/query_test.lua | 1406 ++++++++++++++++++++++---- client/space_lua/runtime.ts | 8 +- 4 files changed, 1384 insertions(+), 313 deletions(-) diff --git a/client/space_lua/eval.ts b/client/space_lua/eval.ts index 6c8ab0d4..be86a8d2 100644 --- a/client/space_lua/eval.ts +++ b/client/space_lua/eval.ts @@ -38,10 +38,7 @@ import { luaValueToJS, singleResult, } from "./runtime.ts"; -import { - ArrayQueryCollection, - type LuaCollectionQuery, -} from "./query_collection.ts"; +import { type LuaCollectionQuery, toCollection } from "./query_collection.ts"; import { coerceNumericPair, coerceToNumber, @@ -187,9 +184,6 @@ type Queryable = { sf: LuaStackFrame, ) => Promise; }; -function isQueryable(x: unknown): x is Queryable { - return !!x && typeof (x as any).query === "function"; -} function arithVerbFromOperator(op: string): string | null { switch (op) { @@ -855,21 +849,24 @@ export function evalExpression( ); } if (collection instanceof LuaTable && collection.empty()) { - // Make sure we're converting an empty result to an array to "query" + // Empty table → empty array collection = []; - } else { - collection = luaValueToJS(collection, sf); - } - // Check if collection is a queryable collection - if (!isQueryable(collection)) { - if (!Array.isArray(collection)) { - throw new LuaRuntimeError( - "Collection does not support query", - sf.withCtx(q.ctx), - ); + } else if (collection instanceof LuaTable) { + if (collection.length > 0) { + // Array-like table: extract array items, keep as LuaTables + const arr: any[] = []; + for (let i = 1; i <= collection.length; i++) { + arr.push(collection.rawGet(i)); + } + collection = arr; + } else { + // Record-like table (no array part): treat as singleton + collection = [collection]; } - collection = new ArrayQueryCollection(collection); } + + collection = toCollection(collection); + // Build up query object const query: LuaCollectionQuery = { objectVariable, @@ -918,9 +915,8 @@ export function evalExpression( } } - return (collection as Queryable).query(query, env, sf).then( - jsToLuaValue, - ); + // Always use the possibly-wrapped collection + return collection.query(query, env, sf).then(jsToLuaValue); }, ); } diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 5af8177e..53def980 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -8,6 +8,7 @@ import type { LuaPropField, LuaUnaryExpression, } from "./ast.ts"; + import { LuaEnv, luaGet, @@ -29,9 +30,6 @@ import type { KvKey } from "../../plug-api/types/datastore.ts"; import { executeAggregate, getAggregateSpec } from "./aggregates.ts"; -export { buildItemEnv } from "./query_env.ts"; -import { buildItemEnv } from "./query_env.ts"; - // Sentinel value representing SQL NULL in query results. export const LUA_SQL_NULL = Symbol.for("silverbullet.sqlNull"); @@ -39,51 +37,35 @@ export function isSqlNull(v: any): boolean { return v === LUA_SQL_NULL; } -// Build environment for post-`group by` clauses (`having`, `select`, -// `order by`). Injects `key` and `group` as top-level variables. Also -// unpacks the `group by` key fields as locals so that `group by name, -// tag` makes `name` and `tag` accessible. -// -// When an objectVariable is set (e.g. `from t = ...`), `t` is bound to -// the first group item so that `t.name` etc. keep working post-group, -// consistent with the non-binding path where bare field names come from -// the first item. +// Build environment for post-`group by` clauses. Injects `key` and `group` +// as top-level variables. Unpacks first group item fields and group-by key +// fields as locals so that bare field access works after grouping. function buildGroupItemEnv( objectVariable: string | undefined, groupByNames: string[] | undefined, item: any, - env: LuaEnv, + parentGlobals: LuaEnv, sf: LuaStackFrame, ): LuaEnv { - const itemEnv = new LuaEnv(env); - - // Always expose the raw group row as `_` + const itemEnv = new LuaEnv(parentGlobals); itemEnv.setLocal("_", item); - if (item instanceof LuaTable) { const keyVal = item.rawGet("key"); const groupVal = item.rawGet("group"); - - // Always unpack first group item's fields as locals, regardless of - // objectVariable, so bare field names (e.g. `name`) are accessible - // in having/select/order by after group by. const firstItem = (groupVal instanceof LuaTable) ? groupVal.rawGet(1) : undefined; if (firstItem) { for (const k of luaKeys(firstItem)) { - itemEnv.setLocal( - k, - luaGet(firstItem, k, sf.astCtx ?? null, sf), - ); + if (typeof k !== "string") continue; + itemEnv.setLocal(k, luaGet(firstItem, k, sf.astCtx ?? null, sf)); } } if (objectVariable) { itemEnv.setLocal(objectVariable, firstItem ?? item); } - if (keyVal !== undefined) { itemEnv.setLocal("key", keyVal); } @@ -93,14 +75,14 @@ function buildGroupItemEnv( if (keyVal instanceof LuaTable) { for (const k of luaKeys(keyVal)) { - itemEnv.setLocal( - k, - luaGet(keyVal, k, sf.astCtx ?? null, sf), - ); + if (typeof k !== "string") continue; + itemEnv.setLocal(k, luaGet(keyVal, k, sf.astCtx ?? null, sf)); } } + // For single-key group by, bind the key name as a local if ( - !(keyVal instanceof LuaTable) && groupByNames && + !(keyVal instanceof LuaTable) && + groupByNames && groupByNames.length === 1 ) { itemEnv.setLocal(groupByNames[0], keyVal); @@ -109,6 +91,43 @@ function buildGroupItemEnv( return itemEnv; } +/** + * Build an environment for evaluating per-item expressions in queries. + * + * When `objectVariable` is NOT set: item fields are unpacked as locals + * and shadow any globals. The item is also bound to `_`. + * + * When `objectVariable` IS set: only the object variable is bound. + * Item fields are NOT unpacked - the user opted into qualified access + * (e.g. `p.name`) and bare names must resolve from the parent env. + */ +function buildItemEnvLocal( + objectVariable: string | undefined, + item: any, + env: LuaEnv, + sf: LuaStackFrame, +): LuaEnv { + const itemEnv = new LuaEnv(env); + if (objectVariable) { + itemEnv.setLocal(objectVariable, item); + } else { + // Unpack item fields as locals so unqualified access works + itemEnv.setLocal("_", item); + if (item instanceof LuaTable) { + for (const key of luaKeys(item)) { + itemEnv.setLocal(key, luaGet(item, key, sf.astCtx ?? null, sf)); + } + } else if (typeof item === "object" && item !== null) { + for (const key of luaKeys(item)) { + itemEnv.setLocal(key, luaGet(item, key, sf.astCtx ?? null, sf)); + } + } + } + return itemEnv; +} + +export { buildItemEnvLocal as buildItemEnv }; + export type LuaOrderBy = { expr: LuaExpression; desc: boolean; @@ -151,7 +170,6 @@ export interface LuaQueryCollection { export class ArrayQueryCollection implements LuaQueryCollection { constructor(private readonly array: T[]) { } - query( query: LuaCollectionQuery, env: LuaEnv, @@ -162,7 +180,20 @@ export class ArrayQueryCollection implements LuaQueryCollection { } } -// Check whether an expression tree contains any aggregate function call. +// Wrap any object, array, or LuaQueryCollection as a queryable collection +export function toCollection(obj: any): LuaQueryCollection { + if ( + obj instanceof ArrayQueryCollection || + obj instanceof DataStoreQueryCollection + ) { + return obj; + } + if (Array.isArray(obj)) { + return new ArrayQueryCollection(obj); + } + return new ArrayQueryCollection([obj]); +} + function containsAggregate(expr: LuaExpression): boolean { switch (expr.type) { case "FunctionCall": { @@ -219,11 +250,9 @@ export async function evalExpressionWithAggregates( objectVariable: string | undefined, outerEnv: LuaEnv, ): Promise { - // Fast path: no aggregate calls in tree -> normal eval if (!containsAggregate(expr)) { return evalExpression(expr, env, sf); } - const recurse = (e: LuaExpression) => evalExpressionWithAggregates( e, @@ -233,8 +262,6 @@ export async function evalExpressionWithAggregates( objectVariable, outerEnv, ); - - // Direct aggregate call if (expr.type === "FunctionCall") { const fc = expr as LuaFunctionCallExpression; if (fc.prefix.type === "Variable") { @@ -254,8 +281,6 @@ export async function evalExpressionWithAggregates( } } } - - // Recurse into field values if (expr.type === "TableConstructor") { const table = new LuaTable(); let nextArrayIndex = 1; @@ -285,11 +310,8 @@ export async function evalExpressionWithAggregates( } return table; } - - // Recurse operands, apply via luaOp if (expr.type === "Binary") { const bin = expr as LuaBinaryExpression; - if (bin.operator === "and") { const left = singleResult(await recurse(bin.left)); if (!luaTruthy(left)) return left; @@ -300,7 +322,6 @@ export async function evalExpressionWithAggregates( if (luaTruthy(left)) return left; return singleResult(await recurse(bin.right)); } - const left = singleResult(await recurse(bin.left)); const right = singleResult(await recurse(bin.right)); return luaOp( @@ -313,8 +334,6 @@ export async function evalExpressionWithAggregates( sf, ); } - - // Recurse argument, apply operator if (expr.type === "Unary") { const un = expr as LuaUnaryExpression; const arg = singleResult(await recurse(un.argument)); @@ -340,13 +359,10 @@ export async function evalExpressionWithAggregates( return evalExpression(expr, env, sf); } } - - // Unwrap if (expr.type === "Parenthesized") { const paren = expr as LuaParenthesizedExpression; return singleResult(await recurse(paren.expression)); } - return evalExpression(expr, env, sf); } @@ -371,19 +387,13 @@ function collectCanonicalKeyOrder(results: any[]): string[] | null { return best; } -// After select, ensure every `LuaTable` result has the same string keys -// in the same insertion order. function normalizeSelectResults(results: any[]): any[] { if (results.length === 0) return results; - const canonicalKeys = collectCanonicalKeyOrder(results); if (!canonicalKeys || canonicalKeys.length === 0) return results; - for (let i = 0; i < results.length; i++) { const item = results[i]; if (!(item instanceof LuaTable)) continue; - - // Check if this table is missing any canonical keys let needsRebuild = false; for (const k of canonicalKeys) { const v = item.rawGet(k); @@ -393,7 +403,6 @@ function normalizeSelectResults(results: any[]): any[] { } } if (!needsRebuild) continue; - const rebuilt = new LuaTable(); for (const k of canonicalKeys) { const v = item.rawGet(k); @@ -412,8 +421,6 @@ function normalizeSelectResults(results: any[]): any[] { return results; } -// Handles both grouped (aggregate-aware) and non-grouped evaluation, -// optional select-alias injection, and collation async function orderByCompare( a: any, b: any, @@ -436,7 +443,6 @@ async function orderByCompare( for (const { expr, desc } of orderBy) { const aEnv = mkEnv(objectVariable, a, env, sf); const bEnv = mkEnv(objectVariable, b, env, sf); - if (aSelectRow) { for (const k of luaKeys(aSelectRow)) { const v = luaGet(aSelectRow, k, sf.astCtx ?? null, sf); @@ -449,7 +455,6 @@ async function orderByCompare( bEnv.setLocal(k, isSqlNull(v) ? null : v); } } - let aVal, bVal; if (grouped) { const aGroup = (a as LuaTable).rawGet("group"); @@ -474,13 +479,11 @@ async function orderByCompare( aVal = await evalExpression(expr, aEnv, sf); bVal = await evalExpression(expr, bEnv, sf); } - const aIsNull = aVal === null || aVal === undefined; const bIsNull = bVal === null || bVal === undefined; if (aIsNull && bIsNull) continue; if (aIsNull) return desc ? -1 : 1; if (bIsNull) return desc ? 1 : -1; - if ( collation?.enabled && typeof aVal === "string" && @@ -499,9 +502,6 @@ async function orderByCompare( return 0; } -/** - * Applies a given query (where, order by, limit etc.) to a set of results - */ export async function applyQuery( results: any[], query: LuaCollectionQuery, @@ -509,15 +509,16 @@ export async function applyQuery( sf: LuaStackFrame, collation?: QueryCollationConfig, ): Promise { - // Shallow copy to avoid updating underlying data structures results = results.slice(); - - // Filter results based on `where` clause first if (query.where) { const filteredResults = []; for (const value of results) { - // Enrich value - const itemEnv = buildItemEnv(query.objectVariable, value, env, sf); + const itemEnv = buildItemEnvLocal( + query.objectVariable, + value, + env, + sf, + ); if (await evalExpression(query.where, itemEnv, sf)) { filteredResults.push(value); } @@ -527,11 +528,11 @@ export async function applyQuery( const grouped = !!query.groupBy; - // Collect `group by` key names for unpacking into the environment. + // Collect group-by key names for unpacking into the post-group environment. let groupByNames: string[] | undefined; - // Apply `group by` if (query.groupBy) { + // Extract bare names from group-by expressions for local binding groupByNames = query.groupBy.map((expr) => { if (expr.type === "Variable") { return expr.name; @@ -542,39 +543,67 @@ export async function applyQuery( return undefined as unknown as string; }).filter(Boolean); - const groups = new Map(); + const groups = new Map< + string, + { key: any; items: any[] } + >(); + const groupByExprs = query.groupBy as LuaExpression[]; + for (const item of results) { - const itemEnv = buildItemEnv(query.objectVariable, item, env, sf); - // Evaluate all `group by` expressions to form a composite key + const itemEnv = buildItemEnvLocal( + query.objectVariable, + item, + env, + sf, + ); + const keyParts: any[] = []; - for (const expr of query.groupBy) { - keyParts.push(await evalExpression(expr, itemEnv, sf)); + const keyRecord: Record = {}; + + for (const expr of groupByExprs) { + if (expr.type === "Variable") { + const v = await evalExpression(expr, itemEnv, sf); + keyParts.push(v); + keyRecord[expr.name] = v; + } else if (expr.type === "PropertyAccess") { + const v = await evalExpression(expr, itemEnv, sf); + keyParts.push(v); + keyRecord[expr.property] = v; + } else { + const v = await evalExpression(expr, itemEnv, sf); + keyParts.push(v); + } } + const compositeKey = keyParts.length === 1 ? generateKey(keyParts[0]) : JSON.stringify(keyParts.map(generateKey)); let entry = groups.get(compositeKey); if (!entry) { - // Unwrap single key; multi-key to `LuaTable` with named fields let keyVal: any; if (keyParts.length === 1) { keyVal = keyParts[0]; } else { const kt = new LuaTable(); + // Always populate array indices from keyParts for (let i = 0; i < keyParts.length; i++) { kt.rawSetArrayIndex(i + 1, keyParts[i]); - if (groupByNames && groupByNames[i]) { - kt.rawSet(groupByNames[i], keyParts[i]); - } + } + // Additionally set named fields for Variable/PropertyAccess exprs + for (const name in keyRecord) { + kt.rawSet(name, keyRecord[name]); } keyVal = kt; } - entry = { key: keyVal, items: [] }; + entry = { + key: keyVal, + items: [], + }; groups.set(compositeKey, entry); } entry.items.push(item); } - // Convert groups to result rows with `key` and `group` + results = []; for (const { key, items } of groups.values()) { const groupTable = new LuaTable(); @@ -610,7 +639,12 @@ export async function applyQuery( env, ); } else { - const itemEnv = buildItemEnv(query.objectVariable, value, env, sf); + const itemEnv = buildItemEnvLocal( + query.objectVariable, + value, + env, + sf, + ); condResult = await evalExpression(query.having, itemEnv, sf); } if (condResult) { @@ -621,16 +655,16 @@ export async function applyQuery( } const mkEnv = grouped - ? (ov: string | undefined, item: any, e: LuaEnv, s: LuaStackFrame) => - buildGroupItemEnv(ov, groupByNames, item, e, s) - : buildItemEnv; + ? ( + ov: string | undefined, + item: any, + e: LuaEnv, + s: LuaStackFrame, + ) => buildGroupItemEnv(ov, groupByNames, item, e, s) + : buildItemEnvLocal; - // When grouped with both select and order by, pre-evaluate select for - // each group row so that order by can reference output aliases - // (e.g., `select { tot = count() } order by tot desc`). - // Store results in a parallel array to preserve insertion order of - // the select table's keys (avoids column reordering side effects). let selectResults: any[] | undefined; + if (grouped && query.select && query.orderBy) { selectResults = []; for (const item of results) { @@ -646,24 +680,18 @@ export async function applyQuery( ); selectResults.push(selected); } - // Normalize early so order by env injection also gets correct keys selectResults = normalizeSelectResults(selectResults); } - // Apply `order by` next if (query.orderBy) { - // Retrieve from config API if not passed if (collation === undefined) { // @ts-ignore: Hack to access client via the browser - const config = globalThis.client.config; // HACK: Shouldn't be using client here directly - + const config = globalThis.client.config; collation = config.get("queryCollation", {}); } - // Both arguments are optional, so passing undefined is fine const collator = Intl.Collator(collation?.locale, collation?.options); if (selectResults) { - // Sort via index array to keep results and selectResults in sync const indices = results.map((_, i) => i); await asyncQuickSort(indices, (ai, bi) => orderByCompare( @@ -681,7 +709,6 @@ export async function applyQuery( selectResults![bi], )); - // Reorder both arrays according to sorted indices results = indices.map((i) => results[i]); selectResults = indices.map((i) => selectResults![i]); } else { @@ -701,8 +728,6 @@ export async function applyQuery( } } - // Apply the select -- aggregate-aware when grouped - // When select was already pre-evaluated for order by, reuse those results if (query.select) { if (selectResults) { results = selectResults; @@ -728,31 +753,22 @@ export async function applyQuery( } results = newResult; } - - // Normalize: ensure all result tables have the same set of keys - // in the same insertion order, using LUA_SQL_NULL for nil gaps results = normalizeSelectResults(results); } - // Apply distinct filter (after select to filter on selected values) if (query.distinct) { const seen = new Set(); const distinctResult = []; - for (const item of results) { - // For non-primitive values, we use a JSON string as the key for comparison const key = generateKey(item); - if (!seen.has(key)) { seen.add(key); distinctResult.push(item); } } - results = distinctResult; } - // Apply the limit and offset if (query.limit !== undefined && query.offset !== undefined) { results = results.slice(query.offset, query.offset + query.limit); } else if (query.limit !== undefined) { @@ -773,7 +789,6 @@ export async function queryLua( enricher?: (key: KvKey, item: any) => any, ): Promise { const results: T[] = []; - // Accumulate all results into an array for await ( let { key, value } of kv.query({ prefix }) ) { @@ -782,11 +797,9 @@ export async function queryLua( } results.push(value); } - return applyQuery(results, query, env, sf); } -// Generate a stable string key for deduplication. function generateKey(value: any) { if (isSqlNull(value)) { return "__SQL_NULL__"; @@ -833,9 +846,7 @@ export class DataStoreQueryCollection implements LuaQueryCollection { constructor( private readonly dataStore: DataStore, readonly prefix: string[], - ) { - } - + ) {} query( query: LuaCollectionQuery, env: LuaEnv, diff --git a/client/space_lua/query_test.lua b/client/space_lua/query_test.lua index e8c3bf67..3266d43d 100644 --- a/client/space_lua/query_test.lua +++ b/client/space_lua/query_test.lua @@ -1,8 +1,17 @@ local function assertEquals(a, b) if a ~= b then - error("Assertion failed: " - .. tostring(a) .. " is not equal to " - .. tostring(b)) + error( + "Assertion failed: " + .. tostring(a) .. " (" .. type(a) .. ")" + .. " is not equal to " + .. tostring(b) .. " (" .. type(b) .. ")" + ) + end +end + +local function assertTrue(v, msg) + if not v then + error("Assertion failed: " .. (msg or "expected truthy value")) end end @@ -17,13 +26,13 @@ local pages = { { name = "Greg", tags = {"work", "fun"}, size = 2, age = 63 }, } --- 1. Basic `from` +-- 1. Basic `from` — all rows returned + do local r = query [[ from pages ]] - assertEquals(#r, #pages) end @@ -32,37 +41,38 @@ do from p = pages ]] - + assertEquals(#r, #pages) assertEquals(r[1].name, "Alice") end --- 2. Select/projection: direct, binding, mixed +-- 2. Select / projection + +-- 2a. Unbound: bare field names do local r = query [[ from pages select { n = name, - t = tags[1], } ]] - assertEquals(r[1].n, "Alice") end +-- 2b. Bound: qualified access do local r = query [[ from p = pages select { n = p.name, - t = p.tags[1], } ]] - + assertEquals(r[1].n, "Alice") assertEquals(r[2].n, "Bob") end +-- 2c. Unbound: mixed with nil-guard for undefined binding do local r = query [[ from @@ -72,85 +82,196 @@ do b = p and p.tags[1], } ]] - assertEquals(r[1].a, "Alice") end --- 3. Select field, select as array, order/limit/offset, where +-- 2d. Select single field (not table constructor) do - local r1 = query [[ + local r = query [[ from pages - select { - value = size, - } + select + name ]] - - assertEquals(r1[1].value, 10) - - local r2 = query [[ - from - p = pages - select { - value = p.size, - } - ]] - - assertEquals(r2[1].value, 10) + assertEquals(r[1], "Alice") + assertEquals(r[2], "Bob") end +-- 2e. Select single field, bound do - local r1 = query [[ + local r = query [[ from + p = pages + select + p.name + ]] + assertEquals(r[1], "Alice") + assertEquals(r[2], "Bob") +end + +-- 2f. Select with expression +do + local r = query [[ + from pages - limit 2 + select + name .. " (" .. size .. ")" + ]] + assertEquals(r[1], "Alice (10)") +end + +-- 2g. Select with expression, bound +do + local r = query [[ + from + p = pages + select + p.name .. " (" .. p.size .. ")" + ]] + assertEquals(r[1], "Alice (10)") +end + +-- 2h. Select whole object via object variable +do + local r = query [[ + from + p = pages + select + p + ]] + assertEquals(r[1].name, "Alice") + assertEquals(r[1].size, 10) +end + +-- 2i. Select table with aliased fields (key ~= value name) +do + local r = query [[ + from + pages select { - name = name, + pageName = name, + sz = size, } ]] + assertEquals(r[1].pageName, "Alice") + assertEquals(r[1].sz, 10) +end - assertEquals(#r1, 2) +-- 3. Limit and offset + +-- 3a. Limit only +do + local r = query [[ + from + pages + limit + 2 + ]] + assertEquals(#r, 2) +end - local r2 = query [[ +-- 3b. Limit with offset +do + local r = query [[ from p = pages - limit 3, 2 select { name = p.name, } + limit + 3, 2 ]] - - assertEquals(r2[1].name, "Carol") + assertEquals(#r, 3) + assertEquals(r[1].name, "Carol") end +-- 3c. Large offset reduces result count do - local r1 = query [[ + local r = query [[ + from + pages + limit + 100, 5 + ]] + assertEquals(#r, 2) +end + +-- 3d. Limit 0 returns empty +do + local r = query [[ + from + pages + limit + 0 + ]] + assertEquals(#r, 0) +end + +-- 4. Order by + +-- 4a. Order by field, unbound +do + local r = query [[ from pages - order by - size desc select { name = name, } + order by + size desc ]] + assertEquals(r[1].name, "Bob") +end - assert(r1[1].name == "Bob") - - local r2 = query [[ +-- 4b. Order by field, bound +do + local r = query [[ from p = pages - order by - p.age select { age = p.age, } + order by + p.age ]] - - assert(r2[1].age == 19) + assertEquals(r[1].age, 19) end +-- 4c. Order by multiple fields do - local r1 = query [[ + local r = query [[ + from + p = pages + select { + name = p.name, + size = p.size, + } + order by + p.size, p.name + ]] + -- size=1 Fran, size=2 Greg, size=3 Ed, size=5 Carol, ... + assertEquals(r[1].name, "Fran") + assertEquals(r[2].name, "Greg") +end + +-- 4d. Order by desc + limit +do + local r = query [[ + from + p = pages + order by + p.age desc + limit + 1 + ]] + assertEquals(r[1].name, "Greg") -- age 63 +end + +-- 5. Where + +-- 5a. Where, unbound +do + local r = query [[ from pages where @@ -159,10 +280,13 @@ do name = name, } ]] + assertEquals(#r, 2) -- Bob (20), Dave (15) + assertEquals(r[1].name, "Bob") +end - assert(r1[1].name == "Bob") - - local r2 = query [[ +-- 5b. Where, bound +do + local r = query [[ from p = pages where @@ -171,18 +295,91 @@ do name = p.name, } ]] - - assert(r2[1].name == "Bob", - "Expected Bob in r2[1], got " .. tostring(r2[1] and r2[1].name)) - - assert(r2[2].name == "Ed", - "Expected Ed in r2[2], got " .. tostring(r2[2] and r2[2].name)) + assertEquals(r[1].name, "Bob") + assertEquals(r[2].name, "Ed") end --- 4. Grouping/group select - +-- 5c. Where with truthy check, unbound do - local r1 = query [[ + local r = query [[ + from + pages + where + name + ]] + assertEquals(#r, #pages) +end + +-- 5d. Where with nil check on nested field, unbound +do + local r = query [[ + from + pages + where + tags[1] ~= nil + ]] + -- Ed has empty tags -> tags[1] is nil -> excluded + assertEquals(#r, 6) +end + +-- 5e. Where with nil check, bound +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + ]] + assertEquals(#r, 6) +end + +-- 5f. Where + order by + limit + select (full pipeline without grouping) +do + local r = query [[ + from + p = pages + where + p.size > 2 + select { + name = p.name, + size = p.size, + } + order by + p.name + limit + 3 + ]] + assertEquals(#r, 3) + assertEquals(r[1].name, "Alice") + assertEquals(r[2].name, "Bob") + assertEquals(r[3].name, "Carol") +end + +-- 5g. Where + order by + limit, unbound +do + local r = query [[ + from + pages + where + size > 2 + select { + name = name, + size = size, + } + order by + name + limit + 3 + ]] + assertEquals(#r, 3) + assertEquals(r[1].name, "Alice") +end + +-- 6. Group by — single key + +-- 6a. Group by with where filter, unbound +do + local r = query [[ from pages where @@ -193,7 +390,14 @@ do key = key, } ]] - local r2 = query [[ + assertTrue(type(r[1].key) == "string" or r[1].key == nil) + -- work, personal, random -> 3 groups + assertEquals(#r, 3) +end + +-- 6b. Group by with where filter, bound +do + local r = query [[ from p = pages where @@ -204,13 +408,66 @@ do key = key, } ]] - - assert(type(r1[1].key) == "string" or r1[1].key == nil) - assert(#r1 == #r2) + assertEquals(#r, 3) end +-- 6c. Group by with group access do - local r1 = query [[ + local r = query [[ + from + pages + where + tags[1] ~= nil + group by + tags[1] + select { + k = key, + gc = #group, + first = group[1].name, + } + ]] + assertTrue(type(r[1].gc) == "number") +end + +-- 6d. Group by bound with group access +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + k = key, + gc = #group, + n = group[1].name, + } + ]] + assertTrue(type(r[1].gc) == "number") +end + +-- 6e. Group by nil key (Ed has empty tags, tags[1] is nil) +do + local r = query [[ + from + pages + group by + tags[1] + select { + k = key, + gc = #group, + } + ]] + -- 4 groups: work, personal, random, nil (Ed) + assertEquals(#r, 4) +end + +-- 7. Group by — composite key + +-- 7a. Multi-key group by, unbound +do + local r = query [[ from pages where @@ -222,7 +479,13 @@ do k2 = key[2], } ]] - local r2 = query [[ + -- Alice: work,urgent; Carol: personal,urgent; Greg: work,fun -> 3 combos + assertEquals(#r, 3) +end + +-- 7b. Multi-key group by, bound +do + local r = query [[ from p = pages where @@ -234,66 +497,18 @@ do k2 = key[2], } ]] - - assert(#r1 == #r2) + assertEquals(#r, 3) end -do - local r = query [[ - from - pages - group by - tags[1] - select { - k = key, - gc = #group, - first = group[1].name, - f2 = group[1].tags[2], - } - ]] - - assert(type(r[1].k) == "string" or r[1].k == nil) - assert(type(r[1].gc) == "number") -end - -do - local r = query [[ - from - p = pages - group by - p.tags[1] - select { - k = key, - gc = #group, - n = group[1].name, - } - ]] - - assert(type(r[1].gc) == "number") -end - -do - local r = query [[ - from - pages - group by - tags[1] - select { - k = key, - n = group[1].name, - t = group[1].tags[1], - } - ]] - - assert(type(r[1].k) == "string" or r[1].k == nil) -end - --- 5. Aggregation/builtins +-- 8. Aggregation builtins +-- 8a. count do local r1 = query [[ from pages + where + tags[1] ~= nil group by tags[1] select { @@ -303,53 +518,47 @@ do local r2 = query [[ from p = pages + where + p.tags[1] ~= nil group by p.tags[1] select { count = count(p.name), } ]] - - assert(type(r1[1].count) == "number") - assert(#r1 == #r2) + assertTrue(type(r1[1].count) == "number") + assertEquals(#r1, #r2) end +-- 8b. min, max, avg, sum do - local r1 = query [[ - from - pages - group by - tags[1] - select { - min = min(age), - max = max(age), - avg = avg(age), - sum = sum(age), - } - ]] - local r2 = query [[ + local r = query [[ from p = pages + where + p.tags[1] ~= nil group by p.tags[1] select { - min = min(p.size), - max = max(p.size), - avg = avg(p.size), - sum = sum(p.size), + mn = min(p.size), + mx = max(p.size), + av = avg(p.size), + sm = sum(p.size), } ]] - - for _, row in ipairs(r2) do - assert(type(row.min) == "number" or row.min == nil) - assert(type(row.avg) == "number" or row.avg == nil) + for _, row in ipairs(r) do + assertTrue(type(row.mn) == "number" or row.mn == nil) + assertTrue(type(row.av) == "number" or row.av == nil) end end +-- 8c. array_agg do local r1 = query [[ from pages + where + tags[1] ~= nil group by tags[1] select { @@ -359,39 +568,67 @@ do local r2 = query [[ from p = pages + where + p.tags[1] ~= nil group by p.tags[1] select { arr = array_agg(p.name), } ]] - - assert(type(r1[1].arr) == "table" or r1[1].arr == nil) - assert(#r1 == #r2) + assertTrue(type(r1[1].arr) == "table" or r1[1].arr == nil) + assertEquals(#r1, #r2) end +-- 8d. count() with no argument (counts all rows) +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + k = key, + n = count(), + } + ]] + assertTrue(type(r[1].n) == "number") +end + +-- 8e. Multiple aggregates in one select do local r = query [[ from pages + where + tags[1] ~= nil group by tags[1] select { c = count(name), - v = min(size), - x = p and count(p.name), + lo = min(size), + hi = max(size), + av = avg(size), + sm = sum(size), + arr = array_agg(name), } ]] - - assert(type(r[1].c) == "number") + assertTrue(type(r[1].c) == "number") + assertTrue(type(r[1].lo) == "number" or r[1].lo == nil) + assertTrue(type(r[1].arr) == "table" or r[1].arr == nil) end --- 6. `having` +-- 9. Having +-- 9a. Having with aggregate, unbound do - local r1 = query [[ + local r = query [[ from pages + where + tags[1] ~= nil group by tags[1] having @@ -400,9 +637,18 @@ do key = key, } ]] - local r2 = query [[ + -- work: Alice,Bob,Greg (3); personal: Carol,Dave (2); random: Fran (1) + -- Only work and personal pass + assertEquals(#r, 2) +end + +-- 9b. Having with aggregate, bound +do + local r = query [[ from p = pages + where + p.tags[1] ~= nil group by p.tags[1] having @@ -411,14 +657,16 @@ do key = key, } ]] - - assertEquals(#r1, #r2) + assertEquals(#r, 2) end +-- 9c. Having with sum do local r = query [[ from p = pages + where + p.tags[1] ~= nil group by p.tags[1] having @@ -427,12 +675,62 @@ do key = key, } ]] - - assert((#r > 0), "expected some groups") + -- work: 10+20+2=32; personal: 5+15=20; random: 1 + -- work and personal pass + assertEquals(#r, 2) end --- 7. Full pipeline +-- 9d. Having without group by (acts as secondary filter), unbound +do + local r = query [[ + from + pages + having + size > 10 + select { + name = name, + } + ]] + assertEquals(#r, 2) -- Bob (20), Dave (15) +end +-- 9e. Having without group by, bound +do + local r = query [[ + from + p = pages + having + p.size > 10 + select { + name = p.name, + } + ]] + assertEquals(#r, 2) +end + +-- 9f. Where + having without group by (both filter) +do + local r = query [[ + from + pages + where + age > 20 + having + size > 10 + select { + name = name, + } + ]] + -- age>20: Alice(31),Bob(25),Carol(41),Dave(52),Fran(55),Greg(63) + -- size>10: Bob(20),Dave(15) + assertEquals(#r, 2) + assertEquals(r[1].name, "Bob") + assertEquals(r[2].name, "Dave") +end + +-- 10. Group by + having + order by + select + limit (full pipeline) + +-- 10a. Bound do local r = query [[ from @@ -448,17 +746,18 @@ do top = max(p.name), total = count(p.name), sum_size = sum(p.size), - min_age = min(age), avg_size = avg(p.size), } order by avg_size desc - limit 2 + limit + 2 ]] - - assert(#r <= 2) + assertTrue(#r <= 2) + assertTrue(type(r[1].avg_size) == "number" or r[1].avg_size == nil) end +-- 10b. Unbound do local r = query [[ from @@ -474,17 +773,301 @@ do top = max(name), total = count(name), sum_size = sum(size), - min_age = min(age), avg_size = avg(size), } order by avg_size desc - limit 2 + limit + 2 ]] - - assert(#r <= 2) + assertTrue(#r <= 2) end +-- 11. Distinct + +-- 11a. Distinct with select, unbound +do + local r = query [[ + from + pages + where + tags[1] ~= nil + select { + tag = tags[1], + } + ]] + -- default distinct=true for queries, so should deduplicate + -- work appears 3x, personal 2x, random 1x -> 3 distinct + assertEquals(#r, 3) +end + +-- 11b. Distinct with select, bound +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + select { + tag = p.tags[1], + } + ]] + assertEquals(#r, 3) +end + +-- 12. Edge cases: empty results + +-- 12a. Where that matches nothing +do + local r = query [[ + from + pages + where + size > 1000 + ]] + assertEquals(#r, 0) +end + +-- 12b. Having that matches nothing +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + having + count(p.name) > 100 + select { + key = key, + } + ]] + assertEquals(#r, 0) +end + +-- 12c. Empty source +do + local empty = {} + local r = query [[ + from + empty + ]] + assertEquals(#r, 0) +end + +-- 13. Group by + order by on aggregate result + +-- 13a. Order by count desc +do + local r = query [[ + from + pages + where + tags[1] ~= nil + group by + tags[1] + select { + tag = key, + n = count(), + } + order by + n desc + ]] + -- work=3, personal=2, random=1 + assertTrue(r[1].n >= r[2].n) +end + +-- 13b. Order by key +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + n = count(), + } + order by + tag + ]] + -- alphabetical: personal, random, work + assertEquals(r[1].tag, "personal") + assertEquals(r[2].tag, "random") + assertEquals(r[3].tag, "work") +end + +-- 14. Group by key name binding + +-- 14a. Single key name available via key variable in select +do + local found_tag = false + local r = query [[ + from + pages + where + tags[1] ~= nil + group by + tags[1] + select { + k = key, + } + ]] + for _, row in ipairs(r) do + if row.k == "work" then + found_tag = true + end + end + assertTrue(found_tag, "expected to find 'work' group key") +end + +-- 15. Caller-injected env variable must not be shadowed by item fields +-- (the requeueTimeouts / mq pattern) + +do + local threshold = 100 + local items = { + { id = "a", ts = 50 }, + { id = "b", ts = 200 }, + } + -- m.ts < ts where ts=threshold from parent env + -- m.ts=50 < 100 -> true; m.ts=200 < 100 -> false + local ts = threshold + local r = query [[ + from + m = items + where + m.ts < ts + ]] + assertEquals(#r, 1) + assertEquals(r[1].id, "a") +end + +-- 16. Unbound: item fields shadow outer locals + +do + local size = 999 -- this should be shadowed by item.size + local r = query [[ + from + pages + where + size < 10 + select { + name = name, + sz = size, + } + ]] + -- size < 10: Carol(5), Ed(3), Fran(1), Greg(2) -> 4 items + assertEquals(#r, 4) + assertTrue(r[1].sz < 10) +end + +-- 17. Bound: outer locals are accessible + +do + local threshold = 10 + local r = query [[ + from + p = pages + where + p.size > threshold + select { + name = p.name, + } + ]] + -- size > 10: Bob(20), Dave(15) -> 2 + assertEquals(#r, 2) +end + +-- 18. Select with table constructor + non-Variable expressions + +-- 18a. Expression value in PropField +do + local r = query [[ + from + p = pages + select { + label = p.name .. "!", + double = p.size * 2, + } + limit + 2 + ]] + assertEquals(r[1].label, "Alice!") + assertEquals(r[1].double, 20) + assertEquals(r[2].label, "Bob!") + assertEquals(r[2].double, 40) +end + +-- 18b. Unbound expression +do + local r = query [[ + from + pages + select { + label = name .. "!", + double = size * 2, + } + limit + 2 + ]] + assertEquals(r[1].label, "Alice!") + assertEquals(r[1].double, 20) +end + +-- 19. Order by + group by + having + limit combined + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + having + count() > 0 + select { + tag = key, + total = sum(p.size), + } + order by + total desc + limit + 2 + ]] + assertEquals(#r, 2) + assertTrue(r[1].total >= r[2].total) +end + +-- 20. Offset with group by + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + n = count(), + } + order by + tag + limit + 2, 1 + ]] + -- 3 groups sorted by tag, skip 1, take 2 + assertEquals(#r, 2) +end + +-- 21. Where + having + group by combined + do local r = query [[ from @@ -494,17 +1077,494 @@ do group by tags[1] having - min(age) > 25 + #group > 1 + select { + tag = key, + gc = #group, + } + ]] + -- After where (age>20): Alice(31),Bob(25),Carol(41),Dave(52),Fran(55),Greg(63) + -- Groups by tags[1]: work=[Alice,Bob,Greg](3), personal=[Carol,Dave](2), random=[Fran](1) + -- Having #group>1: work(3), personal(2) + assertEquals(#r, 2) +end + +-- Same, bound +do + local r = query [[ + from + p = pages + where + p.age > 20 + group by + p.tags[1] + having + #group > 1 + select { + tag = key, + gc = #group, + } + ]] + assertEquals(#r, 2) +end + +-- 22. Select _ (the whole item, unbound) + +do + local r = query [[ + from + pages + select + _ + limit + 1 + ]] + assertEquals(r[1].name, "Alice") + assertEquals(r[1].size, 10) +end + +-- 23. Group by with order by on key + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] select { tag = key, - p = p and p.name, - total = count(name), - avg_size = avg(size), } order by - avg_size desc - limit 2 + key ]] + assertEquals(r[1].tag, "personal") + assertEquals(r[2].tag, "random") + assertEquals(r[3].tag, "work") +end - assert(#r <= 2) +-- 24. Aggregate on entire dataset (single group) + +do + local r = query [[ + from + p = pages + group by + "all" + select { + total = count(), + min_size = min(p.size), + max_size = max(p.size), + sum_size = sum(p.size), + } + ]] + assertEquals(#r, 1) + assertEquals(r[1].total, 7) + assertEquals(r[1].min_size, 1) + assertEquals(r[1].max_size, 20) + assertEquals(r[1].sum_size, 56) -- 10+20+5+15+3+1+2 +end + +-- 25. Nested field access in group by + +do + local r = query [[ + from + pages + where + tags[1] ~= nil + group by + tags[1] + select { + k = key, + first_name = group[1].name, + first_tag2 = group[1].tags[2], + } + ]] + assertTrue(type(r[1].k) == "string" or r[1].k == nil) +end + +-- 26. Mixed aggregate and non-aggregate in select + +do + local r = query [[ + from + pages + where + tags[1] ~= nil + group by + tags[1] + select { + c = count(name), + v = min(size), + x = p and count(p.name), + } + ]] + assertTrue(type(r[1].c) == "number") +end + +-- 27. Having with #group + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + having + #group >= 2 + select { + tag = key, + gc = #group, + } + ]] + for _, row in ipairs(r) do + assertTrue(row.gc >= 2, "expected group count >= 2, got " .. tostring(row.gc)) + end +end + +-- 28. Order by desc on aggregate + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + sm = sum(p.size), + } + order by + sm desc + ]] + for i = 1, #r - 1 do + assertTrue( + (r[i].sm or 0) >= (r[i + 1].sm or 0), + "expected descending sum order" + ) + end +end + +-- 29. Singleton collection (single object, not array) + +do + local item = { name = "solo", size = 42 } + local r = query [[ + from + item + select { + name = name, + size = size, + } + ]] + assertEquals(#r, 1) + assertEquals(r[1].name, "solo") + assertEquals(r[1].size, 42) +end + +do + local item = { name = "solo", size = 42 } + local r = query [[ + from + p = item + select { + name = p.name, + size = p.size, + } + ]] + assertEquals(#r, 1) + assertEquals(r[1].name, "solo") +end + +-- 30. Where on singleton + +do + local item = { name = "solo", size = 42 } + local r = query [[ + from + item + where + size > 100 + ]] + assertEquals(#r, 0) +end + +do + local item = { name = "solo", size = 42 } + local r = query [[ + from + item + where + size > 10 + select { + name = name, + } + ]] + assertEquals(#r, 1) + assertEquals(r[1].name, "solo") +end + +-- 31. Where with comparison operators + +do + local r = query [[ + from + pages + where + size == 10 + ]] + assertEquals(#r, 1) + assertEquals(r[1].name, "Alice") +end + +do + local r = query [[ + from + pages + where + size >= 15 + ]] + assertEquals(#r, 2) -- Bob(20), Dave(15) +end + +do + local r = query [[ + from + pages + where + size <= 3 + ]] + assertEquals(#r, 3) -- Ed(3), Fran(1), Greg(2) +end + +-- 32. Where with logical operators + +do + local r = query [[ + from + pages + where + size > 10 and age < 40 + ]] + -- Bob: size=20, age=25 -> true + assertEquals(#r, 1) + assertEquals(r[1].name, "Bob") +end + +do + local r = query [[ + from + pages + where + size > 15 or age > 60 + ]] + -- Bob: size=20 -> true; Greg: age=63 -> true + assertEquals(#r, 2) +end + +do + local r = query [[ + from + p = pages + where + p.size > 10 and p.age < 40 + ]] + assertEquals(#r, 1) + assertEquals(r[1].name, "Bob") +end + +-- 33. Where with not + +do + local r = query [[ + from + pages + where + not (size > 10) + ]] + -- size <= 10: Alice(10), Carol(5), Ed(3), Fran(1), Greg(2) -> 5 + assertEquals(#r, 5) +end + +-- 34. Order by with nulls + +do + local data = { + { name = "a", val = 3 }, + { name = "b" }, + { name = "c", val = 1 }, + } + local r = query [[ + from + p = data + select { + name = p.name, + } + order by + p.val + ]] + -- nulls sort last in ascending + assertEquals(r[1].name, "c") + assertEquals(r[2].name, "a") + assertEquals(r[3].name, "b") +end + +-- 35. Select preserves order after where + order by + +do + local r = query [[ + from + p = pages + where + p.size >= 5 + select { + name = p.name, + size = p.size, + } + order by + p.size + ]] + -- size >= 5: Carol(5), Alice(10), Dave(15), Bob(20) in order + assertEquals(r[1].name, "Carol") + assertEquals(r[2].name, "Alice") + assertEquals(r[3].name, "Dave") + assertEquals(r[4].name, "Bob") +end + +-- 36. Multiple group by keys produce composite key table + +do + local data = { + { a = "x", b = 1, v = 10 }, + { a = "x", b = 1, v = 20 }, + { a = "x", b = 2, v = 30 }, + { a = "y", b = 1, v = 40 }, + } + local r = query [[ + from + p = data + group by + p.a, p.b + select { + ka = key[1], + kb = key[2], + total = sum(p.v), + } + order by + ka, kb + ]] + assertEquals(#r, 3) -- (x,1), (x,2), (y,1) + assertEquals(r[1].ka, "x") + assertEquals(r[1].kb, 1) + assertEquals(r[1].total, 30) -- 10+20 + assertEquals(r[2].ka, "x") + assertEquals(r[2].kb, 2) + assertEquals(r[2].total, 30) + assertEquals(r[3].ka, "y") + assertEquals(r[3].total, 40) +end + +-- 37. Having on composite group by + +do + local data = { + { a = "x", b = 1, v = 10 }, + { a = "x", b = 1, v = 20 }, + { a = "x", b = 2, v = 30 }, + { a = "y", b = 1, v = 40 }, + } + local r = query [[ + from + p = data + group by + p.a, p.b + having + count() > 1 + select { + ka = key[1], + kb = key[2], + n = count(), + } + ]] + -- Only (x,1) has 2 items + assertEquals(#r, 1) + assertEquals(r[1].ka, "x") + assertEquals(r[1].kb, 1) + assertEquals(r[1].n, 2) +end + +-- 38. Bound: select p returns full item + +do + local r = query [[ + from + p = pages + select + p + limit + 1 + ]] + assertEquals(r[1].name, "Alice") + assertEquals(r[1].age, 31) + assertEquals(r[1].size, 10) +end + +-- 39. Numeric aggregates with bound and unbound + +do + local nums = { + { val = 10 }, + { val = 20 }, + { val = 30 }, + } + local r = query [[ + from + nums + group by + "all" + select { + mn = min(val), + mx = max(val), + av = avg(val), + sm = sum(val), + ct = count(), + } + ]] + assertEquals(r[1].mn, 10) + assertEquals(r[1].mx, 30) + assertEquals(r[1].av, 20) + assertEquals(r[1].sm, 60) + assertEquals(r[1].ct, 3) +end + +do + local nums = { + { val = 10 }, + { val = 20 }, + { val = 30 }, + } + local r = query [[ + from + n = nums + group by + "all" + select { + mn = min(n.val), + mx = max(n.val), + av = avg(n.val), + sm = sum(n.val), + ct = count(), + } + ]] + assertEquals(r[1].mn, 10) + assertEquals(r[1].mx, 30) + assertEquals(r[1].av, 20) + assertEquals(r[1].sm, 60) + assertEquals(r[1].ct, 3) end diff --git a/client/space_lua/runtime.ts b/client/space_lua/runtime.ts index 3410d446..c621860c 100644 --- a/client/space_lua/runtime.ts +++ b/client/space_lua/runtime.ts @@ -1266,11 +1266,15 @@ export function luaGet( if (obj instanceof LuaTable || obj instanceof LuaEnv) { return obj.get(key, sf); } + // Native JS array access: normalize undefined → null (Lua nil). + // Without this, accessing an out-of-bounds index on a JS array + // leaks JS undefined into the Lua runtime, breaking nil checks + // such as `tags[1] ~= nil` on an empty array. if (typeof key === "number") { - return (obj as any[])[key - 1]; + return (obj as any[])[key - 1] ?? null; } if (isTaggedFloat(key)) { - return (obj as any[])[key.value - 1]; + return (obj as any[])[key.value - 1] ?? null; } // Native JS object const k = toNumKey(key); From 8f193dc402bd6f8dd11b292cc55c4e11c6d233ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Fri, 27 Feb 2026 15:44:26 +0100 Subject: [PATCH 05/22] [LIQ] Fix: preserve queryable collections in query evaluation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Check for already-queryable objects (e.g. `DataStoreQueryCollection`) before `LuaTable` extraction or `luaValueToJS` conversion, preventing them from being destroyed by the collection normalization pipeline. Signed-off-by: Matouš Jan Fialka --- client/space_lua/eval.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/client/space_lua/eval.ts b/client/space_lua/eval.ts index be86a8d2..4df11d9b 100644 --- a/client/space_lua/eval.ts +++ b/client/space_lua/eval.ts @@ -848,9 +848,19 @@ export function evalExpression( sf.withCtx(q.ctx), ); } - if (collection instanceof LuaTable && collection.empty()) { + + // If already a queryable collection (e.g. DataStoreQueryCollection), + // use directly - skip all LuaTable/JS conversion. + if ( + typeof collection === "object" && + collection !== null && + "query" in collection && + typeof (collection as any).query === "function" + ) { + // Already queryable, use as-is + } else if (collection instanceof LuaTable && collection.empty()) { // Empty table → empty array - collection = []; + collection = toCollection([]); } else if (collection instanceof LuaTable) { if (collection.length > 0) { // Array-like table: extract array items, keep as LuaTables @@ -858,15 +868,15 @@ export function evalExpression( for (let i = 1; i <= collection.length; i++) { arr.push(collection.rawGet(i)); } - collection = arr; + collection = toCollection(arr); } else { // Record-like table (no array part): treat as singleton - collection = [collection]; + collection = toCollection([collection]); } + } else { + collection = toCollection(luaValueToJS(collection, sf)); } - collection = toCollection(collection); - // Build up query object const query: LuaCollectionQuery = { objectVariable, @@ -916,7 +926,7 @@ export function evalExpression( } // Always use the possibly-wrapped collection - return collection.query(query, env, sf).then(jsToLuaValue); + return (collection as any).query(query, env, sf).then(jsToLuaValue); }, ); } From f3ed6ec5dd688e696234053413e910625f65c609 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Mon, 2 Mar 2026 11:46:07 +0100 Subject: [PATCH 06/22] Fixes #1863 --- .github/workflows/edge.yml | 4 ++++ .github/workflows/server.yml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/.github/workflows/edge.yml b/.github/workflows/edge.yml index e02737ea..7e9d427e 100644 --- a/.github/workflows/edge.yml +++ b/.github/workflows/edge.yml @@ -44,6 +44,10 @@ jobs: GOOS=windows GOARCH=amd64 go build -o silverbullet.exe . zip silverbullet-server-windows-x86_64.zip silverbullet.exe + # FreeBSD x86_64 + GOOS=freebsd GOARCH=amd64 go build -o silverbullet . + zip silverbullet-server-freebsd-x86_64.zip silverbullet + - name: Update edge release uses: softprops/action-gh-release@v1 env: diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index 0fdadc08..5b2fc36f 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -43,6 +43,10 @@ jobs: # Windows x86_64 GOOS=windows GOARCH=amd64 go build -o silverbullet.exe . zip silverbullet-server-windows-x86_64.zip silverbullet.exe + + # FreeBSD x86_64 + GOOS=freebsd GOARCH=amd64 go build -o silverbullet . + zip silverbullet-server-freebsd-x86_64.zip silverbullet - name: Release uses: softprops/action-gh-release@v1 env: From ff6854f6eefaec6f0a02b6b9407ff73e42e3583a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Mon, 2 Mar 2026 12:34:25 +0100 Subject: [PATCH 07/22] [LIQ] Add `nulls first` / `nulls last` to `order by` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend the `order by` clause with optional `nulls first` and `nulls last` modifiers following standard SQL semantics. Each sort key can independently specify where `nil` values should appear in the result. By default, ascending sorts place nulls last and descending sorts place nulls first. An explicit nulls first or nulls last overrides this default. The `asc` keyword is also now accepted as an explicit alternative to the default ascending direction. Documentation and tests were updated accordingly. Signed-off-by: Matouš Jan Fialka --- client/space_lua/ast.ts | 1 + client/space_lua/eval.ts | 1 + client/space_lua/lua.grammar | 2 +- client/space_lua/parse-lua.js | 22 ++-- client/space_lua/parse-lua.terms.js | 32 ++--- client/space_lua/parse.ts | 22 +++- client/space_lua/query_collection.test.ts | 76 +++++++++++ client/space_lua/query_collection.ts | 14 +- client/space_lua/query_test.lua | 154 ++++++++++++++++++++++ website/Space Lua/Lua Integrated Query.md | 30 ++++- 10 files changed, 314 insertions(+), 40 deletions(-) diff --git a/client/space_lua/ast.ts b/client/space_lua/ast.ts index 49be9293..586f5cfe 100644 --- a/client/space_lua/ast.ts +++ b/client/space_lua/ast.ts @@ -322,6 +322,7 @@ export type LuaOrderBy = { type: "Order"; expression: LuaExpression; direction: "asc" | "desc"; + nulls?: "first" | "last"; } & ASTContext; export type LuaSelectClause = { diff --git a/client/space_lua/eval.ts b/client/space_lua/eval.ts index 4df11d9b..53a12105 100644 --- a/client/space_lua/eval.ts +++ b/client/space_lua/eval.ts @@ -894,6 +894,7 @@ export function evalExpression( query.orderBy = clause.orderBy.map((o) => ({ expr: o.expression, desc: o.direction === "desc", + nulls: o.nulls, })); break; } diff --git a/client/space_lua/lua.grammar b/client/space_lua/lua.grammar index 36d67a2d..0da004cd 100644 --- a/client/space_lua/lua.grammar +++ b/client/space_lua/lua.grammar @@ -104,7 +104,7 @@ FromClause { ckw<"from"> (Name "=")? exp } WhereClause { ckw<"where"> exp } LimitClause { ckw<"limit"> exp ("," exp)? } OrderByClause { ckw<"order"> ckw<"by"> list } -OrderBy { exp ckw<"desc">? } +OrderBy { exp (ckw<"desc"> | ckw<"asc">)? (ckw<"nulls"> (ckw<"first"> | ckw<"last">))? } SelectClause { ckw<"select"> exp } GroupByClause { ckw<"group"> ckw<"by"> list } HavingClause { ckw<"having"> exp } diff --git a/client/space_lua/parse-lua.js b/client/space_lua/parse-lua.js index 57f9ce05..d214195c 100644 --- a/client/space_lua/parse-lua.js +++ b/client/space_lua/parse-lua.js @@ -1,22 +1,22 @@ // This file was generated by lezer-generator. You probably shouldn't edit it. import {LRParser} from "@lezer/lr" -const spec_identifier = {__proto__:null,break:16, goto:20, do:24, end:26, while:30, nil:32, true:34, false:36, or:80, and:82, not:104, function:114, query:122, from:129, where:133, order:137, by:139, desc:143, select:147, limit:151, group:155, having:159, repeat:162, until:164, if:168, then:170, elseif:172, else:174, for:178, in:186, local:196, return:212} +const spec_identifier = {__proto__:null,break:16, goto:20, do:24, end:26, while:30, nil:32, true:34, false:36, or:80, and:82, not:104, function:114, query:122, from:129, where:133, order:137, by:139, desc:143, asc:145, nulls:147, first:149, last:151, select:155, limit:159, group:163, having:167, repeat:170, until:172, if:176,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g#P#QAu#Q;'S?g;'S;=`?y<%lO?goBdT$^SO#PBs#P#QCV#Q;'SBs;'S;=`Ci<%lOBskBvTO#PBs#P#QCV#Q;'SBs;'S;=`Ci<%lOBskCYTO#PBs#P#Q%b#Q;'SBs;'S;=`Ci<%lOBskClP;=`<%lBsoCtPjP#P#QCwnC|O$`n~DRO$Z~~DWOq~~D]O$O~~DbOu~~DgP$Q~!_!`$m", tokenizers: [0, 1, 2, 3, 4], topRules: {"Chunk":[0,2]}, - dynamicPrecedences: {"132":1}, - specialized: [{term: 123, get: (value) => spec_identifier[value] || -1}], - tokenPrec: 4041 + dynamicPrecedences: {"136":1}, + specialized: [{term: 127, get: (value) => spec_identifier[value] || -1}], + tokenPrec: 4137 }) diff --git a/client/space_lua/parse-lua.terms.js b/client/space_lua/parse-lua.terms.js index ade51d75..df3ffa53 100644 --- a/client/space_lua/parse-lua.terms.js +++ b/client/space_lua/parse-lua.terms.js @@ -20,19 +20,19 @@ export const WhereClause = 65, OrderByClause = 67, OrderBy = 70, - SelectClause = 72, - LimitClause = 74, - GroupByClause = 76, - HavingClause = 78, - IfStatement = 83, - ForStatement = 88, - ForNumeric = 90, - ForGeneric = 91, - NameList = 92, - ExpList = 94, - FuncName = 96, - VarList = 100, - AttNameList = 102, - AttName = 103, - Attrib = 104, - ReturnStatement = 105 + SelectClause = 76, + LimitClause = 78, + GroupByClause = 80, + HavingClause = 82, + IfStatement = 87, + ForStatement = 92, + ForNumeric = 94, + ForGeneric = 95, + NameList = 96, + ExpList = 98, + FuncName = 100, + VarList = 104, + AttNameList = 106, + AttName = 107, + Attrib = 108, + ReturnStatement = 109 diff --git a/client/space_lua/parse.ts b/client/space_lua/parse.ts index 723d87fd..415c4b5a 100644 --- a/client/space_lua/parse.ts +++ b/client/space_lua/parse.ts @@ -35,7 +35,7 @@ const luaStyleTags = styleTags({ CompareOp: t.operator, "true false": t.bool, Comment: t.lineComment, - "return break goto do end while repeat until function local if then else elseif in for nil or and not query from where limit select order by desc group having": + "return break goto do end while repeat until function local if then else elseif in for nil or and not query from where limit select order by desc asc nulls first last group having": t.keyword, }); @@ -1258,12 +1258,24 @@ function parseQueryClause(t: ParseTree, ctx: ASTCtx): LuaQueryClause { const orderBy: LuaOrderBy[] = []; for (const child of t.children!) { if (child.type === "OrderBy") { - orderBy.push({ + const kids = child.children!; + let direction: "asc" | "desc" = "asc"; + let nulls: "first" | "last" | undefined; + for (let i = 1; i < kids.length; i++) { + const typ = kids[i].type; + if (typ === "desc") direction = "desc"; + else if (typ === "asc") direction = "asc"; + else if (typ === "first") nulls = "first"; + else if (typ === "last") nulls = "last"; + } + const ob: LuaOrderBy = { type: "Order", - expression: parseExpression(child.children![0], ctx), - direction: child.children![1]?.type === "desc" ? "desc" : "asc", + expression: parseExpression(kids[0], ctx), + direction, ctx: context(child, ctx), - }); + }; + if (nulls) ob.nulls = nulls; + orderBy.push(ob); } } return { diff --git a/client/space_lua/query_collection.test.ts b/client/space_lua/query_collection.test.ts index 098b2db6..b46d12ee 100644 --- a/client/space_lua/query_collection.test.ts +++ b/client/space_lua/query_collection.test.ts @@ -248,3 +248,79 @@ Deno.test("ArrayQueryCollection", async () => { assertEquals(resultUpper[2].letter, "Z"); assertEquals(resultUpper[3].letter, "z"); }); + +Deno.test("ArrayQueryCollection - nulls ordering", async () => { + const rootEnv = new LuaEnv(); + + const collection = new ArrayQueryCollection([ + { name: "alice", priority: 10 }, + { name: "bob", priority: undefined }, + { name: "carol", priority: 50 }, + { name: "dave", priority: undefined }, + { name: "eve", priority: 1 }, + ]); + + // Default: asc nulls last + const r1 = await collection.query( + { + objectVariable: "p", + orderBy: [{ expr: parseExpressionString("p.priority"), desc: false }], + }, + rootEnv, + LuaStackFrame.lostFrame, + {}, + ); + assertEquals(r1[0].name, "eve"); + assertEquals(r1[1].name, "alice"); + assertEquals(r1[2].name, "carol"); + assertEquals(r1[3].priority, undefined); + assertEquals(r1[4].priority, undefined); + + // Default: desc nulls first + const r2 = await collection.query( + { + objectVariable: "p", + orderBy: [{ expr: parseExpressionString("p.priority"), desc: true }], + }, + rootEnv, + LuaStackFrame.lostFrame, + {}, + ); + assertEquals(r2[0].priority, undefined); + assertEquals(r2[1].priority, undefined); + assertEquals(r2[2].name, "carol"); + assertEquals(r2[3].name, "alice"); + assertEquals(r2[4].name, "eve"); + + // Explicit: desc nulls last + const r3 = await collection.query( + { + objectVariable: "p", + orderBy: [{ expr: parseExpressionString("p.priority"), desc: true, nulls: "last" }], + }, + rootEnv, + LuaStackFrame.lostFrame, + {}, + ); + assertEquals(r3[0].name, "carol"); + assertEquals(r3[1].name, "alice"); + assertEquals(r3[2].name, "eve"); + assertEquals(r3[3].priority, undefined); + assertEquals(r3[4].priority, undefined); + + // Explicit: asc nulls first + const r4 = await collection.query( + { + objectVariable: "p", + orderBy: [{ expr: parseExpressionString("p.priority"), desc: false, nulls: "first" }], + }, + rootEnv, + LuaStackFrame.lostFrame, + {}, + ); + assertEquals(r4[0].priority, undefined); + assertEquals(r4[1].priority, undefined); + assertEquals(r4[2].name, "eve"); + assertEquals(r4[3].name, "alice"); + assertEquals(r4[4].name, "carol"); +}); diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 53def980..855987de 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -131,6 +131,7 @@ export { buildItemEnvLocal as buildItemEnv }; export type LuaOrderBy = { expr: LuaExpression; desc: boolean; + nulls?: "first" | "last"; }; /** @@ -440,7 +441,7 @@ async function orderByCompare( aSelectRow?: any, bSelectRow?: any, ): Promise { - for (const { expr, desc } of orderBy) { + for (const { expr, desc, nulls } of orderBy) { const aEnv = mkEnv(objectVariable, a, env, sf); const bEnv = mkEnv(objectVariable, b, env, sf); if (aSelectRow) { @@ -479,11 +480,16 @@ async function orderByCompare( aVal = await evalExpression(expr, aEnv, sf); bVal = await evalExpression(expr, bEnv, sf); } + // Handle nulls positioning const aIsNull = aVal === null || aVal === undefined; const bIsNull = bVal === null || bVal === undefined; - if (aIsNull && bIsNull) continue; - if (aIsNull) return desc ? -1 : 1; - if (bIsNull) return desc ? 1 : -1; + if (aIsNull || bIsNull) { + if (aIsNull && bIsNull) continue; + // Default: nulls last for asc, nulls first for desc + const nullsLast = nulls === "last" || (nulls === undefined && !desc); + if (aIsNull) return nullsLast ? 1 : -1; + return nullsLast ? -1 : 1; + } if ( collation?.enabled && typeof aVal === "string" && diff --git a/client/space_lua/query_test.lua b/client/space_lua/query_test.lua index 3266d43d..0c998389 100644 --- a/client/space_lua/query_test.lua +++ b/client/space_lua/query_test.lua @@ -1568,3 +1568,157 @@ do assertEquals(r[1].sm, 60) assertEquals(r[1].ct, 3) end + +-- 40. Order by with nulls — default behavior + +do + local data = { + { name = "alice", priority = 10 }, + { name = "bob" }, + { name = "carol", priority = 50 }, + { name = "dave" }, + { name = "eve", priority = 1 }, + } + + -- 40a. asc default: nulls last + local r1 = query [[ + from + p = data + select { name = p.name } + order by + p.priority + ]] + assertEquals(r1[1].name, "eve") + assertEquals(r1[2].name, "alice") + assertEquals(r1[3].name, "carol") + -- nulls at end (bob and dave, order between them is unspecified) + assertTrue(r1[4].name == "bob" or r1[4].name == "dave", "expected null-priority item") + assertTrue(r1[5].name == "bob" or r1[5].name == "dave", "expected null-priority item") + + -- 40b. desc default: nulls first + local r2 = query [[ + from + p = data + select { name = p.name } + order by + p.priority desc + ]] + assertTrue(r2[1].name == "bob" or r2[1].name == "dave", "expected null-priority item") + assertTrue(r2[2].name == "bob" or r2[2].name == "dave", "expected null-priority item") + assertEquals(r2[3].name, "carol") + assertEquals(r2[4].name, "alice") + assertEquals(r2[5].name, "eve") +end + +-- 41. Order by with explicit nulls last / nulls first + +do + local data = { + { name = "alice", priority = 10 }, + { name = "bob" }, + { name = "carol", priority = 50 }, + { name = "dave" }, + { name = "eve", priority = 1 }, + } + + -- 41a. desc nulls last (override default) + local r3 = query [[ + from + p = data + select { name = p.name } + order by + p.priority desc nulls last + ]] + assertEquals(r3[1].name, "carol") + assertEquals(r3[2].name, "alice") + assertEquals(r3[3].name, "eve") + assertTrue(r3[4].name == "bob" or r3[4].name == "dave", "expected null-priority item") + assertTrue(r3[5].name == "bob" or r3[5].name == "dave", "expected null-priority item") + + -- 41b. asc nulls first (override default) + local r4 = query [[ + from + p = data + select { name = p.name } + order by + p.priority asc nulls first + ]] + assertTrue(r4[1].name == "bob" or r4[1].name == "dave", "expected null-priority item") + assertTrue(r4[2].name == "bob" or r4[2].name == "dave", "expected null-priority item") + assertEquals(r4[3].name, "eve") + assertEquals(r4[4].name, "alice") + assertEquals(r4[5].name, "carol") +end + +-- 42. Order by nulls with unbound access + +do + local data = { + { name = "a", val = 3 }, + { name = "b" }, + { name = "c", val = 1 }, + } + + -- 42a. desc nulls last, unbound + local r = query [[ + from + data + select { name = name } + order by + val desc nulls last + ]] + assertEquals(r[1].name, "a") + assertEquals(r[2].name, "c") + assertEquals(r[3].name, "b") + + -- 42b. asc nulls first, unbound + local r2 = query [[ + from + data + select { name = name } + order by + val nulls first + ]] + assertEquals(r2[1].name, "b") + assertEquals(r2[2].name, "c") + assertEquals(r2[3].name, "a") +end + +-- 43. Order by nulls with multiple keys + +do + local data = { + { name = "a", x = 1, y = 10 }, + { name = "b", x = 1 }, + { name = "c", x = 2, y = 5 }, + { name = "d", x = 2 }, + } + + local r = query [[ + from + p = data + select { name = p.name } + order by + p.x, p.y nulls first + ]] + assertEquals(r[1].name, "b") + assertEquals(r[2].name, "a") + assertEquals(r[3].name, "d") + assertEquals(r[4].name, "c") +end + +-- 44. Explicit asc keyword (same as default) + +do + local r = query [[ + from + p = pages + select { name = p.name } + order by + p.size asc + limit + 2 + ]] + assertEquals(r[1].name, "Fran") + assertEquals(r[2].name, "Greg") +end diff --git a/website/Space Lua/Lua Integrated Query.md b/website/Space Lua/Lua Integrated Query.md index eac79673..7b439dbf 100644 --- a/website/Space Lua/Lua Integrated Query.md +++ b/website/Space Lua/Lua Integrated Query.md @@ -11,7 +11,7 @@ General syntax: where group by [, , ...] having - order by + order by [asc | desc] [nulls { first | last }][, ...] limit , select ]] @@ -121,8 +121,12 @@ ${query[[ See [[Space Lua/Lua Integrated Query/Grouping]] for detailed examples. -## order by [desc] -The `order by` clause allows you to sort data, when `desc` is specified it reverts the sort order. +## order by [asc | desc] [nulls {first | last}][, ...] +The `order by` clause allows you to sort data. Use `desc` for descending order, or `asc` (the default) for ascending. + +You can control where `nil` values are placed using `nulls first` or `nulls last`. The defaults follow SQL conventions: +- **`asc`**: nulls are placed **last**, +- **`desc`**: nulls are placed **first**. As an example, the last 3 modified pages: ${query[[ @@ -141,6 +145,26 @@ ${query[[ limit 3 ]]} +Override the default null placement with `nulls first` or `nulls last`: + +```lua +query[[ + from p = index.tag "page" + order by p.priority desc nulls last + select { name = p.name, priority = p.priority } +]] +``` + +Each sort key can have its own direction and nulls clause: + +```lua +query[[ + from p = data + order by p.category asc, p.priority desc nulls last + select { name = p.name } +]] +``` + Sorting of strings can be adjusted with `queryCollation` in [[^Library/Std/Config]] ## limit [, ] From 0d49a7b0defc16b4ff4a818b609e9708e6a79fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Mon, 2 Mar 2026 13:44:28 +0100 Subject: [PATCH 08/22] [Space Lua] Load scripts without priority last during reload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The new null-aware ordering in `orderByCompare` changed the default placement of undefined values for descending sorts to `nulls first` (SQL standard). This caused Space Lua scripts without a `-- priority:` comment to load before the `Std` library scripts and breaking the boot sequence for user scripts ran before `schema`, `config`, `widget` and other core definitions were available. Add explicit `nulls: "last"` to the reload query so scripts without priority always load last, matching the documented behavior. Signed-off-by: Matouš Jan Fialka --- client/space_lua.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/client/space_lua.ts b/client/space_lua.ts index aa5d7c14..e68f2a5b 100644 --- a/client/space_lua.ts +++ b/client/space_lua.ts @@ -33,6 +33,7 @@ export class SpaceLuaEnvironment { orderBy: [{ expr: parseExpressionString("script.priority"), desc: true, + nulls: "last", }], } as LuaCollectionQuery, ); From e35b61d050ea2b637128c4a7545af6c61d807200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Mon, 2 Mar 2026 14:07:07 +0100 Subject: [PATCH 09/22] Rename `LUA_SQL_NULL` to `LIQ_NULL` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matouš Jan Fialka --- client/space_lua/query_collection.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 855987de..954c6d55 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -31,10 +31,10 @@ import type { KvKey } from "../../plug-api/types/datastore.ts"; import { executeAggregate, getAggregateSpec } from "./aggregates.ts"; // Sentinel value representing SQL NULL in query results. -export const LUA_SQL_NULL = Symbol.for("silverbullet.sqlNull"); +export const LIQ_NULL = Symbol.for("silverbullet.sqlNull"); export function isSqlNull(v: any): boolean { - return v === LUA_SQL_NULL; + return v === LIQ_NULL; } // Build environment for post-`group by` clauses. Injects `key` and `group` @@ -409,7 +409,7 @@ function normalizeSelectResults(results: any[]): any[] { const v = item.rawGet(k); rebuilt.rawSet( k, - (v === undefined || v === null) ? LUA_SQL_NULL : v, + (v === undefined || v === null) ? LIQ_NULL : v, ); } for (const k of luaKeys(item)) { From b786d65307248dda679c0dc038bf6a1612ac670d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Tue, 3 Mar 2026 08:29:18 +0100 Subject: [PATCH 10/22] [LIQ] Add `filter(where )` clause for per-row aggregate filtering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements `filter(where )` for aggregate functions in LIQ queries which allows per-row conditional filtering within grouped aggregates. Also extends test suite and documentation. Signed-off-by: Matouš Jan Fialka --- client/space_lua/aggregates.ts | 14 +- client/space_lua/ast.ts | 10 +- client/space_lua/lua.grammar | 4 +- client/space_lua/parse-lua.js | 22 +- client/space_lua/parse-lua.terms.js | 24 +- client/space_lua/parse.ts | 27 ++- client/space_lua/query_collection.ts | 34 +++ client/space_lua/query_test.lua | 221 ++++++++++++++++++ .../Lua Integrated Query/Aggregating.md | 39 ++++ 9 files changed, 366 insertions(+), 29 deletions(-) diff --git a/client/space_lua/aggregates.ts b/client/space_lua/aggregates.ts index 8311bc31..96b47198 100644 --- a/client/space_lua/aggregates.ts +++ b/client/space_lua/aggregates.ts @@ -16,6 +16,7 @@ import { luaCall, type LuaEnv, LuaTable, + luaTruthy, type LuaValue, } from "./runtime.ts"; import type { LuaExpression } from "./ast.ts"; @@ -157,8 +158,6 @@ export function getAggregateSpec(name: string): AggregateSpec | null { /** * Execute an aggregate function over a group of items. - * - * `evalExprFn` is passed in to avoid a circular import with eval.ts. */ export async function executeAggregate( spec: AggregateSpec, @@ -172,6 +171,7 @@ export async function executeAggregate( env: LuaEnv, sf: LuaStackFrame, ) => Promise | LuaValue, + filterExpr?: LuaExpression, ): Promise { const ctx = buildAggCtx(spec.name); @@ -182,6 +182,16 @@ export async function executeAggregate( const len = items.length; for (let i = 1; i <= len; i++) { const item = items.rawGet(i); + + // Filter + if (filterExpr) { + const filterEnv = buildItemEnv(objectVariable, item, env, sf); + const filterResult = await evalExprFn(filterExpr, filterEnv, sf); + if (!luaTruthy(filterResult)) { + continue; + } + } + let value: LuaValue; if (valueExpr === null) { value = item; diff --git a/client/space_lua/ast.ts b/client/space_lua/ast.ts index 586f5cfe..5c55bc41 100644 --- a/client/space_lua/ast.ts +++ b/client/space_lua/ast.ts @@ -175,7 +175,8 @@ export type LuaExpression = | LuaUnaryExpression | LuaTableConstructor | LuaFunctionDefinition - | LuaQueryExpression; + | LuaQueryExpression + | LuaFilteredCallExpression; export type LuaNilLiteral = { type: "Nil"; @@ -281,6 +282,13 @@ export type LuaFunctionDefinition = { body: LuaFunctionBody; } & ASTContext; +// Aggregate with per-row filter +export type LuaFilteredCallExpression = { + type: "FilteredCall"; + call: LuaFunctionCallExpression; + filter: LuaExpression; +} & ASTContext; + // Query stuff export type LuaQueryExpression = { type: "Query"; diff --git a/client/space_lua/lua.grammar b/client/space_lua/lua.grammar index 0da004cd..4ccb8a46 100644 --- a/client/space_lua/lua.grammar +++ b/client/space_lua/lua.grammar @@ -82,10 +82,10 @@ exp { UnaryExpression | TableConstructor | FunctionDef { kw<"function"> FuncBody } | - Query + Query | + FilteredCall { FunctionCall ckw<"filter"> "(" ckw<"where"> exp ")" } } - Query { kw<"query"> "[[" QueryClause* "]]" } diff --git a/client/space_lua/parse-lua.js b/client/space_lua/parse-lua.js index d214195c..0f70085a 100644 --- a/client/space_lua/parse-lua.js +++ b/client/space_lua/parse-lua.js @@ -1,22 +1,22 @@ // This file was generated by lezer-generator. You probably shouldn't edit it. import {LRParser} from "@lezer/lr" -const spec_identifier = {__proto__:null,break:16, goto:20, do:24, end:26, while:30, nil:32, true:34, false:36, or:80, and:82, not:104, function:114, query:122, from:129, where:133, order:137, by:139, desc:143, asc:145, nulls:147, first:149, last:151, select:155, limit:159, group:163, having:167, repeat:170, until:172, if:176, then:178, elseif:180, else:182, for:186, in:194, local:204, return:220} +const spec_identifier = {__proto__:null,break:16, goto:20, do:24, end:26, while:30, nil:32, true:34, false:36, or:80, and:82, not:104, function:114, query:122, from:129, where:133, order:137, by:139, desc:143, asc:145, nulls:147, first:149, last:151, select:155, limit:159, group:163, having:167, filter:171, repeat:174, until:176, if:180, then:182, elseif:184, else:186, for:190, in:198, local:208, return:224} export const parser = LRParser.deserialize({ version: 14, - states: "FvO!ZQPOOOOQO'#Cc'#CcO!UQPO'#CaO!bQPOOOOQO'#FT'#FTO!vQQO'#CwO$]QPO'#FSOOQO'#FS'#FSO$gQPO'#FSOOQO'#Eh'#EhO%vQPO'#EgOOQO'#FO'#FOOOQO'#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w#Q;'S6x;'S;=`=i<%lO6xk:vVO!_8^!_!`;]!`#P8^#P#Q7t#Q;'S8^;'S;=`8p<%lO8^k;`TO#P8^#P#Q;o#Q;'S8^;'S;=`8p<%lO8^k;tP#wk!_!`7zk;zVO!_7b!_!`:s!`#P7b#P#QR#Q;'S=o;'S;=`>}<%lO=ok>UVO!_>k!_!`?T!`#P>k#P#Q@X#Q;'S>k;'S;=`Ao<%lO>kk>nTO#P=o#P#Q7z#Q;'S=o;'S;=`>}<%lO=ok?QP;=`<%l=ok?WTO#P?g#P#Q@P#Q;'S?g;'S;=`?y<%lO?gk?jTO#P?g#P#Q7z#Q;'S?g;'S;=`?y<%lO?gk?|P;=`<%l?gk@UP#wk!_!`8Qk@[VO!_=o!_!`@q!`#P=o#P#QAu#Q;'S=o;'S;=`>}<%lO=ok@tTO#P=o#P#QAT#Q;'S=o;'S;=`>}<%lO=okAYV#wkO!_>k!_!`?T!`#P>k#P#Q@X#Q;'S>k;'S;=`Ao<%lO>kkArP;=`<%l>kkAxVO!_?g!_!`?T!`#P?g#P#QAu#Q;'S?g;'S;=`?y<%lO?goBdT$`SO#PBs#P#QCV#Q;'SBs;'S;=`Ci<%lOBskBvTO#PBs#P#QCV#Q;'SBs;'S;=`Ci<%lOBskCYTO#PBs#P#Q%b#Q;'SBs;'S;=`Ci<%lOBskClP;=`<%lBsoCtPjP#P#QCwnC|O$bn~DRO$]~~DWOq~~D]O$Q~~DbOu~~DgP$S~!_!`$m", tokenizers: [0, 1, 2, 3, 4], topRules: {"Chunk":[0,2]}, - dynamicPrecedences: {"136":1}, - specialized: [{term: 127, get: (value) => spec_identifier[value] || -1}], - tokenPrec: 4137 + dynamicPrecedences: {"138":1}, + specialized: [{term: 129, get: (value) => spec_identifier[value] || -1}], + tokenPrec: 4451 }) diff --git a/client/space_lua/parse-lua.terms.js b/client/space_lua/parse-lua.terms.js index df3ffa53..f4d2459f 100644 --- a/client/space_lua/parse-lua.terms.js +++ b/client/space_lua/parse-lua.terms.js @@ -24,15 +24,15 @@ export const LimitClause = 78, GroupByClause = 80, HavingClause = 82, - IfStatement = 87, - ForStatement = 92, - ForNumeric = 94, - ForGeneric = 95, - NameList = 96, - ExpList = 98, - FuncName = 100, - VarList = 104, - AttNameList = 106, - AttName = 107, - Attrib = 108, - ReturnStatement = 109 + IfStatement = 89, + ForStatement = 94, + ForNumeric = 96, + ForGeneric = 97, + NameList = 98, + ExpList = 100, + FuncName = 102, + VarList = 106, + AttNameList = 108, + AttName = 109, + Attrib = 110, + ReturnStatement = 111 diff --git a/client/space_lua/parse.ts b/client/space_lua/parse.ts index 415c4b5a..62b23998 100644 --- a/client/space_lua/parse.ts +++ b/client/space_lua/parse.ts @@ -35,7 +35,7 @@ const luaStyleTags = styleTags({ CompareOp: t.operator, "true false": t.bool, Comment: t.lineComment, - "return break goto do end while repeat until function local if then else elseif in for nil or and not query from where limit select order by desc asc nulls first last group having": + "return break goto do end while repeat until function local if then else elseif in for nil or and not query from where limit select order by desc asc nulls first last group having filter": t.keyword, }); @@ -153,6 +153,11 @@ function expressionHasFunctionDef(e: LuaExpression): boolean { } } return false; + case "FilteredCall": + return ( + expressionHasFunctionDef(e.call) || + expressionHasFunctionDef(e.filter) + ); default: return false; } @@ -241,6 +246,11 @@ function exprReferencesNames(e: LuaExpression, names: Set): boolean { } } return false; + case "FilteredCall": + return ( + exprReferencesNames(e.call, names) || + exprReferencesNames(e.filter, names) + ); default: return false; } @@ -546,6 +556,11 @@ function exprCapturesNames(e: LuaExpression, names: Set): boolean { } } return false; + case "FilteredCall": + return ( + exprCapturesNames(e.call, names) || + exprCapturesNames(e.filter, names) + ); default: return false; } @@ -1208,6 +1223,16 @@ function parseExpression(t: ParseTree, ctx: ASTCtx): LuaExpression { clauses: t.children!.slice(2, -1).map((c) => parseQueryClause(c, ctx)), ctx: context(t, ctx), }; + case "FilteredCall": { + const call = parseFunctionCall(t.children![0], ctx); + const filterExpr = parseExpression(t.children![4], ctx); + return { + type: "FilteredCall", + call, + filter: filterExpr, + ctx: context(t, ctx), + }; + } default: console.error(t); throw new Error(`Unknown expression type: ${t.type}`); diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 954c6d55..2765da9a 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -3,6 +3,7 @@ import type { LuaDynamicField, LuaExpression, LuaExpressionField, + LuaFilteredCallExpression, LuaFunctionCallExpression, LuaParenthesizedExpression, LuaPropField, @@ -197,6 +198,14 @@ export function toCollection(obj: any): LuaQueryCollection { function containsAggregate(expr: LuaExpression): boolean { switch (expr.type) { + case "FilteredCall": { + const fc = (expr as LuaFilteredCallExpression).call; + if (fc.prefix.type === "Variable" && getAggregateSpec(fc.prefix.name)) { + return true; + } + return containsAggregate(fc) || + containsAggregate((expr as LuaFilteredCallExpression).filter); + } case "FunctionCall": { const fc = expr as LuaFunctionCallExpression; if (fc.prefix.type === "Variable" && getAggregateSpec(fc.prefix.name)) { @@ -263,6 +272,31 @@ export async function evalExpressionWithAggregates( objectVariable, outerEnv, ); + + if (expr.type === "FilteredCall") { + const filtered = expr as LuaFilteredCallExpression; + const fc = filtered.call; + if (fc.prefix.type === "Variable") { + const name = fc.prefix.name; + const spec = getAggregateSpec(name); + if (spec) { + const valueExpr = fc.args.length > 0 ? fc.args[0] : null; + return executeAggregate( + spec, + groupItems, + valueExpr, + objectVariable, + outerEnv, + sf, + evalExpression, + filtered.filter, + ); + } + } + + return evalExpression(expr, env, sf); + } + if (expr.type === "FunctionCall") { const fc = expr as LuaFunctionCallExpression; if (fc.prefix.type === "Variable") { diff --git a/client/space_lua/query_test.lua b/client/space_lua/query_test.lua index 0c998389..9830103b 100644 --- a/client/space_lua/query_test.lua +++ b/client/space_lua/query_test.lua @@ -1722,3 +1722,224 @@ do assertEquals(r[1].name, "Fran") assertEquals(r[2].name, "Greg") end + +-- 45. Count with filter + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + total = count(), + big = count(p.name) filter(where p.size > 10), + } + order by + tag + ]] + -- personal: Carol(5),Dave(15) -> big=1 (Dave) + -- random: Fran(1) -> big=0 + -- work: Alice(10),Bob(20),Greg(2) -> big=1 (Bob) + assertEquals(#r, 3) + for _, row in ipairs(r) do + if row.tag == "personal" then + assertEquals(row.big, 1) + assertEquals(row.total, 2) + elseif row.tag == "random" then + assertEquals(row.big, 0) + assertEquals(row.total, 1) + elseif row.tag == "work" then + assertEquals(row.big, 1) + assertEquals(row.total, 3) + end + end +end + +-- 46. Sum with filter + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + total_size = sum(p.size), + big_size = sum(p.size) filter(where p.size > 5), + } + order by + tag + ]] + for _, row in ipairs(r) do + if row.tag == "work" then + -- Alice(10)+Bob(20)+Greg(2)=32 total, big: 10+20=30 + assertEquals(row.total_size, 32) + assertEquals(row.big_size, 30) + elseif row.tag == "personal" then + -- Carol(5)+Dave(15)=20 total, big: 15 + assertEquals(row.total_size, 20) + assertEquals(row.big_size, 15) + elseif row.tag == "random" then + -- Fran(1) total=1, big: 0 (none pass) + assertEquals(row.total_size, 1) + assertEquals(row.big_size, 0) + end + end +end + +-- 47. Min/max with filter + +do + local r = query [[ + from + p = pages + group by + "all" + select { + min_big = min(p.size) filter(where p.size > 5), + max_small = max(p.size) filter(where p.size <= 5), + } + ]] + assertEquals(#r, 1) + assertEquals(r[1].min_big, 10) -- smallest > 5: Alice(10) + assertEquals(r[1].max_small, 5) -- largest <= 5: Carol(5) +end + +-- 48. Avg with filter + +do + local r = query [[ + from + p = pages + group by + "all" + select { + avg_all = avg(p.size), + avg_big = avg(p.size) filter(where p.size >= 10), + } + ]] + assertEquals(#r, 1) + -- all: (10+20+5+15+3+1+2)/7 = 56/7 = 8 + assertEquals(r[1].avg_all, 8) + -- big (>=10): (10+20+15)/3 = 45/3 = 15 + assertEquals(r[1].avg_big, 15) +end + +-- 49. Array_agg with filter + +do + local r = query [[ + from + p = pages + group by + "all" + select { + all_names = array_agg(p.name), + big_names = array_agg(p.name) filter(where p.size > 10), + } + ]] + assertEquals(#r, 1) + assertEquals(#r[1].all_names, 7) + -- size > 10: Bob(20), Dave(15) + assertEquals(#r[1].big_names, 2) +end + +-- 50. Unbound access in filter + +do + local r = query [[ + from + pages + where + tags[1] ~= nil + group by + tags[1] + select { + tag = key, + big = count(name) filter(where size > 10), + } + order by + tag + ]] + for _, row in ipairs(r) do + if row.tag == "work" then + assertEquals(row.big, 1) -- Bob(20) + end + end +end + +-- 51. Count without argument with filter + +do + local r = query [[ + from + p = pages + group by + "all" + select { + total = count(), + big = count() filter(where p.size > 10), + } + ]] + assertEquals(r[1].total, 7) + assertEquals(r[1].big, 2) -- Bob(20), Dave(15) +end + +-- 52. Filter that matches nothing + +do + local r = query [[ + from + p = pages + group by + "all" + select { + n = count() filter(where p.size > 1000), + s = sum(p.size) filter(where p.size > 1000), + } + ]] + assertEquals(r[1].n, 0) + assertEquals(r[1].s, 0) +end + +-- 53. Multiple filters in one select + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + young = count(p.name) filter(where p.age < 30), + old = count(p.name) filter(where p.age >= 50), + } + order by + tag + ]] + for _, row in ipairs(r) do + if row.tag == "work" then + -- young: Bob(25) -> 1; old: Greg(63) -> 1 + assertEquals(row.young, 1) + assertEquals(row.old, 1) + elseif row.tag == "personal" then + -- young: none; old: Dave(52) -> 1 + assertEquals(row.young, 0) + assertEquals(row.old, 1) + elseif row.tag == "random" then + -- young: none; old: Fran(55) -> 1 + assertEquals(row.young, 0) + assertEquals(row.old, 1) + end + end +end diff --git a/website/Space Lua/Lua Integrated Query/Aggregating.md b/website/Space Lua/Lua Integrated Query/Aggregating.md index aa74cca7..9a8c4f56 100644 --- a/website/Space Lua/Lua Integrated Query/Aggregating.md +++ b/website/Space Lua/Lua Integrated Query/Aggregating.md @@ -142,6 +142,45 @@ ${query [[ } ]]} +## Per-aggregate filtering with `filter(where ...)` + +Individual aggregate expressions can include a `filter(where )` clause to restrict which rows contribute to that specific aggregate. + +Unlike `where` (which filters rows before grouping) and `having` (which filters entire groups after aggregation), `filter(where ...)` applies per-aggregate, per-row within each group. Multiple aggregates in the same `select` can each have different filters. + +```lua +query[[ + from + p = index.tag 'page' + group by + p.tags[1] + select { + tag = key, + total = count(p.name), + big = count(p.name) filter(where p.size > 10), + big_sz = sum(p.size) filter(where p.size > 10) + } + order by + tag +]] +``` +${query [[ + from + p = index.tag 'page' + group by + p.tags[1] + select { + tag = key, + total = count(p.name), + big = count(p.name) filter(where p.size > 10), + big_sz = sum(p.size) filter(where p.size > 10) + } + order by + tag +]]} + +The filter clause works with all aggregate functions: `count`, `sum`, `min`, `max`, `avg`, `array_agg`, and custom aggregates. When no rows match the filter condition, aggregates return their identity value: `0` for `count` and `sum`, `nil` for `min`, `max`, and `avg`, and an empty table `{}` for `array_agg`. + ## Field access after grouping Non-aggregated field references, such as `name` in `select`, refer to the first item in the group, matching common SQL and MySQL semantics. From 7cc39ce62fde1de5996c0faf1f0569f08c620ad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Tue, 3 Mar 2026 09:25:45 +0100 Subject: [PATCH 11/22] Show null/missing query cells as empty instead of `*(null)*` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matouš Jan Fialka --- client/markdown_renderer/result_render.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/client/markdown_renderer/result_render.ts b/client/markdown_renderer/result_render.ts index fdf692f4..36496f86 100644 --- a/client/markdown_renderer/result_render.ts +++ b/client/markdown_renderer/result_render.ts @@ -7,12 +7,9 @@ import { isTaggedFloat } from "../space_lua/numeric.ts"; import { isSqlNull } from "../space_lua/query_collection.ts"; export function defaultTransformer(v: any, _k: string): Promise { - if (v === undefined) { + if (v === undefined || isSqlNull(v)) { return Promise.resolve(""); } - if (isSqlNull(v)) { - return Promise.resolve("*(null)*"); - } if (typeof v === "string") { return Promise.resolve(escapeRegularPipes(v.replaceAll("\n", " "))); } From ba297f66db163865d7c17575783dafcfd63d39cd Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Tue, 3 Mar 2026 10:43:30 +0100 Subject: [PATCH 12/22] Doc tweaks (less duplication of queryies and more use of bound queries) --- .../Lua Integrated Query/Aggregating.md | 142 +++--------------- .../Lua Integrated Query/Grouping.md | 94 +++--------- 2 files changed, 49 insertions(+), 187 deletions(-) diff --git a/website/Space Lua/Lua Integrated Query/Aggregating.md b/website/Space Lua/Lua Integrated Query/Aggregating.md index 9a8c4f56..8c62c23f 100644 --- a/website/Space Lua/Lua Integrated Query/Aggregating.md +++ b/website/Space Lua/Lua Integrated Query/Aggregating.md @@ -15,31 +15,15 @@ Field names used in `group by` are exposed as locals in `having`, `select`, and > The `having` clause acts only on grouped output. For filtering individual items, use `where` prior to grouping. # Examples - -All queries operate on `index.tag 'page'`. +All example queries operate on `tags.page`, but will work with any query collection. As always, to see the underlying query, hover over the result table and click the _Edit_ button to see the underlying query. ## Counting with and without binding - Grouping pages by their first tag, and computing the count and aggregate statistics: -**Without binding variable:** - -```lua -query[[from - index.tag 'page' -group by - tags[1] -select { - tag = key, - total = count(name), - min_size = min(size), - max_size = max(size), - avg_size = avg(size) -}]] -``` +**Without binding variable** ${query [[ from - index.tag 'page' + tags.page group by tags[1] select { @@ -49,28 +33,13 @@ ${query [[ max_size = max(size), avg_size = avg(size) } + order by total desc ]]} -**With binding variable:** - -```lua -query[[ - from - p = index.tag 'page' - group by - p.tags[1] - select { - tag = key, - total = count(p.name), - min_size = min(p.size), - max_size = max(p.size), - avg_size = avg(p.size) - } -]] -``` +**With binding variable** ${query [[ from - p = index.tag 'page' + p = tags.page group by p.tags[1] select { @@ -80,90 +49,43 @@ ${query [[ max_size = max(p.size), avg_size = avg(p.size) } + order by total desc ]]} ## Multi-key grouping and aggregate - -```lua -query[[ +${query[[ from - index.tag 'page' + p = tags.page group by - tags[1], - tags[2] + p.tags[1], + p.tags[2] select { first = key[1], second = key[2], - count = count(name) - } -]] -``` -${query [[ - from - index.tag 'page' - group by - tags[1], - tags[2] - select { - first = key[1], - second = key[2], - count = count(name) + count = count(p.name) } ]]} ## Group filtering with `having` and aggregates - -Only groups with more than two items: - -```lua -query[[ +Only groups with more than two items and at least one tag set: +${query[[ from - index.tag 'page' + p = tags.page group by - tags[1] + p.tags[1] having - count(name) > 2 + count(p.name) > 2 and key select { tag = key, - total = count(name) - } -]] -``` -${query [[ - from - index.tag 'page' - group by - tags[1] - having - count(name) > 2 - select { - tag = key, - total = count(name) + total = count(p.name) } ]]} ## Per-aggregate filtering with `filter(where ...)` - Individual aggregate expressions can include a `filter(where )` clause to restrict which rows contribute to that specific aggregate. Unlike `where` (which filters rows before grouping) and `having` (which filters entire groups after aggregation), `filter(where ...)` applies per-aggregate, per-row within each group. Multiple aggregates in the same `select` can each have different filters. -```lua -query[[ - from - p = index.tag 'page' - group by - p.tags[1] - select { - tag = key, - total = count(p.name), - big = count(p.name) filter(where p.size > 10), - big_sz = sum(p.size) filter(where p.size > 10) - } - order by - tag -]] -``` ${query [[ from p = index.tag 'page' @@ -182,39 +104,23 @@ ${query [[ The filter clause works with all aggregate functions: `count`, `sum`, `min`, `max`, `avg`, `array_agg`, and custom aggregates. When no rows match the filter condition, aggregates return their identity value: `0` for `count` and `sum`, `nil` for `min`, `max`, and `avg`, and an empty table `{}` for `array_agg`. ## Field access after grouping - Non-aggregated field references, such as `name` in `select`, refer to the first item in the group, matching common SQL and MySQL semantics. -```lua -query[[ - from - index.tag 'page' - group by - tags[1] - select { - tag = key, - first_page = name, - n = count(name) - } -]] -``` ${query [[ from - index.tag 'page' + p = tags.page group by - tags[1] + p.tags[1] select { tag = key, - first_page = name, - n = count(name) + first_page = p.name, + n = count(p.name) } ]]} ## Custom aggregators - Custom aggregator functions may be defined by the user using [[Library/Std/APIs/Aggregate|dedicated API]]. # See also - -- [[Space Lua/Lua Integrated Query/Grouping]] — grouping queries without aggregation -- [[Space Lua/Lua Integrated Query]] — full LIQ language reference and listing available aggregators +* [[Space Lua/Lua Integrated Query/Grouping]] — grouping queries without aggregation +* [[Space Lua/Lua Integrated Query]] — full LIQ language reference and listing available aggregators diff --git a/website/Space Lua/Lua Integrated Query/Grouping.md b/website/Space Lua/Lua Integrated Query/Grouping.md index 9e8ae8a3..db3d15be 100644 --- a/website/Space Lua/Lua Integrated Query/Grouping.md +++ b/website/Space Lua/Lua Integrated Query/Grouping.md @@ -14,120 +14,76 @@ The field names used in `group by` are also available as bare variables in `havi # Examples -All examples below use `index.tag 'tag'`. +All examples below use `tags.tag`. ## Group by single key - Group all tags by `name`: -```lua -query [[ - from - index.tag 'tag' - group by - name -]] -``` - ${query [[ from - index.tag 'tag' + t = tags.tag group by - name + t.name + limit 5 ]]} ## Group by multiple keys - Group tags by `name` and `parent` together: -```lua -query [[ +${query[[ from - index.tag 'tag' + t = tags.tag group by - name, - parent -]] -``` - -${query [[ - from - index.tag 'tag' - group by - name, - parent + t.name, + t.parent + limit 5 ]]} ## Filter groups by count - Only show tags that appear more than 2 times: -```lua -query [[ +${query[[ from - index.tag 'tag' + t = tags.tag group by - name - having - #group > 2 -]] -``` - -${query [[ - from - index.tag 'tag' - group by - name + t.name having #group > 2 + limit 5 ]]} ## Find unique tags - Tags appearing exactly once: -```lua -query [[ +${query[[ from - index.tag 'tag' + t = tags.tag group by - name - having - #group == 1 -]] -``` - -${query [[ - from - index.tag 'tag' - group by - name + t.name having #group == 1 + select key ]]} ## Filter groups by key value - Only show the group where `name` is "meta": -```lua -query [[ +${query[[ from - index.tag 'tag' + tags.tag group by name having - name == 'meta' -]] -``` + name == "meta" +]]} -${query [[ +${query[[ from - index.tag 'tag' + t = tags.tag group by - name + t.name having - name == 'meta' + t.name == "meta" ]]} ## Multi-key having From 01dd7c1db4f119e8e164c34e7ca3d5f6d5459274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Tue, 3 Mar 2026 14:47:28 +0100 Subject: [PATCH 13/22] [Space Lua] LIQ: Add `using ...` support to `order by` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * support for custom comparators in LIQ `order by` clauses via the `using` keyword. * `using` is mutually exclusive with `asc`/`desc` and accepts either a *named function* or an *inline anonymous function*. The comparator receives two values and returns true if the first should come before the second. * `nulls first`/ `nulls last` works independently of `using`. * `using` is now a reserved keyword (`kw`; this cannot be avoided but the chance to collide with user scripts is negligable), * documentation updated + polished a little Signed-off-by: Matouš Jan Fialka --- client/space_lua/ast.ts | 1 + client/space_lua/eval.ts | 1 + client/space_lua/lua.grammar | 2 +- client/space_lua/parse-lua.js | 22 +-- client/space_lua/parse-lua.terms.js | 32 ++-- client/space_lua/parse.ts | 29 ++- client/space_lua/query_collection.ts | 39 +++- client/space_lua/query_test.lua | 220 ++++++++++++++++++++++ website/Space Lua/Lua Integrated Query.md | 109 ++++++++--- 9 files changed, 400 insertions(+), 55 deletions(-) diff --git a/client/space_lua/ast.ts b/client/space_lua/ast.ts index 5c55bc41..dcbea714 100644 --- a/client/space_lua/ast.ts +++ b/client/space_lua/ast.ts @@ -331,6 +331,7 @@ export type LuaOrderBy = { expression: LuaExpression; direction: "asc" | "desc"; nulls?: "first" | "last"; + using?: string | LuaFunctionBody; } & ASTContext; export type LuaSelectClause = { diff --git a/client/space_lua/eval.ts b/client/space_lua/eval.ts index 53a12105..94cd1741 100644 --- a/client/space_lua/eval.ts +++ b/client/space_lua/eval.ts @@ -895,6 +895,7 @@ export function evalExpression( expr: o.expression, desc: o.direction === "desc", nulls: o.nulls, + using: o.using, })); break; } diff --git a/client/space_lua/lua.grammar b/client/space_lua/lua.grammar index 4ccb8a46..c0cd052e 100644 --- a/client/space_lua/lua.grammar +++ b/client/space_lua/lua.grammar @@ -104,7 +104,7 @@ FromClause { ckw<"from"> (Name "=")? exp } WhereClause { ckw<"where"> exp } LimitClause { ckw<"limit"> exp ("," exp)? } OrderByClause { ckw<"order"> ckw<"by"> list } -OrderBy { exp (ckw<"desc"> | ckw<"asc">)? (ckw<"nulls"> (ckw<"first"> | ckw<"last">))? } +OrderBy { exp (ckw<"desc"> | ckw<"asc"> | kw<"using"> (Name | kw<"function"> FuncBody))? (ckw<"nulls"> (ckw<"first"> | ckw<"last">))? } SelectClause { ckw<"select"> exp } GroupByClause { ckw<"group"> ckw<"by"> list } HavingClause { ckw<"having"> exp } diff --git a/client/space_lua/parse-lua.js b/client/space_lua/parse-lua.js index 0f70085a..bd44f2ce 100644 --- a/client/space_lua/parse-lua.js +++ b/client/space_lua/parse-lua.js @@ -1,22 +1,22 @@ // This file was generated by lezer-generator. You probably shouldn't edit it. import {LRParser} from "@lezer/lr" -const spec_identifier = {__proto__:null,break:16, goto:20, do:24, end:26, while:30, nil:32, true:34, false:36, or:80, and:82, not:104, function:114, query:122, from:129, where:133, order:137, by:139, desc:143, asc:145, nulls:147, first:149, last:151, select:155, limit:159, group:163, having:167, filter:171, repeat:174, until:176, if:180, then:182, elseif:184, else:186, for:190, in:198, local:208, return:224} +const spec_identifier = {__proto__:null,break:16, goto:20, do:24, end:26, while:30, nil:32, true:34, false:36, or:80, and:82, not:104, function:114, query:122, from:129, where:133, order:137, by:139, desc:143, asc:145, using:146, nulls:149, first:151, last:153, select:157, limit:161, group:165, having:169, filter:173, repeat:176, until:178, if:182, then:184, elseif:186, else:188, for:192, in:200, local:210, return:226} export const parser = LRParser.deserialize({ version: 14, - states: "GxO!ZQPOOOOQO'#Cc'#CcO!UQPO'#CaO!bQPOOOOQO'#FV'#FVO!vQQO'#CwO$]QPO'#FUOOQO'#FU'#FUO$gQPO'#FUOOQO'#Ej'#EjO%vQPO'#EiOOQO'#FQ'#FQOOQO'#Eq'#EqO%{QPO'#C_OOQO'#C_'#C_QOQPOOO!UQPO'#CeO&`QPO'#CgO!vQQO'#CjO&gQPO'#EUO!vQQO'#E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SO#PBs#P#QCV#Q;'SBs;'S;=`Ci<%lOBskBvTO#PBs#P#QCV#Q;'SBs;'S;=`Ci<%lOBskCYTO#PBs#P#Q%b#Q;'SBs;'S;=`Ci<%lOBskClP;=`<%lBsoCtPjP#P#QCwnC|O$cn~DRO$^~~DWOq~~D]O$R~~DbOu~~DgP$T~!_!`$m", tokenizers: [0, 1, 2, 3, 4], topRules: {"Chunk":[0,2]}, - dynamicPrecedences: {"138":1}, - specialized: [{term: 129, get: (value) => spec_identifier[value] || -1}], - tokenPrec: 4451 + dynamicPrecedences: {"139":1}, + specialized: [{term: 130, get: (value) => spec_identifier[value] || -1}], + tokenPrec: 4566 }) diff --git a/client/space_lua/parse-lua.terms.js b/client/space_lua/parse-lua.terms.js index f4d2459f..ed589dea 100644 --- a/client/space_lua/parse-lua.terms.js +++ b/client/space_lua/parse-lua.terms.js @@ -20,19 +20,19 @@ export const WhereClause = 65, OrderByClause = 67, OrderBy = 70, - SelectClause = 76, - LimitClause = 78, - GroupByClause = 80, - HavingClause = 82, - IfStatement = 89, - ForStatement = 94, - ForNumeric = 96, - ForGeneric = 97, - NameList = 98, - ExpList = 100, - FuncName = 102, - VarList = 106, - AttNameList = 108, - AttName = 109, - Attrib = 110, - ReturnStatement = 111 + SelectClause = 77, + LimitClause = 79, + GroupByClause = 81, + HavingClause = 83, + IfStatement = 90, + ForStatement = 95, + ForNumeric = 97, + ForGeneric = 98, + NameList = 99, + ExpList = 101, + FuncName = 103, + VarList = 107, + AttNameList = 109, + AttName = 110, + Attrib = 111, + ReturnStatement = 112 diff --git a/client/space_lua/parse.ts b/client/space_lua/parse.ts index 62b23998..830537f7 100644 --- a/client/space_lua/parse.ts +++ b/client/space_lua/parse.ts @@ -35,7 +35,7 @@ const luaStyleTags = styleTags({ CompareOp: t.operator, "true false": t.bool, Comment: t.lineComment, - "return break goto do end while repeat until function local if then else elseif in for nil or and not query from where limit select order by desc asc nulls first last group having filter": + "return break goto do end while repeat until function local if then else elseif in for nil or and not query from where limit select order by desc asc nulls first last group having filter using": t.keyword, }); @@ -143,6 +143,11 @@ function expressionHasFunctionDef(e: LuaExpression): boolean { if (expressionHasFunctionDef(c.orderBy[j].expression)) { return true; } + if ( + c.orderBy[j].using && typeof c.orderBy[j].using !== "string" + ) { + return true; + } } break; case "GroupBy": @@ -236,6 +241,12 @@ function exprReferencesNames(e: LuaExpression, names: Set): boolean { if (exprReferencesNames(c.orderBy[j].expression, names)) { return true; } + if ( + typeof c.orderBy[j].using === "string" && + names.has(c.orderBy[j].using as string) + ) { + return true; + } } break; case "GroupBy": @@ -546,6 +557,10 @@ function exprCapturesNames(e: LuaExpression, names: Set): boolean { if (exprCapturesNames(c.orderBy[j].expression, names)) { return true; } + const u = c.orderBy[j].using; + if (u && typeof u !== "string") { + if (functionBodyCapturesNames(u, names)) return true; + } } break; case "GroupBy": @@ -1286,12 +1301,23 @@ function parseQueryClause(t: ParseTree, ctx: ASTCtx): LuaQueryClause { const kids = child.children!; let direction: "asc" | "desc" = "asc"; let nulls: "first" | "last" | undefined; + let usingVal: string | LuaFunctionBody | undefined; for (let i = 1; i < kids.length; i++) { const typ = kids[i].type; if (typ === "desc") direction = "desc"; else if (typ === "asc") direction = "asc"; else if (typ === "first") nulls = "first"; else if (typ === "last") nulls = "last"; + else if (typ === "using") { + const next = kids[i + 1]; + if (next.type === "function") { + usingVal = parseFunctionBody(kids[i + 2], ctx); + i += 2; + } else { + usingVal = next.children![0].text!; + i++; + } + } } const ob: LuaOrderBy = { type: "Order", @@ -1300,6 +1326,7 @@ function parseQueryClause(t: ParseTree, ctx: ASTCtx): LuaQueryClause { ctx: context(child, ctx), }; if (nulls) ob.nulls = nulls; + if (usingVal !== undefined) ob.using = usingVal; orderBy.push(ob); } } diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 2765da9a..15a7da37 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -4,6 +4,7 @@ import type { LuaExpression, LuaExpressionField, LuaFilteredCallExpression, + LuaFunctionBody, LuaFunctionCallExpression, LuaParenthesizedExpression, LuaPropField, @@ -11,7 +12,9 @@ import type { } from "./ast.ts"; import { + luaCall, LuaEnv, + LuaFunction, luaGet, luaKeys, LuaStackFrame, @@ -133,6 +136,7 @@ export type LuaOrderBy = { expr: LuaExpression; desc: boolean; nulls?: "first" | "last"; + using?: string | LuaFunctionBody; }; /** @@ -456,6 +460,18 @@ function normalizeSelectResults(results: any[]): any[] { return results; } +function resolveUsing( + using: string | LuaFunctionBody | undefined, + env: LuaEnv, + _sf: LuaStackFrame, +): LuaValue | null { + if (using === undefined) return null; + if (typeof using === "string") { + return env.get(using) ?? null; + } + return new LuaFunction(using, env); +} + async function orderByCompare( a: any, b: any, @@ -472,10 +488,13 @@ async function orderByCompare( grouped: boolean, collation: QueryCollationConfig | undefined, collator: Intl.Collator, + resolvedUsing: (LuaValue | null)[], aSelectRow?: any, bSelectRow?: any, ): Promise { - for (const { expr, desc, nulls } of orderBy) { + for (let idx = 0; idx < orderBy.length; idx++) { + const { expr, desc, nulls } = orderBy[idx]; + const usingFn = resolvedUsing[idx]; const aEnv = mkEnv(objectVariable, a, env, sf); const bEnv = mkEnv(objectVariable, b, env, sf); if (aSelectRow) { @@ -524,7 +543,16 @@ async function orderByCompare( if (aIsNull) return nullsLast ? 1 : -1; return nullsLast ? -1 : 1; } - if ( + if (usingFn) { + const aLtB = luaTruthy( + await luaCall(usingFn, [aVal, bVal], sf.astCtx ?? {}, sf), + ); + const bLtA = luaTruthy( + await luaCall(usingFn, [bVal, aVal], sf.astCtx ?? {}, sf), + ); + if (aLtB && !bLtA) return desc ? 1 : -1; + if (bLtA && !aLtB) return desc ? -1 : 1; + } else if ( collation?.enabled && typeof aVal === "string" && typeof bVal === "string" @@ -731,6 +759,11 @@ export async function applyQuery( } const collator = Intl.Collator(collation?.locale, collation?.options); + const resolvedUsing: (LuaValue | null)[] = []; + for (const ob of query.orderBy) { + resolvedUsing.push(resolveUsing(ob.using, env, sf)); + } + if (selectResults) { const indices = results.map((_, i) => i); await asyncQuickSort(indices, (ai, bi) => @@ -745,6 +778,7 @@ export async function applyQuery( grouped, collation, collator, + resolvedUsing, selectResults![ai], selectResults![bi], )); @@ -764,6 +798,7 @@ export async function applyQuery( grouped, collation, collator, + resolvedUsing, )); } } diff --git a/client/space_lua/query_test.lua b/client/space_lua/query_test.lua index 9830103b..17ef01c8 100644 --- a/client/space_lua/query_test.lua +++ b/client/space_lua/query_test.lua @@ -1943,3 +1943,223 @@ do end end end + +-- 54. `using` with named function comparator + +local function reverseAlpha(a, b) + return a > b +end + +do + local r = query [[ + from + p = pages + order by + p.name using reverseAlpha + select p.name + ]] + assertEquals(r[1], "Greg") + assertEquals(r[#r], "Alice") +end + +-- 55. `using` with inline anonymous function + +do + local r = query [[ + from + p = pages + order by + p.size using function(a, b) return a > b end + select { name = p.name, size = p.size } + ]] + assertEquals(r[1].name, "Bob") -- size 20 + assertEquals(r[2].name, "Dave") -- size 15 +end + +-- 56. `using` with `nulls last` + +do + local r = query [[ + from + p = pages + order by + p.tags[1] using function(a, b) return a < b end nulls last + select { name = p.name, tag = p.tags[1] } + ]] + assertEquals(r[#r].name, "Ed") +end + +-- 57. `using` with `nulls first` + +do + local r = query [[ + from + p = pages + order by + p.tags[1] using function(a, b) return a < b end nulls first + select { name = p.name, tag = p.tags[1] } + ]] + assertEquals(r[1].name, "Ed") +end + +-- 58. `using` named function with `nulls last` + +do + local r = query [[ + from + p = pages + order by + p.tags[1] using reverseAlpha nulls last + select { name = p.name, tag = p.tags[1] } + ]] + assertEquals(r[#r].name, "Ed") + assertEquals(r[1].tag, "work") +end + +-- 59. `using` anonymous function with `nulls first` + +do + local r = query [[ + from + p = pages + order by + p.tags[1] using function(a, b) return a < b end nulls first + select { name = p.name, tag = p.tags[1] } + ]] + assertEquals(r[1].name, "Ed") +end + +-- 60. `using` on one key, normal on another + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + order by + p.tags[1] using reverseAlpha, + p.name + select { tag = p.tags[1], name = p.name } + ]] + assertEquals(r[1].tag, "work") + assertEquals(r[1].name, "Alice") +end + +-- 61. Multiple keys with mixed using and desc + +do + local data = { + { name = "a", x = 2, y = 10 }, + { name = "b", x = 1, y = 20 }, + { name = "c", x = 2, y = 5 }, + { name = "d", x = 1, y = 15 }, + } + local r = query [[ + from + p = data + order by + p.x using function(a, b) return a < b end, + p.y desc + select { name = p.name } + ]] + assertEquals(r[1].name, "b") + assertEquals(r[2].name, "d") + assertEquals(r[3].name, "a") + assertEquals(r[4].name, "c") +end + +-- 62. `using` anonymous function with `nulls first` + +do + local data = { + { name = "a", val = 3 }, + { name = "b" }, + { name = "c", val = 1 }, + } + local r = query [[ + from + p = data + order by + p.val using function(a, b) return a > b end nulls first + select { name = p.name } + ]] + assertEquals(r[1].name, "b") + assertEquals(r[2].name, "a") + assertEquals(r[3].name, "c") +end + +-- 63. `using` with group by + aggregate order + +do + local r = query [[ + from + p = pages + where + p.tags[1] ~= nil + group by + p.tags[1] + select { + tag = key, + n = count(), + } + order by + n using function(a, b) return a > b end + ]] + assertEquals(r[1].tag, "work") + assertEquals(r[1].n, 3) + assertEquals(r[#r].n, 1) +end + +-- 64. `using` named function in unbound mode + +do + local function byLen(a, b) + return #a < #b + end + local r = query [[ + from + pages + order by + name using byLen + select name + ]] + assertEquals(r[1], "Ed") +end + +-- 65. `using` anonymous function alone + +do + local r = query [[ + from + p = pages + order by + p.age using function(a, b) return a > b end + select { name = p.name, age = p.age } + ]] + assertEquals(r[1].name, "Greg") -- age 63 + assertEquals(r[#r].name, "Ed") -- age 19 +end + +-- 66. `using` with nulls on different keys + +do + local data = { + { name = "a", x = 1, y = 10 }, + { name = "b", x = 1 }, + { name = "c", x = 2, y = 5 }, + { name = "d", x = 2 }, + } + local r = query [[ + from + p = data + order by + p.x using function(a, b) return a < b end, + p.y using function(a, b) return a < b end nulls first + select { name = p.name } + ]] + assertEquals(r[1].name, "b") + assertEquals(r[2].name, "a") + assertEquals(r[3].name, "d") + assertEquals(r[4].name, "c") +end diff --git a/website/Space Lua/Lua Integrated Query.md b/website/Space Lua/Lua Integrated Query.md index 7b439dbf..2e85bb0a 100644 --- a/website/Space Lua/Lua Integrated Query.md +++ b/website/Space Lua/Lua Integrated Query.md @@ -6,13 +6,16 @@ However, in [[Space Lua]] it is interpreted as an SQL (and [LINQ](https://learn. General syntax: - query[[ - from in + query [[ + from where - group by [, , ...] + group by [, ...] having - order by [asc | desc] [nulls { first | last }][, ...] - limit , + order by + [asc | desc | using ] + [nulls { first | last }] + [, ...] + limit [, ...] select ]] @@ -40,7 +43,7 @@ ${some(query[[ # Clauses Here are the clauses that are currently supported: -## from +## `from` The `from` clause specifies the source of your data. There are two syntactic variants: **Recommended:** With explicit variable binding: @@ -69,7 +72,7 @@ ${query[[from n = {1, 2, 3} select n]]} A more realistic example using `index.tag`: ${query[[from p = index.tag "page" order by p.lastModified select p.name limit 3]]} -## where +## `where` The `where` clause allows you to filter data. When the expression evaluated to a truthy value, the item is included in the result. Example: @@ -84,7 +87,7 @@ Or select based on name (including folder) and a [[API/string|string function]]: ${query[[from p = index.tag "page" where p.name:startsWith("Person")]]} -## group by [, , ...] +## `group by` The `group by` clause groups results by one or more key expressions. After grouping, each result row becomes a table with two fields: - `key` — the group key value (single value for one key, table for multi-key) @@ -103,7 +106,7 @@ ${query[[ See [[Space Lua/Lua Integrated Query/Grouping]] for detailed examples. -## having +## `having` The `having` clause filters groups **after** `group by`. It follows SQL semantics: only group key fields, `key`, and `group` are accessible — use `where` to filter individual rows before grouping. Aggregate functions like `count()`, `sum()`, `min()`, `max()`, and `avg()` can be used in `having` expressions. See [[Space Lua/Lua Integrated Query/Aggregating]] for details. @@ -121,13 +124,16 @@ ${query[[ See [[Space Lua/Lua Integrated Query/Grouping]] for detailed examples. -## order by [asc | desc] [nulls {first | last}][, ...] +## `order by` The `order by` clause allows you to sort data. Use `desc` for descending order, or `asc` (the default) for ascending. You can control where `nil` values are placed using `nulls first` or `nulls last`. The defaults follow SQL conventions: - **`asc`**: nulls are placed **last**, - **`desc`**: nulls are placed **first**. +You can also use custom comparator: +- **`using `**. + As an example, the last 3 modified pages: ${query[[ from p = index.tag "page" @@ -167,7 +173,74 @@ query[[ Sorting of strings can be adjusted with `queryCollation` in [[^Library/Std/Config]] -## limit [, ] +### `using` (custom comparators) +The `using` clause specifies a custom comparator. It is mutually exclusive with `asc`/`desc` — the comparator defines the ordering direction. + +> **note** Note +> `using` is a reserved keyword in Space Lua and cannot be used as a variable name. + +Two forms are supported: + +**Named function** — must accept two arguments and return `true` if the first comes before the second. + +Example: + +```lua +local function byLength(a, b) + return #a < #b +end +``` + +And use the custom comparator function in a query: + +```lua +query [[ + from p = index.tag "page" + order by p.name using byLength + select p.name + limit 5 +]] +``` + +Annonymous functions are also supported. Example: + +${query[[ + from n = {5, 1, 3, 2, 4} + order by n using function(a, b) return a < b end +]]} + +The `nulls` clause works with `using`: + +```lua +query [[ + from + p = index.tag "page" + order + by p.name + using + byLength nulls last + select + p.name +]] +``` + +Each sort key can independently use `asc`/`desc` or `using`, combined with `nulls { first | last }`: + +```lua +query [[ + from p = data + order by + p.category using customCategoryCmp, + p.priority desc nulls last + select { + name = p.name + } +]] +``` + +> **note** When `using` is specified, it overrides any `queryCollation` configuration for that sort key. + +## `limit` The `limit` clause allows you to limit the number of results, optionally with an offset. Example: @@ -178,7 +251,7 @@ You can also specify an offset to skip some results: ${query[[from {1, 2, 3, 4, 5} limit 3, 2]]} -## select +## `select` The `select` clause allows you to transform each item in the result set. If omitted, it defaults to returning the item itself. When used with `group by`, aggregate functions like `sum()`, `count()`, `min()`, `max()`, and `avg()` can be used in the `select` expression to compute values across each group. See [[Space Lua/Lua Integrated Query/Aggregating]] for details. @@ -195,18 +268,6 @@ ${query[[ limit 3 ]]} -# Listing available aggregate functions - -You can list all available aggregator functions (built-ins and custom) using LIQ. - -Example: - -${query [[ - from k, v in pairs(config.get("aggregates", {})) - select { name = k, desc = v.description } - order by name -]]} - # Rendering the output To render the output as a template, you can rely on the fact that queries return Lua tables. For example, to apply a template to render every page as a link: From a1024212ee344f764042d7bb9afb07b43be25877 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Wed, 4 Mar 2026 09:06:11 +0100 Subject: [PATCH 14/22] [LIQ] `order by`: Replace Quicksort with merge sort with SWO violation detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add iterative async stable merge sort (*O(n log n)*). - Replace Quicksort with the new merge sort (kept Quicksort for tables). - Update documentation (reorganize for logical flow, add SWO section with invalid comparator example that really throws). Signed-off-by: Matouš Jan Fialka --- client/space_lua/query_collection.test.ts | 53 ++++++- client/space_lua/query_collection.ts | 174 ++++++++++++++-------- client/space_lua/util.ts | 56 +++++-- website/Space Lua/Lua Integrated Query.md | 88 +++++------ 4 files changed, 245 insertions(+), 126 deletions(-) diff --git a/client/space_lua/query_collection.test.ts b/client/space_lua/query_collection.test.ts index b46d12ee..8c8caf96 100644 --- a/client/space_lua/query_collection.test.ts +++ b/client/space_lua/query_collection.test.ts @@ -1,6 +1,11 @@ import { parseExpressionString } from "./parse.ts"; import { ArrayQueryCollection } from "./query_collection.ts"; -import { LuaEnv, LuaNativeJSFunction, LuaStackFrame } from "./runtime.ts"; +import { + LuaEnv, + LuaNativeJSFunction, + LuaRuntimeError, + LuaStackFrame, +} from "./runtime.ts"; import { assert, assertEquals } from "@std/assert"; Deno.test("ArrayQueryCollection", async () => { @@ -296,7 +301,11 @@ Deno.test("ArrayQueryCollection - nulls ordering", async () => { const r3 = await collection.query( { objectVariable: "p", - orderBy: [{ expr: parseExpressionString("p.priority"), desc: true, nulls: "last" }], + orderBy: [{ + expr: parseExpressionString("p.priority"), + desc: true, + nulls: "last", + }], }, rootEnv, LuaStackFrame.lostFrame, @@ -312,7 +321,11 @@ Deno.test("ArrayQueryCollection - nulls ordering", async () => { const r4 = await collection.query( { objectVariable: "p", - orderBy: [{ expr: parseExpressionString("p.priority"), desc: false, nulls: "first" }], + orderBy: [{ + expr: parseExpressionString("p.priority"), + desc: false, + nulls: "first", + }], }, rootEnv, LuaStackFrame.lostFrame, @@ -324,3 +337,37 @@ Deno.test("ArrayQueryCollection - nulls ordering", async () => { assertEquals(r4[3].name, "alice"); assertEquals(r4[4].name, "carol"); }); + +Deno.test("ArrayQueryCollection - SWO violation detection", async () => { + const rootEnv = new LuaEnv(); + rootEnv.setLocal( + "badCmp", + new LuaNativeJSFunction((a, b) => a <= b), + ); + + const collection = new ArrayQueryCollection([ + { name: "alice", score: 10 }, + { name: "bob", score: 10 }, + { name: "carol", score: 5 }, + ]); + + const { assertRejects } = await import("@std/assert"); + await assertRejects( + () => + collection.query( + { + objectVariable: "p", + orderBy: [{ + expr: parseExpressionString("p.score"), + desc: false, + using: "badCmp", + }], + }, + rootEnv, + LuaStackFrame.lostFrame, + {}, + ), + LuaRuntimeError, + "strict weak ordering", + ); +}); diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 15a7da37..7c72a633 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -17,6 +17,7 @@ import { LuaFunction, luaGet, luaKeys, + LuaRuntimeError, LuaStackFrame, LuaTable, luaTruthy, @@ -24,7 +25,7 @@ import { singleResult, } from "./runtime.ts"; import { evalExpression, luaOp } from "./eval.ts"; -import { asyncQuickSort } from "./util.ts"; +import { asyncMergeSort } from "./util.ts"; import type { DataStore } from "../data/datastore.ts"; import type { KvPrimitives } from "../data/kv_primitives.ts"; @@ -472,9 +473,43 @@ function resolveUsing( return new LuaFunction(using, env); } +// Compare values using a custom comparator with SWO violation detection +async function usingCompare( + luaCmp: LuaValue, + aVal: any, + bVal: any, + originalA: number, + originalB: number, + desc: boolean, + sf: LuaStackFrame, + violated: boolean[], + keyIdx: number, +): Promise { + const res = luaTruthy( + singleResult( + await luaCall(luaCmp, [aVal, bVal], sf.astCtx ?? {}, sf), + ), + ); + const reverseRes = luaTruthy( + singleResult( + await luaCall(luaCmp, [bVal, aVal], sf.astCtx ?? {}, sf), + ), + ); + + // both true means SWO violation + if (res && reverseRes) { + violated[keyIdx] = true; + return originalA < originalB ? -1 : 1; + } + + if (res) return desc ? 1 : -1; + if (reverseRes) return desc ? -1 : 1; + return 0; +} + async function orderByCompare( - a: any, - b: any, + a: { val: any; idx: number }, + b: { val: any; idx: number }, orderBy: LuaOrderBy[], mkEnv: ( ov: string | undefined, @@ -489,30 +524,33 @@ async function orderByCompare( collation: QueryCollationConfig | undefined, collator: Intl.Collator, resolvedUsing: (LuaValue | null)[], - aSelectRow?: any, - bSelectRow?: any, + violated: boolean[], + selectResults: any[] | undefined, ): Promise { for (let idx = 0; idx < orderBy.length; idx++) { const { expr, desc, nulls } = orderBy[idx]; - const usingFn = resolvedUsing[idx]; - const aEnv = mkEnv(objectVariable, a, env, sf); - const bEnv = mkEnv(objectVariable, b, env, sf); - if (aSelectRow) { - for (const k of luaKeys(aSelectRow)) { - const v = luaGet(aSelectRow, k, sf.astCtx ?? null, sf); - aEnv.setLocal(k, isSqlNull(v) ? null : v); + const aEnv = mkEnv(objectVariable, a.val, env, sf); + const bEnv = mkEnv(objectVariable, b.val, env, sf); + if (selectResults) { + const aSelectRow = selectResults[a.idx]; + const bSelectRow = selectResults[b.idx]; + if (aSelectRow) { + for (const k of luaKeys(aSelectRow)) { + const v = luaGet(aSelectRow, k, sf.astCtx ?? null, sf); + aEnv.setLocal(k, isSqlNull(v) ? null : v); + } } - } - if (bSelectRow) { - for (const k of luaKeys(bSelectRow)) { - const v = luaGet(bSelectRow, k, sf.astCtx ?? null, sf); - bEnv.setLocal(k, isSqlNull(v) ? null : v); + if (bSelectRow) { + for (const k of luaKeys(bSelectRow)) { + const v = luaGet(bSelectRow, k, sf.astCtx ?? null, sf); + bEnv.setLocal(k, isSqlNull(v) ? null : v); + } } } let aVal, bVal; if (grouped) { - const aGroup = (a as LuaTable).rawGet("group"); - const bGroup = (b as LuaTable).rawGet("group"); + const aGroup = (a.val as LuaTable).rawGet("group"); + const bGroup = (b.val as LuaTable).rawGet("group"); aVal = await evalExpressionWithAggregates( expr, aEnv, @@ -543,22 +581,27 @@ async function orderByCompare( if (aIsNull) return nullsLast ? 1 : -1; return nullsLast ? -1 : 1; } + const usingFn = resolvedUsing[idx]; if (usingFn) { - const aLtB = luaTruthy( - await luaCall(usingFn, [aVal, bVal], sf.astCtx ?? {}, sf), + const cmp = await usingCompare( + usingFn, + aVal, + bVal, + a.idx, + b.idx, + desc, + sf, + violated, + idx, ); - const bLtA = luaTruthy( - await luaCall(usingFn, [bVal, aVal], sf.astCtx ?? {}, sf), - ); - if (aLtB && !bLtA) return desc ? 1 : -1; - if (bLtA && !aLtB) return desc ? -1 : 1; + if (cmp !== 0) return cmp; } else if ( collation?.enabled && typeof aVal === "string" && typeof bVal === "string" ) { const order = collator.compare(aVal, bVal); - if (order != 0) { + if (order !== 0) { return desc ? -order : order; } } else if (aVal < bVal) { @@ -760,46 +803,55 @@ export async function applyQuery( const collator = Intl.Collator(collation?.locale, collation?.options); const resolvedUsing: (LuaValue | null)[] = []; + const violated: boolean[] = []; for (const ob of query.orderBy) { resolvedUsing.push(resolveUsing(ob.using, env, sf)); + violated.push(false); + } + + // Tag each result with its original index for stable sorting + const tagged = results.map((val, idx) => ({ val, idx })); + + await asyncMergeSort(tagged, (a, b) => + orderByCompare( + a, + b, + query.orderBy!, + mkEnv, + query.objectVariable, + env, + sf, + grouped, + collation, + collator, + resolvedUsing, + violated, + selectResults, + )); + + // Check for SWO violations in comparators + for (let i = 0; i < violated.length; i++) { + if (violated[i]) { + throw new LuaRuntimeError( + `order by #${ + i + 1 + }: 'using' comparator violates strict weak ordering`, + sf, + ); + } } if (selectResults) { - const indices = results.map((_, i) => i); - await asyncQuickSort(indices, (ai, bi) => - orderByCompare( - results[ai], - results[bi], - query.orderBy!, - mkEnv, - query.objectVariable, - env, - sf, - grouped, - collation, - collator, - resolvedUsing, - selectResults![ai], - selectResults![bi], - )); - - results = indices.map((i) => results[i]); - selectResults = indices.map((i) => selectResults![i]); + const reorderedResults: any[] = new Array(tagged.length); + const reorderedSelect: any[] = new Array(tagged.length); + for (let i = 0; i < tagged.length; i++) { + reorderedResults[i] = tagged[i].val; + reorderedSelect[i] = selectResults[tagged[i].idx]; + } + results = reorderedResults; + selectResults = reorderedSelect; } else { - results = await asyncQuickSort(results, (a, b) => - orderByCompare( - a, - b, - query.orderBy!, - mkEnv, - query.objectVariable, - env, - sf, - grouped, - collation, - collator, - resolvedUsing, - )); + results = tagged.map((t) => t.val); } } diff --git a/client/space_lua/util.ts b/client/space_lua/util.ts index 20ab1b55..63afe52d 100644 --- a/client/space_lua/util.ts +++ b/client/space_lua/util.ts @@ -14,9 +14,8 @@ export function evalPromiseValues(vals: any[]): Promise | any[] { } if (promises.length === 0) { return promiseResults; - } else { - return Promise.all(promises).then(() => promiseResults); } + return Promise.all(promises).then(() => promiseResults); } /** @@ -36,18 +35,19 @@ async function getPivot( if (await compare(x, y) < 0) { if (await compare(y, z) < 0) { return y; - } else if (await compare(z, x) < 0) { - return x; - } else { - return z; } - } else if (await compare(y, z) > 0) { - return y; - } else if (await compare(z, x) > 0) { - return x; - } else { + if (await compare(z, x) < 0) { + return x; + } return z; } + if (await compare(y, z) > 0) { + return y; + } + if (await compare(z, x) > 0) { + return x; + } + return z; } /** @@ -94,3 +94,37 @@ export async function asyncQuickSort( } return arr; } + +/** + * iterative async merge sort + * @param arr tagged array of { val, idx } elements + * @param compare async comparator returning <0, 0, or >0 + */ +export async function asyncMergeSort( + arr: { val: any; idx: number }[], + compare: ( + a: { val: any; idx: number }, + b: { val: any; idx: number }, + ) => Promise, +): Promise { + const n = arr.length; + if (n <= 1) return; + const work = new Array(n); + + for (let size = 1; size < n; size *= 2) { + for (let left = 0; left < n; left += 2 * size) { + const mid = Math.min(left + size, n); + const right = Math.min(left + 2 * size, n); + + let i = left, j = mid, k = left; + while (i < mid && j < right) { + const cmp = await compare(arr[i], arr[j]); + if (cmp <= 0) work[k++] = arr[i++]; + else work[k++] = arr[j++]; + } + while (i < mid) work[k++] = arr[i++]; + while (j < right) work[k++] = arr[j++]; + for (let m = left; m < right; m++) arr[m] = work[m]; + } + } +} diff --git a/website/Space Lua/Lua Integrated Query.md b/website/Space Lua/Lua Integrated Query.md index 2e85bb0a..133b6e0c 100644 --- a/website/Space Lua/Lua Integrated Query.md +++ b/website/Space Lua/Lua Integrated Query.md @@ -125,16 +125,10 @@ ${query[[ See [[Space Lua/Lua Integrated Query/Grouping]] for detailed examples. ## `order by` -The `order by` clause allows you to sort data. Use `desc` for descending order, or `asc` (the default) for ascending. - -You can control where `nil` values are placed using `nulls first` or `nulls last`. The defaults follow SQL conventions: -- **`asc`**: nulls are placed **last**, -- **`desc`**: nulls are placed **first**. - -You can also use custom comparator: -- **`using `**. +The `order by` clause sorts results by one or more expressions. By default, sorting is ascending. Append `desc` for descending order, or `asc` to be explicit about ascending. As an example, the last 3 modified pages: + ${query[[ from p = index.tag "page" order by p.lastModified desc @@ -142,7 +136,7 @@ ${query[[ limit 3 ]]} -You can order based on multiple expressions by specifying multiple expressions separated by commas: +You can sort by multiple expressions separated by commas. Each key is evaluated left to right — the second key only matters when the first compares as equal: ${query[[ from p = index.tag "page" @@ -151,48 +145,40 @@ ${query[[ limit 3 ]]} -Override the default null placement with `nulls first` or `nulls last`: - -```lua -query[[ - from p = index.tag "page" - order by p.priority desc nulls last - select { name = p.name, priority = p.priority } -]] -``` - -Each sort key can have its own direction and nulls clause: +Each sort key can have its own direction: ```lua query[[ from p = data - order by p.category asc, p.priority desc nulls last + order by p.category asc, p.priority desc select { name = p.name } ]] ``` -Sorting of strings can be adjusted with `queryCollation` in [[^Library/Std/Config]] +### Null placement +By default, `nil` values follow SQL conventions: they appear **last** for ascending order and **first** for descending order. You can override this per key with `nulls first` or `nulls last`: -### `using` (custom comparators) -The `using` clause specifies a custom comparator. It is mutually exclusive with `asc`/`desc` — the comparator defines the ordering direction. +${query[[ + from p = index.tag "page" + order by p.priority desc nulls last + select { name = p.name, priority = p.priority } + limit 3 +]]} -> **note** Note -> `using` is a reserved keyword in Space Lua and cannot be used as a variable name. +### String collation +Sorting of strings can be adjusted with `queryCollation` in [[^Library/Std/Config]]. -Two forms are supported: +### `using` (custom comparators) +The `using` clause specifies a custom comparator function instead of the default `asc`/`desc` ordering. The two are mutually exclusive — `using` defines both the comparison logic and the direction. -**Named function** — must accept two arguments and return `true` if the first comes before the second. - -Example: +The comparator must accept two arguments and return `true` when the first should come strictly before the second. It can be a named function: ```lua -local function byLength(a, b) +function byLength(a, b) return #a < #b end ``` -And use the custom comparator function in a query: - ```lua query [[ from p = index.tag "page" @@ -202,29 +188,14 @@ query [[ ]] ``` -Annonymous functions are also supported. Example: +Or an anonymous function inline. Example: ${query[[ from n = {5, 1, 3, 2, 4} order by n using function(a, b) return a < b end ]]} -The `nulls` clause works with `using`: - -```lua -query [[ - from - p = index.tag "page" - order - by p.name - using - byLength nulls last - select - p.name -]] -``` - -Each sort key can independently use `asc`/`desc` or `using`, combined with `nulls { first | last }`: +The `nulls` clause works with `using`, and each sort key can independently choose `asc`/`desc` or `using`: ```lua query [[ @@ -238,7 +209,22 @@ query [[ ]] ``` -> **note** When `using` is specified, it overrides any `queryCollation` configuration for that sort key. +When `using` is specified, it overrides any `queryCollation` configuration for that sort key. + +> **note** Note +> `using` is a reserved keyword in Space Lua and cannot be used as a variable name. + +#### Strict weak ordering +A comparator must satisfy **strict weak ordering** (SWO) — if comparing A with B returns `true`, then comparing B with A must return `false`. In practice this means using strict comparisons like `<` or `>` and **never** `<=` or `>=`. + +The query engine validates this at runtime. If comparing two values in both directions both return `true`, the query fails with a clear error: + +${query [[ + from n = {5, 1, 3, 2, 3} + order by n using function(a, b) return a <= b end +]]} + +The query engine uses a *stable merge sort* algorithm with guaranteed performance. Items that compare as equal preserve their original order and an invalid comparator cannot cause an infinite loop or crash — the violation is detected and reported as an error. ## `limit` The `limit` clause allows you to limit the number of results, optionally with an offset. From df998ebc68defc95a324d4089868179c87366aa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Wed, 4 Mar 2026 09:58:43 +0100 Subject: [PATCH 15/22] [LIQ] `order by`: Pre-compute sort keys before merge sort (Schwartzian transform) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Evaluate all `order by` expressions once per item in a decorate pass, then compare cached keys during sort. Reduces Lua eval calls from *O(kn log n)* to *O(kn)* where *k* is the number of sort keys. Signed-off-by: Matouš Jan Fialka --- client/space_lua/query_collection.ts | 129 ++++++++++++++++----------- 1 file changed, 75 insertions(+), 54 deletions(-) diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index 7c72a633..f9193ad0 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -507,9 +507,12 @@ async function usingCompare( return 0; } -async function orderByCompare( - a: { val: any; idx: number }, - b: { val: any; idx: number }, +/** + * Pre-compute all sort keys for each result item (Schwartzian transform) + * and evaluate each `order by` expression exactly once per item + */ +async function precomputeSortKeys( + results: any[], orderBy: LuaOrderBy[], mkEnv: ( ov: string | undefined, @@ -521,56 +524,63 @@ async function orderByCompare( env: LuaEnv, sf: LuaStackFrame, grouped: boolean, + selectResults: any[] | undefined, +): Promise { + const allKeys: any[][] = new Array(results.length); + for (let i = 0; i < results.length; i++) { + const item = results[i]; + const itemEnv = mkEnv(objectVariable, item, env, sf); + if (selectResults) { + const row = selectResults[i]; + if (row) { + for (const k of luaKeys(row)) { + const v = luaGet(row, k, sf.astCtx ?? null, sf); + itemEnv.setLocal(k, isSqlNull(v) ? null : v); + } + } + } + const keys: any[] = new Array(orderBy.length); + for (let j = 0; j < orderBy.length; j++) { + if (grouped) { + const groupTable = (item as LuaTable).rawGet("group"); + keys[j] = await evalExpressionWithAggregates( + orderBy[j].expr, + itemEnv, + sf, + groupTable, + objectVariable, + env, + ); + } else { + keys[j] = await evalExpression(orderBy[j].expr, itemEnv, sf); + } + } + allKeys[i] = keys; + } + return allKeys; +} + +/** + * Compare two items by their pre-computed sort keys without Lua + * expressions evaluation. + */ +async function sortKeyCompare( + a: { val: any; idx: number }, + b: { val: any; idx: number }, + orderBy: LuaOrderBy[], + aKeys: any[], + bKeys: any[], collation: QueryCollationConfig | undefined, collator: Intl.Collator, resolvedUsing: (LuaValue | null)[], violated: boolean[], - selectResults: any[] | undefined, + sf: LuaStackFrame, ): Promise { for (let idx = 0; idx < orderBy.length; idx++) { - const { expr, desc, nulls } = orderBy[idx]; - const aEnv = mkEnv(objectVariable, a.val, env, sf); - const bEnv = mkEnv(objectVariable, b.val, env, sf); - if (selectResults) { - const aSelectRow = selectResults[a.idx]; - const bSelectRow = selectResults[b.idx]; - if (aSelectRow) { - for (const k of luaKeys(aSelectRow)) { - const v = luaGet(aSelectRow, k, sf.astCtx ?? null, sf); - aEnv.setLocal(k, isSqlNull(v) ? null : v); - } - } - if (bSelectRow) { - for (const k of luaKeys(bSelectRow)) { - const v = luaGet(bSelectRow, k, sf.astCtx ?? null, sf); - bEnv.setLocal(k, isSqlNull(v) ? null : v); - } - } - } - let aVal, bVal; - if (grouped) { - const aGroup = (a.val as LuaTable).rawGet("group"); - const bGroup = (b.val as LuaTable).rawGet("group"); - aVal = await evalExpressionWithAggregates( - expr, - aEnv, - sf, - aGroup, - objectVariable, - env, - ); - bVal = await evalExpressionWithAggregates( - expr, - bEnv, - sf, - bGroup, - objectVariable, - env, - ); - } else { - aVal = await evalExpression(expr, aEnv, sf); - bVal = await evalExpression(expr, bEnv, sf); - } + const { desc, nulls } = orderBy[idx]; + const aVal = aKeys[idx]; + const bVal = bKeys[idx]; + // Handle nulls positioning const aIsNull = aVal === null || aVal === undefined; const bIsNull = bVal === null || bVal === undefined; @@ -581,6 +591,7 @@ async function orderByCompare( if (aIsNull) return nullsLast ? 1 : -1; return nullsLast ? -1 : 1; } + const usingFn = resolvedUsing[idx]; if (usingFn) { const cmp = await usingCompare( @@ -809,24 +820,34 @@ export async function applyQuery( violated.push(false); } + // Decorate: pre-compute all sort keys once (Schwartzian transform) + const sortKeys = await precomputeSortKeys( + results, + query.orderBy, + mkEnv, + query.objectVariable, + env, + sf, + grouped, + selectResults, + ); + // Tag each result with its original index for stable sorting const tagged = results.map((val, idx) => ({ val, idx })); + // Sort: compare cached keys only, no Lua eval in comparator await asyncMergeSort(tagged, (a, b) => - orderByCompare( + sortKeyCompare( a, b, query.orderBy!, - mkEnv, - query.objectVariable, - env, - sf, - grouped, + sortKeys[a.idx], + sortKeys[b.idx], collation, collator, resolvedUsing, violated, - selectResults, + sf, )); // Check for SWO violations in comparators From 879bfb811ae37eb7f133ee4a397ef384a25006fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Jan=20Fialka?= Date: Wed, 4 Mar 2026 11:47:28 +0100 Subject: [PATCH 16/22] [LIQ] `group by`: Convert plain JS objects to LuaTable in results MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Items from `index.tag` are stored as plain JS objects when no metatable is defined. The `group by` clause wraps rows in `LuaTable` (`key`, `group`) but leaves the individual `group` items as plain JS objects. This causes `t.keys is not a function` errors when passing `row.group` to APIs like `template.each` that expect `LuaTable` instances. Signed-off-by: Matouš Jan Fialka --- client/space_lua/query_collection.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/client/space_lua/query_collection.ts b/client/space_lua/query_collection.ts index f9193ad0..9713fc19 100644 --- a/client/space_lua/query_collection.ts +++ b/client/space_lua/query_collection.ts @@ -12,6 +12,7 @@ import type { } from "./ast.ts"; import { + jsToLuaValue, luaCall, LuaEnv, LuaFunction, @@ -730,7 +731,14 @@ export async function applyQuery( for (const { key, items } of groups.values()) { const groupTable = new LuaTable(); for (let i = 0; i < items.length; i++) { - groupTable.rawSetArrayIndex(i + 1, items[i]); + const item = items[i]; + groupTable.rawSetArrayIndex( + i + 1, + (item instanceof LuaTable || typeof item !== "object" || + item === null) + ? item + : jsToLuaValue(item), + ); } const row = new LuaTable(); row.rawSet("key", key); From 59c271131b3b7522a177197933fcbb6bcf8e9e25 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 4 Mar 2026 13:31:27 +0100 Subject: [PATCH 17/22] Big website content iteration --- libraries/Library/Std/APIs/Schema.md | 50 ++++++++++- libraries/Library/Std/APIs/Template.md | 61 ++++++++++++- website/API.md | 10 ++- website/API/codeWidget.md | 2 + website/API/dom.md | 2 + website/API/event.md | 2 +- website/API/service.md | 14 ++- website/API/taskState.md | 2 +- website/API/widget.md | 12 +++ website/Architecture.md | 9 ++ website/Aspiring Pages.md | 5 ++ website/Attribute.md | 5 ++ website/Authentication.md | 30 ++++++- website/CONFIG.md | 11 +++ website/Command Palette.md | 4 + website/Command.md | 4 + website/Development.md | 2 + website/Document.md | 4 + website/Event.md | 83 ++++++++++++------ website/Extensions.md | 28 +++++- website/Frontmatter.md | 2 + website/Full Text Search.md | 13 ++- website/Install.md | 2 + website/Install/Binary.md | 2 + website/Install/Configuration.md | 4 +- website/Install/Docker.md | 2 + website/Install/Network and Internet.md | 4 +- website/Keyboard Shortcuts.md | 2 + website/LLM Use.md | 44 +++------- website/Library Manager.md | 7 +- website/Library.md | 5 +- website/Library/Development.md | 2 + website/Link.md | 5 ++ website/Linked Mention.md | 39 ++++++++- website/Linked Tasks.md | 28 +++++- website/Live Preview.md | 17 +++- website/Manual.md | 33 +++++-- website/Markdown/Admonition.md | 5 +- website/Markdown/Fenced Code Block.md | 7 +- website/Markdown/Hashtags.md | 5 ++ website/Meta Page.md | 5 ++ website/Metadata.md | 6 +- website/Object Index.md | 7 +- website/Object.md | 5 ++ website/PWA.md | 26 +++++- website/Page Decorations.md | 3 +- website/Page Picker.md | 4 + website/Page Template.md | 5 ++ website/Page.md | 4 + website/Schema.md | 50 +++++++++-- website/Service.md | 17 ++-- website/Share.md | 6 +- website/SilverBullet.md | 1 + website/Slash Command.md | 41 ++++++++- website/Slash Templates.md | 41 ++++++++- website/Space Lua.md | 6 +- website/Space Lua/Lua Integrated Query.md | 4 + website/Space Lua/Widget.md | 101 ++++++++++++++++++++-- website/Space Style.md | 5 ++ website/Space.md | 4 + website/Sync.md | 5 ++ website/TLS.md | 2 + website/Tag.md | 5 ++ website/Task.md | 5 ++ website/Template.md | 52 ++++++++++- website/Transclusions.md | 5 ++ website/Troubleshooting.md | 26 ++++-- website/Vim.md | 2 + 68 files changed, 859 insertions(+), 152 deletions(-) diff --git a/libraries/Library/Std/APIs/Schema.md b/libraries/Library/Std/APIs/Schema.md index 19568322..fa5d2886 100644 --- a/libraries/Library/Std/APIs/Schema.md +++ b/libraries/Library/Std/APIs/Schema.md @@ -1,6 +1,52 @@ -#meta/api +--- +description: Helper functions for building JSON Schema objects in Lua +tags: meta/api +--- -Utilities to succinctly define JSON schema types in Lua. +Helper functions for succinctly defining JSON Schema types in Lua. Used with [[API/tag#tag.define(spec)]] and [[API/config#config.define(key, schema)]]. + +# API + +## schema.string() +Returns `{type = "string"}`. + +## schema.number() +Returns `{type = "number"}`. + +## schema.boolean() +Returns `{type = "boolean"}`. + +## schema.null() +Returns `{type = "null"}`. + +## schema.array(typ) +Returns an array schema with items of the given type. `typ` can be a type string (e.g. `"string"`) or a full schema table. + +Example: + +```lua +schema.array("string") -- {type = "array", items = {type = "string"}} +schema.array { + type = "object", + properties = { + name = {type = "string"} + } +} +``` + +## schema.nullable(typ) +Allows the given type or null. `typ` can be a type string or a schema table. + +## schema.nullableArray(typ) +An array of the given type, or null. + +## schema.func() +Marker for function-typed values. + +## schema.schema() +Marker for schema-typed values. + +# Implementation ```space-lua -- priority: 101 diff --git a/libraries/Library/Std/APIs/Template.md b/libraries/Library/Std/APIs/Template.md index 3fe1a58f..202e5652 100644 --- a/libraries/Library/Std/APIs/Template.md +++ b/libraries/Library/Std/APIs/Template.md @@ -1,6 +1,61 @@ -#meta/api +--- +description: APIs to create and render templates +tags: meta/api +--- -Implements useful template functions +APIs to create templates from strings or pages, and render query collections using templates. + +# API + +## template.new(templateStr, stripIndent) +Creates a template function from a string. The template string can contain `${expression}` placeholders that will be interpolated when the template is called. Conventionally, template strings typically use `[==[` and `]==]` as delimiters. + +If `stripIndent` is `true` or omitted, leading 4-space indentation is stripped from each line. + +Example: + +```lua +-- the `templates` global table is available for custom templates +templates.greet = template.new [==[Hello ${name}!]==] +``` + +Which elsewhere can be used, either directly: + +```lua +${templates.greet {name = "Pete"}} +``` + +or together with `template.each` (see below): + +```lua +${template.each(query[[from tags.page limit 3]], templates.greet)} +``` + +Resulting in something along the lines of `Hello index!Hello CONFIG!...` + + +## template.each(collection, fn) +Iterates over a collection and applies a template to each element, concatenating the results. Commonly used to render query results. + +Example: + +```lua +${template.each(query[[from index.tag "page" limit 3]], template.new [==[ + * [[${name}]] +]==])} +``` + +# Pre-built templates +The `templates` table contains ready-made templates for common query rendering patterns. These are defined in [[^Library/Std/Infrastructure/Query Templates]]. + +* **`templates.pageItem`** — renders a page as `* [[name]]` +* **`templates.fullPageItem`** — renders a page as `* [[name|name]]` (full path) +* **`templates.taskItem`** — renders a task as a togglable `* [state] [[ref]] name` +* **`templates.itemItem`** — renders an item as `* [[ref]] name` +* **`templates.paragraphItem`** — renders a paragraph as `* [[ref]] text` +* **`templates.tagItem`** — renders a tag as `* [[tag:name|#name]]` + +# Implementation ```space-lua -- priority: 50 @@ -22,7 +77,7 @@ end -- Creates a new template function from a string template function template.new(templateStr, stripIndent) -- Preprocess: strip indentation - if stripIndent == nil or strpIndent == true then + if stripIndent == nil or stripIndent == true then local lines = {} local splitLines = string.split(templateStr, "\n") for _, line in ipairs(splitLines) do diff --git a/website/API.md b/website/API.md index e8895c47..c4ce0bc4 100644 --- a/website/API.md +++ b/website/API.md @@ -1,2 +1,10 @@ This describes the APIs available in [[Space Lua]]: -${widgets.subPages("API")} + +## Syscall APIs +${template.each(query[[ from p = tags["api/syscall"] where p.tag == "page" order by p.name ]], templates.pageItem)} + +## Space Lua APIs +${template.each(query[[ from p = tags["api/space-lua"] where p.tag == "page" order by p.name ]], templates.pageItem)} + +## Lua Standard Library +${template.each(query[[ from p = tags["api/lua"] where p.tag == "page" order by p.name ]], templates.pageItem)} diff --git a/website/API/codeWidget.md b/website/API/codeWidget.md index 83ceeaef..2c4f7921 100644 --- a/website/API/codeWidget.md +++ b/website/API/codeWidget.md @@ -1,3 +1,5 @@ +#api/syscall + The Code Widget API provides functions for managing code widgets in the editor. ### codeWidget.refreshAll() diff --git a/website/API/dom.md b/website/API/dom.md index 12836fad..70a3455c 100644 --- a/website/API/dom.md +++ b/website/API/dom.md @@ -1,3 +1,5 @@ +#api/space-lua + An API to easily build DOM objects through the magic of Lua meta tables. # Usage diff --git a/website/API/event.md b/website/API/event.md index d8af53d0..e5a578c3 100644 --- a/website/API/event.md +++ b/website/API/event.md @@ -25,7 +25,7 @@ Example: event.dispatch("custom.event", {message = "Hello"}) -- Event dispatch with timeout and response handling -local responses = event.dispatchEvent("data.request", {id = 123}, 5000) +local responses = event.dispatch("data.request", {id = 123}, 5000) for _, response in ipairs(responses) do print(response) end diff --git a/website/API/service.md b/website/API/service.md index bfaab554..9ac91798 100644 --- a/website/API/service.md +++ b/website/API/service.md @@ -2,7 +2,15 @@ Exposes a simple service registry API leveraged by various parts of SilverBullet, see [[Service]]. -## Example +# Architecture +Services are built on top of [[Event|Events]]. When a service is defined, it registers two event listeners: + +1. `discover:<>` — for service discovery +2. `service:<>` — for invocation + +Discovery broadcasts on the event bus and collects all matches, sorted by priority. Invocation calls the specific service's `run` callback. + +# Example ```space-lua service.define { selector = "greeter-service", @@ -31,7 +39,7 @@ service.define { To invoke: ${service.invokeBestMatch("greeter-service", "Pete")} and ${service.invokeBestMatch("greeter-service", "Hank")} -## API +# API ### service.define(spec) Defines a service matching a selector. @@ -50,5 +58,5 @@ Return value is a list of tables (can be empty) with keys: ### service.invoke(match, data) Invokes a service match (as returned by [[#service.discover(selector, options)]]). -### service.invokeBest(selector, options) +### service.invokeBestMatch(selector, data) Performs a `discover` based on the selector, then immediately performs and `invoke` on the best match (based on priority). \ No newline at end of file diff --git a/website/API/taskState.md b/website/API/taskState.md index 214a9bd6..e33d3e82 100644 --- a/website/API/taskState.md +++ b/website/API/taskState.md @@ -1,4 +1,4 @@ -#maturity/beta +#maturity/experimental #api/space-lua APIs to define [[Task#Custom states]]. diff --git a/website/API/widget.md b/website/API/widget.md index 4a81a664..b6f6ebef 100644 --- a/website/API/widget.md +++ b/website/API/widget.md @@ -1,3 +1,5 @@ +#api/space-lua + APIs to define widgets in SilverBullet, often used through [[Space Lua#Expressions]]. # Widget types @@ -56,3 +58,13 @@ Shortcut for `widget.new { markdown = text }` Shortcut for `widget.new { html = htmlOrDOM }` Usually used in conjunction with [[API/dom]]. + +## widget.htmlBlock(htmlOrDOM) +Shortcut for `widget.new { html = htmlOrDOM, display = "block" }` + +Block-level version of `widget.html`. + +## widget.markdownBlock(text) +Shortcut for `widget.new { markdown = text, display = "block" }` + +Block-level version of `widget.markdown`. Useful for content that needs to render as a block element (lists, tables, headings, etc.). diff --git a/website/Architecture.md b/website/Architecture.md index 7ded8863..60b06c11 100644 --- a/website/Architecture.md +++ b/website/Architecture.md @@ -1,3 +1,5 @@ +#development + Here is a big-picture (conceptual) architecture of SilverBullet: ```excalidraw url:architecture.excalidraw @@ -27,7 +29,14 @@ Syscalls (system calls) are the abstraction used in SilverBullet to cleanly crea [[Event]] ## Datastore +The DataStore is an (IndexedDB-backed) key-value store that lives in the browser. It serves as the local persistence layer for everything the client needs to keep track of: +* **Object index**: All indexed objects (pages, tasks, items, links, tags, etc.) are stored here, enabling fast local queries via [[Space Lua/Lua Integrated Query]]. +* **File cache**: The [[Sync]] engine stores a local copy of all space files, enabling offline access. +* **Configuration**: Runtime configuration and state. +* **Message queue**: An internal message queue (MQ) used for asynchronous operations. + +The DataStore wraps lower-level `KvPrimitives` (IndexedDB operations) in a user-friendly API with `get`, `set`, `delete`, and batch variants. The [[API/datastore]] syscall API exposes this to Space Lua and plugs. The client interacts with the service worker and server primarily via the [[HTTP API]], which exposes CRUD-style operations on files. diff --git a/website/Aspiring Pages.md b/website/Aspiring Pages.md index f0cabeb1..d6988aef 100644 --- a/website/Aspiring Pages.md +++ b/website/Aspiring Pages.md @@ -1,3 +1,8 @@ +--- +description: An aspiring page is a page that does not yet exist, but is already linked to. +tags: glossary +--- + An aspiring page is a [[Page|page]] that does not yet exist, but is already linked to. Aspiring pages appear in the [[Page Picker]] (with a `Create page` hint) as well as in auto complete when creating [[Link]]. \ No newline at end of file diff --git a/website/Attribute.md b/website/Attribute.md index 329a900e..8ba58414 100644 --- a/website/Attribute.md +++ b/website/Attribute.md @@ -1,3 +1,8 @@ +--- +description: A key-value pair attached to a page or object, used for querying and filtering. +tags: glossary +--- + Attribute syntax can contribute additional [[Metadata]] to various [[Object|Objects]], including: * Pages (although the preferred way is [[Frontmatter]]) diff --git a/website/Authentication.md b/website/Authentication.md index 77954abb..39b0b0fa 100644 --- a/website/Authentication.md +++ b/website/Authentication.md @@ -1,13 +1,35 @@ +#getting-started + SilverBullet supports simple authentication for a single user. -By setting the `SB_USER` environment variable with a username:password combination, you enable authentication for a single user. For instance: +# User authentication +Set the `SB_USER` environment variable with a `username:password` combination to enable authentication: ```shell docker run -e SB_USER=pete:1234 ... ``` -Will let `pete` authenticate with password `1234`. +This allows `pete` to log in with password `1234`. When authentication is enabled, SilverBullet shows a login page on first access. -For more options see [[Install/Configuration]]. +# Remember me +The login page has a "Remember me" checkbox. When checked, the session persists across browser restarts. The session duration defaults to 7 days and can be configured: -Alternatively, or in addition, you can also use an [[Authentication Proxy]]. \ No newline at end of file +* `SB_REMEMBER_ME_HOURS`: Sets session duration in hours (default: 168, i.e. 7 days) + +# Lockout protection +To prevent brute-force attacks, SilverBullet locks out clients after too many failed login attempts: + +* `SB_LOCKOUT_LIMIT`: Number of failed attempts before lockout (default: 10) +* `SB_LOCKOUT_TIME`: Duration of lockout in seconds (default: 60) + +# API authentication +For programmatic access via the [[HTTP API]], you can use bearer token authentication: + +* `SB_AUTH_TOKEN`: Sets a token for `Authorization: Bearer ` style authentication + +This is useful for scripts, automation, or integrating SilverBullet with other tools. + +# Authentication proxy +Alternatively, or in addition, you can use an [[Authentication Proxy]] to delegate authentication to an external system (like Authelia, Authentik, or a reverse proxy's built-in auth). This is common in more complex self-hosted setups. + +For all authentication-related configuration options, see [[Install/Configuration#Authentication]]. diff --git a/website/CONFIG.md b/website/CONFIG.md index 94c34439..bb8c3c05 100644 --- a/website/CONFIG.md +++ b/website/CONFIG.md @@ -67,6 +67,17 @@ config.set { # Custom tag definitions (further detailed in [[API/tag#Use cases]]) ```space-lua +tag.define { + name = "glossary", + schema = { + type = "object", + properties = { + description = { type = "string" }, + }, + required = { "description" }, + }, +} + tag.define { name = "person", transform = function(o) diff --git a/website/Command Palette.md b/website/Command Palette.md index 5c65a2d8..bcf93da9 100644 --- a/website/Command Palette.md +++ b/website/Command Palette.md @@ -1,3 +1,7 @@ +--- +description: The searchable popup for running commands. +tags: glossary +--- The Command Palette is used to explore SilverBullet’s numerous [[Command]] as well as execute them. The UI and its operation is largely the same as the [[Page Picker]]‘s, with a few differences: diff --git a/website/Command.md b/website/Command.md index 4657d7a1..b76faa78 100644 --- a/website/Command.md +++ b/website/Command.md @@ -1,3 +1,7 @@ +--- +description: A named action you can invoke from the command palette or bind to a key. +tags: glossary +--- Commands define actions that SilverBullet can perform. They range from simple edit commands, such as `Text: Bold`, but may be more elaborate such as `Page: Rename`. SilverBullet ships with a lot of commands built in, but custom ones can also be defined using [[Space Lua]] and [[Plugs]]. diff --git a/website/Development.md b/website/Development.md index 6229f802..04fab12c 100644 --- a/website/Development.md +++ b/website/Development.md @@ -1,3 +1,5 @@ +#development + SilverBullet development can happen at various level. At its most basic level, you can do a lot using [[Space Lua]]. If this does not give enough power, you can upgrade to [[Plugs]]. If _that_ doesn’t suffice, you can contribute to SilverBullet’s core (see below). diff --git a/website/Document.md b/website/Document.md index a166506d..fb7d02d4 100644 --- a/website/Document.md +++ b/website/Document.md @@ -1,3 +1,7 @@ +--- +description: A non-page file (such as an image, PDF, or other attachment) stored in your space. +tags: glossary +--- While SilverBullet is aimed at primarily text-based content, life can not fully be represented in text always. Therefore, SilverBullet supports documents. Documents, like [[Page]] ultimately are — once again — just files on disk. Using plugs, documents of specific file types can also be viewed and edited. # Uploading diff --git a/website/Event.md b/website/Event.md index f5bf4dd0..5b8bb096 100644 --- a/website/Event.md +++ b/website/Event.md @@ -1,32 +1,63 @@ -SilverBullet has its own event bus. +--- +description: A named signal that plugs and Lua scripts can listen to and react to. +tags: glossary +--- +SilverBullet has its own event bus that allows different parts of the system to communicate. Events are the foundation for much of SilverBullet's extensibility — features like [[Service]], [[Virtual Pages]], widgets, and custom indexing are all built on top of events. -Events can be subscribed to and dispatched via the [[API/event]] API. Other features, such as [[Service]] are built on top of Events. +# Subscribing to events +Use `event.listen` to subscribe to an event: + +```lua +event.listen { + name = "editor:pageLoaded", + run = function(e) + print("Loaded page: " .. e.data.name) + end +} +``` + +The `run` callback receives an event object with a `data` field containing event-specific information. To see what data an event provides, add a `print` call and check the [[Log|logs]]. + +# Dispatching events +You can dispatch your own custom events: + +```lua +event.dispatch("my-custom-event", {message = "Hello!"}) +``` + +Other scripts can then listen for `my-custom-event`. # Built-in events -Here is a list of built-in events (triggered by SilverBullet’s core). -To use them, simply subscribe to them via [[API/event#event.listen(listenerDef)]], and do a `print` to see what data you receive. Alternatively, grep the code base to see exactly where they are triggered. +Here is a list of built-in events triggered by SilverBullet's core: -* `page:click`: user clicks a location on the page -* `page:index`: page has changed and requested to be indexed (used by [[Object]] indexing) -* `editor:complete`: editor completion triggered, returns completion results -* `slash:complete`: slash completion triggered, returns completion results -* `editor:lint`: request to lint, returns errors -* `editor:init`: editor initialized -* `editor:pageLoaded`: page has loaded in the editor -* `editor:pageReloaded`: page reloaded in the editor (e.g. when it was changed on disk) -* `editor:pageSaving`: page is about to save -* `editor:pageSaved`: page has saved -* `editor:pageCreating`: page is creating (can return a page content object) -* `editor:pageModified`: a change was made to the document (real-time) -* `editor:documentSaving`: a document is about to be saved -* `editor:documentSaved`: a document was saved -* `editor:modeswitch`: triggered between vim mode and non-vim mode -* `editor:fold`: code was folded in the editor -* `editor:unfold`: code was unfolded in the editor -* `plugs:loaded`: plugs were loaded -* `cron:secondPassed`: a second has passed (useful to implement cron-like features) -* `hooks:renderTopWidgets`: top widgets have requested to render (return widgets) -* `hooks:renderBottomWidgets`: bottom widgets have requested to render (return widgets) +## Editor events +* `editor:init`: Editor has initialized +* `editor:pageLoaded`: A page has been loaded in the editor +* `editor:pageReloaded`: A page was reloaded (e.g. after being changed on disk) +* `editor:pageSaving`: A page is about to be saved +* `editor:pageSaved`: A page has been saved +* `editor:pageCreating`: A page is being created (can return content — used by [[Virtual Pages]]) +* `editor:pageModified`: A change was made to the document (fires in real-time) +* `editor:documentSaving`: A document (non-page file) is about to be saved +* `editor:documentSaved`: A document was saved +* `editor:modeswitch`: Toggled between [[Vim]] mode and normal mode +* `editor:fold`: Code was folded in the editor +* `editor:unfold`: Code was unfolded in the editor + +## Interaction events +* `page:click`: User clicked a location on the page +* `editor:complete`: Editor completion triggered — return completion results to extend [[Completion]] +* `slash:complete`: Slash completion triggered — return completion results +* `editor:lint`: Lint request — return errors to show in the editor + +## System events +* `page:index`: A page has changed and needs to be indexed (used by [[Object]] indexing) +* `plugs:loaded`: Plugs were loaded +* `cron:secondPassed`: One second has passed (useful for implementing periodic behavior) + +## Widget events +* `hooks:renderTopWidgets`: Top widgets requested to render — return widgets to display above the page content +* `hooks:renderBottomWidgets`: Bottom widgets requested to render — return widgets to display below the page content # All subscribed events Here’s a dynamically generated list of events that this SilverBullet instance has subscribed to, to give a sense of what’s there: @@ -35,3 +66,5 @@ ${query[[ where not _:startsWith("service:") order by _ ]]} + +See [[API/event]] for the full API reference. diff --git a/website/Extensions.md b/website/Extensions.md index db756f36..aadb27c8 100644 --- a/website/Extensions.md +++ b/website/Extensions.md @@ -1,4 +1,26 @@ -There are various ways the functionality of SilverBullet can be extended: +--- +description: A plug or library that adds functionality to SilverBullet. +tags: glossary +--- -* [[Library]] -* [[Plugs]] +There are several ways to extend the functionality of SilverBullet: + +# Libraries +[[Library|Libraries]] are collections of [[Space Lua]] scripts, templates, and pages that you can install into your space via the [[Library Manager]]. They are the primary extension mechanism and the easiest way to add new features. Libraries can define: + +* Custom [[Command|commands]] +* [[Slash Templates]] +* [[Page Template|Page templates]] +* [[API/widget|Widgets]] +* [[Space Style]] customizations +* [[Virtual Pages]] + +Libraries are distributed as SilverBullet spaces themselves (typically via Git repositories), and managed through the [[Library Manager]]. + +# Space Lua +[[Space Lua]] is SilverBullet's embedded scripting language. You can write scripts directly in `space-lua` fenced code blocks on any page. These scripts are active across your entire space and can define functions, commands, widgets, event handlers, and more. + +Space Lua is the foundation that libraries are built on. See [[Space Lua]] for a full guide. + +# Plugs +[[Plugs]] are the lower-level extension mechanism, written in TypeScript and compiled to WebAssembly. SilverBullet's core functionality (editing, indexing, syncing) is itself implemented as plugs. While more powerful than Space Lua, plugs are harder to develop and distribute. Most users will not need to write plugs — Space Lua and libraries cover the vast majority of use cases. diff --git a/website/Frontmatter.md b/website/Frontmatter.md index 55302413..34ee247d 100644 --- a/website/Frontmatter.md +++ b/website/Frontmatter.md @@ -1,5 +1,7 @@ --- +description: A YAML block at the top of a page that sets page-level attributes. status: Complete +tags: glossary --- Frontmatter is a common format to attach additional metadata (data about data) to markdown documents. Many tools support it as a markdown [[Markdown/Extensions|extension]]. diff --git a/website/Full Text Search.md b/website/Full Text Search.md index cec94c85..2920c591 100644 --- a/website/Full Text Search.md +++ b/website/Full Text Search.md @@ -1,3 +1,12 @@ -While, honestly not amazing, SilverBullet does have full-text search support. +Full-text search is not built into SilverBullet's core distribution. It is available as a library you can install. -To use it, run the ${widgets.commandButton("Search Space")} command. \ No newline at end of file +# Search libraries +Two community search libraries are available: +* **[Silversearch](https://github.com/MrMugame/silversearch)** (recommended) — a more capable search implementation +* **[basic-search](https://github.com/silverbulletmd/basic-search)** — a simpler search that was previously built into SilverBullet + +Install either one via the [[Library Manager]]. + +# Tips +* For structured queries over metadata and objects, use [[Space Lua/Lua Integrated Query]] instead — it's much more powerful for querying attributes, tags, and relationships +* The [[Page Picker]] (`Cmd-k` / `Ctrl-k`) also searches page _names_ and can be faster for finding pages you know the name of \ No newline at end of file diff --git a/website/Install.md b/website/Install.md index 0e805536..3c1f613c 100644 --- a/website/Install.md +++ b/website/Install.md @@ -1,3 +1,5 @@ +#getting-started + Excited to use SilverBullet? Here are three ways for you to deploy it. Also have a look at the note on [[#File systems]] at the end. # localhost (desktop, laptop) diff --git a/website/Install/Binary.md b/website/Install/Binary.md index da4aa512..aef6d53b 100644 --- a/website/Install/Binary.md +++ b/website/Install/Binary.md @@ -1,3 +1,5 @@ +#getting-started + SilverBullet is distributed as a single server binary available for the following platforms: * macOS (Intel and Apple Silicon) (platform name “darwin”) diff --git a/website/Install/Configuration.md b/website/Install/Configuration.md index 3d4386b6..56f81955 100644 --- a/website/Install/Configuration.md +++ b/website/Install/Configuration.md @@ -1,3 +1,5 @@ +#getting-started + SilverBullet is primarily configured via environment variables. This page gives a comprehensive overview of all configuration options. You can set these ad-hoc when running the SilverBullet server, or e.g. in your [[Install/Docker|docker-compose file]]. # General configuration @@ -18,7 +20,7 @@ SilverBullet supports basic authentication for a single user. * `SB_USER`: Sets single-user credentials, e.g. `SB_USER=pete:1234` allows you to login with username “pete” and password “1234”. * `SB_AUTH_TOKEN`: Enables `Authorization: Bearer ` style authentication on the [[HTTP API]]. * `SB_LOCKOUT_LIMIT`: Specifies the number of failed login attempt before locking the user out (for a `SB_LOCKOUT_TIME` specified amount of seconds), defaults to `10` -* `SB_LOCKOUT_TIME`: Specifies the amount of time (in seconds) a client will be blocked until attempting to log back in. +* `SB_LOCKOUT_TIME`: Specifies the amount of time (in seconds) a client will be blocked until attempting to log back in, defaults to `60`. * `SB_REMEMBER_ME_HOURS`: Sets the session duration in hours when "Remember me" is checked during login, defaults to 7 days. # Storage diff --git a/website/Install/Docker.md b/website/Install/Docker.md index c07fdc5a..78f2a8c2 100644 --- a/website/Install/Docker.md +++ b/website/Install/Docker.md @@ -1,3 +1,5 @@ +#getting-started + [Docker](https://www.docker.com/) is a convenient and secure way to install server applications either locally or on a server you control. If you don’t have docker already running on your machine and are macOS user, consider giving [OrbStack](https://orbstack.dev/) a try — it’s a super nice docker experience. Conveniently, SilverBullet is published as a [docker image on GHCR](https://github.com/silverbulletmd/silverbullet/pkgs/container/silverbullet). The image comes in two flavors: diff --git a/website/Install/Network and Internet.md b/website/Install/Network and Internet.md index f429c506..17c22def 100644 --- a/website/Install/Network and Internet.md +++ b/website/Install/Network and Internet.md @@ -1,4 +1,6 @@ -Running SilverBullet locally on your machine is nice, but you likely want to access it from elsewhere as well (other machines on your network, your mobile device), perhaps even from outside your home. +#getting-started + +Running SilverBullet locally on your machine is nice, but you likely want to access it from elsewhere as well (other machines on your network, your mobile device), perhaps even from outside your home. > **note** IMPORTANT > To use SilverBullet from anywhere other than localhost, you have to set up [[TLS]]. SilverBullet does not work (other than via localhost) on URLs other than `https://` ones. diff --git a/website/Keyboard Shortcuts.md b/website/Keyboard Shortcuts.md index 69989867..227d611c 100644 --- a/website/Keyboard Shortcuts.md +++ b/website/Keyboard Shortcuts.md @@ -1,3 +1,5 @@ +#customization + SilverBullet uses [CodeMirror](https://codemirror.net) under the hood, which does the majority of the keyboard handling. In addition, it allows to for customization of (most) keys on a per-command basis. When you open the [[Command Palette]], you will see the currently assigned keyboard shortcut(s). # Modifier keys diff --git a/website/LLM Use.md b/website/LLM Use.md index 58a714be..71228d7c 100644 --- a/website/LLM Use.md +++ b/website/LLM Use.md @@ -1,49 +1,27 @@ -**TL;DR:** Please do not (heavily) use LLM-based coding tools to contribute code to the [main SilverBullet code base](https://github.com/silverbulletmd/silverbullet). Also don’t heavily rely on LLMs to contribute to issues or community discussions (except for language support, if you need it). +**TL;DR:** Please apply caution when using LLM-based coding tools to contribute code to the [main SilverBullet code base](https://github.com/silverbulletmd/silverbullet). Please do not heavily rely on LLMs to contribute to issues or community discussions. -The topic of how to deal with (largely) LLM generated contributions comes up from time to time in SilverBullet. Different open source project take different approaches: some allow them because “it’s the future,” some [decidedly do not](https://ziglang.org/code-of-conduct/). After much deliberation, I decided that for now I’ll put SilverBullet in the latter camp, as in: no thank you. +--- -There are two main reasons for this, the first is _moral_, a second more _practical_. +There is a bubble of people that believe a simple prompt given to an LLM will produce work that is consistently good. This not my experience. While LLM-based agents _can_ be skillfully steered into producing good quality work, there is big population of people without these skills that cause a lot of confusion and noise, also in the SilverBullet community. -# The moral reason -I have been open sourcing code for over 25 years. My goals for doing so include helping people solve similar problems that I have, enjoy and benefit from the software I build, to allow them to adapt, improve, change and learn from it, and to build community. I have always distributed code under the most liberal of licenses (usually MIT), and have been lucky enough that those licenses were not exploited. Until recently, when LLMs came around. +From time to time people “contribute” to issues or the community forums with largely LLM generated text and “analysis.” In the best case this results in a lot of text easily detected as LLM slop and ignored, but at worst it contains inaccurate information that simply detracts the conversation or results in investing time in things (e.g. verifying fake bugs) that are simply hallucinated. This is not helping anybody. -Specifically _not_ on my list of goals was allowing companies to take my code (or content in general) as input to a _ridiculously_ resource-intensive (money, energy, cheap labor) algorithm, and have the result be sold back to me in the form of tokens. Yet, here we are. And while some may have the sentiment that this is fine, and perhaps even legal, I’m not too happy about it. +In the context of code contributions, while sloppy work is not unique to LLMs, the pace and ease in which it is produced definitely is. Since the quality of the work produced by LLMs is all over the place, I have to take it upon myself to carefully review every contribution, not knowing what prompts (if any) or level of understanding (if any) was behind it. -There are various areas in my life where I have to make more pragmatic choices, but in my open source work I feel I can afford to take a stand. +With humans, even in an open source setting, you build some level of relationship and trust over time with people. In the SilverBullet community I have a few contributors from whom I’ve seen the work: I know they can be trusted to do great, and I don’t have to zoom in on every single change. This is vital, and is one of the reasons why a project with the scope size of SilverBullet can still be operated by a single person. When I invest time in giving a detailed code review, I think _learning_ can happen. The person on the other end, or so I would like to believe, considers things they hadn’t considered before, learns more about the internal workings of SilverBullet and future directions I have in mind. -Therefore, the first reason to ask you not to contribute to SilverBullet using AI tools is a **moral** one: these tools are built by scraping all text (natural and code) LLM companies can get their hands on (often in sketchy ways), use scarce resources to train and operate them, and disproportionally benefit companies with highly questionable morals. This is not a cause I am interested in associating or supporting in my leisure time. +The ease and pace at which an AI agent produces a full pull request with meticulous sounding description and thousands of lines of code added is impressive. However, reviewing and commenting on this code can take me _hours or even days_ whereas producing it may only have taken _minutes_. A common approach for “drive by” LLM contributors is to simply copy & paste my well-considered comments back into the chatbot and see what happens. -# The practical reason -The second reason is more practical. While there is a bubble of people that claim that the quality of the work produced by LLMs is amazing, this has not been my experience based on using these tools myself and reviewing the work of these tools done by others. Too often, it is _sloppy_. - -From time to time people “contribute” to issues or the community forums with largely LLM generated text. At best it’s just a lot of text easily detected as LLM slop and ignored, at worst it contains inaccurate information that simply detracts the conversation or results in investing time in things that are simply hallucinated. This is not helpful. - -In the context of code contributions, while sloppy work is not unique to LLMs, the pace and ease in which it produces it definitely is. If I would have enough faith in LLMs to either feel I do not have to do code reviews, or I can delegate all reviews to LLMs — this could _hypothetically_ be ok. However, again, this is not my experience. The work produced by LLMs if often bad, and I have little reason to believe that an LLM code review would detect it. - -This means that _I still have to review everything myself._ - -There is an important difference in reviewing code produced by an LLM and a human. - -With humans, even in an open source setting, you build some level of relationship over time. You build trust. In the SilverBullet project I have a few people where I’ve seen their work, I know they can be trusted to do great, and I don’t have to zoom in on every single change. This is great, and is one of the reasons why a project with the scope size of SilverBullet can still be run by a single person. When I invest time in giving a detailed code review, I think _learning_ can happen. The person on the other end, or so I would like to believe, considers things they hadn’t considered before, learns more about the internal workings of SilverBullet, or potentially about how to write code in general. - -This is not the case with an LLM. Sure, in “best practice” scenarios, the LLM output is first reviewed by a skilled human before being submitted for a code review. My lived experience (also observing my own behavior) is that people get lazy quickly. I have had a period in which I was more trusting of AI coding agents and let them go rampant on the SilverBullet code base. I’m still cleaning up the technical debt and mess that it produced in just a few months, _and I completely missed it at the time_. If I cannot trust _myself_ to do this — and I definitely have an incentive — how can I trust random _others_ to do this? - -This means that I have to review every single line of LLM produced code and never get lazy. I have seen cases where a _comment_ produced by the LLM “documented” a certain behavior, and implemented the opposite. I’ve seen LLMs make mistakes a human could not conceivably make. I’ve seen LLMs making code more “robust” by simply littering it with null checks rather than reasoning about why those may actually happen. The level of attention I have to pay in an LLM generated pull request is _higher_ than when it is produced by a human. There is often a disorienting big discrepancy between how it _looks_ and what it actually _is_. - -The ease and pace at which an AI agent produces a full pull request with meticulous sounding description and thousands of lines of code added (many of which are “tests”) is impressive. However, because of reasons listed before, now _my part starts_. I now have to go through this code for _hours or even days_ that only took _minutes_ to produce. - -This is not a fair game, and I’m not here for it. I’m sure your intention is good, but it’s often simply counter productive. +This is not helpful, nor is it fair game. I’ll assume people’s intentions are good, but the reality is that these contributions are simply counter productive. At scale, they can (and do) kill open source projects. # Enforcement I’m not the type of person that is interested in strict rules and policing. My approach is always to focus on explaining the _why_ and giving context so that people can draw their own conclusions. -If I suspect that your contribution is AI generated, I will likely close it pointing to this policy. I may get it wrong sometimes, I’m sorry about that. I’m only human, consider being the same. +If I suspect that your contribution is AI driven, I will likely close it pointing to this policy. I may get it wrong sometimes, I’m sorry about that. I’m only human, consider remaining the same. # What this means for you -So, is the target audience of SilverBullet just #NoAI people, then? No. _Especially_ a tool like SilverBullet is all about self-expression: your notes, your thoughts, your system, your crazy experiments. I know that people use LLMs to write [[Space Lua]] scripts, and I’m happy for them. I know that LLMs help people do things that they could not do before, and even learn things in the process. That’s great. Open source is all about freedom. Do with it what you like, use it as you like. There is a solid [SilverBullet AI library](https://github.com/justyns/silverbullet-ai) if you’re interested. +Tools like SilverBullet is all about self-expression: your notes, your thoughts, your system, your crazy experiments. I know that people use LLMs to write [[Space Lua]] scripts, and I’m happy for them. I know that LLMs help people do things that they could not do before, and even learn things in the process. That’s great. Open source is all about freedom. Do with it what you like, use it as you like. There is a solid [SilverBullet AI library](https://github.com/justyns/silverbullet-ai). -This policy only applies to the SilverBullet code base itself and its community. It is the code that I feel I should be able to understand and own, and the conversations that I decide to spend my time on contributing to. I have to make decisions that keep the project going and sustainable long term, and excessive use of AI tools in contributions puts that at risk. - -I hope that makes sense. +This policy only applies to the SilverBullet code base itself and its community. It is the code that I feel I should be able to understand and own, and the conversations that I decide to spend my time on contributing to. I have to make decisions that keep the project going and sustainable long term, and unproductively leveraging AI tools in contributions puts that at risk. — [[Zef]] diff --git a/website/Library Manager.md b/website/Library Manager.md index e9e726fd..585c8a58 100644 --- a/website/Library Manager.md +++ b/website/Library Manager.md @@ -1,5 +1,8 @@ -#maturity/beta +--- +description: The UI for browsing and importing libraries. +tags: maturity/beta glossary +--- The library manager makes it easy to manage (install, update, remove) [[Library]]. -The library is accessed via the ${widgets.commandButton "Library: Manager"} command. \ No newline at end of file +The library is accessed via the ${widgets.commandButton "Library: Manager"} command. diff --git a/website/Library.md b/website/Library.md index 85845503..6ec076a1 100644 --- a/website/Library.md +++ b/website/Library.md @@ -1,4 +1,7 @@ -#maturity/beta +--- +description: A collection of reusable Space Lua scripts, templates, and pages that can be imported into your space. +tags: maturity/beta glossary +--- SilverBullet is designed to be [[Extensions|extensible]]. In fact, a lot of functionality in SilverBullet is implemented through [[Space Lua]] embedded in [[Meta Page]], other functionality is implemented using [[Plugs]]. diff --git a/website/Library/Development.md b/website/Library/Development.md index 9c2f9106..18a64b4a 100644 --- a/website/Library/Development.md +++ b/website/Library/Development.md @@ -1,3 +1,5 @@ +#development + To develop your own SilverBullet library follow these steps: # Decorate your library with frontmatter diff --git a/website/Link.md b/website/Link.md index 1203a902..ae6dd8ff 100644 --- a/website/Link.md +++ b/website/Link.md @@ -1,3 +1,8 @@ +--- +description: A wiki-link or Markdown link connecting pages in your space. +tags: glossary +--- + In SilverBullet, you can create links to pages or documents inside your space as well as to external resources, using different link formats. # External links diff --git a/website/Linked Mention.md b/website/Linked Mention.md index a8f0f5e6..e6bc602f 100644 --- a/website/Linked Mention.md +++ b/website/Linked Mention.md @@ -1,3 +1,38 @@ -On this site you see a section “Linked Mentions” appear along the bottom of every page that has incoming links. 👇🏻 This section lists all pages that contain a _link to_ the current page. This allows for easy navigation, and may help you discover linked concepts through these links. +--- +description: A backlink reference showing everywhere a page is linked from. +tags: glossary +--- +Linked mentions (also known as backlinks) show all pages that contain a [[Link|link]] to the current page. They appear as a "Linked Mentions" section at the bottom of every page that has incoming links. -More details: [[^Library/Std/Widgets/Widgets]] \ No newline at end of file +# How? +SilverBullet's [[Object Index]] tracks all links between pages. The Linked Mentions widget queries this index to find pages that link _to_ the page you're currently viewing, then displays them with a snippet of the surrounding context. + +This allows for easy navigation and helps you discover connections between concepts through these bi-directional links. + +# Why? +In a traditional notes app, links are one-directional: page A links to page B, but page B has no idea. With linked mentions, every link becomes bi-directional. This means: + +* You can give a person, project, or concept its own page, and the linked mentions section will automatically collect every reference to it +* You discover unexpected connections between ideas +* Your knowledge graph builds itself as you write + +# Configuration +You can enable or disable the Linked Mentions widget in [[CONFIG]]: + +```lua +-- Disable linked mentions widget +config.set("std.widgets.linkedMentions.enabled", false) +``` + +# Programmatic access +You can query linked mentions directly using [[Space Lua/Lua Integrated Query]]: + +```lua +query[[ + from l = tags.link + where l.toPage == "Some Page" + order by l.pageLastModified desc +]] +``` + +See also: [[Link]], [[Linked Tasks]], [[Object/link]] diff --git a/website/Linked Tasks.md b/website/Linked Tasks.md index 05e8cc8f..c1e8960b 100644 --- a/website/Linked Tasks.md +++ b/website/Linked Tasks.md @@ -1,14 +1,34 @@ +--- +description: Tasks that reference a specific page using a link. +tags: glossary +--- + It is a common SilverBullet pattern to give people, groups of people and places dedicated pages so you can easily reference them. It then becomes very convenient to mention these pages elsewhere in your space, and using [[Linked Mention]] you can easily find what _pages_ link back to that page. -The equivalent of this idea the context of [[Task]] is Linked Tasks. These are tasks that _mention_ a particular page. +The equivalent of this idea in the context of [[Task]] is Linked Tasks. These are tasks that _mention_ a particular page. # Example workflow -Let’s say you keep notes of 1-on-1 meetings with people. You have a page for each person where you keep notes for each of your sessions. As you talk to person _A_, something comes up that you need to discuss with person _B_. B _also_ has their own page. What you can do is simply create a task on your note page with _A_ (so you don’t have to context switch) that includes a [[Link|link]] to _B_. +Let's say you keep notes of 1-on-1 meetings with people. You have a page for each person where you keep notes for each of your sessions. As you talk to person _A_, something comes up that you need to discuss with person _B_. B _also_ has their own page. What you can do is simply create a task on your note page with _A_ (so you don't have to context switch) that includes a [[Link|link]] to _B_. + +The next time you open B's page, you'll see the task from your meeting with A listed in the "Linked Tasks" widget at the top. + +# Behind the scenes +The Linked Tasks widget appears at the top of a page and shows all incomplete tasks from _other_ pages that contain a link to the current page. This is powered by a query that finds tasks where `ilinks` (inherited links) includes the current page name. + +When you complete a linked task (by checking the checkbox), the task is updated on its source page — the state change propagates across pages. + +# Configuration +You can enable or disable the Linked Tasks widget via configuration: + +```lua +-- Disable linked tasks widget +config.set("std.widgets.linkedTasks.enabled", false) +``` # Example -Below are two tasks that mention this very page (this is not the general pattern, just for demonstration purposes). Note that the not completed task is listed at the top of this page as well in the “Linked Tasks” widget. +Below are two tasks that mention this very page (this is not the general pattern, just for demonstration purposes). Note that the not completed task is listed at the top of this page as well in the "Linked Tasks" widget. * [ ] [[Linked Tasks]] This is a task * [x] [[Linked Tasks]] This is a completed task -**Implementation:** [[^Library/Std/Widgets/Widgets]] \ No newline at end of file +**Implementation:** [[^Library/Std/Widgets/Widgets]] diff --git a/website/Live Preview.md b/website/Live Preview.md index e11b3e66..7b9bf858 100644 --- a/website/Live Preview.md +++ b/website/Live Preview.md @@ -1,5 +1,16 @@ -SilverBullet uses a “live preview” markdown editor. This mechanism is heavily inspired by [Obsidian’s live preview mode](https://help.obsidian.md/Live+preview+update). +--- +description: The inline rendering of Markdown formatting as you type. +tags: glossary +--- +SilverBullet uses a “live preview” markdown editor. This mechanism is heavily inspired by [Obsidian's live preview mode](https://help.obsidian.md/Live+preview+update). -It reduces visual noise by not constantly showing [[Markdown]] codes such as `[SilverBullet website](https://silverbullet.md)`, only showing the underlying Markdown formatting code when the cursor is placed inside. +It reduces visual noise by not constantly showing [[Markdown]] formatting codes such as `[SilverBullet website](https://silverbullet.md)`, only showing the underlying Markdown formatting when the cursor is placed inside. -In SilverBullet, you can always see the underlying format by moving your cursor “inside.” **Alt-clicking** on any piece of formatted text will move your cursor there and reveal the underlying (markdown) code, or you can reveal it permanently with the `Toggle Markdown Syntax Rendering` command. +# Revealing the source +In SilverBullet, you can always see the underlying format by moving your cursor "inside" any formatted element with the keyboard, or by **Alt-clicking** (or Option-clicking on Mac) on any piece of formatted text. + +# Toggling live preview +If you prefer to see the raw markdown at all times, run the ${widgets.commandButton("Editor: Toggle Markdown Syntax Rendering")} command. This switches between live preview mode and raw markdown mode. + +# Widget rendering +[[Space Lua#Expressions]] (`${...}`) are rendered inline as live widgets. The underlying code is hidden until you move your cursor into the expression. This is what makes SilverBullet pages feel dynamic — queries, templates, and widgets all render seamlessly within the document. diff --git a/website/Manual.md b/website/Manual.md index 26cf9bb2..08f0cea8 100644 --- a/website/Manual.md +++ b/website/Manual.md @@ -1,6 +1,15 @@ Welcome to the wonderful world of SilverBullet. The goal of this manual is to give you a broad sense of how to use this tool and what it’s capable of. However, its full capabilities are yet to be discovered. You too may find new and creative ways to use the various SilverBullet features in ways nobody previously thought of. -However, that is all unlikely to happen unless you understand what SilverBullet can actually do. So let’s give you a bit of a sense. +However, that is all unlikely to happen unless you understand what SilverBullet can actually do. So let's give you a bit of a sense. + +**New here?** Start with the [[Quick Start]], which will walk through the basics in just a few minutes. + +# Guides +Practical walkthroughs for common workflows: + +* [[Guide/Knowledge Base]] — build a personal knowledge base +* [[Guide/Task Management]] — track projects and tasks +* [[Guide/People Notes]] — keep track of people and conversations # Videos ${embed.youtube "https://youtu.be/bb1USz_cEBY"} @@ -14,16 +23,16 @@ ${embed.youtube "https://youtu.be/qkLJ3viVq8I"} * [[CHANGELOG]]: what’s new in SilverBullet? This page will give you the latest details. It’s worth monitoring this page. # Installation and deployment -The biggest hurdle to get over with SilverBullet is that you need to get this thing running. And as of yet, the only way to do that is to install and deploy it yourself. 🤷 - * [[Install]]: Installation instructions for various setups +* [[Authentication]]: Securing your instance * [[TLS]]: the part where we walk through options to expose SilverBullet via HTTPS. +* [[Troubleshooting]]: When things don't go as planned For additional guides, check out [our community guides](https://community.silverbullet.md/c/guides/6). # Core Concepts These are the core concepts used in SilverBullet: - +* [[Glossary]] * [[Space]] * [[Page]] (and [[Meta Page]]) * [[Frontmatter]] @@ -36,7 +45,7 @@ SilverBullet’s UI is minimalist by design. Let’s look at the few UI elements * The [[Top Bar]] contains: * [[Page Namer]] - * [[Index Page]] (the 🏠 button) + * [[Index Page]] (the home button) * [[Page Picker]] * [[Command Palette]] * The main [[Editor]] component contains your currently selected page’s text @@ -52,6 +61,7 @@ SilverBullet’s UI is minimalist by design. Let’s look at the few UI elements * [[Markdown/Fenced Code Block]] * [[Slash Command]] * [[Outlines]] +* [[Completion]] # Navigation The main ways to roam your space, beside following page links, are: @@ -66,14 +76,20 @@ The main ways to roam your space, beside following page links, are: * [[Frontmatter]] * [[Attribute]] * [[Space Lua]] + * [[Space Lua/Standard Library]] + * [[Space Lua/Lua Integrated Query]] + * [[Space Lua/DOM]] + * [[Space Lua/JavaScript Interop]] +* [[Template]] +* [[Virtual Pages]] * [[Library]] -* [[Space Style]] * [[Troubleshooting]] # Customization * [[^Library/Std/Config]] * [[Page Decorations]] * [[Space Style]] +* [[Keyboard Shortcuts]] # Extending SilverBullet SilverBullet’s implementation is built on three things: @@ -82,8 +98,9 @@ SilverBullet’s implementation is built on three things: * A lot of core functionality is implemented in [[Plugs]]. * An increasing amount of additional functionality is now being implemented in “native” [[Space Lua]]. -# Contributing +See [[Extensions]] for an overview. +# Contributing SilverBullet is free and open-source software. You can contribute to it [via Github](https://github.com/silverbulletmd/silverbullet). For some details on how to do this, have a look -at [[Development]]. +at [[Development]]. Another way to contribute is through [[Funding]]. diff --git a/website/Markdown/Admonition.md b/website/Markdown/Admonition.md index 91618cc7..62214bc2 100644 --- a/website/Markdown/Admonition.md +++ b/website/Markdown/Admonition.md @@ -1,4 +1,7 @@ -#level/intermediate +--- +description: A callout block rendered from a special blockquote syntax. +tags: level/intermediate glossary +--- Silverbullet supports [admonitions](https://github.com/community/community/discussions/16925) using GitHub syntax (`note` and `warning`). diff --git a/website/Markdown/Fenced Code Block.md b/website/Markdown/Fenced Code Block.md index 3cecd7c3..260289ab 100644 --- a/website/Markdown/Fenced Code Block.md +++ b/website/Markdown/Fenced Code Block.md @@ -1,3 +1,8 @@ +--- +description: A triple-backtick block that can render widgets, queries, or syntax-highlighted code. +tags: glossary +--- + Blocks use the fenced code block notation of [[Markdown]], and assign special behavior to it. The general syntax is: @@ -11,4 +16,4 @@ These are the block types that ship with SilverBullet, but [[Plugs]] can define * `space-lua`: [[Space Lua]] * `space-style`: [[Space Style]] -The fenced code block syntax is also used to get [[Markdown/Syntax Highlighting]] for numerous programming languages. \ No newline at end of file +The fenced code block syntax is also used to get [[Markdown/Syntax Highlighting]] for numerous programming languages. diff --git a/website/Markdown/Hashtags.md b/website/Markdown/Hashtags.md index ff7e6e17..6c2179aa 100644 --- a/website/Markdown/Hashtags.md +++ b/website/Markdown/Hashtags.md @@ -1,3 +1,8 @@ +--- +description: "An inline #tag that annotates a page or object for categorisation and querying." +tags: glossary +--- + Hashtag syntax (`#my-tag`) can be used to explicitly assign a [[Tag]] to an [[Object]]. # Scope rules diff --git a/website/Meta Page.md b/website/Meta Page.md index 5e12dea6..62560899 100644 --- a/website/Meta Page.md +++ b/website/Meta Page.md @@ -1,3 +1,8 @@ +--- +description: "A page tagged with #meta that serves as tooling (configuration, extensions, templates) rather than regular content." +tags: glossary +--- + Meta pages are pages not core to your content, but function as a way to configure, or extend your [[Space]]. You can think of them as “tooling” pages. The most obvious examples are part of SilverBullet’s [[^Library/Std]] library and include generally useful [[Library/Std/Infrastructure/Slash Templates]]. diff --git a/website/Metadata.md b/website/Metadata.md index 4412b3c5..cac4854a 100644 --- a/website/Metadata.md +++ b/website/Metadata.md @@ -1,5 +1,5 @@ -Metadata is data about data. Most [[Object]] have a set of default attributes that can be augmented in a few additional ways: +Metadata is data about data. Most [[Object|objects]] have a set of default attributes that can be augmented in a few additional ways: * [[Tag]]: to tag the object (and add to the `tags` attribute directly) -* [[Frontmatter]]: at the top of [[Page]], a [[YAML]] encoded block can be used to define additional attributes to a page -* [[Attribute]] syntax +* [[Frontmatter]]: at the top of a [[Page]], a [[YAML]] encoded block defines additional attributes +* [[Attribute]] syntax: inline key-value pairs within your content diff --git a/website/Object Index.md b/website/Object Index.md index 251bd37d..8eaf758d 100644 --- a/website/Object Index.md +++ b/website/Object Index.md @@ -1,3 +1,8 @@ +--- +description: The local index that makes objects queryable. +tags: glossary +--- + The Object Index stores [[Object|Objects]] found in your [[Space]]. You interact with it in a few ways: @@ -39,4 +44,4 @@ Entry points are: * [[API/index#index.tag(name)]], e.g.: `index.tag "page"` * `tags.*`: as a convenience — `tags.page` is equivalent to `index.tag "page"` -If a `metatable` is defined for a particular tag with [[API/tag#tag.define(spec)]], the metatable is set for each object for the tag. \ No newline at end of file +If a `metatable` is defined for a particular tag with [[API/tag#tag.define(spec)]], the metatable is set for each object for the tag. diff --git a/website/Object.md b/website/Object.md index f684794c..af8a77d3 100644 --- a/website/Object.md +++ b/website/Object.md @@ -1,3 +1,8 @@ +--- +description: A structured, queryable unit of data extracted from your pages (e.g. tasks, items, paragraphs). +tags: glossary +--- + SilverBullet automatically maintains an [[Object Index]] extracted from all [[Markdown]] [[Page|pages]] in your [[Space|Space]]. Objects are a feature that powers a lot of SilverBullet functionality, including the [[Page Picker]], [[Linked Mention|Linked Mentions]] and many others. They can also be queried by the user directly, typically via [[Space Lua/Lua Integrated Query]]. diff --git a/website/PWA.md b/website/PWA.md index c82557b7..fb9c8283 100644 --- a/website/PWA.md +++ b/website/PWA.md @@ -1,3 +1,25 @@ -SilverBullet is developed as a [Progressive Web App](https://web.dev/progressive-web-apps/), a web application that is fully offline capable. +--- +description: "SilverBullet's installable web-app mode for offline access and native-like experience." +tags: glossary +--- -After your first load and sync, (practically) all functionality is available even without a network connection. \ No newline at end of file +SilverBullet is built as a [Progressive Web App](https://web.dev/progressive-web-apps/) (PWA) — a web application that works fully offline. + +# What the PWA gives you +* **Offline access**: After your first load and sync, all functionality is available without a network connection. Edits are stored locally and synced when you're back online. +* **App-like experience**: Install SilverBullet as a standalone app on your device — it gets its own window, icon, and feels like a native application. +* **Instant loading**: Since your content is synced to your browser's local storage, pages load instantly without network requests. + +# How to install +* **Chrome / Edge / Chromium-based**: Click the install icon in the address bar, or use the browser menu to "Install SilverBullet" +* **Safari (iOS / macOS)**: Use "Add to Home Screen" from the share menu +* **Android**: Use "Add to Home Screen" or "Install app" from the browser menu + +Once installed, SilverBullet appears in your app launcher / dock / home screen like any other app. + +# How offline works +SilverBullet's [[Sync]] engine keeps a full copy of your space in the browser's IndexedDB. When online, changes are continuously synced between the browser and the server. When offline, you work against the local copy. On reconnection, the sync engine reconciles any changes. + +A service worker caches the application code itself, so even the SilverBullet UI loads without a network connection. + +See also: [[Sync]], [[Architecture]] diff --git a/website/Page Decorations.md b/website/Page Decorations.md index 2041b603..c1c0fd5d 100644 --- a/website/Page Decorations.md +++ b/website/Page Decorations.md @@ -1,5 +1,6 @@ --- -tags: maturity/beta +description: Visual customization (icons, prefixes, CSS) applied to pages matching certain criteria. +tags: maturity/beta glossary pageDecoration: prefix: "🎄 " disableTOC: true diff --git a/website/Page Picker.md b/website/Page Picker.md index 542727e8..add3bf4b 100644 --- a/website/Page Picker.md +++ b/website/Page Picker.md @@ -1,3 +1,7 @@ +--- +description: The quick-open dialog for navigating to any page. +tags: glossary +--- The page picker has two main functions: 1. Enables quick navigation between [[Page]] diff --git a/website/Page Template.md b/website/Page Template.md index b2bea47c..e34fa1b0 100644 --- a/website/Page Template.md +++ b/website/Page Template.md @@ -1,3 +1,8 @@ +--- +description: A template used to pre-populate new pages. +tags: glossary +--- + Page templates can be used to automate or simplify the creation of pages based on a template. # Creating a page template diff --git a/website/Page.md b/website/Page.md index 62d9a17b..3c0674b9 100644 --- a/website/Page.md +++ b/website/Page.md @@ -1,3 +1,7 @@ +--- +description: A single Markdown document in your space. +tags: glossary +--- The primary thing you’ll be doing in SilverBullet (hopefully) is creating and editing pages. Pages are written in [[Markdown]], can contain [[Metadata]] and are kept on the server as text files. Page _names_ are relatively free-form, but have to adhere to a few [[Names#Rules]]. diff --git a/website/Schema.md b/website/Schema.md index 4ba57dca..8bb796d2 100644 --- a/website/Schema.md +++ b/website/Schema.md @@ -1,17 +1,49 @@ -SilverBullet relies on [JSON Schema](https://json-schema.org) for various types of validation, specifically: +--- +description: A definition that validates and constrains the shape of object attributes. +tags: glossary +--- -* [[Tag#Custom tags]] -* [[^Library/Std/Config]] options +SilverBullet uses [JSON Schema](https://json-schema.org) for validation of structured data. Schemas ensure that [[Frontmatter]] attributes, [[Tag#Custom tags|custom tag]] fields, and configuration options conform to expected types and shapes. -Often these schemas are encoded using [[Space Lua]], so take the shape of: +# Where schemas are used +## Custom tag definitions +When you define a custom tag with `tag.define`, you can provide a schema that describes the expected attributes. SilverBullet validates objects against this schema and surfaces errors in the editor: ```lua -local schema = { - type = "object", - properties = { - -- ... +tag.define { + name = "contact", + schema = { + type = "object", + properties = { + email = schema.string(), + phone = schema.nullable("string"), + priority = schema.number(), + } } } ``` -There are is the [[^Library/Std/APIs/Schema]] API for convenience. \ No newline at end of file +Pages or objects tagged with `#contact` will be validated against this schema — if a field has the wrong type, you'll see a lint warning in the editor. + +## Configuration definitions +The `config.define` function uses schemas to validate configuration values: + +```lua +config.define("myLibrary.config", { + type = "object", + properties = { + enabled = schema.boolean(), + maxItems = schema.number(), + } +}) +``` + +This ensures that `config.set("myLibrary.config", ...)` only accepts values matching the schema. + +# Schema helper functions +The [[^Library/Std/APIs/Schema]] library provides convenience functions like `schema.string()`, `schema.number()`, `schema.array(typ)`, etc. for building JSON Schema objects in Lua. See the API page for the full list. + +# How validation surfaces +When schema validation fails for page and attributes, SilverBullet shows the error as a lint warning in the editor. + +See also: [[Tag#Custom tags]], [[API/jsonschema]], [[API/config]] diff --git a/website/Service.md b/website/Service.md index 6b299e34..cc0b5ce9 100644 --- a/website/Service.md +++ b/website/Service.md @@ -1,14 +1,9 @@ -The SilverBullet service bus is an extension mechanism built into SilverBullet. +The SilverBullet service bus is an extension mechanism for defining and discovering pluggable behavior. It lets you register named services that can be discovered and invoked by other parts of SilverBullet or your own scripts. This enables a plugin-like architecture where multiple implementations can compete for the same operation, with the best match winning. # Concepts -* Discovery: the process of discovering available services based on a _selector_. -* Selector: a string (possibly with a wildcard `*`) used to advertise as well as discover services. -* Service: defined via [[API/service#service.define(spec)]]), implements a service advertised via a selector. -* Invocation: running a discovered service. +* **Service**: A named handler defined via `service.define`. It advertises itself under a _selector_ and provides a `run` callback. +* **Selector**: A string used to advertise and discover services. Can contain wildcards (e.g. `export:*`). +* **Discovery**: The process of finding all services matching a selector. Each service's `match` function determines if it applies and at what priority. +* **Invocation**: Running a discovered service's `run` callback. -# Architecture -Services are an abstraction built on top of [[Event]]. When a new service is defined, it registers itself listening to the `discover:<>` event (to be discovered), and under `service:<>` to be invoked. - -Service discovery happens by broadcasting an event on the event bus with the given selector, returning a list of services that are a match, ordered by (self assigned) priority. One (or all) of these services can then be invoked based on their returned ID. - -See [[API/service]] for API details. \ No newline at end of file +See [[API/service]] for more information on how to use and define your own services. diff --git a/website/Share.md b/website/Share.md index 5126d91a..681d52ad 100644 --- a/website/Share.md +++ b/website/Share.md @@ -1,5 +1,7 @@ -#maturity/beta - +--- +description: The mechanism for publishing or sharing individual pages. +tags: maturity/beta glossary +--- SilverBullet is aimed for single-user, private use. Nevertheless, many have the need to _share_ some content kept in SilverBullet with the outside world: to push content out, pull it in, or even sync between different locations. This is where SilverBullet _share_ functionality comes in. **Note:** If you are interested in one-off ways to get content out, have a look at [[Export]]. diff --git a/website/SilverBullet.md b/website/SilverBullet.md index 9cfc9cb5..6d755599 100644 --- a/website/SilverBullet.md +++ b/website/SilverBullet.md @@ -71,6 +71,7 @@ Learn more about SilverBullet’s technical [[Architecture]]. SilverBullet has been in development since early 2022, but is ever evolving. The current iteration is **SilverBullet v2**. We had a little bit of a reboot, rebuilding some of the foundations, and replacing some of the previous ([v1](https://v1.silverbullet.md)) features. # What’s next? +* [[Quick Start]]: Get up and running in five minutes. * [[Manual]]: SilverBullet’s official manual. * [[CHANGELOG]]: we’re in active development, so things change rapidly. Watch this page to keep up. * [Community](https://community.silverbullet.md): join our community: ask questions, share your experiences. diff --git a/website/Slash Command.md b/website/Slash Command.md index 9ebe5bbb..17c4b196 100644 --- a/website/Slash Command.md +++ b/website/Slash Command.md @@ -1,6 +1,39 @@ -Slash commands are quick ways to perform repetitive tasks. 99% of the time this will mean using a [[^Library/Std/Infrastructure/Slash Templates]], but you can also create them in a more low-level way using [[Space Lua#Slash commands]]. +--- +description: "A /-triggered shortcut in the editor for inserting content or running actions." +tags: glossary +--- +Slash commands are quick ways to perform repetitive tasks. You trigger them by typing `/` in your text (after whitespace) followed by the command name — autocompletion will help you find the right one. -# Invoking a slash command -You can trigger a slash command by typing a `/` in your text (after some white space) followed by its name (this will auto complete). +# Built-in slash commands +[[^Library/Std#Slash templates]] provides many useful ones out of the box. -Technically, no slash commands ship with SilverBullet directly. However, you can easily add useful ones via [[Library]]. +**Editing** +* `/h1`, `/h2`, `/h3`, `/h4` — convert the current line into a heading of the given level +* `/task` — convert the current line into a task (`* [ ] ...`) +* `/frontmatter` — insert a YAML frontmatter block at the top of the page +* `/space-lua` — insert a `space-lua` fenced code block + +**Dates** +* `/today` — insert today's date (e.g. `2026-03-04`) +* `/yesterday` — insert yesterday's date +* `/tomorrow` — insert tomorrow's date + +# Slash templates +Most slash commands are implemented as [[Slash Templates]] — pages tagged with `#meta/template/slash` whose content is inserted at the cursor. The standard library includes slash templates for: + +* `/query` — insert a LIQ query block +* `/lua-query` — insert a Lua query expression +* `/code` — insert a fenced code block +* `/table` — insert a Markdown table +* `/hr` — insert a horizontal rule +* `/note-admonition`, `/warning-admonition`, `/success-admonition`, `/danger-admonition` — insert admonition blocks +* `/tpl` — insert a template expression +* `/func` — insert a Lua function definition +* `/lua-command` — insert a command definition +* `/lua-slash-command` — insert a slash command definition + +# Defining your own +There are two ways to create custom slash commands: + +1. **Slash templates** (recommended): Create a page tagged `#meta/template/slash`. See [[Slash Templates]] for details. +2. **`slashCommand.define`**: For slash commands that need logic beyond simple text insertion. See [[API/command#slashCommand.define(spec)]]. diff --git a/website/Slash Templates.md b/website/Slash Templates.md index 91f7e425..a8bea7de 100644 --- a/website/Slash Templates.md +++ b/website/Slash Templates.md @@ -1 +1,40 @@ -See [[^Library/Std/Infrastructure/Slash Templates]] \ No newline at end of file +--- +description: Templates invoked via slash commands to insert pre-defined content. +tags: glossary +--- +Slash templates are a quick way to define [[Slash Command|slash commands]] that insert templated content at the cursor position. They are defined as pages tagged with `#meta/template/slash`. + +# Creating a slash template +1. Create a new page. The last component of the page name (after the `/` if any) will be used as the slash command's name. For example, a page named `Library/Slash Template/action-items` creates a `/action-items` slash command. +2. Tag the page with `#meta/template/slash` in its [[Frontmatter]]. +3. Write the template content in the page body. Lua directives (`${...}`) are supported and will be evaluated when the template is inserted. + +## Example +A page named `Library/Slash Template/action-items` with this content: + +~~~ +--- +tags: meta/template/slash +description: Insert a standard action items section +--- +# Action items +* [ ] |^| +~~~ + +Creates a `/action-items` slash command that inserts an action items section. + +# Configuration +You can configure these optional [[Frontmatter]] keys: + +* `description`: The description shown in the slash command completion menu +* `priority`: Higher priority commands appear earlier in the list +* `onlyContexts` (advanced): Only show the command in certain AST node contexts +* `exceptContexts` (advanced): Show the command everywhere _except_ in these AST node contexts + +# Currently active slash templates +${template.each(query[[ + from index.tag "meta/template/slash" + where _.tag == "page" +]], templates.fullPageItem)} + +See also: [[Slash Command]], [[Template]], [[Page Template]] diff --git a/website/Space Lua.md b/website/Space Lua.md index e7f14c05..bb81badc 100644 --- a/website/Space Lua.md +++ b/website/Space Lua.md @@ -1,3 +1,7 @@ +--- +description: "SilverBullet's embedded Lua scripting environment for extending functionality." +tags: glossary +--- Space Lua is a custom dialect and implementation of the [Lua programming language](https://lua.org/), embedded in SilverBullet. It aims to be a largely complete Lua implementation, but adds a few non-standard features while remaining syntactically compatible with “real” Lua. In its essence, Space Lua adds two features to SilverBullet’s [[Markdown]] language: @@ -29,7 +33,7 @@ Your `space-lua` definitions are constantly being indexed as part of the [[Objec When your client boots, or if you explicitly run the `System: Reload` command, all these scripts are executed in sequence. -It is possible to **control load order** of space lua scripts using the special `-- priority: ` comment in Space Lua code. For instance: +It is possible to **control load order** of Space Lua scripts using the special `-- priority: ` comment in Space Lua code. For instance: ```space-lua -- priority: 10 diff --git a/website/Space Lua/Lua Integrated Query.md b/website/Space Lua/Lua Integrated Query.md index 7b439dbf..5b8269e4 100644 --- a/website/Space Lua/Lua Integrated Query.md +++ b/website/Space Lua/Lua Integrated Query.md @@ -1,3 +1,7 @@ +--- +description: A Lua-embedded query syntax for selecting and transforming objects. +tags: glossary +--- Lua Integrated Query (LIQ) is a SilverBullet specific Lua extension. It adds a convenient query syntax to the language in a backwards compatible way. It does so by overloading Lua’s default function call + single argument syntax when using `query` as the function call. As a result, Lua programs using LIQ are still syntactically valid Lua. The syntax for LIQ is `query[[my query]]`. In regular Lua `[[my query]]` is just another way of writing `"my query"` (it is an alternative string syntax). Function calls that only take a string argument can omit parentheses, therefore `query[[my query]]` is equivalent to `query("my query")`. diff --git a/website/Space Lua/Widget.md b/website/Space Lua/Widget.md index 194f6d39..4c12333c 100644 --- a/website/Space Lua/Widget.md +++ b/website/Space Lua/Widget.md @@ -1,17 +1,42 @@ +--- +description: A rendered UI component (markdown or HTML). +tags: glossary +--- The `${lua expression}` syntax can be used to implement custom widgets. If the Lua expression evaluates to a simple string, it will live preview as that string rendered as markdown. However, if the expression returns a `widget.new`-generated result value, you can do some fancier stuff. -To render a widget, call `widget.new` with a[text](https://meet.google.com/dtz-nbtq-wwf)ny of the following keys: +# Widget types +To render a widget, call `widget.new` with any of the following keys: * `markdown`: Renders the value as markdown -* `html`: Renders a HTML string as a widget. This is somewhat brittle. Therefore, it’s preferred to use the [[^Library/Std/APIs/DOM]] API. +* `html`: Renders an HTML string or DOM element as a widget * `display`: Render the value either `inline` or as a `block` (defaults to `inline`) +* `cssClasses`: Array of CSS class names to add to the widget container -For convenience there are `widget.markdown` and `widget.html` wrappers available, see below for examples. +# Convenience functions +For common cases, use these shortcuts instead of `widget.new` directly: -## Markdown widgets +| Function | Description | +|---|---| +| `widget.markdown(md)` | Inline markdown widget | +| `widget.markdownBlock(md)` | Block-level markdown widget | +| `widget.html(html)` | Inline HTML widget | +| `widget.htmlBlock(html)` | Block-level HTML widget | -## DOM widgets -To render a custom HTML-based widget, use the [[^Library/Std/APIs/DOM]] API: +# Markdown widgets +The simplest widget type renders markdown: + +```lua +${widget.markdown("**Bold** and *italic* text")} +``` + +For block-level content (like lists or tables), use `widget.markdownBlock`: + +```lua +${widget.markdownBlock("## A heading\n* Item 1\n* Item 2") +``` + +# HTML and DOM widgets +For full control over the rendered output, use HTML widgets with the [[Space Lua/DOM|DOM builder API]]: ```space-lua function marquee(text) @@ -33,5 +58,67 @@ We can combine this with some [[Space Style]] to style it: } ``` -Now, let’s use it (try clicking): +Now, let's use it (try clicking): ${marquee "Finally, marqeeeeeee!"} + +# Built-in widgets +The standard library provides several pre-built widgets in the `widgets` table: + +## Buttons +* `widgets.button(text, callback)` — a simple button that runs the callback when clicked +* `widgets.commandButton(commandName)` — a button for a command (button text is the command name) +* `widgets.commandButton(text, commandName)` — a button for a command with custom text +* `widgets.commandButton(text, commandName, args)` — a button for a command with arguments + +Example: +${widgets.button("Hello", function() + editor.flashNotification "Hi there!" +end)} + +${widgets.commandButton("System: Reload")} + +## Sub-pages widget +* `widgets.subPages(pageName?)` — renders a list of sub-pages (pages with the given prefix). Defaults to the current page. + +## Top and bottom widgets +These render automatically on every page and can be configured: + +* **Table of contents** — shows a table of contents at the top of the page +* **Linked mentions** — shows pages that link to the current page at the bottom +* **Linked tasks** — shows incomplete tasks that mention the current page at the top + +Configure them in your [[^Library/Std/Config]] page: + +```lua +-- Disable TOC altogether +config.set("std.widgets.toc.enabled", false) +-- Only render a TOC when there's >= 5 headers +config.set("std.widgets.toc.minHeaders", 5) +-- Disable linked mentions +config.set("std.widgets.linkedMentions.enabled", false) +-- Disable linked tasks +config.set("std.widgets.linkedTasks.enabled", false) +``` + +# Embed widgets +The `embed` namespace provides widgets for embedding external content: + +* `embed.youtube(url)` — embeds a YouTube video +* `embed.peertube(url)` — embeds a PeerTube video +* `embed.vimeo(url)` — embeds a Vimeo video + +# Creating custom top/bottom widgets +You can add your own widgets to the top or bottom of every page by listening to the rendering events: + +```lua +event.listen { + name = "hooks:renderTopWidgets", + run = function(e) + return widget.new { + markdown = "This appears at the top of every page!" + } + end +} +``` + +See also: [[Space Lua/DOM]], [[API/widget]], [[API/dom]] diff --git a/website/Space Style.md b/website/Space Style.md index 43472b76..a63e1565 100644 --- a/website/Space Style.md +++ b/website/Space Style.md @@ -1,3 +1,8 @@ +--- +description: Custom CSS applied across your space via a special page. +tags: customization glossary +--- + Space Style is [[Space Lua]]’s stylish sibling. It enables you to add your own styling to SilverBullet with `space-style` [[Markdown/Fenced Code Block]]. This can be used to achieve various things, such as overriding the default editor font or setting wider page widths. It is also possible to develop custom themes this way. diff --git a/website/Space.md b/website/Space.md index 1338e70c..59a9a99c 100644 --- a/website/Space.md +++ b/website/Space.md @@ -1,3 +1,7 @@ +--- +description: The top-level folder of Markdown files, assets, and configuration that SilverBullet serves. +tags: glossary +--- A _space_ is SilverBullet terminology for a workspace, or project, or instance. [Obsidian](https://obsidian.md/) calls this a vault, [LogSeq](https://logseq.com/) calls it a graph. You may think of it as a [[Folder]] or a directory — because in practical terms, that’s all it is. Feel free to back up or manipulate your space’s folder and its files with whatever tool you like — you don’t have to use SilverBullet exclusively. You may want to turn your space’s folder into a git repository, for instance, and do version control and back-ups that way. diff --git a/website/Sync.md b/website/Sync.md index 20738621..64b6e698 100644 --- a/website/Sync.md +++ b/website/Sync.md @@ -1,3 +1,8 @@ +--- +description: The bidirectional synchronisation between the client's local store and the server. +tags: glossary +--- + SilverBullet is an offline-first web application. Therefore it keeps a copy of your space locally in your browser. It implements a sync engine to continuously keep this local copy in sync with the server (for technical details, see [[Architecture]]). Sync happens: diff --git a/website/TLS.md b/website/TLS.md index bbd56552..cda8009f 100644 --- a/website/TLS.md +++ b/website/TLS.md @@ -1,3 +1,5 @@ +#getting-started + SilverBullet relies on a few advanced browser features to operate (specifically service workers, crypto APIs and clipboard APIs). These features are _only_ enabled by browsers when websites are accessed via `http://localhost` or via [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security), that is — a `https://` URL. This is not a limitation imposed by SilverBullet, it is a restriction encoded in web standards. Therefore, to use SilverBullet you need to either access it via `localhost` or put a TLS certificate on it. diff --git a/website/Tag.md b/website/Tag.md index df119920..7f383eba 100644 --- a/website/Tag.md +++ b/website/Tag.md @@ -1,3 +1,8 @@ +--- +description: A label applied to objects for grouping and querying. +tags: glossary +--- + Tags in SilverBullet are used to encode types of [[Object|Objects]], they’re similar to tables in relational databases, or classes in object-oriented programming. Every [[Object]] has a main `tag`, which signifies the type of object being described. In addition, any number of additional tags can be assigned as well via the `tags` attribute. You can use either the main `tag` or any of the `tags` as query sources in [[Space Lua/Lua Integrated Query]]. diff --git a/website/Task.md b/website/Task.md index 9d632270..e67e87d1 100644 --- a/website/Task.md +++ b/website/Task.md @@ -1,3 +1,8 @@ +--- +description: A checkbox item tracked as a queryable object. +tags: glossary +--- + The task notation syntax is a [[Markdown]] extension to write down tasks. Its most basic form is: diff --git a/website/Template.md b/website/Template.md index 97a777c9..740799b7 100644 --- a/website/Template.md +++ b/website/Template.md @@ -1,3 +1,51 @@ -A template in SilverBullet is simply a page or string using [[Space Lua#Expressions]]. +--- +description: Reusable content with placeholder expressions, used for page creation, slash commands, and more. +tags: glossary +--- +A template in SilverBullet is a string that contains `${expression}` placeholders, which get evaluated using [[Space Lua]]. Templates are a mechanism for dynamically rendering content in your pages. -They’re typically used to dynamically render parts of pages using [[Space Lua]] and in [[Page Template]] and [[Slash Templates]]. \ No newline at end of file +# Creating templates +Use `template.new` to create a template function from a string. By convention, template strings use `[==[` and `]==]` as delimiters: + +```lua +templates.greet = template.new[==[Hello, ${name}!]==] +``` + +Call the template with a table of values: + +```lua +${templates.greet {name = "World"}} +``` + +# Rendering collections with template.each +The most common pattern is using `template.each` to render a list of objects: + +```lua +template.each(query[[ + from index.tag "page" + order by lastModified desc + limit 5 +]], templates.pageItem) +``` + +`template.each` iterates over the collection and applies the template to each item, concatenating the results. + +# Pre-built templates +The standard library provides several commonly used templates in the `templates` table: + +| Template | Description | +|---|---| +| `templates.pageItem` | Renders a page as `* [[pageName]]` | +| `templates.fullPageItem` | Similar to `pageItem` but rendering the full page name (including folders) | +| `templates.taskItem` | Renders a task as a togglable checkbox item with a link to its source so that it can update | +| `templates.itemItem` | Renders a list item with a link to its source | +| `templates.paragraphItem` | Renders a paragraph with a link to its source | +| `templates.tagItem` | Renders a tag as a linked hashtag | + +# Page templates +[[Page Template|Page templates]] are pages tagged with `#meta/template/page`. They serve as blueprints for creating new pages — you can configure them with suggested names, keyboard shortcuts, and commands. + +# Slash templates +[[Slash Templates]] are pages tagged with `#meta/template/slash`. They define [[Slash Command|slash commands]] that insert templated content at the cursor position. The last component of the page name becomes the slash command name. + +See also: [[API/template]], [[Page Template]], [[Slash Templates]], [[Space Lua]] \ No newline at end of file diff --git a/website/Transclusions.md b/website/Transclusions.md index aff06e23..1b215ab0 100644 --- a/website/Transclusions.md +++ b/website/Transclusions.md @@ -1,3 +1,8 @@ +--- +description: Inline embedding of one page's content inside another. +tags: glossary +--- + Transclusions are an extension of the [[Markdown]] syntax enabling inline embedding of content. The general syntax is `![[path]]`. Two types of transclusions are currently supported: diff --git a/website/Troubleshooting.md b/website/Troubleshooting.md index fa41256d..7325d6f0 100644 --- a/website/Troubleshooting.md +++ b/website/Troubleshooting.md @@ -1,20 +1,34 @@ -Running into trouble? Sorry to hear it. Let’s figure this out. +#getting-started -Here are some things you can try when things don’t work, if you’re still stuck — ask the [community for help](https://community.silverbullet.md/). +Running into trouble? Sorry to hear it. Let's figure this out. + +Here are some things you can try when things don't work. If you're still stuck — ask the [community for help](https://community.silverbullet.md/). The starting point is always [[Log|Logs]] to see if you see anything suspicious. # Disable features Depending on the situation you may (temporarily) disable various client features by appending any of the following to any SilverBullet URL (e.g. `http://localhost:3000/?disableSpaceLua=1`): + * `?disableSync=1` disables synchronization with the server * `?disableSpaceLua=1` disables loading of all [[Space Lua]] scripts * `?disableSpaceStyle=1` disables loading of all [[Space Style]] * `?disablePlugs=1` disables loading of all non built-in [[Plugs]] -# Client reset -If all else fails, you may try to perform a full client reset, simply add `?resetClient=1` to any SilverBullet URL. +These can be combined: `?disableSpaceLua=1&disableSpaceStyle=1` -This will do the following: +# Client reset +If all else fails, you can perform a full client reset by adding `?resetClient=1` to any SilverBullet URL. + +This will: 1. Confirm you want to perform a full client reset 2. Wipe all data stored locally in your browser (IndexedDB, unregister the service worker) -3. Reload the client initiating a full resync +3. Reload the client, initiating a full resync + +> **warning** Warning +> A client reset wipes your local cache. Any unsynced local changes will be lost. Make sure your server is accessible before resetting, so the client can resync. + +# Server-side debugging +* `SB_HTTP_LOGGING`: Set this environment variable to enable HTTP request logging +* `SB_LOG_PUSH`: Set this to ask clients to push their logs to the server + +See [[Install/Configuration]] for all configuration options. diff --git a/website/Vim.md b/website/Vim.md index b594e447..dbf2b195 100644 --- a/website/Vim.md +++ b/website/Vim.md @@ -1,3 +1,5 @@ +#customization + SilverBullet has a basic Vim mode. You can toggle it using the ${widgets.commandButton("Editor: Toggle Vim Mode")} command. In addition, it supports various ex commands that you can run as you would expect, for instance: `:imap jj `. From 35542a2cc9d13706b8d13e1d7a50a96d7d33b951 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 4 Mar 2026 13:39:27 +0100 Subject: [PATCH 18/22] Missing website files, whoops --- website/Completion.md | 28 ++++++ website/Glossary.md | 8 ++ website/Guide/Knowledge Base.md | 72 ++++++++++++++++ website/Guide/People Notes.md | 83 ++++++++++++++++++ website/Guide/Task Management.md | 99 ++++++++++++++++++++++ website/Quick Start.md | 94 +++++++++++++++++++++ website/Space Lua/DOM.md | 100 ++++++++++++++++++++++ website/Space Lua/JavaScript Interop.md | 64 ++++++++++++++ website/Space Lua/Standard Library.md | 108 ++++++++++++++++++++++++ website/Virtual Pages.md | 75 ++++++++++++++++ 10 files changed, 731 insertions(+) create mode 100644 website/Completion.md create mode 100644 website/Glossary.md create mode 100644 website/Guide/Knowledge Base.md create mode 100644 website/Guide/People Notes.md create mode 100644 website/Guide/Task Management.md create mode 100644 website/Quick Start.md create mode 100644 website/Space Lua/DOM.md create mode 100644 website/Space Lua/JavaScript Interop.md create mode 100644 website/Space Lua/Standard Library.md create mode 100644 website/Virtual Pages.md diff --git a/website/Completion.md b/website/Completion.md new file mode 100644 index 00000000..813525bb --- /dev/null +++ b/website/Completion.md @@ -0,0 +1,28 @@ +SilverBullet provides context-aware autocomplete to help you write faster. Completions are triggered automatically or via keyboard shortcuts as you type. + +# Page link completion +Type `[[` to trigger page name completion. SilverBullet searches across all pages in your space and offers matching suggestions. Select one to insert a [[Link]] to that page. If no page with that name exists, a link is still created — navigating to it will create the page (these are tracked as [[Aspiring Pages]]). + +# Tag completion +Type `#` to trigger tag completion. SilverBullet suggests existing tags from across your space. This helps maintain consistent tagging — no more typos creating duplicate tags. + +# Emoji completion +Type `:` followed by a keyword to search for emoji. For example, `:rocket` offers the rocket emoji. Press Enter to insert it. + +# Frontmatter key completion +Inside a [[Frontmatter]] block, SilverBullet suggests attribute keys that are already used elsewhere in your space. This helps keep your metadata schema consistent. + +# Slash commands +Type `/` at the beginning of a line (or after a space) to trigger [[Slash Command]] completion. Slash commands can insert templates, perform actions, or trigger custom behavior defined in [[Space Lua]]. + +# Lua code completion +Inside `space-lua` fenced code blocks, SilverBullet provides code completion for: + +* Global functions and variables +* API namespaces (`editor.`, `space.`, `index.`, etc.) +* Table fields and methods + +# Custom completions +You can extend the completion system by subscribing to the `editor:complete` event via [[Space Lua]]. Your handler receives the current cursor context and can return additional completion items. + +See also: [[API/event]] diff --git a/website/Glossary.md b/website/Glossary.md new file mode 100644 index 00000000..cd617119 --- /dev/null +++ b/website/Glossary.md @@ -0,0 +1,8 @@ +A quick-reference guide to SilverBullet-specific terminology: +${template.each(query[[ + from p = tags.glossary + where p.tag == "page" + order by p.name +]], template.new [==[ + - [[${name}]]: ${description} +]==])} diff --git a/website/Guide/Knowledge Base.md b/website/Guide/Knowledge Base.md new file mode 100644 index 00000000..f11c1b26 --- /dev/null +++ b/website/Guide/Knowledge Base.md @@ -0,0 +1,72 @@ +#guide + +This guide walks you through building a personal knowledge base with SilverBullet. You'll learn how pages, links, tags, queries, and transclusions work together to create an interconnected web of knowledge. + +# 1. Create your first topic pages +Start with 3–4 pages on topics you know well: a programming language, a recipe, a book you've read. Open the [[Page Picker]] (`Cmd-k` / `Ctrl-k`), type a name, and press Enter. + +Keep each page focused on one topic. A page about “Rust” covers Rust. A page about “Ownership” covers ownership. This “atomic note” approach makes pages easy to link and reuse. + +Write freely — a paragraph or two is enough to get started. + +# 2. Link as you write +As you write on one page, naturally reference another. Type `[[` and SilverBullet autocompletes page names: + +```markdown +Rust's [[Ownership]] model prevents data races at compile time. +``` + +Don’t worry about organizing pages into the “right” folder structure upfront (or at all). Just write and link. The structure emerges from the connections. + +# 3. Discover connections via backlinks +Navigate to one of your linked pages (click a `[[link]]` or use the Page Picker). Scroll to the bottom and look for the **Linked Mentions** section. + +This shows every page that links _to_ the current page — connections you didn't have to manually create. For example, your “Ownership” page will show that your “Rust” page mentions it. + +This is how a knowledge base builds itself: write naturally, link as you go, and let [[Linked Mention|linked mentions]] surface the connections. + +# 4. Add structure when it's useful +When you want to categorize or query pages, add some structure. + +**Hashtags** on an empty line tag the page (see [[Markdown/Hashtags#Scope rules]]): +```markdown +#concept +``` + +**[[Frontmatter]]** at the top of a page adds structured data: +```yaml +--- +tags: book +author: Italo Calvino +status: reading +--- +``` + +Now this page is tagged `book` and has queryable `author` and `status` attributes. You can add tags to a page either with the `#book` syntax, or via a [[Frontmatter]] attribute. + +# 5. Query your knowledge +[[Space Lua/Lua Integrated Query]] lets you pull live data from your pages. Create a “Currently Reading” page with a query: + +```lua +${template.each(query[[ + from b = tags.book + where b.status == "reading" + order by b.lastModified desc +]], templates.pageItem)} +``` + +See [[Template]] for more rendering options. + +# 6. Embed content across pages +Use [[Transclusions]] to pull content from one page into another. For instance on your [[Index Page]], transclude your “Currently Reading” page: + +```markdown +![[Currently Reading]] +``` + +# What's next? +You now have the core pattern: create pages, link them, add structure with tags and frontmatter, and query across your space. + +* [[Guide/Task Management]] — track projects and tasks +* [[Guide/People Notes]] — keep track of people and conversations +* [[Manual]] — the full user manual diff --git a/website/Guide/People Notes.md b/website/Guide/People Notes.md new file mode 100644 index 00000000..ef400ae6 --- /dev/null +++ b/website/Guide/People Notes.md @@ -0,0 +1,83 @@ +#guide + +This guide walks you through building a personal CRM with SilverBullet. You'll use person pages, meeting notes, linked mentions, linked tasks, and page decorations to automatically track your interactions with people. + +# 1. Create person pages +Make a page for someone you interact with, let’s say “Alice.” Add [[Frontmatter]] to describe them: + +```yaml +--- +--- +``` + +Create a few more person pages the same way. + +## Make person pages stand out +Add a `tag.define` call to your [[CONFIG]] page so person pages get a visual prefix: + +```space-lua +tag.define { + name = "person", + transform = function(o) + o.pageDecoration = { prefix = "🧑 " } + return o + end +} +``` + +After a reload, person pages will show a 🧑 prefix in the [[Page Picker]], [[Completion|completions]], and editor. See [[Page Decorations]] and [[API/tag]] for more options. + +> **warning** Warning +> Tag customization is still a beta feature, it may change in the future. + +# 2. Take meeting notes +Create a page like “Meeting/2026-03-04” and write naturally, linking to attendees: + +```markdown +Met with [[Alice]] and [[Bob]] to discuss the Q2 roadmap. Alice will lead the backend migration. +``` + +The `[[Alice]]` and `[[Bob]]` links connect this meeting note to their person pages. + +# 3. Add tasks that mention people +Write tasks that reference person pages: + +```markdown +* [ ] Send proposal to [[Alice]] +* [ ] Schedule follow-up with [[Bob]] +* [ ] Share roadmap doc with [[Alice]] and [[Bob]] +``` + +These tasks are now linked to both the meeting notes page and the person pages. + +# 4. See a person's full history +Open Alice’s page. Two things happen automatically: + +* **[[Linked Tasks]]** at the top shows all incomplete tasks from other pages that mention Alice (like “Send proposal to Alice” from your meeting notes). +* **[[Linked Mention|Linked Mentions]]** at the bottom shows every page that references Alice — meeting notes, project pages, anything. + +Alice’s page becomes an automatic activity log without you maintaining it. + +# 5. Query across your network +Build useful views on a “People” page or your home page: + +```lua +# People at Acme Corp +${query[[from p = tags.person where p.company == "Acme Corp"]]} +``` + +Show all people, grouped by company: + +```lua +${query[[ + from p = tags.person + order by p.company +]]} +``` + +# What’s next? +You now have a very basic personal CRM: person pages with structured data, meeting notes that link to attendees, tasks that reference people, and automatic activity logs via linked mentions and linked tasks. + +* [[Guide/Knowledge Base]] — build a personal knowledge base +* [[Guide/Task Management]] — track projects and tasks +* [[Manual]] — the full user manual diff --git a/website/Guide/Task Management.md b/website/Guide/Task Management.md new file mode 100644 index 00000000..d0d4c13b --- /dev/null +++ b/website/Guide/Task Management.md @@ -0,0 +1,99 @@ +#guide + +This guide walks you through a project and task management workflow. You'll learn how tasks, frontmatter, linked tasks, and queries combine into a lightweight project tracker — no extra tools needed. + +# 1. Create a project page +Make a page called "Website Redesign" with structured [[Frontmatter]]: + +```yaml +--- +tags: project +status: active +priority: high +--- +``` + +Below the frontmatter, write a brief description of the project and its goals. + +# 2. Add tasks +Type `/task` to insert a task (or just type `* [ ] ` directly). Add a few tasks on the project page: + +```markdown +* [ ] Write the project proposal +* [ ] Create wireframes +* [ ] Set up staging environment +``` + +Click a checkbox to mark a task as done. All tasks are automatically indexed and queryable. + +# 3. Annotate tasks with attributes +Add metadata to tasks using [[Attribute]] syntax: + +```markdown +* [ ] Write the proposal [deadline: "2026-03-15"] [priority: high] +* [ ] Review design mockups [assignee: Alice] +``` + +Optionally hashtags on tasks to categorize them: + +```markdown +* [ ] Get client approval #waiting +``` + +This task is now tagged both `task` and `waiting`, so you can query either tag. + +# 4. Scatter tasks across pages +Real tasks don’t all live in one place — they come up in meetings, while reading, or during other work. Create a page like "Meeting Notes/2026-03-04" and write tasks that link back to the project: + +```markdown +* [ ] Send updated mockups to client [[Website Redesign]] +* [ ] Schedule review meeting [[Website Redesign]] +``` + +The `[[Website Redesign]]` link connects these tasks to the project. + +# 5. See linked tasks automatically +Navigate to your "Website Redesign" page. At the top, the **[[Linked Tasks]]** widget shows all incomplete tasks from _other_ pages that link to this page — including the ones from your meeting notes. + +You can check off a linked task from either page; the state change propagates. No manual copying or moving of tasks needed. + +# 6. Build a dashboard +Create a "Dashboard" page that pulls everything together using [[Space Lua/Lua Integrated Query]]: + +```lua +# Active projects +${query[[from p = tags.project where p.status == "active"]]} +``` + +Add a section for (recently) open tasks (maximum 10): + +```lua +# Open tasks +${template.each(query[[ + from t = tags.task + where not t.done + order by t.lastModified desc + limit 10 +]], templates.taskItem)} +``` + +And a section for tasks with deadlines: + +```lua +# Due soon +${template.each(query[[ + from t = tags.task + where not t.done and t.deadline + order by t.deadline + limit 5 +]], templates.taskItem)} +``` + +Each section updates live as you add, complete, or modify tasks across your space. + +# What's next? +You now have a project tracking system: project pages with frontmatter, tasks scattered naturally across pages, linked tasks that connect everything, and a dashboard for the big picture. + +* [[Guide/Knowledge Base]] — build a personal knowledge base +* [[Guide/People Notes]] — keep track of people and conversations +* [[Manual]] — the full user manual diff --git a/website/Quick Start.md b/website/Quick Start.md new file mode 100644 index 00000000..b259185a --- /dev/null +++ b/website/Quick Start.md @@ -0,0 +1,94 @@ +#getting-started + +Welcome! This guide gets you from zero to productive with SilverBullet in about five minutes. + +# 1. Install and run +The fastest way to get started is with Docker: + +```shell +docker run -p 3000:3000 -v ./space:/space ghcr.io/silverbulletmd/silverbullet +``` + +Or download the [[Install/Binary|single binary]] and run it: + +```shell +silverbullet ./space +``` + +Now open http://localhost:3000 in your browser. + +> **note** Tip +> For a full breakdown of installation options, see [[Install]]. + +# 2. Create your first page +Click the page icon in the [[Top Bar]] (or press `Cmd-k` / `Ctrl-k`) to open the [[Page Picker]]. Type a page name like "My First Page" and press Enter — SilverBullet creates it instantly. + +Start typing. Everything is [[Markdown]]. + +# 3. Link pages together +Type `[[` to link to another page. SilverBullet autocompletes page names for you. Links are bi-directional: the linked page will show a [[Linked Mention]] back to the page you're writing. + +# 4. Add some structure +Tag a page by adding a hashtag on an empty line (see [[Markdown/Hashtags#Scope rules]]), for instance `#project`. Or add structured data using [[Frontmatter]] at the top of a page: + +```yaml +--- +status: active +priority: high +tags: project +--- +``` + +These attributes become queryable, which we’re going to do next. + +# 5. Run your first queries +Pages in SilverBullet can use [[Space Lua]] and [[Space Lua/Lua Integrated Query]] feature specifically to dynamically generate content. Add this to any page: + +```lua +${query[[from tags.page limit 5]]} +``` + +As you move your mouse cursor outside this code fragment, it renders a live table of your pages, right inline. Queries update as your space changes dynamically. + +Now, let’s write a query that finds all your pages tagged with `#project` (as done in the previous step) filtered on only high priority ones: + +```lua +${query[[from p = tags.project where p.priority == "high"]]} +``` + +# 6. Use a template to customize query rendering +By default, queries are rendered as tables, however you can render them in other ways as well. SilverBullet comes with a set of pre-defined [[^Library/Std/Infrastructure/Query Templates]] you can use, for instance: + +```lua +# High qriority projects +${template.each(query[[ + from p = tags.project + where p.priority == "high" + order by p.lastModified desc +]], templates.pageItem)} +``` + +This renders your 5 most recently updated high-priority projects as a bulleted list (an `item` in SilverBullet parlance). + +Of course, you can also create custom templates. Either as reusable Lua functions, or inline: + +```lua +# High qriority projects +${template.each(query[[ + from p = tags.project + where p.priority == "high" + order by p.lastModified desc +]], template.new[==[ + * ${name} (status: ${status}) +]==])} +``` + +# What's next? +Now that you know the basics, explore these guides for real-world workflows: + +* [[Guide/Knowledge Base]] — build a personal knowledge base +* [[Guide/Task Management]] — track projects and tasks +* [[Guide/People Notes]] — keep track of people and conversations +* [[Manual]] — the full user manual +* [[Space Lua]] — learn more about the scripting language that gives SilverBullet a lot of its power +* [[Object]] — understand how SilverBullet indexes your content diff --git a/website/Space Lua/DOM.md b/website/Space Lua/DOM.md new file mode 100644 index 00000000..07b2e876 --- /dev/null +++ b/website/Space Lua/DOM.md @@ -0,0 +1,100 @@ +The DOM builder API provides a clean, declarative way to construct HTML elements from [[Space Lua]]. It is typically used to build [[API/widget|Widgets]] for rendering dynamic UI in your pages. + +The full API reference is at [[API/dom]]. + +# Basic usage +Every HTML tag is available as a function on the `dom` table. Call it with a table of attributes and children: + +```lua +dom.div { + class = "my-container", + dom.h2 { "Hello!" }, + dom.p { "This is a paragraph." } +} +``` + +This creates a `
` with a class attribute, containing an `

` and a `

`. + +# Attributes and content +String keys in the table become HTML attributes. Numeric entries become children: + +```lua +dom.a { + href = "https://example.com", + "Click here" +} +``` + +**Markdown support**: String children are automatically processed as markdown. So `"**bold**"` renders as bold text. + +**Nested elements**: Other `dom.*` calls can be nested as children to build up a tree. + +# Event handlers +Attributes starting with `on` are registered as event listeners: + +```lua +dom.button { + onclick = function() + editor.flashNotification("Clicked!") + end, + "Click me" +} +``` + +This is equivalent to calling `addEventListener("click", fn)` on the button element. + +# Rendering as a widget +DOM elements need to be wrapped in a widget to display on a page. Use `widget.html` for inline or `widget.htmlBlock` for block-level: + +```lua +-- Inline widget (rendered within text flow) +widget.html(dom.span { class = "badge", "New" }) + +-- Block widget (gets its own block) +widget.htmlBlock(dom.table { + dom.tr { + dom.td { "Name" }, + dom.td { "Value" } + } +}) +``` + +# Building tables dynamically +A common pattern is building HTML tables from query results: + +```lua +local rows = {} +for page in query[[ from index.tag "page" limit 5 ]] do + table.insert(rows, dom.tr { + dom.td { "[[" .. page.name .. "]]" }, + dom.td { os.date("%Y-%m-%d", page.lastModified) } + }) +end + +return widget.htmlBlock(dom.table { + dom.thead { + dom.tr { + dom.td { "Page" }, + dom.td { "Modified" } + } + }, + dom.tbody(rows) +}) +``` + +# Embedding widgets inside DOM +Widget objects (like buttons from `widgets.button`) can be nested inside DOM elements: + +```lua +dom.div { + "Status: ", + widgets.button("Refresh", function() + editor.invokeCommand("System: Reload") + end) +} +``` + +# How it works +Under the hood, `dom` uses a Lua metatable so that any property access (e.g. `dom.span`) returns a constructor function. That function calls `js.window.document.createElement(tag)` and processes the spec table to set attributes, add event listeners, and append children. + +See also: [[API/dom]], [[API/widget]], [[Space Lua/Widget]] diff --git a/website/Space Lua/JavaScript Interop.md b/website/Space Lua/JavaScript Interop.md new file mode 100644 index 00000000..f9e9b480 --- /dev/null +++ b/website/Space Lua/JavaScript Interop.md @@ -0,0 +1,64 @@ +Space Lua runs in the browser and has direct access to JavaScript APIs through the `js` module. This enables you to use the browser's native capabilities and import external JavaScript libraries. Use this functionality with caution. With great power comes comes great responsibility. + +The full API reference is at [[API/js]]. + +# Accessing browser APIs +Use `js.window` to access the browser's `window` object: + +```lua +-- Get the current URL +local url = js.window.location.href + +-- Set a timeout +js.window.setTimeout(function() + editor.flashNotification("Timer fired!") +end, 3000) +``` + +# Importing JavaScript modules +Use `js.import` to load JavaScript modules from URLs (typically via CDNs like esm.sh): + +```lua +local lodash = js.import("https://esm.sh/lodash@4.17.21") +local chunks = lodash.chunk({1, 2, 3, 4, 5, 6}, 2) +print(js.stringify(chunks)) -- [[1,2],[3,4],[5,6]] +``` + +# Converting between Lua and JavaScript values +Lua tables and JavaScript objects/arrays are different types. Space Lua tries its best to map between them the best in can, but sometimes you may need finer grained control: + +* `js.tojs(luaValue)` — converts a Lua value to its JavaScript equivalent +* `js.tolua(jsValue)` — converts a JavaScript value to its Lua equivalent + +# Creating JavaScript objects +Use `js.new` to instantiate JavaScript classes: + +```lua +local obj = js.new(SomeConstructor, arg1, arg2) +``` + +# Async transparency +Space Lua handles JavaScript promises transparently. When a JavaScript function returns a Promise, Space Lua automatically awaits it — you don't need to write any special async/await code: + +```lua +-- This just works, even though fetch() returns a Promise +local response = js.window.fetch("https://api.example.com/data") +``` + +# Iterating JavaScript async iterables +Use `js.eachIterable` to iterate over JavaScript async iterables: + +```lua +for value in js.eachIterable(someAsyncIterable) do + print(value) +end +``` + +# Logging +Use `js.log` to write to the browser's developer console: + +```lua +js.log("Debug:", {name = "test", count = 42}) +``` + +See also: [[API/js]], [[Space Lua]] diff --git a/website/Space Lua/Standard Library.md b/website/Space Lua/Standard Library.md new file mode 100644 index 00000000..fdebb138 --- /dev/null +++ b/website/Space Lua/Standard Library.md @@ -0,0 +1,108 @@ +Space Lua includes a comprehensive standard library based on Lua 5.4, with additional non-standard extensions useful for text processing and note-taking workflows. + +This page gives an overview. Each module has its own detailed API reference page. + +# Global functions +The following functions are available globally (no module prefix needed): + +| Function | Description | +|---|---| +| `print(...)` | Print to the log (browser console or server log) | +| `type(v)` | Returns the type of a value as a string | +| `tostring(v)` | Converts a value to its string representation | +| `tonumber(s)` | Converts a string to a number | +| `assert(expr, msg?)` | Raises an error if `expr` is falsy | +| `error(msg)` | Throws an error | +| `pcall(fn, ...)` | Calls a function in protected mode, catching errors | +| `xpcall(fn, handler)` | Like `pcall` but with a custom error handler | +| `pairs(t)` | Iterator over all key-value pairs in a table | +| `ipairs(t)` | Iterator over integer-keyed entries in order | +| `unpack(t)` | Unpacks a table into individual values | +| `setmetatable(t, mt)` | Sets the metatable for a table | +| `getmetatable(t)` | Gets the metatable of a table | +| `rawset(t, k, v)` | Sets a table key bypassing metamethods | +| `dofile(path)` | Loads and executes a `.lua` file from your space | + +**Non-standard globals:** + +| Function | Description | +|---|---| +| `each(t)` | Iterator over values only (no indices) | +| `some(v)` | Returns `nil` if value is "empty" (empty table, whitespace-only string, inf, nan), otherwise returns the value unchanged | + +`some()` is particularly useful in templates and queries for handling missing data gracefully: + +```lua +print(some("hello")) -- hello +print(some("")) -- nil +print(some({})) -- nil +print(some({}) or "empty") -- empty +``` + +Full reference: [[API/global]] + +# string +Standard Lua string operations plus useful extensions. Since strings have `string` as their metatable, you can call these as methods: `s:startsWith("h")`. + +**Non-standard extensions:** + +| Function | Description | +|---|---| +| `string.split(s, sep)` | Splits a string by separator | +| `string.startsWith(s, prefix)` | Tests if a string starts with a prefix | +| `string.endsWith(s, suffix)` | Tests if a string ends with a suffix | +| `string.trim(s)` | Strips whitespace from both ends | +| `string.trimStart(s)` | Strips leading whitespace | +| `string.trimEnd(s)` | Strips trailing whitespace | +| `string.matchRegex(s, pattern)` | Matches against a JavaScript regex | +| `string.matchRegexAll(s, pattern)` | Iterator over all JavaScript regex matches | + +> **warning** Lua patterns vs. regex +> Standard Lua `string.find`, `string.match`, `string.gmatch`, and `string.gsub` use Lua patterns, which are _not_ regular expressions. See [[API/string]] for differences. Use `matchRegex`/`matchRegexAll` when you need full regex support. + +Full reference: [[API/string]] + +# table +Table manipulation functions, plus non-standard extensions: + +| Function | Description | +|---|---| +| `table.keys(t)` | Returns an array of all keys | +| `table.includes(t, value)` | Checks if a list contains a value | +| `table.find(t, fn, from?)` | Finds first element matching a criteria function | +| `table.select(t, keys...)` | Returns a new table with only selected keys | + +Full reference: [[API/table]] + +# math +Standard Lua math functions (`abs`, `ceil`, `floor`, `max`, `min`, `sqrt`, `sin`, `cos`, trigonometric functions, etc.) plus: + +| Function | Description | +|---|---| +| `math.cosineSimilarity(a, b)` | Cosine similarity between two vectors | + +Full reference: [[API/math]] + +# os +Date and time functions: + +| Function | Description | +|---|---| +| `os.time(table?)` | Current Unix timestamp, or timestamp for a specific date | +| `os.date(format?, timestamp?)` | Formats a timestamp as a string | + +Full reference: [[API/os]] + +# encoding +Functions for encoding and decoding data: + +| Function | Description | +|---|---| +| `encoding.base64Encode(data)` | Encode data as base64 | +| `encoding.base64Decode(s)` | Decode a base64 string | +| `encoding.utf8Encode(s)` | Encode a UTF-8 string to bytes | +| `encoding.utf8Decode(data)` | Decode bytes to a UTF-8 string | + +Full reference: [[API/encoding]] + +See also: [[Space Lua]], [[Space Lua/JavaScript Interop]] diff --git a/website/Virtual Pages.md b/website/Virtual Pages.md new file mode 100644 index 00000000..53d4cdaf --- /dev/null +++ b/website/Virtual Pages.md @@ -0,0 +1,75 @@ +--- +description: A page generated dynamically by code rather than stored as a file. +tags: glossary +--- + +Virtual pages are read-only pages that don't exist as files in your space. Instead, they are generated dynamically when you navigate to them. This is useful for building pages whose content is computed on-the-fly — for example, pages that show all objects with a particular tag. + +# How it works +You define a virtual page by calling `virtualPage.define` with a Lua pattern and a function. When someone navigates to a page name matching the pattern, SilverBullet calls your function instead of loading a file from disk. + +The function receives the captured groups from the pattern as arguments, and returns the markdown content to display. + +```lua +virtualPage.define { + pattern = "greeting:(.+)", + run = function(name) + return "# Hello, " .. name .. "!\nWelcome to this virtual page." + end +} +``` + +Navigating to `greeting:World` renders a page with the heading "Hello, World!" — but no file is created. + +Virtual pages are always **read-only**. The editor disables editing controls automatically. + +# Built-in virtual pages + +## Tag pages +The most commonly used virtual pages are **tag pages**. When you click a hashtag like `#project`, SilverBullet navigates to `tag:project`, which is a virtual page that lists all objects with that tag — grouped by type (pages, tasks, items, data, etc.). + +Tag pages are defined in the standard library and work out of the box. You can override the default tag page by defining your own `virtualPage.define` with the pattern `tag:(.+)`. + +## URI pages +Navigating to a page named `uri:https://example.com/page` fetches and displays the content from that URL. This is useful for pulling in external markdown content. + +# Defining your own virtual pages +Here's a more complete example that queries the object index: + +```lua +virtualPage.define { + pattern = "recent:(%d+)", + run = function(count) + local n = tonumber(count) + local pages = query[[ + from index.tag "page" + order by lastModified desc + limit n + ]] + local result = "# " .. count .. " Most Recent Pages\n" + for _, page in ipairs(pages) do + result = result .. "* [[" .. page.name .. "]]\n" + end + return result + end +} +``` + +Navigate to `recent:10` to see the 10 most recently modified pages. + +# Multiple capture groups +Patterns can capture multiple groups, each passed as a separate argument: + +```lua +virtualPage.define { + pattern = "lookup:(.+):(.+)", + run = function(type, id) + return "# " .. type .. "\nLooking up: " .. id + end +} +``` + +# How it works under the hood +Virtual page definitions are stored in the config system under the `virtualPages` key. When a page is being created, SilverBullet fires the `editor:pageCreating` event. The standard library's event listener checks all registered patterns against the page name. If a match is found, the corresponding `run` function is called, and its return value becomes the page content with read-only permissions. + +See also: [[API/event]], [[API/config]] From 405899781eeed2330bfbdfd45e2fb1f4d79dde6a Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 4 Mar 2026 14:23:59 +0100 Subject: [PATCH 19/22] Added journaling guide to website content --- website/Guide/Knowledge Base.md | 1 + website/Guide/People Notes.md | 1 + website/Guide/Task Management.md | 1 + website/Manual.md | 1 + 4 files changed, 4 insertions(+) diff --git a/website/Guide/Knowledge Base.md b/website/Guide/Knowledge Base.md index f11c1b26..27fc2093 100644 --- a/website/Guide/Knowledge Base.md +++ b/website/Guide/Knowledge Base.md @@ -67,6 +67,7 @@ Use [[Transclusions]] to pull content from one page into another. For instance o # What's next? You now have the core pattern: create pages, link them, add structure with tags and frontmatter, and query across your space. +* [[Guide/Journaling]] — set up a daily journal * [[Guide/Task Management]] — track projects and tasks * [[Guide/People Notes]] — keep track of people and conversations * [[Manual]] — the full user manual diff --git a/website/Guide/People Notes.md b/website/Guide/People Notes.md index ef400ae6..bb5c1080 100644 --- a/website/Guide/People Notes.md +++ b/website/Guide/People Notes.md @@ -78,6 +78,7 @@ ${query[[ # What’s next? You now have a very basic personal CRM: person pages with structured data, meeting notes that link to attendees, tasks that reference people, and automatic activity logs via linked mentions and linked tasks. +* [[Guide/Journaling]] — set up a daily journal * [[Guide/Knowledge Base]] — build a personal knowledge base * [[Guide/Task Management]] — track projects and tasks * [[Manual]] — the full user manual diff --git a/website/Guide/Task Management.md b/website/Guide/Task Management.md index d0d4c13b..f31dc11a 100644 --- a/website/Guide/Task Management.md +++ b/website/Guide/Task Management.md @@ -94,6 +94,7 @@ Each section updates live as you add, complete, or modify tasks across your spac # What's next? You now have a project tracking system: project pages with frontmatter, tasks scattered naturally across pages, linked tasks that connect everything, and a dashboard for the big picture. +* [[Guide/Journaling]] — set up a daily journal * [[Guide/Knowledge Base]] — build a personal knowledge base * [[Guide/People Notes]] — keep track of people and conversations * [[Manual]] — the full user manual diff --git a/website/Manual.md b/website/Manual.md index 08f0cea8..27a235da 100644 --- a/website/Manual.md +++ b/website/Manual.md @@ -7,6 +7,7 @@ However, that is all unlikely to happen unless you understand what SilverBullet # Guides Practical walkthroughs for common workflows: +* [[Guide/Journaling]] — set up a daily journal * [[Guide/Knowledge Base]] — build a personal knowledge base * [[Guide/Task Management]] — track projects and tasks * [[Guide/People Notes]] — keep track of people and conversations From 6387b3a864731475e0974c3947fdca15148ab268 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 4 Mar 2026 14:24:27 +0100 Subject: [PATCH 20/22] Actually include the Journaling guide... --- website/Guide/Journaling.md | 83 +++++++++++++++++++++++++++++++++++++ website/Quick Start.md | 1 + 2 files changed, 84 insertions(+) create mode 100644 website/Guide/Journaling.md diff --git a/website/Guide/Journaling.md b/website/Guide/Journaling.md new file mode 100644 index 00000000..4d8c7398 --- /dev/null +++ b/website/Guide/Journaling.md @@ -0,0 +1,83 @@ +#guide + +This guide sets up a daily journaling workflow. Each day you get a fresh journal page where you capture what's happening throughout the day. By linking to topic pages from your journal entries, those entries automatically appear on the topic page via [[Linked Mention|Linked Mentions]] — building a timeline of activity for every topic you care about. + +# 1. Create the journal template +Create a page called `Library/Page Tempaltes/Journal` (or any name you like) with the following content: + +``` +--- +command: "Journal: Today" +key: "Ctrl-q t" +suggestedName: "Journal/${os.date('%Y-%m-%d')}" +confirmName: false +tags: meta/template/page +openIfExists: true +--- +#journal + +* |^| +``` + +This is a [[Page Template]] that: +* Registers a `Journal: Today` command (accessible from the [[Command Palette]]) +* Binds it to `Ctrl-q t` (first press `Ctrl-q` then press `t`) for quick access +* Creates pages under `Journal/` named by today's date (e.g. `Journal/2026-03-04`) +* Opens the existing page if you've already started one today +* Tags the page `#journal` and places the cursor at the first bullet + +Optionally, you may also create an [[^Library/Std/APIs/Action Button]] in your top bar for quick access. For this put the following in your [[CONFIG]]: +```lua +actionButton.define { + icon = "pen-tool", + priority = 3, -- or whatever order puts it in the spot you like + run = function() + editor.invokeCommand "Journal: Today" + end +} +``` + +Then run the ${widgets.commandButton("System: Reload")} command to activate. + +# 2. Start journaling +Press `Ctrl-q t` (or run `Journal: Today` from the Command Palette). You’ll land on today’s journal page with a bullet list ready to go. + +The real power comes from linking journal entries to topic pages. Instead of plain text, reference the pages that matter: + +```markdown +* Reviewed the Q2 roadmap with [[Alice]] and [[Bob]] + * Agreed to prioritize the API redesign + * [[Alice]] will draft the migration plan +* Started reading [[Invisible Cities]] +* Fixed a bug in the [[Login Flow]] + * Root cause was a missing null check in the session handler +``` + +Each `[[link]]` connects that journal entry (and its sub-items) to the referenced page. + +# 4. Watch topic pages come alive +Navigate to Alice’s page. In the [[Linked Mention]] section at the bottom, you’ll see your journal entries that mention her — complete with the surrounding context and sub-items. Tomorrow’s journal entry mentioning Alice will appear there too. + +Over time, each topic page accumulates a reverse-chronological log of every journal entry that references it. You don’t maintain this log — it builds itself from your daily writing. + +This works for any kind of page: people, projects, concepts, books. Your journal becomes the connective tissue between all your topics. + +# 5. Query your journal +Use [[Space Lua/Lua Integrated Query]] to pull insights from your journal pages. For example, show recent journal entries on your [[Index Page]]: + +```lua +${template.each(query[[ + from j = tags.journal + where j.tag == "page" + order by j.name desc + limit 7 +]], templates.pageItem)} +``` + +# What's next? +You now have a daily journaling workflow where topic pages automatically collect every mention from your journal entries. + +* [[Guide/Knowledge Base]] — build a personal knowledge base +* [[Guide/Task Management]] — track projects and tasks +* [[Guide/People Notes]] — keep track of people and conversations +* [[Manual]] — the full user manual diff --git a/website/Quick Start.md b/website/Quick Start.md index b259185a..0260b36f 100644 --- a/website/Quick Start.md +++ b/website/Quick Start.md @@ -86,6 +86,7 @@ ${template.each(query[[ # What's next? Now that you know the basics, explore these guides for real-world workflows: +* [[Guide/Journaling]] — set up a daily journal * [[Guide/Knowledge Base]] — build a personal knowledge base * [[Guide/Task Management]] — track projects and tasks * [[Guide/People Notes]] — keep track of people and conversations From 9a92bced1fe85573b975dfea18ec4c34c32bdc9f Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 4 Mar 2026 14:55:19 +0100 Subject: [PATCH 21/22] CHANGELOG updates --- website/CHANGELOG.md | 62 +++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 21 deletions(-) diff --git a/website/CHANGELOG.md b/website/CHANGELOG.md index 337943c3..85484e7d 100644 --- a/website/CHANGELOG.md +++ b/website/CHANGELOG.md @@ -1,12 +1,35 @@ An attempt at documenting the changes/new features introduced in each release. ## Edge -Whenever a commit is pushed to the `main` branch, within ~10 minutes, it will be released as a docker image with the `:v2` tag, and a binary in the [edge release](https://github.com/silverbulletmd/silverbullet/releases/tag/edge). If you want to live on the bleeding edge of SilverBullet goodness (or regression) this is where to do it. +Whenever a commit is pushed to the `main` branch, within ~5 minutes, it will be released as a docker image with the `:v2` tag, and a binary in the [edge release](https://github.com/silverbulletmd/silverbullet/releases/tag/edge). If you want to live on the bleeding edge of SilverBullet goodness (or regression) this is where to do it. * New _experimental_ API: [[API/tag#tag.define(spec)]], see linked page for docs and example uses. Brings back ability to define 📅 deadlines for tasks (see example). Another part of this is [[Schema]] support for [[Tag|tags]]. When a schema is defined for a tag, you get: * [[Frontmatter]] **attribute completion and linting** (in-editor error indicators) for attributes defined as part of the tag’s schema. - * [[Space Lua/Lua Integrated Query]] **attribute code completion** _if_ you use the `from v = index.tag("bla")` style syntax (so explicitly bind your iterator variable). + * [[Space Lua/Lua Integrated Query]] **attribute code completion** _if_ you use the `from v = index.tag(“bla”)` style syntax (so explicitly bind your iterator variable). * Item-level linting (highlights the object in-line in case of validation errors). +* Tag schema updates: + * `pos` (present in link, item and some other tags) is now _deprecated_, use `range` instead + * `range` is a tuple of two numbers: _from_ and _to_ (e.g. `{0, 10}`) identify where the object appears in the page +* [[Space Lua/Lua Integrated Query]] improvements (courtesy of [Matouš Jan Fialka](https://github.com/mjf)): + * [[Space Lua/Lua Integrated Query/Grouping|group by]] and `having` clauses with [[Space Lua/Lua Integrated Query/Aggregating|aggregator]] support + * `filter(where )` clause for per-row aggregate filtering + * `nulls first`/`nulls last` in `order by` + * Null/missing query cells now render as empty +* [[Space Lua]] engine general improvements (also courtesy of [Matouš Jan Fialka](https://github.com/mjf)): + * [Native Lua pattern matching engine](https://github.com/silverbulletmd/silverbullet/pull/1838) (replacing previous implementation) + * [Support for `` attribute and __close metamethod](https://github.com/silverbulletmd/silverbullet/commit/9419cdcd9be61908330e1dce68a9156dbb911d23) + * [Better arithmetic error messages](https://github.com/silverbulletmd/silverbullet/commit/5a20a5f8f476a98172609e80c799cd1d83765585) + * [Refactor of control flow (performance)](https://github.com/silverbulletmd/silverbullet/commit/e5b4c8feb22a44cb4b22b3a77f9f2ed21dd09297) + * [Improved numeric type semantics](https://github.com/silverbulletmd/silverbullet/pull/1803) + * Implement `string.pack`, `string.unpack` and `string.packsize` + * Implement `math.random`, `math.randomseed`, `math.tointeger`, `math.frexp` and `math.ldexp` + * Implement `table.move`; align `table.pack` and `table.unpack` with Lua semantics + * [Extend `os` module](https://github.com/silverbulletmd/silverbullet/pull/1836) + * Add `_VERSION` environment variable + * `tostring()` now respects `__tostring` metamethod; `#` operator now respects `__len` metamethod + * Fix: `table.sort` comparator, `string.gsub` table replacement, `math.modf` return types, number formatting in `..` and `table.concat` +* Lua APIs: + * [[API/table#table.select(table, keys...)]] (non-standard in Lua) API, convenient to use in [[Space Lua/Lua Integrated Query]] `select` clauses, see example in docs. * Changed keyboard bindings (sorry!). CodeMirror no longer directly allows `Alt-` and `Alt-` [[Keyboard Shortcuts]], meaning I had to **remap a few key bindings**. It’s basically a mission impossible to pick great ones, but here are the new defaults: * `Quick note` is now bound to both `Ctrl-q q` (type `Ctrl-q` first, then hit `q` again) and `Ctrl-q Ctrl-q` (hit `Ctrl-q` twice) * `Navigate: Home` is now bound to `Ctrl-g h` @@ -22,31 +45,28 @@ Whenever a commit is pushed to the `main` branch, within ~10 minutes, it will be * `Page: Rename` keyboard shortcut removed * `Page: Rename Linked Page` keyboard shortcut removed * `Sync: Space` keyboard shortcut removed -* Sync reliability work: + * As documented in [[Keyboard Shortcuts]], it is now possible to specify _multiple_ keyboard shortcuts to a commands. +* [[Sync]] reliability work: * Better indication whether your page is synced to the server: “Dirty state” (slightly tinted color of page name) is now aligned with actual synced-to-server state _unless_ the editor clearly indicates it is in offline mode (yellow top bar). * Sync snapshots are now persisted after every file sync, reducing (and hopefully eliminating) edge cases where the sync engine is killed mid-sync (for whatever reason) and the snapshot becomes of sync with “reality”. * The index status progress indicator (blue circle) should now be more reliably reflect the actual indexing status. -* Tag schema updates: - * `pos` (present in link, item and some other tags) is now _deprecated_, use `range` instead - * `range` is a tuple of two numbers: _from_ and _to_ (e.g. `{0, 10}`) identify where the object appears in the page -* Lua engine improvements (courtesy of [Matouš Jan Fialka](https://github.com/mjf)): - * [Support for `` attribute and __close metamethod](https://github.com/silverbulletmd/silverbullet/commit/9419cdcd9be61908330e1dce68a9156dbb911d23) - * [Better arithmetic error messages](https://github.com/silverbulletmd/silverbullet/commit/5a20a5f8f476a98172609e80c799cd1d83765585) - * [Refactor of control flow (performance)](https://github.com/silverbulletmd/silverbullet/commit/e5b4c8feb22a44cb4b22b3a77f9f2ed21dd09297) - * [Improved numeric type semantics](https://github.com/silverbulletmd/silverbullet/pull/1803) -* Lua APIs: - * [[API/table#table.select(table, keys...)]] (non-standard in Lua) API, convenient to use in [[Space Lua/Lua Integrated Query]] `select` clauses, see example in docs. -* Library manager: SilverBullet now navigates to library page after installing one. + * HTTP status codes >= 500 are now treated as offline (better offline detection). +* Editor improvements: + * New `Page: Create Under Cursor` command, useful to pre-create an aspiring page link. Put your cursor in a wiki link to a non-existing page, and hit `Cmd-Shift-Enter` (`Ctrl-Shift-Enter`) to create it (empty) without navigating there. + * [[Linked Mention|Linked Mentions]] now list full page path rather than abbreviated version. + * Hide vertical scrollbar overflow for long page names. + * Upload file: prompt user before replacing files and no-clobber behavior for paste uploads (by [Oliver Marriott](https://github.com/rktjmp)). + * Trim user input from prompts where appropriate (by [rktjmp](https://github.com/rktjmp)). + * Consider empty string as invalid path (by [rktjmp](https://github.com/rktjmp)). * Styling changes: * Attribute names and values ([key: value] notation) now get different CSS classes in the editor: `sb-attribute-name` for names and `sb-attribute-value` for values. -* New `Page: Create Under Cursor` command, useful to pre-create an aspiring page link. Put your cursor in a wiki link to a non-existing page, and hit `Cmd-Shift-Enter` (`Ctrl-Shift-Enter`) to create it (empty) without navigating there. -* Authentication: - * How long “remember me” works is now configurable (by [Metin Yazici](https://github.com/silverbulletmd/silverbullet/pull/1796)) via [[Install/Configuration]] and more reliably persisted. + * The `diff` [[Markdown/Fenced Code Block]] language now uses colors to indicate additions and removals (by [Lajos Papp](https://github.com/silverbulletmd/silverbullet/pull/1807)). +* Configuration: + * New `shortWikiLinks` config (defaulting to `true`) that decides whether a wiki link should be rendered in its short form (rendering just the last segment, e.g. `Person/John` would show as `John`). To always render the full name, put `config.set(“shortWikiLinks”, false)` in your [[CONFIG]]. + * [[Authentication]]: how long “remember me” works is now configurable (by [Metin Yazici](https://github.com/silverbulletmd/silverbullet/pull/1796)) via [[Install/Configuration]] and more reliably persisted. +* [[Library Manager]]: SilverBullet now navigates to library page after installing one. * Now excluding `.plug.js` and `.js.map` files from the document list. -* New `shortWikiLinks` config (defaulting to `true`) that decides whether a wiki link should be rendered in its short form (rendering just the last segment, e.g. `Person/John` would show as `John`). To always render the full name, put `config.set("shortWikiLinks", false)` in your [[CONFIG]]. -* The `diff` [[Markdown/Fenced Code Block]] language now uses colors to indicate additions and removals (by [Lajos Papp](https://github.com/silverbulletmd/silverbullet/pull/1807)) -* As documented in [[Keyboard Shortcuts]], it is now possible to specify _multiple_ keyboard shortcuts to a commands. -* Linked Mentions now list full page path rather than abbreviated version. +* Fix: bring back [[Virtual Pages]]. ## 2.4.0 * Indexer rework (note: upgrading will start a full space reindex automatically): From 1178f7bc922b71785b48f1fcd5fdadbfe3d776ad Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 4 Mar 2026 15:40:59 +0100 Subject: [PATCH 22/22] Fix: ordering of space-lua scripts No priority defined now means priority 0 --- client/space_lua.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/space_lua.ts b/client/space_lua.ts index e68f2a5b..3bf831b2 100644 --- a/client/space_lua.ts +++ b/client/space_lua.ts @@ -31,9 +31,9 @@ export class SpaceLuaEnvironment { { objectVariable: "script", orderBy: [{ - expr: parseExpressionString("script.priority"), + expr: parseExpressionString("script.priority or 0"), desc: true, - nulls: "last", + nulls: "first", }], } as LuaCollectionQuery, );