activerecord-jdbc-adapter 52.0-java → 52.1-java

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA256:
3
- metadata.gz: d4e30effdf5519398605801e776e032f385bba8da0008c15bdda99426ac0b2ee
4
- data.tar.gz: 5c3075c02b57070186442fd4d8e88252ffab2db0f06ebed390dcdeb7556a27ba
2
+ SHA1:
3
+ metadata.gz: ce3b01a3484aa192fc9a22b788e3117aa44adedd
4
+ data.tar.gz: 48b8197f1de856fe9994bfdf798c078eb92b6e2d
5
5
  SHA512:
6
- metadata.gz: 01c8df592aec36d47474c1968ff73e39f68414a3a3fbde27fcaa5c24fe078ee8cddb2b3f750d580660d567fb3323511e7ad9781913bb6fe658797a9445b42bce
7
- data.tar.gz: 1940e41e96e0ac3af73bb0bbdd1dcc75c9c07554e2d3c05a8cc3bf3562cbd9fa9593919a8159c151577463ad676be42b92b2b61089efdebc9ad94fff34596ec7
6
+ metadata.gz: d1cc13e79b76c8cef827ce7af505720845f5ad7e66c8ffd4bd07dbf4da6563e3d5450c3351ba7dd95b37c096d10b417e28bc3487fba5319d70bbe9776407b0a9
7
+ data.tar.gz: fab5dc5990fb886dda12232efebcdeed0701bddb4e7b605514a07a955149b34b41bde32f7b18b99aa9274e6ced874733ceddbd72c58302dad0781aeacf2f955f
@@ -21,8 +21,8 @@ before_script:
21
21
  mysql -e "grant all privileges on activerecord_unittest.* to rails@localhost;" && \
22
22
  mysql -e "grant all privileges on activerecord_unittest2.* to rails@localhost;" && \
23
23
  mysql -e "grant all privileges on inexistent_activerecord_unittest.* to rails@localhost;" && \
24
- mysql -e "CREATE DATABASE activerecord_unittest;" && \
25
- mysql -e "CREATE DATABASE activerecord_unittest2;" \
24
+ mysql -e "CREATE DATABASE activerecord_unittest DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;" && \
25
+ mysql -e "CREATE DATABASE activerecord_unittest2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;" \
26
26
  || true
27
27
  - |
28
28
  [ "$DB" == "postgresql" ] && [ "$TEST_PREFIX" == "rails:" ] && \
@@ -33,6 +33,8 @@ rvm:
33
33
  - jruby-9.1.16.0
34
34
  jdk:
35
35
  - openjdk8
36
+ addons:
37
+ postgresql: "9.4"
36
38
  env:
37
39
  - DB=mysql2 PREPARED_STATEMENTS=false
38
40
  - DB=mysql2 PREPARED_STATEMENTS=true
data/Rakefile CHANGED
@@ -236,19 +236,16 @@ if defined? JRUBY_VERSION
236
236
  end
237
237
 
238
238
  classpath = []
239
- ENV_PATHS = [ 'java.class.path', 'sun.boot.class.path' ]
240
- ENV_PATHS.map { |key| ENV_JAVA[key] }.compact.each do |v|
241
- classpath += v.split(File::PATH_SEPARATOR).find_all { |jar| jar =~ /jruby/i }
239
+ [ 'java.class.path', 'sun.boot.class.path' ].map { |key| ENV_JAVA[key] }.each do |v|
240
+ classpath += v.split(File::PATH_SEPARATOR).find_all { |jar| jar =~ /jruby/i } if v
242
241
  end
243
-
244
- # Using Java 9+. Let's try and infer jruby jar location from rbconfig
245
- if classpath.empty?
246
- require 'rbconfig'
247
- libdir = RbConfig::CONFIG["libdir"]
248
- if libdir.start_with? "classpath:"
242
+ # Using Java 9+. Let's try and infer jruby.jar location from rbconfig
243
+ if classpath.empty?; require 'rbconfig'
244
+ libdir = RbConfig::CONFIG['libdir']
245
+ if libdir.start_with? 'classpath:'
249
246
  error "Cannot build activerecord-jdbc with jruby-complete"
250
247
  end
251
- classpath << File.join(libdir, "jruby.jar")
248
+ classpath << File.join(libdir, 'jruby.jar')
252
249
  end
253
250
 
254
251
  classpath += driver_jars
@@ -256,11 +253,26 @@ if defined? JRUBY_VERSION
256
253
 
257
254
  source_files = FileList[ 'src/java/**/*.java' ]
258
255
 
259
- require 'tmpdir'
256
+ version = lambda do
257
+ begin
258
+ require 'arjdbc/version'
259
+ rescue LoadError
260
+ path = File.expand_path('../lib', File.dirname(__FILE__))
261
+ unless $LOAD_PATH.include?(path)
262
+ $LOAD_PATH << path; retry
263
+ end
264
+ end
265
+
266
+ gem_version = Gem::Version.create(ArJdbc::VERSION)
267
+ if gem_version.segments.last == 'DEV'
268
+ gem_version.segments[0...-1] # 50.0.DEV -> 50.0
269
+ else
270
+ gem_version.segments.dup
271
+ end
272
+ end
260
273
 
261
- Dir.mktmpdir do |classes_dir|
262
- # Cross-platform way of finding an executable in the $PATH.
263
- # Thanks to @mislav
274
+ require 'tmpdir'; Dir.mktmpdir do |classes_dir|
275
+ # Cross-platform way of finding an executable in the $PATH. Thanks to @mislav
264
276
  which = lambda do |cmd|
265
277
  exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
266
278
  ENV['PATH'].split(File::PATH_SEPARATOR).map do |path|
@@ -284,7 +296,24 @@ if defined? JRUBY_VERSION
284
296
  # avoid environment variable expansion using backslash
285
297
  # class_files.gsub!('$', '\$') unless windows?
286
298
  # args = class_files.map { |path| [ "-C #{classes_dir}", path ] }.flatten
287
- args = [ '-C', "#{classes_dir}/ ." ] # args = class_files
299
+
300
+ if ENV['RELEASE'] == 'true'; require 'tempfile'
301
+ manifest = "Built-Time: #{Time.now.utc.strftime('%Y-%m-%d %H:%M:%S')}\n"
302
+ manifest += "Built-JRuby: #{JRUBY_VERSION}\n"
303
+ manifest += "Specification-Title: ActiveRecord-JDBC\n"
304
+ manifest += "Specification-Vendor: JRuby\n"
305
+ manifest += "Specification-Version: #{version.call[0].to_s.split('').join('.')}\n" # AR VERSION (52 -> 5.2)
306
+ manifest += "Implementation-Vendor: The JRuby Team\n"
307
+ manifest += "Implementation-Version: #{version.call.join('.')}\n"
308
+ manifest = Tempfile.new('MANIFEST').tap { |f| f << manifest; f.close }.path
309
+ end
310
+
311
+ args = []; opts = '-cf'
312
+ if manifest
313
+ opts = "#{opts}m"
314
+ args = [ "#{manifest}" ]
315
+ end
316
+ args += [ '-C', "#{classes_dir}/ ." ]
288
317
 
289
318
  jar_path = jar_file
290
319
  if ext_lib_dir = ENV['RUBYLIBDIR']
@@ -294,7 +323,7 @@ if defined? JRUBY_VERSION
294
323
  unless jar = which.call('jar')
295
324
  warn "could not find jar tool, please make sure it's on the PATH"
296
325
  end
297
- sh("#{jar} cf #{jar_path} #{args.join(' ')}") do |ok|
326
+ sh("#{jar} #{opts} #{jar_path} #{args.join(' ')}") do |ok|
298
327
  raise 'could not build .jar extension - packaging failure' unless ok
299
328
  end
300
329
  cp jar_path, jar_file if ext_lib_dir # NOTE: hopefully RG won't mind?!
@@ -302,6 +331,6 @@ if defined? JRUBY_VERSION
302
331
  end
303
332
  else
304
333
  task :jar do
305
- puts "please run `rake jar' under JRuby to re-compile the native (Java) extension"
334
+ warn "please run `rake jar' under JRuby to re-compile the native (Java) extension"
306
335
  end
307
336
  end
@@ -60,7 +60,17 @@ module ArJdbc
60
60
  end
61
61
  end
62
62
 
63
+ def extract_raw_bind_values(binds)
64
+ binds.map(&:value_for_database)
65
+ end
63
66
 
67
+ # this version of log() automatically fills type_casted_binds from binds if necessary
68
+ def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil)
69
+ if binds.any? && (type_casted_binds.nil? || type_casted_binds.empty?)
70
+ type_casted_binds = ->{ extract_raw_bind_values(binds) }
71
+ end
72
+ super
73
+ end
64
74
  end
65
75
  end
66
76
  end
@@ -27,7 +27,7 @@ module ArJdbc
27
27
  else
28
28
  log(sql, name, binds) do
29
29
  # It seems that #supports_statement_cache? is defined but isn't checked before setting "prepare" (AR 5.0)
30
- cached_statement = fetch_cached_statement(sql) if prepare && supports_statement_cache?
30
+ cached_statement = fetch_cached_statement(sql) if prepare && @jdbc_statement_cache_enabled
31
31
  @connection.execute_prepared_query(sql, binds, cached_statement)
32
32
  end
33
33
  end
@@ -42,6 +42,7 @@ module ArJdbc
42
42
  end
43
43
 
44
44
  def supports_statement_cache?
45
+ ActiveSupport::Deprecation.deprecation_warning(__method__)
45
46
  @jdbc_statement_cache_enabled
46
47
  end
47
48
 
@@ -4,15 +4,8 @@ module ArJdbc
4
4
  ConnectionMethods.module_eval do
5
5
 
6
6
  def jdbc_connection(config)
7
- adapter_class = config[:adapter_class]
8
- adapter_class ||= ::ActiveRecord::ConnectionAdapters::JdbcAdapter
9
-
10
- # Once all adapters converted to AR5 then this rescue can be removed
11
- begin
12
- adapter_class.new(nil, logger, nil, config)
13
- rescue ArgumentError
14
- adapter_class.new(nil, logger, config)
15
- end
7
+ adapter_class = config[:adapter_class] || ::ActiveRecord::ConnectionAdapters::JdbcAdapter
8
+ adapter_class.new(nil, logger, nil, config)
16
9
  end
17
10
 
18
11
  def jndi_connection(config); jdbc_connection(config) end
@@ -31,8 +31,8 @@ module ActiveRecord
31
31
 
32
32
  include ArJdbc::MySQL
33
33
 
34
- def initialize(connection, logger, config)
35
- super(connection, logger, nil, config)
34
+ def initialize(connection, logger, connection_parameters, config)
35
+ super
36
36
  @prepared_statements = false unless config.key?(:prepared_statements)
37
37
  # configure_connection taken care of at ArJdbc::Abstract::Core
38
38
  end
@@ -13,11 +13,14 @@ ArJdbc::ConnectionMethods.module_eval do
13
13
  driver = config[:driver] ||=
14
14
  defined?(::Jdbc::MySQL.driver_name) ? ::Jdbc::MySQL.driver_name : 'com.mysql.jdbc.Driver'
15
15
 
16
+ mysql_driver = driver.start_with?('com.mysql.')
17
+ mariadb_driver = ! mysql_driver && driver.start_with?('org.mariadb.')
18
+
16
19
  begin
17
20
  require 'jdbc/mysql'
18
21
  ::Jdbc::MySQL.load_driver(:require) if defined?(::Jdbc::MySQL.load_driver)
19
22
  rescue LoadError # assuming driver.jar is on the class-path
20
- end if mysql_driver = driver[0, 10] == 'com.mysql.'
23
+ end if mysql_driver
21
24
 
22
25
  config[:username] = 'root' unless config.key?(:username)
23
26
  # jdbc:mysql://[host][,failoverhost...][:port]/[database]
@@ -25,12 +28,12 @@ ArJdbc::ConnectionMethods.module_eval do
25
28
  # - if the port is not specified, it defaults to 3306
26
29
  # - alternate fail-over syntax: [host:port],[host:port]/[database]
27
30
  unless config[:url]
28
- host = config[:host]; host = host.join(',') if host.respond_to?(:join)
31
+ host = config[:host]
32
+ host ||= 'localhost' if mariadb_driver
33
+ host = host.join(',') if host.respond_to?(:join)
29
34
  config[:url] = "jdbc:mysql://#{host}#{ config[:port] ? ":#{config[:port]}" : nil }/#{config[:database]}"
30
35
  end
31
36
 
32
- mariadb_driver = ! mysql_driver && driver.start_with?('org.mariadb.')
33
-
34
37
  properties = ( config[:properties] ||= {} )
35
38
  if mysql_driver
36
39
  properties['zeroDateTimeBehavior'] ||= 'convertToNull'
@@ -63,8 +66,8 @@ ArJdbc::ConnectionMethods.module_eval do
63
66
  end
64
67
  if config[:sslkey] || sslcert = config[:sslcert] # || config[:use_ssl]
65
68
  properties['useSSL'] ||= true # supported by MariaDB as well
66
- properties['requireSSL'] ||= true if mysql_driver
67
69
  if mysql_driver
70
+ properties['requireSSL'] ||= true
68
71
  properties['clientCertificateKeyStoreUrl'] ||= java.io.File.new(sslcert).to_url.to_s if sslcert
69
72
  if sslca = config[:sslca]
70
73
  properties['trustCertificateKeyStoreUrl'] ||= java.io.File.new(sslca).to_url.to_s
@@ -52,8 +52,30 @@ module ArJdbc
52
52
  @postgresql_version ||=
53
53
  begin
54
54
  version = @connection.database_product
55
- if version =~ /PostgreSQL (\d+)\.(\d+)\.(\d+)/
56
- ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i
55
+ if match = version.match(/([\d\.]*\d).*?/)
56
+ version = match[1].split('.').map(&:to_i)
57
+ # PostgreSQL version representation does not have more than 4 digits
58
+ # From version 10 onwards, PG has changed its versioning policy to
59
+ # limit it to only 2 digits. i.e. in 10.x, 10 being the major
60
+ # version and x representing the patch release
61
+ # Refer to:
62
+ # https://www.postgresql.org/support/versioning/
63
+ # https://www.postgresql.org/docs/10/static/libpq-status.html -> PQserverVersion()
64
+ # for more info
65
+
66
+ if version.size >= 3
67
+ (version[0] * 100 + version[1]) * 100 + version[2]
68
+ elsif version.size == 2
69
+ if version[0] >= 10
70
+ version[0] * 100 * 100 + version[1]
71
+ else
72
+ (version[0] * 100 + version[1]) * 100
73
+ end
74
+ elsif version.size == 1
75
+ version[0] * 100 * 100
76
+ else
77
+ 0
78
+ end
57
79
  else
58
80
  0
59
81
  end
@@ -214,12 +236,16 @@ module ArJdbc
214
236
 
215
237
  def supports_ddl_transactions?; true end
216
238
 
239
+ def supports_advisory_locks?; true end
240
+
217
241
  def supports_explain?; true end
218
242
 
219
243
  def supports_expression_index?; true end
220
244
 
221
245
  def supports_foreign_keys?; true end
222
246
 
247
+ def supports_validate_constraints?; true end
248
+
223
249
  def supports_index_sort_order?; true end
224
250
 
225
251
  def supports_partial_index?; true end
@@ -230,6 +256,12 @@ module ArJdbc
230
256
 
231
257
  def supports_views?; true end
232
258
 
259
+ def supports_bulk_alter?; true end
260
+
261
+ def supports_datetime_with_precision?; true end
262
+
263
+ def supports_comments?; true end
264
+
233
265
  # Does PostgreSQL support standard conforming strings?
234
266
  def supports_standard_conforming_strings?
235
267
  standard_conforming_strings?
@@ -244,6 +276,14 @@ module ArJdbc
244
276
  postgresql_version >= 90000
245
277
  end
246
278
 
279
+ def supports_materialized_views?
280
+ postgresql_version >= 90300
281
+ end
282
+
283
+ def supports_json?
284
+ postgresql_version >= 90200
285
+ end
286
+
247
287
  def supports_insert_with_returning?
248
288
  postgresql_version >= 80200
249
289
  end
@@ -377,6 +417,12 @@ module ArJdbc
377
417
  @connection.configure_connection
378
418
  end
379
419
 
420
+ def default_sequence_name(table_name, pk = "id") #:nodoc:
421
+ serial_sequence(table_name, pk)
422
+ rescue ActiveRecord::StatementInvalid
423
+ %Q("#{table_name}_#{pk}_seq")
424
+ end
425
+
380
426
  def last_insert_id_result(sequence_name)
381
427
  exec_query("SELECT currval('#{sequence_name}')", 'SQL')
382
428
  end
@@ -590,6 +636,8 @@ module ArJdbc
590
636
  end
591
637
 
592
638
  def translate_exception(exception, message)
639
+ return super unless exception.is_a?(ActiveRecord::JDBCError)
640
+
593
641
  # TODO: Can we base these on an error code of some kind?
594
642
  case exception.message
595
643
  when /duplicate key value violates unique constraint/
@@ -680,12 +728,12 @@ module ActiveRecord::ConnectionAdapters
680
728
  # AR expects OID to be available on the adapter
681
729
  OID = ActiveRecord::ConnectionAdapters::PostgreSQL::OID
682
730
 
683
- def initialize(connection, logger = nil, config = {})
731
+ def initialize(connection, logger = nil, connection_parameters = nil, config = {})
684
732
  # @local_tz is initialized as nil to avoid warnings when connect tries to use it
685
733
  @local_tz = nil
686
734
  @max_identifier_length = nil
687
735
 
688
- super # configure_connection happens in super
736
+ super(connection, logger, config) # configure_connection happens in super
689
737
 
690
738
  @type_map = Type::HashLookupTypeMap.new
691
739
  initialize_type_map
@@ -698,19 +746,14 @@ module ActiveRecord::ConnectionAdapters
698
746
  Arel::Visitors::PostgreSQL.new(self)
699
747
  end
700
748
 
701
- def exec_query(sql, name = nil, binds = [], prepare: false)
702
- super
703
- rescue ActiveRecord::StatementInvalid => e
704
- raise unless e.cause.message.include?('cached plan must not change result type'.freeze)
749
+ require 'active_record/connection_adapters/postgresql/schema_definitions'
705
750
 
706
- if open_transactions > 0
707
- # In a transaction, have to fail it - See AR code for details
708
- raise ActiveRecord::PreparedStatementCacheExpired.new(e.cause.message)
709
- else
710
- # Not in a transaction, clear the prepared statement and try again
711
- delete_cached_statement(sql)
712
- retry
713
- end
751
+ ColumnMethods = ActiveRecord::ConnectionAdapters::PostgreSQL::ColumnMethods
752
+ TableDefinition = ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition
753
+ Table = ActiveRecord::ConnectionAdapters::PostgreSQL::Table
754
+
755
+ def create_table_definition(*args) # :nodoc:
756
+ TableDefinition.new(*args)
714
757
  end
715
758
 
716
759
  public :sql_for_insert
@@ -51,8 +51,15 @@ ArJdbc::ConnectionMethods.module_eval do
51
51
  properties['tcpKeepAlive'] ||= config[:keepalives] if config.key?(:keepalives)
52
52
  properties['kerberosServerName'] ||= config[:krbsrvname] if config[:krbsrvname]
53
53
 
54
- # If prepared statements are off, lets make sure they are really *off*
55
- properties['prepareThreshold'] ||= 0 unless config[:prepared_statements]
54
+ prepared_statements = config.fetch(:prepared_statements) { true }
55
+ prepared_statements = false if prepared_statements == 'false'
56
+ if prepared_statements
57
+ # this makes the pgjdbc driver handle hot compatibility internally
58
+ properties['autosave'] ||= 'conservative'
59
+ else
60
+ # If prepared statements are off, lets make sure they are really *off*
61
+ properties['prepareThreshold'] = 0
62
+ end
56
63
 
57
64
  jdbc_connection(config)
58
65
  end
@@ -81,7 +81,7 @@ module ArJdbc
81
81
  register_class_with_limit m, 'bit', OID::Bit
82
82
  register_class_with_limit m, 'varbit', OID::BitVarying
83
83
  m.alias_type 'timestamptz', 'timestamp'
84
- m.register_type 'date', Type::Date.new
84
+ m.register_type 'date', OID::Date.new
85
85
 
86
86
  m.register_type 'money', OID::Money.new
87
87
  m.register_type 'bytea', OID::Bytea.new
@@ -168,6 +168,7 @@ module ArJdbc
168
168
  ActiveRecord::Type.register(:bit_varying, OID::BitVarying, adapter: :postgresql)
169
169
  ActiveRecord::Type.register(:binary, OID::Bytea, adapter: :postgresql)
170
170
  ActiveRecord::Type.register(:cidr, OID::Cidr, adapter: :postgresql)
171
+ ActiveRecord::Type.register(:date, OID::Date, adapter: :postgresql)
171
172
  ActiveRecord::Type.register(:datetime, OID::DateTime, adapter: :postgresql)
172
173
  ActiveRecord::Type.register(:decimal, OID::Decimal, adapter: :postgresql)
173
174
  ActiveRecord::Type.register(:enum, OID::Enum, adapter: :postgresql)
@@ -62,8 +62,7 @@ module ArJdbc
62
62
  end
63
63
  end
64
64
 
65
- # DIFFERENCE: we remove connection_options because we are not using it.
66
- def initialize(connection, logger, config)
65
+ def initialize(connection, logger, connection_options, config)
67
66
  super(connection, logger, config)
68
67
 
69
68
  @active = true
@@ -1,52 +1,33 @@
1
1
  module ArJdbc
2
2
  module Tasks
3
3
 
4
- if defined? ActiveRecord::Tasks::DatabaseTasks # AR-4.x
5
-
6
- def self.register_tasks(pattern, task)
7
- ActiveRecord::Tasks::DatabaseTasks.register_task(pattern, task)
8
- end
9
-
10
- # support adapter: mariadb (as if it were mysql)
11
- register_tasks(/mariadb/, ActiveRecord::Tasks::MySQLDatabaseTasks)
12
-
13
- else
14
-
15
- @@tasks = {}
16
-
17
- def self.register_tasks(pattern, task)
18
- @@tasks[pattern] = task
19
- end
20
-
21
- def self.tasks_instance(config)
22
- adapter = config['adapter']
23
- key = @@tasks.keys.detect { |pattern| adapter[pattern] }
24
- ( @@tasks[key] || JdbcDatabaseTasks ).new(config)
25
- end
26
-
4
+ def self.register_tasks(pattern, task)
5
+ ActiveRecord::Tasks::DatabaseTasks.register_task(pattern, task)
27
6
  end
28
7
 
8
+ # support adapter: mariadb (as if it were mysql)
9
+ register_tasks(/mariadb/, ActiveRecord::Tasks::MySQLDatabaseTasks)
10
+
29
11
  require 'arjdbc/tasks/jdbc_database_tasks'
30
- require 'arjdbc/tasks/db2_database_tasks'
31
- require 'arjdbc/tasks/derby_database_tasks'
32
- require 'arjdbc/tasks/h2_database_tasks'
33
- require 'arjdbc/tasks/hsqldb_database_tasks'
34
- require 'arjdbc/tasks/mssql_database_tasks'
12
+ require 'arjdbc/tasks/sqlite_database_tasks_patch'
13
+ #require 'arjdbc/tasks/db2_database_tasks'
14
+ #require 'arjdbc/tasks/derby_database_tasks'
15
+ #require 'arjdbc/tasks/h2_database_tasks'
16
+ #require 'arjdbc/tasks/hsqldb_database_tasks'
17
+ #require 'arjdbc/tasks/mssql_database_tasks'
35
18
 
36
19
  # re-invent built-in (but deprecated on 4.0) tasks :
37
- register_tasks(/sqlserver/, MSSQLDatabaseTasks)
38
- register_tasks(/mssql/, MSSQLDatabaseTasks) # (built-in) alias
20
+ #register_tasks(/sqlserver/, MSSQLDatabaseTasks)
21
+ #register_tasks(/mssql/, MSSQLDatabaseTasks) # (built-in) alias
39
22
  # tasks for custom (JDBC) adapters :
40
- register_tasks(/db2/, DB2DatabaseTasks)
41
- register_tasks(/derby/, DerbyDatabaseTasks)
42
- register_tasks(/h2/, H2DatabaseTasks)
43
- register_tasks(/hsqldb/, HSQLDBDatabaseTasks)
23
+ #register_tasks(/db2/, DB2DatabaseTasks)
24
+ #register_tasks(/derby/, DerbyDatabaseTasks)
25
+ #register_tasks(/h2/, H2DatabaseTasks)
26
+ #register_tasks(/hsqldb/, HSQLDBDatabaseTasks)
44
27
  # (default) generic JDBC task :
45
28
  register_tasks(/^jdbc$/, JdbcDatabaseTasks)
46
29
 
47
30
  # NOTE: no need to register "built-in" adapters such as MySQL
48
- # - on 4.0 these are registered and will be instantiated
49
- # - while on 2.3/3.x we keep the AR built-in task behavior
50
31
 
51
32
  end
52
33
  end
@@ -1,91 +1,48 @@
1
- raise "ArJdbc needs rake 0.9.x or newer" unless Rake.const_defined?(:VERSION)
2
-
3
- Rake::DSL.module_eval do
4
-
5
- def redefine_task(*args, &block)
6
- if Hash === args.first
7
- task_name = args.first.keys[0]
8
- old_prereqs = false # leave as specified
9
- else
10
- task_name = args.first; old_prereqs = []
11
- # args[0] = { task_name => old_prereqs }
12
- end
13
-
14
- full_name = Rake::Task.scope_name(Rake.application.current_scope, task_name)
15
-
16
- if old_task = Rake.application.lookup(task_name)
17
- old_comment = old_task.full_comment
18
- old_prereqs = old_task.prerequisites.dup if old_prereqs
19
- old_actions = old_task.actions.dup
20
- old_actions.shift # remove the main 'action' block - we're redefining it
21
- # old_task.clear_prerequisites if old_prereqs
22
- # old_task.clear_actions
23
- # remove the (old) task instance from the application :
24
- Rake.application.send(:instance_variable_get, :@tasks)[full_name.to_s] = nil
25
- else
26
- # raise "could not find rake task with (full) name '#{full_name}'"
27
- end
28
-
29
- new_task = task(*args, &block)
30
- new_task.comment = old_comment if old_comment
31
- new_task.actions.concat(old_actions) if old_actions
32
- new_task.prerequisites.concat(old_prereqs) if old_prereqs
33
- new_task
34
- end
35
-
36
- end
37
-
38
- namespace :db do
39
-
40
- def rails_env
41
- defined?(Rails.env) ? Rails.env : ( RAILS_ENV || 'development' )
42
- end
1
+ require 'arjdbc/tasks/database_tasks'
43
2
 
44
- if defined? adapt_jdbc_config
45
- ArJdbc.warn "double loading #{__FILE__} please delete lib/tasks/jdbc.rake if present!"
46
- end
3
+ module ActiveRecord::Tasks
47
4
 
48
- def adapt_jdbc_config(config)
49
- return config unless config['adapter']
50
- config.merge 'adapter' => config['adapter'].sub(/^jdbc/, '')
51
- end
5
+ DatabaseTasks.module_eval do
52
6
 
53
- if defined? ActiveRecord::Tasks::DatabaseTasks # 4.0
7
+ # @override patched to adapt jdbc configuration
8
+ def each_current_configuration(environment)
9
+ environments = [environment]
10
+ environments << 'test' if environment == 'development'
54
11
 
55
- def current_config(options = {})
56
- ActiveRecord::Tasks::DatabaseTasks.current_config(options)
12
+ configurations = ActiveRecord::Base.configurations.values_at(*environments)
13
+ configurations.compact.each do |config|
14
+ yield adapt_jdbc_config(config) unless config['database'].blank?
15
+ end
57
16
  end
58
17
 
59
- else # 3.x / 2.3
18
+ # @override patched to adapt jdbc configuration
19
+ def each_local_configuration
20
+ ActiveRecord::Base.configurations.each_value do |config|
21
+ next unless config['database']
60
22
 
61
- def current_config(options = {}) # not on 2.3
62
- options = { :env => rails_env }.merge! options
63
- if options[:config]
64
- @current_config = options[:config]
65
- else
66
- @current_config ||= ENV['DATABASE_URL'] ?
67
- database_url_config : ActiveRecord::Base.configurations[options[:env]]
23
+ if local_database?(config)
24
+ yield adapt_jdbc_config(config)
25
+ else
26
+ $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."
27
+ end
68
28
  end
69
29
  end
70
30
 
71
- def database_url_config(url = ENV['DATABASE_URL'])
72
- # NOTE: ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver
73
- # since AR 4.0 that is handled by DatabaseTasks - only care about 2.3/3.x :
74
- unless defined? ActiveRecord::Base::ConnectionSpecification::Resolver
75
- raise "DATABASE_URL not supported on ActiveRecord #{ActiveRecord::VERSION::STRING}"
76
- end
77
- resolver = ActiveRecord::Base::ConnectionSpecification::Resolver.new(url, {})
78
- resolver.spec.config.stringify_keys
31
+ private
32
+
33
+ def adapt_jdbc_config(config)
34
+ return config unless config['adapter']
35
+ config.merge 'adapter' => config['adapter'].sub(/^jdbc/, '')
79
36
  end
80
37
 
81
38
  end
82
39
 
83
- end
40
+ MySQLDatabaseTasks.class_eval do
84
41
 
85
- require 'arjdbc/tasks/database_tasks'
42
+ def error_class
43
+ ActiveRecord::JDBCError
44
+ end
45
+
46
+ end if const_defined?(:MySQLDatabaseTasks)
86
47
 
87
- if defined? ActiveRecord::Tasks::DatabaseTasks # 4.0
88
- load File.expand_path('databases4.rake', File.dirname(__FILE__))
89
- else # 3.x / 2.3
90
- load File.expand_path('databases3.rake', File.dirname(__FILE__))
91
- end
48
+ end
@@ -0,0 +1,17 @@
1
+ # patch SQLiteDatabaseTasks for JRuby
2
+ # The problem is that JRuby does not yet support the "out:" option for
3
+ # Kernel.system(). Uses plain output redirection as a workaround.
4
+
5
+ require 'active_record/tasks/sqlite_database_tasks'
6
+ require 'shellwords'
7
+
8
+ module ActiveRecord
9
+ module Tasks
10
+ class SQLiteDatabaseTasks
11
+ private
12
+ def run_cmd(cmd, args, out)
13
+ `#{cmd} #{Shellwords.join(args)} > "#{out}"`
14
+ end
15
+ end
16
+ end
17
+ end
@@ -1,3 +1,3 @@
1
1
  module ArJdbc
2
- VERSION = '52.0'
2
+ VERSION = '52.1'
3
3
  end
@@ -4,25 +4,35 @@ namespace :db do
4
4
  task :mysql do
5
5
  require File.expand_path('../../test/shared_helper', __FILE__)
6
6
  fail "could not create test database: mysql executable not found" unless mysql = which('mysql')
7
+
7
8
  load 'test/db/mysql_config.rb' # rescue nil
8
9
  enc = MYSQL_CONFIG[:encoding] || 'utf8' # 'utf8mb4'
9
10
  puts MYSQL_CONFIG.inspect if $VERBOSE
10
- # DROP USER arjdbc@localhost; __ERROR 1396 (HY000): Operation CREATE USER failed__
11
+
12
+ clean_script = sql_script <<-SQL, 'mysqlclean'
13
+ DROP USER #{MYSQL_CONFIG[:username]}@localhost;
14
+ SQL
15
+
11
16
  script = sql_script <<-SQL, 'mysql'
12
17
  DROP DATABASE IF EXISTS `#{MYSQL_CONFIG[:database]}`;
13
18
  CREATE DATABASE `#{MYSQL_CONFIG[:database]}` DEFAULT CHARACTER SET `#{enc}` COLLATE `#{enc}_general_ci`;
19
+ CREATE USER #{MYSQL_CONFIG[:username]}@localhost IDENTIFIED BY '#{MYSQL_CONFIG[:password]}';
14
20
  GRANT ALL PRIVILEGES ON `#{MYSQL_CONFIG[:database]}`.* TO #{MYSQL_CONFIG[:username]}@localhost;
15
21
  GRANT ALL PRIVILEGES ON `test\_%`.* TO #{MYSQL_CONFIG[:username]}@localhost;
16
- SET PASSWORD FOR #{MYSQL_CONFIG[:username]}@localhost = PASSWORD('#{MYSQL_CONFIG[:password]}');
17
22
  SQL
23
+
18
24
  params = { '-u' => 'root' }
19
- if ENV['DATABASE_YML']; require 'yaml'
20
- params['-p'] = YAML.load(File.new(ENV['DATABASE_YML']))["production"]["password"]
25
+ if ENV['DATABASE_YML']
26
+ require 'yaml'
27
+ params['-p'] = YAML.load(File.new(ENV['DATABASE_YML']))["production"]["password"]
21
28
  end
22
29
  params['-u'] = ENV['MY_USER'] if ENV['MY_USER']
23
30
  params['-p'] = ENV['MY_PASSWORD'] if ENV['MY_PASSWORD']
31
+
24
32
  puts "Creating MySQL (test) database: #{MYSQL_CONFIG[:database]}"
25
- sh "cat #{script.path} | #{mysql} -f #{params.map {|k, v| "#{k}#{v}"}.join(' ')}", :verbose => $VERBOSE # so password is not echoed
33
+ mysql_cmd = "#{mysql} -f #{params.map {|k, v| "#{k}#{v}"}.join(' ')}"
34
+ sh "cat #{clean_script.path} | #{mysql_cmd}", verbose: false
35
+ sh "cat #{script.path} | #{mysql_cmd}", verbose: $VERBOSE # so password is not echoed
26
36
  end
27
37
 
28
38
  desc "Creates the test database for PostgreSQL"
@@ -30,8 +40,10 @@ SET PASSWORD FOR #{MYSQL_CONFIG[:username]}@localhost = PASSWORD('#{MYSQL_CONFIG
30
40
  require File.expand_path('../../test/shared_helper', __FILE__)
31
41
  fail 'could not create test database: psql executable not found' unless psql = which('psql')
32
42
  fail 'could not create test database: missing "postgres" role' unless PostgresHelper.postgres_role?
43
+
33
44
  load 'test/db/postgres_config.rb' # rescue nil
34
45
  puts POSTGRES_CONFIG.inspect if $VERBOSE
46
+
35
47
  script = sql_script <<-SQL, 'psql'
36
48
  DROP DATABASE IF EXISTS #{POSTGRES_CONFIG[:database]};
37
49
  DROP USER IF EXISTS #{POSTGRES_CONFIG[:username]};
@@ -40,12 +52,14 @@ CREATE DATABASE #{POSTGRES_CONFIG[:database]} OWNER #{POSTGRES_CONFIG[:username]
40
52
  TEMPLATE template0
41
53
  ENCODING '#{POSTGRES_CONFIG[:encoding]}' LC_COLLATE '#{POSTGRES_CONFIG[:collate]}' LC_CTYPE '#{POSTGRES_CONFIG[:collate]}';
42
54
  SQL
55
+
43
56
  params = { '-U' => ENV['PSQL_USER'] || 'postgres' }
44
57
  params['-q'] = nil unless $VERBOSE
58
+
45
59
  puts "Creating PostgreSQL (test) database: #{POSTGRES_CONFIG[:database]}"
46
- sh "cat #{script.path} | #{psql} #{params.to_a.join(' ')}", :verbose => $VERBOSE
60
+ sh "cat #{script.path} | #{psql} #{params.to_a.join(' ')}", verbose: $VERBOSE
47
61
  end
48
- task :postgres => :postgresql
62
+ task postgres: :postgresql
49
63
 
50
64
  private
51
65
 
