com.softinio.duck4s.algebra

Algebra Package: Core Types and Data Structures

The algebra package contains the fundamental types, error hierarchies, and algebraic data structures that form the foundation of the duck4s library. These types provide type-safe, functional abstractions over DuckDB's JDBC interface.

Core Types

Error Handling

Configuration

Query Execution

Batch Operations

Type Classes for Batch Operations

The algebra package provides powerful type classes for type-safe batch operations:

// Built-in support for tuples up to 4 elements
batch.addBatch((1, "Alice"))                    // (Int, String)
batch.addBatch((1, "Alice", 25))                // (Int, String, Int)
batch.addBatch((1, "Alice", 25, true))          // (Int, String, Int, Boolean)
batch.addBatch((1, "Alice", 25, 999.99))        // (Int, String, Int, Double)

// Built-in support for primitive types
stmt.setInt(1, 42)
stmt.setString(2, "hello")
stmt.setDouble(3, 3.14)
stmt.setBoolean(4, true)
stmt.setLong(5, 1000L)

// Option support for nullable values
stmt.setString(1, Some("value"))    // Sets the string value
stmt.setString(1, None)             // Sets NULL

Custom Type Class Instances

You can provide custom ParameterBinder instances for your own types:

case class UserId(value: Long)

given ParameterBinder[UserId] with
 def bind(stmt: DuckDBPreparedStatement, index: Int, value: UserId): Either[DuckDBError, Unit] =
   stmt.setLong(index, value.value).map(_ => ())

// Now UserId can be used in batch operations
batch.addBatch((UserId(123), "Alice"))

Error Handling Patterns

All operations return Either[DuckDBError, T] for functional composition:

for
 stmt <- conn.prepareStatement("INSERT INTO users VALUES (?, ?)")
 _ <- stmt.setInt(1, 1)
 _ <- stmt.setString(2, "Alice")
 result <- stmt.executeUpdate()
yield result

Resource Management

Types in this package follow consistent resource management patterns:

  • All resource types implement AutoCloseable
  • Prefer with* methods for automatic cleanup
  • Resources are cleaned up even on errors
  • Nested resource usage is safely composed

Attributes

See also

com.softinio.duck4s.DuckDBConnection for the main connection interface

Since

0.1.0

Members list

Type members

Classlikes

trait BatchBinder[T]

Type class for binding batch parameters to prepared statements.

Type class for binding batch parameters to prepared statements.

This type class provides a way to bind different types of parameter values to prepared statements in a type-safe manner. Implementations are provided for tuples of various sizes, allowing batch operations with multiple parameters.

Type parameters

T

the type of parameter values to bind

Attributes

See also

ParameterBinder for individual parameter binding

Since

0.1.0

Example
 // Custom binder for a case class case class User(name: String, age:
 Int)
given BatchBinder[User] with def bind(stmt: DuckDBPreparedStatement, values:
User*): Either[DuckDBError, Unit] = if (values.isEmpty) Right(()) else val
user = values.head for { _ <- stmt.setString(1, user.name) _ <-
stmt.setInt(2, user.age) } yield () 
Companion
object
Supertypes
class Object
trait Matchable
class Any
object BatchBinder

Companion object providing implicit BatchBinder instances for common types.

Companion object providing implicit BatchBinder instances for common types.

This object contains given instances for tuples of various sizes (2, 3, and 4 elements). Each binder uses the appropriate ParameterBinder instances for the tuple elements.

Attributes

Since

0.1.0

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type

Specifies the connection mode for DuckDB connections.

Specifies the connection mode for DuckDB connections.

DuckDB supports two primary connection modes: in-memory databases for temporary data processing and persistent databases stored on disk.

Attributes

Since

0.1.0

Supertypes
trait Enum
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class DuckDBBatch(preparedStatement: DuckDBPreparedStatement) extends AutoCloseable

A batch operation wrapper for executing multiple parameter sets efficiently.

A batch operation wrapper for executing multiple parameter sets efficiently.

This class provides a type-safe way to execute batch operations with prepared statements. It uses type classes (BatchBinder and ParameterBinder) to automatically bind parameters of various types, making batch operations both safe and convenient.

