Some Bits: Nelson's log

22 posts about sqlite

A simple Datasette experiment

Thought I’d give Datasette a quick try. I was curious about which countries were the most and least diverse. Seemed like a good simple use case for the data exploration tool. This is my first time really using it. I am trying to use higher level tools rather than write low level code that works exactly like I want. Here’s what I did. An hour or two of tinkering and learning here, maybe a little more.

Preparing data

Gathered data from Wikipedia: diversity and population. I used this tool to extract CSVs from the tables.

Manually edited the CSVs to change the column headings to simpler things without whitespace.

Installed datasette, sqlite-utils, and csvs-to-sqlite via pip.

Ran csvs-to-sqlite *.csv diversity.db to make a database.

Merged the two tables into one by using sqlite to run create table combined as select * from diversity left join population on diversity.Country = population.Country;

Removed an extra copy of the country name with sqlite-utils transform *db combined --drop 'Country:1';

Converted the population column from string to text with this code:

$ sqlite-utils convert *db combined "Population2023" '
try: return int(value.replace(",", ""))
except: return None'

$ sqlite-utils transform *db combined --type Population2023 integer

Querying data

And with that now I have a nice little web GUI. I used it to make a report of the diversity of large European countries. Which immediately yields a lot of questions about exactly how we’re defining diversity, but that’s not Datasette’s fault.

Thoughts

Datasette is cool, a nice generic HTML front end to tabular data.

Preparing data was more fiddly than I liked. I felt like Datasette and related tools wasn’t doing a lot of work for me I couldn’t just do in sqlite. For instance, I was hoping for a GUI in datasette for doing the join between the two sources tables. It will let you do the Datasette slice-and-dice on top of any sql, so you can have an ephemeral table where you write the join yourself, but I wanted a persistent table for convenience.

The management of the population column types seemed awfully awkward. My input CSV had quoted text-looking columns for the numbers like "233,319". The code uses pandas to import CSV files, which I thought was smart enough to parse those as numbers. Maybe there’s a way to get csvs-to-sqlite to import them that way. It’d be nice if sqlite-utils convert inspected the Python type and changed the column automatically. (There’s a -transform option but I think it only works if you create a new column.)

I was hoping for some way to do a chloropleth of the diversity measures, but no one’s written that plugin. Would be easy enough to export a CSV and use some other service to visualize. There are some map visualization plugins for Datasette but they seem oriented to working with lat/lon pairs, not country names.

It’s really cool how easy it’d be to publish this little set of data to some cloud service.

I’m surprised the integer columns don’t have separators in their display! “144713314” is hard to read. This would be an easy plugin I imagine.

Some IndexedDB notes

I’m using IndexedDB for permanent storage for a webapp. It’s pretty nice; a NoSQL transactional database in your browser! And all built with asynchronous calls. The API is notoriously confusing so I’m using Dexie as my front end. It’s very friendly and I like the way it uses Promises so directly. It also has a smart story about schema versioning. (See also LocalForage.) Anyway, some notes:

How much disk your data uses is a mystery. I have a database with 1873 records that consist of an integer primary key, an integer timestamp, and two doubles. Let’s call it 64 bits each, so that’s 32 bytes a record. OTOH on disk it’s taking 464k, or 254 bytes a record. There’s no Javascript API for asking how much space you’re using or what your quota is.

Storage limits are also confusing. Firefox has no upper bound but will use up to 50% of your disk’s free space and then start evicting stuff on an LRU basis. Chrome also has no fixed limit but may be based on the user’s hard drive size. Older references say a strict 5MB limit but that seems to be much bigger now. For a desktop user it seems likely to be gigabytes.

Firefox implements IndexedDB as sqlite files, but the sqlite schema on disk isn’t anything like my application’s schema. There’s tables named “database” and “index_data” and “object_store”, so I’m guessing they’re using sqlite more as a structured file than the actual database.

 

Moving forward with lolslackbot and Django

I’m very encouraged with how my little Django experiment has worked out. I’m ready to start using it with lolslackbot. A big breakthrough was realizing that I can start using Django as soon as I trust it not to corrupt my database. Keep the existing Python cron job in old code, not using Django, and then have a separate webapp that also uses the same database. The cron job and the webapp will be reading the same tables but in general not writing the same tables. It seems like a good transition plan.

Only now I really have to face the sqlite question. I’m confident that ultimately I need to be using PostgreSQL. I’m envisioning thousands of web users updating the database; there’s no way that works with sqlite’s database-level locking. Even with low traffic the cron job and the webapp will be stepping on each other. I need to switch. But when?

Do I switch databases first, porting my cron job code over to a Postgres-backed system? That seems really painful and not much fun. Lots of backend work with no visible features.

Or do I use Django first, having it talk to the sqlite database? The lock contention won’t be a real problem if I’m the only webapp user. It lets me build fun / useful features sooner. And it gives me some more experience with data modelling. I’m pretty sure I’m going to want to refactor the schema along with the Postgres update, it’d be better to do that after doing some of the webapp work. The risk with Django-first is I do a lot of sqlite-specific work that is ultimately wasted. But Django’s ORM insulates you from the underlying database pretty well, so maybe that doesn’t matter?

Also curious how the Django ORM is going to work for me. I use a couple of non-standard SQL things now. Mostly “insert or replace”, which is sqlite’s upsert-like extension. Does the ORM expose those? Also very curious how testing will work. sqlite is so simple when managing test environments. But I know the Django folks have thought this through.

sqlite: Unix epoch times

I store all my timestamps in the Unix epoch, as Thompson and Ritchie decreed. sqlite doesn’t really have a date type, instead it has date functions that can work with text or numbers. Unfortunately the numbers are defined with respect to two different epochs.

sqlite’s preferred date format is “Julian day”. This is a floating point number, the number of days since November 24, 4714 B.C., with hours/minutes/seconds being reported in fractional. Ie right now it’s 2457524.189894016. A single second is roughly .00001 in this time scale. sqlite3 reals are 64 bit, so we get 2^52 days or about 140M years of dates where individual seconds have distinguishable timestamps. No practical maximum :-P

Unix and Javascript’s preferred date format is an integer, seconds since Jan 1 1970. Right now it’s 1463330612. Unix times are generally 32 bits and therefore limited to the range of 1970–2038, although we’re all hoping we’ll see an extension to 64 bits before the apocalypse. sqlite3 already seems to have extended support and notes it will work on Unix dates from 0000 to 5352. The sqlite functions also seem to be OK with real number Unix epoch timestamps, with the fraction naming subseconds.

The thing that’s confusing is the sqlite functions like date and strftime operate on Julian day numbers by default. If you want calculations in the Unix epoch instead, you have to pass the flag ‘unixepoch’ to the function.

Some examples:

-- Julian days
select julianday('now');
2457524.19912943
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 2457524.19912943);
2016-05-15 16:46:44.783  Julian:2457524.199129433  Unix:1463330804

-- Unix epoch
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 1463330612, 'unixepoch');
2016-05-15 16:43:32.000  Julian:2457524.196898148  Unix:1463330612
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 1463330612.34, 'unixepoch');
2016-05-15 16:43:32.340  Julian:2457524.196902083  Unix:1463330612
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 0, 'unixepoch');
1970-01-01 00:00:00.000  Julian:2440587.5  Unix:0

-- Max sqlite Unix epoch
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 106750000000, 'unixepoch');
5352-10-09 09:46:40.000  Julian:3676119.907407407  Unix:106750000000
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 106760000000, 'unixepoch');
-141-03-01 13:07:12.700  Julian:1205032.046674768  Unix:-106751991168

-- Gotcha with 'now' and Unix epoch
select strftime('%Y-%m-%d %H:%M:%f  Julian:%J  Unix:%s', 'now', 'unixepoch');
1970-01-29 10:38:44.197  Julian:2440615.943567095  Unix:2457524

That last example is confusing; the time stamp ‘now’ is always the Julian day, even in the context of Unix epoch conversions. So it makes no sense to mix ‘now’ and ‘unixepoch’. I’m sure that’s the source of surprising bugs.

I’m not clear why the year 5352, integer 106750000000 is about the limit of sqlite’s Unix date implementation. That number is about 2^36.635, so it’s not some obvious integer rounding problem. Probably doing calendar arithmetic in floating point somewhere?

TinyDB: is this sqlite for JSON?

Awhile back I wanted sqlite for JSON, some simple file-based JSON document store with a basic query interface. TinyDB looks promising. It’s a Python library. It lets you stuff a bunch of JSON documents into a file database and then query them. The query language is pretty simple, mostly “documents that have property X”, but that’s fine. The underlying file format looks like one giant JSON blob and may not be very efficient for updates, not sure.

I’ve used the JSON1 support in sqlite now. It’s pretty good.

I sure wish it were easy to marry jq to some simple JSON document store.

 

sqlite3 test suite

I felt guilty complaining about sqlite3’s source distribution, so I went to look at the real source, what the authors work with. It’s not managed by git but rather in Fossil (an SCM written by the sqlite3 author). Happily the web view is quite good.

One of the miraculous things about sqlite3 is its incredible test suite. There are 683,932 lines of test code. Compare to 273,000 lines of C code for the library and all its extensions. sqlite3 has a reputation for being solid and correct. It’s not an accident.

The test size is overcounted a bit because there’s a lot of test data. For instance the test for the Porter Stemmer is 24k lines of code, but almost all of that is a giant list of words and their correct stemming. Still very useful tests! But not quite as much human effort as it looks on first blush.

The tests are written in Tcl! For all I know it is the oldest large large Tcl program still in active development. But other than the string quoting problem Tcl is a pretty good way to script a test. See for example the tests for the JSON module

do_execsql_test json101-1.1.00 {
  SELECT json_array(1,2.5,null,'hello');
} {[1,2.5,null,"hello"]}
do_execsql_test json101-1.1.01 {
  SELECT json_array(1,'{"abc":2.5,"def":null,"ghi":hello}',99);
  -- the second term goes in as a string:
} {[1,"{\\"abc\\":2.5,\\"def\\":null,\\"ghi\\":hello}",99]}
do_execsql_test json101-1.1.02 {
  SELECT json_array(1,json('{"abc":2.5,"def":null,"ghi":"hello"}'),99);
  -- the second term goes in as JSON
} {[1,{"abc":2.5,"def":null,"ghi":"hello"},99]}

Very readable and compact.

As a software project sqlite3 makes a lot of idiosyncratic choices. Tests written in Tcl. Fossil instead of git. Source code distributed as “the amalgamation”. But sqlite3 is a masterwork of code. It’s fast, it’s reliable, it’s simple, and it works well in embedded systems while also providing a lot of very sophisticated database capabilities. I have nothing but respect for it.

Upgrading sqlite3 within Python 3

Python 3 has sqlite3 baked in. That’s great! But it has an old version of sqlite3; my Ubuntu 14.04 system with Python 3.4 has sqlite 3.8.2. I want sqlite 3.9, for the new JSON hotness.

There’s a pip-installable package called “pysqlite” that should be installable in a virtualenv. But it only supports python 2 and explicitly says “use the built-in sqlite3 for python 3”. Thanks but no thanks!

This Stack Exchange thread has details on recompiling python3 with your own sqlite3, but that’s more work than I want to do. Also it appears that python3 is just loading libsqlite3.so.0 from my Ubuntu install, so I should be able to upgrade it by either upgrading libsqlite in Ubuntu or building my own shared library. But the Ubuntu upgrade looks impossible without upgrading all of Ubuntu 14.04. (I couldn’t find a PPA from a quick search).

Compiling sqlite3 into a shared library is an exercise. The source is distributed in an idiosyncratic format and the version with a Makefile doesn’t build shared libraries. I ended up making something work by following the official docs and this note about the shared library.

gcc -c -fPIC -O2 -I. -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS4    -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_JSON1    -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_EXPLAIN_COMMENTS    -DHAVE_USLEEP -DHAVE_READLINE    shell.c sqlite3.c
gcc -shared -o libsqlite3.so -fPIC sqlite3.o -ldl -lpthread
ln -s libsqlite3.so libsqlite3.so.0
./sqlite3 -version
LD_LIBRARY_PATH=. /usr/bin/python3 -c 'import sqlite3; print(sqlite3.sqlite_version)'

It works! But now I’m nervous. Compiling sqlite3 correctly takes more research than I conducted. It has a whole lot of options! Also I get a bit worried about relying on LD_LIBRARY_PATH to override libraries. It’s totally fine to do of course, but it just seems too easy to forget to do it in some environment and suddenly things aren’t working consistently. If I were serious about doing this I think I’d build my own Ubuntu package for real, using Ubuntu’s Makefile as a starting point.

Python / sqlite3 query logging

When debugging database code it’s really handy to have a text log of the actual SQL being executed by the database. This output is remarkably difficult to get in many database drivers. Happily, starting with Python3.3 there is a way

connection.set_trace_callback(print)

The argument is any function, or None to disable the tracing. I think this has no access to the results, nor can you use it to time how long the query took. That requires some more ambitious thing.

Turning hacky Python into a real app

I’m about to go on vacation. I just finished a bunch of improvements to lolslackbot. Also I suffered my first real outage since it started as a simple cron job six months ago. So I’m reflective on what I need to do to graduate this service into something more serious and reliable. Some projects towards making the system production quality...

