lib/mosql/sql.rb in mosql-0.3.2 vs lib/mosql/sql.rb in mosql-0.4.0

- old
+ new

@@ -37,20 +37,28 @@ def upsert_ns(ns, obj) h = transform_one_ns(ns, obj) upsert!(table_for_ns(ns), @schema.primary_sql_key_for_ns(ns), h) end - # obj must contain an _id field. All other fields will be ignored. def delete_ns(ns, obj) - primary_sql_key = @schema.primary_sql_key_for_ns(ns) + primary_sql_keys = @schema.primary_sql_key_for_ns(ns) h = transform_one_ns(ns, obj) - raise "No #{primary_sql_key} found in transform of #{obj.inspect}" if h[primary_sql_key].nil? - table_for_ns(ns).where(primary_sql_key.to_sym => h[primary_sql_key]).delete + query = {} + primary_sql_keys.each do |key| + raise "No #{primary_sql_keys} found in transform of #{obj.inspect}" if h[key].nil? + query[key.to_sym] = h[key] + end + + table_for_ns(ns).where(query).delete end - def upsert!(table, table_primary_key, item) - rows = table.where(table_primary_key.to_sym => item[table_primary_key]).update(item) + def upsert!(table, table_primary_keys, item) + query = {} + table_primary_keys.each do |key| + query[key.to_sym] = item[key] + end + rows = table.where(query).update(item) if rows == 0 begin table.insert(item) rescue Sequel::DatabaseError => e raise e unless self.class.duplicate_key_error?(e) @@ -66,9 +74,13 @@ # for the list of error codes. # # No thanks to Sequel and pg for making it easy to figure out # how to get at this error code.... e.wrapped_exception.result.error_field(PG::Result::PG_DIAG_SQLSTATE) == "23505" + end + + def self.duplicate_column_error?(e) + e.wrapped_exception.result.error_field(PG::Result::PG_DIAG_SQLSTATE) == "42701" end end end