asf-soap-adapter 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (178) hide show
  1. data/.document +5 -0
  2. data/.gitignore +25 -0
  3. data/LICENSE +20 -0
  4. data/README.rdoc +125 -0
  5. data/Rakefile +59 -0
  6. data/VERSION +1 -0
  7. data/asf-soap-adapter.gemspec +297 -0
  8. data/asf-soap-adapter.pptx +0 -0
  9. data/deploy +6 -0
  10. data/lib/active_record/connection_adapters/activesalesforce.rb +36 -0
  11. data/lib/active_record/connection_adapters/activesalesforce_adapter.rb +912 -0
  12. data/lib/active_record/connection_adapters/asf_active_record.rb +40 -0
  13. data/lib/active_record/connection_adapters/boxcar_command.rb +66 -0
  14. data/lib/active_record/connection_adapters/column_definition.rb +95 -0
  15. data/lib/active_record/connection_adapters/entity_definition.rb +59 -0
  16. data/lib/active_record/connection_adapters/id_resolver.rb +84 -0
  17. data/lib/active_record/connection_adapters/recording_binding.rb +93 -0
  18. data/lib/active_record/connection_adapters/relationship_definition.rb +81 -0
  19. data/lib/active_record/connection_adapters/result_array.rb +31 -0
  20. data/lib/active_record/connection_adapters/sid_authentication_filter.rb +57 -0
  21. data/lib/activerecord-activesalesforce-adapter.rb +1 -0
  22. data/lib/asf-soap-adapter.rb +34 -0
  23. data/lib/salesforce/account.rb +28 -0
  24. data/lib/salesforce/account_feed.rb +27 -0
  25. data/lib/salesforce/apex_log.rb +28 -0
  26. data/lib/salesforce/asset.rb +27 -0
  27. data/lib/salesforce/asset_feed.rb +27 -0
  28. data/lib/salesforce/campaign.rb +27 -0
  29. data/lib/salesforce/campaign_feed.rb +27 -0
  30. data/lib/salesforce/case.rb +27 -0
  31. data/lib/salesforce/case_feed.rb +27 -0
  32. data/lib/salesforce/case_team_member.rb +28 -0
  33. data/lib/salesforce/case_team_role.rb +28 -0
  34. data/lib/salesforce/chatter_feed.rb +291 -0
  35. data/lib/salesforce/contact.rb +27 -0
  36. data/lib/salesforce/contact_feed.rb +29 -0
  37. data/lib/salesforce/contract.rb +27 -0
  38. data/lib/salesforce/contract_feed.rb +27 -0
  39. data/lib/salesforce/entity_subscription.rb +27 -0
  40. data/lib/salesforce/feed_comment.rb +27 -0
  41. data/lib/salesforce/feed_post.rb +27 -0
  42. data/lib/salesforce/feed_tracked_change.rb +27 -0
  43. data/lib/salesforce/file_writer.rb +61 -0
  44. data/lib/salesforce/group.rb +28 -0
  45. data/lib/salesforce/group_member.rb +28 -0
  46. data/lib/salesforce/lead.rb +27 -0
  47. data/lib/salesforce/lead_feed.rb +27 -0
  48. data/lib/salesforce/news_feed.rb +27 -0
  49. data/lib/salesforce/opportunity.rb +27 -0
  50. data/lib/salesforce/opportunity_feed.rb +27 -0
  51. data/lib/salesforce/organization.rb +27 -0
  52. data/lib/salesforce/product2.rb +27 -0
  53. data/lib/salesforce/product2_feed.rb +27 -0
  54. data/lib/salesforce/sf_base.rb +94 -0
  55. data/lib/salesforce/sf_utility.rb +214 -0
  56. data/lib/salesforce/solution.rb +27 -0
  57. data/lib/salesforce/solution_feed.rb +27 -0
  58. data/lib/salesforce/solution_history.rb +28 -0
  59. data/lib/salesforce/task.rb +28 -0
  60. data/lib/salesforce/task_feed.rb +28 -0
  61. data/lib/salesforce/user.rb +27 -0
  62. data/lib/salesforce/user_feed.rb +27 -0
  63. data/lib/salesforce/user_profile_feed.rb +27 -0
  64. data/lib/salesforce/user_role.rb +28 -0
  65. data/test/asf-soap-adapter-rails-app/README +243 -0
  66. data/test/asf-soap-adapter-rails-app/Rakefile +10 -0
  67. data/test/asf-soap-adapter-rails-app/app/controllers/adapter_homes_controller.rb +83 -0
  68. data/test/asf-soap-adapter-rails-app/app/controllers/application_controller.rb +10 -0
  69. data/test/asf-soap-adapter-rails-app/app/helpers/adapter_homes_helper.rb +2 -0
  70. data/test/asf-soap-adapter-rails-app/app/helpers/application_helper.rb +3 -0
  71. data/test/asf-soap-adapter-rails-app/app/models/adapter_home.rb +2 -0
  72. data/test/asf-soap-adapter-rails-app/app/views/adapter_homes/edit.html.erb +24 -0
  73. data/test/asf-soap-adapter-rails-app/app/views/adapter_homes/index.html.erb +24 -0
  74. data/test/asf-soap-adapter-rails-app/app/views/adapter_homes/new.html.erb +23 -0
  75. data/test/asf-soap-adapter-rails-app/app/views/adapter_homes/show.html.erb +18 -0
  76. data/test/asf-soap-adapter-rails-app/app/views/layouts/adapter_homes.html.erb +17 -0
  77. data/test/asf-soap-adapter-rails-app/config/boot.rb +110 -0
  78. data/test/asf-soap-adapter-rails-app/config/database.yml +30 -0
  79. data/test/asf-soap-adapter-rails-app/config/environment.rb +44 -0
  80. data/test/asf-soap-adapter-rails-app/config/environments/development.rb +17 -0
  81. data/test/asf-soap-adapter-rails-app/config/environments/production.rb +28 -0
  82. data/test/asf-soap-adapter-rails-app/config/environments/salesforce-default-realm.rb +30 -0
  83. data/test/asf-soap-adapter-rails-app/config/environments/test.rb +28 -0
  84. data/test/asf-soap-adapter-rails-app/config/initializers/backtrace_silencers.rb +7 -0
  85. data/test/asf-soap-adapter-rails-app/config/initializers/cookie_verification_secret.rb +7 -0
  86. data/test/asf-soap-adapter-rails-app/config/initializers/inflections.rb +10 -0
  87. data/test/asf-soap-adapter-rails-app/config/initializers/mime_types.rb +5 -0
  88. data/test/asf-soap-adapter-rails-app/config/initializers/new_rails_defaults.rb +21 -0
  89. data/test/asf-soap-adapter-rails-app/config/initializers/session_store.rb +15 -0
  90. data/test/asf-soap-adapter-rails-app/config/locales/en.yml +5 -0
  91. data/test/asf-soap-adapter-rails-app/config/routes.rb +46 -0
  92. data/test/asf-soap-adapter-rails-app/db/development.sqlite3 +0 -0
  93. data/test/asf-soap-adapter-rails-app/db/migrate/20101107202112_create_adapter_homes.rb +15 -0
  94. data/test/asf-soap-adapter-rails-app/db/schema.rb +22 -0
  95. data/test/asf-soap-adapter-rails-app/db/seeds.rb +7 -0
  96. data/test/asf-soap-adapter-rails-app/db/test.sqlite3 +0 -0
  97. data/test/asf-soap-adapter-rails-app/log/development.log +51 -0
  98. data/test/asf-soap-adapter-rails-app/log/salesforce-default-realm.log +928 -0
  99. data/test/asf-soap-adapter-rails-app/nbproject/private/config.properties +0 -0
  100. data/test/asf-soap-adapter-rails-app/nbproject/private/private.properties +3 -0
  101. data/test/asf-soap-adapter-rails-app/nbproject/private/private.xml +4 -0
  102. data/test/asf-soap-adapter-rails-app/nbproject/private/rake-d.txt +94 -0
  103. data/test/asf-soap-adapter-rails-app/nbproject/project.properties +5 -0
  104. data/test/asf-soap-adapter-rails-app/nbproject/project.xml +9 -0
  105. data/test/asf-soap-adapter-rails-app/public/404.html +30 -0
  106. data/test/asf-soap-adapter-rails-app/public/422.html +30 -0
  107. data/test/asf-soap-adapter-rails-app/public/500.html +30 -0
  108. data/test/asf-soap-adapter-rails-app/public/favicon.ico +0 -0
  109. data/test/asf-soap-adapter-rails-app/public/images/rails.png +0 -0
  110. data/test/asf-soap-adapter-rails-app/public/javascripts/application.js +2 -0
  111. data/test/asf-soap-adapter-rails-app/public/javascripts/controls.js +963 -0
  112. data/test/asf-soap-adapter-rails-app/public/javascripts/dragdrop.js +973 -0
  113. data/test/asf-soap-adapter-rails-app/public/javascripts/effects.js +1128 -0
  114. data/test/asf-soap-adapter-rails-app/public/javascripts/prototype.js +4320 -0
  115. data/test/asf-soap-adapter-rails-app/public/robots.txt +5 -0
  116. data/test/asf-soap-adapter-rails-app/public/stylesheets/scaffold.css +54 -0
  117. data/test/asf-soap-adapter-rails-app/script/about +4 -0
  118. data/test/asf-soap-adapter-rails-app/script/console +3 -0
  119. data/test/asf-soap-adapter-rails-app/script/dbconsole +3 -0
  120. data/test/asf-soap-adapter-rails-app/script/destroy +3 -0
  121. data/test/asf-soap-adapter-rails-app/script/generate +3 -0
  122. data/test/asf-soap-adapter-rails-app/script/performance/benchmarker +3 -0
  123. data/test/asf-soap-adapter-rails-app/script/performance/profiler +3 -0
  124. data/test/asf-soap-adapter-rails-app/script/plugin +3 -0
  125. data/test/asf-soap-adapter-rails-app/script/runner +3 -0
  126. data/test/asf-soap-adapter-rails-app/script/server +3 -0
  127. data/test/asf-soap-adapter-rails-app/test/performance/browsing_test.rb +9 -0
  128. data/test/asf-soap-adapter-rails-app/test/test_helper.rb +44 -0
  129. data/test/asf-soap-adapter-rails-app/test/test_keys.rb +4 -0
  130. data/test/asf-soap-adapter-rails-app/test/unit/adapter_home_test.rb +8 -0
  131. data/test/asf-soap-adapter-rails-app/test/unit/helpers/adapter_homes_helper_test.rb +4 -0
  132. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/account_feed_test.rb +16 -0
  133. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/account_test.rb +66 -0
  134. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/apex_log_test.rb +10 -0
  135. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/asset_feed_test.rb +14 -0
  136. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/asset_test.rb +13 -0
  137. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/campaign_feed_test.rb +13 -0
  138. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/campaign_test.rb +13 -0
  139. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/case_feed_test.rb +13 -0
  140. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/case_team_member_test.rb +10 -0
  141. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/case_team_role.rb +10 -0
  142. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/case_test.rb +13 -0
  143. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/chatter_feed_test.rb +53 -0
  144. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/contact_feed_test.rb +13 -0
  145. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/contact_test.rb +14 -0
  146. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/contract_feed_test.rb +13 -0
  147. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/contract_test.rb +13 -0
  148. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/entity_subscription_test.rb +13 -0
  149. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/feed_comment_test.rb +9 -0
  150. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/feed_post_test.rb +10 -0
  151. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/feed_tracked_change_test.rb +9 -0
  152. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/group_member_test.rb +10 -0
  153. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/group_test.rb +24 -0
  154. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/lead_feed_test.rb +13 -0
  155. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/lead_test.rb +40 -0
  156. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/news_feed_test.rb +13 -0
  157. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/opportunity_feed_test.rb +13 -0
  158. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/opportunity_test.rb +13 -0
  159. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/organization_test.rb +8 -0
  160. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/product2_feed_test.rb +13 -0
  161. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/product2_test.rb +13 -0
  162. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/salesforce_base_test.rb +10 -0
  163. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/solution_feed_test.rb +13 -0
  164. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/solution_history_test.rb +10 -0
  165. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/solution_test.rb +14 -0
  166. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/task_feed_test.rb +10 -0
  167. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/task_test.rb +10 -0
  168. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/user_feed_test.rb +13 -0
  169. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/user_profile_feed_test.rb +11 -0
  170. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/user_role_test.rb +10 -0
  171. data/test/asf-soap-adapter-rails-app/test/unit/salesforce/user_test.rb +48 -0
  172. data/test/basic_test.rb +204 -0
  173. data/test/config.yml +5 -0
  174. data/test/helper.rb +10 -0
  175. data/test/recorded_test_case.rb +87 -0
  176. data/test/simple_test.rb +96 -0
  177. data/test/tests_without_rail.rb +65 -0
  178. metadata +370 -0
Binary file
data/deploy ADDED
@@ -0,0 +1,6 @@
1
+ git add .
2
+ git commit -m 'Improve documentation'
3
+ sudo rake version:bump:patch
4
+ sudo gem uninstall asf-soap-adapter
5
+ sudo rm pkg/*gem
6
+ sudo rake install
@@ -0,0 +1,36 @@
1
+ =begin
2
+ ActiveSalesforce
3
+ Copyright 2006 Doug Chasman
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+ =end
17
+
18
+ require 'activesalesforce_adapter'
19
+
20
+ module ActionView
21
+ module Helpers
22
+ # Provides a set of methods for making easy links and getting urls that depend on the controller and action. This means that
23
+ # you can use the same format for links in the views that you do in the controller. The different methods are even named
24
+ # synchronously, so link_to uses that same url as is generated by url_for, which again is the same url used for
25
+ # redirection in redirect_to.
26
+ module UrlHelper
27
+ def link_to_asf(active_record, column)
28
+ if column.reference_to
29
+ link_to(column.reference_to, { :action => 'show', :controller => column.reference_to.pluralize, :id => active_record.send(column.name) } )
30
+ else
31
+ active_record.send(column.name)
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,912 @@
1
+ =begin
2
+ ActiveSalesforce
3
+ Copyright 2006 Doug Chasman
4
+ 2010 updated by Raymond Gao
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing, software
13
+ distributed under the License is distributed on an "AS IS" BASIS,
14
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ See the License for the specific language governing permissions and
16
+ limitations under the License.
17
+ =end
18
+
19
+ require 'thread'
20
+ require 'benchmark'
21
+
22
+ require 'active_record'
23
+ require 'active_record/connection_adapters/abstract_adapter'
24
+
25
+ # replaced hardlink to 'rforce' gem as a pre-requisite, allowing parallel evolution of both gem.
26
+ require 'rforce'
27
+ #require File.dirname(__FILE__) + '/../../rforce'
28
+ require File.dirname(__FILE__) + '/column_definition'
29
+ require File.dirname(__FILE__) + '/relationship_definition'
30
+ require File.dirname(__FILE__) + '/boxcar_command'
31
+ require File.dirname(__FILE__) + '/entity_definition'
32
+ require File.dirname(__FILE__) + '/asf_active_record'
33
+ require File.dirname(__FILE__) + '/id_resolver'
34
+ require File.dirname(__FILE__) + '/sid_authentication_filter'
35
+ require File.dirname(__FILE__) + '/recording_binding'
36
+ require File.dirname(__FILE__) + '/result_array'
37
+
38
+ # See http://www.rubular.com/ for Ruby Regular Expression
39
+ # See http://api.rubyonrails.org/classes/ActiveRecord/Base.html for documentation
40
+ # ActiveRecord
41
+ # To Understand how to write an adapter, see:
42
+ # http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/AbstractAdapter.html
43
+ # and
44
+ # http://rails.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/AbstractAdapter.html
45
+
46
+ module ActiveRecord
47
+ # Overrides the ActiveRecord::Base class to provide Salesforce Web Services services
48
+ # Particularly important are 1) getting a 'binding' and 2) 'api_version'
49
+ class Base
50
+ @@cache = {}
51
+
52
+ def self.debug(msg)
53
+ logger.debug(msg) if logger
54
+ end
55
+
56
+ def self.flush_connections()
57
+ @@cache = {}
58
+ end
59
+
60
+ # Establishes a connection to the database that's used by all Active Record objects.
61
+ def self.activesalesforce_connection(config) # :nodoc:
62
+ debug("\nUsing ActiveSalesforce connection\n")
63
+
64
+ # Default to production system using 20.0 API
65
+ url = config[:url]
66
+ url = "https://www.salesforce.com" unless url
67
+
68
+ #Take the API version from the Config file e.g. 'database.yml' -> 'salesforce-default-realm'
69
+ api_version = config[:api_version] ? config[:api_version] : "20.0"
70
+ uri = URI.parse(url)
71
+ #uri.path = "/services/Soap/u/20.0"
72
+ uri.path = "/services/Soap/u/" + (api_version).to_s
73
+ url = uri.to_s
74
+
75
+ sid = config[:sid]
76
+ client_id = config[:client_id]
77
+ username = config[:username].to_s
78
+ password = config[:password].to_s
79
+
80
+ # Recording/playback support
81
+ recording_source = config[:recording_source]
82
+ recording = config[:recording]
83
+
84
+ if recording_source
85
+ recording_source = File.open(recording_source, recording ? "w" : "r")
86
+ binding = ActiveSalesforce::RecordingBinding.new(url, nil, recording != nil, recording_source, logger)
87
+ binding.client_id = client_id if client_id
88
+ binding.login(username, password) unless sid
89
+ end
90
+
91
+ # Check to insure that the second to last path component is a 'u' for Partner API
92
+ raise ActiveSalesforce::ASFError.new(logger, "Invalid salesforce server url '#{url}', must be a valid Parter API URL") unless url.match(/\/u\//mi)
93
+
94
+ if sid
95
+ binding = @@cache["sid=#{sid}"] unless binding
96
+
97
+ unless binding
98
+ debug("Establishing new connection for [sid='#{sid}']")
99
+
100
+ binding = RForce::Binding.new(url, sid)
101
+ @@cache["sid=#{sid}"] = binding
102
+
103
+ debug("Created new connection for [sid='#{sid}']")
104
+ else
105
+ debug("Reused existing connection for [sid='#{sid}']")
106
+ end
107
+ else
108
+ binding = @@cache["#{url}.#{username}.#{password}.#{client_id}"] unless binding
109
+
110
+ unless binding
111
+ debug("Establishing new connection for ['#{url}', '#{username}, '#{client_id}'")
112
+
113
+ seconds = Benchmark.realtime {
114
+ binding = RForce::Binding.new(url, sid)
115
+ binding.login(username, password)
116
+
117
+ @@cache["#{url}.#{username}.#{password}.#{client_id}"] = binding
118
+ }
119
+
120
+ debug("Created new connection for ['#{url}', '#{username}', '#{client_id}'] in #{seconds} seconds")
121
+ end
122
+ end
123
+
124
+ ConnectionAdapters::SalesforceAdapter.new(binding, logger, config)
125
+
126
+ end
127
+ end
128
+
129
+
130
+ module ConnectionAdapters
131
+ # Inherit from <em>ConnectionAdapters::AbstractAdapter</em> see:
132
+ # http://rails.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/AbstractAdapter.html
133
+ class SalesforceAdapter < AbstractAdapter
134
+ include StringHelper
135
+
136
+ MAX_BOXCAR_SIZE = 200
137
+
138
+ attr_accessor :batch_size
139
+ attr_reader :entity_def_map, :keyprefix_to_entity_def_map, :config, :class_to_entity_map
140
+
141
+ # Create a new instance of the connection adapter
142
+ def initialize(connection, logger, config)
143
+ super(connection, logger)
144
+
145
+ @connection_options = nil
146
+ @config = config
147
+
148
+ @entity_def_map = {}
149
+ @keyprefix_to_entity_def_map = {}
150
+
151
+ @command_boxcar = nil
152
+ @class_to_entity_map = {}
153
+ end
154
+
155
+ def set_class_for_entity(klass, entity_name)
156
+ debug("Setting @class_to_entity_map['#{entity_name.upcase}'] = #{klass} for connection #{self}")
157
+ @class_to_entity_map[entity_name.upcase] = klass
158
+ end
159
+
160
+ # returns the binding associated with the current adapter
161
+ # e.g Salesforce::User.first.connection.binding -> returns the binding.
162
+ def binding
163
+ @connection
164
+ end
165
+
166
+ #Sets the adapter name to "ActiveSalesforce"
167
+ def adapter_name #:nodoc:
168
+ 'ActiveSalesforce'
169
+ end
170
+
171
+ def supports_migrations? #:nodoc:
172
+ false
173
+ end
174
+
175
+ # For Silent-e, added 'tables' method to solve ARel problem
176
+ def tables(name = nil) #:nodoc:
177
+ @connection.describeGlobal({}).describeGlobalResponse.result.types
178
+ end
179
+
180
+ def table_exists?(table_name)
181
+ true
182
+ end
183
+
184
+ #-- QUOTING ==================================================
185
+ def quote(value, column = nil)
186
+ case value
187
+ when NilClass then quoted_value = "NULL"
188
+ when TrueClass then quoted_value = "TRUE"
189
+ when FalseClass then quoted_value = "FALSE"
190
+ when Float, Fixnum, Bignum then quoted_value = "'#{value.to_s}'"
191
+ else quoted_value = super(value, column)
192
+ end
193
+
194
+ quoted_value
195
+ end
196
+
197
+ #-- CONNECTION MANAGEMENT ====================================
198
+ # Set the connection state to active
199
+ def active?
200
+ true
201
+ end
202
+
203
+ # Overrides the basic method for ActiveRecord::ConnectionAdapters::AbstractAdapter
204
+ def reconnect!
205
+ connect
206
+ end
207
+
208
+ # TRANSACTIOn SUPPORT (Boxcarring really because the salesforce.com api does not support transactions)
209
+
210
+ # Override AbstractAdapter's transaction method to implement
211
+ # per-connection support for nested transactions that do not commit until
212
+ # the outermost transaction is finished. ActiveRecord provides support
213
+ # for this, but does not distinguish between database connections, which
214
+ # prevents opening transactions to two different databases at the same
215
+ # time.
216
+ def transaction_with_nesting_support(*args, &block)
217
+ open = Thread.current["open_transactions_for_#{self.class.name.underscore}"] ||= 0
218
+ Thread.current["open_transactions_for_#{self.class.name.underscore}"] = open + 1
219
+
220
+ begin
221
+ transaction_without_nesting_support(&block)
222
+ ensure
223
+ Thread.current["open_transactions_for_#{self.class.name.underscore}"] -= 1
224
+ end
225
+ end
226
+ alias_method_chain :transaction, :nesting_support
227
+
228
+ # Begins the transaction (and turns off auto-committing).
229
+ def begin_db_transaction
230
+ log('Opening boxcar', 'begin_db_transaction()')
231
+ @command_boxcar = []
232
+ end
233
+
234
+ # Calls <em>RForce::Binding</em> -> <em>method_missing</em> -> <em>call_remote method, args[0] methods</em>
235
+ def send_commands(commands)
236
+ # Send the boxcar'ed command set
237
+ verb = commands[0].verb
238
+
239
+ args = []
240
+ commands.each do |command|
241
+ command.args.each { |arg| args << arg }
242
+ end
243
+
244
+ response = @connection.send(verb, args)
245
+
246
+ result = get_result(response, verb)
247
+
248
+ result = [ result ] unless result.is_a?(Array)
249
+
250
+ errors = []
251
+ result.each_with_index do |r, n|
252
+ success = r[:success] == "true"
253
+
254
+ # Give each command a chance to process its own result
255
+ command = commands[n]
256
+ command.after_execute(r)
257
+
258
+ # Handle the set of failures
259
+ errors << r[:errors] unless r[:success] == "true"
260
+ end
261
+
262
+ unless errors.empty?
263
+ message = errors.join("\n")
264
+ fault = (errors.map { |error| error[:message] }).join("\n")
265
+ raise ActiveSalesforce::ASFError.new(@logger, message, fault)
266
+ end
267
+
268
+ result
269
+ end
270
+
271
+ # Commits the transaction (and turns on auto-committing).
272
+ def commit_db_transaction()
273
+ log("Committing boxcar with #{@command_boxcar.length} commands", 'commit_db_transaction()')
274
+
275
+ previous_command = nil
276
+ commands = []
277
+
278
+ @command_boxcar.each do |command|
279
+ if commands.length >= MAX_BOXCAR_SIZE or (previous_command and (command.verb != previous_command.verb))
280
+ send_commands(commands)
281
+
282
+ commands = []
283
+ previous_command = nil
284
+ else
285
+ commands << command
286
+ previous_command = command
287
+ end
288
+ end
289
+
290
+ # Discard the command boxcar
291
+ @command_boxcar = nil
292
+
293
+ # Finish off the partial boxcar
294
+ send_commands(commands) unless commands.empty?
295
+
296
+ end
297
+
298
+ # Rolls back the transaction (and turns on auto-committing). Must be
299
+ # done if the transaction block raises an exception or returns false.
300
+ def rollback_db_transaction()
301
+ log('Rolling back boxcar', 'rollback_db_transaction()')
302
+ @command_boxcar = nil
303
+ end
304
+
305
+
306
+ # DATABASE STATEMENTS ======================================
307
+ # This method is very important. Pretty much all the 'find' methods call
308
+ # it. This is the place to toggle linebreak for debugging purpose.
309
+ # In essence, your finder method calls ActiveRecord, which generates a 'sql'
310
+ # And, this methods turn it into a 'soql' statement, and use Rforce to call
311
+ # Salesforce and gets a result.
312
+ # So, if you are having problems, make sure you check 'soql' and toggle the
313
+ # 'result' object.
314
+ def select_all(sql, name = nil) #:nodoc:
315
+
316
+ # silent-e's solution for single quote escape
317
+ # fix the single quote escape method in WHERE condition expression
318
+ sql = fix_single_quote_in_where(sql)
319
+ # Arel adds the class to the selection - we do not want this i.e...
320
+ # SELECT contacts.* FROM => SELECT * FROM
321
+ sql = sql.gsub(/SELECT\s+[^\(][A-Z]+\./mi," ")
322
+
323
+
324
+ raw_table_name = sql.match(/FROM (\w+)/mi)[1]
325
+
326
+ table_name, columns, entity_def = lookup(raw_table_name)
327
+
328
+ column_names = columns.map { |column| column.api_name }
329
+
330
+ # Check for SELECT COUNT(*) FROM query
331
+
332
+ # Rails 1.1
333
+ selectCountMatch = sql.match(/SELECT\s+COUNT\(\*\)\s+AS\s+count_all\s+FROM/mi)
334
+
335
+ # Rails 1.0
336
+ selectCountMatch = sql.match(/SELECT\s+COUNT\(\*\)\s+FROM/mi) unless selectCountMatch
337
+
338
+ if selectCountMatch
339
+ soql = "SELECT COUNT() FROM#{selectCountMatch.post_match}"
340
+ else
341
+ if sql.match(/SELECT\s+\*\s+FROM/mi)
342
+ # Always convert SELECT * to select all columns (required for the AR attributes mechanism to work correctly)
343
+ soql = sql.sub(/SELECT .+ FROM/mi, "SELECT #{column_names.join(', ')} FROM")
344
+ else
345
+ soql = sql
346
+ end
347
+ end
348
+
349
+ soql.sub!(/\s+FROM\s+\w+/mi, " FROM #{entity_def.api_name}")
350
+
351
+ if selectCountMatch
352
+ query_result = get_result(@connection.query(:queryString => soql), :query)
353
+ return [{ :count => query_result[:size] }]
354
+ end
355
+
356
+ # Look for a LIMIT clause
357
+ limit = extract_sql_modifier(soql, "LIMIT")
358
+ limit = MAX_BOXCAR_SIZE unless limit
359
+
360
+ # Look for an OFFSET clause
361
+ offset = extract_sql_modifier(soql, "OFFSET")
362
+
363
+ # Fixup column references to use api names
364
+ columns = entity_def.column_name_to_column
365
+ soql.gsub!(/((?:\w+\.)?\w+)(?=\s*(?:=|!=|<|>|<=|>=|like)\s*(?:'[^']*'|NULL|TRUE|FALSE))/mi) do |column_name|
366
+ # strip away any table alias
367
+ column_name.sub!(/\w+\./, '')
368
+
369
+ column = columns[column_name]
370
+ raise ActiveSalesforce::ASFError.new(@logger, "Column not found for #{column_name} - in <select_all> method!") unless column
371
+
372
+ column.api_name
373
+ end
374
+
375
+ # Update table name references
376
+ soql.sub!(/#{raw_table_name}\./mi, "#{entity_def.api_name}.")
377
+
378
+ @connection.batch_size = @batch_size if @batch_size
379
+ @batch_size = nil
380
+
381
+ query_result = get_result(@connection.query(:queryString => soql), :query)
382
+ result = ActiveSalesforce::ResultArray.new(query_result[:size].to_i)
383
+ return result unless query_result[:records]
384
+
385
+ add_rows(entity_def, query_result, result, limit)
386
+
387
+ while ((query_result[:done].casecmp("true") != 0) and (result.size < limit or limit == 0))
388
+ # Now queryMore
389
+ locator = query_result[:queryLocator];
390
+ query_result = get_result(@connection.queryMore(:queryLocator => locator), :queryMore)
391
+
392
+ add_rows(entity_def, query_result, result, limit)
393
+ end
394
+
395
+ result
396
+ end
397
+
398
+ # This methods constructs an array of result objects to be returned to your
399
+ # ActiveRecord's finder method.
400
+ def add_rows(entity_def, query_result, result, limit)
401
+ records = query_result[:records]
402
+ records = [ records ] unless records.is_a?(Array)
403
+
404
+ records.each do |record|
405
+ row = {}
406
+
407
+ record.each do |name, value|
408
+ if name != :type
409
+ # Ids may be returned in an array with 2 duplicate entries...
410
+ value = value[0] if name == :Id && value.is_a?(Array)
411
+
412
+ column = entity_def.api_name_to_column[name.to_s]
413
+ attribute_name = column.name
414
+
415
+ if column.type == :boolean
416
+ row[attribute_name] = (value.casecmp("true") == 0)
417
+ else
418
+ row[attribute_name] = value
419
+ end
420
+ end
421
+ end
422
+
423
+ result << row
424
+
425
+ break if result.size >= limit and limit != 0
426
+ end
427
+ end
428
+
429
+ # Calls the <b><em>'select_all'</em></b> method, but limits the result to return only a
430
+ # single row.
431
+ def select_one(sql, name = nil) #:nodoc:
432
+ self.batch_size = 1
433
+
434
+ result = select_all(sql, name)
435
+
436
+ result.nil? ? nil : result.first
437
+ end
438
+
439
+ # Insert object into Salesforce DB
440
+ def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
441
+ log(sql, name) {
442
+ # Convert sql to sobject
443
+ table_name, columns, entity_def = lookup(sql.match(/INSERT\s+INTO\s+(\w+)\s+/mi)[1])
444
+ columns = entity_def.column_name_to_column
445
+
446
+ # Extract array of column names
447
+ names = sql.match(/\((.+)\)\s+VALUES/mi)[1].scan(/\w+/mi)
448
+
449
+ # Extract arrays of values
450
+ values = sql.match(/VALUES\s*\((.+)\)/mi)[1]
451
+ values = values.scan(/(NULL|TRUE|FALSE|'(?:(?:[^']|'')*)'),*/mi).flatten
452
+ values.map! { |v| v.first == "'" ? v.slice(1, v.length - 2) : v == "NULL" ? nil : v }
453
+
454
+ fields = get_fields(columns, names, values, :createable)
455
+
456
+ sobject = create_sobject(entity_def.api_name, nil, fields)
457
+
458
+ # Track the id to be able to update it when the create() is actually executed
459
+ id = String.new
460
+ queue_command ActiveSalesforce::BoxcarCommand::Insert.new(self, sobject, id)
461
+
462
+ id
463
+ }
464
+ end
465
+
466
+ # Updates object(s) via SQL. It is an adapter method to be used by ActiveRecord
467
+ def update(sql, name = nil) #:nodoc:
468
+ # From silent-e, solution for ARel
469
+ sql = sql.gsub(/WHERE\s+\([A-Z]+\./mi,"WHERE ")
470
+
471
+
472
+ #log(sql, name) {
473
+ # Convert sql to sobject
474
+ table_name, columns, entity_def = lookup(sql.match(/UPDATE\s+(\w+)\s+/mi)[1])
475
+ columns = entity_def.column_name_to_column
476
+
477
+ match = sql.match(/SET\s+(.+)\s+WHERE/mi)[1]
478
+ names = match.scan(/(\w+)\s*=\s*(?:'|NULL|TRUE|FALSE)/mi).flatten
479
+
480
+ values = match.scan(/=\s*(NULL|TRUE|FALSE|'(?:(?:[^']|'')*)'),*/mi).flatten
481
+ values.map! { |v| v.first == "'" ? v.slice(1, v.length - 2) : v == "NULL" ? nil : v }
482
+
483
+ fields = get_fields(columns, names, values, :updateable)
484
+ null_fields = get_null_fields(columns, names, values, :updateable)
485
+
486
+ ids = sql.match(/WHERE\s+id\s*=\s*'(\w+)'/mi)
487
+ return if ids.nil?
488
+ id = ids[1]
489
+
490
+ sobject = create_sobject(entity_def.api_name, id, fields, null_fields)
491
+
492
+ queue_command ActiveSalesforce::BoxcarCommand::Update.new(self, sobject)
493
+ #}
494
+ end
495
+
496
+ # Delete object(s) from Salesforce
497
+ def delete(sql, name = nil)
498
+ log(sql, name) {
499
+ # Extract the id
500
+ match = sql.match(/WHERE\s+id\s*=\s*'(\w+)'/mi)
501
+
502
+ if match
503
+ ids = [ match[1] ]
504
+ else
505
+ # Check for the form (id IN ('x', 'y'))
506
+ match = sql.match(/WHERE\s+\(\s*id\s+IN\s*\((.+)\)\)/mi)[1]
507
+ ids = match.scan(/\w+/)
508
+ end
509
+
510
+ ids_element = []
511
+ ids.each { |id| ids_element << :ids << id }
512
+
513
+ queue_command ActiveSalesforce::BoxcarCommand::Delete.new(self, ids_element)
514
+ }
515
+ end
516
+
517
+ # If a SF object is dirty, it is called to get fresh attributes.
518
+ def get_updated(object_type, start_date, end_date, name = nil)
519
+ msg = "get_updated(#{object_type}, #{start_date}, #{end_date})"
520
+ log(msg, name) {
521
+ get_updated_element = []
522
+ get_updated_element << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << object_type
523
+ get_updated_element << :startDate << start_date
524
+ get_updated_element << :endDate << end_date
525
+
526
+ result = get_result(@connection.getUpdated(get_updated_element), :getUpdated)
527
+
528
+ result[:ids]
529
+ }
530
+ end
531
+
532
+ # Get SF object(s) that have been marked as deleted but not yet permanently removed, like things in a recycle bin.
533
+ def get_deleted(object_type, start_date, end_date, name = nil)
534
+ msg = "get_deleted(#{object_type}, #{start_date}, #{end_date})"
535
+ log(msg, name) {
536
+ get_deleted_element = []
537
+ get_deleted_element << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << object_type
538
+ get_deleted_element << :startDate << start_date
539
+ get_deleted_element << :endDate << end_date
540
+
541
+ result = get_result(@connection.getDeleted(get_deleted_element), :getDeleted)
542
+
543
+ ids = []
544
+ result[:deletedRecords].each do |v|
545
+ ids << v[:id]
546
+ end
547
+
548
+ ids
549
+ }
550
+ end
551
+
552
+ # Returns information about the user account which is used to connect to salesforce.
553
+ # <b>Salesforce::User.first.connection.get_user_info</b>
554
+ def get_user_info(name = nil)
555
+ msg = "get_user_info()"
556
+ log(msg, name) {
557
+ get_result(@connection.getUserInfo([]), :getUserInfo)
558
+ }
559
+ end
560
+
561
+ # Get value given object type, fields, and Salesforce Object.
562
+ def retrieve_field_values(object_type, fields, ids, name = nil)
563
+ msg = "retrieve(#{object_type}, [#{ids.to_a.join(', ')}])"
564
+ log(msg, name) {
565
+ retrieve_element = []
566
+ retrieve_element << :fieldList << fields.to_a.join(", ")
567
+ retrieve_element << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << object_type
568
+ ids.to_a.each { |id| retrieve_element << :ids << id }
569
+
570
+ result = get_result(@connection.retrieve(retrieve_element), :retrieve)
571
+
572
+ result = [ result ] unless result.is_a?(Array)
573
+
574
+ # Remove unwanted :type and normalize :Id if required
575
+ field_values = []
576
+ result.each do |v|
577
+ v = v.dup
578
+ v.delete(:type)
579
+ v[:Id] = v[:Id][0] if v[:Id].is_a? Array
580
+
581
+ field_values << v
582
+ end
583
+
584
+ field_values
585
+ }
586
+ end
587
+
588
+
589
+ def get_fields(columns, names, values, access_check)
590
+ fields = {}
591
+ names.each_with_index do | name, n |
592
+ value = values[n]
593
+
594
+ if value
595
+ column = columns[name]
596
+
597
+ raise ActiveSalesforce::ASFError.new(@logger, "Column not found for #{name} - get_fields!") unless column
598
+
599
+ value.gsub!(/''/, "'") if value.is_a? String
600
+
601
+ include_field = ((not value.empty?) and column.send(access_check))
602
+
603
+ if (include_field)
604
+ case column.type
605
+ when :date
606
+ value = Time.parse(value + "Z").utc.strftime("%Y-%m-%d")
607
+ when :datetime
608
+ value = Time.parse(value + "Z").utc.strftime("%Y-%m-%dT%H:%M:%SZ")
609
+ end
610
+
611
+ fields[column.api_name] = value
612
+ end
613
+ end
614
+ end
615
+
616
+ fields
617
+ end
618
+
619
+ def get_null_fields(columns, names, values, access_check)
620
+ fields = {}
621
+ names.each_with_index do | name, n |
622
+ value = values[n]
623
+
624
+ if !value
625
+ column = columns[name]
626
+ fields[column.api_name] = nil if column.send(access_check) && column.api_name.casecmp("ownerid") != 0
627
+ end
628
+ end
629
+
630
+ fields
631
+ end
632
+
633
+ # Removed no valid SQL modifier, right now, only LIMIT is allowed.
634
+ # To use a custom SQL, it is better to interface with RForce, see
635
+ # Salesforce::SfBase query_by_sql(sql) method.
636
+ def extract_sql_modifier(soql, modifier)
637
+ value = soql.match(/\s+#{modifier}\s+(\d+)/mi)
638
+ if value
639
+ value = value[1].to_i
640
+ if !(modifier.upcase == "LIMIT")
641
+ # If it is not the keyword - LIMIT, remove it from the SOQL
642
+ soql.sub!(/\s+#{modifier}\s+\d+/mi, "")
643
+ else
644
+ # If it is the keyword - LIMIT, do not remove it from the SOQL
645
+ end
646
+ # SOQL now supports LIMIT clause. If the user is not an app admin &
647
+ # queries Newsfeed or EntitySubscription & without q limit (e.g. > 1000),
648
+ # it would cause MQL_FORMED_QUERY exception:
649
+ # However, OFFSET is still not supported by SOQL.
650
+ # ***NOTE: needs to change it in the gem to make it effective.
651
+ end
652
+
653
+ value
654
+ end
655
+
656
+ # A clever contraption to construct the key to the object array which is returned
657
+ # by Rforce from SOAP result.
658
+ def get_result(response, method)
659
+ responseName = (method.to_s + "Response").to_sym
660
+ finalResponse = response[responseName]
661
+
662
+ raise ActiveSalesforce::ASFError.new(@logger, response[:Fault][:faultstring], response.fault) unless finalResponse
663
+
664
+ result = finalResponse[:result]
665
+ end
666
+
667
+
668
+ def check_result(result)
669
+ result = [ result ] unless result.is_a?(Array)
670
+
671
+ result.each do |r|
672
+ raise ActiveSalesforce::ASFError.new(@logger, r[:errors], r[:errors][:message]) unless r[:success] == "true"
673
+ end
674
+
675
+ result
676
+ end
677
+
678
+
679
+ # A clever contract to get meta-attribute associated with a Salesforce Object.
680
+ # by Rforce from SOAP result. e.g.
681
+ # <b>pp user.connection.get_entity_def("AccountFeed") </b>
682
+ # <ActiveSalesforce::EntityDefinition:0x1030eee40
683
+ # @api_name_to_column=
684
+ # {"CreatedDate"=> <ActiveRecord::ConnectionAdapters::SalesforceColumn:0x1030f2c20
685
+ # @api_name="CreatedDate",
686
+ # @createable=false,
687
+ # .....
688
+ def get_entity_def(entity_name)
689
+ cached_entity_def = @entity_def_map[entity_name]
690
+
691
+ if cached_entity_def
692
+ # Check for the loss of asf AR setup
693
+ entity_klass = class_from_entity_name(entity_name)
694
+
695
+ configure_active_record(cached_entity_def) unless entity_klass.respond_to?(:asf_augmented?)
696
+
697
+ return cached_entity_def
698
+ end
699
+
700
+ cached_columns = []
701
+ cached_relationships = []
702
+
703
+ begin
704
+ metadata = get_result(@connection.describeSObject(:sObjectType => entity_name), :describeSObject)
705
+ custom = false
706
+ rescue ActiveSalesforce::ASFError
707
+ # Fallback and see if we can find a custom object with this name
708
+ debug(" Unable to find medata for '#{entity_name}', falling back to custom object name #{entity_name + "__c"}")
709
+
710
+ metadata = get_result(@connection.describeSObject(:sObjectType => entity_name + "__c"), :describeSObject)
711
+ custom = true
712
+ end
713
+
714
+ metadata[:fields].each do |field|
715
+ column = SalesforceColumn.new(field)
716
+ cached_columns << column
717
+
718
+ cached_relationships << SalesforceRelationship.new(field, column) if field[:type] =~ /reference/mi
719
+ end
720
+
721
+ relationships = metadata[:childRelationships]
722
+ if relationships
723
+ relationships = [ relationships ] unless relationships.is_a? Array
724
+
725
+ relationships.each do |relationship|
726
+ if relationship[:cascadeDelete] == "true"
727
+ r = SalesforceRelationship.new(relationship)
728
+ cached_relationships << r
729
+ end
730
+ end
731
+ end
732
+
733
+ key_prefix = metadata[:keyPrefix]
734
+
735
+ entity_def = ActiveSalesforce::EntityDefinition.new(self, entity_name, entity_klass,
736
+ cached_columns, cached_relationships, custom, key_prefix)
737
+
738
+ @entity_def_map[entity_name] = entity_def
739
+ @keyprefix_to_entity_def_map[key_prefix] = entity_def
740
+
741
+ configure_active_record(entity_def)
742
+
743
+ entity_def
744
+ end
745
+
746
+
747
+ def configure_active_record(entity_def)
748
+ entity_name = entity_def.name
749
+ klass = class_from_entity_name(entity_name)
750
+
751
+ class << klass
752
+ def asf_augmented?
753
+ true
754
+ end
755
+ end
756
+
757
+ # Add support for SID-based authentication
758
+ ActiveSalesforce::SessionIDAuthenticationFilter.register(klass)
759
+
760
+ klass.set_inheritance_column nil unless entity_def.custom?
761
+ klass.set_primary_key "id"
762
+
763
+ # Create relationships for any reference field
764
+ entity_def.relationships.each do |relationship|
765
+ referenceName = relationship.name
766
+ unless self.respond_to? referenceName.to_sym or relationship.reference_to == "Profile"
767
+ reference_to = relationship.reference_to
768
+ one_to_many = relationship.one_to_many
769
+ foreign_key = relationship.foreign_key
770
+
771
+ # DCHASMAN TODO Figure out how to handle polymorphic refs (e.g. Note.parent can refer to
772
+ # Account, Contact, Opportunity, Contract, Asset, Product2, <CustomObject1> ... <CustomObject(n)>
773
+ if reference_to.is_a? Array
774
+ debug(" Skipping unsupported polymophic one-to-#{one_to_many ? 'many' : 'one' } relationship '#{referenceName}' from #{klass} to [#{relationship.reference_to.join(', ')}] using #{foreign_key}")
775
+ next
776
+ end
777
+
778
+ # Handle references to custom objects
779
+ reference_to = reference_to.chomp("__c").camelize if reference_to.match(/__c$/)
780
+
781
+ begin
782
+ referenced_klass = class_from_entity_name(reference_to)
783
+ rescue NameError => e
784
+ # Automatically create a least a stub for the referenced entity
785
+ debug(" Creating ActiveRecord stub for the referenced entity '#{reference_to}'")
786
+
787
+ referenced_klass = klass.class_eval("Salesforce::#{reference_to} = Class.new(ActiveRecord::Base)")
788
+ referenced_klass.instance_variable_set("@asf_connection", klass.connection)
789
+
790
+ # Automatically inherit the connection from the referencee
791
+ def referenced_klass.connection
792
+ @asf_connection
793
+ end
794
+ end
795
+
796
+ if referenced_klass
797
+ if one_to_many
798
+ assoc_name = reference_to.underscore.pluralize.to_sym
799
+ klass.has_many assoc_name, :class_name => referenced_klass.name, :foreign_key => foreign_key
800
+ else
801
+ assoc_name = reference_to.underscore.singularize.to_sym
802
+ klass.belongs_to assoc_name, :class_name => referenced_klass.name, :foreign_key => foreign_key
803
+ end
804
+
805
+ debug(" Created one-to-#{one_to_many ? 'many' : 'one' } relationship '#{referenceName}' from #{klass} to #{referenced_klass} using #{foreign_key}")
806
+ end
807
+ end
808
+ end
809
+
810
+ end
811
+
812
+
813
+ # Return column names given a table_name, usage:
814
+ # >> pp user.connection.columns('account_feed') or ('AccountFeed')
815
+ def columns(table_name, name = nil)
816
+ table_name, columns, entity_def = lookup(table_name)
817
+ entity_def.columns
818
+ end
819
+
820
+ # Given a entity and show column names,
821
+ # >>pp user.connection.class_from_entity_name("AccountFeed")
822
+ def class_from_entity_name(entity_name)
823
+ entity_klass = @class_to_entity_map[entity_name.upcase]
824
+ debug("Found matching class '#{entity_klass}' for entity '#{entity_name}'") if entity_klass
825
+
826
+ # Constantize entities under the Salesforce namespace.
827
+ entity_klass = ("Salesforce::" + entity_name).constantize unless entity_klass
828
+
829
+ entity_klass
830
+ end
831
+
832
+ # Create a blank Salesforce object
833
+ def create_sobject(entity_name, id, fields, null_fields = [])
834
+ sobj = []
835
+
836
+ sobj << 'type { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << entity_name
837
+ sobj << 'Id { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << id if id
838
+
839
+ # add any changed fields
840
+ fields.each do | name, value |
841
+ sobj << name.to_sym << value if value
842
+ end
843
+
844
+ # add null fields
845
+ null_fields.each do | name, value |
846
+ sobj << 'fieldsToNull { :xmlns => "urn:sobject.partner.soap.sforce.com" }' << name
847
+ end
848
+
849
+ [ :sObjects, sobj ]
850
+ end
851
+
852
+ # Returns column names associated with a Salesforce Object
853
+ def column_names(table_name)
854
+ columns(table_name).map { |column| column.name }
855
+ end
856
+
857
+
858
+ def lookup(raw_table_name)
859
+ table_name = raw_table_name.singularize
860
+
861
+ # See if a table name to AR class mapping was registered
862
+ klass = @class_to_entity_map[table_name.upcase]
863
+
864
+ entity_name = klass ? raw_table_name : table_name.camelize
865
+ entity_def = get_entity_def(entity_name)
866
+
867
+ [table_name, entity_def.columns, entity_def]
868
+ end
869
+
870
+
871
+ def debug(msg)
872
+ @logger.debug(msg) if @logger
873
+ end
874
+
875
+ protected
876
+
877
+ # For Silent-e, added 'tables' method to solve ARel problem
878
+ # fix single-quote escape sequence for WHERE condition expressions. Salesforce enforces a backspace on SELECTs
879
+ # NOTE: this method is only used for SELECT queries. INSERT/UPDATE queries are smart enough to use the primary
880
+ # key for their WHERE statements, or so I've found.
881
+ def fix_single_quote_in_where(sql)
882
+ where_match = sql.match(/WHERE\s*\((.*)\)/mi)
883
+
884
+ return sql unless where_match
885
+ where_conditions = where_match[1]
886
+
887
+ # debug("where_conditions: #{where_conditions}")
888
+ where_conditions.gsub!(/''/, "\\\\'")
889
+
890
+ # debug("updated where_conditions: #{where_conditions.gsub(/''/, "\\\\'")}")
891
+
892
+ sql = "#{where_match.pre_match}WHERE (#{where_conditions})#{where_match.post_match}"
893
+ end
894
+
895
+
896
+ def queue_command(command)
897
+ # If @command_boxcar is not nil, then this is a transaction
898
+ # and commands should be queued in the boxcar
899
+ if @command_boxcar
900
+ @command_boxcar << command
901
+
902
+ # If a command is not executed within a transaction, it should
903
+ # be executed immediately
904
+ else
905
+ send_commands([command])
906
+ end
907
+ end
908
+
909
+ end
910
+
911
+ end
912
+ end