Class: DataMapper::Adapters::DataObjectAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- DataMapper::Adapters::DataObjectAdapter
- Includes:
- Coersion, Sql, Quoting
- Defined in:
- lib/data_mapper/adapters/data_object_adapter.rb
Overview
You must inherit from the DoAdapter, and implement the required methods to adapt a database library for use with the DataMapper.
NOTE: By inheriting from DoAdapter, you get a copy of all the standard sub-modules (Quoting, Coersion and Queries) in your own Adapter. You can extend and overwrite these copies without affecting the originals.
Direct Known Subclasses
Constant Summary collapse
- FIND_OPTIONS =
[ :select, :offset, :limit, :class, :include, :shallow_include, :reload, :conditions, :order, :intercept_load ]
- TABLE_QUOTING_CHARACTER =
'`'.freeze
- COLUMN_QUOTING_CHARACTER =
'`'.freeze
- SYNTAX =
{ :now => 'NOW()'.freeze }
- MAGIC_PROPERTIES =
{ :updated_at => lambda { self.updated_at = Time::now }, :updated_on => lambda { self.updated_on = Date::today }, :created_at => lambda { self.created_at ||= Time::now }, :created_on => lambda { self.created_on ||= Date::today } }
- TYPES =
{ :integer => 'int'.freeze, :string => 'varchar'.freeze, :text => 'text'.freeze, :class => 'varchar'.freeze, :decimal => 'decimal'.freeze, :float => 'float'.freeze, :datetime => 'datetime'.freeze, :date => 'date'.freeze, :boolean => 'boolean'.freeze, :object => 'text'.freeze }
Class Method Summary collapse
-
.inherited(base) ⇒ Object
This callback copies and sub-classes modules and classes in the DoAdapter to the inherited class so you don’t have to copy and paste large blocks of code from the DoAdapter.
Instance Method Summary collapse
- #activate! ⇒ Object
- #activated? ⇒ Boolean
- #batch_insertable? ⇒ Boolean
- #callback(instance, callback_name) ⇒ Object
- #column_exists_for_table?(table_name, column_name) ⇒ Boolean
-
#connection ⇒ Object
Yields an available connection.
- #create(database_context, instance) ⇒ Object
- #create_connection ⇒ Object
- #delete(database_context, instance) ⇒ Object
- #empty_insert_sql ⇒ Object
- #execute(*args) ⇒ Object
-
#flush_connections! ⇒ Object
Close any open connections.
- #get(database_context, klass, keys) ⇒ Object
- #handle_error(error) ⇒ Object
-
#initialize(configuration) ⇒ DataObjectAdapter
constructor
A new instance of DataObjectAdapter.
- #load(database_context, klass, options) ⇒ Object
- #query(*args) ⇒ Object
- #save(database_context, instance, validate = true, cleared = Set.new) ⇒ Object
- #save_without_validation(database_context, instance, cleared = Set.new) ⇒ Object
- #schema ⇒ Object
- #table(instance) ⇒ Object
- #transaction(&block) ⇒ Object
- #update(database_context, instance) ⇒ Object
- #update_magic_properties(database_context, instance) ⇒ Object
Methods inherited from AbstractAdapter
Constructor Details
#initialize(configuration) ⇒ DataObjectAdapter
Returns a new instance of DataObjectAdapter.
55 56 57 58 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 55 def initialize(configuration) super @connection_pool = Support::ConnectionPool.new { create_connection } end |
Class Method Details
.inherited(base) ⇒ Object
This callback copies and sub-classes modules and classes in the DoAdapter to the inherited class so you don’t have to copy and paste large blocks of code from the DoAdapter.
Basically, when inheriting from the DoAdapter, you aren’t just inheriting a single class, you’re inheriting a whole graph of Types. For convenience.
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 439 def self.inherited(base) commands = base.const_set('Commands', Module.new) Sql::Commands.constants.each do |name| commands.const_set(name, Class.new(Sql::Commands.const_get(name))) end mappings = base.const_set('Mappings', Module.new) Sql::Mappings.constants.each do |name| mappings.const_set(name, Class.new(Sql::Mappings.const_get(name))) end base.const_set('TYPES', TYPES.dup) base.const_set('FIND_OPTIONS', FIND_OPTIONS.dup) base.const_set('SYNTAX', SYNTAX.dup) super end |
Instance Method Details
#activate! ⇒ Object
64 65 66 67 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 64 def activate! @activated = true schema.activate! end |
#activated? ⇒ Boolean
60 61 62 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 60 def activated? @activated end |
#batch_insertable? ⇒ Boolean
73 74 75 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 73 def batch_insertable? true end |
#callback(instance, callback_name) ⇒ Object
427 428 429 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 427 def callback(instance, callback_name) instance.class.callbacks.execute(callback_name, instance) end |
#column_exists_for_table?(table_name, column_name) ⇒ Boolean
166 167 168 169 170 171 172 173 174 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 166 def column_exists_for_table?(table_name, column_name) connection do |db| table = self.table(table_name) command = db.create_command(table.to_column_exists_sql) command.execute_reader(table.name, column_name, table.schema.name) do |reader| reader.any? { reader.item(1) == column_name.to_s } end end end |
#connection ⇒ Object
Yields an available connection. Flushes the connection-pool and reconnects if the connection returns an error.
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 79 def connection begin # Yield the appropriate connection @connection_pool.hold { |active_connection| yield(active_connection) } rescue => execution_error # Log error on failure logger.error { execution_error } # Close all open connections, assuming that if one # had an error, it's likely due to a lost connection, # in which case all connections are likely broken. flush_connections! raise execution_error end end |
#create(database_context, instance) ⇒ Object
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 285 def create(database_context, instance) callback(instance, :before_create) instance = update_magic_properties(database_context, instance) table = self.table(instance) attributes = instance.dirty_attributes if table.multi_class? instance.instance_variable_set( table[:type].instance_variable_name, attributes[:type] = instance.class.name ) end keys = [] values = [] attributes.each_pair do |key, value| raise ArgumentError.new("#{value.inspect} is not a valid value for #{key.inspect}") if value.is_a?(Array) keys << table[key].to_sql values << value end sql = if keys.size > 0 "INSERT INTO #{table.to_sql} (#{keys.join(', ')}) VALUES ?" else "INSERT INTO #{table.to_sql} #{self.empty_insert_sql}" end result = connection do |db| db.create_command(sql).execute_non_query(values) end if result.to_i > 0 instance.instance_variable_set(:@new_record, false) instance.key = result.last_insert_row if table.key.serial? && !attributes.include?(table.key.name) database_context.identity_map.set(instance) callback(instance, :after_create) return true else return false end end |
#create_connection ⇒ Object
69 70 71 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 69 def create_connection raise NotImplementedError.new end |
#delete(database_context, instance) ⇒ Object
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 176 def delete(database_context, instance) table = self.table(instance) if instance.is_a?(Class) table.delete_all! else callback(instance, :before_destroy) table.associations.each do |association| instance.send(association.name).deactivate unless association.is_a?(::DataMapper::Associations::BelongsToAssociation) end if table.paranoid? instance.instance_variable_set(table.paranoid_column.instance_variable_name, Time::now) instance.save else if connection do |db| command = db.create_command("DELETE FROM #{table.to_sql} WHERE #{table.key.to_sql} = ?") command.execute_non_query(instance.key).to_i > 0 end # connection do...end # if continued below: instance.instance_variable_set(:@new_record, true) instance.database_context = database_context instance.original_values.clear database_context.identity_map.delete(instance) callback(instance, :after_destroy) end end end end |
#empty_insert_sql ⇒ Object
281 282 283 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 281 def empty_insert_sql "DEFAULT VALUES" end |
#execute(*args) ⇒ Object
147 148 149 150 151 152 153 154 155 156 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 147 def execute(*args) db = create_connection command = db.create_command(args.shift) return command.execute_non_query(*args) rescue => e logger.error { e } raise e ensure db.close end |
#flush_connections! ⇒ Object
Close any open connections.
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 97 def flush_connections! @connection_pool.available_connections.each do |active_connection| begin active_connection.close rescue => close_connection_error # An error on closing the connection is almost expected # if the socket is broken. logger.warn { close_connection_error } end end # Reopen fresh connections. @connection_pool.instance_variable_set('@created_count', 0) @connection_pool.available_connections.clear end |
#get(database_context, klass, keys) ⇒ Object
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 348 def get(database_context, klass, keys) table = self.table(klass) instance_id = table.key.type_cast_value(keys.first) instance = database_context.identity_map.get(klass, instance_id) return instance if instance column_indexes = {} select_columns = [] table.columns.each_with_index do |column, i| column_indexes[column] = i select_columns << column.to_sql end sql = "SELECT #{select_columns.join(', ')} FROM #{table.to_sql} WHERE #{table.keys.map { |key| "#{key.to_sql} = ?" }.join(' AND ')}" connection do |db| reader = nil begin reader = db.create_command(sql).execute_reader(*keys) if reader.has_rows? instance_type = klass if table.multi_class? && table.type_column value = reader.item(column_indexes[table.type_column]) instance_type = table.type_column.type_cast_value(value) unless value.blank? end if instance.nil? instance = instance_type.allocate() instance.instance_variable_set(:@__key, instance_id) instance.instance_variable_set(:@new_record, false) database_context.identity_map.set(instance) elsif instance.new_record? instance.instance_variable_set(:@__key, instance_id) instance.instance_variable_set(:@new_record, false) database_context.identity_map.set(instance) end instance.database_context = database_context instance_type.callbacks.execute(:before_materialize, instance) originals = instance.original_values column_indexes.each_pair do |column, i| value = column.type_cast_value(reader.item(i)) instance.instance_variable_set(column.instance_variable_name, value) case value when String, Date, Time then originals[column.name] = value.dup else originals[column.name] = value end end instance.loaded_set = [instance] instance_type.callbacks.execute(:after_materialize, instance) end # if reader.has_rows? ensure reader.close if reader && reader.open? end end # connection return instance end |
#handle_error(error) ⇒ Object
158 159 160 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 158 def handle_error(error) raise error end |
#load(database_context, klass, options) ⇒ Object
344 345 346 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 344 def load(database_context, klass, ) self.class::Commands::LoadCommand.new(self, database_context, klass, ).call end |
#query(*args) ⇒ Object
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 117 def query(*args) db = create_connection command = db.create_command(args.shift) reader = command.execute_reader(*args) fields = reader.fields.map { |field| Inflector.underscore(field).to_sym } results = [] if fields.size > 1 struct = Struct.new(*fields) reader.each do results << struct.new(*reader.current_row) end else reader.each do results << reader.item(0) end end return results rescue => e logger.error { e } raise e ensure reader.close if reader db.close end |
#save(database_context, instance, validate = true, cleared = Set.new) ⇒ Object
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 206 def save(database_context, instance, validate = true, cleared = Set.new) case instance when Class then table(instance).create! table(instance).activate_associations! when Mappings::Table then instance.create! when DataMapper::Persistence then event = instance.new_record? ? :create : :update return false if (validate && !instance.validate_recursively(event, Set.new)) || cleared.include?(instance) cleared << instance callback(instance, :before_save) return true unless instance.new_record? || instance.dirty? result = send(event, database_context, instance) instance.database_context = database_context instance.attributes.each_pair do |name, value| instance.original_values[name] = value end instance.loaded_associations.each do |association| association.save_without_validation(database_context, cleared) if association.dirty? end callback(instance, :after_save) result end rescue => error logger.error(error) raise error end |
#save_without_validation(database_context, instance, cleared = Set.new) ⇒ Object
241 242 243 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 241 def save_without_validation(database_context, instance, cleared = Set.new) save(database_context, instance, false, cleared) end |
#schema ⇒ Object
162 163 164 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 162 def schema @schema || ( @schema = self.class::Mappings::Schema.new(self, @configuration.database) ) end |
#table(instance) ⇒ Object
418 419 420 421 422 423 424 425 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 418 def table(instance) case instance when DataMapper::Adapters::Sql::Mappings::Table then instance when DataMapper::Persistence then schema[instance.class] when Class, String then schema[instance] else raise "Don't know how to map #{instance.inspect} to a table." end end |
#transaction(&block) ⇒ Object
113 114 115 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 113 def transaction(&block) raise NotImplementedError.new end |
#update(database_context, instance) ⇒ Object
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 245 def update(database_context, instance) callback(instance, :before_update) instance = update_magic_properties(database_context, instance) table = self.table(instance) attributes = instance.dirty_attributes parameters = [] unless attributes.empty? sql = "UPDATE " << table.to_sql << " SET " sql << attributes.map do |key, value| parameters << value "#{table[key].to_sql} = ?" end.join(', ') sql << " WHERE #{table.key.to_sql} = ?" parameters << instance.key result = connection do |db| db.create_command(sql).execute_non_query(*parameters) end # BUG: do_mysql returns inaccurate affected row counts for UPDATE statements. if true || result.to_i > 0 callback(instance, :after_update) return true else return false end else true end end |
#update_magic_properties(database_context, instance) ⇒ Object
337 338 339 340 341 342 |
# File 'lib/data_mapper/adapters/data_object_adapter.rb', line 337 def update_magic_properties(database_context, instance) instance.class.properties.find_all { |property| MAGIC_PROPERTIES.has_key?(property.name) }.each do |property| instance.instance_eval(&MAGIC_PROPERTIES[property.name]) end instance end |