Sequel to lekki, bezpieczny wątkowo (thread-safe) zestaw narzędzi bazodanowych oraz ORM dla Ruby.
Nawiązywanie połączeń z bazami danych
require 'sequel'
# SQLite w pamięci lub jako plik
DB = Sequel.sqlite('database.db')
# PostgreSQL / MySQL
DB = Sequel.connect('postgres://user:password@localhost/mydb', max_connections: 10)
Zbiory danych (Datasets) i zapytania
Wyrażenia w Sequel można łączyć łańcuchowo i są ewaluowane leniwie:
items = DB[:items] # Reprezentuje zbiór danych (dataset)
# Select, Where, Order
items.where(category: 'tools').order(:price).limit(10).all
# Złożone filtry
items.where{ price > 100 }
items.exclude(status: 'archived')
# Wstawianie i aktualizacja
items.insert(name: 'Hammer', price: 15.99)
items.where(id: 1).update(price: 19.99)
# Usuwanie
items.where(id: 1).delete
Modele Sequel
class User < Sequel::Model
plugin :validation_helpers
plugin :timestamps
one_to_many :posts
def validate
super
validates_presence [:name, :email]
validates_unique :email
end
end
user = User.create(name: 'Alice', email: '[email protected]')
Transakcje bazodanowe
DB.transaction do
account_a.update(balance: account_a.balance - 100)
account_b.update(balance: account_b.balance + 100)
end