activerecord-yugabytedb-adapter 7.0.4.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (54) hide show
  1. checksums.yaml +7 -0
  2. data/.rubocop.yml +13 -0
  3. data/CHANGELOG.md +5 -0
  4. data/CODE_OF_CONDUCT.md +84 -0
  5. data/Gemfile +10 -0
  6. data/Gemfile.lock +67 -0
  7. data/README.md +31 -0
  8. data/Rakefile +8 -0
  9. data/activerecord-yugabytedb-adapter.gemspec +39 -0
  10. data/lib/active_record/connection_adapters/yugabytedb/column.rb +69 -0
  11. data/lib/active_record/connection_adapters/yugabytedb/database_statements.rb +156 -0
  12. data/lib/active_record/connection_adapters/yugabytedb/database_tasks.rb +19 -0
  13. data/lib/active_record/connection_adapters/yugabytedb/explain_pretty_printer.rb +44 -0
  14. data/lib/active_record/connection_adapters/yugabytedb/oid/array.rb +91 -0
  15. data/lib/active_record/connection_adapters/yugabytedb/oid/bit.rb +53 -0
  16. data/lib/active_record/connection_adapters/yugabytedb/oid/bit_varying.rb +15 -0
  17. data/lib/active_record/connection_adapters/yugabytedb/oid/bytea.rb +17 -0
  18. data/lib/active_record/connection_adapters/yugabytedb/oid/cidr.rb +48 -0
  19. data/lib/active_record/connection_adapters/yugabytedb/oid/date.rb +31 -0
  20. data/lib/active_record/connection_adapters/yugabytedb/oid/date_time.rb +36 -0
  21. data/lib/active_record/connection_adapters/yugabytedb/oid/decimal.rb +15 -0
  22. data/lib/active_record/connection_adapters/yugabytedb/oid/enum.rb +20 -0
  23. data/lib/active_record/connection_adapters/yugabytedb/oid/hstore.rb +109 -0
  24. data/lib/active_record/connection_adapters/yugabytedb/oid/inet.rb +15 -0
  25. data/lib/active_record/connection_adapters/yugabytedb/oid/interval.rb +49 -0
  26. data/lib/active_record/connection_adapters/yugabytedb/oid/jsonb.rb +15 -0
  27. data/lib/active_record/connection_adapters/yugabytedb/oid/legacy_point.rb +44 -0
  28. data/lib/active_record/connection_adapters/yugabytedb/oid/macaddr.rb +25 -0
  29. data/lib/active_record/connection_adapters/yugabytedb/oid/money.rb +41 -0
  30. data/lib/active_record/connection_adapters/yugabytedb/oid/oid.rb +15 -0
  31. data/lib/active_record/connection_adapters/yugabytedb/oid/point.rb +64 -0
  32. data/lib/active_record/connection_adapters/yugabytedb/oid/range.rb +115 -0
  33. data/lib/active_record/connection_adapters/yugabytedb/oid/specialized_string.rb +18 -0
  34. data/lib/active_record/connection_adapters/yugabytedb/oid/timestamp.rb +15 -0
  35. data/lib/active_record/connection_adapters/yugabytedb/oid/timestamp_with_time_zone.rb +30 -0
  36. data/lib/active_record/connection_adapters/yugabytedb/oid/type_map_initializer.rb +125 -0
  37. data/lib/active_record/connection_adapters/yugabytedb/oid/uuid.rb +35 -0
  38. data/lib/active_record/connection_adapters/yugabytedb/oid/vector.rb +28 -0
  39. data/lib/active_record/connection_adapters/yugabytedb/oid/xml.rb +30 -0
  40. data/lib/active_record/connection_adapters/yugabytedb/oid.rb +38 -0
  41. data/lib/active_record/connection_adapters/yugabytedb/quoting.rb +205 -0
  42. data/lib/active_record/connection_adapters/yugabytedb/referential_integrity.rb +77 -0
  43. data/lib/active_record/connection_adapters/yugabytedb/schema_creation.rb +100 -0
  44. data/lib/active_record/connection_adapters/yugabytedb/schema_definitions.rb +243 -0
  45. data/lib/active_record/connection_adapters/yugabytedb/schema_dumper.rb +74 -0
  46. data/lib/active_record/connection_adapters/yugabytedb/schema_statements.rb +812 -0
  47. data/lib/active_record/connection_adapters/yugabytedb/type_metadata.rb +44 -0
  48. data/lib/active_record/connection_adapters/yugabytedb/utils.rb +80 -0
  49. data/lib/active_record/connection_adapters/yugabytedb_adapter.rb +1069 -0
  50. data/lib/activerecord-yugabytedb-adapter.rb +11 -0
  51. data/lib/arel/visitors/yugabytedb.rb +99 -0
  52. data/lib/version.rb +5 -0
  53. data/sig/activerecord-yugabytedb-adapter.rbs +4 -0
  54. metadata +124 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3db689c384694018413781b6b103d41fe67fa1f01e9e26e7e628b4bb2bb07535
