Persisting objects ([%x persist %]) lets us save and restore program state
But we often want fast lookup without reloading all the data
And interoperability across languages
Create a simple [%g log_structured_db “log-structured database” %]
A simple [%g key_value_store “key-value store” %] that lets us look things up
User must provide a function that gets key from record
[%inc interface_original.py %]
[%inc just_dict_original.py %]
[%inc record_original.py omit=omit %]
pytest.fixture decorator from [%x func %][%inc test_db_original.py mark=fixture %]
[%inc test_db_original.py mark=test %]
We’re going to need other record manipulation functions
So save the record class instead of the key function
[%inc interface.py %]
[%inc just_dict_refactored.py %]
Records must know how to pack and unpack themselves
Start by calculating the size of each
[%inc record.py mark=base %]
[%inc record.py mark=pack %]
Save as strings with [%g null_byte “null byte” %] \0
between them
A real implementation would pack as binary ([%x binary %])
[%inc record.py mark=unpack %]
Note: this doesn’t handle strings with null bytes
Methods for packing and unpacking multiple records are straightforward
[% figure slug=“db-single-file” img=“single_file.svg” alt=“Using a single file” caption=“Saving the entire database in a single file.” %]
[%inc file_backed.py mark=core %]
[%inc file_backed.py mark=helper %]
Still saving and loading entire database
But look at all the infrastructure we’ve built
Save N records per [%g block_memory “block” %]
Keep the [%g index_database “index” %] in memory
When writing, only modify one block (smaller and faster)
When reading, only load one block (ditto)
[% figure slug=“db-alloc” img=“alloc.svg” alt=“Mapping records to blocks” caption=“Mapping records to blocks.” %]
[%inc blocked.py mark=class %]
[%inc blocked.py mark=add %]
Get the sequence ID for this record
Store the key-to-sequence mapping in the index
Find or create the right block
Add the record
[%inc blocked.py mark=get %]
Do we even know about this record?
Find its current sequence ID
Find the corresponding block
Get the record
[%inc blocked.py mark=helper %]
[%inc blocked_file.py mark=class %]
[%inc blocked_file.py mark=save %]
[%inc blocked_file.py mark=load %]
[%inc blocked_file.py mark=index %]
Obvious extension: save the index in another file
Would have to profile ([%x perf %]) to see if this was worthwhile
Clean up unused files
[%g compact “Compact” %] storage periodically
Use other data structures for indexing
[% figure slug=“db-concept-map” img=“concept_map.svg” alt=“Concept map for database” caption=“Concept map.” %]