![]() |
The Scheme database layers | ![]() |
The Scheme interface to databases lives in
src/TeXmacs/progs/database/
. It is organized as a chain of modules, each of which uses the previous one and redefines some of the basic routines with tm-define, calling the previous definition through former:
db-base \(\rightarrow\) db-format \(\rightarrow\) db-users \(\rightarrow\) db-version \(\rightarrow\) db-edit \(\rightarrow\) db-convert
followed by db-markup, db-tmfs, db-widgets and db-menu for the user interface, and by the modules of the individual kinds (bib-db, bib-manage, …, ai-agents-db). The public routines db-set-field, db-get-field, db-set-entry, db-get-entry, db-remove-entry, db-create-entry and db-search are therefore the composition of all loaded layers. The implicit parameters of the layers are global variables which are bound dynamically with with-global by the context macros; db-reset resets all of them (every layer extends it).
The API reference TeXmacs databases documents the public routines of these layers. Two details of that reference are outdated: db-get-field-first takes a third argument (the default value returned when the field is empty), and the macro with-indexing, index-do-indexate? and index-attribute-table no longer exist, since indexing is now done unconditionally in C++ (see The database engine). Below we concentrate on the implementation and on what the reference does not say.
db-base.scm)
current-database
(with-database db . body)
current-database is a URL (initially (url-none), in which case db-get-db raises an error). with-database* moreover disables the history of the database (tmdb-keep-history), so that it gets compressed on disk.
db-time
(with-time t . body)
db-time is :now (the default), :always (all lines, passed as time 0 to C++), a number or a numeric string. db-get-time converts it to the inexact number expected by the glue. Modifications should be done at :now: nothing prevents a modification in the past, but the result would be inconsistent with the journal order.
(with-limit n . body)
(with-extra-fields l . body)
db-limit bounds the number of results of db-search (default \(10^6\)). db-set-entry adds the fields of db-extra-fields which are not already present, and, if db-time-stamp? holds, a date field with the current time. Notice that only db-set-entry (and hence db-create-entry) takes these into account, not db-set-field.
All routines are thin wrappers around the glue of the engine. Worth noting are:
(db-entry-exists? id) tests whether the entry has a name field, not whether the identifier occurs at all.
(db-create-id) draws identifiers with create-unique-id until it finds one without attributes.
(db-search q) rewrites the keyword forms of constraints (:order, :modified, :match, :prefix, :contains, :completes) with rewrite-query before calling tmdb-query; db-search-paginate takes an explicit limit and offset; db-search-name and db-search-owner are shortcuts.
(index-get-completions prefix) and (index-get-name-completions prefix) give access to the keyword and name indices; the latter is used to complete citation keys (
bib-kbd.scm
).
(global-database) returns $TEXMACS_HOME_PATH/server/global.tmdb, the database of a TeXmacs server.
A typical use of the basic layer:
(with-database (url->url "$TEXMACS_HOME_PATH/system/test.tmdb")
(with id (db-create-entry '(("type" "note") ("name" "n1")
("text" "hello world")))
(db-set-field id "text" (list "hello again"))
(list (db-get-field id "text")
(with-time :always (db-get-field id "text"))
(db-search '((:match "hello") (:order "name" #t)))))) |
The second call returns both values, the old and the current one. If the full layer stack is loaded, the values are moreover encoded as TeXmacs snippets, as explained in the next section.
db-format.scm)
Entries have a type field, and databases have a kind which determines the admissible types. Both are declared in smart tables:
maps a kind to its list of entry types, for instance "bib" to ("article" "book" …) in
bib-db.scm
and "ai-agents" to ("corrector" "interlocutor" "translator") in
ai-agents-db.scm
.
maps an entry type to a format: a string (a mandatory field), (and f1 …), (or a1 a2 …) (exactly one of the alternatives should be filled out) or (optional a). format->attributes flattens a format into the list of its attributes. The format is used by the editor to complete entries with empty fields and to decide whether an entry is complete, and by db-get-entry to put the fields in a canonical order.
(db-reserved-attributes) (type, location, dir, date, pseudo, id) and (db-meta-attributes) (date, contributor, modus, origin, newer) are special: meta attributes describe the provenance of an entry, are shown separately in the editor and are ignored when comparing entries.
The engine only stores strings, but most values are really TeXmacs content (a title with mathematics, an author name with name markup). The encoding layer converts values on the fly. For a field attr of an entry of type type, the encoding is looked up in db-encoding-table under the keys (attr type enc), where enc is the current value of db-encoding (set with with-encoding), trying the wildcard * for each component in turn. If nothing is found, the encoding is :texmacs, which means that values are stored as serialized TeXmacs snippets (serialize-texmacs-snippet and parse-texmacs-snippet). The encoders and decoders themselves are found in db-encoder-table and db-decoder-table.
With the default value :default of db-encoding, all values are therefore stored as TeXmacs snippets, and plain strings are essentially stored as themselves. (with-encoding #f …) disables the layer and gives access to the raw strings. The users layer adds a second encoding: under (with-encoding :pseudos …), the permission attributes (owner, readable, …) are converted between user identifiers in the database and user pseudos in Scheme (:users encoder and decoder); the server uses the same mechanism for version-by in
server/server-tmfs.scm
.
db-search encodes the values of its constraints using the type found in a "type" constraint, if any. Keyword searches work on the serialized strings, but since keywords are extracted from the parsed snippets (see), they are not affected by the serialization.
db-users.scm)
The master database $TEXMACS_HOME_PATH/users/users-master.tmdb contains entries of type "user" (fields pseudo and name) and of type "preference". The routines are:
Returns the identifier of the default user. The first time, a user is created from the login name and the full name of the operating system account (create-default-user). add-user uses the pseudo as identifier, so that identifiers of local users usually coincide with their pseudos. The dialogue Data\(\rightarrow\)Open identities (open-identities in
db-widgets.scm
) allows the user to create, rename and delete identities (add-user, remove-user, set-default-user, set-user-info).
(user-database . opt-kind)
(get-preferred-database uid kind)
user-database returns the preferred database of the default user for the given kind, or for (db-get-kind) if no kind is given. The function db-get-kind returns "general" by default and is redefined in the modes in-bib? ("bib") and in-ai-agents? ("ai-agents"), so that inside a buffer showing a database the “current” database is the one of its kind. When no preference exists, the file users/uid/pseudo-kind.tmdb is chosen and recorded. use-database and recent-databases implement the Data\(\rightarrow\)Storage menu; the list of recent databases is simply the history of the value field of the preference entry.
db-current-user (set with with-user) is either #t (root, the default: everything is allowed), a user identifier or a list of identifiers. (db-allow? id uid attr) checks whether one of the users obtained by expanding uid through the groups which delegate attr (db-expand-user; the pseudo-user "all" is always included) occurs in the field attr of the entry; owners have all permissions. The layer redefines the basic routines as follows:
db-get-field and db-get-entry return empty results unless the user is an owner or reader of the entry;
db-set-field, db-set-entry and db-remove-entry do nothing unless the user is an owner (the writable attribute is currently not consulted);
db-create-entry adds the current user(s) to the owner field;
db-search adds a constraint on owner or readable and returns the union of both searches.
Locally, all code runs as root. The permission layer is mainly used by the server, which wraps requests of remote users in with-user (see The remote file system).
db-version.scm)
An entry is never modified in place by the editor: saving a modified entry creates a new entry which supersedes the old one. This is necessary because entries circulate between users (through attachments of documents, synchronization with a server, or shared .bib files), and one needs to decide which version is the most recent.
If new-l equals the current entry up to the meta attributes (db-same-entries?), nothing happens and id is returned. Otherwise a new entry is created (with identifier opt-new-id if given and free), its newer field is set to id followed by the older history, and the old entry is removed.
Imports an entry l which carries its own identifier id. In order:
if id is already used, the entry is ignored (with a warning if the contents differ);
if an identical entry with the same name exists, that entry absorbs id in its newer field;
if some entry declares id as older (newer contains id), the import is cancelled;
all entries listed in the newer field of l are removed;
if an entry with the same name and the same contributor exists, the one entered manually (modus is "manual") wins over an imported one, and otherwise the one with the most recent date;
otherwise the entry is simply stored.
Warnings are sent to the debug channel database-warning with db-warning, and can be silenced with db-duplicate-warning?.
db-convert.scm)
In documents, an entry is represented by the tag
(db-entry id type name (document meta-fields) (document fields)) |
where each field is (db-field attr value), a multi-valued field being represented by several db-field tags with the same attribute. The meta fields (provenance) are stored separately from the ordinary fields. The variants db-folded-entry and db-pretty-entry have the same children and only differ in presentation; db-entry-any? recognizes all three (db-entry? only the first). While editing, db-field-optional and db-field-alternative mark empty optional and alternative fields. Utilities in
db-edit.scm
such as db-entry-ref, db-entry-set, db-entry-remove and db-entry-rename manipulate this markup as Scheme trees, the pseudo attributes "id", "type" and "name" referring to the first three children.
(db-load-entry id)
(assoc-list->entry id l)
(db-load)
Convert entries of the current database into db-entry markup. db-load returns a document with all entries, db-load-types only those of the given types. The hook db-load-post is applied to each entry.
(entry->assoc-list t . opt-skip-pre?)
(db-save t)
(db-save-types t types)
db-save-selected walks through a document, applies the hook db-save-pre to each db-entry or bib-entry whose identifier is not yet in the database, and imports it with db-import-entry. Entries which are already present are skipped: saving is an importation, not an update. Updates of existing entries are done by the editor (db-confirm-entries-in, see Editing databases).
The hooks db-save-pre and db-load-post are the extension points for kinds with a foreign native format. By default they rename the fields id, type and name of the body to id*, type* and name* and back, because these attributes are used for the first three children of db-entry (for instance, the BibTEX field type of a techreport is stored under the attribute type*).
bib-db.scm
additionally converts bib-entry markup with bib->db in db-save-pre.
(db-change-list uid kind t) returns the entries of the given kind (owned by uid unless it is #t) which were modified since time t, as triples of an identifier, a name and the current entry. It is the basis of database synchronization.
Besides the bibliographic and AI agents kinds, the following code uses databases directly:
the TeXmacs server (server/*.scm) stores accounts, files, versions, chat messages and notifications in (global-database), see The TeXmacs server;
the client keeps accounts in (user-database "remote") and synchronization records in (user-database "sync"), see Synchronization of files and databases;
utils/literate/lp-build.scm
calls the glue (tmdb-set-field, tmdb-get-field) directly on system/database/lp-master.tmdb to remember build times.
The kind "ai-agents" is a small and complete example. The steps are:
Declare the entry types and their formats, preferably in a module that uses (database db-convert) and (database db-edit):
(smart-table db-kind-table
("ai-agents" ("corrector" "interlocutor" "translator")))
(smart-table db-format-table
("corrector" (and "instructions"))
…) |
Provide an accessor for the user database of this kind and the routines needed by the rest of TeXmacs, all written inside with-database:
(tm-define (ai-agents-database) (user-database "ai-agents"))
(tm-define (ai-agents-correctors)
(with-database (ai-agents-database)
(with ids (db-search ‘(("type" "corrector")))
…))) |
Write an editing style database-kind.ts which uses the package database and sets db-kind (see
styles/test/database-ai-agents.ts
), and a mode which detects it, redefining db-get-kind in this mode so that user-database and the Insert menu select the right kind:
(texmacs-modes
(in-ai-agents% (style-has? "database-ai-agents-style")))
(tm-define (db-get-kind)
(:mode in-ai-agents?)
"ai-agents") |
Open the database as a document with (load-db-buffer "tmfs://db/ai-agents/global"), register the new modules with lazy-define in
init-texmacs.scm
, and add a menu entry (see db-menu in
db-menu.scm
).
Optionally, redefine db-pretty for the kind (used by the "Pretty" presentation and by the search dialogue), and db-save-pre/db-load-post if entries need to be converted.
If values should not be stored as TeXmacs snippets, add entries to db-encoding-table (and, for a new encoding, to db-encoder-table and db-decoder-table).
Layers are combined through tm-define overloading, so the behavior of db-get-field depends on which modules have been loaded. Code that only uses (database db-base) sees raw strings; code that uses db-format or later layers sees decoded TeXmacs content.
Decoded values are Scheme trees, not necessarily strings; for instance a field entered in the editor may come back as a concat. Code such as (car (db-get-field id "name")) should check for empty lists and non-string values.
Context variables are global and bound dynamically. A callback (for instance a widget action or a delayed command) does not inherit the database of the code that created it; it must use with-database itself. open-db-chooser even calls db-reset.
db-save skips entries whose identifier already exists. To update an entry, use db-update-entry (which changes its identifier) or db-set-entry.
user-database without argument depends on the mode of the current buffer through db-get-kind. Pass the kind explicitly in code which may run in another buffer.