niceql 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: 7f43c7e4d45b26a700c72420b528e162d26814bd
4
+ data.tar.gz: e634c50d9336928faf6730428098752269ae6de9
5
+ SHA512:
6
+ metadata.gz: a6467d75c04de184e7adfd2972753e94237b96e14b7d952f18c8939982dfba353c4f17281492878c9a04edd957d14b60ef8dd2649a91c0fa1a76df0ee1144fec
7
+ data.tar.gz: dd708fe3bc10676735fb4a9a821366fb3206d04e4f8402bc2433db155a5eff25aa63bd2ffea7b8a71fe509de0c2600f44aa2dc3dbf090ab4723d61796ec22118
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /inspectionProfiles/
11
+ .idea
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.1
5
+ before_install: gem install bundler -v 1.15.4
data/Gemfile ADDED
@@ -0,0 +1,6 @@
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 niceql.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 alekseyl
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,102 @@
1
+ # Niceql
2
+
3
+ This is small, nice, simple and dependentless solution for SQL prettifiyng for Ruby.
4
+ It can be used in irb console without any dependencies ( run ./console from bin and look for examples ).
5
+
6
+ Any reasonable suggestions on formatting/coloring are welcome
7
+
8
+ ## Before/After
9
+ ### SQL prettifier:
10
+ ![alt text](https://github.com/alekseyl/niceql/raw/master/to_niceql.png "To_niceql")
11
+
12
+ ### PG errors prettifier
13
+
14
+ before:
15
+ ![alt text](https://github.com/alekseyl/niceql/raw/master/err_was.png "To_niceql")
16
+
17
+ after:
18
+ ![alt text](https://github.com/alekseyl/niceql/raw/master/err_now.png "To_niceql")
19
+
20
+
21
+ ## Installation
22
+
23
+ Add this line to your application's Gemfile:
24
+
25
+ ```ruby
26
+ gem 'niceql'
27
+ ```
28
+
29
+ And then execute:
30
+
31
+ $ bundle
32
+
33
+ Or install it yourself as:
34
+
35
+ $ gem install niceql
36
+
37
+ ## Usage
38
+
39
+ ### With ActiveRecord
40
+
41
+ ```ruby
42
+ # prettify to_sql
43
+ Model.scope.to_niceql
44
+
45
+ # prettify PG errors
46
+ Model.scope_with_err.explain_err
47
+ ```
48
+
49
+ ### Without ActiveRecord
50
+
51
+ ```ruby
52
+ puts Niceql::Prettifier.prettify_sql("SELECT * FROM ( VALUES(1), (2) ) AS tmp")
53
+
54
+ # see colors in irb %)
55
+ #=> SELECT *
56
+ #=> FROM ( VALUES(1), (2) ) AS tmp
57
+
58
+ # rails combines err with query, so don't forget to do it yourself
59
+ # to get real nice result you should execute on your DB prettified_sql!
60
+ # otherwise you will not get such a nice output
61
+
62
+ puts Niceql::Prettifier.prettify_pg_err(<<-ERR )
63
+ ERROR: VALUES in FROM must have an alias
64
+ LINE 2: FROM ( VALUES(1), (2) )
65
+ ^
66
+ HINT: For example, FROM (VALUES ...) [AS] foo.
67
+ SELECT err
68
+ FROM ( VALUES(1), (2) )
69
+ ORDER BY 1
70
+ ERR
71
+
72
+
73
+ # ERROR: VALUES in FROM must have an alias
74
+ # LINE 2: FROM ( VALUES(1), (2) )
75
+ # ^
76
+ # HINT: For example, FROM (VALUES ...) [AS] foo.
77
+ # SELECT err
78
+ # FROM ( VALUES(1), (2) )
79
+ # ^
80
+ # ORDER BY 1
81
+
82
+ ```
83
+ ## Limitations
84
+
85
+ Right now it detect only uppercase verbs with simple indentation and parsing options.
86
+ Also if your console support more colors or different schemes, or you prefer different colorization you can override ColorizeString
87
+ methods. Current color are selected with dark and white console themes in mind, so it works good for dark, and good enough for white.
88
+
89
+
90
+ ## Development
91
+
92
+ 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.
93
+
94
+ 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).
95
+
96
+ ## Contributing
97
+
98
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/niceql.
99
+
100
+ ## License
101
+
102
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
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
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "niceql"
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
data/err_now.png ADDED
Binary file
data/err_was.png ADDED
Binary file
data/lib/niceql.rb ADDED
@@ -0,0 +1,103 @@
1
+ require "niceql/version"
2
+
3
+ module Niceql
4
+ module StringColorize
5
+ def self.colorize_verb( str)
6
+ #yellow ANSI color
7
+ "\e[0;33;49m#{str}\e[0m"
8
+ end
9
+ def self.colorize_str(str)
10
+ #cyan ANSI color
11
+ "\e[0;36;49m#{str}\e[0m"
12
+ end
13
+ def self.colorize_err(err)
14
+ #red ANSI color
15
+ "\e[0;31;49m#{err}\e[0m"
16
+ end
17
+ end
18
+
19
+ module ArExtentions
20
+ def explain_err
21
+ begin
22
+ connection.execute( "EXPLAIN #{Prettifier.prettify_sql(to_sql, false)}" )
23
+ rescue StandardError => e
24
+ puts Prettifier.prettify_err(e )
25
+ end
26
+ end
27
+
28
+ def to_niceql( colorize = true )
29
+ puts Prettifier.prettify_sql( to_sql, colorize )
30
+ end
31
+ end
32
+
33
+ module Prettifier
34
+ INLINE_VERBS = %w(ASC IN AS WHEN THEN ELSE END AND UNION ALL WITH ON DISTINCT INTERSECT EXCEPT EXISTS NOT).join('| ')
35
+ NEW_LINE_VERBS = 'SELECT|FROM|WHERE|CASE|ORDER BY|LIMIT|GROUP BY|WITH|LEFT JOIN|RIGHT JOIN|JOIN|HAVING|OFFSET'
36
+ VERBS = "#{INLINE_VERBS}|#{NEW_LINE_VERBS}"
37
+ STRINGS = /("[^"]+")|('[^']+')/
38
+ BRACKETS = '[\(\)]'
39
+
40
+ def self.prettify_err(err)
41
+ if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql'
42
+ prettify_pg_err( err.to_s )
43
+ else
44
+ puts err
45
+ end
46
+ end
47
+
48
+
49
+ def self.prettify_pg_err(err)
50
+ err_line_num = err[/LINE \d+/][5..-1].to_i
51
+ start_sql_line = err.lines[3][/HINT/] ? 4 : 3
52
+ err_body = err.lines[start_sql_line..-1]
53
+ err_line = StringColorize.colorize_err( err_body[err_line_num-1] )
54
+
55
+ err_body = err_body.join.gsub(/#{VERBS}/ ) { |verb| StringColorize.colorize_verb(verb) }
56
+ err_body = err_body.gsub(STRINGS){ |str| StringColorize.colorize_str(str) }
57
+
58
+ err_body = err_body.lines
59
+ err_body[err_line_num-1]= err_line
60
+ err_body.insert( err_line_num, StringColorize.colorize_err( err.lines[2][err.lines[1][/LINE \d+:/].length+1..-1] ) )
61
+ puts err.lines[0..start_sql_line-1].join + err_body.join
62
+ end
63
+
64
+ def self.prettify_sql( sql, colorize = true )
65
+ indent = 0
66
+ parentness = []
67
+
68
+ sql = sql.gsub(STRINGS){ |str| StringColorize.colorize_str(str) } if colorize
69
+
70
+ sql.gsub( /(#{VERBS}|#{BRACKETS})/) do |verb|
71
+ add_new_line = false
72
+ if 'SELECT' == verb
73
+ indent += 1
74
+ parentness.last[:nested] = true if parentness.last
75
+ add_new_line = true
76
+ elsif verb == '('
77
+ parentness << { nested: false }
78
+ indent += 1
79
+ elsif verb == ')'
80
+ # this also covers case when right bracket is used without corresponding left one
81
+ add_new_line = parentness.last.nil? || parentness.last[:nested]
82
+ indent -= add_new_line ? 2 : 1
83
+ indent = 0 if indent < 0
84
+ parentness.pop
85
+ elsif verb == 'ORDER BY'
86
+ # in postgres ORDER BY can be used in aggregation function this will keep it
87
+ # inline with its agg function
88
+ add_new_line = parentness.last.nil? || parentness.last[:nested]
89
+ else
90
+ add_new_line = verb[/(#{INLINE_VERBS})/].nil?
91
+ end
92
+ verb = StringColorize.colorize_verb(verb) if !['(', ')'].include?(verb) && colorize
93
+
94
+ add_new_line ? "\n#{' ' * indent}" + verb : verb
95
+ end
96
+ end
97
+ end
98
+
99
+ if defined? ::ActiveRecord::Base
100
+ ::ActiveRecord::Base.extend ArExtentions
101
+ [::ActiveRecord::Relation, ::ActiveRecord::Associations::CollectionProxy].each { |klass| klass.send(:include, ArExtentions) }
102
+ end
103
+ end
@@ -0,0 +1,3 @@
1
+ module Niceql
2
+ VERSION = "0.1.0"
3
+ end
data/niceql.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "niceql/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "niceql"
8
+ spec.version = Niceql::VERSION
9
+ spec.authors = ["alekseyl"]
10
+ spec.email = ["leshchuk@gmail.com"]
11
+
12
+ spec.summary = %q{This is simple and nice sql prettifier, it splits, indent and colorize SQL query and PG errors if any }
13
+ spec.description = %q{This is simple and nice sql prettifier, it splits, indent and colorize SQL query and PG error if any }
14
+ spec.homepage = "https://github.com/alekseyl/niceql"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
27
+ f.match(%r{^(test|spec|features)/})
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_development_dependency "bundler", "~> 1.15"
34
+ spec.add_development_dependency "rake", "~> 10.0"
35
+ spec.add_development_dependency "minitest", "~> 5.0"
36
+
37
+ end
data/to_niceql.png ADDED
Binary file
metadata ADDED
@@ -0,0 +1,103 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: niceql
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - alekseyl
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-09-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.15'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.15'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description: 'This is simple and nice sql prettifier, it splits, indent and colorize
56
+ SQL query and PG error if any '
57
+ email:
58
+ - leshchuk@gmail.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - ".travis.yml"
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - bin/console
70
+ - bin/setup
71
+ - err_now.png
72
+ - err_was.png
73
+ - lib/niceql.rb
74
+ - lib/niceql/version.rb
75
+ - niceql.gemspec
76
+ - to_niceql.png
77
+ homepage: https://github.com/alekseyl/niceql
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ allowed_push_host: https://rubygems.org
82
+ post_install_message:
83
+ rdoc_options: []
84
+ require_paths:
85
+ - lib
86
+ required_ruby_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirements: []
97
+ rubyforge_project:
98
+ rubygems_version: 2.6.11
99
+ signing_key:
100
+ specification_version: 4
101
+ summary: This is simple and nice sql prettifier, it splits, indent and colorize SQL
102
+ query and PG errors if any
103
+ test_files: []