Today we are embarking on a series of episodes to show how to persist data in your applications using SQLite. SQLite is one of the most well-crafted and battle-tested pieces of software in the history of software. It’s installed on tens of billions of devices worldwide, and its test suite runs over 500 million tests every day!
However, SQLite is a C library, and C is a language that does not have many of the niceties that we have come to expect from our experience with Swift. There’s a very limited type system, no enums, no generics, and it has pervasive use of unsafe pointers. However, Swift has great interoperability with C and so with a little bit of work we can very easy call into any of SQLite’s functionality.
In the series we are going to accomplish 3 main goals:
First we are going to give a crash course in calling into C code from Swift, including how one deals with all the unsafe pointers that are necessary when dealing with C code. And along the way we will learn the basics of SQLite, including how to create a database, how to create a table, how to insert data into the table, and how to query the database.
Then we will show how to use one of the most popular 3rd party libraries for putting a nice Swift interface on top of SQLite, which is GRDB by Gwendal Roué. This gives you all the basic tools for interacting with a database, such as creating tables, insert data and querying, but with some additional powers for subscribing to changes and modeling relationships between models.
And the finally we will explore some advanced topics in SQLite and GRDB by showing off how to display data from the database in SwiftUI, how to observe changes to the database so that the view updates automatically when data is updated, and more.
But, let’s start from the very beginning. Let’s see what it takes to interact with the SQLite C library that automatically comes on every iOS and macOS device.