![]() |
The database engine | ![]() |
A TeXmacs database is a list of lines. A line records that, during a certain time interval, the identifier \(i\) has the value \(v\) for the attribute \(a\). Identifiers, attributes and values are arbitrary strings; an identifier together with all its lines is called an entry, and the lines of an entry which share an attribute form a field, which may therefore have several values. The class db_line of
Plugins/Database/database.hpp
is:
typedef int db_atom;
typedef double db_time;
#define DB_MAX_TIME ((db_time) 10675199166.0)
class db_line_rep: public concrete_struct {
public:
db_atom id;
db_atom attr;
db_atom val;
db_time created;
db_time expires;
…
}; |
All strings are interned: the first time a string is seen, it gets the next free integer code (an atom), and all tables work on atoms. The mapping is stored in atom_encode (a hashmap<string,db_atom>) and atom_decode (an array). Atoms are never removed.
Times are UNIX time stamps in seconds, stored as doubles but written to disk as integers. A line is alive at time \(t\) if created <= t < expires; a line which has not been removed has expires == DB_MAX_TIME. Nothing is ever deleted from the table: removing a field or an entry only sets the expiration date of its lines. This is what makes it possible to query any past state of a database. The special time \(0\) means “at any time”: queries with \(t = 0\) see all lines, dead or alive. On the Scheme side this corresponds to (with-time :always …), which is used for instance by recent-preferred-databases to recover all past values of a field.
Setting a field at time \(t\) expires all alive lines of this field at \(t\) and appends new lines created at \(t\), one for each value; setting an entry does the same for all fields of the entry. Consequently an update always grows the table, even if the new values are identical to the old ones; the Scheme layer db-update-entry avoids useless updates by comparing entries first.
Besides the table db of lines, database_rep maintains:
id_lines[id] and val_lines[val]: the numbers of the lines with a given identifier resp. value (for each atom, whether it is used as an identifier, attribute or value);
ids_list and ids_set: all identifiers ever used in a line, in order of first appearance;
the keyword index (key_encode, key_decode, key_occurrences, key_completions, atom_indexed) and the name index (name_completions, name_indexed) described in the section on searching below.
All indices are rebuilt in memory when the database is loaded; only the journal of lines and atoms is stored on disk.
database is a concrete (reference counted) handle to database_rep. The public methods of database_rep work on atoms:
void set_field (db_atom id, db_atom attr, db_atoms vals, db_time t)
db_atoms get_field (db_atom id, db_atom attr, db_time t)
void remove_field (db_atom id, db_atom attr, db_time t)
db_atoms get_attributes (db_atom id, db_time t)
void set_entry (db_atom id, db_atoms pairs, db_time t)
db_atoms get_entry (db_atom id, db_time t)
An entry is represented as a flat array pairs of alternating attributes and values. get_field, get_attributes and get_entry only consider the lines alive at time t (all lines if t == 0). The modifying routines call the notification hooks notify_created_atom, notify_extended_field and notify_removed_field, which append the change to the pending journal (see the section on storage below).
Returns the identifiers of the entries which satisfy the query q at time t; query_args contains a limit, an offset and a sort_flag. The format of queries is described in the section on searching below.
bool atom_exists (string s)
db_atom as_atom (string s)
string from_atom (db_atom a)
tree as_tuple (db_atoms a)
db_atoms entry_as_atoms (tree t)
Conversions between strings and atoms, and between the flat representation of entries and the Scheme representation. On the Scheme side an entry is a list of fields ((attr val1 val2 …) …); as a tree (via scheme_tree) this is a tuple of tuples of quoted strings, which explains the calls to scm_quote and scm_unquote. as_atom creates the atom if necessary and journals its creation, see the pitfalls at the end of this page.
The rest of TeXmacs never manipulates database objects directly. Databases are designated by their URL, and
database.cpp
keeps a global table of all databases which have been opened in this process:
array<database> dbs;
hashmap<tree,int> db_index;
database
get_database (url u) {
check_for_updates ();
if (!db_index->contains (u->t)) {
db_index (u->t)= N(dbs);
dbs << database (u);
}
return dbs [db_index [u->t]];
} |
A database is loaded the first time it is used and stays in memory until the end of the session. The following functions, declared at the end of
database.hpp
, convert their string arguments to atoms and call the corresponding method. They are exported to Scheme by
build-glue-basic.scm
; the time argument is a double and Scheme code normally obtains it from (db-get-time).
(tmdb-set-field db id attr vals t)
(tmdb-get-field db id attr t)
(tmdb-remove-field db id attr t)
C++: set_field, get_field, remove_field, get_attributes. vals and the results are lists of strings.
(tmdb-set-entry db id l t)
(tmdb-get-entry db id t)
C++: set_entry, get_entry, remove_entry. The entry l is a list (("type" "article") ("author" "A" "B") …); get_entry groups the values by attribute, in the order of the first occurrence of each attribute.
C++: query. Returns a list of identifiers.
(tmdb-get-completions db prefix)
C++: get_completions, get_name_completions. The first function completes a prefix into indexed keywords, the second into values of name fields (used for completing citation keys).
C++: keep_history. By default the whole history is kept. When the history is not kept, the database file is periodically compressed by rewriting it with the alive lines only (see the section on storage below). The Scheme macro with-database* selects a database and disables its history; it is used for bookkeeping databases such as (user-database "sync").
C++: inspect_history. Prints on standard output all lines with attribute name and value name, together with their creation and expiration dates.
A query is a list of constraints; an entry matches if it satisfies all constraints at the query time. At the C++ level a query is a tree built from a Scheme list, in which strings are quoted and symbols are not. The following constraints are recognized by database_rep::encode_constraint (
db_query.cpp
) and normalize_query (
db_index.cpp
):
where attr is a string: the entry has a line with attribute attr and one of the given values. Values which have never been interned are dropped; if no value remains the constraint cannot be satisfied.
(symbol any): some attribute has one of the given values.
the text is split into keywords (see below) and each keyword becomes a keywords constraint.
like contains, except that the last keyword is replaced by the list of all its completions. This implements “search as you type”.
some value of the entry contains one of the keywords. It is encoded as an any constraint over all values in which the keywords occur. If this list contains more than 1000 values, the constraint is considered too weak and is ignored (it is always satisfied).
always satisfied; requests sorting of the results on attr.
where the times are strings: the entry has a line created or expired in the interval \([t 1, t 2)\) (lines which were both created and removed inside the interval are ignored). This is used by db-change-list for synchronization.
The Scheme function db-search accepts the more readable keyword forms (:order attr asc?), (:modified t1 t2), (:match text) and (:contains text) (both mapped to contains), and (:prefix text) and (:completes text) (both mapped to completes); see rewrite-query in
db-base.scm
.
database_rep::query proceeds as follows:
normalize_query expands contains and completes into keywords constraints.
ansatz chooses the most selective constraint, namely the one for which the total number of lines with one of its values (compute_complexity) is minimal, and computes the candidate identifiers from val_lines. If there is no usable constraint (for instance for the empty query, or when all constraints are order/modified), all identifiers are candidates.
filter checks the remaining constraints for each candidate using id_lines. It skips the first offset candidates and stops after limit matches (no limit if limit == 0). When the query contains an order constraint the limit is raised to at least 1000, since sorting happens afterwards.
modified constraints are applied by filter_modified.
sort_results (
db_sort.cpp
) sorts the results lexicographically on the values of the order attributes (the last alive value of each attribute is used, and the identifier breaks ties). Only the direction of the first order constraint is taken into account.
Notice that the limit and offset are applied before sorting and before the modified filter, so that paginated or limited sorted queries are only approximately correct on large databases.
Whenever a line is created (extend_field), its value is indexed by indexate, unless the attribute is contributor; values of name fields are moreover indexed by indexate_name.
compute_keywords parses the value as a serialized TeXmacs snippet (texmacs_to_tree), and splits all its strings into keywords made of digits, lowercase letters and underscores, after transliteration to ASCII with uni_translit and conversion to lowercase. Hence accented letters match their unaccented versions in searches, and markup in values does not produce spurious keywords.
Each new keyword \(k\) is registered in key_completions[p] for all prefixes \(p\) of \(k\) of at most 6 characters (MAX_PREFIX_LENGTH). To complete a prefix, compute_completions looks up its first 6 characters and filters the candidates with starts.
The name index works in the same way, but on the full values of name fields, without normalization.
The index is purely in memory and only grows: values which are no longer alive remain indexed, which is harmless because the filter checks the lines at the query time.
A .tmdb file is a binary journal of the modifications of the database, which is replayed when the database is loaded (database_rep::initialize and replay in
db_disk.cpp
). It is a sequence of commands, each starting with one byte:
followed by a string: creates the next atom. Atoms are numbered implicitly, in the order of these commands.
followed by four numbers: identifier, attribute, value (as atoms) and creation time. Appends a line.
followed by two numbers: a line number and an expiration time.
Numbers \(n < 248\) are written as the single byte \(n + 8\); larger numbers are written as a byte \(l\) giving their length followed by \(l\) bytes in little endian order. Strings are written as their length followed by their bytes. Since line numbers are implicit as well, the journal can only be interpreted from its beginning.
Modifications are not written immediately. The notification hooks append the encoded commands to the string pending, and the function sync_databases is called by the main loop (tm_server_rep::interpose_handler). For each open database it calls purge, which writes the pending commands:
if there are at most 4096 bytes, they are saved to a temporary file name.append-random which is then appended to the database with append_to;
otherwise the whole new contents (loaded * pending) are saved to name.replace-random, which is then moved over the database file.
In both cases the operation is cancelled if the modification time of the file is more recent than the time stamp recorded at the last read or write, so that another process which modified the file in the meantime is not overwritten. The pending changes are then kept and written after the next reload.
If the history is not kept and more than half of the lines are dead, sync_databases instead builds a compressed clone with the alive lines only (compress), writes it to a temporary file, moves it over the original file and replaces the in-memory database by the clone.
Several TeXmacs processes may use the same database files (typically the user databases). Before writing, sync_databases calls check_for_updates, which reloads every database whose file was modified on disk since it was last read or written, and replays the lines created locally since the last write (replay (clone, start_pending, true)) on top of the reloaded database. After a call to sync_databases, the next access through get_database performs the same check. The detection relies on file modification times with a resolution of one second. The comments in the code acknowledge that the test and the write are not a single atomic operation and that the reload is not incremental; this mechanism should therefore be understood as a best effort for occasional concurrent use, not as a transactional database.
Reading may write. The functional interface converts all strings to atoms with as_atom, which creates and journals atoms for unknown strings. Reading a field of an unknown identifier, or testing whether an identifier is free (db-create-id does this in a loop), therefore appends a few bytes to the database file.
No real deletion. With history enabled (the default), a database only grows. Use with-database* (or tmdb-keep-history) for bookkeeping data which changes often.
Times have a resolution of one second. Two modifications of the same field within the same second create lines which are never alive (created and expired at the same time), which is correct for the current state but loses intermediate history.
Limits. db-search uses a default limit of \(10^6\) results, and sorted queries consider at most \(\max (\operatorname{limit}, 1000)\) matches before sorting.
Concurrent replays lose some information. When a database is reloaded because another process modified it, only the lines created locally since the last write are replayed; a pending removal of a line written earlier is not replayed, and replayed lines which were removed get their creation date as expiration date.
No SQLite. The functions sql-exec, sql-quote and supports-sql? (
Plugins/Sqlite3/
) are an older experiment which is not used by the database engine nor by any Scheme module.