Skip to content

Database

David Ciulla edited this page Nov 7, 2026 · 2 revisions

Database

Laravex uses SQLite as its sole database driver. The connection layer (Laravex.Database.Connection) shells out to the sqlite3 CLI — no Hex package dependencies required.

Configuration

# config/database.exs
%{
  "default" => "sqlite",
  "connections" => %{
    "sqlite" => %{
      "driver"   => "sqlite",
      "database" => "database/database.sqlite"
    }
  }
}

The path is resolved relative to the application's base path (Laravex.Foundation.Application.base_path/0). An absolute path may also be specified.

If the database file does not exist, Connection.ensure_database!/0 creates it (along with any missing parent directories) automatically on the first query.

The sqlite3 CLI

All queries are executed by spawning:

sqlite3 -json <path> <sql>

for SELECT queries (returns JSON rows) and:

sqlite3 <path> <sql>

for INSERT, UPDATE, DELETE, and DDL statements.

Ensure sqlite3 is available in your PATH:

sqlite3 --version
# SQLite 3.x.x ...

Running Queries

Use the low-level Connection module for raw SQL:

alias Laravex.Database.Connection

# SELECT — returns a list of string-keyed maps
rows = Connection.query("SELECT * FROM users WHERE active = ?", [1])

# DML / DDL
Connection.execute("UPDATE users SET name = ? WHERE id = ?", ["Alice", 42])

# Last inserted row ID
id = Connection.last_insert_id()

Bindings are positional (?). Values are safely quoted by the connection layer:

Elixir type SQL
nil NULL
true / false 1 / 0
%DateTime{} ISO-8601 string
integer / float numeric literal
binary '…' (single quotes escaped)

Transactions

{:ok, result} = Connection.transaction(fn ->
  Connection.execute("INSERT INTO posts (title) VALUES (?)", ["Hello"])
  Connection.last_insert_id()
end)

A transaction wraps the closure in BEGIN / COMMIT. On exception the connection issues ROLLBACK and re-raises.

The DB Facade

Laravex.Database.DB is a convenience facade for the most common operations:

alias Laravex.Database.DB

# Fluent query builder (see Query Builder)
DB.table("users")

# Raw SELECT
DB.select("SELECT COUNT(*) AS n FROM users")

# Raw statement
DB.statement("PRAGMA journal_mode=WAL")

# Transaction
DB.transaction(fn -> ... end)

Schema Inspection

Laravex.Database.Schema.has_table?("users")       # => true | false
Laravex.Database.Schema.has_index?("users", "users_email_unique")  # => true | false

See Also

  • Query-Builder — Fluent SQL builder (Laravex.Database.Query)
  • Migrations — Schema creation and versioning
  • Eloquex — Model-based ORM built on this connection layer

Clone this wiki locally