GNU TeXmacsUser manualReferenceAboutEnglish
The Scheme database layers

1.Organization

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.

2.The basic layer (
db-base.scm
)

2.1.Context

current-database

(with-database db . body)

(with-database* db . body)
(the current database)

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-get-time)
(the time of queries and updates)

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)

(with-time-stamp on? . body)
(other context)

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.

2.2.Routines

All routines are thin wrappers around the glue of the engine. Worth noting are:

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.

3.Formats and encodings (
db-format.scm
)

3.1.Kinds, types and formats

Entries have a type field, and databases have a kind which determines the admissible types. Both are declared in smart tables:

db-kind-table

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

.

db-format-table

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.

3.2.Encodings

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.

4.Users and permissions (
db-users.scm
)

4.1.Users and user databases

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:

(get-default-user)
(current user identifier)

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)

(set-preferred-database uid kind db)
(per-user databases)

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.

4.2.Permissions

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:

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).

5.Versions and importation (
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.

(db-update-entry id new-l . opt-new-id)
(create a new version)

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.

(db-import-entry id l)
(import a foreign entry)

Imports an entry l which carries its own identifier id. In order:

  1. if id is already used, the entry is ignored (with a warning if the contents differ);

  2. if an identical entry with the same name exists, that entry absorbs id in its newer field;

  3. if some entry declares id as older (newer contains id), the import is cancelled;

  4. all entries listed in the newer field of l are removed;

  5. 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;

  6. 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?.

6.Entries as documents (
db-convert.scm
)

6.1.The markup

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.

6.2.Conversion routines

(db-load-entry id)

(assoc-list->entry id l)

(db-load)

(db-load-types types)
(database to markup)

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 t pred?)
(markup to database)

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.

7.Other users of the engine

Besides the bibliographic and AI agents kinds, the following code uses databases directly:

8.Adding a new kind of database

The kind "ai-agents" is a small and complete example. The steps are:

  1. 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"))
      …)
  2. 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")))
          …)))
  3. 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")
  4. 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

    ).

  5. 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).

9.Pitfalls

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".