zio.blocks.sql

package zio.blocks.sql

Members list

Packages

Type members

Classlikes

case object BuildInfo

This object was generated by sbt-buildinfo.

This object was generated by sbt-buildinfo.

Attributes

Source
BuildInfo.scala
Supertypes
trait Singleton
trait Product
trait Mirror
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
Self type
BuildInfo.type
final case class ColumnDef(name: String, sqlType: String, nullable: Boolean)

Metadata for a single column in a CREATE TABLE statement.

Metadata for a single column in a CREATE TABLE statement.

Value parameters

name

The column name as it appears in SQL.

nullable

Whether the column allows SQL NULL.

sqlType

The SQL type string (e.g. "INTEGER", "TEXT").

Attributes

Source
Ddl.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
final case class ColumnMeta(name: String, dbValue: DbValue, nullable: Boolean)

Attributes

Source
TableMetadata.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object DbCodec

Attributes

Companion
trait
Source
DbCodec.scala
Supertypes
class Object
trait Matchable
class Any
Self type
DbCodec.type
trait DbCodec[A]

Bidirectional codec between a Scala value A and one or more database columns.

Bidirectional codec between a Scala value A and one or more database columns.

Column ordering matches the columns IndexedSeq. The startIndex parameter in positional readValue / writeValue is 1-based (JDBC convention): column 1 corresponds to columns(0). Query decoding prefers the label-based overload so result column order can differ from codec order as long as column labels still match.

Attributes

Companion
object
Source
DbCodec.scala
Supertypes
class Object
trait Matchable
class Any

Attributes

Companion
class
Source
DbCodecDeriver.scala
Supertypes
trait Deriver[DbCodec]
class Object
trait Matchable
class Any
Self type
class DbCodecDeriver(columnNameMapper: SqlNameMapper = ...) extends Deriver[DbCodec]

Attributes

Companion
object
Source
DbCodecDeriver.scala
Supertypes
trait Deriver[DbCodec]
class Object
trait Matchable
class Any
Known subtypes
trait DbCon

Attributes

Source
DbCon.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait DbTx
trait DbConnection extends AutoCloseable

Attributes

Source
DbConnection.scala
Supertypes
class Object
trait Matchable
class Any
object DbParam

Attributes

Companion
trait
Source
SqlInterpolator.scala
Supertypes
class Object
trait Matchable
class Any
Self type
DbParam.type

Writes parameter values to a prepared statement.

Writes parameter values to a prepared statement.

All index parameters are 1-based (JDBC convention). Use setNull to write SQL NULL for a given parameter index.

Attributes

Source
DbCodec.scala
Supertypes
class Object
trait Matchable
class Any

Attributes

Source
DbConnection.scala
Supertypes
class Object
trait Matchable
class Any

Reads column values from a database result set.

Reads column values from a database result set.

All index parameters are 1-based (JDBC convention). Label-based access is available for order-independent decoding. After any get* call, use wasNull to check whether the value was SQL NULL.

Attributes

Source
DbCodec.scala
Supertypes
class Object
trait Matchable
class Any
trait DbResultSet extends AutoCloseable

Attributes

Source
DbConnection.scala
Supertypes
class Object
trait Matchable
class Any
trait DbTx extends DbCon

Transactional connection with savepoint support for nested transactions.

Transactional connection with savepoint support for nested transactions.

Savepoint semantics: nested transactions are emulated via SQL savepoints named zib_tx_1 .. zib_tx_N where N is the nesting depth. On success the savepoint is released via RELEASE SAVEPOINT, on failure the transaction rolls back to the savepoint via ROLLBACK TO SAVEPOINT and rethrows the exception. Only the outermost Transactor.transact does a real COMMIT/ROLLBACK; inner blocks are savepoint-scoped and share the same underlying JDBC connection.

Depth tracking: each DbTx instance tracks its current nesting depth (0 = outermost). The counter is incremented only after the savepoint is created successfully and decremented in a finally block, guaranteeing correct depth even if savepoint creation throws and reset even when inner blocks throw.

Attributes

Companion
object
Source
DbTx.scala
Supertypes
trait DbCon
class Object
trait Matchable
class Any
object DbTx

Attributes

Companion
trait
Source
DbTx.scala
Supertypes
class Object
trait Matchable
class Any
Self type
DbTx.type
sealed trait DbValue

Attributes

Companion
object
Source
DbValue.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class DbArray
class DbBigDecimal
class DbBoolean
class DbByte
class DbBytes
class DbChar
class DbDouble
class DbDuration
class DbFloat
class DbInstant
class DbInt
class DbLocalDate
class DbLocalTime
class DbLong
object DbNull
class DbShort
class DbString
class DbUUID
Show all
object DbValue

Attributes

Companion
trait
Source
DbValue.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
DbValue.type
object Ddl

