Sequel คืออะไร? — Gem เข้าถึง Database ไม่ต้อง Rails
เชื่อม Database ได้หลายวิธี — หลัก 2 แบบ:
- ส่ง Raw SQL Commands
- 用 ORM
ตัวอย่าง Raw SQL + MySQL:
require 'mysql2'
client = Mysql2::Client.new(host: "localhost")
results = client.query("SELECT * FROM users WHERE age > 21")
ผลลัพธ์? Array of Hashes — ถ้าอยากทำงานกับ Data แบบ OO ต้องทำให้เป็น Objects — ส่วนใหญ่ ORM ทำนี่
ORM คืออะไร? Object-Relational-Mapping — Sequel (อ่านว่า "ซีเควล" ตามเสียง SQL) คือ ORM ตัวหนึ่ง
มาค้นหาวิธีใช้กัน!
Sequel Example: เชื่อมต่อ Database
Step แรก ใช้ Sequel = Connect Database
ตัวอย่าง:
require 'sequel'
DB = Sequel.sqlite('/tmp/testing.db')
สร้าง Sequel::Database Object assign ให้ DB — 用 SQLite3
แต用 Others ได้:
Sequel.postgresSequel.mysql2Sequel.oracle
ต่อไป? สร้าง Table เก็บ Data
สร้างแบบนี้:
unless DB.table_exists?(:fruits)
DB.create_table :fruits do
primary_key :id
column :name, String
column :amount, Integer
end
end
มี Migration System ใช้ได้ — แต Optional — พร้อม Add Data และ Query!
วิธีใช้ Sequel Datasets
ต้องมี Dataset Object 互動กับ Table เฉพาะ
ได้แบบนี้:
table = DB[:fruits] # Sequel::SQLite::Dataset
เพิ่ม Records ด้วย insert:
table.insert(name: "Orange", amount: 10) table.insert(name: "Apple", amount: 2) table.insert(name: "Banana", amount: 7)
นับจำนวน: table.count # 3
ดูทั้งหมด:
table.all
# [
# { id: 1, name: "Orange", amount: 10 },
# { id: 2, name: "Apple", amount: 2 },
# { id: 3, name: "Banana", amount: 7 }
# ]
เหมือน Array of Hashes — ใช่แล้ว! Sequel Query ได้โดยไม่ต้อง Model — แต用 Models ได้...
วิธีใช้ Models ใน Sequel
Sequel Model คล้าย ActiveRecord มาก
ตัวอย่าง:
class Fruit < Sequel::Model end
Models พرفتเหมือน Dataset แต Wrap Results ใน Model Class
ตัวอย่างเพิ่ม:
Fruit.map(:name) # ["Orange", "Apple", "Banana"] Fruit.where(name: "Apple").or(amount: 10).map(:name) # ["Orange", "Apple"] Fruit.first[:amount] # 10
Very nice!
Sequel vs ActiveRecord
ตอนรู้ Sequel เยี่ยมแล้ว — เปรียบเทียบ ActiveRecord ยังไง?
ActiveRecord = Default ORM ของ Rails — Rails Really Likes Conventions
คิดว่าไม่ Worth Replace ActiveRecord ด้วย Sequel ใน Rails App
แต่... Framework อื่น เช่น Sinatra — Sequel = Great Choice!
Summary (สรุป)
คุณเรียนรู้ Database ใน Ruby ด้วย ORM คือ Sequel Gem
ตอนนี้ถึงคุณ ลองเล่นดู — ขอบคุณที่อ่านครับ!