TOKYOCABINET(3)

okay bestie πŸ’– you just opened tokyocabinet(3) β€” that's Tokyo Cabinet, section 3 of the manual, and I am so ready to walk you through it. she's a whole legend, an icon, a modern implementation of DBM, and by the end of this you're gonna be obsessed 🫢 grab a boba, we're going in.


✨ NAME ✨

tokyocabinet β€” a modern implementation of DBM


🌸 INTRODUCTION 🌸

okay so Tokyo Cabinet is a library of routines for managing a database, right? and the database is just a simple data file full of records, where every record is a pair of a key and a value. every key and every value is serial bytes with variable length β€” both binary data and character string can be used as a key and as a value. and listen: there is neither concept of data tables nor data types. none. zero. it's giving minimalism. the records are organized in hash table, B+ tree, or fixed-length array.

so for a database of hash table, every key must be unique within a database, which means it is impossible to store two or more records with a key that overlaps. the access methods it gives you are: storing a record with a key and a value, deleting a record by a key, and retrieving a record by a key. plus traversal access to every key is provided, although the order is arbitrary (no promises, she's chaotic like that πŸ™ˆ). these access methods are similar to the ones of the DBM library (or its followers: NDBM and GDBM) defined in the UNIX standard. Tokyo Cabinet is literally an alternative for DBM because of its higher performance. slay.

for a database of B+ tree, records whose keys are duplicated can be stored β€” yes bestie, duplicates are allowed here πŸ’…. access methods of storing, deleting, and retrieving are provided, same as with the database of hash table. records are stored in order by a comparison function assigned by a user. and it is possible to access each record with the cursor in ascending or descending order. according to this mechanism, forward matching search for strings and range search for integers are realized. iconic behavior.

for a database of fixed-length array, records are stored with unique natural numbers. it is impossible to store two or more records with a key that overlaps. moreover, the length of each record is limited by the specified length. the operations provided are the same as the ones of hash database.

Table database is also provided as a variant of hash database. each record is identified by the primary key and has a set of named columns. although there is no concept of data schema, it is possible to search for records with complex conditions efficiently by using indices of arbitrary columns. the range.

Tokyo Cabinet is written in the C language, and provided as API of C, Perl, Ruby, Java, and Lua. Tokyo Cabinet is available on platforms which have API conforming to C99 and POSIX. and she's a free software licensed under the GNU Lesser General Public License. we love a generous queen.


πŸ¦– THE DINOSAUR WING OF THE DBM FORKS πŸ¦–

Tokyo Cabinet is developed as the successor of GDBM and QDBM on the following purposes. they are achieved and Tokyo Cabinet replaces conventional DBM products. no cap.

  • improves space efficiency : smaller size of database file.
  • improves time efficiency : faster processing speed.
  • improves parallelism : higher performance in multi-thread environment.
  • improves usability : simplified API.
  • improves robustness : database file is not corrupted even under catastrophic situation.
  • supports 64-bit architecture : enormous memory space and database file are available.

as with QDBM, the following three restrictions of traditional DBM are cleared: a process can handle only one database, the size of a key and a value is bounded, a database file is sparse. and moreover, the following three restrictions of QDBM are cleared too: the size of a database file is limited to 2GB, environments with different byte orders can not share a database file, only one thread can search a database at the same time. bye to all of that πŸ‘‹

Tokyo Cabinet runs very fast. for example, elapsed time to store 1 million records is 0.7 seconds for hash database, and 1.6 seconds for B+ tree database. moreover, the size of database of Tokyo Cabinet is very small. for example, overhead for a record is 16 bytes for hash database, and 5 bytes for B+ tree database. furthermore, scalability of Tokyo Cabinet is great β€” the database size can be up to 8EB (9.22e18 bytes). EIGHT EXABYTES. bestie. that's the whole vibe. 😭


πŸ”₯ EFFECTIVE IMPLEMENTATION OF HASH DATABASE πŸ”₯

Tokyo Cabinet uses hash algorithm to retrieve records. if a bucket array has sufficient number of elements, the time complexity of retrieval is "O(1)". that is, time required for retrieving a record is constant, regardless of the scale of a database. same goes for storing and deleting, ngl. collision of hash values is managed by separate chaining. data structure of the chains is binary search tree. and even if a bucket array has unusually scarce elements, the time complexity of retrieval is "O(log n)". she always has a plan.

Tokyo Cabinet attains improvement in retrieval by loading RAM with the whole of a bucket array. if a bucket array is on RAM, it is possible to access a region of a target record by about one path of file operations. a bucket array saved in a file is not read into RAM with the read call but directly mapped to RAM with the mmap call. therefore, preparation time on connecting to a database is very short, and two or more processes can share the same memory map. sharing is caring 🫢

if the number of elements of a bucket array is about half of records stored within a database, although it depends on characteristic of the input, the probability of collision of hash values is about 56.7% (36.8% if the same, 21.3% if twice, 11.5% if four times, 6.0% if eight times). in such case, it is possible to retrieve a record by two or less paths of file operations. if it is made into a performance index, in order to handle a database containing one million of records, a bucket array with half a million of elements is needed. the size of each element is 4 bytes. that is, if 2M bytes of RAM is available, a database containing one million records can be handled. math queen ✨

Traditional DBM provides two modes of the storing operations: "insert" and "replace". in the case a key overlaps an existing record, the insert mode keeps the existing value, while the replace mode transposes it to the specified value. in addition to the two modes, Tokyo Cabinet provides "concatenate" mode. in that mode, the specified value is concatenated at the end of the existing value and stored. this feature is useful when adding an element to a value as an array. lowkey genius.

generally speaking, while succession of updating, fragmentation of available regions occurs, and the size of a database grows rapidly. Tokyo Cabinet deals with this problem by coalescence of dispensable regions and reuse of them. when overwriting a record with a value whose size is greater than the existing one, it is necessary to remove the region to another position of the file. because the time complexity of the operation depends on the size of the region of a record, extending values successively is inefficient. however, Tokyo Cabinet deals with this problem by alignment. if increment can be put in padding, it is not necessary to remove the region. the way she just solves things πŸ’…

the "free block pool" to reuse dispensable regions efficiently is also implemented. it keeps a list of dispensable regions and reuses the "best fit" region, that is the smallest region in the list, when a new block is requested. because fragmentation is inevitable even then, two kinds of optimization (defragmentation) mechanisms are implemented. the first is called static optimization, which deploys all records into another file and then writes them back to the original file at once. the second is called dynamic optimization, which gathers up dispensable regions by replacing the locations of records and dispensable regions gradually.


πŸ¦‹ USEFUL IMPLEMENTATION OF B+ TREE DATABASE πŸ¦‹

although B+ tree database is slower than hash database, it features ordering access to each record. the order can be assigned by users. records of B+ tree are sorted and arranged in logical pages. sparse index organized in B tree that is multiway balanced tree are maintained for each page. thus, the time complexity of retrieval and so on is "O(log n)". Cursor is provided to access each record in order. the cursor can jump to a position specified by a key and can step forward or backward from the current position. because each page is arranged as double linked list, the time complexity of stepping cursor is "O(1)". she's structured AND she's fast, we stan.

B+ tree database is implemented, based on the above hash database. because each page of B+ tree is stored as each record of hash database, B+ tree database inherits efficiency of storage management of hash database. because the header of each record is smaller and alignment of each page is adjusted according to the page size, in most cases, the size of database file is cut by half compared to one of hash database. although operation of many pages are required to update B+ tree, QDBM expedites the process by caching pages and reducing file operations. in most cases, because whole of the sparse index is cached on memory, it is possible to retrieve a record by one or less path of file operations. half the size, all the power ✨

each pages of B+ tree can be stored with compressed. two compression methods are supported: Deflate of ZLIB and Block Sorting of BZIP2. because each record in a page has similar patterns, high efficiency of compression is expected due to the Lempel-Ziv or the BWT algorithms. in case of handling text data, the size of a database is reduced to about 25%. if the scale of a database is large and disk I/O is the bottleneck, featuring compression makes the processing speed improved to a large extent. tiny file, big energy πŸŽ€


πŸ“ NAIVE IMPLEMENTATION OF FIXED-LENGTH DATABASE πŸ“

fixed-length database has restrictions: each key should be a natural number, and the length of each value is limited. however, time efficiency and space efficiency are higher than the other data structures as long as the use case is within the restriction. rules are rules, but she makes them worth it πŸ’…

because the whole region of the database is mapped on memory by the mmap call and referred as a multidimensional array, the overhead related to the file I/O is minimized. due to this simple structure, fixed-length database works faster than hash database, and its concurrency in multi-thread environment is prominent. she's simple, she's fast, she's everything.

the size of the database is proportional to the range of keys and the limit size of each value. that is, the smaller the range of keys is or the smaller the length of each value is, the higher the space efficiency is. for example, if the maximum key is 1000000 and the limit size of the value is 100 bytes, the size of the database will be about 100MB. because regions around referred records are only loaded on the RAM, you can increase the size of the database to the size of the virtual memory. main character energy fr fr πŸ‘‘


bestie that's part 1 and there's more coming, so don't go anywhere πŸ’–

✨ FLEXIBLE IMPLEMENTATION OF TABLE DATABASE ✨

okay bestie, this one is the moment πŸ’… so a table database doesn't do the plain little key/value thing β€” it's giving actual table energy, like a relational database. Every record is identified by its primary key and it's got a whole set of multiple columns, each one named with whatever arbitrary strings you want. fr fr.

so like, a stuff (yes, an employee, a person, a whole human) in your company can be expressed as a record identified by the primary key of the employee ID number, and structured by columns of their name, division, salary, and so on. 🫢

but here's the twist that makes it iconic: unlike a relational database, a table database does not need you to define any data schema, and it can contain records of various structures that are all different from each other. no rigid mold, no cap.

Table database supports query functions with not only the primary key but also with conditions about arbitrary columns. Each column condition is composed of the name of a column and a condition expression. for the string type you get operators for:

  • full matching
  • forward matching
  • regular expression matching
  • and so on ✨

for the number type you get:

  • full matching
  • range matching
  • and so on 🌸

Operators for tag search and full-text search are also provided. A single query can contain multiple conditions for logical intersection, and searching by multiple queries for logical union is also available. The order of the result set can be specified as the ascending or descending order of strings or numbers. slay.

You can create indices for arbitrary columns to improve performance of search and sorting πŸ”₯. And lowkey a fun detail: although columns do not have data types, indices do have types, for strings or numbers. Inverted indices for space separated tokens and character N-gram tokens are also supported. The query optimizer uses indices in a suitable way according to each query, and β€” plot twist β€” indices are implemented as different files of B+ tree database. the way it just reuses the B+ tree... obsessed 😭


πŸ’– PRACTICAL FUNCTIONALITY πŸ’–

Databases on the filesystem feature transaction mechanisms, bestie. It's possible to:

  • commit a series of operations between the beginning and the end of the transaction in a lump, or
  • abort the transaction and perform rollback to the state before the transaction πŸ™ˆ

Two isolation levels are supported: serializable and read uncommitted. Durability is secured by write ahead logging and shadow paging. very main character energy of it.

Tokyo Cabinet provides two modes to connect to a database: "reader" and "writer".

  • A reader can perform retrieving but neither storing nor deleting.
  • A writer can perform all access methods.

Exclusion control between processes is performed when connecting to a database by file locking. So here's the vibe check on who's allowed in:

  • While a writer is connected to a database, neither readers nor writers can be connected.
  • While a reader is connected to a database, other readers can be connected, but writers can not.

According to this mechanism, data consistency is guaranteed with simultaneous connections in a multitasking environment. periodt. ✨

Functions of API of Tokyo Cabinet are reentrant and available in multi-thread environment. Discrete database object can be operated in parallel entirely. For simultaneous operations of the same database object, read-write lock is used for exclusion control. That is:

  • while a writing thread is operating the database, other reading threads and writing threads are blocked.
  • However, while a reading thread is operating the database, reading threads are not blocked. πŸ’…

The locking granularity of hash database and fixed-length database is per record, and that of the other databases is per file. iykyk.


🌈 SIMPLE BUT VARIOUS INTERFACES 🌈

Tokyo Cabinet provides a simple API based on the object oriented design. Every operation for database is encapsulated and published as lucid methods as open (connect), close (disconnect), put (insert), out (remove), get (retrieve), and so on. πŸŽ€

Because the three of hash, B+ tree, and fixed-length array database APIs are very similar with each other, porting an application from one to the other is easy. Moreover, the abstract API is provided to handle these databases with the same interface. Applications of the abstract API can determine the type of the database in runtime. so flexible, so slay.

The utility API is also provided. Such fundamental data structure as list and map are included. And, some useful features; memory pool, string processing, encoding, are also included. πŸ¦‹

Six kinds of API are provided for the C language:

  1. the utility API
  2. the hash database API
  3. the B+ tree database API
  4. the fixed-length database API
  5. the table database API
  6. the abstract database API

Command line interfaces are also provided corresponding to each API. They are useful for prototyping, test, and debugging. Except for C, Tokyo Cabinet provides APIs for Perl, Ruby, Java, and Lua. APIs for other languages will hopefully be provided by third party. (manifesting πŸ™)

In cases that multiple processes access a database at the same time or some processes access a database on a remote host, the remote service is useful. The remote service is composed of a database server and its access library. Applications can access the database server by using the remote database API. The server implements HTTP and the memcached protocol partly so that client programs on almost all platforms can access the server easily. iconic honestly.


🧚 HOW TO USE THE LIBRARY 🧚

Tokyo Cabinet provides API of the C language and it is available by programs conforming to the C89 (ANSI C) standard or the C99 standard.

As the header files of Tokyo Cabinet are provided as tcutil.h, tchdb.h, and tcbdb.h, applications should include one or more of them accordingly to use the API. As the library is provided as libtokyocabinet.a and libtokyocabinet.so and they depends libz.so, librt.so, libpthread.so, libm.so, and libc.so, linker options -ltokyocabinet, -lz, -lbz2, -lrt, -lpthread, -lm, and -lc are required for build command. 😭 (yes bestie, you have to type them all)

A typical build command is the following:

gcc -I/usr/local/include tc_example.c -o tc_example \
  -L/usr/local/lib -ltokyocabinet -lz -lbz2 -lrt -lpthread -lm
-lc

You can also use Tokyo Cabinet in programs written in C++. Because each header is wrapped in C linkage (extern "C" block), you can simply include them into your C++ programs. 🫢


πŸ’œ LICENSE πŸ’œ

Tokyo Cabinet is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License or any later version.

Tokyo Cabinet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with Tokyo Cabinet (See the file COPYING); if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.

Tokyo Cabinet was written by FAL Labs. You can contact the author by e-mail to info@fallabs.com. πŸ‘‘


⭐ SEE ALSO ⭐

tcutil(3), tchdb(3), tcbdb(3), tcfdb(3), tctdb(3), tcadb(3)

Please see http://1978th.net/tokyocabinet/ for detail. 🌸


and that's a wrap on the whole page, bestie!! πŸ’– this one's the 2012-08-18 build of the TOKYOCABINET(3) man page, straight from the Man Page corner of the docs β€” go read the whole Tokyo Cabinet saga, it ate and left no crumbs. mwah πŸŽ€βœ¨