Class: ActiveRecord::ConnectionAdapters::SalesforceAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::SalesforceAdapter
- Includes:
- StringHelper
- Defined in:
- lib/active_record/connection_adapters/activesalesforce_adapter.rb
Constant Summary collapse
- MAX_BOXCAR_SIZE =
200
Instance Attribute Summary collapse
-
#batch_size ⇒ Object
Returns the value of attribute batch_size.
-
#class_to_entity_map ⇒ Object
readonly
Returns the value of attribute class_to_entity_map.
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#entity_def_map ⇒ Object
readonly
Returns the value of attribute entity_def_map.
-
#keyprefix_to_entity_def_map ⇒ Object
readonly
Returns the value of attribute keyprefix_to_entity_def_map.
Instance Method Summary collapse
-
#active? ⇒ Boolean
CONNECTION MANAGEMENT ====================================.
-
#adapter_name ⇒ Object
:nodoc:.
- #add_rows(entity_def, query_result, result, limit) ⇒ Object
-
#begin_db_transaction ⇒ Object
Begins the transaction (and turns off auto-committing).
- #binding ⇒ Object
- #check_result(result) ⇒ Object
- #class_from_entity_name(entity_name) ⇒ Object
- #column_names(table_name) ⇒ Object
- #columns(table_name, name = nil) ⇒ Object
-
#commit_db_transaction ⇒ Object
Commits the transaction (and turns on auto-committing).
- #configure_active_record(entity_def) ⇒ Object
- #create_sobject(entity_name, id, fields, null_fields = []) ⇒ Object
- #debug(msg) ⇒ Object
- #delete(sql, name = nil) ⇒ Object
- #extract_sql_modifier(soql, modifier) ⇒ Object
- #get_deleted(object_type, start_date, end_date, name = nil) ⇒ Object
- #get_entity_def(entity_name) ⇒ Object
- #get_fields(columns, names, values, access_check) ⇒ Object
- #get_null_fields(columns, names, values, access_check) ⇒ Object
- #get_result(response, method) ⇒ Object
- #get_updated(object_type, start_date, end_date, name = nil) ⇒ Object
- #get_user_info(name = nil) ⇒ Object
-
#initialize(connection, logger, config) ⇒ SalesforceAdapter
constructor
A new instance of SalesforceAdapter.
- #insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object
- #lookup(raw_table_name) ⇒ Object
- #primary_key(table) ⇒ Object
-
#quote(value, column = nil) ⇒ Object
QUOTING ==================================================.
- #reconnect! ⇒ Object
- #retrieve_field_values(object_type, fields, ids, name = nil) ⇒ Object
-
#rollback_db_transaction ⇒ Object
Rolls back the transaction (and turns on auto-committing).
-
#select_all(sql, name = nil) ⇒ Object
DATABASE STATEMENTS ======================================.
-
#select_one(sql, name = nil) ⇒ Object
:nodoc:.
- #send_commands(commands) ⇒ Object
- #set_class_for_entity(klass, entity_name) ⇒ Object
-
#supports_migrations? ⇒ Boolean
:nodoc:.
- #table_exists?(table_name) ⇒ Boolean
-
#tables(name = nil) ⇒ Object
:nodoc:.
-
#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.
-
#update(sql, name = nil) ⇒ Object
:nodoc:.
Methods included from StringHelper
Constructor Details
#initialize(connection, logger, config) ⇒ SalesforceAdapter
Returns a new instance of SalesforceAdapter.
125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 125 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_size ⇒ Object
Returns the value of attribute batch_size.
122 123 124 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 122 def batch_size @batch_size end |
#class_to_entity_map ⇒ Object (readonly)
Returns the value of attribute class_to_entity_map.
123 124 125 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 123 def class_to_entity_map @class_to_entity_map end |
#config ⇒ Object (readonly)
Returns the value of attribute config.
123 124 125 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 123 def config @config end |
#entity_def_map ⇒ Object (readonly)
Returns the value of attribute entity_def_map.
123 124 125 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 123 def entity_def_map @entity_def_map end |
#keyprefix_to_entity_def_map ⇒ Object (readonly)
Returns the value of attribute keyprefix_to_entity_def_map.
123 124 125 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 123 def keyprefix_to_entity_def_map @keyprefix_to_entity_def_map end |
Instance Method Details
#active? ⇒ Boolean
CONNECTION MANAGEMENT ====================================
183 184 185 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 183 def active? true end |
#adapter_name ⇒ Object
:nodoc:
150 151 152 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 150 def adapter_name #:nodoc: 'ActiveSalesforce' end |
#add_rows(entity_def, query_result, result, limit) ⇒ Object
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 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 377 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_transaction ⇒ Object
Begins the transaction (and turns off auto-committing).
214 215 216 217 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 214 def begin_db_transaction # log('Opening boxcar', 'begin_db_transaction()') @command_boxcar = [] end |
#binding ⇒ Object
145 146 147 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 145 def binding @connection end |
#check_result(result) ⇒ Object
629 630 631 632 633 634 635 636 637 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 629 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
774 775 776 777 778 779 780 781 782 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 774 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
805 806 807 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 805 def column_names(table_name) columns(table_name).map { |column| column.name } end |
#columns(table_name, name = nil) ⇒ Object
765 766 767 768 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 765 def columns(table_name, name = nil) table_name, columns, entity_def = lookup(table_name) entity_def.columns end |
#commit_db_transaction ⇒ Object
Commits the transaction (and turns on auto-committing).
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 258 def commit_db_transaction() # log("Committing boxcar with #{@command_boxcar.length} commands", 'commit_db_transaction()') # puts("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
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 752 753 754 755 756 757 758 759 760 761 762 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 699 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
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 785 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
823 824 825 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 823 def debug(msg) @logger.debug(msg) if @logger end |
#delete(sql, name = nil) ⇒ Object
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 473 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
608 609 610 611 612 613 614 615 616 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 608 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
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 509 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
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 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 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 640 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
564 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 590 591 592 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 564 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
594 595 596 597 598 599 600 601 602 603 604 605 606 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 594 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
619 620 621 622 623 624 625 626 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 619 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
494 495 496 497 498 499 500 501 502 503 504 505 506 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 494 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
529 530 531 532 533 534 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 529 def get_user_info(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
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 417 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
810 811 812 813 814 815 816 817 818 819 820 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 810 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 |
#primary_key(table) ⇒ Object
770 771 772 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 770 def primary_key(table) "id" end |
#quote(value, column = nil) ⇒ Object
QUOTING ==================================================
169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 169 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
188 189 190 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 188 def reconnect! connect end |
#retrieve_field_values(object_type, fields, ids, name = nil) ⇒ Object
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 537 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_transaction ⇒ Object
Rolls back the transaction (and turns on auto-committing). Must be done if the transaction block raises an exception or returns false.
287 288 289 290 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 287 def rollback_db_transaction() # log('Rolling back boxcar', 'rollback_db_transaction()') @command_boxcar = nil end |
#select_all(sql, name = nil) ⇒ Object
DATABASE STATEMENTS ======================================
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 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 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 295 def select_all(sql, name = nil) #:nodoc: # fix the single quote escape method in WHERE condition expression sql = quote_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\s+(\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:
406 407 408 409 410 411 412 413 414 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 406 def select_one(sql, name = nil) #:nodoc: # debug "#{sql}" # puts "#{sql}" self.batch_size = 1 result = select_all(sql, name) result.nil? ? nil : result.first end |
#send_commands(commands) ⇒ Object
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 220 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? = errors.join("\n") fault = (errors.map { |error| error[:message] }).join("\n") raise ActiveSalesforce::ASFError.new(@logger, , fault) end result end |
#set_class_for_entity(klass, entity_name) ⇒ Object
139 140 141 142 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 139 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:
155 156 157 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 155 def supports_migrations? #:nodoc: false end |
#table_exists?(table_name) ⇒ Boolean
163 164 165 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 163 def table_exists?(table_name) true end |
#tables(name = nil) ⇒ Object
:nodoc:
159 160 161 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 159 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.
201 202 203 204 205 206 207 208 209 210 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 201 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
:nodoc:
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# File 'lib/active_record/connection_adapters/activesalesforce_adapter.rb', line 444 def update(sql, name = nil) #:nodoc: sql = sql.gsub(/WHERE\s+\([A-Z]+\./mi,"WHERE ") # puts("Update: #{sql}, #{name}") # 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) # puts "return if ids.nil? #{ids}" 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 |