Locking and timeouts. The outage was because I tried grafting lockrun into my cron job to ensure only one update runs at a time. But if the update script hangs (say, because the remote API is down) then it holds the lock forever, or at least until I wake up in the morning. I’ve removed the locking for now, running the update twice at once isn’t too bad. But I’m considering adding back the locking along with some sort of global timeout to the scripts, or at least the network requests, so they can’t hang forever. But that’s a hack on top of a hack. “Run this once and only once, reliably” is a hard problem.

Error recovery. I’m a big believer in throwing exceptions when things go wrong, then fixing the code to handle the error. But at some high level I’d rather the script kept going. I’m processing hundreds of game objects a day; it’d be better to skip a game that’s weird and breaks my code than to have the whole system fail until I can fix it.

Logging. I’ve been using Python’s logging program but I’m not logging to a file anywhere; just stderr. That makes it hard to look back at what happened. Or even notice if I skipped a weird game. I might also benefit from some contextual logging, but that may be overkill.

monitoring. I don’t exactly need a pager for 3am, but I would like some better way of knowing if stuff is working than “did cron email me?” and “have any new messages shown up in awhile?”

virtualenv. I’m naughty and don’t use venv. I should.

make code a module. I’m also naughty and don’t have my own code in a proper module. I should. Would be nice to separate the Python scripts from the precious data files, too.

test suite. A lot of my tests run based on some live data I captured a month or two ago and has baked in it things like “there are exactly 110 game objects”. That makes it hard to add new test cases. I think I’m stuck here and need to just suck it up and hand-edit in new test cases to the JSON blobs I use in my mock framework. And then update all the tests. I also had a hilarious problem yesterday where one of my test cases had enshrined the wrong expected output, basically hiding a bug I sort of knew about. That’s the hazard of starting a test suite with “I think this code is working; let’s assume its current output is correct”. Still that test suite is the single best investment I’ve made in the project, so much value.

indices / SQL performance. I haven’t done any work towards creating indices for common queries other than the implicit indices that primary keys and unique constraints give you. So far my whole database is only 20MB, hardly worth worrying about. But at some point table scans are going to stop being fast. I haven’t seen any evidence of a slow query log in sqlite, I suppose I could build my own wrapper in Python.

Distributed transactions. A closely related problem to locking; I have a sort of distributed transaction problem when I’m delivering messages to Discord. I want to mark the message delivered in my database if the message is successfully delivered to Discord. So I write the “message processed” bit after Discord accepts the message. But sometimes Discord throws an error even though the message got delivered anyway, so the message doesn’t get marked processed and later is delivered a second time. It’s sort of a distributed transaction problem I don’t quite know how to solve.

Web view. Big project, I think I’ve graduated to needing a web view for seeing and editing the objects in my database. Particularly for stuff like “add a player to a team”. I really don’t want to roll this all ad-hoc, way too much work. Currently thinking of doing this as a whole new codebase not reusing much (if any) existing code, to try out Flask and SQLAlchemy. With a plugin to generate the editing UI, maybe WTForms or Flask-Admin.

sqlite3 vs postgres. I continue to have the feeling that I should switch to postgres, but I’m now pretty in love with sqlite’s simplicity. The planned web view will be my first time with simultaneous writers, which previously I assumed was when sqlite may be too limiting. OTOH sqlite does have database-level locking, it’s not going to blow up. As long as the locks are only held for “a few milliseconds” I can live with that. Python’s driver has a 5 second timeout for connections by default. The sqlite3 command tool by default just throws an error if the database is locked, but you can specify a timeout in a somewhat awkward way. (If sqlite3 is compiled wrong, locks can last seconds.)

So that’s a big list of projects. I’m not thrilled to do any of them; they’re not features, and they’re a significant investment for a project that has very few users. OTOH they will make my life better as I work on this.

 

Python is fast opening sqlite3

I’ve got a lot of code calling sqlite3.connect() in my program now. Particularly in my test suites. In MySQL and Postgres this can be slow and you end up needing connection pooling. I had a feeling it shouldn’t be in sqlite3 given its simplicity, but I wasn’t sure.

A bit of work with timeit later I can report it’s taking about 18usec to open a database. My connection function is more complex too, doing a select into a “globals” table to test the schema version. Even with all that work it’s 170usec, or < 2ms. That’s not super fast but it’s not a problem if my test suite does it 100 times.

$ python3 -m timeit -s 'import sqlite3' "sqlite3.connect('games.sqlite')"
100000 loops, best of 3: 17.6 usec per loop

sqldiff for sqlite3

Learned about a nice tool today: sqldiff. It shows differences between two sqlite databases. Particularly nice with the “--schema” flag, so you can just compare schema differences. I’m in the middle of database versioning hell as I keep iterating my lolslackbot project. Beginning to regret rolling all the database stuff by hand instead of using some ORM.

sqlite3 vs postgres: uneasy feeling

I continue to write my LoL Slack bot with sqlite3. I can live with the primary drawback of sqlite3, which is that writes require a database level lock (ie: no table or row locking). In normal use I should only ever have one writer to the database anyway. But I still have a nagging feeling I should use “a real database”. Ie: Postgres

The nervousness is I’m writing more complex code that’s wedded to sqlite. I’m using sqlite’s upsert equivalent, for which there is no standard syntax. I’m also using sqlite’s Python convenience feature of not using cursor objects. And just now I’m starting to pay attention to Python’s weird transactional semantics, which I suspect might be different in Postgres. In short my code has been dating sqlite for awhile but now things are getting serious and I’m getting commitment anxiety. Also Postgres has some alluring features I could use, like JSON and array types.

The underlying question is whether Postgres is really “better” for my kind of application. I suspect not, and part of why I stick with sqlite is to test that assumption, but the cost of being wrong is getting higher. The flip side is managing a Postgres daemon is still a PITA. Particularly on Ubuntu where upgrading is scary.

Two sqlite3 gotchas

Ran into a couple of odd problems when doing database schema migrations on my sqlite3 database.

Transactions don’t work like you’d expect in the sqlite3 command line tool! I wrote a few lines of SQL to create a new table and drop an old one, then fed that script to sqlite with the command line tool like this: sqlite3 my.db < script.sql. I was clever and wrapped my script.sql in a “begin transaction... commit” so that if there were any errors, nothing would be committed. Smart, right? Wrong. sqlite3 will gladly execute line n+1 in a script it’s fed even if line n fails. This makes sense for interactive use, but is a disaster for a script that wants a transaction; the commit at the end will always run. The solution is to put .bail on in the top of your script so any errors cause execution to terminate. See also this discussion.

I was using an “insert or replace” command to be sure I only had one row per key in my database, along with a unique constraint to tell the DB what the key was. Only I didn’t actually add the unique constraint during my migration, because it’s a PITA to do schema changes like that in sqlite3. unique constraints are only hints, right, it’s like a type checker! Well not if you rely on the constraint violation enabling an “insert or replace” to work. Oops.

 

sqlite upserts, inserts, etc

sqlite has a nifty feature; “on conflict”, aka “insert or”. You apply it to insert and update operators to tell sqlite what to do if the operation would violate a constraint like unique or not null.

I’m using “insert or ignore” to only insert a row if it doesn’t exist.

insert or ignore into mytable(userid) value (23)

You can also use “insert or replace” to do an upsert

insert or replace into mytable(userid, name) value (23, "Joe")

 

Don’t store JSON blobs in text columns in sqlite3

I decided to try something naïve and put big JSON blobs in a sqlite3 database. About 1700 of them, 150k each, data from League of Legends matches. I knew this was dumb but I did it anyway. And it was dumb, like 300MB of dumb. To be fair sqlite3 handles this just fine, but the single big file makes backups and caching awkward. And I wasn’t even using the column!

I rewrote the code to store the JSON blobs as gzip files instead. 36MB instead of 300MB, and each file doesn’t ever change once written. Just nicer all around. Kind of a pain to remove the data though. sqlite3 doesn’t let you drop columns so you have to make a temporary table to remove it. And even then the file didn’t get smaller on disk; I ended up doing a dump / restore to reclaim the space.

I still want sqlite-for-JSON, a simple JSON datastore. I see the JSON1 module made it into sqlite3 3.9, no longer draft. I should try it out. It’s not compiled in by default. Also I assume it’s not compressed. sqlite3 does have compressed database support, but only as a paid extension.

JSON1, a SQLite extension

A couple months back I expressed a desire for a SQLite-for-JSON system. And someone’s done it! I got here from this Hacker News discussion about a different system.

JSON1/SQLite

JSON1 is a draft SQLite extension for JSON. Here’s notes on how to use it in Python, including a demo notebook. Still some rough edges, but it’s promising.

JSON is stored as type text. No binary encoding, the docs say the improvement isn’t worth the trouble. JSON arrays are used as a container type in parts of the query language, for things that return N JSON blobs. There’s also some SQLite virtual tables that are created by advanced query methods.

There’s the basic functions you’d expect for manipulating JSON, mostly setting and changing properties on a JSON object.

For basic query, json_extract() is the basic function that pulls out pieces of a document based on a query path. (Ie: $.title means “give me the title property”, $.authors[2] means “give me the 3rd element of the array that is the value of the authors property”)

