Skip to content
chdb-ioPublic

About

chdb-ruby is a Ruby library for accessing chDB embedded analytical database with SQLite3-compatible API design.

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Repository files navigation

Ruby binding for chDB

Overview

This library allows Ruby programs to use the chDB embedded analytical database (https://github.com/chdb-io/chdb).

Designed with SQLite3-compatible API style - If you're familiar with Ruby's sqlite3 gem, you'll feel right at home with chdb-ruby's similar interface design.

Note that this module is only compatible with ChDB 3.0.0 or newer.

Quick start

Before using chdb-ruby, install the gem first. This will download the libchdb C++ library dependencies, so please be patient:

gem install chdb-ruby

Below are examples of common interfaces usage:

require 'chdb'

# Open a database
# Parameter explanation:
# 1. path supports two formats:
#    - ":memory:" in-memory temporary database (data destroyed on close)
#    - "file:/path/to/db" file-based persistent database
#    Configuration parameters can be appended via URL-style query (e.g. 'file:test.db?results_as_hash=true')
# 2. options hash supports:
#    - results_as_hash: controls whether result sets return as hashes (default: arrays)
db = ChDB::Database.new('file:test.db', results_as_hash: true)

# Create a database
db.execute('CREATE DATABASE IF NOT EXISTS test')

# Create a table
db.execute('DROP TABLE IF EXISTS test.test_table')
rows = db.execute <<-SQL
  CREATE TABLE test.test_table(
    id Int32,
    name String)
    ENGINE = MergeTree()
    ORDER BY id
SQL

# Execute a few inserts
{
  1 => 'Alice',
  2 => 'Bob'
}.each do |pair|
  db.execute 'INSERT INTO test.test_table VALUES ( ?, ? )', pair
end

# Find a few rows
db.execute('SELECT * FROM test.test_table ORDER BY id') do |row|
  p row
end
# [{ 'id' => '1', 'name' => 'Alice' },
#  { 'id' => '2', 'name' => 'Bob' }]

# When you need to open another database, you must first close the previous database 
db.close()

# Open another database
db = ChDB::Database.new 'file:test.db'

# Create another table
db.execute('DROP TABLE IF EXISTS test.test2_table')
rows = db.execute <<-SQL
  CREATE TABLE test.test2_table(
    id Int32,
    name String)
    ENGINE = MergeTree()
    ORDER BY id
SQL

# Execute inserts with parameter markers
db.execute('INSERT INTO test.test2_table (id, name)
            VALUES (?, ?)', [3, 'Charlie'])

# Find rows with the first row displaying column names
db.execute2('SELECT * FROM test.test2_table') do |row|
  p row
end
# ["id", "name"]
# ["3", "Charlie"]

# Close the database
db.close()

# Use ChDB::Database.open to automatically close the database connection:
ChDB::Database.open('file:test.db') do |db|
  result = db.execute('SELECT 1')
  p result.to_a # => [["1"]]
end

# Query with specific output formats (CSV, JSON, etc.):
# See more details at https://clickhouse.com/docs/interfaces/formats.
ChDB::Database.open(':memory:') do |db|
  csv_data = db.query_with_format('SELECT 1 as a, 2 as b', 'CSV')
  p csv_data
  # "1,2\n"

  json_data = db.query_with_format('SELECT 1 as a, 2 as b', 'JSON')
  p json_data
end

# Execute streaming query
ChDB::Database.open(':memory:') do |db|
  total_rows = 0
  collected = []
  db.send_query('SELECT * FROM numbers(200000)') do |chunk|
    collected << chunk.buf
    total_rows += chunk.rows_read
  end
  p total_rows # => 200000
end

Scalar user-defined functions

A Ruby block can be registered as a scalar function and called from SQL. The API follows ruby-duckdb's DuckDB::ScalarFunction, and needs chDB core v26.11.2-rc.3 or later, the engine this gem installs.

require 'chdb'

db = ChDB::Database.new(':memory:')

# Called once per row, with the values of its arguments.
db.register_scalar_function(name: 'plus_one', return_type: 'Int64', parameter_type: 'Int64') { |x| x + 1 }
db.execute('SELECT plus_one(toInt64(number)) FROM numbers(3)')
# => [["1"], ["2"], ["3"]]

# The same with a ChDB::ScalarFunction, from ChDB::ScalarFunction.create or with setters.
title_case = ChDB::ScalarFunction.new
title_case.name = 'title_case'
title_case.add_parameter('String')
title_case.return_type = 'Nullable(String)'
title_case.set_function { |s| s.empty? ? nil : s.split.map(&:capitalize).join(' ') }
db.register_scalar_function(title_case)

# batch: true calls the block once per batch of rows with an Array per argument;
# it returns an Array with a result per row.
db.register_scalar_function(name: 'weighted', return_type: 'Float64',
                            parameter_types: %w[Float64 Float64], batch: true) do |values, weights|
  values.zip(weights).map { |value, weight| value * weight }
end
db.execute("SELECT title_case('green tea'), weighted(3.5, 2)")
# => [["Green Tea", "7"]]

db.drop_scalar_function('plus_one')

Arguments and results are declared with ClickHouse type names, written as toTypeName prints them, and their values map to Ruby like this:

ClickHouse type Argument in Ruby Result from Ruby
Bool true or false true or false
Int8 to Int64, UInt8 to UInt64 Integer Integer
Float32, Float64, BFloat16 Float Float or Integer
String UTF-8 String, or binary (ASCII-8BIT) with binary_strings String of any encoding, as bytes
Date, Date32 Date Date
DateTime, DateTime64(p) with or without a time zone Time in UTC Time
Nullable(T) as T, or nil with null_handling as T, or nil
LowCardinality(T) as T as T

Other types, such as Array, Tuple, Map, Decimal, UUID, Enum and the 128- and 256-bit integers, fail registration with ChDB::InvalidArgumentException. An argument must have the declared type or one that converts to it without loss: an Int32 column is accepted for an Int64 parameter, a UInt64 one is not (cast it with toInt64, since numbers() yields UInt64). chDB converts a result to the declared return type, and a value that does not fit it, such as 300 for UInt8, fails the query. Only a Nullable return type accepts nil, and a value of another Ruby class fails the query with a TypeError message.

The keyword arguments of register_scalar_function and ChDB::ScalarFunction.create, or the setters, change how chDB calls the function:

  • null_handling: true (set_special_handling) passes NULL arguments to the block as nil. By default a row with a NULL argument yields NULL without calling the block, and the result type becomes Nullable.
  • volatile: true (set_volatile) evaluates the function for every row, like rand(). By default chDB may evaluate a call with constant arguments, such as one without arguments, once for all rows of a query.
  • binary_strings: true (set_binary_strings) passes String arguments as binary (ASCII-8BIT) strings. By default they are UTF-8, and a value that is not valid UTF-8 fails the query.
  • batch: true (set_function(batch: true)) calls the block once per batch, as above. A batch function needs at least one parameter.

An exception raised by the block fails the query with a ChDB::Exception that carries the exception's class and message, e.g. Scalar function 'f' failed on a batch of 3 rows: ArgumentError: zero is not allowed, and the database keeps working. An Interrupt, a Timeout, exit, Thread#kill or throw in a block stops the query too, and then propagates from the method that ran the query, as it would from any other method.

Registered functions are process-wide, unlike DuckDB's per-connection functions: a function is visible to every connection of the process, and stays registered after the database is closed until drop_scalar_function, which also works on a closed database. The name must not be taken by a built-in function (in any case for case-insensitive ones such as LOWER), an aggregate function or another user-defined function: registering a taken name, or dropping one that is not registered, raises ChDB::Exception.

chDB calls a function once per batch of rows, from its own threads and several at a time, and those threads cannot run Ruby. So every call this gem makes into chDB runs on a helper thread, while the Ruby thread that made it waits with the GVL released and runs the blocks of its query, a batch at a time. Blocks therefore run one at a time, normally on the thread that issued the query, and other Ruby threads keep running while chDB works. A block must not use chDB itself: a query from inside a block raises ChDB::Exception, and so does any other call into chDB, and a block that waits for another thread's chDB call waits forever.

ChDB.library_version returns the version of the loaded libchdb. An older one still works for everything else, but registering a function then raises ChDB::Exception ("this libchdb lacks the scalar function ABI (needs v26.11.2-rc.3 or later)").

Thread Safety

When using ChDB::Database.new or ChDB::Database.open to open a database connection, all read/write operations within that session are thread-safe: chDB runs them one at a time, and releases the GVL while it does, so other Ruby threads keep running. However, currently only one active database connection is allowed per process. Therefore, when you need to open another database connection, you must first close the previous connection. Please note that ChDB::Database.new, ChDB::Database.open, and ChDB::Database.close methods themselves are not thread-safe. If used in multi-threaded environments, external synchronization must be implemented to prevent concurrent calls to these methods, which could lead to undefined behavior.

require 'chdb'

db = ChDB::Database.new ':memory:'

latch = Queue.new

ts = 10.times.map {
  Thread.new {
    latch.pop
    db.execute 'SELECT 1'
  }
}
10.times { latch << nil }

p ts.map(&:value)
# [[["1"]], [["1"]], [["1"]], [["1"]], [["1"]], [["1"]], [["1"]], [["1"]], [["1"]], [["1"]]]

db.close()

Other instances can be shared among threads, but they require that you provide your own locking for thread safety. For example, ChDB::Statement objects (prepared statements) are mutable, so applications must take care to add appropriate locks to avoid data race conditions when sharing these objects among threads.

It is generally recommended that if applications want to share a database among threads, they only share the database instance object. Other objects are fine to share, but may require manual locking for thread safety.

Support

Installation

If you're having trouble with installation, please first read INSTALLATION.md.

Bug reports

You can file the bug at the github issues page.

License

This library is licensed under Apache License 2.0, see LICENSE.

Acknowledgments

Special thanks to the following projects:

  • chDB 2.0 Ruby client – As the foundational work for chDB 2.0, its design and architecture inspired this chDB 3.0 Ruby client.
  • SQLite3 – We adopted patterns from its elegant Ruby API design.

About

chdb-ruby is a Ruby library for accessing chDB embedded analytical database with SQLite3-compatible API design.

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages