Class: ActiveRecord::ConnectionAdapters::SalesforceAdapter

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

Overview

Inherit from ConnectionAdapters::AbstractAdapter see:

http://rails.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/AbstractAdapter.html

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

Create a new instance of the connection adapter



149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 149

def initialize(connection, logger, config)
  super(connection, logger)

  @connection_options = nil
  @config = config

  @entity_def_map = {}
  @keyprefix_to_entity_def_map = {}

  @command_boxcar = nil
  @class_to_entity_map = {}
end

Instance Attribute Details

#batch_sizeObject

Returns the value of attribute batch_size.



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

def batch_size
  @batch_size
end

#class_to_entity_mapObject (readonly)

Returns the value of attribute class_to_entity_map.



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

def class_to_entity_map
  @class_to_entity_map
end

#configObject (readonly)

Returns the value of attribute config.



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

def config
  @config
end

#entity_def_mapObject (readonly)

Returns the value of attribute entity_def_map.



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

def entity_def_map
  @entity_def_map
end

#keyprefix_to_entity_def_mapObject (readonly)

Returns the value of attribute keyprefix_to_entity_def_map.



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

def keyprefix_to_entity_def_map
  @keyprefix_to_entity_def_map
end

Instance Method Details

#active?Boolean

– CONNECTION MANAGEMENT ==================================== Set the connection state to active

Returns:

  • (Boolean)


206
207
208
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 206

def active?
  true
end

#adapter_nameObject

Sets the adapter name to “ActiveSalesforce”



174
175
176
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 174

def adapter_name #:nodoc:
  'ActiveSalesforce'
end

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

This methods constructs an array of result objects to be returned to your ActiveRecord’s finder method.



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

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).



236
237
238
239
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 236

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

#bindingObject

returns the binding associated with the current adapter e.g Salesforce::User.first.connection.binding -> returns the binding.



169
170
171
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 169

def binding
  @connection
end

#check_result(result) ⇒ Object



675
676
677
678
679
680
681
682
683
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 675

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

Given a entity and show column names, >>pp user.connection.class_from_entity_name(“AccountFeed”)



829
830
831
832
833
834
835
836
837
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 829

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

  # Constantize entities under the Salesforce namespace.
  entity_klass = ("Salesforce::" + entity_name).constantize unless entity_klass

  entity_klass
end

#column_names(table_name) ⇒ Object

Returns column names associated with a Salesforce Object



860
861
862
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 860

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

#columns(table_name, name = nil) ⇒ Object

Return column names given a table_name, usage: >> pp user.connection.columns(‘account_feed’) or (‘AccountFeed’)



822
823
824
825
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 822

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).



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

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

  # Discard the command boxcar
  @command_boxcar = nil

  # Finish off the partial boxcar
  send_commands(commands) unless commands.empty?

end

#configure_active_record(entity_def) ⇒ Object



754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 754

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").camelize 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("Salesforce::#{reference_to} = Class.new(ActiveRecord::Base)")
        referenced_klass.instance_variable_set("@asf_connection", klass.connection)

        # Automatically inherit the connection from the referencee
        def referenced_klass.connection
          @asf_connection
        end
      end

      if referenced_klass
        if one_to_many
          assoc_name = reference_to.underscore.pluralize.to_sym
          klass.has_many assoc_name, :class_name => referenced_klass.name, :foreign_key => foreign_key
        else
          assoc_name = reference_to.underscore.singularize.to_sym
          klass.belongs_to assoc_name, :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

Create a blank Salesforce object



840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 840

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



878
879
880
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 878

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

#delete(sql, name = nil) ⇒ Object

Delete object(s) from Salesforce



504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 504

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 }

    queue_command ActiveSalesforce::BoxcarCommand::Delete.new(self, ids_element)
  }
end

#extract_sql_modifier(soql, modifier) ⇒ Object

Removed no valid SQL modifier, right now, only LIMIT is allowed. To use a custom SQL, it is better to interface with RForce, see Salesforce::SfBase query_by_sql(sql) method.



643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 643