Helpers for generating DDL fragments (CREATE TABLE, DROP TABLE).

Helpers for generating DDL fragments (CREATE TABLE, DROP TABLE).

Attributes

Source
Ddl.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Ddl.type
trait Dialect extends SqlMigration

Database-specific SQL generation for migration support structures.

Database-specific SQL generation for migration support structures.

Attributes

Companion
object
Source
Dialect.scala
Supertypes
trait SqlMigration
class Object
trait Matchable
class Any
Known subtypes
object Postgres
object SQLite
object Dialect

Attributes

Companion
trait
Source
Dialect.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Dialect.type
object Dump

Compile-time SQL dump emission.

Compile-time SQL dump emission.

When the JVM system property zib.sql.dumpDir is set, inline macro entry points dumpTable and dumpQuery emit .sql files to that directory at compile time. When the property is absent the calls expand to () with zero runtime cost. Files are named -.sql (owner derived from the enclosing symbol or query/table name), written as UTF-8 with a trailing newline, and skipped when the existing content is byte-identical (content-hash skip).

Attributes

Source
Dump.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Dump.type
object Frag

Attributes

Companion
class
Source
Frag.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Frag.type
final case class Frag(parts: IndexedSeq[String], params: IndexedSeq[DbValue])

A SQL fragment composed of literal text interleaved with typed parameter values.

A SQL fragment composed of literal text interleaved with typed parameter values.

parts(i) is a literal SQL string and params(i) is the value bound at the ? placeholder that follows it. The invariant is parts.length == params.length + 1: the fragment begins and ends with a literal segment (which may be empty).

Fragments are assembled via ++ and rendered to a dialect-specific SQL string with sql. Use the extension methods on Frag (e.g. query, queryOne, update) to execute them against a live DbCon.

The sql"..." string interpolator is the primary way to construct fragments; use Frag.literal for parameter-free SQL.

Attributes

Companion
object
Source
Frag.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Attributes

Companion
class
Source
JdbcTransactor.scala
Supertypes
class Object
trait Matchable
class Any
Self type
class JdbcTransactor(connectionFactory: () => Connection, val dialect: SqlDialect, val sqlLogger: SqlLogger = ...) extends Transactor

Attributes

Companion
object
Source
JdbcTransactor.scala
Supertypes
trait Transactor
class Object
trait Matchable
class Any

Canonical User/Repo/Star example for compile-time dump verification.

Canonical User/Repo/Star example for compile-time dump verification.

Builds the two-join query on the typed query IR (zio.blocks.sql.query.SqlQuery) and dumps it with Dump.dumpQuery.

Attributes

Source
JoinsDumpExample.scala
Supertypes
class Object
trait Matchable
class Any
Self type
object PgCodec

PostgreSQL-specific DbParam instances for collection types.

PostgreSQL-specific DbParam instances for collection types.

Import PgCodec.given to enable passing Seq[A], List[A], and IndexedSeq[A] as SQL array parameters in the sql"..." interpolator.

import zio.blocks.sql.*
import zio.blocks.sql.PgCodec.given

val ids: List[String] = List("a", "b", "c")
val frag = sql"SELECT * FROM products WHERE id = ANY($ids)"

These instances produce DbValue.DbArray values that bind as JDBC arrays via Connection.createArrayOf. The SQL element type is inferred from the Scala element type.

Attributes

Source
PgCodec.scala
Supertypes
class Object
trait Matchable
class Any
Self type
PgCodec.type
abstract class Repo[E, ID]

A type-safe repository that provides standard CRUD operations for entities of type E identified by a primary key of type ID.

A type-safe repository that provides standard CRUD operations for entities of type E identified by a primary key of type ID.

Repo wraps a Table and a description of its identity column, and generates all SQL at construction time so query strings are not re-built on every call.

==Construction== Use the companion constructors, or subclass Repo directly:

  • Repo.apply — fully explicit (table, id column, codec, getter)
  • Repo.derived — derived from a zio.blocks.schema.Schema
  • class UserRepo extends Repo[User, UserId] — derives from the contextual Schema and DbCodec and inherits all default CRUD operations.

==Thread safety== Repo is immutable and safe for concurrent use. Individual operations require a DbCon or DbTx given context which is not shared across threads unless the caller arranges it.

==Empty-input policy==

  • Builders throw on empty input (require): insertAll (empty rows), Frag.values (empty rows). An empty multi-row VALUES list is invalid SQL, so construction fails fast.
  • Executors return 0 (or List.empty for reads) on empty input without touching the database: insertBatch, insertOrUpdateBatch, deleteAll, findAll.
  • update returns 0 both when no row matches the ID and when the entity carries only the ID column (nothing to set) — callers cannot distinguish the two cases from the return value alone.

