-
Notifications
You must be signed in to change notification settings - Fork 321
Expand file tree
/
Copy pathoracle_enhanced_adapter.rb
More file actions
1496 lines (1323 loc) · 61 KB
/
Copy pathoracle_enhanced_adapter.rb
File metadata and controls
1496 lines (1323 loc) · 61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
# oracle_enhanced_adapter.rb -- ActiveRecord adapter for Oracle 10g, 11g and 12c
#
# Authors or original oracle_adapter: Graham Jenkins, Michael Schoen
#
# Current maintainer: Raimonds Simanovskis (http://blog.rayapps.com)
#
#########################################################################
#
# See History.md for changes added to original oracle_adapter.rb
#
#########################################################################
#
# From original oracle_adapter.rb:
#
# Implementation notes:
# 1. Redefines (safely) a method in ActiveRecord to make it possible to
# implement an autonumbering solution for Oracle.
# 2. The OCI8 driver is patched to properly handle values for LONG and
# TIMESTAMP columns. The driver-author has indicated that a future
# release of the driver will obviate this patch.
# 3. LOB support is implemented through an after_save callback.
# 4. Oracle does not offer native LIMIT and OFFSET options; this
# functionality is mimiced through the use of nested selects.
# See http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:127412348064
#
# Do what you want with this code, at your own peril, but if any
# significant portion of my code remains then please acknowledge my
# contribution.
# portions Copyright 2005 Graham Jenkins
require "arel/visitors/oracle"
require "arel/visitors/oracle12"
require "active_record/connection_adapters"
require "active_record/connection_adapters/abstract_adapter"
require "active_record/connection_adapters/statement_pool"
require "active_record/connection_adapters/oracle_enhanced/deprecator"
require "active_record/connection_adapters/oracle_enhanced/connection"
require "active_record/connection_adapters/oracle_enhanced/database_statements"
require "active_record/connection_adapters/oracle_enhanced/schema_creation"
require "active_record/connection_adapters/oracle_enhanced/schema_definitions"
require "active_record/connection_adapters/oracle_enhanced/schema_dumper"
require "active_record/connection_adapters/oracle_enhanced/schema_statements"
require "active_record/connection_adapters/oracle_enhanced/schema_versions_formatter"
require "active_record/connection_adapters/oracle_enhanced/context_index"
require "active_record/connection_adapters/oracle_enhanced/column"
require "active_record/connection_adapters/oracle_enhanced/quoting"
require "active_record/connection_adapters/oracle_enhanced/database_limits"
require "active_record/connection_adapters/oracle_enhanced/dbms_output"
require "active_record/connection_adapters/oracle_enhanced/type_metadata"
require "active_record/connection_adapters/oracle_enhanced/structure_dump"
require "active_record/connection_adapters/oracle_enhanced/structure_dump/dbms_metadata"
require "active_record/connection_adapters/oracle_enhanced/structure_dump/dispatcher"
require "active_record/connection_adapters/oracle_enhanced/lob"
require "active_record/type/oracle_enhanced/raw"
require "active_record/type/oracle_enhanced/integer"
require "active_record/type/oracle_enhanced/string"
require "active_record/type/oracle_enhanced/national_character_string"
require "active_record/type/oracle_enhanced/text"
require "active_record/type/oracle_enhanced/national_character_text"
require "active_record/type/oracle_enhanced/boolean"
require "active_record/type/oracle_enhanced/json"
require "active_record/type/oracle_enhanced/timestamptz"
require "active_record/type/oracle_enhanced/timestampltz"
require "active_record/type/oracle_enhanced/character_string"
module ActiveRecord
module ConnectionAdapters # :nodoc:
# Oracle enhanced adapter will work with both
# CRuby ruby-oci8 gem (which provides interface to Oracle OCI client)
# or with JRuby and Oracle JDBC driver.
#
# It should work with Oracle 10g, 11g and 12c databases.
#
# Usage notes:
# * Key generation assumes a "${table_name}_seq" sequence is available
# for all tables; the sequence name can be changed using
# ActiveRecord::Base.set_sequence_name. When using Migrations, these
# sequences are created automatically.
# Use set_sequence_name :autogenerated with legacy tables that have
# triggers that populate primary keys automatically.
# * Oracle uses DATE or TIMESTAMP datatypes for both dates and times.
# Consequently some hacks are employed to map data back to Date or Time
# in Ruby. Timezones and sub-second precision on timestamps are
# not supported.
# * Default values that are functions (such as "SYSDATE") are not
# supported. This is a restriction of the way ActiveRecord supports
# default values.
#
# Required parameters:
#
# * <tt>:username</tt>
# * <tt>:password</tt>
# * <tt>:database</tt> - either TNS alias or connection string for OCI client or database name in JDBC connection string
#
# Optional parameters:
#
# * <tt>:host</tt> - host name for JDBC connection, defaults to "localhost"
# * <tt>:port</tt> - port number for JDBC connection, defaults to 1521
# * <tt>:privilege</tt> - set "SYSDBA" if you want to connect with this privilege
# * <tt>:allow_concurrency</tt> - set to "true" if non-blocking mode should be enabled (just for OCI client)
# * <tt>:prefetch_rows</tt> - how many rows should be fetched at one time to increase performance, defaults to 100
# * <tt>:cursor_sharing</tt> - cursor sharing mode. Accepts "exact" or "force"
# (per Oracle's documented values), or <tt>:default</tt> (the new effective default).
# With <tt>:default</tt> (or unset) the adapter does not run <tt>ALTER SESSION SET
# cursor_sharing</tt> and the database's instance-level setting (Oracle's documented
# software default is <tt>EXACT</tt>) is what the session sees. Pass an explicit
# value to issue the corresponding <tt>ALTER SESSION</tt>.
#
# NOTE: Connections still configured with <tt>prepared_statements: false</tt> have AR
# interpolate application-SQL literals at the visitor level, so each unique value
# produces a fresh shared cursor on the server. Such installs can keep the legacy
# behavior by setting <tt>:cursor_sharing => 'force'</tt> explicitly here.
# * <tt>:time_zone</tt> - database session time zone
# (it is recommended to set it using ENV['TZ'] which will be then also used for database session time zone)
# * <tt>:schema</tt> - database schema which holds schema objects.
# * <tt>:tcp_keepalive</tt> - TCP keepalive is enabled for OCI client, defaults to true
# * <tt>:tcp_keepalive_time</tt> - TCP keepalive time for OCI client, defaults to 600
# * <tt>:jdbc_statement_cache_size</tt> - number of cached SQL cursors to keep open, disabled per default (for unpooled JDBC only)
# * <tt>:jdbc_connect_properties</tt> - Additional properties for establishing Oracle JDBC connection (for unpooled JDBC only)
# example to require encryption and checksumming for network connection:
# adapter: oracle_enhanced
# jdbc_connect_properties:
# 'oracle.net.encryption_client': REQUIRED
# 'oracle.net.crypto_checksum_client': REQUIRED
#
# Optionals NLS parameters:
#
# * <tt>:nls_calendar</tt>
# * <tt>:nls_comp</tt>
# * <tt>:nls_currency</tt>
# * <tt>:nls_date_language</tt>
# * <tt>:nls_dual_currency</tt>
# * <tt>:nls_iso_currency</tt>
# * <tt>:nls_language</tt>
# * <tt>:nls_length_semantics</tt> - semantics of size of VARCHAR2 and CHAR columns, defaults to <tt>CHAR</tt>
# (meaning that size specifies number of characters and not bytes)
# * <tt>:nls_nchar_conv_excp</tt>
# * <tt>:nls_numeric_characters</tt>
# * <tt>:nls_sort</tt>
# * <tt>:nls_territory</tt>
# * <tt>:nls_timestamp_tz_format</tt>
# * <tt>:nls_time_format</tt>
# * <tt>:nls_time_tz_format</tt>
#
# Fixed NLS values (not overridable):
#
# * <tt>:nls_date_format</tt> - format for :date columns is <tt>YYYY-MM-DD HH24:MI:SS</tt>
# * <tt>:nls_timestamp_format</tt> - format for :timestamp columns is <tt>YYYY-MM-DD HH24:MI:SS:FF6</tt>
#
class OracleEnhancedAdapter < AbstractAdapter
include OracleEnhanced::DatabaseStatements
include OracleEnhanced::SchemaStatements
include OracleEnhanced::ContextIndex
include OracleEnhanced::Quoting
include OracleEnhanced::DatabaseLimits
include OracleEnhanced::DbmsOutput
include OracleEnhanced::StructureDump
class Version < AbstractAdapter::Version # :nodoc:
# `AbstractAdapter::Version#<=>` only accepts String (it calls `.split`
# on its argument). Accept another Version too by delegating to its
# `to_s`, so comparisons like `v1 >= v2` and `v1 == v2` work.
def <=>(other)
super(other.is_a?(AbstractAdapter::Version) ? other.to_s : other)
end
def first
OracleEnhanced.deprecator.warn(
"Calling #first on database_version is deprecated. " \
"database_version is no longer an Array; use database_version >= \"N\" for version checks."
)
@version.first
end
def second
OracleEnhanced.deprecator.warn(
"Calling #second on database_version is deprecated. " \
"database_version is no longer an Array; use database_version >= \"X.Y\" for version checks."
)
@version[1]
end
def [](index)
OracleEnhanced.deprecator.warn(
"Calling #[#{index}] on database_version is deprecated. " \
"database_version is no longer an Array; use database_version >= \"N\" for version checks " \
"or read full_version_string for the dotted version string."
)
@version[index]
end
def ==(other)
if other.is_a?(Array)
OracleEnhanced.deprecator.warn(
"Comparing database_version against an Array is deprecated. " \
"database_version is no longer an Array; use database_version == \"#{other.join('.')}\" instead."
)
@version.first(2) == other
else
super
end
end
end
##
# :singleton-method:
# By default, the OracleEnhancedAdapter will consider all columns of type <tt>NUMBER(1)</tt>
# as boolean. If you wish to disable this emulation you can add the following line
# to your initializer file:
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_booleans = false
cattr_accessor :emulate_booleans
self.emulate_booleans = true
##
# :singleton-method:
# OracleEnhancedAdapter will use the default tablespace, but if you want specific types of
# objects to go into specific tablespaces, specify them like this in an initializer:
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_tablespaces =
# {:clob => 'TS_LOB', :blob => 'TS_LOB', :index => 'TS_INDEX', :table => 'TS_DATA'}
#
# Using the :tablespace option where available (e.g create_table) will take precedence
# over these settings.
cattr_accessor :default_tablespaces
self.default_tablespaces = {}
##
# :singleton-method:
# If you wish that CHAR(1), VARCHAR2(1) columns are typecasted to booleans
# then you can add the following line to your initializer file:
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_booleans_from_strings = true
cattr_accessor :emulate_booleans_from_strings
self.emulate_booleans_from_strings = false
##
# :singleton-method:
# Controls whether <tt>add_index :col, unique: true</tt> implicitly creates
# a same-named UNIQUE CONSTRAINT in addition to the unique index. This
# behavior was introduced so that Oracle-specific FK targetability worked
# with Rails-standard <tt>add_index unique: true</tt> migrations, but the
# explicit <tt>add_unique_constraint</tt> DSL is now the recommended path
# for callers who actually need a constraint. Defaults to +true+ for
# backward compatibility; will flip to +false+ in a future release.
#
# Set to +false+ in an initializer to opt out of the implicit-constraint
# behavior (and silence the deprecation warning) immediately:
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.add_index_unique_creates_constraint = false
cattr_accessor :add_index_unique_creates_constraint
self.add_index_unique_creates_constraint = true
##
# :singleton-method:
# Selects the Arel visitor used to compile SQL for the connection.
#
# * +:auto+ — pick based on the connected database version:
# +Arel::Visitors::Oracle12+ on Oracle 12.1+,
# +Arel::Visitors::Oracle+ (ROWNUM-based LIMIT/OFFSET) on earlier
# releases.
# * +:rownum+ — force +Arel::Visitors::Oracle+ regardless of version.
# * +:fetch_first+ — force +Arel::Visitors::Oracle12+. Raises
# +ArgumentError+ during adapter initialization (after the connection
# is established and the visitor is resolved) if the connected server
# is older than 12.1.
#
# When the key is omitted, the class-level +use_old_oracle_visitor+
# decides the default: +true+ maps to +:rownum+, +false+ (default)
# maps to +:auto+. Setting +arel_visitor: :auto+ explicitly overrides
# the class-level setting, so the result stays the same when
# +use_old_oracle_visitor+ is removed in a future major.
#
# Set per connection via database.yml:
#
# production:
# adapter: oracle_enhanced
# arel_visitor: rownum
@@use_old_oracle_visitor = false
def self.use_old_oracle_visitor
@@use_old_oracle_visitor
end
# Only the writer is deprecated. The reader is consulted on the
# fallback path inside +configured_arel_visitor_mode+ even when the user
# never wrote to it, so warning on read would be noisy.
def self.use_old_oracle_visitor=(value)
OracleEnhanced.deprecator.deprecation_warning(
"ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.use_old_oracle_visitor=",
"set `arel_visitor: rownum` per connection in database.yml instead"
)
@@use_old_oracle_visitor = value
end
def use_old_oracle_visitor
self.class.use_old_oracle_visitor
end
def use_old_oracle_visitor=(value)
self.class.use_old_oracle_visitor = value
end
##
# :singleton-method:
# Specify default sequence start with value (by default 1 if not explicitly set), e.g.:
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value = 10000
cattr_accessor :default_sequence_start_value
self.default_sequence_start_value = 1
# Per-connection identifier-length policy. Set via database.yml:
#
# production:
# adapter: oracle_enhanced
# identifier_max_length: short # :auto (default), :short, or :long
#
# Accepted values:
# * +:auto+ (default when the key is absent) — use 128 byte identifiers on
# Oracle 12.2+, silently fall back to 30 bytes on older databases.
# * +:short+ — force the 30 byte limit on every database version.
# * +:long+ — request 128 byte identifiers. Raises +ArgumentError+ on
# pre-12.2 databases (use +:auto+ if you want the version-aware
# fallback to 30 bytes).
#
# Unknown values (e.g. +identifier_max_length: :legacy+) and non-Symbol /
# non-String inputs (e.g. a stray boolean after a mechanical YAML
# migration) raise +ArgumentError+ up front rather than degrading
# silently.
#
# +use_shorter_identifier+ (below) is a deprecated global fallback for
# connections that do not set +identifier_max_length+ themselves.
@@use_shorter_identifier = false
##
# :singleton-method:
# Deprecated. Prefer the per-connection +identifier_max_length+ key in
# database.yml. When truthy, behaves as +identifier_max_length: short+ for
# connections that do not set +identifier_max_length+ themselves.
def self.use_shorter_identifier
OracleEnhanced.deprecator.deprecation_warning(
"ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.use_shorter_identifier",
"set `identifier_max_length: short` per connection in database.yml instead"
)
@@use_shorter_identifier
end
def self.use_shorter_identifier=(value)
OracleEnhanced.deprecator.deprecation_warning(
"ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.use_shorter_identifier=",
"set `identifier_max_length: short` per connection in database.yml instead"
)
@@use_shorter_identifier = value
end
def use_shorter_identifier
self.class.use_shorter_identifier
end
def use_shorter_identifier=(value)
self.class.use_shorter_identifier = value
end
##
# :singleton-method:
# By default, OracleEnhanced adapter will grant unlimited tablespace, create session, create table, create view,
# and create sequence when running the rake task db:create.
#
# If you wish to change these permissions you can add the following line to your initializer file:
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.permissions =
# ["create session", "create table", "create view", "create sequence", "create trigger", "ctxapp"]
cattr_accessor :permissions
self.permissions = ["unlimited tablespace", "create session", "create table", "create view", "create sequence"]
##
# :singleton-method:
# Selects which `structure_dump` backend the adapter uses. Accepts:
#
# * +:auto+ (default) — pick +:dbms_metadata+ on Oracle 12.1 and later,
# fall back to +:data_dictionary+ on earlier releases. The
# +:dbms_metadata+ path relies on constructs Oracle only emits
# completely from 12.1 onward (notably +IDENTITY+ columns and
# +EDITIONABLE+ keywords); +:auto+ keeps the new backend opt-in by
# capability, not by user action.
# * +:dbms_metadata+ — force Oracle's
# <tt>DBMS_METADATA.GET_DDL</tt> / <tt>GET_DEPENDENT_DDL</tt>. The
# Oracle-native equivalent of <tt>pg_dump --schema-only</tt> /
# <tt>mysqldump --no-data</tt>. Raises +ArgumentError+ at dump time
# when the connected server is older than 12.1.
# * +:data_dictionary+ — force the original implementation that
# assembles DDL from the <tt>ALL_*</tt> static data dictionary views
# in Ruby. Retained as a fallback while the +:dbms_metadata+ backend
# stabilises; may be removed in a future release. If
# <tt>DBMS_METADATA</tt> does not produce usable DDL for your schema,
# please open an issue at https://github.com/rsim/oracle-enhanced/issues
# so the new backend can be fixed before the +:data_dictionary+ one
# is removed.
#
# Set globally (e.g. in <tt>config/initializers/oracle_enhanced.rb</tt>):
#
# ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.structure_dump_method = :data_dictionary
#
# The toggle is intentionally a Rails-app-global setting rather than a
# per-connection +database.yml+ key — the choice of structure-dump
# backend is an implementation strategy, not something that varies
# across the databases an app connects to.
STRUCTURE_DUMP_METHODS = %i[auto dbms_metadata data_dictionary].freeze
cattr_accessor :structure_dump_method
self.structure_dump_method = :auto
##
# :singleton-method:
# Specify default sequence start with value (by default 1 if not explicitly set), e.g.:
class StatementPool < ConnectionAdapters::StatementPool
private
def dealloc(stmt)
stmt.close
end
end
def initialize(config_or_deprecated_connection, deprecated_logger = nil, deprecated_connection_options = nil, deprecated_config = nil) # :nodoc:
super(config_or_deprecated_connection, deprecated_logger, deprecated_connection_options, deprecated_config)
resolve_database_aliases
connect
@enable_dbms_output = false
@prefetch_primary_key_cache = {}
@columns_cache = {}
@trigger_assigned_pk_cache = {}
@notice_receiver_sql_warnings = []
configure_connection
# AbstractAdapter#initialize ran `@visitor = arel_visitor` before
# `connect`, when `database_version` was unavailable. Reassign now that
# the connection is live so :auto sees the real server version. A lazy
# `visitor` override is not an option: AbstractAdapter exposes
# `attr_reader :visitor` and reads `@visitor` directly. Nothing in
# `configure_connection` compiles SQL, so the placeholder visitor set
# by super is never used before this reassignment.
@visitor = arel_visitor
end
ADAPTER_NAME = "OracleEnhanced"
def adapter_name # :nodoc:
ADAPTER_NAME
end
# Oracle enhanced adapter has no implementation because
# Oracle Database cannot detect `NoDatabaseError`.
# Please refer to the following discussion for details.
# https://github.com/rsim/oracle-enhanced/pull/1900
def self.database_exists?(config)
raise NotImplementedError
end
# Opens a database console session via sqlplus.
#
# Called by Rails' `bin/rails dbconsole` command on the adapter class
# returned from adapter registration. Builds an Oracle logon string of
# the form `user[/password]@database` and execs `sqlplus`.
def self.dbconsole(config, options = {})
oracle_config = config.configuration_hash
logon = +""
if oracle_config[:username]
logon << oracle_config[:username]
logon << "/#{oracle_config[:password]}" if oracle_config[:password] && options[:include_password]
logon << "@#{config.database}" if config.database
end
find_cmd_and_exec(ActiveRecord.database_cli[:oracle] || "sqlplus", logon)
end
def supports_savepoints? # :nodoc:
true
end
# Oracle's ALTER TABLE accepts combined `ADD (...)` and `MODIFY (...)`
# clauses in a single statement, which `bulk_change_table` uses to
# collapse contiguous `add_column` / `change_column` operations.
# `DROP (...)` cannot be combined with any other ALTER clause
# (ORA-12987: cannot combine drop column with other operations) so
# it is issued as its own statement.
# See the Oracle 19c SQL Language Reference, ALTER TABLE:
# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/ALTER-TABLE.html
def supports_bulk_alter? # :nodoc:
true
end
def supports_lazy_transactions? # :nodoc:
true
end
def supports_transaction_isolation? # :nodoc:
true
end
def supports_foreign_keys?
true
end
# Oracle has supported DEFERRABLE constraints since 8i:
# https://docs.oracle.com/cd/A87860_01/doc/appdev.817/a76939/adg05itg.htm
def supports_deferrable_constraints?
true
end
def supports_unique_constraints?
true
end
def supports_check_constraints?
true
end
def supports_validate_constraints?
true
end
def supports_enforced_foreign_keys?
true
end
def supports_expression_index?
true
end
def supports_index_sort_order?
true
end
def supports_insert_returning?
true
end
def supports_insert_on_duplicate_skip?
true
end
def supports_insert_on_duplicate_update?
true
end
def supports_insert_conflict_target?
true
end
def supports_optimizer_hints?
true
end
def supports_common_table_expressions?
true
end
def supports_views?
true
end
def supports_materialized_views?
true
end
def supports_fetch_first_n_rows_and_offset?
return false unless _connection
database_version >= "12"
end
def supports_datetime_with_precision?
true
end
def supports_comments?
true
end
def supports_virtual_columns?
database_version >= "11"
end
# Oracle 11g Release 1 (11.1) introduced INVISIBLE indexes
# (`ALTER INDEX ... INVISIBLE` / `VISIBLE`), which the optimizer ignores
# while the index is still maintained on writes. That matches
# `supports_disabling_indexes?` semantics on MySQL 8.0+ and MariaDB 10.6+.
# See the Oracle Database 11.1 SQL Language Reference, ALTER INDEX:
# https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_1010.htm
def supports_disabling_indexes?
database_version >= "11"
end
# Oracle Database 12.1 and above support `GENERATED BY DEFAULT AS IDENTITY`.
def supports_identity_columns? # :nodoc:
database_version >= "12"
end
# Oracle Database 23ai (23.4) introduced the `IF EXISTS` and
# `IF NOT EXISTS` clauses for several DDL statements (DROP TABLE,
# DROP SEQUENCE, etc.). On older releases the adapter has to rescue
# ORA-00942 / ORA-02289 manually for idempotent drops.
def supports_drop_if_exists? # :nodoc:
database_version >= "23.4"
end
# Whether `structure_dump_method: :auto` resolves to +:dbms_metadata+
# on this connection. `DBMS_METADATA.GET_DDL` itself exists since
# Oracle 9i, but the constructs the backend depends on (`IDENTITY`
# columns, `EDITIONABLE` keywords, the modern set of
# `SET_TRANSFORM_PARAM` options) only land in Oracle 12.1, so older
# releases fall back to +:data_dictionary+ under +:auto+. The 12.1
# floor is a project policy choice, not a strict database capability
# check; +:data_dictionary+ remains explicitly selectable on 12.1+.
def use_dbms_metadata_dump? # :nodoc:
database_version >= "12.1"
end
def supports_json?
# Oracle Database 12.1 or higher version supports JSON.
# However, Oracle enhanced adapter has limited support for JSON data type.
# which does not pass many of ActiveRecord JSON tests.
#
# No migration supported for :json type due to there is no `JSON` data type
# in Oracle Database itself.
#
# If you want to use JSON data type, here are steps
# 1.Define :string or :text in migration
#
# create_table :test_posts, force: true do |t|
# t.string :title
# t.text :article
# end
#
# 2. Set :json attributes
#
# class TestPost < ActiveRecord::Base
# attribute :title, :json
# attribute :article, :json
# end
#
# 3. Add `is json` database constraints by running sql statements
#
# alter table test_posts add constraint test_posts_title_is_json check (title is json)
# alter table test_posts add constraint test_posts_article_is_json check (article is json)
#
false
end
# Pure capability flag: does the connected database support 128-byte
# identifiers? Independent of the +identifier_max_length+ config — the
# adapter may still emit 30-byte identifiers via +:short+ or
# +use_shorter_identifier+ on a 12.2+ server. Use +max_identifier_length+
# for the byte count the adapter actually emits.
def supports_longer_identifier? # :nodoc:
database_version >= "12.2"
end
# :stopdoc:
DEFAULT_NLS_PARAMETERS = {
nls_calendar: nil,
nls_comp: nil,
nls_currency: nil,
nls_date_language: nil,
nls_dual_currency: nil,
nls_iso_currency: nil,
nls_language: nil,
nls_length_semantics: "CHAR",
nls_nchar_conv_excp: nil,
nls_numeric_characters: nil,
nls_sort: nil,
nls_territory: nil,
nls_timestamp_tz_format: nil,
nls_time_format: nil,
nls_time_tz_format: nil
}.freeze
# :stopdoc:
FIXED_NLS_PARAMETERS = {
nls_date_format: "YYYY-MM-DD HH24:MI:SS",
nls_timestamp_format: "YYYY-MM-DD HH24:MI:SS:FF6"
}.freeze
# :stopdoc:
# rubocop:disable Style/MutableConstant
NATIVE_DATABASE_TYPES = {
primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
identity_primary_key: "NUMBER(38) GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY",
string: { name: "VARCHAR2", limit: 255 },
text: { name: "CLOB" },
ntext: { name: "NCLOB" },
integer: { name: "NUMBER", limit: 38 },
float: { name: "BINARY_FLOAT" },
decimal: { name: "NUMBER" },
datetime: { name: "TIMESTAMP" },
timestamp: { name: "TIMESTAMP" },
timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
time: { name: "TIMESTAMP" },
date: { name: "DATE" },
binary: { name: "BLOB" },
boolean: { name: "NUMBER", limit: 1 },
raw: { name: "RAW", limit: 2000 },
bigint: { name: "NUMBER", limit: 19 }
}
# if emulate_booleans_from_strings then store booleans in VARCHAR2
NATIVE_DATABASE_TYPES_BOOLEAN_STRINGS = NATIVE_DATABASE_TYPES.dup.merge(
boolean: { name: "VARCHAR2", limit: 1 }
)
# rubocop:enable Style/MutableConstant
# :startdoc:
def native_database_types # :nodoc:
self.class.native_database_types
end
# CONNECTION MANAGEMENT ====================================
#
# The oracle-enhanced-specific `auto_retry` toggle has been removed
# in favor of AR core's standard `connection_retries:` setting; the
# accessors are kept only to surface a clear migration path. Both
# raise to tell callers exactly what to change.
def auto_retry # :nodoc:
raise NotImplementedError,
"OracleEnhancedAdapter#auto_retry has been removed. " \
"Set `connection_retries:` in database.yml (or your connection " \
"configuration) to use AR core's retry instead. " \
"See https://github.com/rsim/oracle-enhanced/issues/2760."
end
def auto_retry=(_value) # :nodoc:
raise NotImplementedError,
"OracleEnhancedAdapter#auto_retry= has been removed. " \
"Set `connection_retries:` in database.yml (or your connection " \
"configuration) to use AR core's retry instead. " \
"See https://github.com/rsim/oracle-enhanced/issues/2760."
end
# return raw OCI8 or JDBC connection
def raw_connection
with_raw_connection do |conn|
disable_lazy_transactions!
@raw_connection_dirty = true
conn.raw_connection
end
end
# Returns true if the connection is active.
def active? # :nodoc:
# Pings the connection to check if it's still good. Note that an
# #active? method is also available, but that simply returns the
# last known state, which isn't good enough if the connection has
# gone stale since the last use.
_connection.ping
rescue OracleEnhanced::ConnectionException
false
end
# Reconnects to the database.
def reconnect!(restore_transactions: false) # :nodoc:
super
rescue OracleEnhanced::ConnectionException => e
@logger.warn "#{adapter_name} automatic reconnection failed: #{e.message}" if @logger
end
def clear_cache!(new_connection: false)
super
self.class.clear_type_map!
end
def reset!
clear_cache!
super
end
# Disconnects from the database.
def disconnect! # :nodoc:
super
_connection.logoff rescue nil
end
def discard!
super
@raw_connection = nil
end
# use in set_sequence_name to avoid fetching primary key value from sequence
AUTOGENERATED_SEQUENCE_NAME = "autogenerated"
# Returns the next sequence value from a sequence generator. Not generally
# called directly; used by ActiveRecord to get the next primary key value
# when inserting a new database record (see #prefetch_primary_key?).
def next_sequence_value(sequence_name)
# if sequence_name is set to :autogenerated then it means that primary key will be populated by trigger
raise ArgumentError.new "Trigger based primary key is not supported" if sequence_name == AUTOGENERATED_SEQUENCE_NAME
# call directly connection method to avoid prepared statement which causes fetching of next sequence value twice
select_value(<<~SQL.squish, "SCHEMA")
SELECT #{quote_table_name(sequence_name)}.NEXTVAL FROM dual
SQL
end
def prefetch_primary_key?(table_name = nil)
return true if table_name.nil?
table_name = table_name.to_s
return @prefetch_primary_key_cache[table_name] if @prefetch_primary_key_cache.key?(table_name)
result = prefetch_primary_key_from_schema_cache(table_name)
result = prefetch_primary_key_from_dictionary(table_name) if result.nil?
@prefetch_primary_key_cache[table_name] = result
end
# Returns true when the primary key column of +desc_table_name+ is an
# identity column. Oracle allows identity columns to exist on non-PK
# columns (one identity column per table maximum), so the join with
# +all_constraints+ is required to avoid disabling PK prefetch on tables
# that combine a sequence-backed PK with a non-PK identity column.
def identity_primary_key?(owner, desc_table_name) # :nodoc:
select_values(<<~SQL.squish, "SCHEMA", [bind_string("owner", owner), bind_string("table_name", desc_table_name)]).any?
SELECT 1
FROM all_tab_identity_cols itc
JOIN all_cons_columns cc
ON cc.owner = itc.owner
AND cc.table_name = itc.table_name
AND cc.column_name = itc.column_name
JOIN all_constraints c
ON c.owner = cc.owner
AND c.constraint_name = cc.constraint_name
WHERE itc.owner = :owner
AND itc.table_name = :table_name
AND c.constraint_type = 'P'
SQL
end
# Detects only triggers whose body contains the
# `<seq>.NEXTVAL INTO :new.<pk>` pattern emitted by `create_pk_trigger`.
# Restricts the +all_triggers+ scan with an +EXISTS+ over +all_source+
# so unrelated `BEFORE INSERT` row triggers (audit, last_modified, etc.)
# do not flip +prefetch_primary_key?+ to false on tables that still
# rely on Rails-side sequence prefetch.
def trigger_backed_primary_key?(owner, desc_table_name) # :nodoc:
select_values(<<~SQL.squish, "SCHEMA", [bind_string("owner", owner), bind_string("table_name", desc_table_name)]).any?
SELECT 1
FROM all_triggers t
WHERE t.owner = :owner
AND t.table_name = :table_name
AND t.trigger_type = 'BEFORE EACH ROW'
AND t.triggering_event = 'INSERT'
AND EXISTS (
SELECT 1 FROM all_source s
WHERE s.owner = t.owner
AND s.name = t.trigger_name
AND s.type = 'TRIGGER'
AND UPPER(s.text) LIKE '%NEXTVAL INTO :NEW%'
)
SQL
end
def trigger_backed_table_names # :nodoc:
rows = select_all(<<~SQL.squish, "SCHEMA")
SELECT t.table_name, t.trigger_name
FROM all_triggers t
WHERE t.owner = SYS_CONTEXT('userenv', 'current_schema')
AND t.trigger_type = 'BEFORE EACH ROW'
AND t.triggering_event = 'INSERT'
AND EXISTS (
SELECT 1 FROM all_source s
WHERE s.owner = t.owner
AND s.name = t.trigger_name
AND s.type = 'TRIGGER'
AND UPPER(s.text) LIKE '%NEXTVAL INTO :NEW%'
)
SQL
rows.each_with_object({}) do |row, hash|
hash[row["table_name"]] = row["trigger_name"]
end
end
def reset_pk_sequence!(table_name, primary_key = nil, sequence_name = nil) # :nodoc:
return nil unless data_source_exists?(table_name)
unless primary_key && sequence_name
# *Note*: Only primary key is implemented - sequence will be nil.
primary_key, sequence_name = pk_and_sequence_for(table_name)
# TODO This sequence_name implemantation is just enough
# to satisty fixures. To get correct sequence_name always
# pk_and_sequence_for method needs some work.
begin
sequence_name = table_name.classify.constantize.sequence_name
rescue
sequence_name = default_sequence_name(table_name, primary_key)
end
end
if @logger && primary_key && !sequence_name
@logger.warn "#{table_name} has primary key #{primary_key} with no default sequence"
end
if primary_key && sequence_name
new_start_value = select_value(<<~SQL.squish, "SCHEMA")
select NVL(max(#{quote_column_name(primary_key)}),0) + 1 from #{quote_table_name(table_name)}
SQL
execute "DROP SEQUENCE #{quote_table_name(sequence_name)}"
execute "CREATE SEQUENCE #{quote_table_name(sequence_name)} START WITH #{new_start_value}"
end
end
# Current database name
def current_database
select_value(<<~SQL.squish, "SCHEMA")
SELECT SYS_CONTEXT('userenv', 'con_name') FROM dual
SQL
rescue ActiveRecord::StatementInvalid
select_value(<<~SQL.squish, "SCHEMA")
SELECT SYS_CONTEXT('userenv', 'db_name') FROM dual
SQL
end
# Current database session user
def current_user
select_value(<<~SQL.squish, "SCHEMA")
SELECT SYS_CONTEXT('userenv', 'session_user') FROM dual
SQL
end
# Current database session schema
def current_schema
select_value(<<~SQL.squish, "SCHEMA")
SELECT SYS_CONTEXT('userenv', 'current_schema') FROM dual
SQL
end
# Default tablespace name of current user
def default_tablespace
select_value(<<~SQL.squish, "SCHEMA")
SELECT LOWER(default_tablespace) FROM user_users
WHERE username = SYS_CONTEXT('userenv', 'current_schema')
SQL
end
def column_definitions(table_name)
(owner, desc_table_name) = resolve_data_source_name(table_name)
# `ALL_TAB_COLS.IDENTITY_COLUMN` is only available on Oracle 12.1+
# (the release that introduced identity columns), so on older servers
# we substitute a constant 'NO' to keep the projection stable.
#
# See:
# https://docs.oracle.com/en/database/oracle/oracle-database/23/refrn/ALL_TAB_COLS.html
# https://docs.oracle.com/en/database/oracle/oracle-database/23/refrn/ALL_TAB_IDENTITY_COLS.html
identity_column_expr = supports_identity_columns? ? "cols.identity_column" : "'NO' AS identity_column"
select_all(<<~SQL.squish, "SCHEMA", [bind_string("owner", owner), bind_string("table_name", desc_table_name)])
SELECT cols.column_name AS name, cols.data_type AS sql_type,
cols.data_default, cols.nullable, cols.virtual_column, cols.hidden_column,
#{identity_column_expr},
cols.data_type_owner AS sql_type_owner,
DECODE(cols.data_type, 'NUMBER', data_precision,
'FLOAT', data_precision,
'VARCHAR2', DECODE(char_used, 'C', char_length, data_length),
'RAW', DECODE(char_used, 'C', char_length, data_length),
'CHAR', DECODE(char_used, 'C', char_length, data_length),
NULL) AS limit,
DECODE(data_type, 'NUMBER', data_scale, NULL) AS scale,
comments.comments as column_comment
FROM all_tab_cols cols, all_col_comments comments
WHERE cols.owner = :owner
AND cols.table_name = :table_name
AND cols.hidden_column = 'NO'
AND cols.owner = comments.owner
AND cols.table_name = comments.table_name
AND cols.column_name = comments.column_name
ORDER BY cols.column_id
SQL
end
def clear_table_caches(table_name) # :nodoc:
table_name = table_name.to_s
@columns_cache[table_name] = nil
@trigger_assigned_pk_cache.delete(table_name)
@prefetch_primary_key_cache.delete(table_name)
evict_prepared_statements_for(table_name)
end
def clear_table_columns_cache(table_name)
OracleEnhanced.deprecator.deprecation_warning(
"ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter#clear_table_columns_cache",
"use clear_table_caches instead"
)
clear_table_caches(table_name)
end
def evict_prepared_statements_for(table_name) # :nodoc: