require "sqlite3"
module AR
class RecordNotFound < StandardError; end
class RecordInvalid < StandardError
def initialize(record)
@record = record
@message = "Validation failed: #{record.errors.full_messages.join(", ")}"
end
def record
@record
end
def message
@message
end
end
class Errors
def initialize
@messages = {}
end
def add(attr, message)
(@messages[attr.to_s] ||= []) << message
end
def [](attr)
@messages[attr.to_s] || []
end
def empty?
@messages.empty?
end
def any?
!@messages.empty?
end
def clear
@messages = {}
end
def count
total = 0
@messages.each { |_attr, msgs| total += msgs.length }
total
end
def full_messages
out = []
@messages.each do |attr, msgs|
human = attr.split("_").map { |p| p.capitalize }.join(" ")
msgs.each { |m| out << "#{human} #{m}" }
end
out
end
end
class Relation
include Enumerable
def initialize(model)
@model = model
@wheres = [] @order = nil
@limit = nil
@offset = nil
end
def spawn
r = Relation.new(@model)
r.set_state(@wheres.dup, @order, @limit, @offset)
r
end
def set_state(wheres, order, limit, offset)
@wheres = wheres
@order = order
@limit = limit
@offset = offset
self
end
def where(conds = nil)
return WhereChain.new(self) if conds.nil?
fragment, values = build_conditions(conds, false)
return spawn if fragment.empty? r = spawn
r.push_where(fragment, values)
r
end
def where_not(conds)
fragment, values = build_conditions(conds, true)
return spawn if fragment.empty?
r = spawn
r.push_where(fragment, values)
r
end
def push_where(fragment, values)
@wheres << [fragment, values]
self
end
def order(col)
r = spawn
r.set_order(col.to_s)
r
end
def set_order(order)
@order = order
self
end
def limit(n)
r = spawn
r.set_limit(n)
r
end
def set_limit(n)
@limit = n
self
end
def offset(m)
r = spawn
r.set_offset(m)
r
end
def set_offset(m)
@offset = m
self
end
def where_sql
return "" if @wheres.empty?
" WHERE " + @wheres.map { |w| w[0] }.join(" AND ")
end
def bind_values
values = []
@wheres.each { |w| values.concat(w[1]) }
values
end
def tail_sql
sql = where_sql
sql += " ORDER BY #{@order}" if @order
sql += " LIMIT #{@limit}" if @limit
sql += " OFFSET #{@offset}" if @offset
sql
end
def to_sql
"SELECT * FROM #{@model.table_name}#{tail_sql}"
end
def to_a
@model.columns
@model.connection.execute(to_sql, bind_values).map { |row| @model.new(row) }
end
def each(&block)
to_a.each(&block)
end
def pluck(col)
@model.columns
sql = "SELECT #{col} FROM #{@model.table_name}#{tail_sql}"
@model.connection.execute(sql, bind_values).map { |row| row[col.to_s] }
end
def count
@model.columns
sql = "SELECT COUNT(*) FROM #{@model.table_name}#{where_sql}"
@model.connection.get_first_value(sql, bind_values)
end
def exists?
count > 0
end
def first
rel = @order ? self : order("id")
rel.limit(1).to_a.first
end
def last
rel = @order ? order(reverse_order_sql(@order)) : order("id DESC")
rel.limit(1).to_a.first
end
def find_by(conds)
where(conds).first
end
def find_by!(conds)
record = find_by(conds)
raise RecordNotFound, "Couldn't find #{@model.model_name}" if record.nil?
record
end
def find_each(batch_size = 1000)
current = 0
loop do
batch = order("id").limit(batch_size).offset(current).to_a
break if batch.empty?
batch.each { |record| yield record }
break if batch.length < batch_size
current += batch_size
end
end
def destroy_all
to_a.each { |record| record.destroy }
end
def update_all(attrs)
@model.columns
affected = count
assignments = attrs.keys.map { |k| "#{k} = ?" }.join(", ")
sql = "UPDATE #{@model.table_name} SET #{assignments}#{where_sql}"
@model.connection.execute(sql, attrs.values + bind_values)
affected
end
private
def reverse_order_sql(order)
order.split(",").map do |term|
t = term.strip
low = t.downcase
if low.end_with?(" desc")
t[0...-5].strip + " ASC"
elsif low.end_with?(" asc")
t[0...-4].strip + " DESC"
else
t + " DESC"
end
end.join(", ")
end
def build_conditions(conds, negate)
parts = []
values = []
conds.each do |key, value|
if value.nil?
parts << (negate ? "#{key} IS NOT NULL" : "#{key} IS NULL")
else
parts << (negate ? "#{key} != ?" : "#{key} = ?")
values << value
end
end
[parts.join(" AND "), values]
end
end
class WhereChain
def initialize(relation)
@relation = relation
end
def not(conds)
@relation.where_not(conds)
end
end
class Base
@@connection = nil
@@registry = {}
def self.establish_connection(path)
@@connection = SQLite3::Database.new(path)
@@connection.results_as_hash = true
@@connection
end
def self.connection
raise "no database connection: call AR::Base.establish_connection(path) first" if @@connection.nil?
@@connection
end
def self.connected?
!@@connection.nil?
end
def self.model_name
self.name.split("::").last
end
def self.config
@@registry[model_name] ||= {}
end
def self.pluralize(word)
if word.end_with?("y")
word[0...-1] + "ies"
else
word + "s"
end
end
def self.singularize(word)
word = word.to_s
if word.end_with?("ies")
word[0...-3] + "y"
elsif word.end_with?("s")
word[0...-1]
else
word
end
end
def self.camelize(word)
word.to_s.split("_").map { |part| part.capitalize }.join
end
def self.default_table_name
pluralize(model_name.downcase)
end
def self.table_name(value = nil)
if value.nil?
config["table"] ||= default_table_name
else
config["table"] = value.to_s
end
end
def self.columns
unless config["columns"]
rows = connection.execute("PRAGMA table_info(#{table_name})")
cols = rows.map { |r| r["name"] }
raise "no such table: #{table_name}" if cols.empty?
config["columns"] = cols
define_column_accessors(cols)
end
config["columns"]
end
def self.has_column?(name)
columns.include?(name.to_s)
end
def self.define_column_accessors(cols)
cols.each do |col|
define_method(col) { @attributes[col] }
define_method("#{col}=") { |value| @attributes[col] = value }
end
end
def self.validators
config["validators"] ||= []
end
def self.validates_presence_of(*attrs)
attrs.each { |attr| validators << ["presence", attr.to_s, nil] }
end
def self.validates_uniqueness_of(*attrs)
attrs.each { |attr| validators << ["uniqueness", attr.to_s, nil] }
end
def self.callbacks(kind)
config["callbacks"] ||= {}
config["callbacks"][kind] ||= []
end
def self.before_save(method_name)
callbacks("before_save") << method_name
end
def self.after_save(method_name)
callbacks("after_save") << method_name
end
def self.before_create(method_name)
callbacks("before_create") << method_name
end
def self.after_create(method_name)
callbacks("after_create") << method_name
end
def self.before_destroy(method_name)
callbacks("before_destroy") << method_name
end
def self.belongs_to(name, options = {})
fk = (options[:foreign_key] || "#{name}_id").to_s
class_name = (options[:class_name] || camelize(name)).to_s
define_method(name) do
fk_value = @attributes[fk]
return nil if fk_value.nil?
Object.const_get(class_name).find_by(id: fk_value)
end
end
def self.has_many(name, options = {})
class_name = (options[:class_name] || camelize(singularize(name))).to_s
fk = (options[:foreign_key] || "#{model_name.downcase}_id").to_s
define_method(name) do
conds = {}
conds[fk] = id
Object.const_get(class_name).where(conds)
end
end
def self.all
Relation.new(self)
end
def self.where(conds = nil)
all.where(conds)
end
def self.order(col)
all.order(col)
end
def self.limit(n)
all.limit(n)
end
def self.offset(m)
all.offset(m)
end
def self.pluck(col)
all.pluck(col)
end
def self.count
all.count
end
def self.exists?
all.exists?
end
def self.first
all.first
end
def self.last
all.last
end
def self.find_by(conds)
all.find_by(conds)
end
def self.find_by!(conds)
all.find_by!(conds)
end
def self.find_each(batch_size = 1000, &block)
all.find_each(batch_size, &block)
end
def self.destroy_all
all.destroy_all
end
def self.update_all(attrs)
all.update_all(attrs)
end
def self.find(id)
columns
row = connection.get_first_row("SELECT * FROM #{table_name} WHERE id = ?", [id])
raise RecordNotFound, "Couldn't find #{model_name} with id=#{id}" if row.nil?
new(row)
end
def self.create(attrs = {})
record = new(attrs)
record.save
record
end
def self.create!(attrs = {})
record = new(attrs)
record.save!
record
end
def initialize(attrs = {})
@attributes = {}
self.class.columns.each { |c| @attributes[c] = nil }
@errors = Errors.new
@original = @attributes.dup
attrs.each { |k, v| @attributes[k.to_s] = v }
@original = @attributes.dup if persisted?
end
def id
@attributes["id"]
end
def persisted?
!@attributes["id"].nil?
end
def new_record?
!persisted?
end
def attributes
@attributes.dup
end
def [](col)
@attributes[col.to_s]
end
def []=(col, value)
@attributes[col.to_s] = value
end
def errors
@errors
end
def changed?
@attributes != @original
end
def changed
@attributes.keys.select { |k| @attributes[k] != @original[k] }
end
def valid?
@errors = Errors.new
self.class.validators.each do |validator|
kind = validator[0]
attr = validator[1]
run_validator(kind, attr)
end
@errors.empty?
end
def invalid?
!valid?
end
def save
return false unless valid?
run_callbacks("before_save")
stamp = current_timestamp
if persisted?
set_timestamp("updated_at", stamp)
persist_update
else
set_timestamp("created_at", stamp)
set_timestamp("updated_at", stamp)
run_callbacks("before_create")
persist_insert
run_callbacks("after_create")
end
run_callbacks("after_save")
@original = @attributes.dup
true
end
def save!
raise RecordInvalid.new(self) unless save
true
end
def update(attrs)
attrs.each { |k, v| @attributes[k.to_s] = v }
save
end
def update!(attrs)
attrs.each { |k, v| @attributes[k.to_s] = v }
save!
end
def destroy
return self unless persisted?
run_callbacks("before_destroy")
sql = "DELETE FROM #{self.class.table_name} WHERE id = ?"
self.class.connection.execute(sql, [@attributes["id"]])
@attributes["id"] = nil
self
end
def reload
row = self.class.connection.get_first_row(
"SELECT * FROM #{self.class.table_name} WHERE id = ?", [id]
)
raise RecordNotFound, "Couldn't find #{self.class.model_name} with id=#{id}" if row.nil?
@attributes = {}
self.class.columns.each { |c| @attributes[c] = nil }
row.each { |k, v| @attributes[k.to_s] = v }
@original = @attributes.dup
self
end
private
def run_validator(kind, attr)
value = @attributes[attr]
if kind == "presence"
blank = value.nil? || (value.is_a?(String) && value.strip.empty?)
@errors.add(attr, "can't be blank") if blank
elsif kind == "uniqueness"
conds = {}
conds[attr] = value
others = self.class.where(conds).to_a
taken = others.reject { |r| persisted? && r.id == id }
@errors.add(attr, "has already been taken") unless taken.empty?
end
end
def run_callbacks(kind)
self.class.callbacks(kind).each { |method_name| send(method_name) }
end
def current_timestamp
Time.now.to_s
end
def set_timestamp(col, stamp)
@attributes[col] = stamp if self.class.has_column?(col)
end
def writable_columns
self.class.columns.reject { |c| c == "id" }
end
def persist_insert
cols = writable_columns
placeholders = cols.map { "?" }.join(", ")
values = cols.map { |c| @attributes[c] }
sql = "INSERT INTO #{self.class.table_name} (#{cols.join(", ")}) VALUES (#{placeholders})"
self.class.connection.execute(sql, values)
@attributes["id"] = self.class.connection.last_insert_row_id
end
def persist_update
cols = writable_columns
assignments = cols.map { |c| "#{c} = ?" }.join(", ")
values = cols.map { |c| @attributes[c] }
sql = "UPDATE #{self.class.table_name} SET #{assignments} WHERE id = ?"
self.class.connection.execute(sql, values + [@attributes["id"]])
end
end
class TableDefinition
SQL_TYPES = {
"string" => "TEXT",
"text" => "TEXT",
"integer" => "INTEGER",
"float" => "REAL",
"boolean" => "INTEGER",
"datetime" => "TEXT"
}
def initialize(name)
@name = name.to_s
@columns = ["id INTEGER PRIMARY KEY"]
end
SQL_TYPES.each do |ruby_type, sql_type|
define_method(ruby_type) do |col_name|
@columns << "#{col_name} #{sql_type}"
end
end
def timestamps
@columns << "created_at TEXT"
@columns << "updated_at TEXT"
end
def to_sql
"CREATE TABLE #{@name} (#{@columns.join(", ")})"
end
end
class SchemaDefiner
def create_table(name, options = {})
table = TableDefinition.new(name)
table.timestamps if options[:timestamps]
yield table
AR::Base.connection.execute("DROP TABLE IF EXISTS #{name}")
AR::Base.connection.execute(table.to_sql)
end
end
module Schema
def self.define
yield SchemaDefiner.new
end
end
end