database-core 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: d09296cddff25f0ba310543cec359b71519de3ad5507ca20c3b9e366c8464e86
4
+ data.tar.gz: a9685fcee5587df9319ff5fba6af87f3ae178d2b1c38ecae7618f4eba0d57009
5
+ SHA512:
6
+ metadata.gz: fafbf01c5983c61265ecafea3296b7a8ecb92b57e5c2ee1482e913eafcb8bc8cae2f1c746608a5effe4ca80d88110e66d98f002f87e1660c46a27016ed4cae28
7
+ data.tar.gz: 3dc796dc1c6a90250a94d95e23f399bcac0c9e6da73183ae53e303b8c335562425134bc987c4b12960a1b56e55a9e2aa979fa6329e77cc5fe7046a1a8e04749d
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-12-31
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 Tiago da Silva
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,116 @@
1
+ # database-core
2
+
3
+ Biblioteca Ruby para centralizar o acesso a banco de dados e regras comuns de persistência, para ser reutilizada entre diferentes serviços e aplicações da organização.
4
+
5
+ Ela não é uma aplicação standalone, mas sim um "core" que expõe classes, módulos e configurações para ser usada como dependência em outros projetos Ruby/Rails.
6
+
7
+ ## Instalação
8
+
9
+ ### Via Git (recomendado durante o desenvolvimento)
10
+
11
+ No `Gemfile` da sua aplicação, adicione:
12
+
13
+ ```ruby
14
+ gem 'database-core', git: 'https://github.com/[USERNAME]/database-core.git'
15
+ ```
16
+
17
+ Depois rode:
18
+
19
+ ```bash
20
+ bundle install
21
+ ```
22
+
23
+ ### Via gem (quando publicada no RubyGems)
24
+
25
+ Quando a gem estiver publicada, você poderá instalá-la com:
26
+
27
+ ```bash
28
+ gem install database-core
29
+ ```
30
+
31
+ Ou adicionar ao `Gemfile`:
32
+
33
+ ```ruby
34
+ gem 'database-core'
35
+ ```
36
+
37
+ ## Uso
38
+
39
+ 1. Adicione a gem ao seu projeto (ver seção de Instalação).
40
+ 2. Requeira a biblioteca principal no ponto de entrada da sua aplicação, caso necessário:
41
+
42
+ ```ruby
43
+ require 'database/core'
44
+ ```
45
+
46
+ 3. Utilize os módulos e classes expostos pela gem, por exemplo:
47
+
48
+ ```ruby
49
+ # Exemplo ilustrativo, ajuste para refletir suas APIs reais
50
+ Database::Core.configure do |config|
51
+ config.logger = Rails.logger
52
+ config.default_connection_url = ENV['DATABASE_URL']
53
+ end
54
+
55
+ connection = Database::Core.connection
56
+ result = connection.execute('SELECT 1')
57
+ ```
58
+
59
+ Consulte a pasta `lib/` para ver os componentes disponíveis (conexões, repositórios, adapters, etc.) e adapte o exemplo acima à API real do projeto.
60
+
61
+ ## Desenvolvimento
62
+
63
+ Após clonar o repositório, instale as dependências:
64
+
65
+ ```bash
66
+ bin/setup
67
+ ```
68
+
69
+ Para abrir um console interativo com o ambiente da gem carregado:
70
+
71
+ ```bash
72
+ bin/console
73
+ ```
74
+
75
+ Para rodar a suíte de testes (ajuste o comando conforme o test runner configurado, por exemplo RSpec ou Minitest):
76
+
77
+ ```bash
78
+ bundle exec rake test
79
+ # ou
80
+ bundle exec rspec
81
+ ```
82
+
83
+ Para instalar a gem localmente (para usar em outro projeto do mesmo ambiente):
84
+
85
+ ```bash
86
+ bundle exec rake install
87
+ ```
88
+
89
+ Para criar uma nova versão:
90
+
91
+ 1. Atualize o número da versão em `lib/database/core/version.rb`.
92
+ 2. Rode:
93
+
94
+ ```bash
95
+ bundle exec rake release
96
+ ```
97
+
98
+ Isso criará uma tag git, fará o push dos commits e publicará a gem (se configurado).
99
+
100
+ ## Contribuindo
101
+
102
+ Relatos de bugs e pull requests são bem-vindos no GitHub em:
103
+
104
+ https://github.com/[USERNAME]/database-core
105
+
106
+ Ao contribuir, siga as boas práticas de código Ruby, adicione testes cobrindo as mudanças e atualize a documentação quando necessário.
107
+
108
+ ## Licença
109
+
110
+ Este projeto está disponível como código aberto sob os termos da [Licença MIT](https://opensource.org/licenses/MIT).
111
+
112
+ ## Código de Conduta
113
+
114
+ Todos que interagem com o repositório `database-core`, issue trackers, salas de bate-papo e listas de e-mail devem seguir o código de conduta definido em:
115
+
116
+ https://github.com/[USERNAME]/database-core/blob/master/CODE_OF_CONDUCT.md
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
@@ -0,0 +1,144 @@
1
+ module Database::V1
2
+
3
+ class Query
4
+
5
+ def self.build table, query
6
+
7
+ output = []
8
+
9
+ build_select output, query
10
+
11
+ output << "FROM `#{table}`"
12
+
13
+ build_where output, query
14
+ build_order output, query
15
+ build_limit output, query
16
+ build_offset output, query
17
+
18
+ output.join " "
19
+ end
20
+
21
+ def self.build_select output, query
22
+
23
+ columns = []
24
+
25
+ build_keys columns, query
26
+
27
+ unless query["columns"].nil?
28
+ columns.concat query["columns"]
29
+ end
30
+
31
+ if columns.empty?
32
+ output << "SELECT *"
33
+ end
34
+
35
+ unless columns.empty?
36
+ columns.map!{ |column| "`#{column}`" }
37
+ output << "SELECT #{columns.join ","}"
38
+ end
39
+ end
40
+
41
+ def self.build_where output, query
42
+
43
+ where = []
44
+
45
+ unless query["equal"].nil?
46
+ query["equal"].each do |key, value|
47
+ where << "`#{key}`=#{value}"
48
+ end
49
+ end
50
+
51
+ unless query["in_query"].nil?
52
+ query["in_query"].each do |key, value|
53
+ value.each do |table, query|
54
+ query = build table, query
55
+ where << "`#{key}` IN (#{query})"
56
+ end
57
+ end
58
+ end
59
+
60
+ unless query["in_value"].nil?
61
+ query["in_value"].each do |key, value|
62
+ unless value.empty?
63
+ value = value.join ","
64
+ where << "`#{key}` IN (#{value})"
65
+ end
66
+ end
67
+ end
68
+
69
+ unless query["like"].nil?
70
+ query["like"].each do |key, value|
71
+ where << "`#{key}` LIKE '#{value}'"
72
+ end
73
+ end
74
+
75
+ unless where.empty?
76
+ where = where.join " AND "
77
+ output << "WHERE #{where}"
78
+ end
79
+ end
80
+
81
+ def self.build_order output, query
82
+
83
+ order = []
84
+
85
+ unless query["order"].nil?
86
+ query["order"].each do |key, value|
87
+ order << "`#{key}` #{value}"
88
+ end
89
+ end
90
+
91
+ unless order.empty?
92
+ order = order.join ","
93
+ output << "ORDER BY #{order}"
94
+ end
95
+ end
96
+
97
+ def self.build_limit output, query
98
+
99
+ unless query["limit"].nil?
100
+ output << "LIMIT #{query["limit"]}"
101
+ end
102
+ end
103
+
104
+ def self.build_offset output, query
105
+
106
+ unless query["offset"].nil?
107
+ output << "OFFSET #{query["offset"]}"
108
+ end
109
+ end
110
+
111
+ def self.build_keys output, query
112
+
113
+ unless query["has_one_key"].nil?
114
+ unless output.include? "id"
115
+ output << "id"
116
+ end
117
+ end
118
+
119
+ unless query["has_many"].nil?
120
+ unless output.include? "id"
121
+ output << "id"
122
+ end
123
+ end
124
+
125
+ unless query["has_many_key"].nil?
126
+ unless output.include? query["has_many_key"]
127
+ output << query["has_many_key"]
128
+ end
129
+ end
130
+
131
+ unless query["has_one"].nil?
132
+ query["has_one"].each do |table, query|
133
+ unless query["has_one_key"].nil?
134
+ unless output.include? query["has_one_key"]
135
+ output << query["has_one_key"]
136
+ end
137
+ end
138
+ end
139
+ end
140
+ end
141
+
142
+ end
143
+
144
+ end
@@ -0,0 +1,157 @@
1
+ module Database::V1
2
+
3
+ class QueryRunner
4
+
5
+ def self.query tables_query
6
+
7
+ tables_values = QueryRunner.tables_query tables_query
8
+
9
+ tables_values.each do |table, values|
10
+
11
+ query = tables_query[table]
12
+ next if query.nil?
13
+
14
+ QueryRunner.values_remove_keys values, query
15
+ end
16
+
17
+ tables_values
18
+ end
19
+
20
+ def self.tables_query tables_query
21
+
22
+ tables_values = {}
23
+
24
+ tables_query.each do |table, query|
25
+
26
+ sql = Query.build table, query
27
+
28
+ values = ActiveRecord::Base.connection.exec_query(sql).map(&:as_json)
29
+
30
+ QueryRunner.tables_has_many values, query
31
+ QueryRunner.tables_has_one values, query
32
+
33
+ tables_values[table] = values
34
+ end
35
+
36
+ tables_values
37
+ end
38
+
39
+ def self.tables_has_many parents, query
40
+
41
+ has_many = query["has_many"]
42
+ return if has_many.nil?
43
+
44
+ QueryRunner.setup_has_many parents, has_many
45
+ tables_values = QueryRunner.tables_query has_many
46
+
47
+ parents.each do |parent|
48
+
49
+ tables_values.each do |table, values|
50
+
51
+ query = has_many[table]
52
+ next if query.nil?
53
+ has_many_key = query["has_many_key"]
54
+ next if has_many_key.nil?
55
+ key_value = parent["id"]
56
+ next if key_value.nil?
57
+
58
+ values = values.deep_dup.select{ |value| value[has_many_key] == key_value }
59
+ QueryRunner.values_remove_keys values, query
60
+ parent[table] = values
61
+ end
62
+ end
63
+ end
64
+
65
+ def self.tables_has_one parents, query
66
+
67
+ has_one = query["has_one"]
68
+ return if has_one.nil?
69
+
70
+ QueryRunner.setup_has_one parents, has_one
71
+ tables_values = QueryRunner.tables_query has_one
72
+
73
+ parents.each do |parent|
74
+
75
+ tables_values.each do |table, values|
76
+
77
+ query = has_one[table]
78
+ next if query.nil?
79
+ has_one_key = query["has_one_key"]
80
+ next if has_one_key.nil?
81
+ key_value = parent[has_one_key]
82
+ next if key_value.nil?
83
+
84
+ values = values.deep_dup.select{ |value| value["id"] == key_value }
85
+ QueryRunner.values_remove_keys values, query
86
+ parent[table] = values[0]
87
+ end
88
+ end
89
+ end
90
+
91
+ def self.setup_has_many values, tables_query
92
+
93
+ return if values.empty?
94
+
95
+ tables_query.each do |_, query|
96
+
97
+ has_many_key = query["has_many_key"]
98
+
99
+ next if has_many_key.nil?
100
+
101
+ unless query["in_value"].nil?
102
+ if query["in_value"].key? has_many_key
103
+ query["in_value"][has_many_key] << values.map{ |value| value["id"] }.compact.uniq
104
+ end
105
+ end
106
+
107
+ if query["in_value"].nil?
108
+ query["in_value"] = {}
109
+ query["in_value"][has_many_key] = values.map{ |value| value["id"] }.compact.uniq
110
+ end
111
+ end
112
+ end
113
+
114
+ def self.setup_has_one values, tables_query
115
+
116
+ return if values.empty?
117
+
118
+ tables_query.each do |_, query|
119
+
120
+ has_one_key = query["has_one_key"]
121
+
122
+ next if has_one_key.nil?
123
+
124
+ unless query["in_value"].nil?
125
+ if query["in_value"].key? "id"
126
+ query["in_value"]["id"] << values.map{ |value| value[has_one_key] }.compact.uniq
127
+ end
128
+ end
129
+
130
+ if query["in_value"].nil?
131
+ query["in_value"] = {}
132
+ query["in_value"]["id"] = values.map{ |value| value[has_one_key] }.compact.uniq
133
+ end
134
+ end
135
+ end
136
+
137
+ def self.values_remove_keys values, query
138
+
139
+ columns = query["columns"]
140
+ return if columns.nil?
141
+
142
+ keys = []
143
+
144
+ Query.build_keys keys, query
145
+
146
+ keys.each do |key|
147
+ unless columns.include? key
148
+ values.each do |value|
149
+ value.delete key
150
+ end
151
+ end
152
+ end
153
+ end
154
+
155
+ end
156
+
157
+ end