SQLite on Rails: Loading extensions

Rails continues to expand its lead as the single best platform for building web applications backed by SQLite! You can now load extensions directly from the database.yml file. This now means you have quick and easy access to the full range of SQLite extensions. This is a major step forward from the previous way, which required writing a custom initializer or using the enhanced adapter.


The PR that was recently merged for this feature was implemented by the one and only Mike Dalessio (aka @flavorjones).

It builds on the work that Mike did in the sqlite3-ruby driver to make loading extensions much easier.

These two features together allow your config/database.yml to look like:

development:
adapter: sqlite3
extensions:
- SQLean::UUID # module name responding to `.to_path`
- .sqlpkg/nalgeon/crypto/crypto.so # or a filesystem path
- <%= AppExtensions.location %> # or ruby code returning a path

Also, if you are using the SQLite3 gem directly, you can load extensions when you initialize your database connection:

db = SQLite3::Database.new(
":memory:",
extensions: [
"/path/to/extension",
SQLean::Crypto
]
)

To work with SQLite extensions in Ruby, you have two great gems to lean on. The first packages up the sqlean collection of extenions gathered by Anton Zhiyanov into a simple to download gem—sqlean-ruby (this gem is built and maintained by none other than Mike)

The other—sqlpkg-ruby—makes the sqlpkg package manager (another project by Anton Zhiyanov) available to Rails apps and Ruby projects.

Both gems are now properly setup to take advantage of this new feature. So, jump onto Rails main and start taking advantage of the added power of SQLite extensions.

To use an extension from the sqlean collection, simply pass the appropriate constant name, e.g.:

development:
adapter: sqlite3
extensions:
- SQLean::UUID

To use an extension installed via the sqlpkg utility, call the .path_for method with the extension name, e.g.:

development:
adapter: sqlite3
extensions:
- <%= Sqlpkg.path_for("asg017/ulid") %>

All posts in this series