==Identifier quoting== Every identifier this repository renders — table and column names in SELECT/INSERT/UPDATE/DELETE and in the IN-list prefixes — is validated and wrapped in standard double quotes, matching zio.blocks.sql.query.QueryRenderer and the query IR (zio.blocks.sql.query.SqlQuery). Both dialects (PostgreSQL, SQLite) accept double-quoted identifiers, so there is no per-dialect quoting exception anywhere on these paths.

Attributes

Companion
object
Source
Repo.scala
Supertypes
class Object
trait Matchable
class Any
object Repo

Attributes

Companion
class
Source
Repo.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Repo.type
object SqlDialect

Attributes

Companion
trait
Source
SqlDialect.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
SqlDialect.type
sealed trait SqlDialect

Attributes

Companion
object
Source
SqlDialect.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object PostgreSQL
object SQLite

Pure identifier checker for SQL literal parts produced by the sql interpolator.

Pure identifier checker for SQL literal parts produced by the sql interpolator.

Tokenizes literal parts respecting single-quoted string literals, double-quoted identifiers and interpolation holes, subtracts the SQL keyword/function allowlist, tracks aliases introduced via AS alias, and reports unknown identifiers with Levenshtein suggestions.

Attributes

Source
SqlIdentifierChecker.scala
Supertypes
class Object
trait Matchable
class Any
Self type
final case class SqlLiteral(sql: String)

Escape hatch for unchecked raw SQL.

Escape hatch for unchecked raw SQL.

SqlLiteral holds a SQL string that is spliced verbatim into a sql"..." fragment without parameter binding or identifier checking. Use it for dialect-specific functions or dynamic SQL that the lint-grade checked sql (StringContext(...).sql(table)(...)) cannot model. Prefer the checked StringContext(...).sql(table)(...) form for all hand-written queries; reserve SqlLiteral for genuinely dynamic or dialect-specific cases.

Standalone usage (unchecked, no validation):

 val frag: Frag = SqlLiteral("SELECT * FROM legacy WHERE id = 1").toFrag

Splicing into sql interpolator as a raw fragment (not a parameter):

 sql"SELECT ${SqlLiteral("MY_FUNC(id)")} FROM users"

Attributes

Companion
object
Source
SqlLiteral.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object SqlLiteral

Attributes

Companion
class
Source
SqlLiteral.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
SqlLiteral.type
trait SqlLogger

Attributes

Companion
object
Source
SqlLogger.scala
Supertypes
class Object
trait Matchable
class Any
object SqlLogger

Attributes

Companion
trait
Source
SqlLogger.scala
Supertypes
class Object
trait Matchable
class Any
Self type
SqlLogger.type
trait SqlMigration

SQL generation for the data-migration queue machinery.

SQL generation for the data-migration queue machinery.

All identifier parameters (table, col, shadowName, sourceTable, sourceIdColumn, queueKeyColumn) must be bare, pre-validated SQL identifiers — never user input, never schema-qualified, never quoted. Valid identifiers match [A-Za-z_][A-Za-z0-9_]*. Each method enforces this whitelist up front via SqlIdentifier.validate (same package, no new API) so the documented contract holds mechanically rather than by convention. Implementations interpolate the validated identifiers into DDL/DML as-is.

Attributes

Source
Dialect.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait Dialect
object Postgres
object SQLite
object SqlNameMapper

The SqlNameMapper object provides predefined strategies for transforming field names into SQL column naming conventions.

The SqlNameMapper object provides predefined strategies for transforming field names into SQL column naming conventions.

This object defines several SqlNameMapper implementations:

  • SnakeCase: Transforms strings to snake_case (default for SQL). For example, "firstName" → "first_name", "userID" → "user_id".
  • Identity: Returns the input string as-is, performing no transformation.
  • Custom: Allows for user-defined transformations by applying a given function to the input column name.

Attributes

Companion
trait
Source
SqlNameMapper.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait SqlNameMapper extends String => String

A sealed trait that represents a strategy for mapping column names. Classes or objects that extend SqlNameMapper provide an implementation of the apply method, which specifies how a field name is transformed to a column name.

A sealed trait that represents a strategy for mapping column names. Classes or objects that extend SqlNameMapper provide an implementation of the apply method, which specifies how a field name is transformed to a column name.

Attributes

Companion
object
Source
SqlNameMapper.scala
Supertypes
trait String => String
class Object
trait Matchable
class Any
Known subtypes
class Custom
object Identity
object SnakeCase
final case class Table[A](name: String, codec: DbCodec[A], columnsMeta: IndexedSeq[ColumnMeta])

Metadata binding a Scala type A to a specific database table.

Metadata binding a Scala type A to a specific database table.

Value parameters

codec

The DbCodec used to read and write rows of type A.

columnsMeta

Per-column metadata (name, SQL type, nullability) derived from the schema. Used by createTable to emit DDL.

name

The SQL table name used in generated queries.

Attributes

