Module: SqlFormatterWebInterface

Defined in:
lib/sql_formatter_web_interface.rb,
lib/sql_formatter_web_interface/to_formatted_sql.rb

Overview

</b>

Defined Under Namespace

Modules: ToFormattedSql

Constant Summary collapse

SQL_FORMATTER_URL =
'http://sqlformat.appspot.com/format/'
DEFAULT_OPTIONS =
{
  'format'          => 'text',
  'remove_comments' => '',
  'highlight'       => '',
  'keyword_case'    => 'upper',
  'identifier_case' => '',
  'n_indents'       => '2',
  'right_margin'    => '',
  'output_format'   => 'sql'
}

Class Method Summary collapse

Class Method Details

.format(sql, options = {}) ⇒ String

It makes a request to an online formatting service which will format a SQL string, according to the setted options (see sqlformat.appspot.com for details about the default SQL formatting service)

Examples:

sql = <<-SQL
         select user_id, count(*) as how_many from bboard where 
         not exists (select 1 from bboard_authorized_maintainers bam 
         where bam.user_id = bboard.user_id) and posting_time ` 60 > sysdate 
         group by user_id order by how_many desc;
         SQL
SqlFormatterWebInterface.format(sql) #=>
# SELECT user_id,
#        count(*) AS how_many
# FROM bboard
# WHERE NOT EXISTS
#     (SELECT 1
#      FROM bboard_authorized_maintainers bam
#      WHERE bam.user_id = bboard.user_id)
#   AND posting_time + 60 > sysdate
# GROUP BY user_id
# ORDER BY how_many DESC;

Parameters:

  • sql (String)

    SQL query to be formatted

  • options (Hash) (defaults to: {})

    The options to pass to the web service (see sqlformat.appspot.com/api/ for informations about the available options); it will be merged with DEFAULT_OPTIONS. The special option ‘:url` can be used in order to specify the URL of the request (if `nil` SQL_FORMATTER_URL will be used)

Returns:

  • (String)

    If ‘sql` is a valid SQL a formatted copy of the string converted to the expected format, else an identical copy of the string

Raises:

  • (SocketError)

    When the service cannot reach the setted URL



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/sql_formatter_web_interface.rb', line 65

def self.format(sql, options = {})
  uri = URI(options[:url].nil? ? SQL_FORMATTER_URL : options.delete(:url))

  stringify_hash!(options)

  options['data'] = sql
  options = DEFAULT_OPTIONS.merge(options)

  Net::HTTP.post_form(uri, options).body

rescue SocketError
  raise SocketError.new "unable to resolve #{uri.to_s}"
end