zio.blocks.sql
Members list
Type members
Classlikes
This object was generated by sbt-buildinfo.
This object was generated by sbt-buildinfo.
Attributes
- Source
- BuildInfo.scala
- Supertypes
-
trait Singletontrait Producttrait Mirrortrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
- Self type
-
BuildInfo.type
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
Attributes
- Source
- TableMetadata.scala
- Supertypes
Attributes
- Companion
- trait
- Source
- DbCodec.scala
- Supertypes
- Self type
-
DbCodec.type
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
Attributes
- Companion
- class
- Source
- DbCodecDeriver.scala
- Supertypes
- Self type
-
DbCodecDeriver.type
Attributes
- Companion
- object
- Source
- DbCodecDeriver.scala
- Supertypes
- Known subtypes
-
object DbCodecDeriver
Attributes
- Source
- DbCon.scala
- Supertypes
- Known subtypes
-
trait DbTx
Attributes
- Source
- DbConnection.scala
- Supertypes
Attributes
- Companion
- object
- Source
- SqlInterpolator.scala
- Supertypes
- Known subtypes
-
object dbParamBytesobject given_DbParam_BigDecimalobject given_DbParam_Booleanobject given_DbParam_Byteobject given_DbParam_DbValueobject given_DbParam_Doubleobject given_DbParam_Durationobject given_DbParam_Floatobject given_DbParam_Instantobject given_DbParam_Intobject given_DbParam_LocalDateobject given_DbParam_LocalDateTimeobject given_DbParam_LocalTimeobject given_DbParam_Longobject given_DbParam_Shortobject given_DbParam_Stringobject given_DbParam_UUIDobject iArrayStringParamobject indexedSeqIntParamobject indexedSeqLongParamobject indexedSeqStringParamobject listBooleanParamobject listDoubleParamobject listIntParamobject listLongParamobject listStringParamobject listUuidParamobject seqBooleanParamobject seqDoubleParamobject seqIntParamobject seqLongParamobject seqStringParamobject seqUuidParamShow all
Attributes
- Companion
- trait
- Source
- SqlInterpolator.scala
- Supertypes
- 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
Attributes
- Source
- DbConnection.scala
- Supertypes
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
Attributes
- Source
- DbConnection.scala
- Supertypes
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
Attributes
- Companion
- trait
- Source
- DbTx.scala
- Supertypes
- Self type
-
DbTx.type
Attributes
- Companion
- object
- Source
- DbValue.scala
- Supertypes
- Known subtypes
-
class DbArrayclass DbBigDecimalclass DbBooleanclass DbByteclass DbBytesclass DbCharclass DbDoubleclass DbDurationclass DbFloatclass DbInstantclass DbIntclass DbLocalDateclass DbLocalDateTimeclass DbLocalTimeclass DbLongobject DbNullclass DbShortclass DbStringclass DbUUIDShow all
Attributes
- Companion
- trait
- Source
- DbValue.scala
- Supertypes
- Self type
-
DbValue.type
Database-specific SQL generation for migration support structures.
Database-specific SQL generation for migration support structures.
Attributes
- Companion
- object
- Source
- Dialect.scala
- Supertypes
- Known subtypes
Attributes
- Companion
- trait
- Source
- Dialect.scala
- Supertypes
- Self type
-
Dialect.type
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
- Self type
-
Dump.type
Attributes
- Companion
- class
- Source
- Frag.scala
- Supertypes
- Self type
-
Frag.type
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
Attributes
- Companion
- class
- Source
- JdbcTransactor.scala
- Supertypes
- Self type
-
JdbcTransactor.type
Attributes
- Companion
- object
- Source
- JdbcTransactor.scala
- Supertypes
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
- Self type
-
JoinsDumpExample.type
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
- Self type
-
PgCodec.type
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 contextualSchemaandDbCodecand 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(orList.emptyfor reads) on empty input without touching the database: insertBatch, insertOrUpdateBatch, deleteAll, findAll. - update returns
0both 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
Attributes
- Companion
- class
- Source
- Repo.scala
- Supertypes
- Self type
-
Repo.type
Attributes
- Companion
- trait
- Source
- SqlDialect.scala
- Supertypes
- Self type
-
SqlDialect.type
Attributes
- Companion
- object
- Source
- SqlDialect.scala
- Supertypes
- Known subtypes
-
object PostgreSQLobject 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
- Self type
-
SqlIdentifierChecker.type
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
Attributes
- Companion
- class
- Source
- SqlLiteral.scala
- Supertypes
- Self type
-
SqlLiteral.type
Attributes
- Companion
- object
- Source
- SqlLogger.scala
- Supertypes
Attributes
- Companion
- trait
- Source
- SqlLogger.scala
- Supertypes
- Self type
-
SqlLogger.type
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
- Known subtypes
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
- Self type
-
SqlNameMapper.type
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
- Known subtypes
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
Attributes
- Companion
- class
- Source
- Table.scala
- Supertypes
- Self type
-
Table.type
Attributes
- Source
- TableMetadata.scala
- Supertypes
- Self type
-
TableMetadata.type
Attributes
- Companion
- trait
- Source
- TableMetadata.scala
- Supertypes
- Self type
-
TableNamingPolicy.type
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 Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
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
- Known subtypes
-
class JdbcTransactor
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
- Self type
-
Upsert.type
Value members
Concrete methods
Top-level helper that mirrors DbTx.transactNested with using syntax.
Extensions
Extensions
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
Plain sql"SELECT ... $param" — validates quotes/parentheses only.
Plain sql"SELECT ... $param" — validates quotes/parentheses only.
Attributes
- Source
- SqlInterpolator.scala