@@ -2898,7 +2898,7 @@ public class RubyJdbcConnection extends RubyObject {
2898
2898
  final RubySymbol type = (RubySymbol) attributeSQLType(context, attribute);
2899
2899
 
2900
2900
  // For some reason the driver doesn't like "character varying" as a type
2901
- if ( type.eql(context.runtime.newSymbol("string")) ) return "text";
2901
+ if ( type.eql(context.runtime.newSymbol("string")) ) return "varchar";
2902
2902
 
2903
2903
  final RubyHash nativeTypes = (RubyHash) getAdapter().callMethod(context, "native_database_types");
2904
2904
  // e.g. `integer: { name: 'integer' }`
@@ -3445,12 +3445,14 @@ public class RubyJdbcConnection extends RubyObject {
3445
3445
  if ( ! gotConnection ) { // SQLException from driver/data-source
3446
3446
  reconnectOnRetry = connected;
3447
3447
  }
3448
+ else if (!autoCommit) {
3449
+ // never retry inside a transaction
3450
+ break;
3451
+ }
3448
3452
  else if ( isTransient(exception) ) {
3449
3453
  reconnectOnRetry = false; // continue;
3450
3454
  }
3451
3455
  else {
3452
- if ( ! autoCommit ) break; // do not retry if (inside) transactions
3453
-
3454
3456
  if ( isConnectionValid(context, getConnectionImpl()) ) {
3455
3457
  break; // connection not broken yet failed (do not retry)
3456
3458
  }
@@ -55,6 +55,7 @@ import org.joda.time.DateTimeZone;
55
55
  import org.jruby.*;
56
56
  import org.jruby.anno.JRubyMethod;
57
57
  import org.jruby.exceptions.RaiseException;
58
+ import org.jruby.ext.bigdecimal.RubyBigDecimal;
58
59
  import org.jruby.javasupport.JavaUtil;
59
60
  import org.jruby.runtime.ObjectAllocator;
60
61
  import org.jruby.runtime.ThreadContext;
@@ -100,6 +101,7 @@ public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection
100
101
  POSTGRES_JDBC_TYPE_FOR.put("line", Types.OTHER);
101
102
  POSTGRES_JDBC_TYPE_FOR.put("lseg", Types.OTHER);
102
103
  POSTGRES_JDBC_TYPE_FOR.put("ltree", Types.OTHER);
104
+ POSTGRES_JDBC_TYPE_FOR.put("money", Types.OTHER);
103
105
  POSTGRES_JDBC_TYPE_FOR.put("numrange", Types.OTHER);
104
106
  POSTGRES_JDBC_TYPE_FOR.put("path", Types.OTHER);
105
107
  POSTGRES_JDBC_TYPE_FOR.put("point", Types.OTHER);
@@ -374,12 +376,26 @@ public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection
374
376
  final int index, IRubyObject value,
375
377
  final IRubyObject attribute, final int type) throws SQLException {
376
378
 
379
+ if ( value instanceof RubyFloat ) {
380
+ final double doubleValue = ( (RubyFloat) value ).getValue();
381
+ if ( Double.isInfinite(doubleValue) ) {
382
+ setTimestampInfinity(statement, index, doubleValue);
383
+ return;
384
+ }
385
+ }
386
+
377
387
  if ( ! "Date".equals(value.getMetaClass().getName()) && value.respondsTo("to_date") ) {
378
388
  value = value.callMethod(context, "to_date");
379
389
  }
380
390
 
381
- // NOTE: assuming Date#to_s does right ...
382
- statement.setDate(index, Date.valueOf(value.toString()));
391
+ int year = RubyNumeric.num2int(value.callMethod(context, "year"));
392
+ int month = RubyNumeric.num2int(value.callMethod(context, "month"));
393
+ int day = RubyNumeric.num2int(value.callMethod(context, "day"));
394
+
395
+ @SuppressWarnings("deprecated")
396
+ Date date = new Date(year - 1900, month - 1, day);
397
+
398
+ statement.setDate(index, date);
383
399
  }
384
400
 
385
401
  @Override
@@ -441,6 +457,14 @@ public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection
441
457
  }
442
458
  break;
443
459
 
460
+ case "money":
461
+ if (value instanceof RubyBigDecimal) {
462
+ statement.setBigDecimal(index, ((RubyBigDecimal) value).getValue());
463
+ } else {
464
+ setPGobjectParameter(statement, index, value, columnType);
465
+ }
466
+ break;
467
+
444
468
  case "lseg":
445
469
  pointValues = parseDoubles(value);
446
470
  statement.setObject(index, new PGlseg(pointValues[0], pointValues[1], pointValues[2], pointValues[3]));
@@ -690,8 +714,16 @@ public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection
690
714
  protected IRubyObject dateToRuby(ThreadContext context, Ruby runtime, ResultSet resultSet, int index) throws SQLException {
691
715
  // NOTE: PostgreSQL adapter under MRI using pg gem returns UTC-d Date/Time values
692
716
  final String value = resultSet.getString(index);
717
+ if (value == null) return context.nil;
718
+
719
+ final int len = value.length();
720
+ if (len < 10 && value.charAt(len - 1) == 'y') { // infinity / -infinity
721
+ IRubyObject infinity = parseInfinity(context.runtime, value);
722
+
723
+ if (infinity != null) return infinity;
724
+ }
693
725
 
694
- return value == null ? context.nil : DateTimeUtils.parseDate(context, value, getDefaultTimeZone(context));
726
+ return DateTimeUtils.parseDate(context, value, getDefaultTimeZone(context));
695
727
  }
696
728
 
697
729
 
@@ -30,6 +30,7 @@ import java.util.TimeZone;
30
30
 
31
31
  import org.joda.time.DateTime;
32
32
  import org.joda.time.DateTimeZone;
33
+ import org.joda.time.chrono.GJChronology;
33
34
  import org.joda.time.chrono.ISOChronology;
34
35
  import org.jruby.Ruby;
35
36
  import org.jruby.RubyFloat;
@@ -303,19 +304,24 @@ public abstract class DateTimeUtils {
303
304
  // month
304
305
  end = nonDigitIndex(str, start, len);
305
306
  month = extractIntValue(str, start, end);
306
-
307
- //sep = str.charAt(end);
308
- //if ( sep != '-' ) {
309
- // throw new NumberFormatException("expected date to be dash-separated, got '" + sep + "'");
310
- //}
311
-
312
307
  start = end + 1; // Skip '-'
313
308
 
314
309
  // day of month
315
310
  end = nonDigitIndex(str, start, len);
316
311
  day = extractIntValue(str, start, end);
317
312
 
318
- return newDate(context, year, month, day, ISOChronology.getInstance(defaultZone));
313
+ start = end + 1; // Skip possible space
314
+ boolean bcEra = false;
315
+ if ( start + 1 < len ) {
316
+ final char e1 = str.charAt(start);
317
+ if ( e1 == 'B' && str.charAt(start + 1) == 'C' ) bcEra = true;
318
+ }
319
+
320
+ if ( bcEra ) year = -1 * year; // no + 1 since we use GJChronology
321
+
322
+ DateTime dateTime = new DateTime(year, month, day, 0, 0, 0, GJChronology.getInstance(defaultZone));
323
+ final Ruby runtime = context.runtime;
324
+ return runtime.getClass("Date").newInstance(context, Java.getInstance(runtime, dateTime), Block.NULL_BLOCK);
319
325
  }
320
326
 
321
327
  public static IRubyObject parseTime(final ThreadContext context, final CharSequence str, final DateTimeZone defaultZone)
metadata CHANGED
@@ -1,24 +1,24 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activerecord-jdbc-adapter
3
3
  version: !ruby/object:Gem::Version
4
- version: '52.0'
4
+ version: '52.1'
5
5
  platform: java
6
6
  authors:
7
7
  - Nick Sieger, Ola Bini, Karol Bucek and JRuby contributors
8
- autorequire:
8
+ autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2018-08-13 00:00:00.000000000 Z
11
+ date: 2018-09-13 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
- name: activerecord
15
14
  requirement: !ruby/object:Gem::Requirement
16
15
  requirements:
17
16
  - - "~>"
18
17
  - !ruby/object:Gem::Version
19
18
  version: 5.2.0
20
- type: :runtime
19
+ name: activerecord
21
20
  prerelease: false
21
+ type: :runtime
22
22
  version_requirements: !ruby/object:Gem::Requirement
23
23
  requirements:
24
24
  - - "~>"
@@ -119,7 +119,6 @@ files:
119
119
  - lib/arjdbc/jdbc/error.rb
120
120
  - lib/arjdbc/jdbc/extension.rb
121
121
  - lib/arjdbc/jdbc/java.rb
122
- - lib/arjdbc/jdbc/jdbc.rake
123
122
  - lib/arjdbc/jdbc/railtie.rb
124
123
  - lib/arjdbc/jdbc/rake_tasks.rb
125
124
  - lib/arjdbc/jdbc/serialized_attributes_helper.rb
@@ -157,14 +156,13 @@ files:
157
156
  - lib/arjdbc/tasks.rb
158
157
  - lib/arjdbc/tasks/database_tasks.rb
159
158
  - lib/arjdbc/tasks/databases.rake
160
- - lib/arjdbc/tasks/databases3.rake
161
- - lib/arjdbc/tasks/databases4.rake
162
159
  - lib/arjdbc/tasks/db2_database_tasks.rb
163
160
  - lib/arjdbc/tasks/derby_database_tasks.rb
164
161
  - lib/arjdbc/tasks/h2_database_tasks.rb
165
162
  - lib/arjdbc/tasks/hsqldb_database_tasks.rb
166
163
  - lib/arjdbc/tasks/jdbc_database_tasks.rb
167
164
  - lib/arjdbc/tasks/mssql_database_tasks.rb
165
+ - lib/arjdbc/tasks/sqlite_database_tasks_patch.rb
168
166
  - lib/arjdbc/util/quoted_cache.rb
169
167
  - lib/arjdbc/util/serialized_attributes.rb
170
168
  - lib/arjdbc/util/table_copier.rb
@@ -181,7 +179,6 @@ files:
181
179
  - rakelib/01-tomcat.rake
182
180
  - rakelib/02-test.rake
183
181
  - rakelib/bundler_ext.rb
184
- - rakelib/compile.rake
185
182
  - rakelib/db.rake
186
183
  - rakelib/rails.rake
187
184
  - src/java/arjdbc/ArJdbcModule.java
@@ -225,7 +222,7 @@ homepage: https://github.com/jruby/activerecord-jdbc-adapter
225
222
  licenses:
226
223
  - BSD-2-Clause
227
224
  metadata: {}
228
- post_install_message:
225
+ post_install_message:
229
226
  rdoc_options:
230
227
  - "--main"
231
228
  - README.md
@@ -245,9 +242,9 @@ required_rubygems_version: !ruby/object:Gem::Requirement
245
242
  - !ruby/object:Gem::Version
246
243
  version: '0'
247
244
  requirements: []
248
- rubyforge_project:
249
- rubygems_version: 2.7.6
250
- signing_key:
245
+ rubyforge_project:
246
+ rubygems_version: 2.6.14.1
247
+ signing_key:
251
248
  specification_version: 4
252
249
  summary: JDBC adapter for ActiveRecord, for use within JRuby on Rails.
253
250
  test_files: []
@@ -1,4 +0,0 @@
1
- load 'arjdbc/tasks.rb'
2
-
3
- require 'arjdbc'
4
- ArJdbc.deprecate "load 'arjdbc/tasks.rb' (or 'arjdbc/tasks/database.rake') instead of 'arjdbc/jdbc/jdbc.rake'"
@@ -1,215 +0,0 @@
1
- module ArJdbc
2
- module Tasks
3
- class << self
4
-
5
- # API similar to ActiveRecord::Tasks::DatabaseTasks on AR 4.0
6
-
7
- def create(config)
8
- tasks_instance(config).create
9
- end
10
-
11
- def drop(config)
12
- tasks_instance(config).drop
13
- end
14
-
15
- def purge(config)
16
- tasks_instance(config).purge
17
- end
18
-
19
- def charset(config)
20
- tasks_instance(config).charset
21
- end
22
-
23
- def collation(config)
24
- tasks_instance(config).collation
25
- end
26
-
27
- def structure_dump(config, filename)
28
- tasks_instance(config).structure_dump(filename)
29
- end
30
-
31
- def structure_load(config, filename)
32
- tasks_instance(config).structure_load(filename)
33
- end
34
-
35
- end
36
- end
37
- end
38
-
39
- namespace :db do
40
-
41
- class << self
42
- alias_method :_rails_create_database, :create_database
43
- alias_method :_rails_drop_database, :drop_database
44
- end
45
-
46
- def create_database(config)
47
- case config['adapter']
48
- when /mysql2/
49
- unless defined? Mysql2::Error
50
- # NOTE: fake it for create_database(config)
51
- Object.const_set :Mysql2, Module.new
52
- Mysql2.const_set :Error, ActiveRecord::JDBCError
53
- ActiveRecord::JDBCError.class_eval do
54
- def error; self end # Mysql2::Error#error
55
- end
56
- end
57
- _rails_create_database adapt_jdbc_config(config)
58
- when /mysql/
59
- unless defined? Mysql::Error
60
- # NOTE: fake it for create_database(config)
61
- Object.const_set :Mysql, Module.new
62
- Mysql.const_set :Error, ActiveRecord::JDBCError
63
- ActiveRecord::JDBCError.class_eval do
64
- def error; self end # Mysql::Error#error
65
- end
66
- end
67
- _rails_create_database adapt_jdbc_config(config)
68
- when /postgresql|sqlite/
69
- _rails_create_database adapt_jdbc_config(config)
70
- else
71
- ArJdbc::Tasks.create(config)
72
- end
73
- end
74
-
75
- def drop_database(config)
76
- case config['adapter']
77
- when /mysql|postgresql|sqlite/
78
- _rails_drop_database adapt_jdbc_config(config)
79
- else
80
- ArJdbc::Tasks.drop(config)
81
- end
82
- end
83
-
84
- redefine_task :charset do # available on 2.3
85
- ArJdbc::Tasks.charset ActiveRecord::Base.configurations[rails_env]
86
- end
87
-
88
- redefine_task :collation do # available on 2.3
89
- ArJdbc::Tasks.collation ActiveRecord::Base.configurations[rails_env]
90
- end
91
-
92
- namespace :structure do
93
-
94
- redefine_task :dump do
95
- config = ActiveRecord::Base.configurations[rails_env] # current_config
96
- filename = structure_sql
97
-
98
- case config['adapter']
99
- when /mysql/
100
- ActiveRecord::Base.establish_connection(config)
101
- File.open(filename, 'w:utf-8') { |f| f << ActiveRecord::Base.connection.structure_dump }
102
- when /postgresql/
103
- ActiveRecord::Base.establish_connection(config)
104
-
105
- ENV['PGHOST'] = config['host'] if config['host']
106
- ENV['PGPORT'] = config['port'].to_s if config['port']
107
- ENV['PGPASSWORD'] = config['password'].to_s if config['password']
108
- ENV['PGUSER'] = config['username'].to_s if config['username']
109
-
110
- require 'shellwords'
111
- search_path = config['schema_search_path']
112
- unless search_path.blank?
113
- search_path = search_path.split(",").map{ |part| "--schema=#{Shellwords.escape(part.strip)}" }.join(" ")
114
- end
115
- sh "pg_dump -i -s -x -O -f #{Shellwords.escape(filename)} #{search_path} #{Shellwords.escape(config['database'])}"
116
-
117
- File.open(filename, 'a') { |f| f << "SET search_path TO #{ActiveRecord::Base.connection.schema_search_path};\n\n" }
118
- when /sqlite/
119
- dbfile = config['database']
120
- sh "sqlite3 #{dbfile} .schema > #{filename}"
121
- else
122
- ActiveRecord::Base.establish_connection(config)
123
- ArJdbc::Tasks.structure_dump(config, filename)
124
- end
125
-
126
- if ActiveRecord::Base.connection.supports_migrations?
127
- File.open(filename, 'a') { |f| f << ActiveRecord::Base.connection.dump_schema_information }
128
- end
129
-
130
- end
131
-
132
- redefine_task :load do
133
- config = current_config
134
- filename = structure_sql
135
-
136
- case config['adapter']
137
- when /mysql/
138
- ActiveRecord::Base.establish_connection(config)
139
- ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
140
- IO.read(filename).split("\n\n").each do |table|
141
- ActiveRecord::Base.connection.execute(table)
142
- end
143
- when /postgresql/
144
- ENV['PGHOST'] = config['host'] if config['host']
145
- ENV['PGPORT'] = config['port'].to_s if config['port']
146
- ENV['PGPASSWORD'] = config['password'].to_s if config['password']
147
- ENV['PGUSER'] = config['username'].to_s if config['username']
148
-
149
- `psql -f "#{filename}" #{config['database']}`
150
- when /sqlite/
151
- dbfile = config['database']
152
- `sqlite3 #{dbfile} < "#{filename}"`
153
- else
154
- ArJdbc::Tasks.structure_load(config, filename)
155
- end
156
- end
157
-
158
- def structure_sql
159
- ENV['DB_STRUCTURE'] ||= begin
160
- root = defined?(Rails.root) ? Rails.root : ( RAILS_ROOT rescue nil )
161
- if ActiveRecord::VERSION::STRING > '3.2'
162
- root ? File.join(root, "db", "structure.sql") : File.join("db", "structure.sql")
163
- else
164
- root ? File.join(root, "db/#{rails_env}_structure.sql") : "db/#{rails_env}_structure.sql"
165
- end
166
- end
167
- end
168
-
169
- end
170
-
171
- namespace :test do
172
-
173
- # desc "Recreate the test database from an existent structure.sql file"
174
- redefine_task :load_structure => 'db:test:purge' do # not on 2.3
175
- begin
176
- current_config(:config => ActiveRecord::Base.configurations['test'])
177
- Rake::Task["db:structure:load"].invoke
178
- ensure
179
- current_config(:config => nil)
180
- end
181
- end
182
-
183
- # desc "Recreate the test database from a fresh structure.sql file"
184
- redefine_task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ]
185
- # same as on 3.2 - but this task gets changed on 2.3 by depending on :load_structure
186
-
187
- # desc "Empty the test database"
188
- redefine_task :purge do
189
- config = ActiveRecord::Base.configurations['test']
190
- case config['adapter']
191
- when /mysql/
192
- ActiveRecord::Base.establish_connection(:test)
193
- options = mysql_creation_options(config) rescue config
194
- ActiveRecord::Base.connection.recreate_database(config['database'], options)
195
- when /postgresql/
196
- ActiveRecord::Base.clear_active_connections!
197
- # drop_database(config) :
198
- ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
199
- ActiveRecord::Base.connection.drop_database config['database']
200
- # create_database(config) :
201
- encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
202
- ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => encoding))
203
- when /sqlite/
204
- dbfile = config['database']
205
- File.delete(dbfile) if File.exist?(dbfile)
206
- else
207
- ArJdbc::Tasks.purge(config)
208
- end
209
- end
210
- # only does (:purge => :environment) on AR < 3.2
211
- task :purge => :load_config if Rake::Task.task_defined?(:load_config)
212
-
213
- end
214
-
215
- end
@@ -1,39 +0,0 @@
1
- module ActiveRecord::Tasks
2
-
3
- DatabaseTasks.module_eval do
4
-
5
- # patched to adapt jdbc configuration
6
- def each_current_configuration(environment)
7
- environments = [environment]
8
- environments << 'test' if environment == 'development'
9
-
10
- configurations = ActiveRecord::Base.configurations.values_at(*environments)
11
- configurations.compact.each do |config|
12
- yield adapt_jdbc_config(config) unless config['database'].blank?
13
- end
14
- end
15
-
16
- # patched to adapt jdbc configuration
17
- def each_local_configuration
18
- ActiveRecord::Base.configurations.each_value do |config|
19
- next unless config['database']
20
-
21
- if local_database?(config)
22
- yield adapt_jdbc_config(config)
23
- else
24
- $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."
25
- end
26
- end
27
- end
28
-
29
- end
30
-
31
- MySQLDatabaseTasks.class_eval do
32
-
33
- def error_class
34
- ActiveRecord::JDBCError
35
- end
36
-
37
- end
38
-
39
- end
@@ -1,70 +0,0 @@
1
- jar_file = File.join(*%w(lib arjdbc jdbc adapter_java.jar))
2
- begin
3
- require 'ant'
4
- directory classes = "pkg/classes"
5
- CLEAN << classes
6
-
7
- driver_jars = []
8
- # PostgreSQL driver :
9
- driver_jars << Dir.glob("jdbc-postgres/lib/*.jar").sort.last
10
-
11
- file jar_file => FileList['src/java/**/*.java', 'pkg/classes'] do
12
- rm_rf FileList["#{classes}/**/*"]
13
- ant.javac :srcdir => "src/java", :destdir => "pkg/classes",
14
- :source => "7", :target => "7", :debug => true, :deprecation => true,
15
- :classpath => "${java.class.path}:${sun.boot.class.path}:#{driver_jars.join(':')}",
16
- :includeantRuntime => false
17
-
18
- ant.tstamp do |ts|
19
- ts.format(:property => 'TODAY', :pattern => 'yyyy-MM-dd HH:mm:ss')
20
- end
21
-
22
- begin
23
- require 'arjdbc/version'
24
- rescue LoadError
25
- path = File.expand_path('../lib', File.dirname(__FILE__))
26
- unless $LOAD_PATH.include?(path)
27
- $LOAD_PATH << path; retry
28
- end
29
- end
30
-
31
- gem_version = Gem::Version.create(ArJdbc::VERSION)
32
- if gem_version.segments.last == 'DEV'
33
- version = gem_version.segments[0...-1] # 1.3.0.DEV -> 1.3.0
34
- else
35
- version = gem_version.segments.dup
36
- end
37
- version = version.join('.')
38
-
39
- ant.manifest :file => 'MANIFEST.MF' do |mf|
40
- mf.attribute :name => 'Built-By', :value => '${user.name}'
41
- mf.attribute :name => 'Built-Time', :value => '${TODAY}'
42
- mf.attribute :name => 'Built-Jdk', :value => '${java.version}'
43
- mf.attribute :name => 'Built-JRuby', :value => JRUBY_VERSION
44
-
45
- mf.attribute :name => 'Specification-Title', :value => 'ActiveRecord-JDBC'
46
- mf.attribute :name => 'Specification-Version', :value => '1.3'
47
- mf.attribute :name => 'Specification-Vendor', :value => 'JRuby'
48
- mf.attribute :name => 'Implementation-Version', :value => version
49
- mf.attribute :name => 'Implementation-Vendor', :value => 'The JRuby Team'
50
- end
51
-
52
- ant.jar :basedir => "pkg/classes", :includes => "**/*.class",
53
- :destfile => jar_file, :manifest => 'MANIFEST.MF'
54
- end
55
-
56
- desc "Compile the native Java code."
57
- task :jar => jar_file
58
-
59
- namespace :jar do
60
- task :force do
61
- rm jar_file if File.exist?(jar_file)
62
- Rake::Task['jar'].invoke
63
- end
64
- end
65
-
66
- rescue LoadError
67
- task :jar do
68
- puts "Run 'jar' with JRuby to re-compile the agent extension class"
69
- end
70
- end