Last Updated: February 25, 2016
·
3.046K
· mountaincode

SQL Queries with Sublime Text and Ruby

Create a global Rakefile to execute SQL queries.

~/.rake/Rakefile

require 'json'
require 'mysql2'

desc "Run a SQL query on MySQL"
namespace :mysql do
  task :query do
    # Shift the rake task name into oblivion
    ARGV.shift
    # Now grab input from ARGF (file, piped input stdin or whatever)
    str = ARGF.read
    lines = str.split("\n")
    client = Mysql2::Client.new JSON.parse(lines[0].gsub(/^--\s*?/, ''))
    results = client.query str
    results.each do |row|
      p row
    end
  end
  task :q => :query
end

This can be executed with rake -g mysql:query. Enter a file to read from
as an argument rake -g mysql:query myquery.sql or pipe in the input.

$ echo 'select * from users limit 50' | rake -g mysql:q

Create a Sublime Text build system for .sql files.

~/.config/sublime-text-2/Packages/User/SQL.sublime-build

or ~/Library/Application Support/Sublime Text 2/Packages/User/SQL.sublime-build

{
  "cmd": ["ruby", "-S", "rake", "-g", "mysql:query", "$file"],
  "selector": "source.sql"
}

SQL files in Sublime Text can now be executed by running an automatic build.
Add a header comment with the connection properties as a JSON string.

-- {"host": "localhost", "database": "test", "username": "test_user", "password": "secret"}

select * from users limit 50