Bibliothecula: Using sqlite3 as a Notekeeping Document Graph with Automatic Reference Indexing #779
Labels
New-Label
Choose this option if the existing labels are insufficient to describe the content accurately
python
Python code, tools, info
shell-tools
Tools and utilities for shell scripting and command line operations
source-code
Code snippets
Sqlite
Sqlite DB and tools
technical-writing
Links to deep technical writing and books
TIL
Short notes or tips on coding, linux, llms, ml, etc
Bibliothecula: Using sqlite3 as a Notekeeping Document Graph with Automatic Reference Indexing
Snippet
Instructions
IMPORTANT: ADD NO ADDITIONAL COMMENTARY OR TEXT OF ANY KIND, except that which is needed to sensibly render the document.
Content
TL;DR:
The full schema required for this article's examples is here
There's a web demo of sociologist Niklas Luhmann's zettelkasten you can explore online using sql.js, sqlite3 compiled to webassembly (total compressed asset size: 16MB). source code
The full-text functionality of sqlite3 along with the powerful SQL indexing and trigger features allows us to easily keep notes with references in an sqlite3 database. In this document I present a workflow for doing so.
First, let's examine the pros and cons of this workflow:
Pros:
Cons:
The schema
side-note: How to create a new database by reading the creation statements from a file:
You can use anything you like as long as it has a basic property: your notes table must have a unique id that you can reference in plain text.
For this demo, I use the bibliothecula schema which has UUIDs for primary keys and allows you to tag or add other arbitrary metadata (and files) to each document. In this model, the document is our notes collection and the files of this document can include plain text ones that are our notes.
side-note: sqlite3 doesn't have a built-in way to produce UUIDs. There's an official uuid.c extension you can compile and load but that's all. There might be a way to generate UUIDs natively using the provided randomness functions.
The sqlite3 documentation for randomblob states:
Keep in mind that this is NOT a UUID. UUIDs are not just random numbers, they have some structure. You can easily generate UUIDs with stock python3:
The table used for files in bibliothecula is BinaryMetadata; since it's binary it can also hold plain text data. This is the CREATE statement for BinaryMetadata:
The name column can hold our filename. What about mime type? Furthermore, what if I want to know the size of a file, do I have to calculate the data length every time? †
†. By the way, doing LENGTH(data) for non-BLOB columns is wrong, because they may include NUL bytes. Always do LENGTH(CAST(col AS BLOB)) for TEXT.
The default sqlite distribution includes the JSON1 extension which allows us to place structured data in a column, so I chose to store filename, mime type and size in bytes in the name column. Examples:
Again, this is only for convenience. Our notes don't have to have filenames if they already have a unique identifier, and there's no restriction for filename UNIQUENESS anywhere.
You can create JSON objects with the json_object SQL function, and extract fields with the json_extract SQL function:
Note the use of json_valid to ignore non-JSON names, and also the use of readfile: this is a CLI-only function allowing you to read files as BLOBs. We can use it to quickly attach files to our note database.
The indices
Full-text search
I will use the fts5 extension, included by default nowadays in sqlite3. To create an fts5 index, I issue:
Note that this doesn't seem limited to our text notes; indeed I can produce the full text of other attached binary files like PDFs and index them too, or maybe at a dedicated fts5 table as well.
The fts5 index needs to be filled manually by us, and we can use SQL triggers to automate this.
An INSERT trigger for BinaryMetadata might look like:
I insert some dummy values:
Querying the index is as simple as SELECTing from it:
Read the fts5 documentation here.
Reference index
First we need a way to recognize UUIDs in text. For this purpose I create a text tokenizer using the fts3 text tokenizers that spouts tokens that look like UUIDs:
The UUIDs are spouted when you query the tokenizer. Querying a tokenizer in general is done with a special SELECT:
token
sun
bicycle
trigger
journal
Now, to get stuff that look like UUIDs from the tokenizer:
This returns:
ref
623fec5beac242fcb0b0d17ada20e2b5
37a3ff02c8cd4d7fb3280e5b160d1389
Note the use of REPLACE to exclude any hyphens from our processing.
Now we can create a reference index that we can update on insert/update/delete with triggers:
We can make triggers that use the SELECT DISTINCT above along with a check that the reference target exists by adding
By having two columns in refs_fts, referrer and target we can get all references inside a note and all back references from other notes.
Examples
referrer
b0697d8d76ae41bf8e942d505aff8963
target
623fec5beac242fcb0b0d17ada20e2b5
37a3ff02c8cd4d7fb3280e5b160d1389
Miscellanea
We can read text from the sqlite3 CLI by just SELECTing the data. To save the data, text or any binary into a file use the writefile CLI function:
To insert a file as a BLOB, use the readfile CLI function (example from sqlite3 documentation:
To edit a file, use edit() (again, CLI only):
Yes, that means you can use your editor of choice without problem. You can also just view any file with edit() by selecting it without doing any UPDATE.
sqlite supports Common Table Expressions, an SQL standard that allows you to query hierarchical relationships like nodes in a graph. That means you can easily find all the notes you can reach with references and back references. For info see the documentation
The full schema required for this article's examples is here
There's a web demo of sociologist Niklas Luhmann's zettelkasten you can explore online using sql.js, sqlite3 compiled to webassembly (total compressed asset size: 16MB). source code
Epilogue
You can check out the bibliothecula project if you are interested in small tools to support tagged storage inside sqlite3 databases.
Updated 2021 June 29: Discussion on lobste.rs.
Task
Suggested Labels
Suggested labels
{'label-name': 'Notekeeping', 'label-description': 'Using sqlite3 for notekeeping with automatic indexing and reference management.', 'confidence': 57.62}
The text was updated successfully, but these errors were encountered: