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



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 142

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.



138
139
140
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 138

def batch_size
  @batch_size
end

#class_to_entity_mapObject (readonly)

Returns the value of attribute class_to_entity_map.



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

def class_to_entity_map
  @class_to_entity_map
end

#configObject (readonly)

Returns the value of attribute config.



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

def config
  @config
end

#entity_def_mapObject (readonly)

Returns the value of attribute entity_def_map.



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

def entity_def_map
  @entity_def_map
end

#keyprefix_to_entity_def_mapObject (readonly)

Returns the value of attribute keyprefix_to_entity_def_map.



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

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)


199
200
201
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 199

def active?
  true
end

#adapter_nameObject

Sets the adapter name to “ActiveSalesforce”



167
168
169
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 167

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.



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

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



229
230
231
232
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 229

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.



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

def binding
  @connection
end

#check_result(result) ⇒ Object



671
672
673
674
675
676
677
678
679
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 671

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



825
826
827
828
829
830
831
832
833
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 825

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



856
857
858
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 856

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



818
819
820
821
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 818

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



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

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)

      #Patch from Kostyl
      commands = [command] # Otherwise command will be lost at all (every 200th command (MAX_BOXCAR_SIZE = 200))
      previous_command = command
      #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



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

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



836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 836

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



874
875
876
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 874

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

#delete(sql, name = nil) ⇒ Object

Delete object(s) from Salesforce



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 500

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.



639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 639

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.



536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 536

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


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

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



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

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



622
623
624
625
626
627
628
629
630
631
632
633
634
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 622

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.



661
662
663
664
665
666
667
668
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 661

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.



521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 521

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



557
558
559
560
561
562
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 557

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



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

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



861
862
863
864
865
866
867
868
869
870
871
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 861

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



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 185

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



204
205
206
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 204

def reconnect!
  connect
end

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

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



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

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.



303
304
305
306
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 303

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.



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

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,"SELECT ")


  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.



434
435
436
437
438
439
440
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 434

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



235
236
237
238
239
240
241
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
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 235

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



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

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)


171
172
173
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 171

def supports_migrations? #:nodoc:
  false
end

#table_exists?(table_name) ⇒ Boolean

Returns:

  • (Boolean)


180
181
182
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 180

def table_exists?(table_name)
  true
end

#tables(name = nil) ⇒ Object

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



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

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.



216
217
218
219
220
221
222
223
224
225
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 216

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



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

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