Databases
These recipes show three ways to use a database from Zig, at three different levels, and the first is SQLite through its C API. SQLite is the shortest path to durable storage, and a clear example of how Zig links C. The second is the PostgreSQL wire protocol, written by hand from the startup message to the row description. The protocol is simpler than its client libraries suggest. The third is Redis RESP, which is small enough to parse in one page. For a query layer on top of these recipes, see the ORM chapters in Projects.
- A database driver is mostly a codec. When the framing code is complete, a query is one message that you send. Then you read a stream of messages until the server says that it is ready again.
- Postgres and Redis both frame every message with a type and a length. It is simpler to implement either protocol than to install a client library for it. The complexity in a real driver is pooling, auth and types, not the protocol.
- If protocol code reads from a
Readerand not from a socket, you can test the code with a string literal. - SQLite is a C library. Thus the SQLite recipe is also the shortest realistic example of translate-c, of linking, and of how to change C error codes into Zig errors.
3 chapters.
- Recipe: SQLite From ZigOpen a database, create a table, insert with a prepared statement, and query, through the C API.
- Recipe: A Redis RESP Round TripUse the RESP protocol of Redis over a socket, with a small server and client in one process.
- Recipe: The PostgreSQL Wire ProtocolUse the Postgres protocol directly, and frame a startup handshake and a query by hand.