arfi 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4913826264984ac5b1770bdb6d8f7791091e5211744a2f1dc56743a1d623b3e6
4
+ data.tar.gz: ed864c812bdead458a6dcbb664a6a334fe4ec5789e0832699a619558005cfa74
5
+ SHA512:
6
+ metadata.gz: 29a2edda4c4fd87bedc107439269665033acc8f2c4d501a65727b6569ea47f512eaa857cb8b3c6e92111050ab11d7a63a0646c65cca62a559e149c3d0ce112ed
7
+ data.tar.gz: 33a01c96166d42f757972b24fe70e7743ddd64f519bccde85ff45539f76fed5577556ba33081021a0d9ce9f9040282469b2c5cbe3683c1bc4e0eb9ac85439dd7
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,3 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.4.2
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-04-22
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 daniil.lyubimcev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # ARFI
2
+
3
+ ![Alt](https://repobeats.axiom.co/api/embed/324b4f481b219890ef5a26e3c6fb73fff8929c93.svg "Repobeats analytics image")
4
+
5
+ ---
6
+
7
+ **! WARNING !**
8
+
9
+ This project supports only PostgreSQL databases. In near future, ARFI will support MySQL databases. Since SQLite3 does
10
+ not support functional indexes with custom functions, this project won't support SQLite3 databases in near future.
11
+
12
+ ---
13
+
14
+ ARFI – *ActiveRecord Functional Indexes*
15
+
16
+ ARFI gem brings you the ability to create and maintain functional indexes for your ActiveRecord models without
17
+ transition to `structure.sql` (SQL-based schema).
18
+
19
+ * [ARFI](#arfi)
20
+ * [Installation](#installation)
21
+ * [Usage](#usage)
22
+ * [CLI](#cli)
23
+ * [Project creation](#project-creation)
24
+ * [Index creation](#index-creation)
25
+ * [Index destroy](#index-destroy)
26
+ * [Additional help](#additional-help)
27
+ * [Development](#development)
28
+ * [Build from source](#build-from-source)
29
+ * [Requirements](#requirements)
30
+ * [Contributing](#contributing)
31
+ * [License](#license)
32
+ * [Code of Conduct](#code-of-conduct)
33
+
34
+ ## Installation
35
+
36
+ Install the gem and add to the application's Gemfile by executing:
37
+
38
+ ```bash
39
+ bundle add arfi
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ### CLI
45
+
46
+ ARFI uses Thor as a command line interface (CLI) instead of Rake, so it has a specific DSL.
47
+
48
+ ### Project creation
49
+
50
+ Firstly, run `bundle exec arfi project create` to create a new project. This command will create `db/functions`
51
+ directory. ARFI uses `db/functions` directory to store your functional indexes.
52
+
53
+ ### Index creation
54
+
55
+ Run `bundle exec arfi f_idx create function_name` to create a new functional index. New index will be created in
56
+ `db/functions` directory under `function_name_v01.sql` name. Edit you index and run `bundle exec rails db:migrate`
57
+
58
+ ### Index destroy
59
+
60
+ If you want to destroy your index, run `bundle exec arfi f_idx destroy function_name [revision (1 by default)]`
61
+
62
+ ### Additional help
63
+
64
+ Run `bundle exec arfi` for additional help.
65
+
66
+ ## Development
67
+
68
+ ### Build from source
69
+
70
+ The manual installation includes installation via command line interface. it is practically no different from what
71
+ happens during the automatic build of the project:
72
+
73
+ ```shell
74
+ git clone https://github.com/unurgunite/arfi.git
75
+ cd arfi
76
+ bundle install
77
+ gem build arfi.gemspec
78
+ gem install arfi-0.1.0.gem
79
+ ```
80
+
81
+ Also, you can run `bin/setup` to automatically install everything needed.
82
+
83
+ ## Requirements
84
+
85
+ ARFI is built on top of the following gems:
86
+
87
+ | Dependencies | Description |
88
+ |--------------|--------------------------------------------------------------------------------------------|
89
+ | ActiveRecord | Used to patch `ActiveRecord::Base` module with new methods. |
90
+ | Rails | Used for fetching project settings (database connection settings, Rails environment, etc.) |
91
+ | Thor | For CLI development. |
92
+ | Rubocop | For static code analysis. |
93
+ | Rake | For patching built-in Rails Rake tasks. |
94
+
95
+ ## Roadmap
96
+
97
+ | Task | Completed |
98
+ |----------------|-----------|
99
+ | db:migrate | [x] |
100
+ | db:setup | [] |
101
+ | db:prepare | [] |
102
+ | db:schema:load | [] |
103
+
104
+ ## Contributing
105
+
106
+ Bug reports and pull requests are welcome on GitHub at https://github.com/unurgunite/arfi. This project is intended to
107
+ be a safe, welcoming space for collaboration, and contributors are expected to adhere to
108
+ the [code of conduct](https://github.com/[USERNAME]/Arfi/blob/master/CODE_OF_CONDUCT.md).
109
+
110
+ ## License
111
+
112
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
113
+
114
+ ## Code of Conduct
115
+
116
+ Everyone interacting in the Arfi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow
117
+ the [code of conduct](https://github.com/[USERNAME]/Arfi/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/exe/arfi ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'thor'
5
+ require_relative '../lib/arfi/cli'
6
+
7
+ Arfi::CLI.start(ARGV)
data/lib/arfi/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'arfi'
4
+
5
+ path = File.expand_path(__dir__)
6
+ Dir.glob("#{path}/tasks/**/*.rake").each { |f| import f }
data/lib/arfi/cli.rb ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thor'
4
+ require_relative 'commands/project'
5
+ require_relative 'commands/f_idx'
6
+
7
+ module Arfi
8
+ # Top level CLI class
9
+ class CLI < Thor
10
+ desc 'project [COMMAND]', 'Project specific commands.'
11
+ subcommand 'project', Commands::Project
12
+
13
+ desc 'f_idx [COMMAND]', 'Command to handle functional indexes.'
14
+ subcommand 'f_idx', Commands::FIdx
15
+ end
16
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thor'
4
+ require 'rails'
5
+ require File.expand_path('config/environment', Dir.pwd)
6
+
7
+ module Arfi
8
+ module Commands
9
+ # +Arfi::Commands::FIdx+ module contains commands for manipulating functional index in Rails project.
10
+ class FIdx < Thor
11
+ desc 'create INDEX_NAME', 'Initialize the functional index'
12
+ # +Arfi::Commands::FIdx#create+ -> void
13
+ #
14
+ # This command is used to create the functional index.
15
+ #
16
+ # @example
17
+ # bundle exec arfi f_idx create some_function
18
+ # @param index_name [String] Name of the index.
19
+ # @return [void]
20
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby
21
+ # @raise [Arfi::Errors::NoFunctionsDir] if there is no `db/functions` directory
22
+ # @see Arfi::Commands::FIdx#validate_schema_format!
23
+ def create(index_name)
24
+ validate_schema_format!
25
+ content = build_sql_function(index_name)
26
+ create_index_file(index_name, content)
27
+ end
28
+
29
+ desc 'destroy INDEX_NAME [REVISION]', 'Delete the functional index'
30
+ # +Arfi::Commands::FIdx#destroy+ -> void
31
+ #
32
+ # This command is used to delete the functional index.
33
+ #
34
+ # @example
35
+ # bundle exec arfi f_idx destroy some_function [revision index (just an integer, 1 is by default)]
36
+ # @param index_name [String] Name of the index.
37
+ # @param revision [String] Revision of the index.
38
+ # @return [void]
39
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby
40
+ def destroy(index_name, revision = '01')
41
+ validate_schema_format!
42
+
43
+ revision = "0#{revision}" if revision.match?(/^\d$/)
44
+ FileUtils.rm("#{functions_dir}/#{index_name}_v#{revision}.sql")
45
+ puts "Deleted: #{functions_dir}/#{index_name}_v#{revision}.sql"
46
+ end
47
+
48
+ private
49
+
50
+ # +Arfi::Commands::FIdx#functions_dir+ -> Pathname
51
+ #
52
+ # Helper method to get path to `db/functions` directory.
53
+ #
54
+ # @!visibility private
55
+ # @private
56
+ # @return [Pathname] Path to `db/functions` directory
57
+ def functions_dir
58
+ Rails.root.join('db/functions')
59
+ end
60
+
61
+ # +Arfi::Commands::FIdx#validate_schema_format!+ -> void
62
+ #
63
+ # Helper method to validate the schema format.
64
+ #
65
+ # @!visibility private
66
+ # @private
67
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby.
68
+ # @return [nil] if the schema format is valid.
69
+ def validate_schema_format!
70
+ raise Arfi::Errors::InvalidSchemaFormat unless ActiveRecord.schema_format == :ruby
71
+ end
72
+
73
+ # +Arfi::Commands::FIdx#build_sql_function+ -> String
74
+ #
75
+ # Helper method to build the SQL function.
76
+ #
77
+ # @!visibility private
78
+ # @private
79
+ # @param index_name [String] Name of the index.
80
+ # @return [String] SQL function body.
81
+ def build_sql_function(index_name)
82
+ <<~SQL
83
+ CREATE OR REPLACE FUNCTION #{index_name}() RETURNS TEXT[]
84
+ LANGUAGE SQL
85
+ IMMUTABLE AS
86
+ $$
87
+ -- Function body here
88
+ $$
89
+ SQL
90
+ end
91
+
92
+ # +Arfi::Commands::FIdx#create_index_file+ -> void
93
+ #
94
+ # Helper method to create the index file.
95
+ #
96
+ # @!visibility private
97
+ # @private
98
+ # @param index_name [String] Name of the index.
99
+ # @param content [String] SQL function body.
100
+ # @return [void]
101
+ def create_index_file(index_name, content)
102
+ existing_files = Dir.glob("#{functions_dir}/#{index_name}*.sql")
103
+
104
+ return write_file(index_name, content, 1) if existing_files.empty?
105
+
106
+ latest_version = extract_latest_version(existing_files)
107
+ write_file(index_name, content, latest_version.next)
108
+ end
109
+
110
+ # +Arfi::Commands::FIdx#extract_latest_version+ -> Integer
111
+ #
112
+ # Helper method to extract the latest version of the index.
113
+ #
114
+ # @!visibility private
115
+ # @private
116
+ # @param files [Array<String>] List of files.
117
+ # @return [String] Latest version of the index.
118
+ def extract_latest_version(files)
119
+ version_numbers = files.map do |file|
120
+ File.basename(file)[/\w+_v(\d+)\.sql/, 1]
121
+ end.compact
122
+
123
+ version_numbers.max
124
+ end
125
+
126
+ # +Arfi::Commands::FIdx#write_file+ -> void
127
+ #
128
+ # Helper method to write the index file.
129
+ #
130
+ # @!visibility private
131
+ # @private
132
+ # @param index_name [String] Name of the index.
133
+ # @param content [String] SQL function body.
134
+ # @param version [Integer] Version of the index.
135
+ # @return [void]
136
+ def write_file(index_name, content, version)
137
+ version_str = format('%02d', version)
138
+ path = "#{functions_dir}/#{index_name}_v#{version_str}.sql"
139
+ File.write(path, content)
140
+ puts "Created: #{path}"
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thor'
4
+ require 'fileutils'
5
+ require 'rails'
6
+
7
+ module Arfi
8
+ module Commands
9
+ # +Arfi::Commands::Project+ class is used to create `db/functions` directory.
10
+ class Project < Thor
11
+ desc 'create', 'Initialize project by creating db/functions directory'
12
+ # +Arfi::Commands::Project#create+ -> void
13
+ #
14
+ # This command is used to create `db/functions` directory.
15
+ #
16
+ # @example
17
+ # bundle exec arfi project create
18
+ # @return [void]
19
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby.
20
+ def create
21
+ raise Arfi::Errors::InvalidSchemaFormat unless ActiveRecord.schema_format == :ruby
22
+ return puts "Directory #{functions_dir} already exists" if Dir.exist?(functions_dir)
23
+
24
+ FileUtils.mkdir_p(functions_dir)
25
+ puts "Created: #{functions_dir}"
26
+ end
27
+
28
+ private
29
+
30
+ # +Arfi::Commands::Project#functions_dir+ -> Pathname
31
+ #
32
+ # Helper method to get path to `db/functions` directory.
33
+ #
34
+ # @!visibility private
35
+ # @private
36
+ # @return [Pathname] Path to `db/functions` directory
37
+ def functions_dir
38
+ Rails.root.join('db/functions')
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Arfi
4
+ module Errors
5
+ # This error is raised when there is no `db/functions` directory
6
+ class NoFunctionsDir < StandardError
7
+ def initialize(message =
8
+ 'There is no such directory: db/functions. Did you run `bundle exec arfi project:create`?')
9
+ @message = message
10
+ super
11
+ end
12
+ end
13
+
14
+ # This error is raised when Rails project schema format is not +schema.rb+
15
+ class InvalidSchemaFormat < StandardError
16
+ def initialize(message = 'Invalid schema format. ARFI supports only ruby format schemas.')
17
+ @message = message
18
+ super
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+
5
+ module ActiveRecord
6
+ class Base # :nodoc:
7
+ # +ActiveRecord::Base.function_exists?+ -> bool
8
+ #
9
+ # This method checks if a custom SQL function exists in the database.
10
+ #
11
+ # @example
12
+ # ActiveRecord::Base.function_exists?('my_function') #=> true
13
+ # ActiveRecord::Base.function_exists?('my_function123') #=> false
14
+ # @param [String] function_name The name of the function to check.
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?
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module Tasks
5
+ # @!visibility private
6
+ # Under construction.
7
+ module DatabaseTasks
8
+ # class << self
9
+ # alias original_load_schema load_schema
10
+ #
11
+ # def load_schema(*args)
12
+ # Arfi::SqlFunctionLoader.load!
13
+ # original_load_schema(*args)
14
+ # end
15
+ #
16
+ # alias original_load_schema_current load_schema_current
17
+ #
18
+ # def load_schema_current(*args)
19
+ # Arfi::SqlFunctionLoader.load!
20
+ # original_load_schema_current(*args)
21
+ # end
22
+ #
23
+ # alias original_dump_schema dump_schema
24
+ #
25
+ # def dump_schema(*args)
26
+ # Arfi::SqlFunctionLoader.load!
27
+ # original_dump_schema(*args)
28
+ # end
29
+ # end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+ require 'active_record/schema'
5
+ require 'arfi/sql_function_loader'
6
+ require_relative 'active_record/base'
7
+ require_relative 'active_record/tasks/database_tasks'
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'arfi'
4
+ require 'rails'
5
+
6
+ module Arfi
7
+ class Railtie < ::Rails::Railtie # :nodoc:
8
+ railtie_name :arfi
9
+
10
+ rake_tasks do
11
+ path = File.expand_path(__dir__)
12
+ Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f }
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Arfi
4
+ # +Arfi::SqlFunctionLoader+ is a class which loads user defined SQL functions into database.
5
+ class SqlFunctionLoader
6
+ class << self
7
+ def load!
8
+ return unless sql_files&.any?
9
+
10
+ puts '[ARFI] Loading SQL functions BEFORE schema load transaction...'
11
+ db_config = Rails.configuration.database_configuration[Rails.env]
12
+ conn = conn(db_config)
13
+
14
+ sql_files&.each do |file|
15
+ sql = File.read(file).strip
16
+ conn.exec(sql)
17
+ puts "[ARFI] Loaded: #{File.basename(file)}"
18
+ end
19
+
20
+ conn.close
21
+ end
22
+
23
+ private
24
+
25
+ def sql_files
26
+ Dir.glob(Rails.root.join('db', 'functions').join('*.sql'))
27
+ end
28
+
29
+ def conn(db_config)
30
+ PG.connect(
31
+ user: db_config['username'],
32
+ password: db_config['password'],
33
+ host: db_config['host'],
34
+ port: db_config['port'],
35
+ dbname: db_config['database']
36
+ )
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rake'
4
+ require 'arfi/sql_function_loader'
5
+
6
+ namespace :_db do
7
+ task :arfi_enhance do
8
+ Arfi::SqlFunctionLoader.load!
9
+ end
10
+ end
11
+
12
+ Rake::Task.define_task(:environment) unless Rake::Task.task_defined?(:environment)
13
+ raise UnrecognizedCommandError, 'Warning: db:migrate task not found' unless Rake::Task.task_defined?('db:migrate')
14
+
15
+ %w[db:migrate db:schema:load db:setup db:prepare].each do |task|
16
+ Rake::Task[task].enhance(['_db:arfi_enhance']) if Rake::Task.task_defined?(task)
17
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Arfi
4
+ VERSION = '0.1.0'
5
+ end
data/lib/arfi.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'arfi/version'
4
+ require_relative 'arfi/errors'
5
+ require 'arfi/extensions/extensions'
6
+ require 'rails' if defined?(Rails)
7
+
8
+ # Top level module
9
+ module Arfi
10
+ require_relative 'arfi/railtie' if defined?(Rails)
11
+ end
data/sig/arfi.rbs ADDED
@@ -0,0 +1,2 @@
1
+ module Arfi
2
+ end
@@ -0,0 +1,94 @@
1
+ module Arfi
2
+ module Commands
3
+ class FIdx < Thor
4
+ # +Arfi::Commands::FIdx#create+ -> void
5
+ #
6
+ # This command is used to create the functional index.
7
+ #
8
+ # @example
9
+ # bundle exec arfi f_idx create some_function
10
+ # @param index_name [String] Name of the index.
11
+ # @return [void]
12
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby
13
+ # @raise [Arfi::Errors::NoFunctionsDir] if there is no `db/functions` directory
14
+ # @see Arfi::Commands::FIdx#validate_schema_format!
15
+ def create: (string index_name) -> untyped
16
+
17
+ # +Arfi::Commands::FIdx#destroy+ -> void
18
+ #
19
+ # This command is used to delete the functional index.
20
+ #
21
+ # @example
22
+ # bundle exec arfi f_idx destroy some_function [revision index (just an integer, 1 is by default)]
23
+ # @param index_name [String] Name of the index.
24
+ # @param revision [String] Revision of the index.
25
+ # @return [void]
26
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby
27
+ def destroy: (string index_name, ?::String revision) -> untyped
28
+
29
+ private
30
+
31
+ # +Arfi::Commands::FIdx#functions_dir+ -> Pathname
32
+ #
33
+ # Helper method to get path to `db/functions` directory.
34
+ #
35
+ # @!visibility private
36
+ # @private
37
+ # @return [Pathname] Path to `db/functions` directory
38
+ def functions_dir: () -> Pathname
39
+
40
+ # +Arfi::Commands::FIdx#validate_schema_format!+ -> void
41
+ #
42
+ # Helper method to validate the schema format.
43
+ #
44
+ # @!visibility private
45
+ # @private
46
+ # @raise [Arfi::Errors::InvalidSchemaFormat] if ActiveRecord.schema_format is not :ruby.
47
+ # @return [nil] if the schema format is valid.
48
+ def validate_schema_format!: () -> (untyped | nil)
49
+
50
+ # +Arfi::Commands::FIdx#build_sql_function+ -> String
51
+ #
52
+ # Helper method to build the SQL function.
53
+ #
54
+ # @!visibility private
55
+ # @private
56
+ # @param index_name [String] Name of the index.
57
+ # @return [String] SQL function body.
58
+ def build_sql_function: (string index_name) -> ::String
59
+
60
+ # +Arfi::Commands::FIdx#create_index_file+ -> void
61
+ #
62
+ # Helper method to create the index file.
63
+ #
64
+ # @!visibility private
65
+ # @private
66
+ # @param index_name [String] Name of the index.
67
+ # @param content [String] SQL function body.
68
+ # @return [void]
69
+ def create_index_file: (string index_name, string content) -> untyped
70
+
71
+ # +Arfi::Commands::FIdx#extract_latest_version+ -> String
72
+ #
73
+ # Helper method to extract the latest version of the index.
74
+ #
75
+ # @!visibility private
76
+ # @private
77
+ # @param files [Array<String>] List of files.
78
+ # @return [String] Latest version of the index.
79
+ def extract_latest_version: (Array[String] files) -> string
80
+
81
+ # +Arfi::Commands::FIdx#write_file+ -> void
82
+ #
83
+ # Helper method to write the index file.
84
+ #
85
+ # @!visibility private
86
+ # @private
87
+ # @param index_name [String] Name of the index.
88
+ # @param content [String] SQL function body.
89
+ # @param version [Integer] Version of the index.
90
+ # @return [void]
91
+ def write_file: (string index_name, string content, ::Integer version) -> untyped
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,14 @@
1
+ module Arfi
2
+ module Commands
3
+ class Project < Thor
4
+ # @return [void]
5
+ def create: () -> void
6
+
7
+ private
8
+
9
+ # @private
10
+ # @return [Pathname] Path to `db/functions` directory
11
+ def functions_dir: () -> Pathname
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,15 @@
1
+ module Arfi
2
+ module Errors
3
+ class NoFunctionsDir < StandardError
4
+ @message: string
5
+
6
+ def initialize: (?::String message) -> void
7
+ end
8
+
9
+ class InvalidSchemaFormat < StandardError
10
+ @message: string
11
+
12
+ def initialize: (?::String message) -> void
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,14 @@
1
+ module ActiveRecord
2
+ class Base
3
+ # +ActiveRecord::Base.function_exists?+ -> bool
4
+ #
5
+ # This method checks if a custom SQL function exists in the database.
6
+ #
7
+ # @example
8
+ # ActiveRecord::Base.function_exists?('my_function') #=> true
9
+ # ActiveRecord::Base.function_exists?('my_function123') #=> false
10
+ # @param [String] function_name The name of the function to check.
11
+ # @return [Boolean] Returns true if the function exists, false otherwise.
12
+ def self.function_exists?: (string function_name) -> bool
13
+ end
14
+ end
@@ -0,0 +1,19 @@
1
+ module Arfi
2
+ class SqlFunctionLoader
3
+ type db_config = {
4
+ user: String,
5
+ password: String,
6
+ host: String,
7
+ port: Integer,
8
+ dbname: String
9
+ }
10
+
11
+ def self.load!: () -> (nil | untyped)
12
+
13
+ private
14
+
15
+ def self.sql_files: () -> (Array[String] | nil)
16
+
17
+ def self.conn: (db_config db_config) -> untyped
18
+ end
19
+ end
@@ -0,0 +1,3 @@
1
+ module Arfi
2
+ VERSION: "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: arfi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - unurgunite
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Bring the ability to create and maintain functional indexes without transition
13
+ to structure.sql.
14
+ email:
15
+ - senpaiguru1488@gmail.com
16
+ executables:
17
+ - arfi
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".rspec"
22
+ - ".rubocop.yml"
23
+ - ".ruby-version"
24
+ - CHANGELOG.md
25
+ - CODE_OF_CONDUCT.md
26
+ - LICENSE.txt
27
+ - README.md
28
+ - Rakefile
29
+ - exe/arfi
30
+ - lib/arfi.rb
31
+ - lib/arfi/Rakefile
32
+ - lib/arfi/cli.rb
33
+ - lib/arfi/commands/f_idx.rb
34
+ - lib/arfi/commands/project.rb
35
+ - lib/arfi/errors.rb
36
+ - lib/arfi/extensions/active_record/base.rb
37
+ - lib/arfi/extensions/active_record/tasks/database_tasks.rb
38
+ - lib/arfi/extensions/extensions.rb
39
+ - lib/arfi/railtie.rb
40
+ - lib/arfi/sql_function_loader.rb
41
+ - lib/arfi/tasks/db.rake
42
+ - lib/arfi/version.rb
43
+ - sig/arfi.rbs
44
+ - sig/lib/arfi/commands/f_idx.rbs
45
+ - sig/lib/arfi/commands/project.rbs
46
+ - sig/lib/arfi/errors.rbs
47
+ - sig/lib/arfi/extensions/active_record/base.rbs
48
+ - sig/lib/arfi/sql_function_loader.rbs
49
+ - sig/lib/arfi/version.rbs
50
+ homepage: https://github.com/unurgunite/arfi
51
+ licenses:
52
+ - MIT
53
+ metadata:
54
+ allowed_push_host: https://rubygems.org
55
+ homepage_uri: https://github.com/unurgunite/arfi
56
+ source_code_uri: https://github.com/unurgunite/arfi
57
+ changelog_uri: https://github.com/unurgunite/arfi/CHANGELOG.md
58
+ rubygems_mfa_required: 'true'
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 3.1.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.6.8
74
+ specification_version: 4
75
+ summary: ActiveRecord Functional Indexes.
76
+ test_files: []