For advanced query, json_each() and json_tree() turn a single JSON blob into a virtual table you can then query. The table has a schema with one JSON column per property queried, as well as some other data related to the query like integer IDs and the path. json_each() only queries the top level properties, json_tree() is a recursive search.

I like it, it looks really promising. Maybe not quite ready for civilian use yet, but soon? The discussion a month ago advises we “check back soon”.

My one mild concern is that JSON data tends to be really big. Like I have 1000 LoL matches in a SQLite database, each one a 200kb JSON blob. And no surprise, it’s a 200MB file! That starts to get awkward for backups, etc, and is kinda dumb since the JSON is immutable. It’d be better to store them as read-only files but that’s not compatible with SQLite’s design.

JSONlite

JSONlite is the topic of the HN post that let me to JSON1. It’s a valiant effort, a set of bash scripts to store JSON as files and retrieve them with UUIDs. It’s not a bad little wrapper but it’s very simple. And no query interface, which to me is the interesting part, although one could probably just use jq on the backend store.

UnQLite

UnQLite also came up, in this description. “UnQLite is to MongoDB what SQLite is to Postgres”, which sounds good to me! It uses Jx9 for query. I didn’t look any further; it seems promising, but my general rule with tech like this is wait for critical mass before investing any time.

CSV query tools

I do a lot of work with CSV files, and up to now I’ve been mostly doing clumsy stuff with standard text tools like “awk -F,” and the like. Here’s a roundup of some Unix command line tools for working with CSV files, lifted from One Thing Well

  • xsv: slice, split, summary stats, etc. also supports creating a quick index to accelerate things. Seems pretty solid. Rust program, which is awfully weird, but he provides a Linux binary.
  • csvkit: suite of programs for manipulating CSV. Includes import/export to JSON, Postgres, Excel, etc. Also has a SQL query via in-memory sqlite3. Python program.
  • Miller: “like sed, awk, cut, join, and sort for name-indexed data such as CSV”. More limited queries than xsv or csvkit. But it embraces more input file types, including CSV files that change schema and arbitrary keyword/value data. Seems perfect for the “long list of JSON object” files I often work with. (Although no JSON support?!)
  • csvfix: thin docs, another xsv-style tool. Has more operations than other tools.
  • q: SQL queries on CSV files via sqlite. Python program.
  • TextQL: SQL queries via sqlite. Go program.
  • fsql: SQL queries via some Perl SQL implementation. Supports JSON and YAML.

I just tried xsv and it’s quite nice, may be the closest to what I need day to day. I’ve used q before and remember it working nicely, albeit a bit slowly. Arbitrary SQL is appealing.

Wanted: SQLite for JSON

I like SQLite. It’s such a nice simple data store. It’s fast for small data (< 100 MB), it requires no separate daemon process, it has great support in every language I work in.

I like JSON and the idea of schemaless databases. I want to be able to download JSON blobs from an API or create some new JSON blobs and store them away with a minimum of effort. Typeless. Then I want to be able to query them somehow.

Now I want to mix the two together. I want to take a bunch of JSON objects and store them in somewhere simple, then query them.

MongoDB was the first big “store a bunch of JSON”. It sort of fits the bill for what I want, but it’s way overengineered for my needs. I don’t want a separate database process. I definitely don’t want a separate cluster of database processes. Also MongoDB is fundamentally untrustworthy and should not be used by anyone for anything serious. It might be OK for my casual hacking, particularly without clustering, but then you run into the way the query language is so awkward.

Postgres has decent JSON support with some queries. I will probably try that for my next hack. Unfortunately it requires a separate database process and I prefer the simplicity of sqlite’s “just open the file” design. But I have a Postgres instance lying around already so what’s one more database?

Node.js sqlite3: very slow bulk inserts

I’m running into a baffling problem where the straightforward way to use prepared statements in the MapBox sqlite3 Node.js code is super slow. Like inserting 100 rows in a table takes 16 seconds!

Update: found the problem, I wasn’t using transactions right. See bottom. Simple solution for faster bulk inserts in sqlite3: do them with a transaction.

The API docs have a strange note for Statement.finalize() which says “if you experience long delays before the next query is executed, explicitly finalizing your statement might be necessary”. I’m seeing exactly that. But after you’ve finalized it you can’t reuse the prepared statement; what’s the point of using statements at all then?

There’s notes online that naive bulk inserts in sqlite3 are slow, nothing to do with Node. See StackOverflow and Blog::Quibb. The quick fix I learned from both of those is to wrap the insert block in a transaction, because without that sqlite3 treats each insert as a separate transaction and is understandably slow. OK, so we’ll use a transaction.