Value parameters

preparedStatement

the prepared statement to use for batch operations

Attributes

See also

BatchBinder for parameter binding type class

ParameterBinder for individual parameter binding

DuckDBBatchResult for batch execution results

Since

0.1.0

Example
 // Batch insert with tuples val batch = for { stmt <-
 connection.prepareStatement("INSERT INTO users (name, age) VALUES (?, ?)")
 batch <- Right(DuckDBBatch(stmt)) _ <- batch.addBatch(("Alice", 25),
 ("Bob", 30), ("Charlie", 35)) result <- batch.executeBatch() } yield
 result
// Batch update with different parameter types val updateBatch = for { stmt
<- connection.prepareStatement("UPDATE products SET price = ?, active = ?
WHERE id = ?") batch <- Right(DuckDBBatch(stmt)) _ <- batch.addBatch((19.99,
true, 1), (29.99, false, 2)) result <- batch.executeBatch() } yield result
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class DuckDBBatchResult(updateCounts: Array[Int], successCount: Int, failureCount: Int)

Result of executing a batch operation, containing update counts and statistics.

Result of executing a batch operation, containing update counts and statistics.

This class encapsulates the results of executing a batch operation, providing both detailed update counts for each operation in the batch and summary statistics about successes and failures.

Value parameters

failureCount

the number of operations that failed

successCount

the number of operations that completed successfully

updateCounts

array of update counts for each operation in the batch. Non-negative values indicate the number of rows affected by that operation. Negative values indicate failures.

Attributes

See also

DuckDBBatch.executeBatch for executing batch operations

DuckDBBatch for batch operation management

Since

0.1.0

Example
 val result = for { batch <- Right(DuckDBBatch(stmt)) _ <-
 batch.addBatch(("Alice", 25), ("Bob", 30), ("Charlie", 35)) result <-
 batch.executeBatch() } yield result
result match { case Right(batchResult) => println(s"Total operations:
${batchResult.updateCounts.length}") println(s"Successful:
${batchResult.successCount}") println(s"Failed:
${batchResult.failureCount}")
// Check individual operation results
batchResult.updateCounts.zipWithIndex.foreach { case (count, index) => if
(count >= 0) { println(s"Operation $index: $count rows affected") } else {
println(s"Operation $index: failed") } }
// Check if all operations succeeded if (batchResult.isAllSuccessful) {
println("All operations completed successfully!") }
case Left(error) => println(s"Batch execution failed: $error") } 
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class DuckDBConfig(mode: ConnectionMode, readOnly: Boolean, tempDirectory: Option[String], streamResults: Boolean, additionalProperties: Map[String, String])

Configuration options for DuckDB connections.

Configuration options for DuckDB connections.

This case class provides a comprehensive set of configuration options for customizing DuckDB connection behavior, including connection mode, read-only access, temporary directory settings, and additional JDBC properties.

Value parameters

additionalProperties

Additional JDBC properties to pass to the connection

mode

The connection mode (in-memory or persistent)

readOnly

Whether the connection should be read-only

streamResults

Whether to enable JDBC result streaming for large result sets

tempDirectory

Optional custom temporary directory for DuckDB operations

Attributes

See also

ConnectionMode for available connection modes

Since

0.1.0

Example
 // In-memory database with streaming enabled val config =
 DuckDBConfig( mode = ConnectionMode.InMemory, streamResults = true )
// Persistent read-only database val readOnlyConfig = DuckDBConfig( mode =
ConnectionMode.Persistent("/path/to/database.db"), readOnly = true ) 
Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object DuckDBConfig

Factory methods for creating common DuckDB configurations.

Factory methods for creating common DuckDB configurations.

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait DuckDBError

Root error type for all DuckDB-related errors in duck4s.

Root error type for all DuckDB-related errors in duck4s.

This sealed trait represents all possible errors that can occur when working with DuckDB through the duck4s library. All operations return Either[DuckDBError, T] for functional error handling.

Attributes

See also

DuckDBError.ConnectionError for connection-related errors

DuckDBError.QueryError for SQL execution errors

DuckDBError.TransactionError for transaction-related errors

