Business intelligence made simple
Updated indentation for private methods [skip ci]
Andrew Kane6ec0d22c97d3
diff --git a/app/controllers/blazer/base_controller.rb b/app/controllers/blazer/base_controller.rbindex 8d7d17af..d8841f8d 100644--- a/app/controllers/blazer/base_controller.rb+++ b/app/controllers/blazer/base_controller.rb@@ -32,101 +32,101 @@ module Blazerprivate- def process_vars(statement, var_params = nil)- var_params ||= request.query_parameters- (@bind_vars ||= []).concat(statement.variables).uniq!- # update in-place so populated in view and consistent across queries on dashboard- @bind_vars.each do |var|- if !var_params[var]- default = statement.data_source.variable_defaults[var]- # only add if default exists- var_params[var] = default if default- end+ def process_vars(statement, var_params = nil)+ var_params ||= request.query_parameters+ (@bind_vars ||= []).concat(statement.variables).uniq!+ # update in-place so populated in view and consistent across queries on dashboard+ @bind_vars.each do |var|+ if !var_params[var]+ default = statement.data_source.variable_defaults[var]+ # only add if default exists+ var_params[var] = default if defaultend- runnable = @bind_vars.all? { |v| var_params[v] }- statement.add_values(var_params) if runnable- runnableend+ runnable = @bind_vars.all? { |v| var_params[v] }+ statement.add_values(var_params) if runnable+ runnable+ end- def refresh_query(query)- statement = query.statement_object- runnable = process_vars(statement)- cohort_analysis_statement(statement) if statement.cohort_analysis?- statement.clear_cache if runnable- end+ def refresh_query(query)+ statement = query.statement_object+ runnable = process_vars(statement)+ cohort_analysis_statement(statement) if statement.cohort_analysis?+ statement.clear_cache if runnable+ end- def add_cohort_analysis_vars- @bind_vars << "cohort_period" unless @bind_vars.include?("cohort_period")- @smart_vars["cohort_period"] = ["day", "week", "month"] if @smart_vars- # TODO create var_params method- request.query_parameters["cohort_period"] ||= "week"- end+ def add_cohort_analysis_vars+ @bind_vars << "cohort_period" unless @bind_vars.include?("cohort_period")+ @smart_vars["cohort_period"] = ["day", "week", "month"] if @smart_vars+ # TODO create var_params method+ request.query_parameters["cohort_period"] ||= "week"+ end- def parse_smart_variables(var, data_source)- smart_var_data_source =- ([data_source] + Array(data_source.settings["inherit_smart_settings"]).map { |ds| Blazer.data_sources[ds] }).find { |ds| ds.smart_variables[var] }-- if smart_var_data_source- query = smart_var_data_source.smart_variables[var]-- if query.is_a? Hash- smart_var = query.map { |k,v| [v, k] }- elsif query.is_a? Array- smart_var = query.map { |v| [v, v] }- elsif query- result = smart_var_data_source.run_statement(query)- smart_var = result.rows.map { |v| v.reverse }- error = result.error if result.error- end+ def parse_smart_variables(var, data_source)+ smart_var_data_source =+ ([data_source] + Array(data_source.settings["inherit_smart_settings"]).map { |ds| Blazer.data_sources[ds] }).find { |ds| ds.smart_variables[var] }++ if smart_var_data_source+ query = smart_var_data_source.smart_variables[var]++ if query.is_a? Hash+ smart_var = query.map { |k,v| [v, k] }+ elsif query.is_a? Array+ smart_var = query.map { |v| [v, v] }+ elsif query+ result = smart_var_data_source.run_statement(query)+ smart_var = result.rows.map { |v| v.reverse }+ error = result.error if result.errorend-- [smart_var, error]end- def cohort_analysis_statement(statement)- @cohort_period = params["cohort_period"] || "week"- @cohort_period = "week" unless ["day", "week", "month"].include?(@cohort_period)-- # for now- @conversion_period = @cohort_period- @cohort_days =- case @cohort_period- when "day"- 1- when "week"- 7- when "month"- 30- end-- statement.apply_cohort_analysis(period: @cohort_period, days: @cohort_days)- end+ [smart_var, error]+ end- def variable_params(resource, var_params = nil)- permitted_keys = resource.variables- var_params ||= request.query_parameters- var_params.slice(*permitted_keys)- end- helper_method :variable_params+ def cohort_analysis_statement(statement)+ @cohort_period = params["cohort_period"] || "week"+ @cohort_period = "week" unless ["day", "week", "month"].include?(@cohort_period)++ # for now+ @conversion_period = @cohort_period+ @cohort_days =+ case @cohort_period+ when "day"+ 1+ when "week"+ 7+ when "month"+ 30+ end- def nested_variable_params(resource)- variable_params(resource, request.query_parameters["variables"] || {})- end+ statement.apply_cohort_analysis(period: @cohort_period, days: @cohort_days)+ end- def blazer_user- send(Blazer.user_method) if Blazer.user_method && respond_to?(Blazer.user_method, true)- end- helper_method :blazer_user+ def variable_params(resource, var_params = nil)+ permitted_keys = resource.variables+ var_params ||= request.query_parameters+ var_params.slice(*permitted_keys)+ end+ helper_method :variable_params- def render_errors(resource)- @errors = resource.errors- action = resource.persisted? ? :edit : :new- render action, status: :unprocessable_entity- end+ def nested_variable_params(resource)+ variable_params(resource, request.query_parameters["variables"] || {})+ end- # do not inherit from ApplicationController - #120- def default_url_options- {}- end+ def blazer_user+ send(Blazer.user_method) if Blazer.user_method && respond_to?(Blazer.user_method, true)+ end+ helper_method :blazer_user++ def render_errors(resource)+ @errors = resource.errors+ action = resource.persisted? ? :edit : :new+ render action, status: :unprocessable_entity+ end++ # do not inherit from ApplicationController - #120+ def default_url_options+ {}+ endendenddiff --git a/app/controllers/blazer/checks_controller.rb b/app/controllers/blazer/checks_controller.rbindex 580214c5..5bb4c17b 100644--- a/app/controllers/blazer/checks_controller.rb+++ b/app/controllers/blazer/checks_controller.rb@@ -45,12 +45,12 @@ module Blazerprivate- def check_params- params.require(:check).permit(:query_id, :emails, :slack_channels, :invert, :check_type, :schedule)- end+ def check_params+ params.require(:check).permit(:query_id, :emails, :slack_channels, :invert, :check_type, :schedule)+ end- def set_check- @check = Blazer::Check.find(params[:id])- end+ def set_check+ @check = Blazer::Check.find(params[:id])+ endendenddiff --git a/app/controllers/blazer/dashboards_controller.rb b/app/controllers/blazer/dashboards_controller.rbindex 5cb5564d..33badf71 100644--- a/app/controllers/blazer/dashboards_controller.rb+++ b/app/controllers/blazer/dashboards_controller.rb@@ -65,35 +65,35 @@ module Blazerprivate- def dashboard_params- params.require(:dashboard).permit(:name)- end+ def dashboard_params+ params.require(:dashboard).permit(:name)+ end- def set_dashboard- @dashboard = Blazer::Dashboard.find(params[:id])- end+ def set_dashboard+ @dashboard = Blazer::Dashboard.find(params[:id])+ end- def update_dashboard(dashboard)- dashboard.assign_attributes(dashboard_params)- Blazer::Dashboard.transaction do- if params[:query_ids].is_a?(Array)- query_ids = params[:query_ids].map(&:to_i)- @queries = Blazer::Query.find(query_ids).sort_by { |q| query_ids.index(q.id) }- end- if dashboard.save- if @queries- @queries.each_with_index do |query, i|- dashboard_query = dashboard.dashboard_queries.where(query_id: query.id).first_or_initialize- dashboard_query.position = i- dashboard_query.save!- end- if dashboard.persisted?- dashboard.dashboard_queries.where.not(query_id: query_ids).destroy_all- end+ def update_dashboard(dashboard)+ dashboard.assign_attributes(dashboard_params)+ Blazer::Dashboard.transaction do+ if params[:query_ids].is_a?(Array)+ query_ids = params[:query_ids].map(&:to_i)+ @queries = Blazer::Query.find(query_ids).sort_by { |q| query_ids.index(q.id) }+ end+ if dashboard.save+ if @queries+ @queries.each_with_index do |query, i|+ dashboard_query = dashboard.dashboard_queries.where(query_id: query.id).first_or_initialize+ dashboard_query.position = i+ dashboard_query.save!+ end+ if dashboard.persisted?+ dashboard.dashboard_queries.where.not(query_id: query_ids).destroy_allend- trueend+ trueendend+ endendenddiff --git a/app/controllers/blazer/queries_controller.rb b/app/controllers/blazer/queries_controller.rbindex d852e2c8..b1bd1cb9 100644--- a/app/controllers/blazer/queries_controller.rb+++ b/app/controllers/blazer/queries_controller.rb@@ -215,219 +215,219 @@ module Blazerprivate- def set_data_source- @data_source = Blazer.data_sources[params[:data_source]]- end+ def set_data_source+ @data_source = Blazer.data_sources[params[:data_source]]+ end- def continue_run- render json: {run_id: @run_id, timestamp: @timestamp}, status: :accepted- end+ def continue_run+ render json: {run_id: @run_id, timestamp: @timestamp}, status: :accepted+ end- def render_run- @checks = @query ? @query.checks.order(:id) : []-- @first_row = @rows.first || []- @column_types = []- if @rows.any?- @columns.each_with_index do |_, i|- @column_types << (- case @first_row[i]- when Integer- "int"- when Float, BigDecimal- "float"- else- "string-ins"- end- )- end+ def render_run+ @checks = @query ? @query.checks.order(:id) : []++ @first_row = @rows.first || []+ @column_types = []+ if @rows.any?+ @columns.each_with_index do |_, i|+ @column_types << (+ case @first_row[i]+ when Integer+ "int"+ when Float, BigDecimal+ "float"+ else+ "string-ins"+ end+ )end+ end- @min_width_types = @columns.each_with_index.select { |c, i| @first_row[i].is_a?(Time) || @first_row[i].is_a?(String) || @data_source.smart_columns[c] }.map(&:last)-- @boom = @result.boom if @result-- @linked_columns = @data_source.linked_columns-- @markers = []- [["latitude", "longitude"], ["lat", "lon"], ["lat", "lng"]].each do |keys|- lat_index = @columns.index(keys.first)- lon_index = @columns.index(keys.last)- if lat_index && lon_index- @markers =- @rows.select do |r|- r[lat_index] && r[lon_index]- end.map do |r|- {- tooltip: r.each_with_index.map { |v, i| i == lat_index || i == lon_index ? nil : "<strong>#{ERB::Util.html_escape(@columns[i])}:</strong> #{ERB::Util.html_escape(v)}" }.compact.join("<br>").truncate(140, separator: " "),- latitude: r[lat_index],- longitude: r[lon_index]- }- end- end- end+ @min_width_types = @columns.each_with_index.select { |c, i| @first_row[i].is_a?(Time) || @first_row[i].is_a?(String) || @data_source.smart_columns[c] }.map(&:last)- render_cohort_analysis if @cohort_analysis && !@error+ @boom = @result.boom if @result- respond_to do |format|- format.html do- render layout: false- end- format.csv do- # not ideal, but useful for testing- raise Error, @error if @error && Rails.env.test?+ @linked_columns = @data_source.linked_columns- send_data csv_data(@columns, @rows, @data_source), type: "text/csv; charset=utf-8; header=present", disposition: "attachment; filename=\"#{@query.try(:name).try(:parameterize).presence || 'query'}.csv\""- end+ @markers = []+ [["latitude", "longitude"], ["lat", "lon"], ["lat", "lng"]].each do |keys|+ lat_index = @columns.index(keys.first)+ lon_index = @columns.index(keys.last)+ if lat_index && lon_index+ @markers =+ @rows.select do |r|+ r[lat_index] && r[lon_index]+ end.map do |r|+ {+ tooltip: r.each_with_index.map { |v, i| i == lat_index || i == lon_index ? nil : "<strong>#{ERB::Util.html_escape(@columns[i])}:</strong> #{ERB::Util.html_escape(v)}" }.compact.join("<br>").truncate(140, separator: " "),+ latitude: r[lat_index],+ longitude: r[lon_index]+ }+ endendend- def set_queries(limit = nil)- @queries = Blazer::Query.named.select(:id, :name, :creator_id, :statement)- @queries = @queries.includes(:creator) if Blazer.user_class+ render_cohort_analysis if @cohort_analysis && !@error- if blazer_user && params[:filter] == "mine"- @queries = @queries.where(creator_id: blazer_user.id).reorder(updated_at: :desc)- elsif blazer_user && params[:filter] == "viewed" && Blazer.audit- @queries = queries_by_ids(Blazer::Audit.where(user_id: blazer_user.id).order(created_at: :desc).limit(500).pluck(:query_id).uniq)- else- @queries = @queries.limit(limit) if limit- @queries = @queries.active.order(:name)+ respond_to do |format|+ format.html do+ render layout: falseend- @queries = @queries.to_a+ format.csv do+ # not ideal, but useful for testing+ raise Error, @error if @error && Rails.env.test?- @more = limit && @queries.size >= limit+ send_data csv_data(@columns, @rows, @data_source), type: "text/csv; charset=utf-8; header=present", disposition: "attachment; filename=\"#{@query.try(:name).try(:parameterize).presence || 'query'}.csv\""+ end+ end+ end- @queries = @queries.select { |q| !q.name.to_s.start_with?("#") || q.try(:creator).try(:id) == blazer_user.try(:id) }+ def set_queries(limit = nil)+ @queries = Blazer::Query.named.select(:id, :name, :creator_id, :statement)+ @queries = @queries.includes(:creator) if Blazer.user_class- @queries =- @queries.map do |q|- {- id: q.id,- name: q.name,- creator: blazer_user && q.try(:creator) == blazer_user ? "You" : q.try(:creator).try(Blazer.user_name),- vars: q.variables.join(", "),- to_param: q.to_param- }- end+ if blazer_user && params[:filter] == "mine"+ @queries = @queries.where(creator_id: blazer_user.id).reorder(updated_at: :desc)+ elsif blazer_user && params[:filter] == "viewed" && Blazer.audit+ @queries = queries_by_ids(Blazer::Audit.where(user_id: blazer_user.id).order(created_at: :desc).limit(500).pluck(:query_id).uniq)+ else+ @queries = @queries.limit(limit) if limit+ @queries = @queries.active.order(:name)end+ @queries = @queries.to_a- def queries_by_ids(favorite_query_ids)- queries = Blazer::Query.active.named.where(id: favorite_query_ids)- queries = queries.includes(:creator) if Blazer.user_class- queries = queries.index_by(&:id)- favorite_query_ids.map { |query_id| queries[query_id] }.compact- end+ @more = limit && @queries.size >= limit- def set_query- @query = Blazer::Query.find(params[:id].to_s.split("-").first)- end+ @queries = @queries.select { |q| !q.name.to_s.start_with?("#") || q.try(:creator).try(:id) == blazer_user.try(:id) }- def render_forbidden- render plain: "Access denied", status: :forbidden- end+ @queries =+ @queries.map do |q|+ {+ id: q.id,+ name: q.name,+ creator: blazer_user && q.try(:creator) == blazer_user ? "You" : q.try(:creator).try(Blazer.user_name),+ vars: q.variables.join(", "),+ to_param: q.to_param+ }+ end+ end- def query_params- params.require(:query).permit(:name, :description, :statement, :data_source)- end+ def queries_by_ids(favorite_query_ids)+ queries = Blazer::Query.active.named.where(id: favorite_query_ids)+ queries = queries.includes(:creator) if Blazer.user_class+ queries = queries.index_by(&:id)+ favorite_query_ids.map { |query_id| queries[query_id] }.compact+ end- def blazer_params- params[:blazer] || {}- end+ def set_query+ @query = Blazer::Query.find(params[:id].to_s.split("-").first)+ end- def csv_data(columns, rows, data_source)- CSV.generate do |csv|- csv << columns- rows.each do |row|- csv << row.each_with_index.map { |v, i| v.is_a?(Time) ? blazer_time_value(data_source, columns[i], v) : v }- end+ def render_forbidden+ render plain: "Access denied", status: :forbidden+ end++ def query_params+ params.require(:query).permit(:name, :description, :statement, :data_source)+ end++ def blazer_params+ params[:blazer] || {}+ end++ def csv_data(columns, rows, data_source)+ CSV.generate do |csv|+ csv << columns+ rows.each do |row|+ csv << row.each_with_index.map { |v, i| v.is_a?(Time) ? blazer_time_value(data_source, columns[i], v) : v }endend+ end- def blazer_time_value(data_source, k, v)- data_source.local_time_suffix.any? { |s| k.ends_with?(s) } ? v.to_s.sub(" UTC", "") : v.in_time_zone(Blazer.time_zone)- end- helper_method :blazer_time_value+ def blazer_time_value(data_source, k, v)+ data_source.local_time_suffix.any? { |s| k.ends_with?(s) } ? v.to_s.sub(" UTC", "") : v.in_time_zone(Blazer.time_zone)+ end+ helper_method :blazer_time_value++ def blazer_run_id+ params[:run_id].to_s.gsub(/[^a-z0-9\-]/i, "")+ end- def blazer_run_id- params[:run_id].to_s.gsub(/[^a-z0-9\-]/i, "")+ def run_cohort_analysis+ unless @statement.data_source.supports_cohort_analysis?+ @cohort_error = "This data source does not support cohort analysis"end- def run_cohort_analysis- unless @statement.data_source.supports_cohort_analysis?- @cohort_error = "This data source does not support cohort analysis"- end+ @show_cohort_rows = !params[:query_id] || @cohort_error+ cohort_analysis_statement(@statement) unless @show_cohort_rows+ end- @show_cohort_rows = !params[:query_id] || @cohort_error- cohort_analysis_statement(@statement) unless @show_cohort_rows- end+ def render_cohort_analysis+ if @show_cohort_rows+ @cohort_analysis = false- def render_cohort_analysis- if @show_cohort_rows- @cohort_analysis = false+ @row_limit = 1000- @row_limit = 1000+ # check results+ unless @cohort_error+ # check names+ expected_columns = ["user_id", "conversion_time"]+ missing_columns = expected_columns - @result.columns+ if missing_columns.any?+ @cohort_error = "Expected user_id and conversion_time columns"+ end- # check results+ # check types (user_id can be any type)unless @cohort_error- # check names- expected_columns = ["user_id", "conversion_time"]- missing_columns = expected_columns - @result.columns- if missing_columns.any?- @cohort_error = "Expected user_id and conversion_time columns"- end+ column_types = @result.columns.zip(@result.column_types).to_h- # check types (user_id can be any type)- unless @cohort_error- column_types = @result.columns.zip(@result.column_types).to_h-- if !column_types["cohort_time"].in?(["time", nil])- @cohort_error = "cohort_time must be time column"- elsif !column_types["conversion_time"].in?(["time", nil])- @cohort_error = "conversion_time must be time column"- end+ if !column_types["cohort_time"].in?(["time", nil])+ @cohort_error = "cohort_time must be time column"+ elsif !column_types["conversion_time"].in?(["time", nil])+ @cohort_error = "conversion_time must be time column"endend- else- @today = Blazer.time_zone.today- @min_cohort_date, @max_cohort_date = @result.rows.map { |r| r[0] }.minmax- @buckets = {}- @rows.each do |r|- @buckets[[r[0], r[1]]] = r[2]- end-- @cohort_dates = []- current_date = @max_cohort_date- while current_date && current_date >= @min_cohort_date- @cohort_dates << current_date- current_date =- case @cohort_period- when "day"- current_date - 1- when "week"- current_date - 7- else- current_date.prev_month- end- end+ end+ else+ @today = Blazer.time_zone.today+ @min_cohort_date, @max_cohort_date = @result.rows.map { |r| r[0] }.minmax+ @buckets = {}+ @rows.each do |r|+ @buckets[[r[0], r[1]]] = r[2]+ end- num_cols = @cohort_dates.size- @columns = ["Cohort", "Users"] + num_cols.times.map { |i| "#{@conversion_period.titleize} #{i + 1}" }- rows = []- date_format = @cohort_period == "month" ? "%b %Y" : "%b %-e, %Y"- @cohort_dates.each do |date|- row = [date.strftime(date_format), @buckets[[date, 0]] || 0]-- num_cols.times do |i|- if @today >= date + (@cohort_days * i)- row << (@buckets[[date, i + 1]] || 0)- end+ @cohort_dates = []+ current_date = @max_cohort_date+ while current_date && current_date >= @min_cohort_date+ @cohort_dates << current_date+ current_date =+ case @cohort_period+ when "day"+ current_date - 1+ when "week"+ current_date - 7+ else+ current_date.prev_monthend+ end++ num_cols = @cohort_dates.size+ @columns = ["Cohort", "Users"] + num_cols.times.map { |i| "#{@conversion_period.titleize} #{i + 1}" }+ rows = []+ date_format = @cohort_period == "month" ? "%b %Y" : "%b %-e, %Y"+ @cohort_dates.each do |date|+ row = [date.strftime(date_format), @buckets[[date, 0]] || 0]- rows << row+ num_cols.times do |i|+ if @today >= date + (@cohort_days * i)+ row << (@buckets[[date, i + 1]] || 0)+ endend- @rows = rows++ rows << rowend+ @rows = rowsend+ endendenddiff --git a/app/controllers/blazer/uploads_controller.rb b/app/controllers/blazer/uploads_controller.rbindex 12f8ca4a..9f441c7b 100644--- a/app/controllers/blazer/uploads_controller.rb+++ b/app/controllers/blazer/uploads_controller.rb@@ -86,62 +86,62 @@ module Blazerprivate- def update_file(upload, drop: nil)- file = params.require(:upload).fetch(:file)- raise Blazer::UploadError, "File is not a CSV" if file.content_type != "text/csv"- raise Blazer::UploadError, "File is too large (maximum is 100MB)" if file.size > 100.megabytes-- contents = file.read- rows = CSV.parse(contents, converters: %i[numeric date date_time])-- # friendly column names- columns = rows.shift.map { |v| v.to_s.encode("UTF-8").gsub("%", " pct ").parameterize.gsub("-", "_") }- duplicate_column = columns.find { |c| columns.count(c) > 1 }- raise Blazer::UploadError, "Duplicate column name: #{duplicate_column}" if duplicate_column-- column_types =- columns.size.times.map do |i|- values = rows.map { |r| r[i] }.uniq.compact- if values.all? { |v| v.is_a?(Integer) && v >= -9223372036854775808 && v <= 9223372036854775807 }- "bigint"- elsif values.all? { |v| v.is_a?(Numeric) }- "decimal"- elsif values.all? { |v| v.is_a?(DateTime) }- "timestamptz"- elsif values.all? { |v| v.is_a?(Date) }- "date"- else- "text"- end+ def update_file(upload, drop: nil)+ file = params.require(:upload).fetch(:file)+ raise Blazer::UploadError, "File is not a CSV" if file.content_type != "text/csv"+ raise Blazer::UploadError, "File is too large (maximum is 100MB)" if file.size > 100.megabytes++ contents = file.read+ rows = CSV.parse(contents, converters: %i[numeric date date_time])++ # friendly column names+ columns = rows.shift.map { |v| v.to_s.encode("UTF-8").gsub("%", " pct ").parameterize.gsub("-", "_") }+ duplicate_column = columns.find { |c| columns.count(c) > 1 }+ raise Blazer::UploadError, "Duplicate column name: #{duplicate_column}" if duplicate_column++ column_types =+ columns.size.times.map do |i|+ values = rows.map { |r| r[i] }.uniq.compact+ if values.all? { |v| v.is_a?(Integer) && v >= -9223372036854775808 && v <= 9223372036854775807 }+ "bigint"+ elsif values.all? { |v| v.is_a?(Numeric) }+ "decimal"+ elsif values.all? { |v| v.is_a?(DateTime) }+ "timestamptz"+ elsif values.all? { |v| v.is_a?(Date) }+ "date"+ else+ "text"end+ end- begin- # maybe SET LOCAL statement_timeout = '30s'- # maybe regenerate CSV in Ruby to ensure consistent parsing- Blazer.uploads_connection.transaction do- Blazer.uploads_connection.execute("DROP TABLE IF EXISTS #{Blazer.uploads_table_name(drop)}") if drop- Blazer.uploads_connection.execute("CREATE TABLE #{upload.table_name} (#{columns.map.with_index { |c, i| "#{Blazer.uploads_connection.quote_column_name(c)} #{column_types[i]}" }.join(", ")})")- Blazer.uploads_connection.raw_connection.copy_data("COPY #{upload.table_name} FROM STDIN CSV HEADER") do- Blazer.uploads_connection.raw_connection.put_copy_data(contents)- end+ begin+ # maybe SET LOCAL statement_timeout = '30s'+ # maybe regenerate CSV in Ruby to ensure consistent parsing+ Blazer.uploads_connection.transaction do+ Blazer.uploads_connection.execute("DROP TABLE IF EXISTS #{Blazer.uploads_table_name(drop)}") if drop+ Blazer.uploads_connection.execute("CREATE TABLE #{upload.table_name} (#{columns.map.with_index { |c, i| "#{Blazer.uploads_connection.quote_column_name(c)} #{column_types[i]}" }.join(", ")})")+ Blazer.uploads_connection.raw_connection.copy_data("COPY #{upload.table_name} FROM STDIN CSV HEADER") do+ Blazer.uploads_connection.raw_connection.put_copy_data(contents)end- rescue ActiveRecord::StatementInvalid => e- raise Blazer::UploadError, "Table already exists" if e.message.include?("PG::DuplicateTable")- raise eend+ rescue ActiveRecord::StatementInvalid => e+ raise Blazer::UploadError, "Table already exists" if e.message.include?("PG::DuplicateTable")+ raise eend+ end- def upload_params- params.require(:upload).except(:file).permit(:table, :description)- end+ def upload_params+ params.require(:upload).except(:file).permit(:table, :description)+ end- def set_upload- @upload = Blazer::Upload.find(params[:id])- end+ def set_upload+ @upload = Blazer::Upload.find(params[:id])+ end- # routes aren't added, but also check here- def ensure_uploads- render plain: "Uploads not enabled" unless Blazer.uploads?- end+ # routes aren't added, but also check here+ def ensure_uploads+ render plain: "Uploads not enabled" unless Blazer.uploads?+ endendend