Class: DuckDB::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/duckdb/connection.rb,
ext/duckdb/connection.c

Overview

The DuckDB::Connection encapsulates connection with DuckDB database.

require 'duckdb'
db = DuckDB::Database.open
con = db.connect
con.query(sql)

Instance Method Summary collapse

Instance Method Details

#appender(table) {|appender| ... } ⇒ Object

returns Appender object. The first argument is table name

Yields:



61
62
63
64
65
66
67
68
69
# File 'lib/duckdb/connection.rb', line 61

def appender(table)
  appender = create_appender(table)

  return appender unless block_given?

  yield appender
  appender.flush
  appender.close
end

#connect(db) ⇒ Object Also known as: open

connects DuckDB database The first argument is DuckDB::Database object



38
39
40
41
42
43
44
45
46
47
# File 'lib/duckdb/connection.rb', line 38

def connect(db)
  conn = _connect(db)
  return conn unless block_given?

  begin
    yield conn
  ensure
    conn.disconnect
  end
end

#disconnectObject Also known as: close



58
59
60
61
62
63
64
65
# File 'ext/duckdb/connection.c', line 58

static VALUE duckdb_connection_disconnect(VALUE self) {
    rubyDuckDBConnection *ctx;

    TypedData_Get_Struct(self, rubyDuckDBConnection, &connection_data_type, ctx);
    duckdb_disconnect(&(ctx->con));

    return self;
}

#prepared_statement(str) ⇒ Object

returns PreparedStatement object. The first argument is SQL string.



53
54
55
# File 'lib/duckdb/connection.rb', line 53

def prepared_statement(str)
  PreparedStatement.new(self, str)
end

#query(sql, *args) ⇒ Object Also known as: execute

executes sql with args. The first argument sql must be SQL string. The rest arguments are parameters of SQL string. The parameters must be ‘?’ in SQL statement.

require 'duckdb'
db = DuckDB::Database.open('duckdb_file')
con = db.connect
users = con.query('SELECT * FROM users')
sql = 'SELECT * FROM users WHERE name = ? AND email = ?'
dave = con.query(sql, 'Dave', '[email protected]')


24
25
26
27
28
29
30
31
32
# File 'lib/duckdb/connection.rb', line 24

def query(sql, *args)
  return query_sql(sql) if args.empty?

  stmt = PreparedStatement.new(self, sql)
  args.each_with_index do |arg, i|
    stmt.bind(i + 1, arg)
  end
  stmt.execute
end