DuckDBError.ConfigurationError for configuration errors

DuckDBError.InvalidStateError for invalid state errors

Since

0.1.0

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object DuckDBError

Contains all concrete error types that can occur in duck4s operations.

Contains all concrete error types that can occur in duck4s operations.

Attributes

Companion
trait
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
case class DuckDBPreparedStatement(underlying: PreparedStatement, sql: String) extends AutoCloseable

A wrapper around a JDBC PreparedStatement that provides type-safe parameter binding and error handling with DuckDB-specific error types.

A wrapper around a JDBC PreparedStatement that provides type-safe parameter binding and error handling with DuckDB-specific error types.

This class encapsulates a JDBC PreparedStatement and provides methods for setting parameters and executing queries/updates in a functional style. All parameter setting methods return Either types for error handling, making it safe to compose operations.

Value parameters

sql

the SQL query string, used for error reporting

underlying

the underlying JDBC PreparedStatement

Attributes

See also

DuckDBConnection.prepareStatement for creating prepared statements

DuckDBBatch for batch operations

DuckDBResultSet for query results

Since

0.1.0

Example
 // Setting parameters and executing a query val result = for { stmt <-
 connection.prepareStatement("SELECT * FROM users WHERE age > ? AND name
 LIKE ?") _ <- stmt.setInt(1, 18) _ <- stmt.setString(2, "John%") rs <-
 stmt.executeQuery() } yield rs
// Batch operations val batch = for { stmt <-
connection.prepareStatement("INSERT INTO users (name, age) VALUES (?, ?)") _
<- stmt.setString(1, "Alice") _ <- stmt.setInt(2, 25) _ <- stmt.addBatch() _
<- stmt.setString(1, "Bob") _ <- stmt.setInt(2, 30) _ <- stmt.addBatch() }
yield stmt 
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
case class DuckDBResultSet(underlying: ResultSet, statement: Statement) extends AutoCloseable

A wrapper around a JDBC ResultSet that provides automatic resource management for both the result set and its associated statement.

A wrapper around a JDBC ResultSet that provides automatic resource management for both the result set and its associated statement.

This class is designed to be used with the using pattern or explicit resource management to ensure that both the underlying ResultSet and its Statement are properly closed when no longer needed. The class exports common ResultSet methods for convenient access.

Value parameters

statement

the Statement that created this ResultSet, needed for proper cleanup

underlying

the underlying JDBC ResultSet

Attributes

See also

DuckDBConnection for creating result sets

DuckDBPreparedStatement for parameterized queries

Since

0.1.0

Example
 import scala.util.Using
// Automatic resource management val result =
Using(connection.executeQuery("SELECT * FROM users")) { rs => while
(rs.next()) { println(s"Name: ${rs.getString("name")}, Age:
${rs.getInt("age")}") } }
// Or with explicit management val rs = connection.executeQuery("SELECT
count(*) FROM users") try { if (rs.next()) { val count = rs.getInt(1)
println(s"Total users: $count") } } finally { rs.close() // Closes both
ResultSet and Statement } 
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
trait ParameterBinder[T]

Type class for binding individual parameters to prepared statements.

Type class for binding individual parameters to prepared statements.

This type class provides a way to bind individual parameter values to prepared statements at specific parameter indexes. Implementations are provided for common Scala types and Option types.

Type parameters

T

the type of parameter value to bind

Attributes

See also

BatchBinder for batch parameter binding

Since

0.1.0

Example
 // Custom binder for a custom type case class UserId(value: Long)
given ParameterBinder[UserId] with def bind( stmt: DuckDBPreparedStatement,
index: Int, value: UserId ): Either[DuckDBError, Unit] = stmt.setLong(index,
value.value).map(_ => ()) 
Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object booleanBinder
object doubleBinder
object intBinder
object longBinder
object stringBinder

Companion object providing implicit ParameterBinder instances for common types.

Companion object providing implicit ParameterBinder instances for common types.

This object contains given instances for primitive types (Int, Long, Double, String, Boolean) and Option types, providing automatic parameter binding for these common cases.

Attributes

Since

0.1.0

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type