sql_to_csv_stream 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 69a16996a6f5e332d51e2cf6d352f323a7fe01939d3ff238eec27c1d640958d5
4
+ data.tar.gz: 8ddc1c3aca1f1d0a70a41af04436c50d4892be178b1991978b8e95bd03d50da6
5
+ SHA512:
6
+ metadata.gz: 18295c63a869342ab2f1833b968c1374228375fbe7544187c41a68d750de497f67b8659ed44539968f3943df8ff9c7781835ad1475ce142b8d4513651e8ed4e8
7
+ data.tar.gz: f47042d236d18caa9965d33e7302befd14f14d0c5abb6be343d38ed486e89386890c32955e8836b08575fcb02860f1cbb761a1378ef7a61922140b60be992b8d
@@ -0,0 +1,78 @@
1
+ version: 2
2
+ references:
3
+ base: &base
4
+ docker:
5
+ - image: circleci/ruby:2.6.3
6
+ environment:
7
+ RAILS_ENV: test
8
+ PGHOST: 127.0.0.1
9
+ PGUSER: bitcrowd
10
+ DATABASE_URL: "postgres://bitcrowd@localhost:5432/bitcrowd_test"
11
+ COVERAGE: 'true'
12
+ BUNDLE_PATH: '~/bitcrowd/vendor/bundle'
13
+ DISPLAY: 99.0
14
+ CAPYBARA_WAIT_TIME: 40
15
+ - image: circleci/postgres:9.6.12-alpine
16
+ environment:
17
+ POSTGRES_USER: bitcrowd
18
+ POSTGRES_DB: bitcrowd_test
19
+ working_directory: ~/bitcrowd
20
+ jobs:
21
+ setup:
22
+ <<: *base
23
+ steps:
24
+ - checkout
25
+
26
+ # ruby dependencies
27
+ - restore_cache:
28
+ keys:
29
+ - bundler-cache-v1-{{ checksum "Gemfile.lock" }}
30
+ - bundler-cache-v1-
31
+ - run: gem install bundler
32
+ - run:
33
+ name: Install ruby dependencies
34
+ command: |
35
+ bundle check || bundle install --jobs 4 --retry 3
36
+ bundle clean
37
+ - save_cache:
38
+ key: bundler-cache-v1-{{ checksum "Gemfile.lock" }}
39
+ paths:
40
+ - vendor/bundle
41
+
42
+ - save_cache:
43
+ key: repo-{{ .Environment.CIRCLE_SHA1 }}
44
+ paths:
45
+ - ~/bitcrowd
46
+ test:
47
+ <<: *base
48
+ steps:
49
+ - restore_cache:
50
+ key: repo-{{ .Environment.CIRCLE_SHA1 }}
51
+ - run:
52
+ name: Install postgresql-client
53
+ command: |
54
+ sudo apt-get update
55
+ sudo apt install -y postgresql-client
56
+ - run:
57
+ name: rubocop
58
+ command: |
59
+ bundle exec rubocop
60
+ - run:
61
+ name: Wait for DB
62
+ command: dockerize -wait tcp://localhost:5432 -timeout 1m
63
+ - run:
64
+ name: Database Setup
65
+ command: |
66
+ bundle exec rails db:create db:schema:load
67
+ - run:
68
+ name: rspec
69
+ command: |
70
+ bundle exec rspec
71
+ workflows:
72
+ version: 2
73
+ checks:
74
+ jobs:
75
+ - setup
76
+ - test:
77
+ requires:
78
+ - setup
@@ -0,0 +1,16 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ # dummy app we only use for testing against rails
14
+ /spec/integration/dummy_app/db
15
+ /spec/integration/dummy_app/tmp
16
+ /spec/integration/dummy_app/log
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
@@ -0,0 +1,18 @@
1
+ require: rubocop-rails
2
+
3
+ inherit_gem:
4
+ rubocop-bitcrowd: .rubocop.yml
5
+
6
+ # Note: skip this if you want to override the default AllCops:Include and AllCops:Exclude list
7
+ inherit_mode:
8
+ merge:
9
+ - Include
10
+ - Exclude
11
+
12
+ AllCops:
13
+ Exclude:
14
+ - 'spec/integration/dummy_app/bin/*'
15
+ - 'sql_to_csv_stream.gemspec'
16
+
17
+ Metrics/MethodLength:
18
+ Max: 15
@@ -0,0 +1 @@
1
+ ruby 2.6.1
@@ -0,0 +1,21 @@
1
+ # SqlToCsvStream Changelog
2
+
3
+ ## 0.4.0 / unreleased
4
+
5
+ ### Features
6
+
7
+ *
8
+
9
+
10
+ ### Bug fixes
11
+
12
+ *
13
+
14
+
15
+ ## 0.2.0 / 2019-08-21
16
+
17
+ ### Security
18
+
19
+ * upgrade nokogiri (addressed CVE-2019-5477)
20
+ * upgrade all dependent gems
21
+ * move to CircleCI
@@ -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 philipp@tessenow.org. 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,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in sql_to_csv_stream.gemspec
8
+ gemspec
@@ -0,0 +1,194 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ sql_to_csv_stream (0.2.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ actioncable (5.2.3)
10
+ actionpack (= 5.2.3)
11
+ nio4r (~> 2.0)
12
+ websocket-driver (>= 0.6.1)
13
+ actionmailer (5.2.3)
14
+ actionpack (= 5.2.3)
15
+ actionview (= 5.2.3)
16
+ activejob (= 5.2.3)
17
+ mail (~> 2.5, >= 2.5.4)
18
+ rails-dom-testing (~> 2.0)
19
+ actionpack (5.2.3)
20
+ actionview (= 5.2.3)
21
+ activesupport (= 5.2.3)
22
+ rack (~> 2.0)
23
+ rack-test (>= 0.6.3)
24
+ rails-dom-testing (~> 2.0)
25
+ rails-html-sanitizer (~> 1.0, >= 1.0.2)
26
+ actionview (5.2.3)
27
+ activesupport (= 5.2.3)
28
+ builder (~> 3.1)
29
+ erubi (~> 1.4)
30
+ rails-dom-testing (~> 2.0)
31
+ rails-html-sanitizer (~> 1.0, >= 1.0.3)
32
+ activejob (5.2.3)
33
+ activesupport (= 5.2.3)
34
+ globalid (>= 0.3.6)
35
+ activemodel (5.2.3)
36
+ activesupport (= 5.2.3)
37
+ activerecord (5.2.3)
38
+ activemodel (= 5.2.3)
39
+ activesupport (= 5.2.3)
40
+ arel (>= 9.0)
41
+ activestorage (5.2.3)
42
+ actionpack (= 5.2.3)
43
+ activerecord (= 5.2.3)
44
+ marcel (~> 0.3.1)
45
+ activesupport (5.2.3)
46
+ concurrent-ruby (~> 1.0, >= 1.0.2)
47
+ i18n (>= 0.7, < 2)
48
+ minitest (~> 5.1)
49
+ tzinfo (~> 1.1)
50
+ addressable (2.6.0)
51
+ public_suffix (>= 2.0.2, < 4.0)
52
+ arel (9.0.0)
53
+ ast (2.4.0)
54
+ builder (3.2.3)
55
+ capybara (3.28.0)
56
+ addressable
57
+ mini_mime (>= 0.1.3)
58
+ nokogiri (~> 1.8)
59
+ rack (>= 1.6.0)
60
+ rack-test (>= 0.6.3)
61
+ regexp_parser (~> 1.5)
62
+ xpath (~> 3.2)
63
+ coderay (1.1.2)
64
+ concurrent-ruby (1.1.5)
65
+ crass (1.0.4)
66
+ diff-lcs (1.3)
67
+ erubi (1.8.0)
68
+ fivemat (1.3.7)
69
+ globalid (0.4.2)
70
+ activesupport (>= 4.2.0)
71
+ i18n (1.6.0)
72
+ concurrent-ruby (~> 1.0)
73
+ jaro_winkler (1.5.3)
74
+ loofah (2.2.3)
75
+ crass (~> 1.0.2)
76
+ nokogiri (>= 1.5.9)
77
+ mail (2.7.1)
78
+ mini_mime (>= 0.1.1)
79
+ marcel (0.3.3)
80
+ mimemagic (~> 0.3.2)
81
+ method_source (0.9.2)
82
+ mimemagic (0.3.3)
83
+ mini_mime (1.0.2)
84
+ mini_portile2 (2.4.0)
85
+ minitest (5.11.3)
86
+ nio4r (2.4.0)
87
+ nokogiri (1.10.4)
88
+ mini_portile2 (~> 2.4.0)
89
+ parallel (1.17.0)
90
+ parser (2.6.3.0)
91
+ ast (~> 2.4.0)
92
+ pg (1.1.4)
93
+ pry (0.12.2)
94
+ coderay (~> 1.1.0)
95
+ method_source (~> 0.9.0)
96
+ pry-rails (0.3.9)
97
+ pry (>= 0.10.4)
98
+ public_suffix (3.1.1)
99
+ puma (3.12.1)
100
+ rack (2.0.7)
101
+ rack-test (1.1.0)
102
+ rack (>= 1.0, < 3)
103
+ rails (5.2.3)
104
+ actioncable (= 5.2.3)
105
+ actionmailer (= 5.2.3)
106
+ actionpack (= 5.2.3)
107
+ actionview (= 5.2.3)
108
+ activejob (= 5.2.3)
109
+ activemodel (= 5.2.3)
110
+ activerecord (= 5.2.3)
111
+ activestorage (= 5.2.3)
112
+ activesupport (= 5.2.3)
113
+ bundler (>= 1.3.0)
114
+ railties (= 5.2.3)
115
+ sprockets-rails (>= 2.0.0)
116
+ rails-dom-testing (2.0.3)
117
+ activesupport (>= 4.2.0)
118
+ nokogiri (>= 1.6)
119
+ rails-html-sanitizer (1.2.0)
120
+ loofah (~> 2.2, >= 2.2.2)
121
+ railties (5.2.3)
122
+ actionpack (= 5.2.3)
123
+ activesupport (= 5.2.3)
124
+ method_source
125
+ rake (>= 0.8.7)
126
+ thor (>= 0.19.0, < 2.0)
127
+ rainbow (3.0.0)
128
+ rake (10.5.0)
129
+ regexp_parser (1.6.0)
130
+ rspec (3.8.0)
131
+ rspec-core (~> 3.8.0)
132
+ rspec-expectations (~> 3.8.0)
133
+ rspec-mocks (~> 3.8.0)
134
+ rspec-core (3.8.2)
135
+ rspec-support (~> 3.8.0)
136
+ rspec-expectations (3.8.4)
137
+ diff-lcs (>= 1.2.0, < 2.0)
138
+ rspec-support (~> 3.8.0)
139
+ rspec-mocks (3.8.1)
140
+ diff-lcs (>= 1.2.0, < 2.0)
141
+ rspec-support (~> 3.8.0)
142
+ rspec-support (3.8.2)
143
+ rubocop (0.74.0)
144
+ jaro_winkler (~> 1.5.1)
145
+ parallel (~> 1.10)
146
+ parser (>= 2.6)
147
+ rainbow (>= 2.2.2, < 4.0)
148
+ ruby-progressbar (~> 1.7)
149
+ unicode-display_width (>= 1.4.0, < 1.7)
150
+ rubocop-bitcrowd (1.3.0)
151
+ rubocop (~> 0.56)
152
+ rubocop-rails (2.3.0)
153
+ rack (>= 1.1)
154
+ rubocop (>= 0.72.0)
155
+ ruby-progressbar (1.10.1)
156
+ sprockets (3.7.2)
157
+ concurrent-ruby (~> 1.0)
158
+ rack (> 1, < 3)
159
+ sprockets-rails (3.2.1)
160
+ actionpack (>= 4.0)
161
+ activesupport (>= 4.0)
162
+ sprockets (>= 3.0.0)
163
+ thor (0.20.3)
164
+ thread_safe (0.3.6)
165
+ tzinfo (1.2.5)
166
+ thread_safe (~> 0.1)
167
+ unicode-display_width (1.6.0)
168
+ websocket-driver (0.7.1)
169
+ websocket-extensions (>= 0.1.0)
170
+ websocket-extensions (0.1.4)
171
+ xpath (3.2.0)
172
+ nokogiri (~> 1.8)
173
+
174
+ PLATFORMS
175
+ ruby
176
+
177
+ DEPENDENCIES
178
+ bundler (~> 1.17)
179
+ capybara
180
+ fivemat
181
+ pg
182
+ pry
183
+ pry-rails
184
+ puma (~> 3.11)
185
+ rails (~> 5.2.2)
186
+ rake (~> 10.0)
187
+ rspec (~> 3.0)
188
+ rubocop
189
+ rubocop-bitcrowd
190
+ rubocop-rails
191
+ sql_to_csv_stream!
192
+
193
+ BUNDLED WITH
194
+ 1.17.3
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Philipp Tessenow
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.
@@ -0,0 +1,120 @@
1
+ # SqlToCsvStream
2
+
3
+ This is your favorite gem to produce CSV or JSON directly from SQL queries.
4
+ It queries a PostgreSQL with a [`COPY`](https://www.postgresql.org/docs/current/sql-copy.html) statement and streams the result as CSV/JSON directly into a ruby enumerator.
5
+
6
+ This gem can be used in all ruby applications, but ships with a special renderer for Rails to easily render downloads from your rails controller.
7
+
8
+ Note: This is project is still in a proof-of-concept phase. We may rename some things, make the code more readable and very likely add some tests :)
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'sql_to_csv_stream'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install sql_to_csv_stream
25
+
26
+ If you use rails, you may register the new stream renderers in an initializer.
27
+
28
+ ```ruby
29
+ require 'sql_to_csv_stream'
30
+
31
+ SqlToCsvStream.register_rails_renderer
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ In Rails, you can use the stream renderer from a Controller:
37
+
38
+ ```ruby
39
+ class UsersController < ApplicationController
40
+ def index
41
+ @users = User.all.where(deleted_at: null)
42
+
43
+ respond_to do |format|
44
+ format.csv do
45
+ render csv_stream: @users, filename: 'users.csv'
46
+ end
47
+ format.json do
48
+ render json_stream: @users, filename: 'users.json'
49
+ end
50
+ end
51
+ end
52
+ end
53
+ ```
54
+
55
+ This, unlike many other CSV/JSON rendering techniques, instantly sends results to the user by streaming the content while it is being generated.
56
+ This is light on memory. By streaming the data instantly, even large files (that need longer to generate than the HTTP server connection timeout value) can be produced without the connection being interrupted by a connection timeout.
57
+
58
+ The streaming renderer automatically responds with a gzipped encoding if the client accepts it. This drastically reduces file sizes we need to send over the wire.
59
+
60
+ Any SQL string the PostgreSQL [`COPY` command](https://www.postgresql.org/docs/current/sql-copy.html) accepts can be given to the renderer.
61
+ Alternatively, any object may be given that produces such SQL on `.to_sql` or `to_s`.
62
+ So you can use your favorite query-object pattern :)
63
+
64
+ If you are not in Rails or want to process CSV/JSON in any other way from within Rails, you can use the `*Enumerator` classes.
65
+
66
+ ```ruby
67
+ file = File.open('users.csv', 'w')
68
+ SqlToCsvStream::CsvEnumerator.new('SELECT * FROM users;').each do |csv_row|
69
+ file.write
70
+ end
71
+ file.close
72
+ ```
73
+
74
+ Or write the compressed file with:
75
+
76
+ ```ruby
77
+ csv_enum = SqlToCsvStream::CsvEnumerator.new('SELECT * FROM users;')
78
+ zip_enum = SqlToCsvStream::GzipWrapper.new(csv_enum)
79
+
80
+ file = File.open('users.csv.gz', 'w')
81
+ zip_enum.each do |csv_row|
82
+ file.write
83
+ end
84
+ file.close
85
+ ```
86
+
87
+ Writing a JSON file works similarly:
88
+
89
+ ```ruby
90
+ file = File.open('users.json', 'w')
91
+ SqlToCsvStream::JsonEnumerator.new('SELECT * FROM users;').each do |csv_row|
92
+ file.write
93
+ end
94
+ file.close
95
+ ```
96
+
97
+ For more options, see the class documentation of the `CsvEnumerator` or `JsonEnumerator` class.
98
+
99
+ ## Development
100
+
101
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
102
+
103
+ 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).
104
+
105
+ ## Contributing
106
+
107
+ Bug reports and pull requests are welcome on GitHub at https://github.com/tessi/sql_to_csv_stream. New feature ideas are welcome too -- please present your ideas in an issue first so we can together discuss whether this idea fits into the scope of this project.
108
+ 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.
109
+
110
+ ## License
111
+
112
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
113
+
114
+ ## Code of Conduct
115
+
116
+ Everyone interacting in the SqlToCsvStream project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/tessi/sql_to_csv_stream/blob/master/CODE_OF_CONDUCT.md).
117
+
118
+ ## Previous work
119
+
120
+ We didn't invent streaming, nor did we were the first to have the idea to integrate this in ruby and/or rails. Some previous approaches are described [here](https://shift.infinite.red/fast-csv-report-generation-with-postgres-in-rails-d444d9b915ab), [here](https://www.smartly.io/blog/streaming-data-with-ruby-enumerators), [here](https://medium.com/table-xi/stream-csv-files-in-rails-because-you-can-46c212159ab7), or [here](https://gist.github.com/stereoscott/6996507). We are thankful for the previous work done which led us into the right direction and enabled us to (hopefully) improve upon it.
@@ -0,0 +1,8 @@
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
+ task default: :spec
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'sql_to_csv_stream'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
@@ -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
+ # frozen_string_literal: true
2
+
3
+ require 'sql_to_csv_stream/version'
4
+ require 'sql_to_csv_stream/gzip_wrapper'
5
+ require 'sql_to_csv_stream/postgresql_copy_enumerator'
6
+ require 'sql_to_csv_stream/csv_enumerator'
7
+ require 'sql_to_csv_stream/json_enumerator'
8
+ require 'sql_to_csv_stream/rails_support'
9
+
10
+ module SqlToCsvStream
11
+ def self.register_rails_renderer
12
+ RailsSupport.register_renderer
13
+ end
14
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'csv'
4
+
5
+ module SqlToCsvStream
6
+ class CsvEnumerator
7
+ PREFIXES_TO_ESCAPE = %w[= @ + - |].freeze
8
+ ESCAPE_CHAR = "'"
9
+
10
+ # Other possible options are
11
+ # force_quote: '*'
12
+ # escape: "E'\\\\'"
13
+ # For details see Postgresqls COPY documentation.
14
+ COPY_OPTIONS_DEFAULTS = {
15
+ format: 'CSV',
16
+ header: true
17
+ }.freeze
18
+
19
+ def initialize(
20
+ object,
21
+ connection: PostgresqlCopyEnumerator.default_connection,
22
+ copy_options: {},
23
+ sanitize: true,
24
+ force_quotes: false
25
+ )
26
+ @sanitize = sanitize
27
+ @force_quotes = force_quotes
28
+
29
+ sql = (object.respond_to?(:to_sql) ? object.to_sql : object.to_s).chomp(';')
30
+ copy_options = COPY_OPTIONS_DEFAULTS.merge(copy_options)
31
+ copy_options[:force_quote] = '*' if @force_quotes
32
+ @copy_enum = PostgresqlCopyEnumerator.new(sql, connection: connection, copy_options: copy_options)
33
+ end
34
+
35
+ def each
36
+ @copy_enum.each do |line|
37
+ yield(sanitize(line)) if block_given?
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def sanitize(line)
44
+ return line unless @sanitize
45
+
46
+ row = CSV.parse_line(line, headers: false)
47
+ .map do |value|
48
+ if value.to_s.start_with?(*PREFIXES_TO_ESCAPE)
49
+ ESCAPE_CHAR + value
50
+ else
51
+ value
52
+ end
53
+ end
54
+
55
+ CSV.generate_line(row, headers: false, force_quotes: @force_quotes)
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'zlib'
4
+
5
+ module SqlToCsvStream
6
+ class GzipWrapper
7
+ def initialize(source)
8
+ @source = source
9
+ end
10
+
11
+ def each(&block)
12
+ @destination = block
13
+ # Zlib::GzipWriter needs to get passed an object that implements the #write method.
14
+ # this is why we implement the #write method further down
15
+ # while assigning the stream we need to write to in an instance variable to be used there.
16
+ @zipper = Zlib::GzipWriter.new(self)
17
+ @source.each do |string|
18
+ @zipper.write(string)
19
+ end
20
+ ensure
21
+ @zipper.close
22
+ end
23
+
24
+ # called indirectly by Zlib::GzipWriter
25
+ def write(zipped_string)
26
+ @destination.yield(zipped_string)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SqlToCsvStream
4
+ class JsonEnumerator
5
+ JSON_COPY_OPTIONS = { format: 'TEXT' }.freeze
6
+
7
+ def initialize(object, connection: PostgresqlCopyEnumerator.default_connection)
8
+ sql = (object.respond_to?(:to_sql) ? object.to_sql : object.to_s).chomp(';')
9
+ # The inspiration of this magic was:
10
+ # https://dba.stackexchange.com/questions/90482/export-postgres-table-as-json?newreg=0b667caa47c34084bee6c90feec5e4be
11
+ #
12
+ # The idea is to stream with postgresql COPY command with the TEXT format.
13
+ # To do this, we need to convert each row in the postgresql query result into JSON first.
14
+ # This query does exactly that by using ROW_TO_JSON.
15
+ # There is one edge case when text in that JSON contains backslashes -- to not break our
16
+ # escaping, we need to manually add additional escape-backslashes.
17
+ sql = "SELECT REGEXP_REPLACE(ROW_TO_JSON(t)::TEXT, '\\\\', '\\', 'g') FROM (#{sql}) AS t"
18
+ @copy_enum = PostgresqlCopyEnumerator.new(sql, connection: connection, copy_options: JSON_COPY_OPTIONS)
19
+ end
20
+
21
+ def each(&stream)
22
+ stream.yield('[')
23
+
24
+ # do not prepend a comma on the very first item
25
+ # to not break json syntax
26
+ prepend_comma = false
27
+ @copy_enum.each do |line|
28
+ line = ',' + line if prepend_comma
29
+ prepend_comma = true
30
+ stream.yield(line.chomp)
31
+ end
32
+
33
+ stream.yield("]\n")
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SqlToCsvStream
4
+ class PostgresqlCopyEnumerator
5
+ COPY_OPTIONS_DEFAULTS = {
6
+ encoding: 'utf8'
7
+ }.freeze
8
+
9
+ def self.default_connection
10
+ raise 'PostgreSQL database connection required' unless defined?(ActiveRecord)
11
+
12
+ ActiveRecord::Base.connection.raw_connection
13
+ end
14
+
15
+ def initialize(sql, connection: self.class.default_connection, copy_options: {})
16
+ @sql = sql.chomp(';')
17
+ @connection = connection
18
+ @copy_options = COPY_OPTIONS_DEFAULTS.merge(copy_options)
19
+ end
20
+
21
+ def each
22
+ @connection.copy_data(copy_sql) do
23
+ while (row = @connection.get_copy_data)
24
+ yield(row) if block_given?
25
+ end
26
+ end
27
+ end
28
+
29
+ private
30
+
31
+ def copy_sql
32
+ "COPY (#{@sql}) TO STDOUT WITH (#{joined_copy_options})"
33
+ end
34
+
35
+ def joined_copy_options
36
+ @copy_options.map { |k, v| "#{k.upcase} #{v}" }
37
+ .join(', ')
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SqlToCsvStream
4
+ module RailsSupport
5
+ def self.register_renderer
6
+ register_csv_renderer
7
+ register_json_renderer
8
+ end
9
+
10
+ # `stream` can be anything that responds to `.each`.
11
+ # We make use of this by providing our own stream that fetches data from Postgresql
12
+ # stream = (1..10).lazy.map do |i|
13
+ # sleep(1);
14
+ # "#{i}\n";
15
+ # end
16
+ # stream = Enumerator.new do |strean|
17
+ # csv_service.call do |csv_line|
18
+ # strean << csv_line
19
+ # end
20
+ # end
21
+ def self.register_csv_renderer
22
+ ActionController::Renderers.add :csv_stream do |sql, copy_options: {}, **options|
23
+ sanitize = options.delete(:sanitize) || true
24
+ force_quotes = options.delete(:force_quotes) || false
25
+ filename = options.delete(:filename) || 'data.csv'
26
+ stream = CsvEnumerator.new(sql, copy_options: copy_options, sanitize: sanitize, force_quotes: force_quotes)
27
+ stream = GzipWrapper.new(stream) if RailsSupport.use_gzip?(request)
28
+ RailsSupport.set_streaming_headers(headers, request, response, filename)
29
+ stream
30
+ end
31
+ end
32
+
33
+ def self.register_json_renderer
34
+ ActionController::Renderers.add :json_stream do |sql, filename: 'data.csv'|
35
+ stream = JsonEnumerator.new(sql)
36
+ stream = GzipWrapper.new(stream) if RailsSupport.use_gzip?(request)
37
+ RailsSupport.set_streaming_headers(headers, request, response, filename)
38
+ stream
39
+ end
40
+ end
41
+
42
+ def self.set_streaming_headers(headers, request, response, filename)
43
+ headers['X-Accel-Buffering'] = 'no'
44
+ headers['Cache-Control'] = 'no-cache'
45
+ headers['Content-Encoding'] = 'gzip' if use_gzip?(request)
46
+ headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
47
+ headers.delete('Content-Length')
48
+ response.status = 200
49
+ end
50
+
51
+ def self.use_gzip?(request)
52
+ request.headers['HTTP_ACCEPT_ENCODING']
53
+ .to_s
54
+ .include?('gzip')
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SqlToCsvStream
4
+ VERSION = '0.2.0'
5
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'sql_to_csv_stream/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'sql_to_csv_stream'
9
+ spec.version = SqlToCsvStream::VERSION
10
+ spec.authors = ['Philipp Tessenow']
11
+ spec.email = ['philipp@tessenow.org']
12
+
13
+ spec.summary = 'A shortcut to the COPY command from PostgreSQL. Give it SQL and get an Enumerator for the CSV that comes out of it.'
14
+ spec.description = 'A shortcut to the COPY command from PostgreSQL. Give it SQL and get an Enumerator for the CSV that comes out of it.'
15
+ spec.homepage = 'https://github.com/tessi/sql_to_csv_stream'
16
+ spec.license = 'MIT'
17
+
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/tessi/sql_to_csv_stream'
21
+ spec.metadata['changelog_uri'] = 'https://github.com/tessi/sql_to_csv_stream/master/CHANGELOG.md'
22
+ else
23
+ raise 'RubyGems 2.0 or newer is required to protect against ' \
24
+ 'public gem pushes.'
25
+ end
26
+
27
+ # Specify which files should be added to the gem when it is released.
28
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
29
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
30
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
31
+ end
32
+ spec.bindir = 'exe'
33
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
34
+ spec.require_paths = ['lib']
35
+
36
+ spec.add_development_dependency 'bundler', '~> 1.17'
37
+ spec.add_development_dependency 'pry'
38
+ spec.add_development_dependency 'rake', '~> 10.0'
39
+ spec.add_development_dependency 'rspec', '~> 3.0'
40
+ spec.add_development_dependency 'fivemat'
41
+
42
+ # for the rails dummy app
43
+ spec.add_development_dependency 'capybara'
44
+ spec.add_development_dependency 'pg'
45
+ spec.add_development_dependency 'pry-rails'
46
+ spec.add_development_dependency 'puma', '~> 3.11'
47
+ spec.add_development_dependency 'rails', '~> 5.2.2'
48
+ spec.add_development_dependency 'rubocop'
49
+ spec.add_development_dependency 'rubocop-bitcrowd'
50
+ spec.add_development_dependency 'rubocop-rails'
51
+ end
metadata ADDED
@@ -0,0 +1,252 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sql_to_csv_stream
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Philipp Tessenow
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-08-21 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.17'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: fivemat
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: capybara
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: pg
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: pry-rails
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: puma
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '3.11'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '3.11'
139
+ - !ruby/object:Gem::Dependency
140
+ name: rails
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - "~>"
144
+ - !ruby/object:Gem::Version
145
+ version: 5.2.2
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - "~>"
151
+ - !ruby/object:Gem::Version
152
+ version: 5.2.2
153
+ - !ruby/object:Gem::Dependency
154
+ name: rubocop
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ">="
158
+ - !ruby/object:Gem::Version
159
+ version: '0'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ - !ruby/object:Gem::Dependency
168
+ name: rubocop-bitcrowd
169
+ requirement: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: '0'
174
+ type: :development
175
+ prerelease: false
176
+ version_requirements: !ruby/object:Gem::Requirement
177
+ requirements:
178
+ - - ">="
179
+ - !ruby/object:Gem::Version
180
+ version: '0'
181
+ - !ruby/object:Gem::Dependency
182
+ name: rubocop-rails
183
+ requirement: !ruby/object:Gem::Requirement
184
+ requirements:
185
+ - - ">="
186
+ - !ruby/object:Gem::Version
187
+ version: '0'
188
+ type: :development
189
+ prerelease: false
190
+ version_requirements: !ruby/object:Gem::Requirement
191
+ requirements:
192
+ - - ">="
193
+ - !ruby/object:Gem::Version
194
+ version: '0'
195
+ description: A shortcut to the COPY command from PostgreSQL. Give it SQL and get an
196
+ Enumerator for the CSV that comes out of it.
197
+ email:
198
+ - philipp@tessenow.org
199
+ executables: []
200
+ extensions: []
201
+ extra_rdoc_files: []
202
+ files:
203
+ - ".circleci/config.yml"
204
+ - ".gitignore"
205
+ - ".rspec"
206
+ - ".rubocop.yml"
207
+ - ".tool-versions"
208
+ - CHANGELOG.md
209
+ - CODE_OF_CONDUCT.md
210
+ - Gemfile
211
+ - Gemfile.lock
212
+ - LICENSE.txt
213
+ - README.md
214
+ - Rakefile
215
+ - bin/console
216
+ - bin/setup
217
+ - lib/sql_to_csv_stream.rb
218
+ - lib/sql_to_csv_stream/csv_enumerator.rb
219
+ - lib/sql_to_csv_stream/gzip_wrapper.rb
220
+ - lib/sql_to_csv_stream/json_enumerator.rb
221
+ - lib/sql_to_csv_stream/postgresql_copy_enumerator.rb
222
+ - lib/sql_to_csv_stream/rails_support.rb
223
+ - lib/sql_to_csv_stream/version.rb
224
+ - sql_to_csv_stream.gemspec
225
+ homepage: https://github.com/tessi/sql_to_csv_stream
226
+ licenses:
227
+ - MIT
228
+ metadata:
229
+ homepage_uri: https://github.com/tessi/sql_to_csv_stream
230
+ source_code_uri: https://github.com/tessi/sql_to_csv_stream
231
+ changelog_uri: https://github.com/tessi/sql_to_csv_stream/master/CHANGELOG.md
232
+ post_install_message:
233
+ rdoc_options: []
234
+ require_paths:
235
+ - lib
236
+ required_ruby_version: !ruby/object:Gem::Requirement
237
+ requirements:
238
+ - - ">="
239
+ - !ruby/object:Gem::Version
240
+ version: '0'
241
+ required_rubygems_version: !ruby/object:Gem::Requirement
242
+ requirements:
243
+ - - ">="
244
+ - !ruby/object:Gem::Version
245
+ version: '0'
246
+ requirements: []
247
+ rubygems_version: 3.0.2
248
+ signing_key:
249
+ specification_version: 4
250
+ summary: A shortcut to the COPY command from PostgreSQL. Give it SQL and get an Enumerator
251
+ for the CSV that comes out of it.
252
+ test_files: []