arfi 0.3.1 → 0.5.0

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
2
  SHA256:
3
- metadata.gz: 072f0f4098aec38e2d25e6d3350502930f9be8b0c5b6396545239662c2651570
4
- data.tar.gz: 8be6c8f4e5f8a38b381289c8fe127d07c9a23313aa87b24022ddb5457eb9429f
3
+ metadata.gz: 40e55ca1e1481bb0b4e2c0e52dba409acee9cab6dc52b175c8ea07c43a8ff480
4
+ data.tar.gz: 54cf735abda9f80045e1d5dd182993fdbe3b9a82f4b1280a5bd0f9ca96664551
5
5
  SHA512:
6
- metadata.gz: ab81783efb65e023578c70e578248ea267ba3bac815726d9911ced210c139424da8e777160f75c903cdbc45e718d137772109581fe120ef886f73d31cd524f01
7
- data.tar.gz: ce0c50d27cce3dedd894106ef50111d13b0424e00e690c2acd731c213863fcbd988d8e2a3fa7265962c58b874a320b3d04c6ab36b815524550c39472eca4b26e
6
+ metadata.gz: 47e45b99ccccac4149e6fe340b72ff1a418c245fb6f151890d473c2ef18c0ef7d435e0faf95483cafbeee64478db2d1265281dc1fff8a8b32f0a39a9df10caa4
7
+ data.tar.gz: 6c008777c326d7f15afab77e1a6473ce6a4f94525898e2392d55664ff5d6b4213d2ed5a06050fdfd44a9e8f183cb66278bd17e832b15f4b256591129a73c95eb
data/README.md CHANGED
@@ -1,28 +1,35 @@
1
1
  # ARFI
2
2
 
