Class: BetterSeeder::Exporters::Sql
- Defined in:
- lib/better_seeder/exporters/sql.rb
Instance Attribute Summary
Attributes inherited from Base
#data, #output_path, #table_name
Instance Method Summary collapse
-
#export ⇒ Object
Esporta i dati in formato SQL, generando una singola istruzione INSERT che inserisce in blocco tutti i record.
- #extension ⇒ Object
Methods inherited from Base
#ensure_output_directory, #full_output_path, #initialize, #output_directory
Constructor Details
This class inherits a constructor from BetterSeeder::Exporters::Base
Instance Method Details
#export ⇒ Object
Esporta i dati in formato SQL, generando una singola istruzione INSERT che inserisce in blocco tutti i record.
Il metodo costruisce una stringa con la sintassi: INSERT INTO table_name (col1, col2, …) VALUES
(val11, val12, ...),
(val21, val22, ...),
... ;
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/better_seeder/exporters/sql.rb', line 14 def export return if data.empty? columns = data.first.keys # Crea l'array delle tuple di valori per ciascun record. values_list = data.map do |row| row_values = columns.map do |col| value = row[col] # Se il valore è nil restituisce NULL, altrimenti esegue l'escaping delle virgolette singole. value.nil? ? 'NULL' : "'#{value.to_s.gsub("'", "''")}'" end "(#{row_values.join(', ')})" end # Costruisce la query INSERT unica insert_statement = "INSERT INTO #{table_name} (#{columns.join(', ')}) VALUES #{values_list.join(', ')};" full_path = File.join(full_output_path) File.open(full_path, 'w') do |file| file.puts(insert_statement) end end |
#extension ⇒ Object
39 40 41 |
# File 'lib/better_seeder/exporters/sql.rb', line 39 def extension '.sql' end |