Class: Anonymize::SQL
- Inherits:
-
Object
- Object
- Anonymize::SQL
- Defined in:
- lib/anonymize/sql.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(connection, options, definition) ⇒ SQL
constructor
A new instance of SQL.
- #process_table(table, data) ⇒ Object
- #replacement(column, row, proc) ⇒ Object
- #run! ⇒ Object
- #update_row(id, table, tuples, retries) ⇒ Object
Constructor Details
#initialize(connection, options, definition) ⇒ SQL
Returns a new instance of SQL.
4 5 6 7 8 |
# File 'lib/anonymize/sql.rb', line 4 def initialize(connection, , definition) @connection = connection @options = @definition = definition end |
Class Method Details
.run!(*args) ⇒ Object
10 11 12 |
# File 'lib/anonymize/sql.rb', line 10 def self.run!(*args) self.new(*args).run! end |
Instance Method Details
#process_table(table, data) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/anonymize/sql.rb', line 23 def process_table(table, data) columns = data[:columns] rows = @connection.query("SELECT * FROM #{table}") = ProgressBar.create(:format => '%a %B %c of %C', :total => rows.count) if @options[:progress] rows.each do |row| tuples = {} columns.each do |column, proc| replacement = replacement(column, row, proc) tuples[column] = replacement if replacement end update_row(row["id"], table, tuples, data[:options][:retries]) .increment if @options[:progress] end end |
#replacement(column, row, proc) ⇒ Object
38 39 40 41 42 43 44 45 |
# File 'lib/anonymize/sql.rb', line 38 def replacement(column, row, proc) original = row[column.to_s] case proc.arity when 1 then proc.call(original) when 2 then proc.call(original, row) else proc.call end end |
#run! ⇒ Object
14 15 16 17 18 19 20 21 |
# File 'lib/anonymize/sql.rb', line 14 def run! total_count = @definition.count counter = 0 @definition.each do |table, data| puts "(#{counter+=1}/#{total_count}) Anonymizing columns #{data[:columns].keys.inspect} from table '#{table}'" process_table(table, data) end end |
#update_row(id, table, tuples, retries) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/anonymize/sql.rb', line 47 def update_row(id, table, tuples, retries) retries ||= 0 if tuples.count > 0 update_part = tuples.map { |column, value| "#{column} = \"#{@connection.escape(value)}\"" } update_sql = "UPDATE #{table} SET #{update_part.join(', ')} WHERE id = #{id}" puts update_sql if @options[:verbose] @connection.query(update_sql) unless @options[:pretend] end rescue StandardError => e raise e if retries <= 0 retries -= 1 retry end |