But even with transactions using prepared statements is still slow in the Node version. I don’t know if this is a bug, me not understanding sqlite3 right, or me not understanding Node right. I am using serialized mode and trying to do simple nonconcurrent programming. The delay only occurs when the database is closed, btw, sqlite3 is accumulating the changes in a journal before committing them.

Three approaches:

  1. Call db.run(‘INSERT...’) a bunch of times. This is fast, but only if I wrap the inserts in a transaction.
  2. Prepare a statement once, then call stmt.run(‘INSERT...’) a bunch of times. This is slow whether I use a transaction or not.
  3. Prepare a separate statement for each row, then call stmt.run(‘INSERT...’) on it and then stmt.finalize(). This is fast.

Sample code is in this gist. “db” and “finalize” both take about 400ms on my Linux box. “reuse” takes 16 seconds to insert the 100 rows.

Update: the problem was I was creating the prepared statement before I did the “begin transaction”. Apparently that means the prepared statement is executed without the transaction context. Beginning the transaction and then preparing the statement, the three methods all run fast. I suspect the call to finalize has nothing to do with it, but I’m not sure.

Here’s the revision view: version one had the begin transaction too late.

Node.js sqlite3 error handling

This post is an exercise in trying to learn how to debug errors in Node.js programs.

Trying to write some sqlite3 code in Node.js. MapBox has a lovely Node module, but the docs are a bit thin and assume Node expertise I do not yet have. This morning’s challenge is trying to gracefully handle an error if database.run(“DROP TABLE”) fails. All work is running after database.serialize, so no concurrency.

By default with no error handling code, an error will cause an Unhandled ‘error’ event that kills the process. But you can’t just catch an exception because this is Node.js and exceptions don’t really work. So instead you need to specify a callback to database.run(), to get the Error (or else inspect the results of a successful statement.) Fair enough.

But what is the Error object in the callback? The sqlite3 docs don’t document this anywhere. In Chrome I’d just console.log() the object and use the lovely inspector. Node’s equivalent to the inspector is util.inspect, and you want to set showHidden to 1 to really see it. And voila:

{ [Error: SQLITE_ERROR: no such table: logs]
  [stack]: [Getter/Setter],
  [arguments]: undefined,
  [type]: undefined,
  [message]: 'SQLITE_ERROR: no such table: logs',
  errno: 1,
  code: 'SQLITE_ERROR' }

So this object looks like an ordinary Error object, with the message property. In addition it has errno and code properties. And now I know.

Another way to have learned all this would be to use the Node debugger. It’s pretty primitive, but you can set breakpoints in your code with the “debugger;” statement or from the debugger command line with “sb(lineno)”. Once it breaks you want to run “repl” to switch to the scope of your running script, then you can inspect objects. It all works but is a bit awkward without a GUI. I miss Chrome’s beautiful debugger; should try out node-inspector or something similar.

The irony of all this is I don’t even need too handle this error; sqlite supports “DROP TABLE IF EXISTS”. But oh well, now I know more about sqlite3 error handling and how to debug Node programs.

Digital National Geographic schema notes

I bought a digital copy of the National Geographic Magazine archives. Great data collection, horrible Adobe Air interface to access it. Fortunately the archive is basically a bunch of lightly obfuscated image files and SQLite databases. I might take a crack at making a more usable index to all the articles. To that end, some notes on the database schema I found.

There’s individual sqlite files on the DVDs and downloads, but I think they are all merged in a file called Contents/Resources/assets/db/cngcontent.sqlite3.full. I find 7977 article entries in 1416 issues for my set up to 2012, which sounds roughly the right scale. Here’s the tables in it and some notes on schema. Numbers in parentheses are how many rows are in the table.

Tables all have simple primary keys named “id”. “search_time” is a popular field, it stores the date of the issue as an integer. IE “1977 Sep” has a search_time of 19770901.

articles (7977)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
“start_page_offset” integer,
“page_count” integer,
“display_name” varchar(255),
“summary” varchar(255),
“search_time” integer,
“issue_id” integer

issues (1416)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“display_name” varchar(255)
“search_time” integer
“page_count” integer
“numbered_page_offset” integer
“numbered_page_count” integer
“numbered_page_start_value” integer
“page_exceptions” varchar(255));

geolinks (27570)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“location_id” integer
“article_id” integer
“department_id” integer
“map_id” integer

locations (5016)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“display_name” varchar(255)
“lat” float
“lng” float
“bounds_ne_lat” float
“bounds_ne_lng” float
“bounds_sw_lat” float
“bounds_sw_lng” float
“geo_provider” varchar(255)
“kms_per_lng_degree” float

