Class: ActiveRecord::ConnectionAdapters::SalesforceAdapter

Inherits:
AbstractAdapter
  • Object
show all
Includes:
StringHelper
Defined in:
lib/active_record/connection_adapters/activesalesforce_adapter.rb

Constant Summary collapse

MAX_BOXCAR_SIZE =
200

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from StringHelper

#column_nameize

Constructor Details

#initialize(connection, logger, config) ⇒ SalesforceAdapter

Returns a new instance of SalesforceAdapter.



126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 126

def initialize(connection, logger, config)
  super(connection, logger)
  
  @connection_options = nil
  @config = config
  
  @entity_def_map = {}
  @keyprefix_to_entity_def_map = {}
  
  @command_boxcar = []
  @class_to_entity_map = {}
end

Instance Attribute Details

#batch_sizeObject

Returns the value of attribute batch_size.



123
124
125
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 123

def batch_size
  @batch_size
end

#class_to_entity_mapObject (readonly)

Returns the value of attribute class_to_entity_map.



124
125
126
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 124

def class_to_entity_map
  @class_to_entity_map
end

#configObject (readonly)

Returns the value of attribute config.



124
125
126
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 124

def config
  @config
end

#entity_def_mapObject (readonly)

Returns the value of attribute entity_def_map.



124
125
126
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 124

def entity_def_map
  @entity_def_map
end

#keyprefix_to_entity_def_mapObject (readonly)

Returns the value of attribute keyprefix_to_entity_def_map.



124
125
126
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 124

def keyprefix_to_entity_def_map
  @keyprefix_to_entity_def_map
end

Instance Method Details

#active?Boolean

CONNECTION MANAGEMENT ====================================

Returns:

  • (Boolean)


177
178
179
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 177

def active?
  true
end

#adapter_nameObject

:nodoc:



151
152
153
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 151

def adapter_name #:nodoc:
  'ActiveSalesforce'
end

#add_rows(entity_def, query_result, result, limit) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 341

def add_rows(entity_def, query_result, result, limit)
  records = query_result[:records]
  records = [ records ] unless records.is_a?(Array)

  records.each do |record|
    row = {}
    
    record.each do |name, value| 
      if name != :type
        # Ids may be returned in an array with 2 duplicate entries...
        value = value[0] if name == :Id && value.is_a?(Array)
        
        column = entity_def.api_name_to_column[name.to_s]
        attribute_name = column.name
        
        if column.type == :boolean
          row[attribute_name] = (value.casecmp("true") == 0)
        else
          row[attribute_name] = value
        end
      end
    end  
    
    result << row
    
    break if result.size >= limit and limit != 0
  end
end

#begin_db_transactionObject

Begins the transaction (and turns off auto-committing).



190
191
192
193
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 190

def begin_db_transaction()    
  log('Opening boxcar', 'begin_db_transaction()')
  @command_boxcar = []
end

#bindingObject



146
147
148
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 146

def binding
  @connection
end

#check_result(result) ⇒ Object



586
587
588
589
590
591
592
593
594
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 586

def check_result(result)
  result = [ result ] unless result.is_a?(Array)
  
  result.each do |r|
    raise ActiveSalesforce::ASFError.new(@logger, r[:errors], r[:errors][:message]) unless r[:success] == "true"
  end
  
  result
end

#class_from_entity_name(entity_name) ⇒ Object



725
726
727
728
729
730
731
732
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 725

def class_from_entity_name(entity_name)
  entity_klass = @class_to_entity_map[entity_name.upcase]
  debug("Found matching class '#{entity_klass}' for entity '#{entity_name}'") if entity_klass
  
  entity_klass = entity_name.constantize unless entity_klass
  
  entity_klass
end

#column_names(table_name) ⇒ Object



755
756
757
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 755

def column_names(table_name)
  columns(table_name).map { |column| column.name }
end

#columns(table_name, name = nil) ⇒ Object



719
720
721
722
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 719

def columns(table_name, name = nil)
  table_name, columns, entity_def = lookup(table_name)
  entity_def.columns
end

#commit_db_transactionObject

Commits the transaction (and turns on auto-committing).



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 234

def commit_db_transaction()   
  log("Committing boxcar with #{@command_boxcar.length} commands", 'commit_db_transaction()')
  
  previous_command = nil
  commands = []
  
  @command_boxcar.each do |command|
    if commands.length >= MAX_BOXCAR_SIZE or (previous_command and (command.verb != previous_command.verb))
      send_commands(commands)
      
      commands = []
      previous_command = nil
    else
      commands << command
   previous_command = command
    end
  end
  
  # Finish off the partial boxcar
  send_commands(commands) unless commands.empty?
  