def extract_sql_modifier(soql, modifier)
  value = soql.match(/\s+#{modifier}\s+(\d+)/mi)
  if value
    value = value[1].to_i
    if !(modifier.upcase == "LIMIT")
      # If it is not the keyword - LIMIT, remove it from the SOQL
      soql.sub!(/\s+#{modifier}\s+\d+/mi, "")
    else
      # If it is the keyword - LIMIT, do not remove it from the SOQL
    end
    # SOQL now supports LIMIT clause. If the user is not an app admin &
    # queries Newsfeed or EntitySubscription & without q limit (e.g. > 1000),
    # it would cause MQL_FORMED_QUERY exception:
    # However, OFFSET is still not supported by SOQL.
    # ***NOTE: needs to change it in the gem to make it effective.
  end

  value
end

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

Get SF object(s) that have been marked as deleted but not yet permanently removed, like things in a recycle bin.



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 540

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

A clever contract to get meta-attribute associated with a Salesforce Object. by Rforce from SOAP result. e.g. pp user.connection.get_entity_def(“AccountFeed”)

<ActiveSalesforce::EntityDefinition:0x1030eee40
@api_name_to_column=
  {"CreatedDate"=> <ActiveRecord::ConnectionAdapters::SalesforceColumn:0x1030f2c20
    @api_name="CreatedDate",
    @createable=false,
    .....


695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 695

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



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

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} - get_fields!") 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



626
627
628
629
630
631
632
633
634
635
636
637
638
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 626

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

A clever contraption to construct the key to the object array which is returned by Rforce from SOAP result.



665
666
667
668
669
670
671
672
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 665

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

If a SF object is dirty, it is called to get fresh attributes.



525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 525

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

Returns information about the user account which is used to connect to salesforce. Salesforce::User.first.connection.get_user_info



561
562
563
564
565
566
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 561

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

Insert object into Salesforce DB



447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 447

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
    queue_command ActiveSalesforce::BoxcarCommand::Insert.new(self, sobject, id)

    id
  }
end

#lookup(raw_table_name) ⇒ Object



865
866
867
868
869
870
871
872
873
874
875
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 865

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 ==================================================



192
193
194
195
196
197
198
199
200
201
202
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 192

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

Overrides the basic method for ActiveRecord::ConnectionAdapters::AbstractAdapter



211
212
213
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 211

def reconnect!
  connect
end

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

Get value given object type, fields, and Salesforce Object.



569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 569

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.



307
308
309
310
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 307

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

#select_all(sql, name = nil) ⇒ Object

DATABASE STATEMENTS ====================================== This method is very important. Pretty much all the ‘find’ methods call it. This is the place to toggle linebreak for debugging purpose. In essence, your finder method calls ActiveRecord, which generates a ‘sql’ And, this methods turn it into a ‘soql’ statement, and use Rforce to call Salesforce and gets a result. So, if you are having problems, make sure you check ‘soql’ and toggle the ‘result’ object.



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
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
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 321

def select_all(sql, name = nil) #:nodoc:

  # silent-e's solution for single quote escape
  # fix the single quote escape method in WHERE condition expression
  sql = fix_single_quote_in_where(sql)
  # Arel adds the class to the selection - we do not want this i.e...
  # SELECT     contacts.* FROM  => SELECT * FROM
  sql = sql.gsub(/SELECT\s+[^\(][A-Z]+\./mi," ")


  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} - in <select_all> method!") 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

Calls the ‘select_all’ method, but limits the result to return only a single row.



438
439
440
441
442
443
444
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 438

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

Calls RForce::Binding -> method_missing -> call_remote method, args[0] methods



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

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



162
163
164
165
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 162

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)


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

def supports_migrations? #:nodoc:
  false
end

#table_exists?(table_name) ⇒ Boolean

Returns:

  • (Boolean)


187
188
189
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 187

def table_exists?(table_name)
  true
end

#tables(name = nil) ⇒ Object

For Silent-e, added ‘tables’ method to solve ARel problem



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

def tables(name = nil) #:nodoc:
  @connection.describeGlobal({}).describeGlobalResponse.result.types
end

#transaction_with_nesting_support(*args, &block) ⇒ Object

Override AbstractAdapter’s transaction method to implement per-connection support for nested transactions that do not commit until the outermost transaction is finished. ActiveRecord provides support for this, but does not distinguish between database connections, which prevents opening transactions to two different databases at the same time.



223
224
225
226
227
228
229
230
231
232
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 223

def transaction_with_nesting_support(*args, &block)
  open = Thread.current["open_transactions_for_#{self.class.name.underscore}"] ||= 0
  Thread.current["open_transactions_for_#{self.class.name.underscore}"] = open + 1

  begin
    transaction_without_nesting_support(&block)
  ensure
    Thread.current["open_transactions_for_#{self.class.name.underscore}"] -= 1
  end
end

#update(sql, name = nil) ⇒ Object

Updates object(s) via SQL. It is an adapter method to be used by ActiveRecord



474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 474

def update(sql, name = nil) #:nodoc:
  # From silent-e, solution for ARel
  sql = sql.gsub(/WHERE\s+\([A-Z]+\./mi,"WHERE ")


  #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)

  ids = sql.match(/WHERE\s+id\s*=\s*'(\w+)'/mi)
  return if ids.nil?
  id = ids[1]

  sobject = create_sobject(entity_def.api_name, id, fields, null_fields)

  queue_command ActiveSalesforce::BoxcarCommand::Update.new(self, sobject)
  #}
end