Skip to content

Commit

Permalink
Merge pull request #7 from timhwang21/tim/support-exec-query
Browse files Browse the repository at this point in the history
Tim/support exec query
  • Loading branch information
sufleR authored Aug 3, 2020
2 parents f8477d0 + 3ca8313 commit 935c30c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ SqlQuery.new('player/get_by_email', email: '[email protected]')
### Methods

- **execute** - executes query and returns result data. It accepts boolean argument. When argument is false it will run raw sql query instead of prepared_for_logs.
- **exec_query** - similar to `#execute` but with data returned via `ActiveRecord::Result`.
- **explain** - runs explain for SQL from template
- **sql** - returns SQL string
- **pretty_sql** - returns SQL string prettier to read in console
Expand Down Expand Up @@ -141,3 +142,10 @@ If you have some examples to share please make pull request.
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

To run specs, setup Postgres with the following:

```sql
CREATE DATABASE sqlquery;
CREATE ROLE sqlquery WITH LOGIN;
```
5 changes: 5 additions & 0 deletions lib/sql_query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ def execute(prepare = true)
connection.execute(to_execute).entries
end

def exec_query(prepare = true)
to_execute = prepare ? prepared_for_logs : sql
connection.exec_query(to_execute).to_a
end

def sql
@sql ||= ERB.new(File.read(file_path)).result(binding)
end
Expand Down
32 changes: 32 additions & 0 deletions spec/sql_query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,38 @@ class Model < ActiveRecord::Base
end
end

describe '#exec_query' do
before do
ActiveRecord::Base.connection.execute(
"INSERT INTO players (email) VALUES ('[email protected]')"
)
end

after do
ActiveRecord::Base.connection.execute(
'DELETE FROM players'
)
end

it 'returns data from database' do
expect(query.exec_query).to eq [{ 'email' => '[email protected]' }]
end

context 'when prepare argument is true' do
it 'executes prepared query for logs' do
expect(query).to receive(:prepared_for_logs) { '' }
query.exec_query
end
end

context 'when prepare argument is false' do
it 'executes unchanged sql query' do
expect(query).not_to receive(:prepared_for_logs)
query.exec_query(false)
end
end
end

describe '#partial' do
let(:file_name) { :get_player_by_email_with_template }
it 'resolves partials as parts of sql queries' do
Expand Down

0 comments on commit 935c30c

Please sign in to comment.