# Ruby

Connect to ParticleDB from Ruby, run parameterized queries, handle transactions and errors.

Source: https://particledb.ai/sdks/ruby/

Use the configured address for your client. See [connection addresses](/installation/ports/) and [security](/guides/security/). The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.

Use the standard
[`pg`](https://github.com/ged/ruby-pg) gem over the SQL client interface (port 5432): queries, bind
parameters, transactions and key-value SQL functions are available through this connection.

## Install

```ruby
# Gemfile
gem "pg"
```

## Quick start

The example connects as `postgres` with the password `secret`, for a server started with
`particledb start --auth-method scram-sha-256 --pg-password secret`. With the server's default
`--auth-method password`, pass `sslmode: "require"`; see
[TLS and authentication](/connectivity/tls/#authentication).

```ruby
require "pg"

conn = PG.connect(host: "localhost", port: 5432, dbname: "particledb",
                  user: "postgres", password: "secret")

conn.exec("CREATE TABLE products (id BIGINT PRIMARY KEY, name TEXT, price DOUBLE PRECISION)")
conn.exec_params(
  "INSERT INTO products (id, name, price) VALUES ($1, $2, $3)",
  [1, "Keyboard", 89.99]
)
conn.exec_params("INSERT INTO products VALUES ($1, $2, $3)", [2, "Mouse", 19.5])

conn.exec_params("SELECT name, price FROM products WHERE price > $1", [50]).each do |row|
  puts "#{row['name']}: #{row['price']}"
end

conn.transaction do |c|
  c.exec_params("UPDATE products SET price = price - $1 WHERE id = $2", [10, 1])
  c.exec_params("UPDATE products SET price = price + $1 WHERE id = $2", [10, 2])
end

conn.exec("SELECT id, price FROM products ORDER BY id").each { |r| p r }

conn.exec_params("SELECT KV_SET($1, $2)", ["user:1", "alice"])
puts conn.exec_params("SELECT KV_GET($1) AS value", ["user:1"]).getvalue(0, 0)
conn.close
```

Output:

```
Keyboard: 89.99
{"id"=>"1", "price"=>"79.99"}
{"id"=>"2", "price"=>"29.5"}
alice
```

`conn.transaction` commits when the block returns and rolls back if it raises. Values come
back as strings unless you configure a type map (`PG::BasicTypeMapForResults`). Key-value data
is also reachable over the [Redis protocol](/connectivity/redis-commands/).

## Next steps

- [SQL Reference](/sql/overview/). SQL syntax and examples
- [ORM compatibility](/connectivity/orm-compatibility/). ORMs tested against ParticleDB
- [Vector Search](/sql/vector-search/). vector columns, indexes, and distance functions