4
+ data.tar.gz: '008122cddcd6ff3d30c3527c67d4455f91298a7822242f8de51d4abc8add98eb'
5
+ SHA512:
6
+ metadata.gz: c23aaf43a62c4a84848678204dd9cf54184bff185e0998955a0c13e6c7bd2cd84ba1c966567a31236678abe128cd91937c3fcbe51c55c8cbc866bfff2837dc11
7
+ data.tar.gz: f87027546cb7cdb1cb732bc0b880eda9eb20e599f87af2f4bd3e21f51d769503bc820ac4e99c7c44e255f8aea0dd60e686b827f17a5c0f974f460e69969f1a9e
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-06-24
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported [here](https://www.yugabyte.com/contact/). All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in activerecord-yugabytedb-adapter.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,67 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ activerecord-yugabytedb-adapter (7.0.4.1)
5
+ activerecord (= 7.0.4)
6
+ yugabyte_ysql (~> 0.3)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ activemodel (7.0.4)
12
+ activesupport (= 7.0.4)
13
+ activerecord (7.0.4)
14
+ activemodel (= 7.0.4)
15
+ activesupport (= 7.0.4)
16
+ activesupport (7.0.4)
17
+ concurrent-ruby (~> 1.0, >= 1.0.2)
18
+ i18n (>= 1.6, < 2)
19
+ minitest (>= 5.1)
20
+ tzinfo (~> 2.0)
21
+ ast (2.4.2)
22
+ concurrent-ruby (1.3.3)
23
+ i18n (1.14.5)
24
+ concurrent-ruby (~> 1.0)
25
+ json (2.7.2)
26
+ language_server-protocol (3.17.0.3)
27
+ minitest (5.24.0)
28
+ parallel (1.25.1)
29
+ parser (3.3.3.0)
30
+ ast (~> 2.4.1)
31
+ racc
32
+ racc (1.8.0)
33
+ rainbow (3.1.1)
34
+ rake (13.2.1)
35
+ regexp_parser (2.9.2)
36
+ rexml (3.3.1)
37
+ strscan
38
+ rubocop (1.64.1)
39
+ json (~> 2.3)
40
+ language_server-protocol (>= 3.17.0)
41
+ parallel (~> 1.10)
42
+ parser (>= 3.3.0.2)
43
+ rainbow (>= 2.2.2, < 4.0)
44
+ regexp_parser (>= 1.8, < 3.0)
45
+ rexml (>= 3.2.5, < 4.0)
46
+ rubocop-ast (>= 1.31.1, < 2.0)
47
+ ruby-progressbar (~> 1.7)
48
+ unicode-display_width (>= 2.4.0, < 3.0)
49
+ rubocop-ast (1.31.3)
50
+ parser (>= 3.3.1.0)
51
+ ruby-progressbar (1.13.0)
52
+ strscan (3.1.0)
53
+ tzinfo (2.0.6)
54
+ concurrent-ruby (~> 1.0)
55
+ unicode-display_width (2.5.0)
56
+ yugabyte_ysql (0.3)
57
+
58
+ PLATFORMS
59
+ x86_64-linux
60
+
61
+ DEPENDENCIES
62
+ activerecord-yugabytedb-adapter!
63
+ rake (~> 13.0)
64
+ rubocop (~> 1.21)
65
+
66
+ BUNDLED WITH
67
+ 2.3.27
data/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # ActiveRecord YugabyteDB Adapter
2
+
3
+ This is an adapter for YugabyteDB for ActiveRecord. The adapter uses YugabyteDB's Ruby smart driver underneath. The adapter code is derived from the [PostgreSQL adapter v7.0.4 for ActiveRecord in the Rails repository](https://github.com/rails/rails/tree/v7.0.4/activerecord/lib/active_record/connection_adapters).
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ $ bundle add activerecord-yugabytedb-adapter
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ $ gem install activerecord-yugabytedb-adapter
14
+
15
+ ## Usage
16
+
17
+ Check this [simple example](https://github.com/YugabyteDB-Samples/orm-examples/tree/ruby-smart-driver) for usage of this adapter.
18
+
19
+ ## Development
20
+
21
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
22
+
23
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
24
+
25
+ ## Contributing
26
+
27
+ Bug reports and pull requests are welcome on GitHub at https://github.com/yugabyte/activerecord-yugabytedb-adapter. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/yugabyte/activerecord-yugabytedb-adapter/blob/master/CODE_OF_CONDUCT.md).
28
+
29
+ ## Code of Conduct
30
+
31
+ Everyone interacting in this project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/yugabyte/activerecord-yugabytedb-adapter/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: :rubocop
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "activerecord-yugabytedb-adapter"
7
+ spec.version = ActiveRecord::YUGABYTE_DB_ADAPTER_VERSION
8
+ spec.authors = ["YugabyteDB Development Team"]
9
+ spec.email = ["info@yugabyte.com"]
10
+
11
+ spec.summary = "YugabyteDB adapter for ActiveRecord."
12
+ spec.description = "YugabyteDB adapter for ActiveRecord."
13
+ spec.homepage = "https://docs.yugabyte.com/preview/drivers-orms/ruby/activerecord/"
14
+ spec.required_ruby_version = ">= 2.6.0"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/yugabyte/activerecord-yugabytedb-adapter"
18
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(__dir__) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
25
+ end
26
+ end
27
+ spec.bindir = "exe"
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ # Uncomment to register a new dependency of your gem
32
+ # spec.add_dependency "example-gem", "~> 1.0"
33
+ spec.add_dependency "activerecord", "7.0.4"
34
+ spec.add_dependency "yugabyte_ysql", "~> 0.3"
35
+
36
+
37
+ # For more information and examples about making a new gem, check out our
38
+ # guide at: https://bundler.io/guides/creating_gem.html
39
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/object/blank"
4
+
5
+ module ActiveRecord
6
+ module ConnectionAdapters
7
+ module YugabyteDB
8
+ class Column < ConnectionAdapters::Column # :nodoc:
9
+ delegate :oid, :fmod, to: :sql_type_metadata
10
+
11
+ def initialize(*, serial: nil, generated: nil, **)
12
+ super
13
+ @serial = serial
14
+ @generated = generated
15
+ end
16
+
17
+ def serial?
18
+ @serial
19
+ end
20
+
21
+ def virtual?
22
+ # We assume every generated column is virtual, no matter the concrete type
23
+ @generated.present?
24
+ end
25
+
26
+ def has_default?
27
+ super && !virtual?
28
+ end
29
+
30
+ def array
31
+ sql_type_metadata.sql_type.end_with?("[]")
32
+ end
33
+ alias :array? :array
34
+
35
+ def enum?
36
+ type == :enum
37
+ end
38
+
39
+ def sql_type
40
+ super.delete_suffix("[]")
41
+ end
42
+
43
+ def init_with(coder)
44
+ @serial = coder["serial"]
45
+ super
46
+ end
47
+
48
+ def encode_with(coder)
49
+ coder["serial"] = @serial
50
+ super
51
+ end
52
+
53
+ def ==(other)
54
+ other.is_a?(Column) &&
55
+ super &&
56
+ serial? == other.serial?
57
+ end
58
+ alias :eql? :==
59
+
60
+ def hash
61
+ Column.hash ^
62
+ super.hash ^
63
+ serial?.hash
64
+ end
65
+ end
66
+ end
67
+ YugabyteDBColumn = YugabyteDB::Column # :nodoc:
68
+ end
69
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module YugabyteDB
6
+ module DatabaseStatements
7
+ def explain(arel, binds = [])
8
+ sql = "EXPLAIN #{to_sql(arel, binds)}"
9
+ YugabyteDB::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", binds))
10
+ end
11
+
12
+ # Queries the database and returns the results in an Array-like object
13
+ def query(sql, name = nil) # :nodoc:
14
+ materialize_transactions
15
+ mark_transaction_written_if_write(sql)
16
+
17
+ log(sql, name) do
18
+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
19
+ @connection.async_exec(sql).map_types!(@type_map_for_results).values
20
+ end
21
+ end
22
+ end
23
+
24
+ READ_QUERY = ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp(
25
+ :close, :declare, :fetch, :move, :set, :show
26
+ ) # :nodoc:
27
+ private_constant :READ_QUERY
28
+
29
+ def write_query?(sql) # :nodoc:
30
+ !READ_QUERY.match?(sql)
31
+ rescue ArgumentError # Invalid encoding
32
+ !READ_QUERY.match?(sql.b)
33
+ end
34
+
35
+ # Executes an SQL statement, returning a PG::Result object on success
36
+ # or raising a PG::Error exception otherwise.
37
+ # Note: the PG::Result object is manually memory managed; if you don't
38
+ # need it specifically, you may want consider the <tt>exec_query</tt> wrapper.
39
+ def execute(sql, name = nil)
40
+ sql = transform_query(sql)
41
+ check_if_write_query(sql)
42
+
43
+ materialize_transactions
44
+ mark_transaction_written_if_write(sql)
45
+
46
+ log(sql, name) do
47
+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
48
+ @connection.async_exec(sql)
49
+ end
50
+ end
51
+ end
52
+
53
+ def exec_query(sql, name = "SQL", binds = [], prepare: false, async: false) # :nodoc:
54
+ execute_and_clear(sql, name, binds, prepare: prepare, async: async) do |result|
55
+ types = {}
56
+ fields = result.fields
57
+ fields.each_with_index do |fname, i|
58
+ ftype = result.ftype i
59
+ fmod = result.fmod i
60
+ case type = get_oid_type(ftype, fmod, fname)
61
+ when Type::Integer, Type::Float, OID::Decimal, Type::String, Type::DateTime, Type::Boolean
62
+ # skip if a column has already been type casted by pg decoders
63
+ else types[fname] = type
64
+ end
65
+ end
66
+ build_result(columns: fields, rows: result.values, column_types: types)
67
+ end
68
+ end
69
+
70
+ def exec_delete(sql, name = nil, binds = []) # :nodoc:
71
+ execute_and_clear(sql, name, binds) { |result| result.cmd_tuples }
72
+ end
73
+ alias :exec_update :exec_delete
74
+
75
+ def sql_for_insert(sql, pk, binds) # :nodoc:
76
+ if pk.nil?
77
+ # Extract the table from the insert sql. Yuck.
78
+ table_ref = extract_table_ref_from_insert_sql(sql)
79
+ pk = primary_key(table_ref) if table_ref
80
+ end
81
+
82
+ if pk = suppress_composite_primary_key(pk)
83
+ sql = "#{sql} RETURNING #{quote_column_name(pk)}"
84
+ end
85
+
86
+ super
87
+ end
88
+ private :sql_for_insert
89
+
90
+ def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil) # :nodoc:
91
+ if use_insert_returning? || pk == false
92
+ super
93
+ else
94
+ result = exec_query(sql, name, binds)
95
+ unless sequence_name
96
+ table_ref = extract_table_ref_from_insert_sql(sql)
97
+ if table_ref
98
+ pk = primary_key(table_ref) if pk.nil?
99
+ pk = suppress_composite_primary_key(pk)
100
+ sequence_name = default_sequence_name(table_ref, pk)
101
+ end
102
+ return result unless sequence_name
103
+ end
104
+ last_insert_id_result(sequence_name)
105
+ end
106
+ end
107
+
108
+ # Begins a transaction.
109
+ def begin_db_transaction # :nodoc:
110
+ execute("BEGIN", "TRANSACTION")
111
+ end
112
+
113
+ def begin_isolated_db_transaction(isolation) # :nodoc:
114
+ begin_db_transaction
115
+ execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
116
+ end
117
+
118
+ # Commits a transaction.
119
+ def commit_db_transaction # :nodoc:
120
+ execute("COMMIT", "TRANSACTION")
121
+ end
122
+
123
+ # Aborts a transaction.
124
+ def exec_rollback_db_transaction # :nodoc:
125
+ execute("ROLLBACK", "TRANSACTION")
126
+ end
127
+
128
+ # From https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT
129
+ HIGH_PRECISION_CURRENT_TIMESTAMP = Arel.sql("CURRENT_TIMESTAMP").freeze # :nodoc:
130
+ private_constant :HIGH_PRECISION_CURRENT_TIMESTAMP
131
+
132
+ def high_precision_current_timestamp
133
+ HIGH_PRECISION_CURRENT_TIMESTAMP
134
+ end
135
+
136
+ private
137
+ def execute_batch(statements, name = nil)
138
+ execute(combine_multi_statements(statements))
139
+ end
140
+
141
+ def build_truncate_statements(table_names)
142
+ ["TRUNCATE TABLE #{table_names.map(&method(:quote_table_name)).join(", ")}"]
143
+ end
144
+
145
+ # Returns the current ID of a table's sequence.
146
+ def last_insert_id_result(sequence_name)
147
+ exec_query("SELECT currval(#{quote(sequence_name)})", "SQL")
148
+ end
149
+
150
+ def suppress_composite_primary_key(pk)
151
+ pk unless pk.is_a?(Array)
152
+ end
153
+ end
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,19 @@
1
+ require "active_record/base"
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module YugabyteDB
6
+ class DatabaseTasks < ActiveRecord::Tasks::PostgreSQLDatabaseTasks
7
+ def structure_load(filename, extra_flags)
8
+ # todo
9
+ args = ["--set", ON_ERROR_STOP_1, "--quiet", "--no-psqlrc", "--output", File::NULL, "--file", filename]
10
+ args.concat(Array(extra_flags)) if extra_flags
11
+ args << db_config.database
12
+ run_cmd("psql", args, "loading")
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
18
+
19
+ ActiveRecord::Tasks::DatabaseTasks.register_task(/yugabytedb/, ActiveRecord::ConnectionAdapters::YugabyteDB::DatabaseTasks)
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module YugabyteDB
6
+ class ExplainPrettyPrinter # :nodoc:
7
+ # Pretty prints the result of an EXPLAIN in a way that resembles the output of the
8
+ # PostgreSQL shell:
9
+ #
10
+ # QUERY PLAN
11
+ # ------------------------------------------------------------------------------
12
+ # Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
13
+ # Join Filter: (posts.user_id = users.id)
14
+ # -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
15
+ # Index Cond: (id = 1)
16
+ # -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
17
+ # Filter: (posts.user_id = 1)
18
+ # (6 rows)
19
+ #
20
+ def pp(result)
21
+ header = result.columns.first
22
+ lines = result.rows.map(&:first)
23
+
24
+ # We add 2 because there's one char of padding at both sides, note
25
+ # the extra hyphens in the example above.
26
+ width = [header, *lines].map(&:length).max + 2
27
+
28
+ pp = []
29
+
30
+ pp << header.center(width).rstrip
31
+ pp << "-" * width
32
+
33
+ pp += lines.map { |line| " #{line}" }
34
+
35
+ nrows = result.rows.length
36
+ rows_label = nrows == 1 ? "row" : "rows"
37
+ pp << "(#{nrows} #{rows_label})"
38
+
39
+ pp.join("\n") + "\n"
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ConnectionAdapters
5
+ module YugabyteDB
6
+ module OID # :nodoc:
7
+ class Array < Type::Value # :nodoc:
8
+ include ActiveModel::Type::Helpers::Mutable
9
+
10
+ Data = Struct.new(:encoder, :values) # :nodoc:
11
+
12
+ attr_reader :subtype, :delimiter
13
+ delegate :type, :user_input_in_time_zone, :limit, :precision, :scale, to: :subtype
14
+
15
+ def initialize(subtype, delimiter = ",")
16
+ @subtype = subtype
17
+ @delimiter = delimiter
18
+
19
+ @pg_encoder = YugabyteYSQL::TextEncoder::Array.new name: "#{type}[]", delimiter: delimiter
20
+ @pg_decoder = YugabyteYSQL::TextDecoder::Array.new name: "#{type}[]", delimiter: delimiter
21
+ end
22
+
23
+ def deserialize(value)
24
+ case value
25
+ when ::String
26
+ type_cast_array(@pg_decoder.decode(value), :deserialize)
27
+ when Data
28
+ type_cast_array(value.values, :deserialize)
29
+ else
30
+ super
31
+ end
32
+ end
33
+
34
+ def cast(value)
35
+ if value.is_a?(::String)
36
+ value = begin
37
+ @pg_decoder.decode(value)
38
+ rescue TypeError
39
+ # malformed array string is treated as [], will raise in PG 2.0 gem
40
+ # this keeps a consistent implementation
41
+ []
42
+ end
43
+ end
44
+ type_cast_array(value, :cast)
45
+ end
46
+
47
+ def serialize(value)
48
+ if value.is_a?(::Array)
49
+ casted_values = type_cast_array(value, :serialize)
50
+ Data.new(@pg_encoder, casted_values)
51
+ else
52
+ super
53
+ end
54
+ end
55
+
56
+ def ==(other)
57
+ other.is_a?(Array) &&
58
+ subtype == other.subtype &&
59
+ delimiter == other.delimiter
60
+ end
61
+
62
+ def type_cast_for_schema(value)
63
+ return super unless value.is_a?(::Array)
64
+ "[" + value.map { |v| subtype.type_cast_for_schema(v) }.join(", ") + "]"
65
+ end
66
+
67
+ def map(value, &block)
68
+ value.map(&block)
69
+ end
70
+
71
+ def changed_in_place?(raw_old_value, new_value)
72
+ deserialize(raw_old_value) != new_value
73
+ end
74
+
75
+ def force_equality?(value)
76
+ value.is_a?(::Array)
77
+ end
78
+
79
+ private
80
+ def type_cast_array(value, method)
81
+ if value.is_a?(::Array)
82
+ value.map { |item| type_cast_array(item, method) }
83
+ else
84
+ @subtype.public_send(method, value)
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end