Sequel은 Ruby를 위한 경량의 스레드 안전(thread-safe) 데이터베이스 툴킷이자 ORM입니다.
데이터베이스 연결
require 'sequel'
# 인메모리 또는 파일 기반 SQLite
DB = Sequel.sqlite('database.db')
# PostgreSQL / MySQL
DB = Sequel.connect('postgres://user:password@localhost/mydb', max_connections: 10)
데이터셋 및 쿼리
Sequel 표현식은 체이닝이 가능하며 지연 평가(lazily evaluated)됩니다:
items = DB[:items] # 데이터셋을 나타냄
# Select, Where, Order
items.where(category: 'tools').order(:price).limit(10).all
# 복합 필터 조건
items.where{ price > 100 }
items.exclude(status: 'archived')
# 삽입 및 업데이트
items.insert(name: 'Hammer', price: 15.99)
items.where(id: 1).update(price: 19.99)
# 삭제
items.where(id: 1).delete
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]')
데이터베이스 트랜잭션
DB.transaction do
account_a.update(balance: account_a.balance - 100)
account_b.update(balance: account_b.balance + 100)
end