Companion
object
Source
Table.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object Table

Attributes

Companion
class
Source
Table.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Table.type
object TableMetadata

Attributes

Source
TableMetadata.scala
Supertypes
class Object
trait Matchable
class Any
Self type

Attributes

Companion
trait
Source
TableMetadata.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait TableNamingPolicy

Attributes

Companion
object
Source
TableMetadata.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class Custom
object Plural
object Singular
enum TransactionIsolation(val jdbcLevel: Int)

Transaction isolation level.

Transaction isolation level.

Each value maps to the standard JDBC isolation level via jdbcLevel. Levels are defined as local Int constants matching the JDBC specification (1, 2, 4, 8) to avoid a java.sql dependency in the shared (JS) build. This keeps sql/shared free of java.sql — the JVM side interprets jdbcLevel via Connection.setTransactionIsolation — mirroring the convention in DbCodec.scala:101 where shared sources keep java.sql constants local.

SQLite semantics: SQLite natively supports only SERIALIZABLE (its default). Other levels are accepted by the driver and documented here but may be treated as SERIALIZABLE by the SQLite engine — the implementation still applies the requested level via Connection.setTransactionIsolation so behaviour is uniform across dialects, with the caveat that on SQLite the isolation guarantee remains serializable regardless of the requested level.

Attributes

Source
TransactionIsolation.scala
Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
trait Transactor

Entry point for executing SQL against a database.

Entry point for executing SQL against a database.

Both methods acquire a connection, execute the provided body, and close the connection upon return (whether the body succeeds or throws).

==Nested transactions (savepoints)==

Top-level transactions are started via transact { ... }, which opens a new connection, disables auto-commit, and commits/rolls back on exit. Inner (nested) transactions are emulated via SQL savepoints on the same connection and are accessed through the ambient DbTx:

transactor.transact {
 sql"INSERT INTO t VALUES (1)".update
 summon[DbTx].transact {
   sql"INSERT INTO t VALUES (2)".update
 }
}

Names are zib_tx_1 .. zib_tx_N where N is the nesting depth tracked in DbTx.currentDepth. Success → RELEASE SAVEPOINT, failure → ROLLBACK TO SAVEPOINT then rethrow; depth is decremented in finally so no savepoint leak occurs and the counter resets for subsequent siblings.

===Given-priority trick (documented)===

When a DbTx is already in scope (inside transact), the extension summon[DbTx].transact { ... } is preferred over transactor.transact { ... } because it resolves via the more specific DbTx receiver and reuses the same connection with a savepoint. A transparent-inline given trick that would make Transactor.transact auto-delegate to the savepoint path when an ambient DbTx exists is possible (e.g. transparent inline given DbTx with priority), but is not required here: the explicit summon[DbTx].transact form is the supported nested path and Transactor.transact remains the top-level entry point that opens a new connection. This keeps semantics explicit and avoids implicit-resolution surprises. If desired, a future inline trick can delegate transactor.transact to summon[DbTx].transact when summon[DbTx] is available, but the current implementation documents the pattern instead of hiding it behind implicits.

Additionally transactNested { ... } (both DbTx.transactNested and the top-level transactNested helper) is provided as an alias that takes the outer transaction as a using parameter.

Attributes

Source
Transactor.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Upsert

Builders for SQLite/PostgreSQL upsert Frags.

Builders for SQLite/PostgreSQL upsert Frags.

Every produced Frag follows the invariant parts.length == params.length + 1 and is rendered via dialect.paramPlaceholder (both dialects use ?). Identifiers are validated through SqlIdentifier.validate and quoted with double quotes in the conflict clause. Assignment columns are additionally validated against Table.columns.

Attributes

Source
Upsert.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Upsert.type

Value members

Concrete methods

def transactNested[A](f: DbTx ?=> A)(using outer: DbTx): A

Top-level helper that mirrors DbTx.transactNested with using syntax.

Top-level helper that mirrors DbTx.transactNested with using syntax.

Attributes

Source
DbTx.scala

Extensions

Extensions

extension (outer: DbTx)
def transact[A](f: DbTx ?=> A): A

Execute f inside a savepoint nested transaction.

Execute f inside a savepoint nested transaction.

Creates savepoint zib_tx_ where depth is outer.currentDepth + 1, runs f with the same underlying connection (given DbTx is outer with incremented depth), releases on success and rolls back to the savepoint on failure. Depth is always decremented in finally. On failure only depth is decremented and the savepoint is not released (it will be cleaned up when outer transaction commits/rolls back).

Attributes

Source
DbTx.scala
extension (inline sc: StringContext)
inline def sql(inline args: Any*): Frag

Plain sql"SELECT ... $param" — validates quotes/parentheses only.

Plain sql"SELECT ... $param" — validates quotes/parentheses only.

Attributes

Source
SqlInterpolator.scala