pgb 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 060fc2513c44822e85176d57cd22e8ce31c36b65b1103366048fef1a2aaba5d1
4
+ data.tar.gz: 2ae4bee33b32d211311629d680b78901a0794c7cd2898b44774795e3646c1c64
5
+ SHA512:
6
+ metadata.gz: b3a661d7941ea09a150a93d211c0b373296b4804158cb9afe34282d16d3a3ca0fecbbe3af7c1c2c7633d9db2ffbadec3adf78855159b706cca0e2ca917992fe4
7
+ data.tar.gz: e46d3993fafba112ef23040653373b9373c8e4ff864027011c63e91cd6f502af9de3c67c9ab33b7b99ea1092849086cbb4c43a502ea7d81c4505d83e0a6cb084
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,66 @@
1
+ require:
2
+ - rubocop-performance
3
+ - rubocop-rake
4
+ - rubocop-rspec
5
+
6
+ AllCops:
7
+ TargetRubyVersion: 2.7
8
+ NewCops: enable
9
+ EnabledByDefault: true
10
+
11
+ Layout/LineLength:
12
+ Max: 100
13
+
14
+ Style/Documentation:
15
+ Enabled: false
16
+
17
+ Metrics/MethodLength:
18
+ Max: 20
19
+
20
+ Lint/MissingSuper:
21
+ Enabled: false
22
+
23
+ Style/AccessorGrouping:
24
+ EnforcedStyle: separated
25
+
26
+ Style/ModuleFunction:
27
+ Enabled: false
28
+
29
+ Style/GuardClause:
30
+ Enabled: false
31
+
32
+ Style/NumberedParameters:
33
+ Enabled: false
34
+
35
+ Style/Copyright:
36
+ Enabled: false
37
+
38
+ Lint/ConstantResolution:
39
+ Enabled: false
40
+
41
+ Style/DocumentationMethod:
42
+ Enabled: false
43
+
44
+ Style/DisableCopsWithinSourceCodeDirective:
45
+ Enabled: false
46
+
47
+ Style/ClassMethodsDefinitions:
48
+ Enabled: false
49
+
50
+ Style/StringHashKeys:
51
+ Enabled: false
52
+
53
+ Style/MethodCallWithArgsParentheses:
54
+ Enabled: false
55
+
56
+ Style/ConstantVisibility:
57
+ Enabled: false
58
+
59
+ Bundler/GemComment:
60
+ Enabled: false
61
+
62
+ Layout/MultilineAssignmentLayout:
63
+ Enabled: false
64
+
65
+ Style/CommentAnnotation:
66
+ RequireColon: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.7.7
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-12-11
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 to the community leaders responsible for enforcement at d.gubitskiy@gmail.com. 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,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'pry', '= 0.14.1'
8
+ gem 'rake', '~> 13.0'
9
+ gem 'rspec', '~> 3.12'
10
+ gem 'rubocop', '~> 1.40'
11
+ gem 'rubocop-performance', '~> 1.15'
12
+ gem 'rubocop-rake', '= 0.6.0'
13
+ gem 'rubocop-rspec', '~> 2.15'
data/Gemfile.lock ADDED
@@ -0,0 +1,78 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ pgb (0.1.0)
5
+ pg (~> 1.4)
6
+ zeitwerk (~> 2.6)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ ast (2.4.2)
12
+ coderay (1.1.3)
13
+ diff-lcs (1.5.0)
14
+ json (2.6.3)
15
+ method_source (1.0.0)
16
+ parallel (1.22.1)
17
+ parser (3.1.3.0)
18
+ ast (~> 2.4.1)
19
+ pg (1.4.5)
20
+ pry (0.14.1)
21
+ coderay (~> 1.1)
22
+ method_source (~> 1.0)
23
+ rainbow (3.1.1)
24
+ rake (13.0.6)
25
+ regexp_parser (2.6.1)
26
+ rexml (3.2.5)
27
+ rspec (3.12.0)
28
+ rspec-core (~> 3.12.0)
29
+ rspec-expectations (~> 3.12.0)
30
+ rspec-mocks (~> 3.12.0)
31
+ rspec-core (3.12.0)
32
+ rspec-support (~> 3.12.0)
33
+ rspec-expectations (3.12.0)
34
+ diff-lcs (>= 1.2.0, < 2.0)
35
+ rspec-support (~> 3.12.0)
36
+ rspec-mocks (3.12.0)
37
+ diff-lcs (>= 1.2.0, < 2.0)
38
+ rspec-support (~> 3.12.0)
39
+ rspec-support (3.12.0)
40
+ rubocop (1.40.0)
41
+ json (~> 2.3)
42
+ parallel (~> 1.10)
43
+ parser (>= 3.1.2.1)
44
+ rainbow (>= 2.2.2, < 4.0)
45
+ regexp_parser (>= 1.8, < 3.0)
46
+ rexml (>= 3.2.5, < 4.0)
47
+ rubocop-ast (>= 1.23.0, < 2.0)
48
+ ruby-progressbar (~> 1.7)
49
+ unicode-display_width (>= 1.4.0, < 3.0)
50
+ rubocop-ast (1.24.0)
51
+ parser (>= 3.1.1.0)
52
+ rubocop-performance (1.15.1)
53
+ rubocop (>= 1.7.0, < 2.0)
54
+ rubocop-ast (>= 0.4.0)
55
+ rubocop-rake (0.6.0)
56
+ rubocop (~> 1.0)
57
+ rubocop-rspec (2.15.0)
58
+ rubocop (~> 1.33)
59
+ ruby-progressbar (1.11.0)
60
+ unicode-display_width (2.3.0)
61
+ zeitwerk (2.6.6)
62
+
63
+ PLATFORMS
64
+ arm64-darwin-21
65
+ x86_64-linux
66
+
67
+ DEPENDENCIES
68
+ pgb!
69
+ pry (= 0.14.1)
70
+ rake (~> 13.0)
71
+ rspec (~> 3.12)
72
+ rubocop (~> 1.40)
73
+ rubocop-performance (~> 1.15)
74
+ rubocop-rake (= 0.6.0)
75
+ rubocop-rspec (~> 2.15)
76
+
77
+ BUNDLED WITH
78
+ 2.3.26
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Dmitry Gubitskiy
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,15 @@
1
+ # PGB ![build status](https://github.com/enthrops/pgb/actions/workflows/main.yml/badge.svg)
2
+
3
+ Postgres-specific ORM for Ruby
4
+
5
+ ## Contributing
6
+
7
+ Bug reports and pull requests are welcome on GitHub at https://github.com/enthrops/pgb. 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/enthrops/pgb/blob/master/CODE_OF_CONDUCT.md)
8
+
9
+ ## License
10
+
11
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT)
12
+
13
+ ## Code of Conduct
14
+
15
+ Everyone interacting in the PGB project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/enthrops/pgb/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]
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ module Casting
5
+ private
6
+
7
+ # TODO More types
8
+ # TODO DRY literal types
9
+ def to_expression(object)
10
+ case object
11
+ when Expression
12
+ object
13
+ when TrueClass
14
+ Keyword.new('TRUE')
15
+ when FalseClass
16
+ Keyword.new('FALSE')
17
+ when NilClass
18
+ Keyword.new('NULL')
19
+ when String, Symbol, Numeric
20
+ Literal.new(object)
21
+ else
22
+ raise Error, "Can not convert type to expression: #{object.class}"
23
+ end
24
+ end
25
+
26
+ def to_identifier(object)
27
+ object.is_a?(Identifier) ? object : Identifier.new(object)
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class ColumnReference < Expression
5
+ def initialize(table, column)
6
+ @value = "#{to_identifier(table)}.#{to_identifier(column)}"
7
+ end
8
+
9
+ def to_sql
10
+ value
11
+ end
12
+
13
+ private
14
+
15
+ attr_reader :value
16
+ end
17
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class Command
5
+ include SQLDisplayable
6
+ include Casting
7
+ include Executable
8
+ end
9
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class EvaluationContext
5
+ include Shortcuts
6
+
7
+ # TODO Evaluate multiple args?
8
+ # TODO Implement respond_to_missing and remove cop skip?
9
+ # rubocop:disable Style/MissingRespondToMissing
10
+ def method_missing(*args, **opts, &block)
11
+ if args.one?
12
+ Identifier.new(args.first)
13
+ else
14
+ super
15
+ end
16
+ end
17
+ # rubocop:enable Style/MissingRespondToMissing
18
+ end
19
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ module Executable
5
+ include Enumerable
6
+
7
+ def each
8
+ PGB.execute(self).each { yield _1 }
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class Expression
5
+ include SQLDisplayable
6
+
7
+ private
8
+
9
+ include Casting
10
+
11
+ # TODO Multiple args?
12
+ def evaluate_arg(arg, &block)
13
+ if block
14
+ EvaluationContext.new.instance_exec(&block)
15
+ else
16
+ arg
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class FunctionCall < Expression
5
+ def initialize(function, *args)
6
+ @function = function.to_s.upcase
7
+ @args = args.map { to_expression(_1) }
8
+ end
9
+
10
+ def to_sql
11
+ "#{function}(#{args.map(&:to_sql).join(', ')})"
12
+ end
13
+
14
+ private
15
+
16
+ attr_reader :function
17
+ attr_reader :args
18
+ end
19
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class Identifier < Expression
5
+ def initialize(value)
6
+ @value = "\"#{value.to_s.gsub('"', '""')}\""
7
+ end
8
+
9
+ def to_sql
10
+ value
11
+ end
12
+
13
+ private
14
+
15
+ attr_reader :value
16
+ end
17
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class Keyword < Expression
5
+ SUPPORTED_VALUES = %w[TRUE FALSE NULL].freeze
6
+
7
+ def initialize(value)
8
+ if SUPPORTED_VALUES.include?(normalized(value))
9
+ @value = normalized(value)
10
+ else
11
+ raise Error, "Unsupported keyword: #{value.inspect}"
12
+ end
13
+ end
14
+
15
+ def to_sql
16
+ value
17
+ end
18
+
19
+ private
20
+
21
+ attr_reader :value
22
+
23
+ def normalized(value)
24
+ value.to_s.upcase
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class Literal < Expression
5
+ def initialize(value)
6
+ @value = to_db(value).to_s
7
+ end
8
+
9
+ def to_sql
10
+ value
11
+ end
12
+
13
+ private
14
+
15
+ attr_reader :value
16
+
17
+ # TODO More types
18
+ def to_db(value)
19
+ case value
20
+ when String, Symbol
21
+ "'#{value.to_s.gsub("'", "''")}'"
22
+ when Numeric
23
+ # TODO Correctly convert different numeric types
24
+ value
25
+ else
26
+ raise Error, "Unsupported type for literal: #{value.class}"
27
+ end
28
+ end
29
+ end
30
+ end
data/lib/pgb/model.rb ADDED
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ # TODO Explicit table names
5
+ # TODO Support queries for from
6
+ # TODO Automatically infer validations from db constraints
7
+ # TODO Do not litter this class with methods since others inherit from it (e.g. parse)
8
+ # TODO Support explicitly setting table_name / query / etc
9
+ # TODO table_name changing at runtime
10
+ # TODO Defined attributes might be needed before connecting to the database
11
+ # TODO Support keyword attributes for #new and make parse use that
12
+ # TODO #inspect
13
+ # TODO #to_s
14
+ # TODO Module inclusions on relations?
15
+ # TODO Include enumerable methods unless they clash with existing
16
+ # TODO Enumerable methods should act on current selection
17
+ # TODO Check all enumerable methods are functional (e.g. sort, to_h)
18
+ # TODO Implement base methods, e.g. ==, etc
19
+ # TODO Check Enumerable and Shortcuts methods clashing (e.g. [])
20
+ # TODO Lazy for enumerable
21
+ class Model
22
+ # TODO These two should respect already constructed relations
23
+ include Shortcuts
24
+
25
+ class << self
26
+ include Enumerable
27
+ include Shortcuts
28
+
29
+ attr_reader :table_name
30
+
31
+ def inherited(klass)
32
+ # TODO Bad method for setting table name
33
+ klass.table_name = "#{klass.name.downcase.split('::').last}s"
34
+ end
35
+
36
+ def each
37
+ all.each { yield _1 }
38
+ end
39
+
40
+ # TODO Only execute when data is required
41
+ # TODO Schema auto reload?
42
+ # TODO Schema manual reload?
43
+ # TODO Called again? Remove all conditions or do nothing?
44
+ def all
45
+ from(table_name).then { execute(_1) }.map { parse(_1) }
46
+ end
47
+
48
+ # TODO Column names clashing with existing methods
49
+ # TODO Overwriting column readers / writers
50
+ def schema
51
+ @schema ||= class_exec do
52
+ PGB.schema(table_name).each_key do
53
+ attr_accessor _1
54
+ end
55
+ end
56
+ end
57
+
58
+ def columns
59
+ schema.keys
60
+ end
61
+
62
+ protected
63
+
64
+ attr_writer :table_name
65
+
66
+ private
67
+
68
+ # TODO Types
69
+ # TODO Column in schema, but not in result
70
+ # TODO Column in result, but not in schema
71
+ # TODO Enums
72
+ # TODO Custom type read / write
73
+ def parse(row)
74
+ object = new
75
+ columns.each { |column| object.public_send("#{column}=", row.fetch(column)) }
76
+ object
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ module Mutable
5
+ def mutable(method)
6
+ original_method = "original_#{method}"
7
+ alias_method original_method, method
8
+
9
+ define_method("#{method}!") do |*args, **opts, &block|
10
+ public_send(original_method, *args, **opts, &block)
11
+ self
12
+ end
13
+
14
+ define_method(method) do |*args, **opts, &block|
15
+ copy = dup
16
+ copy.instance_exec { public_send(original_method, *args, **opts, &block) }
17
+ copy
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class OperatorCall < Expression
5
+ # TODO Validate and parse operators https://www.postgresql.org/docs/current/functions.html
6
+
7
+ def initialize(operator, expression1, expression2 = nil)
8
+ @operator = operator.to_s
9
+ @expression1 = to_expression(expression1)
10
+ @expression2 = to_expression(expression2) if expression2
11
+ end
12
+
13
+ def to_sql
14
+ if unary?
15
+ "#{operator}#{expression1}"
16
+ else
17
+ "#{expression1} #{operator} #{expression2}"
18
+ end
19
+ end
20
+
21
+ private
22
+
23
+ attr_reader :operator
24
+ attr_reader :expression1
25
+ attr_reader :expression2
26
+
27
+ def unary?
28
+ !expression2
29
+ end
30
+
31
+ def binary?
32
+ !unary?
33
+ end
34
+ end
35
+ end
data/lib/pgb/query.rb ADDED
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class Query < Expression
5
+ include Executable
6
+ extend Mutable
7
+
8
+ # TODO Support everything https://www.postgresql.org/docs/current/sql-select.html
9
+ # TODO Table can be other things, e.g. query
10
+
11
+ def initialize(table = nil, *expressions)
12
+ self.table = table
13
+ self.expressions = expressions
14
+ end
15
+
16
+ # TODO Can not select star if no table
17
+ def to_sql
18
+ "SELECT #{expressions.any? ? expressions.map(&:to_sql).join(', ') : '*'}".then do
19
+ table ? "#{_1} FROM #{table}" : _1
20
+ end
21
+ end
22
+
23
+ mutable def from(table, &block)
24
+ self.table = evaluate_arg(table, &block)
25
+ end
26
+
27
+ # TODO Naming for adding, removing, replacing selects
28
+ # TODO Raise if no expressions?
29
+ mutable def select(*expressions, &block)
30
+ self.expressions = evaluate_arg(expressions, &block)
31
+ end
32
+
33
+ private
34
+
35
+ attr_reader :table
36
+ attr_reader :expressions
37
+
38
+ def table=(table)
39
+ @table = table ? to_identifier(table) : nil
40
+ end
41
+
42
+ def expressions=(expressions)
43
+ @expressions = expressions.map { to_expression(_1) }
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ # TODO Support dynamic param evaluation
5
+ module Shortcuts
6
+ extend self
7
+
8
+ def execute(...)
9
+ PGB.execute(...)
10
+ end
11
+
12
+ def select(...)
13
+ PGB::Query.new(nil, ...)
14
+ end
15
+
16
+ def from(table)
17
+ PGB::Query.new(table)
18
+ end
19
+
20
+ def func(...)
21
+ PGB::FunctionCall.new(...)
22
+ end
23
+
24
+ def lit(...)
25
+ PGB::Literal.new(...)
26
+ end
27
+
28
+ def [](...)
29
+ PGB::Identifier.new(...)
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ module SQLDisplayable
5
+ def to_s
6
+ to_sql
7
+ end
8
+
9
+ def inspect
10
+ to_sql
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ class TypeCast < Expression
5
+ # TODO
6
+ end
7
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PGB
4
+ VERSION = '0.1.0'
5
+ end
data/lib/pgb.rb ADDED
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ # TODO SQL pretty format
4
+ # TODO DDL https://www.postgresql.org/docs/current/ddl.html
5
+ # TODO Parenthesis in to_sql
6
+ # TODO RBS DRY type definitions
7
+ # TODO RBS line length
8
+ # TODO RBS update signatures
9
+ # TODO Parse strings and symbols as identifiers by default?
10
+ # TODO Enumerable methods on queries and commands?
11
+ # TODO Do we need to repeat execution on already executed queries and commands?
12
+ # TODO Enumerable clashes and behavior on queries and commands
13
+ # TODO Lazy enumerable on queries and commands
14
+ # TODO Rails support
15
+ # TODO README
16
+ # TODO CHANGELOG
17
+ # TODO Rubocop
18
+ # TODO Supported ruby versions
19
+ # TODO Specs
20
+ # TODO CI
21
+ # TODO Push gem
22
+ # TODO Check code is compatible with ruby 2.7
23
+
24
+ require 'pg'
25
+ require 'zeitwerk'
26
+
27
+ module PGB
28
+ class << self
29
+ attr_accessor :loader
30
+ end
31
+ end
32
+
33
+ loader = Zeitwerk::Loader.for_gem
34
+ loader.inflector.inflect('pgb' => 'PGB', 'sql_displayable' => 'SQLDisplayable')
35
+ loader.enable_reloading
36
+ loader.setup
37
+
38
+ PGB.loader = loader
39
+
40
+ module PGB
41
+ class Error < StandardError
42
+ end
43
+
44
+ class << self
45
+ def evaluate(&block)
46
+ EvaluationContext.new.instance_exec(&block)
47
+ end
48
+
49
+ # TODO Log
50
+ # TODO Connection pool
51
+ # TODO DB connection params
52
+ # TODO Extract
53
+ # TODO Wrap errors in PGB::Error
54
+ # TODO Support block evaluation
55
+ # TODO Log runtime
56
+ # TODO Log source of query
57
+ # TODO Check postgres version on first call
58
+ # TODO Look through everything
59
+ # TODO Enable all rubocop cops
60
+ def execute(query)
61
+ sql = query.is_a?(Query) || query.is_a?(Command) ? query.to_sql : query
62
+ puts sql
63
+ connection.exec(sql).to_a
64
+ end
65
+
66
+ # TODO Connection lost? Reconnect? Different version?
67
+ def connection
68
+ @connection ||= begin
69
+ connection = PG.connect(dbname: 'hubstaff_development')
70
+ connection
71
+ end
72
+ end
73
+
74
+ # TODO Extract
75
+ # TODO Model is not a table name (e.g. query)?
76
+ # TODO Do not select all columns
77
+ # TODO Request as PGB query
78
+ # TODO Support getting schema for all tables
79
+ # TODO Remove line breaks for raw queries?
80
+ def schema(table_name)
81
+ table_name = table_name.to_s
82
+ @schema ||= begin
83
+ result = execute <<~SQL
84
+ SELECT *
85
+ FROM information_schema.columns
86
+ WHERE table_schema = 'public'
87
+ SQL
88
+ result.group_by { _1['table_name'] }
89
+ end
90
+
91
+ schema = @schema.fetch(table_name) do
92
+ raise Error, "Failed to load schema for #{table_name.inspect}"
93
+ end
94
+
95
+ schema.group_by { _1['column_name'] }.transform_values(&:first)
96
+ end
97
+ end
98
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pgb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dmitry Gubitskiy
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-12-11 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: pg
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.4'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.4'
27
+ - !ruby/object:Gem::Dependency
28
+ name: zeitwerk
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.6'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.6'
41
+ description:
42
+ email:
43
+ - d.gubitskiy@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rspec"
49
+ - ".rubocop.yml"
50
+ - ".ruby-version"
51
+ - CHANGELOG.md
52
+ - CODE_OF_CONDUCT.md
53
+ - Gemfile
54
+ - Gemfile.lock
55
+ - LICENSE.txt
56
+ - README.md
57
+ - Rakefile
58
+ - lib/pgb.rb
59
+ - lib/pgb/casting.rb
60
+ - lib/pgb/column_reference.rb
61
+ - lib/pgb/command.rb
62
+ - lib/pgb/evaluation_context.rb
63
+ - lib/pgb/executable.rb
64
+ - lib/pgb/expression.rb
65
+ - lib/pgb/function_call.rb
66
+ - lib/pgb/identifier.rb
67
+ - lib/pgb/keyword.rb
68
+ - lib/pgb/literal.rb
69
+ - lib/pgb/model.rb
70
+ - lib/pgb/mutable.rb
71
+ - lib/pgb/operator_call.rb
72
+ - lib/pgb/query.rb
73
+ - lib/pgb/shortcuts.rb
74
+ - lib/pgb/sql_displayable.rb
75
+ - lib/pgb/type_cast.rb
76
+ - lib/pgb/version.rb
77
+ homepage: https://github.com/enthrops/pgb
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ homepage_uri: https://github.com/enthrops/pgb
82
+ source_code_uri: https://github.com/enthrops/pgb
83
+ changelog_uri: https://github.com/enthrops/pgb/blob/master/CHANGELOG.md
84
+ rubygems_mfa_required: 'true'
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '2.7'
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 3.3.26
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: Postgres-specific ORM for Ruby
104
+ test_files: []