contributors (12400)

“id” INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
“display_name” varchar(255)
“search_time” integer
“article_id” integer
“department_id” integer
“map_id” integer
“start_page_offset” integer

other tables

article_subjects (25774),
ad_subjects, ads,
departments, department_subjects,
maps, map_subjects,
photos (251002), photo_subjects,
links, schema_migrations, trivia_questions, trivia_rankings

 

Looks totally feasible to join through geolinks to find all articles in a specific region.

iPhone consolidated.db location tracking notes

I’m trying to understand the consolidated.db iPhone location database, which means understanding how iOS stores and managing data. Here’s some notes.

Resources

  1. @aallan’s original announcement
  2. iPhone Tracker (Objective C code)
  3. Technical instructions from howto.wired
  4. nphonetrack (.NET code)
  5. iPhoneLs.py
  6. iphone-tracker.py
  7. Quick start for sqlite3
Notes
  • When you make a backup of an iPhone, it creates a big directory full of files with random 160 bit filenames. These are named files in the iPhone that iphonels.py can display. My 3 biggest files are named
    HomeDomain::Library/Caches/com.apple.WebAppCache/ApplicationCache.db
    AppDomain-com.foreflight.ForeFlightMobile::Documents/Procedures.zip
    RootDomain::Library/Caches/locationd/consolidated.db
  • consolidated.db is the file with the location data in it. It’s a sqlite3 database.
  • The juicy tables are (apparently) CellLocation and WifiLocation. The *Counts tables seem to contain just a row count. Presumably the Boxes tables are some sort of spatial index. I can find no record of how often I was at a specific location other than what’s implicit in the timestamps and density of cell/wifi locations.
  • I have 32,013 rows in CellLocation, 171,040 rows in WifiLocation
  • Timestamps are like 309803342: I believe this is NSDate seconds since 1 Jan 2001. Add 978307200 to get it in seconds since Unix 1970 epoch.
  • HorizontalAccuracy varies from 50-300 for WifiLocation, and up to 80,000 for CellLocation.
  • Confidence is 0, 50, 60, 65, 68, or 70
  • Speed and Course are always -1 (no surprise).
Some quicky sqlite3 shell code
.mode csv
.output wifilocation.csv
select Timestamp, Latitude, Longitude from WifiLocation order by Timestamp;
.output CellLocation.csv
select Timestamp, Latitude, Longitude from CellLocation order by Timestamp;
Some pasted info from sqlite3
sqlite> .tables
CdmaCellLocation                   CellLocationCounts
CdmaCellLocationBoxes              CellLocationHarvest
CdmaCellLocationBoxes_node         CellLocationHarvestCounts
CdmaCellLocationBoxes_parent       CellLocationLocal
CdmaCellLocationBoxes_rowid        CellLocationLocalBoxes
CdmaCellLocationCounts             CellLocationLocalBoxes_node
CdmaCellLocationHarvest            CellLocationLocalBoxes_parent
CdmaCellLocationHarvestCounts      CellLocationLocalBoxes_rowid
CdmaCellLocationLocal              CellLocationLocalCounts
CdmaCellLocationLocalBoxes         CompassCalibration
CdmaCellLocationLocalBoxes_node    Fences
CdmaCellLocationLocalBoxes_parent  Location
CdmaCellLocationLocalBoxes_rowid   LocationHarvest
CdmaCellLocationLocalCounts        LocationHarvestCounts
Cell                               TableInfo
CellLocation                       Wifi
CellLocationBoxes                  WifiLocation
CellLocationBoxes_node             WifiLocationCounts
CellLocationBoxes_parent           WifiLocationHarvest
CellLocationBoxes_rowid            WifiLocationHarvestCounts

CREATE TABLE CellLocation (
  MCC INTEGER,
  MNC INTEGER,
  LAC INTEGER,
  CI INTEGER,
  Timestamp FLOAT,
  Latitude FLOAT,
  Longitude FLOAT,
  HorizontalAccuracy FLOAT,
  Altitude FLOAT,
  VerticalAccuracy FLOAT,
  Speed FLOAT,
  Course FLOAT,
  Confidence INTEGER,
PRIMARY KEY (MCC, MNC, LAC, CI));

CREATE TABLE WifiLocation (
  MAC TEXT,
  Timestamp FLOAT,
  Latitude FLOAT,
  Longitude FLOAT,
  HorizontalAccuracy FLOAT,
  Altitude FLOAT,
  VerticalAccuracy FLOAT,
  Speed FLOAT,
  Course FLOAT,
  Confidence INTEGER,
  PRIMARY KEY (MAC));