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
- DuckDBError - Sealed trait hierarchy for all possible errors
- DuckDBError.ConnectionError - Connection establishment and management errors
- DuckDBError.QueryError - SQL execution errors with query context
- DuckDBError.TransactionError - Transaction-related errors
- DuckDBError.ConfigurationError - Configuration validation errors
- DuckDBError.InvalidStateError - Invalid object state errors
Configuration
- DuckDBConfig - Comprehensive connection configuration
- ConnectionMode - In-memory vs persistent database modes
Query Execution
- DuckDBResultSet - Wrapper around JDBC ResultSet with resource management
- DuckDBPreparedStatement - Type-safe prepared statement wrapper
Batch Operations
- DuckDBBatch - Efficient batch operation wrapper
- DuckDBBatchResult - Results and metrics from batch execution
- BatchBinder - Type class for binding batch parameters
- ParameterBinder - Type class for individual parameter binding
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
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
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
- Self type
-
BatchBinder.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 Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
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 Serializabletrait Producttrait Equalstrait AutoCloseableclass Objecttrait Matchableclass AnyShow all
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
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
Factory methods for creating common DuckDB configurations.
Factory methods for creating common DuckDB configurations.
Attributes
- Companion
- class
- Supertypes
- Self type
-
DuckDBConfig.type
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
- Known subtypes
-
class ConfigurationErrorclass ConnectionErrorclass InvalidStateErrorclass QueryErrorclass TransactionError
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
- Self type
-
DuckDBError.type
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 Serializabletrait Producttrait Equalstrait AutoCloseableclass Objecttrait Matchableclass AnyShow all
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 Serializabletrait Producttrait Equalstrait AutoCloseableclass Objecttrait Matchableclass AnyShow all
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
- Known subtypes
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
- Self type
-
ParameterBinder.type