3
+ ![Build status](https://img.shields.io/github/actions/workflow/status/unurgunite/arfi/main.yml "Build status")
4
+ [![Gem Version](https://badge.fury.io/rb/arfi.svg)](https://badge.fury.io/rb/arfi)
5
+
3
6
  ![Alt](https://repobeats.axiom.co/api/embed/324b4f481b219890ef5a26e3c6fb73fff8929c93.svg "Repobeats analytics image")
4
7
 
5
8
  ---
6
9
 
7
10
  > [!WARNING]
8
- > This project only supports PostgreSQL databases, however, MySQL usage will also be available in upcoming updates.
9
- > Since SQLite3 does not support functional indexes with custom functions, support for this database will not be
10
- > available for a while, however, you can help the project by contributing to the open source.
11
+ > This project only supports PostgreSQL and MySQL databases. SQLite3 will be supported in the future as well as other
12
+ > databases supported by Rails.
11
13
 
12
14
  > [!NOTE]
13
- > This project requires Ruby 3.1.0+, it has not yet been tested on other versions, however, at the time of writing,
14
- > backward compatibility was maintained wherever possible.
15
+ > This project requires Ruby 3.1.0+, in future updated 2.6+ Ruby versions will be supported.
15
16
 
16
17
  ---
17
18
 
18
19
  ARFI – *ActiveRecord Functional Indexes*
19
20
 
20
- ARFI gem brings you the ability to create and maintain functional indexes for your ActiveRecord models without
21
- transition to `structure.sql` (SQL-based schema).
21
+ The ARFI gem provides the ability to create and maintain custom SQL functions for ActiveRecord models without switching
22
+ to `structure.sql` (an SQL-based schema). You can use your own SQL functions in any part of the project, from migrations
23
+ and models to everything else. There is a working example in
24
+ the [demo project](https://github.com/unurgunite/poc_arfi_72). All instructions are described
25
+ in [README](https://github.com/unurgunite/poc_arfi_72/blob/master/README.md). ARFI supports all types of database
26
+ architectures implemented in Rails, suitable for both working with single databases and for simultaneous work with
27
+ multiple databases in the same environment.
22
28
 
23
29
  * [ARFI](#arfi)
24
30
  * [Installation](#installation)
25
31
  * [Usage](#usage)
32
+ * [Internal documentation](#internal-documentation)
26
33
  * [CLI](#cli)
27
34
  * [Project creation](#project-creation)
28
35
  * [Index creation](#index-creation)
@@ -31,6 +38,13 @@ transition to `structure.sql` (SQL-based schema).
31
38
  * [Demo](#demo)
32
39
  * [Library features](#library-features)
33
40
  * [Roadmap](#roadmap)
41
+ * [Commands](#commands)
42
+ * [Function creation](#function-creation)
43
+ * [Function destroy](#function-destroy)
44
+ * [Options](#options)
45
+ * [`--template` option](#--template-option)
46
+ * [`--adapter` option](#--adapter-option)
47
+ * [Limitations](#limitations)
34
48
  * [Development](#development)
35
49
  * [Build from source](#build-from-source)
36
50
  * [Requirements](#requirements)
@@ -49,6 +63,10 @@ bundle add arfi
49
63
 
50
64
  ## Usage
51
65
 
66
+ ### Internal documentation
67
+
68
+ Internal documentation available at https://github.com/unurgunite/arfi_docs.
69
+
52
70
  ### CLI
53
71
 
54
72
  ARFI uses Thor as a command line interface (CLI) instead of Rake, so it has a specific DSL.
@@ -56,17 +74,20 @@ ARFI uses Thor as a command line interface (CLI) instead of Rake, so it has a sp
56
74
  ### Project creation
57
75
 
58
76
  Firstly, run `bundle exec arfi project create` to create a new project. This command will create `db/functions`
59
- directory. ARFI uses `db/functions` directory to store your functional indexes.
77
+ directory. ARFI uses `db/functions` directory to store your SQL functions.
60
78
 
61
- ### Index creation
79
+ ### Function creation
62
80
 
63
- Run `bundle exec arfi f_idx create function_name` to create a new functional index. New index will be created in
64
- `db/functions` directory under `function_name_v01.sql` name. Edit you index and run `bundle exec rails db:migrate`. You
65
- can also use custom template for index. Type `bundle exec arfi f_idx help create` for additional info.
81
+ Run `bundle exec arfi f_idx create function_name` to create a new function. New SQL function will be created in
82
+ `db/functions` directory under `function_name_v01.sql` name. Edit your function and run `bundle exec rails db:migrate`.
83
+ You can also use custom template for functions using `--template` flag, this behaviour is described below.
84
+ Type `bundle exec arfi f_idx help create` for additional info.
66
85
 
67
- ### Index destroy
86
+ ### Function destroy
68
87
 
69
- If you want to destroy your index, run `bundle exec arfi f_idx destroy function_name [revision (1 by default)]`
88
+ If you want to destroy your function, run `bundle exec arfi f_idx destroy function_name [revision (default 1)]`. Please
89
+ note that after deleting the function, it will still be available, but if you run "bundle exec rails db:migrate" again,
90
+ an error will occur when using the function. Enter `bundle exec arfi f_idx help destroy` for more information.
70
91
 
71
92
  ### Additional help
72
93
 
@@ -79,40 +100,118 @@ README is also available.
79
100
 
80
101
  ## Library features
81
102
 
82
- 1. ARFI supports all types of database initialization
103
+ 1. ARFI supports about all types of database initialization. It respects your database schema format and database
104
+ configuration.
83
105
 
84
- | Task | Completed |
85
- |----------------|--------------------|
86
- | db:migrate | :white_check_mark: |
87
- | db:setup | :white_check_mark: |
88
- | db:prepare | :white_check_mark: |
89
- | db:schema:load | :white_check_mark: |
106
+ | Task | Completed |
107
+ |------------------|--------------------------------------------------------------|
108
+ | db:migrate | :white_check_mark: |
109
+ | db:setup | :white_check_mark: |
110
+ | db:prepare | :white_check_mark: |
111
+ | db:schema:load | :white_check_mark: |
112
+ | db:reset | :white_check_mark: |
113
+ | db:setup:db_name | In progress (see [limitations][1]) :arrows_counterclockwise: |
90
114
 
91
- 2. Database support
115
+ 2. Database support. ARFI supports PostgreSQL and MySQL databases and projects with multiple databases at the same time.
92
116
 
93
- | DB adapter | Tested |
94
- |----------------|-------------------------------------------------------|
95
- | PostgreSQL | 9+ :white_check_mark: |
96
- | MySQL | In progress :arrows_counterclockwise: |
97
- | SQLite3 | In progress (not primarily) :arrows_counterclockwise: |
117
+ | DB adapter | Tested |
118
+ |------------|---------------------------------------|
119
+ | PostgreSQL | :white_check_mark: |
120
+ | MySQL | :white_check_mark: |
121
+ | SQLite3 | In progress :arrows_counterclockwise: |
98
122
 
99
123
  3. Rails support
100
124
 
101
125
  | Rails version | Tested |
102
126
  |---------------|---------------------------------------|
103
- | 8 | In progress :arrows_counterclockwise: |
127
+ | 8 | :white_check_mark: |
104
128
  | 7 | :white_check_mark: |
105
129
  | 6 | In progress :arrows_counterclockwise: |
106
130
 
107
131
  ## Roadmap
108
132
 
109
133
  1. ~~Custom template for SQL functions using `--template` flag;~~
110
- 2. Multidb support (Rails 6+ feature);
134
+ 2. ~~Multidb support (Rails 6+ feature);~~
111
135
  3. Add support for 4+ ActiveRecord;
112
136
  4. Add RSpec tests;
113
- 5. Add separate YARD doc page;
114
- 6. Update CI/CD;
115
- 7. Add support for Ruby 2.6+.
137
+ 5. ~~Add separate YARD doc page;~~
138
+ 6. ~~Update CI/CD;~~
139
+ 7. Add support for Ruby 2.6+.
140
+
141
+ ## Commands
142
+
143
+ ARFI has a set of commands to work with SQL functions. Type `bundle exec arfi help` for additional help. As noted above,
144
+ ARFI uses Thor as a command line interface.
145
+
146
+ ### Function creation
147
+
148
+ ARFI supports creation of SQL functions. To create a new function, run `bundle exec arfi f_idx create function_name`.
149
+ Also, there are some options:
150
+
151
+ | Option name | Description | Possible values | Default value |
152
+ |--------------|--------------------------------------------------------------------------------------|----------------------------|---------------------------------------------------------------|
153
+ | `--template` | use custom template | path within you filesystem | nil (will be used default template for each type of adapters) |
154
+ | `--adapter` | adapter specific function creation due to syntax differences between different RDBMS | postgresql, mysql | nil (function will be stored in generic `db/functions`) |
155
+
156
+ ### Function destroy
157
+
158
+ ARFI supports destroy of SQL functions. To destroy a function, run
159
+ `bundle exec arfi f_idx destroy function_name [revision (1 by default)]`.
160
+
161
+ | Option name | Description | Possible values | Default value |
162
+ |--------------|------------------------------|-------------------|------------------------------------------------------------|
163
+ | `--revision` | Function revision to destroy | Integer | 1 |
164
+ | `--adapter` | adapter specific function | postgresql, mysql | nil (function will be destroyed in generic `db/functions`) |
165
+
166
+ #### Options
167
+
168
+ ##### `--template` option
169
+
170
+ This option is used for creating an SQL function. In this case, the function will not be created with the default
171
+ template, but with user defined. There are some rules for templates:
172
+
173
+ 1. The template must be written in a Ruby-compatible syntax: the function must be placed in a HEREDOC statement and must
174
+ use interpolation for variables. If you need to take a more comprehensive approach to the issue of function
175
+ generation, you can try using your own methods in the template file. No matter what you write there, the main rule is
176
+ that your main method should return a string with a function template, as described below.
177
+ 2. ARFI supports dynamic variables in templates, but only one at the moment. You need to specify `index_name`
178
+ variable as below. In feature updated ARFI will support more variables. Here are default templates in ARFI for
179
+ PostgreSQL and MySQL:
180
+
181
+ PostgreSQL:
182
+ ```ruby
183
+ <<~SQL
184
+ CREATE OR REPLACE FUNCTION #{index_name}() RETURNS TEXT[]
185
+ LANGUAGE SQL
186
+ IMMUTABLE AS
187
+ $$
188
+ -- Function body here
189
+ $$
190
+ SQL
191
+ ```
192
+ MySQL:
193
+ ```ruby
194
+ <<~SQL
195
+ CREATE FUNCTION #{index_name} ()
196
+ RETURNS return_type
197
+ BEGIN
198
+ -- Function body here
199
+ END;
200
+ SQL
201
+ ```
202
+ 3. By default ARFI uses PostgreSQL template.
203
+
204
+ ##### `--adapter` option
205
+
206
+ This option is used both when destroying and when creating an SQL function. In this case, the function will not be
207
+ created in the default directory `db/functions`, but in the child `db/functions/#{adapter}`. Supported adapters:
208
+ `postgresql`and `mysql`, but there will be more in the future.
209
+
210
+ ## Limitations
211
+
212
+ Currently, ARFI has a limitation for `db:setup:db_name` task due to the fact how Rails manage this rake task. More info
213
+ here: [limitations][1]. This command will work, but it is not recommended to use it. Note that this limitation applies
214
+ only to multi-db setup, default `db:setup` will work as expected.
116
215
 
117
216
  ## Development
118
217
 
@@ -126,7 +225,7 @@ git clone https://github.com/unurgunite/arfi.git
126
225
  cd arfi
127
226
  bundle install
128
227
  gem build arfi.gemspec
129
- gem install arfi-0.3.1.gem
228
+ gem install arfi-0.5.0.gem
130
229
  ```
131
230
 
132
231
  Also, you can run `bin/setup` to automatically install everything needed.
@@ -142,12 +241,15 @@ ARFI is built on top of the following gems:
142
241
  | Thor | For CLI development. |
143
242
  | Rubocop | For static code analysis. |
144
243
  | Rake | For patching built-in Rails Rake tasks. |
244
+ | Steep | For static type checking. |
245
+ | RBS | For static type checking. |
246
+ | YARD | For generating documentation. |
145
247
 
146
248
  ## Contributing
147
249
 
148
250
  Bug reports and pull requests are welcome on GitHub at https://github.com/unurgunite/arfi. This project is intended to
149
251
  be a safe, welcoming space for collaboration, and contributors are expected to adhere to
150
- the [code of conduct](https://github.com/[USERNAME]/Arfi/blob/master/CODE_OF_CONDUCT.md).
252
+ the [code of conduct](https://github.com/unurgunite/arfi/blob/master/CODE_OF_CONDUCT.md).
151
253
 
152
254
  ## Miscellaneous
153
255
 
@@ -160,4 +262,6 @@ The gem is available as open source under the terms of the [MIT License](https:/
160
262
  ## Code of Conduct
161
263
 
162
264
  Everyone interacting in the ARFI project's codebases, issue trackers, chat rooms and mailing lists is expected to follow
163
- the [code of conduct](https://github.com/[USERNAME]/Arfi/blob/master/CODE_OF_CONDUCT.md).
265
+ the [code of conduct](https://github.com/unurgunite/arfi/blob/master/CODE_OF_CONDUCT.md).
266
+
267
+ [1]: https://blog.saeloun.com/2021/10/27/rails-7-adds-database-specific-setup/#limitation
data/Steepfile ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # D = Steep::Diagnostic
4
+ #
5
+ target :lib do
6
+ signature 'sig'
7
+ # ignore_signature "sig/test"
8
+ # use "rbs_collection"
9
+ check 'lib' # Directory name
10
+ # check "path/to/source.rb" # File name
11
+ # check "app/models/**/*.rb" # Glob
12
+ # ignore "lib/templates/*.rb"
13
+ ignore 'lib/arfi/extensions/active_record/connection_adapters/postgresql/database_statements.rb'
14
+
15
+ # library "pathname" # Standard libraries
16
+ # library "strong_json" # Gems
17
+
18
+ # configure_code_diagnostics(D::Ruby.default) # `default` diagnostics setting (applies by default)
19
+ # configure_code_diagnostics(D::Ruby.strict) # `strict` diagnostics setting
20
+ # configure_code_diagnostics(D::Ruby.lenient) # `lenient` diagnostics setting
21
+ # configure_code_diagnostics(D::Ruby.silent) # `silent` diagnostics setting
22
+ # configure_code_diagnostics do |hash| # You can setup everything yourself
23
+ # hash[D::Ruby::NoMethod] = :information
24
+ # end
25
+ end
26
+
27
+ # target :test do
28
+ # unreferenced! # Skip type checking the `lib` code when types in `test` target is changed
29
+ # signature "sig/test" # Put RBS files for tests under `sig/test`
30
+ # check "test" # Type check Ruby scripts under `test`
31
+ #
32
+ # configure_code_diagnostics(D::Ruby.lenient) # Weak type checking for test code
33
+ #
34
+ # # library "pathname" # Standard libraries
35
+ # end
data/lib/arfi/cli.rb CHANGED
@@ -4,13 +4,20 @@ require 'thor'
4
4
  require_relative 'commands/project'
5
5
  require_relative 'commands/f_idx'
6
6
 
7
+ # steep:ignore:start
7
8
  module Arfi
8
9
  # Top level CLI class
9
10
  class CLI < Thor
10
11
  desc 'project [COMMAND]', 'Project specific commands.'
11
12
  subcommand 'project', Commands::Project
12
13
 
13
- desc 'f_idx [COMMAND]', 'Command to handle functional indexes.'
14
+ desc 'f_idx [COMMAND]', 'Command to handle functions.'
14
15
  subcommand 'f_idx', Commands::FIdx
16
+
17
+ desc 'version', 'Print the version'
18
+ def version
19
+ $stdout.write(Arfi::VERSION, "\n")
20
+ end
15
21
  end
16
22
  end
23
+ # steep:ignore:end
@@ -8,8 +8,18 @@ module Arfi
8
8
  module Commands
9
9
  # +Arfi::Commands::FIdx+ module contains commands for manipulating functional index in Rails project.
10
10
  class FIdx < Thor
11
- desc 'create INDEX_NAME', 'Initialize the functional index'
12
- option :template, type: :string, banner: 'template_file'
11
+ ADAPTERS = %i[postgresql mysql].freeze
12
+
13
+ # steep:ignore:start
14
+ desc 'create FUNCTION_NAME [--template=template_file --adapter=adapter]', 'Initialize the functional index'
15
+ option :template, type: :string, banner: 'template_file',
16
+ desc: 'Path to the template file. See `README.md` for details.'
17
+ option :adapter, type: :string,
18
+ desc: 'Specify database adapter, used for projects with multiple database architecture. ' \
19
+ "Available adapters: #{ADAPTERS.join(', ')}",
20
+ banner: 'adapter'
21
+ # steep:ignore:end
22
+
13
23
  # +Arfi::Commands::FIdx#create+ -> void
14
24
  #
15
25
  # This command is used to create the functional index.
@@ -47,10 +57,18 @@ module Arfi
47
57
  def create(index_name)
48
58
  validate_schema_format!
49
59
  content = build_sql_function(index_name)
50
- create_index_file(index_name, content)
60
+ create_function_file(index_name, content)
51
61
  end
52
62
 
53
- desc 'destroy INDEX_NAME [REVISION]', 'Delete the functional index'
63
+ # steep:ignore:start
64
+ desc 'destroy INDEX_NAME [--revision=revision --adapter=adapter]', 'Delete the functional index.'
65
+ option :revision, type: :string, banner: 'revision', desc: 'Revision of the function.'
66
+ option :adapter, type: :string,
67
+ desc: 'Specify database adapter, used for projects with multiple database architecture. ' \
68
+ "Available adapters: #{ADAPTERS.join(', ')}",
69
+ banner: 'adapter'
70
+ # steep:ignore:end
71
+
54
72
  # +Arfi::Commands::FIdx#destroy+ -> void
55
73
  #
56
74
  # This command is used to delete the functional index.
@@ -58,30 +76,19 @@ module Arfi
58
76
  # @example
59
77
  # bundle exec arfi f_idx destroy some_function [revision index (just an integer, 1 is by default)]
60
78
  # @param index_name [String] Name of the index.
61
- # @param revision [String] Revision of the index.
62
79
  # @return [void]
63
80
  # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby
64
- def destroy(index_name, revision = '01')
81
+ def destroy(index_name)
65
82
  validate_schema_format!
66
83
 
67
- revision = "0#{revision}" if revision.match?(/^\d$/)
84
+ revision = Integer(options[:revision] || '01') # steep:ignore NoMethod
85
+ revision = "0#{revision}"
68
86
  FileUtils.rm("#{functions_dir}/#{index_name}_v#{revision}.sql")
69
87
  puts "Deleted: #{functions_dir}/#{index_name}_v#{revision}.sql"
70
88
  end
71
89
 
72
90
  private
73
91
 
74
- # +Arfi::Commands::FIdx#functions_dir+ -> Pathname
75
- #
76
- # Helper method to get path to `db/functions` directory.
77
- #
78
- # @!visibility private
79
- # @private
80
- # @return [Pathname] Path to `db/functions` directory
81
- def functions_dir
82
- Rails.root.join('db/functions')
83
- end
84
-
85
92
  # +Arfi::Commands::FIdx#validate_schema_format!+ -> void
86
93
  #
87
94
  # Helper method to validate the schema format.
@@ -91,7 +98,7 @@ module Arfi
91
98
  # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby.
92
99
  # @return [nil] if the schema format is valid.
93
100
  def validate_schema_format!
94
- raise Arfi::Errors::InvalidSchemaFormat unless ActiveRecord.schema_format == :ruby
101
+ raise Arfi::Errors::InvalidSchemaFormat unless ActiveRecord.schema_format == :ruby # steep:ignore NoMethod
95
102
  end
96
103
 
97
104
  # +Arfi::Commands::FIdx#build_sql_function+ -> String
@@ -102,17 +109,43 @@ module Arfi
102
109
  # @private
103
110
  # @param index_name [String] Name of the index.
104
111
  # @return [String] SQL function body.
105
- def build_sql_function(index_name)
106
- return build_from_file(index_name) if options[:template]
107
-
108
- <<~SQL
109
- CREATE OR REPLACE FUNCTION #{index_name}() RETURNS TEXT[]
110
- LANGUAGE SQL
111
- IMMUTABLE AS
112
- $$
112
+ def build_sql_function(index_name) # rubocop:disable Metrics/MethodLength
113
+ return build_from_file(index_name) if options[:template] # steep:ignore NoMethod
114
+
115
+ unless options[:adapter] # steep:ignore NoMethod
116
+ return <<~SQL
117
+ CREATE OR REPLACE FUNCTION #{index_name}() RETURNS TEXT[]
118
+ LANGUAGE SQL
119
+ IMMUTABLE AS
120
+ $$
121
+ -- Function body here
122
+ $$
123
+ SQL
124
+ end
125
+
126
+ case options[:adapter] # steep:ignore NoMethod
127
+ when 'postgresql'
128
+ <<~SQL
129
+ CREATE OR REPLACE FUNCTION #{index_name}() RETURNS TEXT[]
130
+ LANGUAGE SQL
131
+ IMMUTABLE AS
132
+ $$
133
+ -- Function body here
134
+ $$
135
+ SQL
136
+ when 'mysql'
137
+ <<~SQL
138
+ CREATE FUNCTION #{index_name} ()
139
+ RETURNS return_type
140
+ BEGIN
113
141
  -- Function body here
114
- $$
115
- SQL
142
+ END;
143
+ SQL
144
+ else
145
+ # steep:ignore:start
146
+ raise "Unknown adapter: #{options[:adapter]}. Supported adapters: #{ADAPTERS.join(', ')}"
147
+ # steep:ignore:end
148
+ end
116
149
  end
117
150
 
118
151
  # +Arfi::Commands::FIdx#build_from_file+ -> String
@@ -126,10 +159,12 @@ module Arfi
126
159
  # @see Arfi::Commands::FIdx#create
127
160
  # @see Arfi::Commands::FIdx#build_sql_function
128
161
  def build_from_file(index_name)
162
+ # steep:ignore:start
129
163
  RubyVM::InstructionSequence.compile("index_name = '#{index_name}'; #{File.read(options[:template])}").eval
164
+ # steep:ignore:end
130
165
  end
131
166
 
132
- # +Arfi::Commands::FIdx#create_index_file+ -> void
167
+ # +Arfi::Commands::FIdx#create_function_file+ -> void
133
168
  #
134
169
  # Helper method to create the index file.
135
170
  #
@@ -138,13 +173,13 @@ module Arfi
138
173
  # @param index_name [String] Name of the index.
139
174
  # @param content [String] SQL function body.
140
175
  # @return [void]
141
- def create_index_file(index_name, content)
176
+ def create_function_file(index_name, content)
142
177
  existing_files = Dir.glob("#{functions_dir}/#{index_name}*.sql")
143
178
 
144
179
  return write_file(index_name, content, 1) if existing_files.empty?
145
180
 
146
181
  latest_version = extract_latest_version(existing_files)
147
- write_file(index_name, content, latest_version.next)
182
+ write_file(index_name, content, latest_version.succ)
148
183
  end
149
184
 
150
185
  # +Arfi::Commands::FIdx#extract_latest_version+ -> Integer
@@ -171,14 +206,33 @@ module Arfi
171
206
  # @private
172
207
  # @param index_name [String] Name of the index.
173
208
  # @param content [String] SQL function body.
174
- # @param version [Integer] Version of the index.
209
+ # @param version [String|Integer] Version of the index.
175
210
  # @return [void]
176
211
  def write_file(index_name, content, version)
177
212
  version_str = format('%02d', version)
178
213
  path = "#{functions_dir}/#{index_name}_v#{version_str}.sql"
179
- File.write(path, content)
214
+ File.write(path, content.to_s)
180
215
  puts "Created: #{path}"
181
216
  end
217
+
218
+ # +Arfi::Commands::FIdx#functions_dir+ -> Pathname
219
+ #
220
+ # Helper method to get path to `db/functions` directory.
221
+ #
222
+ # @!visibility private
223
+ # @private
224
+ # @return [Pathname] Path to `db/functions` directory
225
+ def functions_dir
226
+ # steep:ignore:start
227
+ if options[:adapter]
228
+ raise Arfi::Errors::AdapterNotSupported unless ADAPTERS.include?(options[:adapter].to_sym)
229
+
230
+ Rails.root.join("db/functions/#{options[:adapter]}")
231
+ # steep:ignore:end
232
+ else
233
+ Rails.root.join('db/functions')
234
+ end
235
+ end
182
236
  end
183
237
  end
184
238
  end
@@ -8,7 +8,16 @@ module Arfi
8
8
  module Commands
9
9
  # +Arfi::Commands::Project+ class is used to create `db/functions` directory.
10
10
  class Project < Thor
11
+ ADAPTERS = %i[postgresql mysql].freeze
12
+
13
+ # steep:ignore:start
11
14
  desc 'create', 'Initialize project by creating db/functions directory'
15
+ option :adapter, type: :string,
16
+ desc: 'Specify database adapter, used for projects with multiple database architecture. ' \
17
+ "Available adapters: #{ADAPTERS.join(', ')}",
18
+ banner: 'adapter'
19
+ # steep:ignore:end
20
+
12
21
  # +Arfi::Commands::Project#create+ -> void
13
22
  #
14
23
  # This command is used to create `db/functions` directory.
@@ -18,7 +27,7 @@ module Arfi
18
27
  # @return [void]
19
28
  # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby.
20
29
  def create
21
- raise Arfi::Errors::InvalidSchemaFormat unless ActiveRecord.schema_format == :ruby
30
+ raise Arfi::Errors::InvalidSchemaFormat unless ActiveRecord.schema_format == :ruby # steep:ignore NoMethod
22
31
  return puts "Directory #{functions_dir} already exists" if Dir.exist?(functions_dir)
23
32
 
24
33
  FileUtils.mkdir_p(functions_dir)
@@ -27,7 +36,7 @@ module Arfi
27
36
 
28
37
  private
29
38
 
30
- # +Arfi::Commands::Project#functions_dir+ -> Pathname
39
+ # +Arfi::Commands::Project#functions_dir+ -> Pathname
31
40
  #
32
41
  # Helper method to get path to `db/functions` directory.
33
42
  #
@@ -35,7 +44,15 @@ module Arfi
35
44
  # @private
36
45
  # @return [Pathname] Path to `db/functions` directory
37
46
  def functions_dir
38
- Rails.root.join('db/functions')
47
+ # steep:ignore:start
48
+ if options[:adapter]
49
+ raise Arfi::Errors::AdapterNotSupported unless ADAPTERS.include?(options[:adapter].to_sym)
50
+
51
+ Rails.root.join("db/functions/#{options[:adapter]}")
52
+ # steep:ignore:end
53
+ else
54
+ Rails.root.join('db/functions')
55
+ end
39
56
  end
40
57
  end
41
58
  end
@@ -13,8 +13,24 @@ module ActiveRecord
13
13
  # ActiveRecord::Base.function_exists?('my_function123') #=> false
14
14
  # @param [String] function_name The name of the function to check.
15
15
  # @return [Boolean] Returns true if the function exists, false otherwise.
16
- def self.function_exists?(function_name)
17
- connection.execute("SELECT * FROM pg_proc WHERE proname = '#{function_name}'").any?
16
+ def self.function_exists?(function_name) # rubocop:disable Metrics/MethodLength
17
+ case connection
18
+ when ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
19
+ connection.execute("SELECT * FROM pg_proc WHERE proname = '#{function_name}'").any?
20
+ when ActiveRecord::ConnectionAdapters::Mysql2Adapter
21
+ sql = <<~SQL
22
+ SELECT 1
23
+ FROM information_schema.ROUTINES
24
+ WHERE ROUTINE_TYPE = 'FUNCTION'
25
+ AND ROUTINE_SCHEMA = '#{connection.current_database}'
26
+ AND ROUTINE_NAME = '#{function_name}'
27
+ LIMIT 1;
28
+ SQL
29
+
30
+ !!connection.execute(sql).first
31
+ else
32
+ raise ActiveRecord::AdapterNotFound, "adapter #{connection.class.name} is not supported"
33
+ end
18
34
  end
19
35
  end
20
36
  end
@@ -6,6 +6,7 @@ module ActiveRecord
6
6
  module ConnectionAdapters
7
7
  module PostgreSQL
8
8
  module DatabaseStatements
9
+ # This patch is used for db:prepare task.
9
10
  def raw_execute(sql, name, async: false, allow_retry: false, materialize_transactions: true)
10
11
  log(sql, name, async: async) do |notification_payload|
11
12
  with_raw_connection(allow_retry: allow_retry, materialize_transactions: materialize_transactions) do |conn|
data/lib/arfi/railtie.rb CHANGED
@@ -8,7 +8,7 @@ module Arfi
8
8
  railtie_name :arfi
9
9
 
10
10
  rake_tasks do
11
- path = File.expand_path(__dir__)
11
+ path = File.expand_path(__dir__ || '.')
12
12
  Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f }
13
13
  end
14
14
  end