# * George Moschovitis # (c) 2004-2005 Navel, all rights reserved. # $Id$ module Og module Enchant # Enchant a managed class. Add useful DB related methods # to the class and its instances. def enchant(klass) # Generate standard methods. klass.module_eval %{ def self.create(*params, &block) obj = #{klass}.new(*params, &block) obj.save! end def self.save(obj) @@og_db << obj end def self.load(oid_or_name) @@og_db.load(oid_or_name, #{klass}) end def self.get(oid_or_name) @@og_db.load(oid_or_name, #{klass}) end def self.[](oid_or_name) @@og_db.load(oid_or_name, #{klass}) end def self.load_all(extra_sql = nil) @@og_db.load_all(#{klass}, extra_sql) end def self.all(extra_sql = nil) @@og_db.load_all(#{klass}, extra_sql) end def self.update_all(set_sql, extra_sql = nil) @@og_db.exec("UPDATE #{klass::DBTABLE} SET \#\{set_sql\} \#\{extra_sql\}") end def self.update(set_sql, extra_sql = nil) @@og_db.exec("UPDATE #{klass::DBTABLE} SET \#\{set_sql\} \#\{extra_sql\}") end def self.count(sql = "SELECT COUNT(*) FROM #{klass::DBTABLE}") @@og_db.count(sql, #{klass}) end def self.select(sql) @@og_db.select(sql, #{klass}) end def self.find(sql) @@og_db.select(sql, #{klass}) end def self.select_one(sql) @@og_db.select_one(sql, #{klass}) end def self.find_one(sql) @@og_db.select_one(sql, #{klass}) end def self.one(sql) @@og_db.select_one(sql, #{klass}) end def self.delete(obj_or_oid) @@og_db.delete(obj_or_oid, #{klass}) end def self.transaction(&block) @@og_db.transaction(&block) end def self.properties_and_relations @@__meta[:props_and_relations] end def self.each(&block) all.each(&block) end include Enumerable def save @@og_db << self return self end alias_method :save!, :save def reload raise 'Cannot reload unmanaged object' unless @oid res = @@og_db.query "SELECT * FROM #{klass::DBTABLE} WHERE oid=\#\{@oid\}" og_read(@@og_db.get_row(res)) end alias_method :reload!, :reload def update_properties(updatesql) @@og_db.pupdate(updatesql, self.oid, #{klass}) end alias_method :pupdate, :update_properties alias_method :update_property, :update_properties def set_property(prop, value) @@og_db.pupdate("\#\{prop\}=\#\{value\}", self.oid, #{klass}) end def delete! @@og_db.delete(self, #{klass}) end } # Generate finder methods. code = '' for p in klass.__props code << %{ def self.find_by_#{p.name}(val, operator = '=', extra_sql = nil) } val = klass.og_db.adapter.typecast[p.klass].gsub(/\:s\:/, 'val') if p.meta[:unique] code << %{@@og_db.select_one("#{p.name}\#\{operator\}#{val} \#\{extra_sql\}", #{klass})} else code << %{@@og_db.select("#{p.name}\#\{operator\}#{val} \#\{extra_sql\}", #{klass})} end code << %{ end; } end klass.module_eval(code) end end end