active_house 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
+ SHA1:
3
+ metadata.gz: 58b0c99dba934d9221bab61deaf93f9c57c2c7b1
4
+ data.tar.gz: 3599246186ddb0b17614125df13873759accd1ac
5
+ SHA512:
6
+ metadata.gz: 70097321f7661448738fe93cb002c48436093a98280bdb566b304c86ec3ec0716b11d99a6783442289f42df9aafb01aa46f7c57065034d261437456487ad2d24
7
+ data.tar.gz: 41a34905f357a2b5b9a3675c7a1bd9e66c962e59fcad6eb650461f7d198b2c7b104c6e643ea2c93abfb8a039c7e96e005a0f9876fcb9484bb329a2f3174f30a4
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
data/.rubocop.yml ADDED
@@ -0,0 +1,39 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.2
3
+ DisplayCopNames: true
4
+
5
+ Style/Documentation:
6
+ Enabled: false
7
+
8
+ Metrics/LineLength:
9
+ Enabled: false
10
+
11
+ Metrics/MethodLength:
12
+ Enabled: false
13
+
14
+ Metrics/AbcSize:
15
+ Enabled: false
16
+
17
+ Metrics/MethodLength:
18
+ Enabled: false
19
+
20
+ Metrics/PerceivedComplexity:
21
+ Enabled: false
22
+
23
+ Metrics/CyclomaticComplexity:
24
+ Enabled: false
25
+
26
+ Metrics/ClassLength:
27
+ Enabled: false
28
+
29
+ Metrics/BlockLength:
30
+ Enabled: false
31
+
32
+ Style/SymbolArray:
33
+ EnforcedStyle: brackets
34
+
35
+ Layout/IndentArray:
36
+ IndentationWidth: 4
37
+
38
+ Layout/IndentHash:
39
+ IndentationWidth: 4
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.2.4
7
+ before_install: gem install bundler -v 1.16.3
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at senid231@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source 'https://rubygems.org'
2
+
3
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in active_house.gemspec
6
+ gemspec
7
+
8
+ group :test do
9
+ gem 'rubocop', '0.58.1', require: false
10
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Denis Talakevich
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,41 @@
1
+ # ActiveHouse
2
+
3
+ ClickHouse ORM and Query DSL
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'active_house'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install active_house
20
+
21
+ ## Usage
22
+
23
+ TODO: Write usage instructions here
24
+
25
+ ## Development
26
+
27
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
28
+
29
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
30
+
31
+ ## Contributing
32
+
33
+ Bug reports and pull requests are welcome on GitHub at https://github.com/senid231/active_house. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
34
+
35
+ ## License
36
+
37
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
38
+
39
+ ## Code of Conduct
40
+
41
+ Everyone interacting in the ActiveHouse project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/active_house/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rake/testtask'
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << 'test'
6
+ t.libs << 'lib'
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task default: :test
@@ -0,0 +1,32 @@
1
+ lib = File.expand_path('lib', __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'active_house/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'active_house'
7
+ spec.version = ActiveHouse::VERSION
8
+ spec.authors = ['Denis Talakevich']
9
+ spec.email = ['senid231@gmail.com']
10
+
11
+ spec.summary = 'ORM and Query DSL for ClickHouse'
12
+ spec.description = 'ORM and Query DSL for ClickHouse'
13
+ spec.homepage = 'https://github.com/senid231/active_house'
14
+ spec.license = 'MIT'
15
+
16
+ # Specify which files should be added to the gem when it is released.
17
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
18
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
19
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ end
21
+ spec.bindir = 'exe'
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ['lib']
24
+
25
+ spec.add_dependency 'activemodel', '~> 5.0.0'
26
+ spec.add_dependency 'activesupport', '~> 5.0.0'
27
+ spec.add_dependency 'clickhouse', '~> 0.1.10'
28
+
29
+ spec.add_development_dependency 'bundler', '~> 1.16'
30
+ spec.add_development_dependency 'minitest', '~> 5.0'
31
+ spec.add_development_dependency 'rake', '~> 10.0'
32
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'active_house'
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require 'irb'
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,14 @@
1
+ require 'active_house/version'
2
+ require 'active_house/configuration'
3
+ require 'active_house/query'
4
+ require 'active_house/model'
5
+
6
+ module ActiveHouse
7
+ def self.configure
8
+ yield configuration
9
+ end
10
+
11
+ def self.configuration
12
+ ActiveHouse::Configuration.configuration
13
+ end
14
+ end
@@ -0,0 +1,117 @@
1
+ require_relative 'selectable'
2
+ require_relative 'fromable'
3
+ require_relative 'whereable'
4
+ require_relative 'orderable'
5
+ require_relative 'groupable'
6
+ require 'active_support/concern'
7
+
8
+ module ActiveHouse
9
+ module Chainable
10
+ extend ActiveSupport::Concern
11
+
12
+ include ActiveHouse::Selectable
13
+ include ActiveHouse::Fromable
14
+ include ActiveHouse::Whereable
15
+ include ActiveHouse::Orderable
16
+ include ActiveHouse::Groupable
17
+
18
+ included do
19
+ protected
20
+
21
+ def data
22
+ chain_methods.values.map { |var| [var, instance_variable_get(:"@#{var}")] }.to_h
23
+ end
24
+
25
+ def data=(other_data)
26
+ chain_methods.values.each do |var|
27
+ instance_variable_set(:"@#{var}", other_data.fetch(var).dup)
28
+ end
29
+ end
30
+
31
+ def query_parts
32
+ [
33
+ build_select_query_part,
34
+ build_from_query_part,
35
+ build_where_query_part,
36
+ build_group_by_query_part,
37
+ build_order_by_query_part
38
+ ]
39
+ end
40
+
41
+ def build_query
42
+ query_parts.reject(&:nil?).join("\n")
43
+ end
44
+
45
+ private
46
+
47
+ # By default each chain method (select, where, group_by) returns new instance of query
48
+ # but in some cases we need to modify and return existing query object
49
+ # (for example when we apply default_scope on query initialize).
50
+ # For this you need just to wrap code that appends chain methods with #with_current_query.
51
+ # Example:
52
+ #
53
+ # scope1 = SomeModel.all # object id #1
54
+ # scope2 = scope1.where(id: 3) # object id #2
55
+ # scope3 = scope2.send(:with_current_query) { scope2.where(success: true) } # object id #2
56
+ #
57
+ def with_current_query
58
+ @_with_current_query = true
59
+ yield
60
+ ensure
61
+ @_with_current_query = false
62
+ end
63
+
64
+ def chain_query(options = {})
65
+ options.assert_valid_keys(*chain_methods.values)
66
+ if @_with_current_query
67
+ self.data = data.merge(options)
68
+ self
69
+ else
70
+ new_instance = self.class.new(model_class)
71
+ new_instance.data = data.merge(options)
72
+ new_instance
73
+ end
74
+ end
75
+ end
76
+
77
+ def initialize(*)
78
+ @_with_current_query = false
79
+ super
80
+ end
81
+
82
+ # key - chain method name
83
+ # value - instance variable name that which store values
84
+ def chain_methods
85
+ {
86
+ select: :fields,
87
+ where: :conditions,
88
+ group_by: :grouping,
89
+ order_by: :ordering
90
+ }
91
+ end
92
+
93
+ def except(*values)
94
+ raise ArgumentError, 'wrong number of arguments' if values.empty?
95
+ not_allowed = values - chain_methods.keys
96
+ unless not_allowed.empty?
97
+ raise ArgumentError, "Values #{not_allowed} are not allowed, allowed only #{chain_methods.keys}."
98
+ end
99
+
100
+ new_data = {}
101
+ chain_methods.each do |meth, var|
102
+ new_data[var] = [] if values.include?(meth)
103
+ end
104
+ chain_query(new_data)
105
+ end
106
+
107
+ def to_query
108
+ build_query
109
+ end
110
+
111
+ def dup
112
+ chain_query
113
+ end
114
+
115
+ alias clone dup
116
+ end
117
+ end
@@ -0,0 +1,33 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveHouse
4
+ module Collectable
5
+ extend ActiveSupport::Concern
6
+
7
+ def initialize(*)
8
+ @collection = nil
9
+ super
10
+ end
11
+
12
+ def to_a
13
+ collection
14
+ end
15
+
16
+ def reset
17
+ @collection = nil
18
+ end
19
+
20
+ def loaded?
21
+ !@collection.nil?
22
+ end
23
+
24
+ def collection
25
+ @collection ||= fetch_collection
26
+ end
27
+
28
+ def fetch_collection
29
+ result = connection.select_rows(to_query.squish)
30
+ result.map { |row| model_class.new(row) }
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,41 @@
1
+ require 'singleton'
2
+ require 'clickhouse'
3
+ require 'active_support/core_ext/hash/keys'
4
+ require 'active_support/concern'
5
+
6
+ module ActiveHouse
7
+ class Configuration
8
+ include Singleton
9
+
10
+ MAIN_NAME = :main
11
+ CONNECTION_KEYS = [
12
+ :url, :urls, :host, :port, :scheme, :database
13
+ ].freeze
14
+
15
+ class << self
16
+ alias configuration instance
17
+ end
18
+
19
+ attr_reader :connection_config, :logger
20
+
21
+ def logger=(value)
22
+ @logger = value
23
+ Clickhouse.logger = @logger
24
+ end
25
+
26
+ def connection_config=(value)
27
+ @connection_config = value.deep_symbolize_keys
28
+ end
29
+
30
+ def connection_config_for(name = nil)
31
+ name ||= MAIN_NAME
32
+ name = name.to_sym
33
+ config = if name == MAIN_NAME
34
+ connection_config.key?(name) ? connection_config.fetch(name) : connection_config
35
+ else
36
+ connection_config.fetch(name)
37
+ end
38
+ config.slice(*CONNECTION_KEYS)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,36 @@
1
+ require_relative 'connection'
2
+ require_relative 'configuration'
3
+ require 'active_support/core_ext/class/attribute'
4
+ require 'active_support/concern'
5
+
6
+ module ActiveHouse
7
+ module Connecting
8
+ extend ActiveSupport::Concern
9
+
10
+ included do
11
+ class_attribute :_connection_class, instance_accessor: false
12
+ class_attribute :_connection, instance_accessor: false
13
+ self._connection_class = ActiveHouse::Connection
14
+ end
15
+
16
+ class_methods do
17
+ def ensure_connection
18
+ establish_connection if _connection.nil?
19
+ end
20
+
21
+ def establish_connection(name_or_config = nil)
22
+ config = if name_or_config.is_a?(Hash)
23
+ name_or_config.symbolize_keys
24
+ else
25
+ ActiveHouse.configuration.connection_config_for(name_or_config)
26
+ end
27
+ self._connection = _connection_class.new(config)
28
+ end
29
+
30
+ def connection
31
+ ensure_connection
32
+ _connection
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,82 @@
1
+ require_relative 'connection_error'
2
+ require_relative 'prepared_statement'
3
+ require 'clickhouse/cluster'
4
+ require 'clickhouse/connection'
5
+
6
+ module ActiveHouse
7
+ class Connection
8
+ attr_reader :config
9
+
10
+ def initialize(config)
11
+ config.assert_valid_keys(:url, :urls, :database, :username, :password, :host, :port, :scheme)
12
+ @config = config
13
+ @connection = nil
14
+ ensure_connected!
15
+ end
16
+
17
+ def execute(sql, *bindings)
18
+ prepared_sql = prepared_statement(sql, *bindings)
19
+ connection.execute(prepared_sql)
20
+ end
21
+
22
+ def select_all(sql, *bindings)
23
+ prepared_sql = prepared_statement(sql, *bindings)
24
+ connection.query(prepared_sql)
25
+ end
26
+
27
+ def select_values(sql, *bindings)
28
+ select_all(sql, *bindings).flatten
29
+ end
30
+
31
+ def select_value(sql, *bindings)
32
+ select_all(sql, *bindings).flatten.first
33
+ end
34
+
35
+ def select_row(sql, *bindings)
36
+ select_all(sql, *bindings).to_hashes.first
37
+ end
38
+
39
+ def select_rows(sql, *bindings)
40
+ select_all(sql, *bindings).to_hashes
41
+ end
42
+
43
+ def connection_alive?
44
+ return false if connection.nil?
45
+ if connection.is_a?(Clickhouse::Cluster)
46
+ !connection.pond.available.empty?
47
+ else
48
+ begin
49
+ connection.ping!
50
+ true
51
+ rescue StandardError
52
+ false
53
+ end
54
+ end
55
+ end
56
+
57
+ def reconnect!
58
+ ensure_connected!
59
+ end
60
+
61
+ private
62
+
63
+ def prepared_statement(sql, *bindings)
64
+ ActiveHouse::PreparedStatement.prepare_sql(sql, *bindings)
65
+ end
66
+
67
+ attr_reader :connection
68
+
69
+ def ensure_connected!
70
+ @connection = establish_connection unless connection_alive?
71
+ raise ActiveHouse::ConnectionError unless connection_alive?
72
+ end
73
+
74
+ def establish_connection
75
+ if config.key?(:urls)
76
+ Clickhouse::Cluster.new(config)
77
+ else
78
+ Clickhouse::Connection.new(config)
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,6 @@
1
+ require_relative 'error'
2
+
3
+ module ActiveHouse
4
+ class ConnectionError < Error
5
+ end
6
+ end
@@ -0,0 +1,4 @@
1
+ module ActiveHouse
2
+ class Error < ::StandardError
3
+ end
4
+ end
@@ -0,0 +1,22 @@
1
+ module ActiveHouse
2
+ module Fromable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ private
7
+
8
+ def build_from_query_part
9
+ "FROM #{table_name}"
10
+ end
11
+ end
12
+
13
+ def initialize(*)
14
+ @table_name = model_class._table_name
15
+ super
16
+ end
17
+
18
+ def table_name
19
+ @table_name
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,23 @@
1
+ module ActiveHouse
2
+ module Groupable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ private
7
+
8
+ def build_group_by_query_part
9
+ "GROUP BY #{@grouping.join(', ')}" unless @grouping.empty?
10
+ end
11
+ end
12
+
13
+ def initialize(*)
14
+ @grouping = []
15
+ super
16
+ end
17
+
18
+ def group_by(*fields)
19
+ raise ArgumentError, 'wrong number of arguments' if fields.empty?
20
+ chain_query grouping: (@grouping + fields.map(&:to_s)).uniq
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,17 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveHouse
4
+ module Logger
5
+ extend ActiveSupport::Concern
6
+
7
+ class_methods do
8
+ def logger
9
+ Clickhouse.logger
10
+ end
11
+ end
12
+
13
+ def logger
14
+ self.class.logger
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,27 @@
1
+ require_relative 'scoping'
2
+ require_relative 'querying'
3
+ require_relative 'modeling'
4
+ require_relative 'connecting'
5
+ require_relative 'logger'
6
+ require 'active_model/conversion'
7
+ require 'active_model/naming'
8
+
9
+ module ActiveHouse
10
+ class Model
11
+ include ActiveHouse::Scoping
12
+ include ActiveHouse::Querying
13
+ include ActiveHouse::Modeling
14
+ include ActiveHouse::Connecting
15
+ include ActiveHouse::Logger
16
+ include ActiveModel::Conversion
17
+ extend ActiveModel::Naming
18
+
19
+ class_attribute :_table_name, instance_accessor: false
20
+
21
+ class << self
22
+ def table_name(name)
23
+ self._table_name = name.to_s
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,76 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveHouse
4
+ module Modeling
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ class_attribute :_attribute_opts, instance_writer: false
9
+ self._attribute_opts = {}
10
+
11
+ private
12
+
13
+ def parse_attribute_method_name(method_name)
14
+ name, is_setter = method_name.to_s.match(/\A(.+)?(=)?\z/).captures
15
+ name = name.to_sym
16
+ is_setter = !is_setter.nil?
17
+ [name, is_setter]
18
+ end
19
+
20
+ def attribute_method?(name, is_setter, *args)
21
+ (_attribute_opts.key?(name) || @_attributes.key?(name)) && (is_setter ? args.size.one? : true)
22
+ end
23
+
24
+ def get_attribute(name)
25
+ @_attributes[name]
26
+ end
27
+
28
+ def set_attribute(name, value)
29
+ @_attributes[name] = value
30
+ end
31
+ end
32
+
33
+ class_methods do
34
+ def attribute(name, options = {})
35
+ name = name.to_sym
36
+ self._attribute_opts = _attribute_opts.merge(name => options)
37
+ end
38
+
39
+ def attributes(*names)
40
+ options = names.extract_options!
41
+ names.each { |name| attributes(name, options.dup) }
42
+ end
43
+ end
44
+
45
+ def initialize(params = {})
46
+ @_attributes = {}
47
+ assign_attributes(params)
48
+ end
49
+
50
+ def as_json(*_args)
51
+ to_h
52
+ end
53
+
54
+ def to_h
55
+ @_attributes.dup
56
+ end
57
+
58
+ def [](key)
59
+ @_attributes[key.to_sym]
60
+ end
61
+
62
+ def respond_to_missing?(method_name, *args)
63
+ name, is_setter = parse_attribute_method_name(method_name)
64
+ attribute_method?(name, is_setter, *args)
65
+ end
66
+
67
+ def method_missing(method_name, *args, &block)
68
+ name, is_setter = parse_attribute_method_name(method_name)
69
+ if attribute_method?(name, is_setter, *args)
70
+ is_setter ? set_attribute(name, args.first) : get_attribute(name)
71
+ else
72
+ super
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,43 @@
1
+ module ActiveHouse
2
+ module Orderable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ private
7
+
8
+ def build_order_by_query_part
9
+ "ORDER BY #{@ordering.join(', ')}" unless @ordering.empty?
10
+ end
11
+ end
12
+
13
+ def initialize(*)
14
+ @ordering = []
15
+ super
16
+ end
17
+
18
+ def order_by(*clauses)
19
+ raise ArgumentError, 'wrong number of arguments' if clauses.empty?
20
+ formatter_clauses = clauses.map do |clause|
21
+ if clause.is_a?(String)
22
+ clause
23
+ elsif clause.is_a?(Symbol)
24
+ clause.to_s
25
+ elsif clause.is_a?(Hash)
26
+ if clause.keys.one?
27
+ direction = clause.values.first
28
+ raise ArgumentError, 'direction must be asc or desc' if [:asc, :desc].exclude?(direction.try!(:to_sym))
29
+ "#{clause.keys.first} #{direction.to_s.upcase}"
30
+ else
31
+ clause.assert_valid_keys(:field, :direction, :collate)
32
+ [
33
+ clause.fetch(:field),
34
+ clause[:direction].try!(:to_s).try!(:upcase),
35
+ clause.key?(:collate) ? "COLLATE '#{clause[:collate]}'" : nil
36
+ ].reject(&:nil?).join(' ')
37
+ end
38
+ end
39
+ end
40
+ chain_query ordering: (@ordering + formatter_clauses).uniq
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,38 @@
1
+ module ActiveHouse
2
+ module PreparedStatement
3
+ def self.prepare_sql(sql, *bindings)
4
+ return sql if bindings.empty?
5
+ parts = sql_parts(sql)
6
+ raise ArgumentError, 'wrong number of bindings' if parts.size != bindings.size + 1
7
+ parts.map.with_index do |part, idx|
8
+ value = idx + 1 > bindings.size ? nil : format_value(bindings[idx])
9
+ "#{part}#{value}"
10
+ end.join
11
+ sql
12
+ end
13
+
14
+ def self.format_value(value)
15
+ return 'NULL' if value.nil?
16
+ if value.is_a?(Array)
17
+ "(#{value.map { |val| format_value(val) }.join(', ')})"
18
+ elsif value.is_a?(String)
19
+ "'#{value.gsub("'", "\\'")}'"
20
+ elsif value.is_a?(Time)
21
+ if value.respond_to?(:zone)
22
+ "toDateTime('#{value.strftime('%Y-%m-%d %H:%M:%S')}', '#{value.zone}')"
23
+ else
24
+ "toDateTime('#{value.strftime('%Y-%m-%d %H:%M:%S')}')"
25
+ end
26
+ else
27
+ value.to_s
28
+ end
29
+ end
30
+
31
+ def self.sql_parts(sql)
32
+ # TODO: except prepended with backslash or inside brackets
33
+ parts = sql.split('?')
34
+ parts.push('') if sql.end_with?('?')
35
+ parts
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,22 @@
1
+ require_relative 'chainable'
2
+ require_relative 'scopeable'
3
+ require_relative 'collectable'
4
+
5
+ module ActiveHouse
6
+ class Query
7
+ attr_reader :model_class
8
+
9
+ def initialize(model_class = ActiveHouse::Model)
10
+ @model_class = model_class
11
+ super()
12
+ end
13
+
14
+ def connection
15
+ model_klass.connection
16
+ end
17
+
18
+ include ActiveHouse::Chainable
19
+ include ActiveHouse::Collectable
20
+ include ActiveHouse::Scopeable
21
+ end
22
+ end
@@ -0,0 +1,21 @@
1
+ require 'active_support/concern'
2
+ require 'active_support/core_ext/module/delegation'
3
+
4
+ module ActiveHouse
5
+ module Querying
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ class_attribute :_query_class, instance_accessor: false
10
+ self._query_class = ActiveHouse::Query
11
+ end
12
+
13
+ class_methods do
14
+ delegate :to_a, :select, :where, :group_by, to: :all
15
+
16
+ def all
17
+ _query_class.new(self)
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,41 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveHouse
4
+ module Scopeable
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ private
9
+
10
+ def apply_scope(name)
11
+ scope = model_class._scopes.fetch(name.to_sym)
12
+ instance_exec(*args, &scope)
13
+ end
14
+
15
+ def scope?(name)
16
+ model_class._scopes.key?(name.to_sym)
17
+ end
18
+
19
+ def apply_default_scope
20
+ apply_scope(model_class._default_scope) unless model_class._default_scope.nil?
21
+ end
22
+ end
23
+
24
+ def initialize(*)
25
+ super
26
+ with_current_query { apply_default_scope }
27
+ end
28
+
29
+ def respond_to_missing?(method_name, *_args)
30
+ scope?(method_name) || super
31
+ end
32
+
33
+ def method_missing(method_name, *args, &_block)
34
+ if scope?(method_name)
35
+ apply_scope(method_name)
36
+ else
37
+ super
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,37 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveHouse
4
+ module Scoping
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ class_attribute :_default_scope, instance_accessor: false
9
+ class_attribute :_scopes, instance_accessor: false
10
+ self._scopes = {}
11
+ end
12
+
13
+ class_methods do
14
+ def default_scope(&block)
15
+ self._default_scope = block
16
+ end
17
+
18
+ def scope(name, block)
19
+ self._scopes = _scopes.merge(name.to_sym => block)
20
+ end
21
+
22
+ def respond_to_missing?(method_name, *_args)
23
+ _scopes.key?(method_name.to_sym)
24
+ end
25
+
26
+ def method_missing(method_name, *args, &_block)
27
+ method_name = method_name.to_sym
28
+ if _scopes.key?(method_name)
29
+ scope = _scopes.fetch(method_name)
30
+ all.instance_exec(*args, &scope)
31
+ else
32
+ super
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,37 @@
1
+ module ActiveHouse
2
+ module Selectable
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ private
7
+
8
+ def build_select_query_part
9
+ if !@fields.empty?
10
+ query_data = ['SELECT']
11
+ query_data.concat @fields
12
+ else
13
+ query_data = ['SELECT *']
14
+ end
15
+ query_data.join("\n")
16
+ end
17
+ end
18
+
19
+ def initialize(*)
20
+ @fields = []
21
+ super
22
+ end
23
+
24
+ def select(*fields)
25
+ raise ArgumentError, 'wrong number of arguments' if fields.empty?
26
+ formatted_fields = fields.map do |field|
27
+ if field.is_a?(Symbol) && model_class._attribute_opts.key?(field)
28
+ opts = model_class._attribute_opts.fetch(field)
29
+ opts.key?(:select) ? "#{opts[:select]} AS #{field}" : field.to_s
30
+ else
31
+ field.to_s
32
+ end
33
+ end
34
+ chain_query fields: (@fields + formatted_fields).uniq
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,3 @@
1
+ module ActiveHouse
2
+ VERSION = '0.1.0'.freeze
3
+ end
@@ -0,0 +1,54 @@
1
+ require_relative 'prepared_statement'
2
+ require 'active_support/core_ext/array/wrap'
3
+
4
+ module ActiveHouse
5
+ module Whereable
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ private
10
+
11
+ def format_condition_value(value)
12
+ ActiveHouse::PreparedStatement.format_value(value)
13
+ end
14
+
15
+ def format_condition(*conditions)
16
+ raise ArgumentError, 'wrong number of arguments' if conditions.empty?
17
+ return ActiveHouse::PreparedStatement.prepare_sql(*conditions) if conditions.size > 1
18
+ condition = conditions.first
19
+ if condition.is_a?(Hash)
20
+ condition.map do |field, value|
21
+ "#{field} #{sign_for_condition(value)} #{ActiveHouse::PreparedStatement.format_value(value)}"
22
+ end
23
+ else
24
+ condition.to_s
25
+ end
26
+ end
27
+
28
+ def sign_for_condition(value)
29
+ if value.is_a?(Array)
30
+ 'IN'
31
+ elsif value.nil?
32
+ 'IS'
33
+ else
34
+ '='
35
+ end
36
+ end
37
+
38
+ def build_where_query_part
39
+ "WHERE\n" + @conditions.join(" AND\n") unless @conditions.empty?
40
+ end
41
+ end
42
+
43
+ def initialize(*)
44
+ @conditions = []
45
+ super
46
+ end
47
+
48
+ def where(*conditions)
49
+ raise ArgumentError, 'wrong number of arguments' if conditions.empty?
50
+ formatted_conditions = Array.wrap(format_condition(*conditions))
51
+ chain_query conditions: (@conditions + formatted_conditions).uniq
52
+ end
53
+ end
54
+ end
metadata ADDED
@@ -0,0 +1,161 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_house
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Denis Talakevich
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-07-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activemodel
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 5.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 5.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 5.0.0
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 5.0.0
41
+ - !ruby/object:Gem::Dependency
42
+ name: clickhouse
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 0.1.10
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 0.1.10
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.16'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.16'
69
+ - !ruby/object:Gem::Dependency
70
+ name: minitest
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '5.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '5.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '10.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '10.0'
97
+ description: ORM and Query DSL for ClickHouse
98
+ email:
99
+ - senid231@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rubocop.yml"
106
+ - ".travis.yml"
107
+ - CODE_OF_CONDUCT.md
108
+ - Gemfile
109
+ - LICENSE.txt
110
+ - README.md
111
+ - Rakefile
112
+ - active_house.gemspec
113
+ - bin/console
114
+ - bin/setup
115
+ - lib/active_house.rb
116
+ - lib/active_house/chainable.rb
117
+ - lib/active_house/collectable.rb
118
+ - lib/active_house/configuration.rb
119
+ - lib/active_house/connecting.rb
120
+ - lib/active_house/connection.rb
121
+ - lib/active_house/connection_error.rb
122
+ - lib/active_house/error.rb
123
+ - lib/active_house/fromable.rb
124
+ - lib/active_house/groupable.rb
125
+ - lib/active_house/logger.rb
126
+ - lib/active_house/model.rb
127
+ - lib/active_house/modeling.rb
128
+ - lib/active_house/orderable.rb
129
+ - lib/active_house/prepared_statement.rb
130
+ - lib/active_house/query.rb
131
+ - lib/active_house/querying.rb
132
+ - lib/active_house/scopeable.rb
133
+ - lib/active_house/scoping.rb
134
+ - lib/active_house/selectable.rb
135
+ - lib/active_house/version.rb
136
+ - lib/active_house/whereable.rb
137
+ homepage: https://github.com/senid231/active_house
138
+ licenses:
139
+ - MIT
140
+ metadata: {}
141
+ post_install_message:
142
+ rdoc_options: []
143
+ require_paths:
144
+ - lib
145
+ required_ruby_version: !ruby/object:Gem::Requirement
146
+ requirements:
147
+ - - ">="
148
+ - !ruby/object:Gem::Version
149
+ version: '0'
150
+ required_rubygems_version: !ruby/object:Gem::Requirement
151
+ requirements:
152
+ - - ">="
153
+ - !ruby/object:Gem::Version
154
+ version: '0'
155
+ requirements: []
156
+ rubyforge_project:
157
+ rubygems_version: 2.4.8
158
+ signing_key:
159
+ specification_version: 4
160
+ summary: ORM and Query DSL for ClickHouse
161
+ test_files: []