2012-04-27 11 views
13

C'è un modo semplice per pretty print SQL casuale nella console (rails 3)?Pretty Print SQL in Ruby

Qualcosa di simile a awesome_print, o forse anche a Pretty Print.

Non deve comprendere tutti i dialetti possibili o essere super-avanzato.
Tutto ciò che voglio veramente è ispezionare l'SQL generato da ActiveRecord più semplice.

Attualmente ho appena copiare l'SQL andare online per formattarlo che è ovviamente un killer di produttività.

Voglio davvero a query.to_sql.pretty_format_sql e vedere l'output più bello.

Grazie.

+0

Se stai usando JRuby si potrebbe prendere in considerazione alcune risposte per una [domanda simile] (http://stackoverflow.com/q/312552/215168) posato per Java, come ad esempio 'org.hibernate di Hibernate. jdbc.util.BasicFormatterImpl' –

+0

Hah, utilizzando la risonanza magnetica. –

risposta

9

Prova questo:

git clone https://github.com/sonota/anbt-sql-formatter 
cd anbt-sql-formatter 
rails setup.rb 

Poi, in un inizializzatore Rails:

# config/initializers/pretty_format_sql.rb 
class String 
    def pretty_format_sql 
    require "anbt-sql-formatter/formatter" 
    rule = AnbtSql::Rule.new 
    rule.keyword = AnbtSql::Rule::KEYWORD_UPPER_CASE 
    %w(count sum substr date).each{|func_name| 
     rule.function_names << func_name.upcase 
    } 
    rule.indent_string = " " 
    formatter = AnbtSql::Formatter.new(rule) 
    formatter.format(self) 
    end 
end 

prova:

rails console 
# Some complex SQL 
puts Recipe.joins(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at', Time.utc(0,Time.now.month,Time.now.day,12,0,0)]).to_sql.pretty_format_sql 
SELECT 
     "recipes" . * 
    FROM 
     "recipes" INNER JOIN "festivities" 
      ON "festivities" . "id" = "recipes" . "festivity_id" 
    WHERE 
     (
      '0000-04-27 12:00:00.000000' BETWEEN festivities.starts_at AND festivities.ends_at 
     ) 
=> nil 

lascio raffinazione a voi (refactoring: scimmia-patching -> modulo, formattazione personalizzata, ecc .:-))

+2

Dovrebbe fare il lavoro, ma voglio davvero evitare l'uso di plugin rails deprecati (non gemme). –

+0

Anch'io ho sentito che non è un lib di tipo "standard" ... ma non dovrebbe essere difficile estrarre le parti buone e farne una gemma (l'ho testata e funziona abbastanza bene, e visto che non potevo trovare alternative, perché riscrivere le cose che funzionano?) ... ci proverò! – mdesantis

7

La anbt-sql-formatter del first answer è available as a gem, è possibile installarlo con:

gem install anbt-sql-formatter 

Ecco un esempio di utilizzo:

require "anbt-sql-formatter/formatter" 
rule = AnbtSql::Rule.new 
    formatter = AnbtSql::Formatter.new(rule) 

[ 
"SELECT `col1`, `col2` FROM `table` WHERE ((`col1` = 1) AND (`col2` = 5))", 
"SELECT `col1`, `col2` FROM `table` WHERE (`col1` = 1) AND (`col2` = 5)", 
"SELECT `col1` FROM `table` WHERE (`col1` IN (SELECT * FROM `table21` WHERE (`col2` = 5)))", 
"SELECT `col1` FROM `table` INNER JOIN `tab2` ON (`tab1`.`id` = `tab2`.`id1`) WHERE ((`id` >= 1) AND (`id` <= 5))", 
].each{|sql_cmd| 
    puts "======" 
    puts sql_cmd 
    puts formatter.format(sql_cmd) 
} 

Il risultato:

====== 
SELECT `col1`, `col2` FROM `table` WHERE ((`col1` = 1) AND (`col2` = 5)) 
SELECT 
     `col1` 
     ,`col2` 
    FROM 
     `table` 
    WHERE 
     (
      (
       `col1` = 1 
      ) 
      AND (
       `col2` = 5 
      ) 
     ) 
====== 
SELECT `col1`, `col2` FROM `table` WHERE (`col1` = 1) AND (`col2` = 5) 
SELECT 
     `col1` 
     ,`col2` 
    FROM 
     `table` 
    WHERE 
     (
      `col1` = 1 
     ) 
     AND (
      `col2` = 5 
     ) 
====== 
SELECT `col1` FROM `table` WHERE (`col1` IN (SELECT * FROM `table21` WHERE (`col2` = 5))) 
SELECT 
     `col1` 
    FROM 
     `table` 
    WHERE 
     (
      `col1` IN (
       SELECT 
         * 
        FROM 
         `table21` 
        WHERE 
         (
          `col2` = 5 
         ) 
      ) 
     ) 
====== 
SELECT `col1` FROM `table` INNER JOIN `tab2` ON (`tab1`.`id` = `tab2`.`id1`) WHERE ((`id` >= 1) AND (`id` <= 5)) 
SELECT 
     `col1` 
    FROM 
     `table` INNER JOIN `tab2` 
      ON (
      `tab1`.`id` = `tab2`.`id1` 
     ) 
    WHERE 
     (
      (
       `id` >= 1 
      ) 
      AND (
       `id` <= 5 
      ) 
     ) 

V'è anche la possibilità di estendere le regole, ad es

# User defined additional functions: 
%w(count sum substr date coalesce).each{|func_name| 
    rule.function_names << func_name.upcase 
}