Configuring ULIDs for SQLite in rails+litestack
ULIDs are Universally Unique Lexicographically Sortable Identifiers, a sortable and more compact alternative to UUIDs that are appropriate in certain use cases.
The following describes how to configure the sqlite_ulid gem to enable ULID support in SQLite under litestack, but the technique is applicable to other SQLite extensions. It is derived from this excellent post by Stephen Margheim.
Steps
Start with a working litestack installation.
Install the sqlite_ulid gem:
bundle add sqlite-ulid
Create an initializer to read the extensions config e.g. in config/initializers/litedb.rb
:
module RailsExt
module LitedbAdapter
def configure_connection
super
@raw_connection.enable_load_extension(true)
@config[:extensions].each do |extension_name|
Rails.logger.debug("Loading SQLite extension: #{extension_name}")
require extension_name
extension_classname = extension_name.camelize
extension_class = extension_classname.constantize
extension_class.load(@raw_connection)
rescue LoadError
Rails.logger.error("Failed to find the SQLite extension gem: #{extension_name}. Skipping...")
rescue NameError
Rails.logger.error("Failed to find the SQLite extension class: #{extension_classname}. Skipping...")
end
@raw_connection.enable_load_extension(false)
end
endend
ActiveRecord::ConnectionAdapters::LitedbAdapter.prepend(RailsExt::LitedbAdapter)
Amend the database.yml file to include the extensions config:
default: &default
adapter: litedb
# ...
extensions:
- sqlite_ulid
Verify installation from the rails console (bin/rails console
) with:
ActiveRecord::Base.connection.execute("SELECT ULID()")
Which should return something like:
Loading SQLite extension: sqlite_ulid
Loading SQLite extension: sqlite_ulid
(22.3ms) SELECT ULID()
=> [{"ULID()"=>"01j69pqkr5k8mvjvrsbq5md9d1"}]
Success!