end

#configure_active_record(entity_def) ⇒ Object



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 656

def configure_active_record(entity_def)
  entity_name = entity_def.name
  klass = class_from_entity_name(entity_name)

  class << klass
    def asf_augmented?
      true
    end
  end
  
  # Add support for SID-based authentication
  ActiveSalesforce::SessionIDAuthenticationFilter.register(klass)
  
  klass.set_inheritance_column nil unless entity_def.custom?
  klass.set_primary_key "id" 
  
  # Create relationships for any reference field
  entity_def.relationships.each do |relationship|
    referenceName = relationship.name
    unless self.respond_to? referenceName.to_sym or relationship.reference_to == "Profile" 
      reference_to = relationship.reference_to
      one_to_many = relationship.one_to_many
      foreign_key = relationship.foreign_key
      
      # DCHASMAN TODO Figure out how to handle polymorphic refs (e.g. Note.parent can refer to 
      # Account, Contact, Opportunity, Contract, Asset, Product2, <CustomObject1> ... <CustomObject(n)>
      if reference_to.is_a? Array
        debug("   Skipping unsupported polymophic one-to-#{one_to_many ? 'many' : 'one' } relationship '#{referenceName}' from #{klass} to [#{relationship.reference_to.join(', ')}] using #{foreign_key}")
        next 
      end
      
      # Handle references to custom objects
      reference_to = reference_to.chomp("__c").capitalize if reference_to.match(/__c$/)
      
      begin
        referenced_klass = class_from_entity_name(reference_to)
      rescue NameError => e
          # Automatically create a least a stub for the referenced entity
          debug("   Creating ActiveRecord stub for the referenced entity '#{reference_to}'")
          
          referenced_klass = klass.class_eval("::#{reference_to} = Class.new(ActiveRecord::Base)")
          
          # Automatically inherit the connection from the referencee
          def referenced_klass.connection
            klass.connection
          end
      end
      
      if referenced_klass
        if one_to_many
          klass.has_many referenceName.to_sym, :class_name => referenced_klass.name, :foreign_key => foreign_key, :dependent => :nullify
        else
          klass.belongs_to referenceName.to_sym, :class_name => referenced_klass.name, :foreign_key => foreign_key
        end
        
        debug("   Created one-to-#{one_to_many ? 'many' : 'one' } relationship '#{referenceName}' from #{klass} to #{referenced_klass} using #{foreign_key}")
      end            
    end
  end
  
end

#create_sobject(entity_name, id, fields, null_fields = []) ⇒ Object



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 735

def create_sobject(entity_name, id, fields, null_fields = [])
  sobj = []
  
  sobj << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << entity_name
  sobj << 'Id { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << id if id    
  
  # add any changed fields
  fields.each do | name, value |
    sobj << name.to_sym << value if value
  end
  
  # add null fields
  null_fields.each do | name, value |
			sobj << 'fieldsToNull { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << name
		end
  
  [ :sObjects, sobj ]
end

#debug(msg) ⇒ Object



773
774
775
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 773

def debug(msg)
  @logger.debug(msg) if @logger
end

#delete(sql, name = nil) ⇒ Object



430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 430

def delete(sql, name = nil) 
  log(sql, name) {
    # Extract the id
    match = sql.match(/WHERE\s+id\s*=\s*'(\w+)'/mi)
    
    if match 
      ids = [ match[1] ]
    else
      # Check for the form (id IN ('x', 'y'))
      match = sql.match(/WHERE\s+\(\s*id\s+IN\s*\((.+)\)\)/mi)[1]
      ids = match.scan(/\w+/)
    end
    
    ids_element = []        
    ids.each { |id| ids_element << :ids << id }
    
    @command_boxcar << ActiveSalesforce::BoxcarCommand::Delete.new(self, ids_element)
  }
end

#extract_sql_modifier(soql, modifier) ⇒ Object



565
566
567
568
569
570
571
572
573
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 565

def extract_sql_modifier(soql, modifier)
    value = soql.match(/\s+#{modifier}\s+(\d+)/mi)
    if value            
      value = value[1].to_i
      soql.sub!(/\s+#{modifier}\s+\d+/mi, "")
    end
    
    value
end

#get_deleted(object_type, start_date, end_date, name = nil) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 466

def get_deleted(object_type, start_date, end_date, name = nil)
  msg = "get_deleted(#{object_type}, #{start_date}, #{end_date})"
  log(msg, name) {
    get_deleted_element = []
    get_deleted_element << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << object_type
    get_deleted_element << :startDate << start_date
    get_deleted_element << :endDate << end_date
    
    result = get_result(@connection.getDeleted(get_deleted_element), :getDeleted)
    
    ids = []
    result[:deletedRecords].each do |v| 
      ids << v[:id]
    end
    
    ids
  }      
end

#get_entity_def(entity_name) ⇒ Object



597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 597

def get_entity_def(entity_name)
  cached_entity_def = @entity_def_map[entity_name]
  
  if cached_entity_def
    # Check for the loss of asf AR setup 
    entity_klass = class_from_entity_name(entity_name)
    
    configure_active_record(cached_entity_def) unless entity_klass.respond_to?(:asf_augmented?)
    
    return cached_entity_def 
  end
  
  cached_columns = []
  cached_relationships = []
  
  begin
     = get_result(@connection.describeSObject(:sObjectType => entity_name), :describeSObject)
    custom = false
  rescue ActiveSalesforce::ASFError
    # Fallback and see if we can find a custom object with this name
    debug("   Unable to find medata for '#{entity_name}', falling back to custom object name #{entity_name + "__c"}")
    
     = get_result(@connection.describeSObject(:sObjectType => entity_name + "__c"), :describeSObject)
    custom = true
  end
  
  [:fields].each do |field| 
    column = SalesforceColumn.new(field) 
    cached_columns << column
    
    cached_relationships << SalesforceRelationship.new(field, column) if field[:type] =~ /reference/mi
  end
  
  relationships = [:childRelationships]
  if relationships
    relationships = [ relationships ] unless relationships.is_a? Array
    
    relationships.each do |relationship|  
      if relationship[:cascadeDelete] == "true"
        r = SalesforceRelationship.new(relationship)
        cached_relationships << r
      end
    end
  end
  
  key_prefix = [:keyPrefix]
  
  entity_def = ActiveSalesforce::EntityDefinition.new(self, entity_name, entity_klass,
                                                      cached_columns, cached_relationships, custom, key_prefix)
  
  @entity_def_map[entity_name] = entity_def
  @keyprefix_to_entity_def_map[key_prefix] = entity_def
  
  configure_active_record(entity_def)
  
  entity_def
end

#get_fields(columns, names, values, access_check) ⇒ Object



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 521

def get_fields(columns, names, values, access_check) 
  fields = {}
  names.each_with_index do | name, n | 
    value = values[n]
    
    if value
      column = columns[name]
      
      raise ActiveSalesforce::ASFError.new(@logger, "Column not found for #{name}!") unless column
      
      value.gsub!(/''/, "'") if value.is_a? String
      
      include_field = ((not value.empty?) and column.send(access_check))
      
      if (include_field)           
        case column.type
          when :date 
            value = Time.parse(value + "Z").utc.strftime("%Y-%m-%d")
          when :datetime
            value = Time.parse(value + "Z").utc.strftime("%Y-%m-%dT%H:%M:%SZ")
        end
                    
        fields[column.api_name] = value
      end
    end
  end
  
  fields      
end

#get_null_fields(columns, names, values, access_check) ⇒ Object



551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 551

def get_null_fields(columns, names, values, access_check)
  	fields = {}
 	names.each_with_index do | name, n |
	value = values[n]

	if !value
		column = columns[name]
		fields[column.api_name] = nil if column.send(access_check) && column.api_name.casecmp("ownerid") != 0
	end
end

		fields
end

#get_result(response, method) ⇒ Object

Raises:

  • (ActiveSalesforce::ASFError)


576
577
578
579
580
581
582
583
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 576

def get_result(response, method)
  responseName = (method.to_s + "Response").to_sym
  finalResponse = response[responseName]
  
  raise ActiveSalesforce::ASFError.new(@logger, response[:Fault][:faultstring], response.fault) unless finalResponse
  
  result = finalResponse[:result]
end

#get_updated(object_type, start_date, end_date, name = nil) ⇒ Object



451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 451

def get_updated(object_type, start_date, end_date, name = nil)
  msg = "get_updated(#{object_type}, #{start_date}, #{end_date})"
  log(msg, name) {
    get_updated_element = []
    get_updated_element << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << object_type
    get_updated_element << :startDate << start_date
    get_updated_element << :endDate << end_date
    
    result = get_result(@connection.getUpdated(get_updated_element), :getUpdated)
    
    result[:ids]
  }
end

#get_user_info(name = nil) ⇒ Object



486
487
488
489
490
491
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 486

def (name = nil)
  msg = "get_user_info()"
  log(msg, name) {
    get_result(@connection.getUserInfo([]), :getUserInfo)
  }      
end

#insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object



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
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 379

def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
  log(sql, name) {
    # Convert sql to sobject
    table_name, columns, entity_def = lookup(sql.match(/INSERT\s+INTO\s+(\w+)\s+/mi)[1])
    columns = entity_def.column_name_to_column
    
    # Extract array of column names
    names = sql.match(/\((.+)\)\s+VALUES/mi)[1].scan(/\w+/mi)
    
    # Extract arrays of values
    values = sql.match(/VALUES\s*\((.+)\)/mi)[1]
    values = values.scan(/(NULL|TRUE|FALSE|'(?:(?:[^']|'')*)'),*/mi).flatten
    values.map! { |v| v.first == "'" ? v.slice(1, v.length - 2) : v == "NULL" ? nil : v }
    
    fields = get_fields(columns, names, values, :createable)
    
    sobject = create_sobject(entity_def.api_name, nil, fields)
    
    # Track the id to be able to update it when the create() is actually executed
    id = String.new
    @command_boxcar << ActiveSalesforce::BoxcarCommand::Insert.new(self, sobject, id)
    
    id
  }
end

#lookup(raw_table_name) ⇒ Object



760
761
762
763
764
765
766
767
768
769
770
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 760

def lookup(raw_table_name)
  table_name = raw_table_name.singularize
  
  # See if a table name to AR class mapping was registered
  klass = @class_to_entity_map[table_name.upcase]
  
  entity_name = klass ? raw_table_name : table_name.camelize
  entity_def = get_entity_def(entity_name)
  
  [table_name, entity_def.columns, entity_def]
end

#quote(value, column = nil) ⇒ Object

QUOTING ==================================================



163
164
165
166
167
168
169
170
171
172
173
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 163

def quote(value, column = nil)
  case value
  when NilClass              then quoted_value = "NULL"
  when TrueClass             then quoted_value = "TRUE"
  when FalseClass            then quoted_value = "FALSE"
  when Float, Fixnum, Bignum then quoted_value = "'#{value.to_s}'"
  else                       quoted_value = super(value, column)
  end      
  
  quoted_value
end

#reconnect!Object



182
183
184
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 182

def reconnect!
  connect
end

#retrieve_field_values(object_type, fields, ids, name = nil) ⇒ Object



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 494

def retrieve_field_values(object_type, fields, ids, name = nil) 
  msg = "retrieve(#{object_type}, [#{ids.to_a.join(', ')}])"
  log(msg, name) {
    retrieve_element = []      
    retrieve_element << :fieldList << fields.to_a.join(", ")
    retrieve_element << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << object_type
    ids.to_a.each { |id| retrieve_element << :ids << id }
    
    result = get_result(@connection.retrieve(retrieve_element), :retrieve)
    
    result = [ result ] unless result.is_a?(Array)
    
    # Remove unwanted :type and normalize :Id if required
    field_values = []
    result.each do |v| 
      v = v.dup
      v.delete(:type)
      v[:Id] = v[:Id][0] if v[:Id].is_a? Array
      
      field_values << v
    end
    
    field_values
  }
end

#rollback_db_transactionObject

Rolls back the transaction (and turns on auto-committing). Must be done if the transaction block raises an exception or returns false.



259
260
261
262
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 259

def rollback_db_transaction() 
  log('Rolling back boxcar', 'rollback_db_transaction()')
  @command_boxcar = []
end

#select_all(sql, name = nil) ⇒ Object

DATABASE STATEMENTS ======================================



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 267

def select_all(sql, name = nil) #:nodoc:
  raw_table_name = sql.match(/FROM (\w+)/mi)[1]
    table_name, columns, entity_def = lookup(raw_table_name)
    
    column_names = columns.map { |column| column.api_name }

    # Check for SELECT COUNT(*) FROM query
  
  # Rails 1.1
  selectCountMatch = sql.match(/SELECT\s+COUNT\(\*\)\s+AS\s+count_all\s+FROM/mi)
  
  # Rails 1.0
  selectCountMatch = sql.match(/SELECT\s+COUNT\(\*\)\s+FROM/mi) unless selectCountMatch 
  
  if selectCountMatch
    soql = "SELECT COUNT() FROM#{selectCountMatch.post_match}"
  else 
    if sql.match(/SELECT\s+\*\s+FROM/mi)
      # Always convert SELECT * to select all columns (required for the AR attributes mechanism to work correctly)
      soql = sql.sub(/SELECT .+ FROM/mi, "SELECT #{column_names.join(', ')} FROM")
    else
      soql = sql
    end
  end
  
  soql.sub!(/\s+FROM\s+\w+/mi, " FROM #{entity_def.api_name}")

    if selectCountMatch
      query_result = get_result(@connection.query(:queryString => soql), :query)
      return [{ :count => query_result[:size] }]
    end
    
    # Look for a LIMIT clause
  limit = extract_sql_modifier(soql, "LIMIT")
  limit = MAX_BOXCAR_SIZE unless limit
  
  # Look for an OFFSET clause
  offset = extract_sql_modifier(soql, "OFFSET")
  
  # Fixup column references to use api names
  columns = entity_def.column_name_to_column
  soql.gsub!(/((?:\w+\.)?\w+)(?=\s*(?:=|!=|<|>|<=|>=|like)\s*(?:'[^']*'|NULL|TRUE|FALSE))/mi) do |column_name| 
    # strip away any table alias
    column_name.sub!(/\w+\./, '')
    
    column = columns[column_name]
    raise ActiveSalesforce::ASFError.new(@logger, "Column not found for #{column_name}!") unless column
    
    column.api_name
  end
  
  # Update table name references
  soql.sub!(/#{raw_table_name}\./mi, "#{entity_def.api_name}.")

    @connection.batch_size = @batch_size if @batch_size
    @batch_size = nil
    
    query_result = get_result(@connection.query(:queryString => soql), :query)
    result = ActiveSalesforce::ResultArray.new(query_result[:size].to_i)
    return result unless query_result[:records]

    add_rows(entity_def, query_result, result, limit)
    
    while ((query_result[:done].casecmp("true") != 0) and (result.size < limit or limit == 0))
    # Now queryMore            
    locator = query_result[:queryLocator];
    query_result = get_result(@connection.queryMore(:queryLocator => locator), :queryMore)
    
    add_rows(entity_def, query_result, result, limit)
  end
  
  result
end

#select_one(sql, name = nil) ⇒ Object

:nodoc:



370
371
372
373
374
375
376
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 370

def select_one(sql, name = nil) #:nodoc:
  self.batch_size = 1
  
  result = select_all(sql, name)
  
  result.nil? ? nil : result.first
end

#send_commands(commands) ⇒ Object



196
197
198
199
200
201
202
203
204
205
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
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 196

def send_commands(commands)
  # Send the boxcar'ed command set
  verb = commands[0].verb
  
  args = []
  commands.each do |command| 
    command.args.each { |arg| args << arg }
  end
  
  response = @connection.send(verb, args)
  
  result = get_result(response, verb)
  
  result = [ result ] unless result.is_a?(Array)
  
  errors = []
  result.each_with_index do |r, n|
    success = r[:success] == "true"
    
    # Give each command a chance to process its own result
    command = commands[n]
    command.after_execute(r)
    
    # Handle the set of failures
    errors << r[:errors] unless r[:success] == "true"
  end
  
  unless errors.empty?
    message = errors.join("\n")
    fault = (errors.map { |error| error[:message] }).join("\n")
    raise ActiveSalesforce::ASFError.new(@logger, message, fault) 
  end
  
  result
end

#set_class_for_entity(klass, entity_name) ⇒ Object



140
141
142
143
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 140

def set_class_for_entity(klass, entity_name)
  debug("Setting @class_to_entity_map['#{entity_name.upcase}'] = #{klass} for connection #{self}")
  @class_to_entity_map[entity_name.upcase] = klass
end

#supports_migrations?Boolean

:nodoc:

Returns:

  • (Boolean)


156
157
158
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 156

def supports_migrations? #:nodoc:
  false
end

#update(sql, name = nil) ⇒ Object

:nodoc:



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 406

def update(sql, name = nil) #:nodoc:
  #log(sql, name) {
    # Convert sql to sobject
    table_name, columns, entity_def = lookup(sql.match(/UPDATE\s+(\w+)\s+/mi)[1])
    columns = entity_def.column_name_to_column
    
    match = sql.match(/SET\s+(.+)\s+WHERE/mi)[1]
    names = match.scan(/(\w+)\s*=\s*(?:'|NULL|TRUE|FALSE)/mi).flatten
    
    values = match.scan(/=\s*(NULL|TRUE|FALSE|'(?:(?:[^']|'')*)'),*/mi).flatten
    values.map! { |v| v.first == "'" ? v.slice(1, v.length - 2) : v == "NULL" ? nil : v }
    
    fields = get_fields(columns, names, values, :updateable)
  null_fields = get_null_fields(columns, names, values, :updateable)          
    
    id = sql.match(/WHERE\s+id\s*=\s*'(\w+)'/mi)[1]
    
    sobject = create_sobject(entity_def.api_name, id, fields, null_fields)
    
    @command_boxcar << ActiveSalesforce::BoxcarCommand::Update.new(self, sobject)
  #}
end