Class: Sage::QueriesController

Inherits:
BaseController
  • Object
show all
Defined in:
app/controllers/sage/queries_controller.rb

Instance Method Summary collapse

Instance Method Details

#cancelObject



285
286
287
288
# File 'app/controllers/sage/queries_controller.rb', line 285

def cancel
  @data_source.cancel(blazer_run_id)
  head :ok
end

#createObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'app/controllers/sage/queries_controller.rb', line 59

def create
  # Handle the new Sage form submission with question parameter
  if params[:query][:question].present?
    question = params[:query][:question]

    # Create query with placeholder name and statement
    @query = Blazer::Query.new(
      name: "Sage Query - #{Time.current.strftime('%Y-%m-%d %H:%M')}",
      statement: "-- Processing your question...\n-- #{question}",
      data_source: Blazer.data_sources.keys.first
    )
    @query.creator = blazer_user if @query.respond_to?(:creator)
    @query.status = "active" if @query.respond_to?(:status)

    if @query.save
      # Create associated Sage::Message record with the user's question
      message = @query.messages.create!(
        body: question,
        creator: (blazer_user if ::Blazer.user_class)
      )

      # Generate a unique stream target ID for real-time updates
      stream_target_id = "message_#{SecureRandom.hex(8)}"

      # Kick off the ProcessReportJob with 1-second delay
      Sage::ProcessReportJob.set(wait: 1.second).perform_later(
        question,
        query_id: @query.id,
        stream_target_id: stream_target_id
      )

      redirect_to edit_query_path(@query)
    else
      render_errors @query
    end
  else
    # Handle traditional Blazer query creation
    @query = Blazer::Query.new(query_params)
    @query.creator = blazer_user if @query.respond_to?(:creator)
    @query.status = "active" if @query.respond_to?(:status)

    if @query.save
      redirect_to query_path(@query, params: variable_params(@query))
    else
      render_errors @query
    end
  end
end

#destroyObject



252
253
254
255
# File 'app/controllers/sage/queries_controller.rb', line 252

def destroy
  @query.destroy if @query.editable?(blazer_user)
  redirect_to root_path
end

#docsObject



261
262
263
264
265
# File 'app/controllers/sage/queries_controller.rb', line 261

def docs
  @smart_variables = @data_source.smart_variables
  @linked_columns = @data_source.linked_columns
  @smart_columns = @data_source.smart_columns
end

#editObject



131
132
133
# File 'app/controllers/sage/queries_controller.rb', line 131

def edit
  # Messages will be loaded via turbo_frame from messages#index
end

#indexObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'app/controllers/sage/queries_controller.rb', line 6

def index
  @q = Blazer::Query.ransack(params[:q])
  @queries = @q.result.named.active

  # Only include creator if Blazer.user_class is configured
  @queries = @queries.includes(:creator) if Blazer.user_class

  @queries = @queries.order(:name)

  # Apply additional filters if needed
  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
    query_ids = Blazer::Audit.where(user_id: blazer_user.id).order(created_at: :desc).limit(500).pluck(:query_id).uniq
    @queries = @queries.where(id: query_ids)
  end

  # Filter out private queries (starting with #) unless they belong to the current user
  @queries = @queries.where("name NOT LIKE ? OR creator_id = ?", "#%", blazer_user.try(:id))

  # Apply pagination with Pagy
  @pagy, @queries = pagy(@queries)
end

#newObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'app/controllers/sage/queries_controller.rb', line 30

def new
  @query = Blazer::Query.new(
    data_source: params[:data_source],
    name: params[:name]
  )
  if params[:fork_query_id]
    @query.statement ||= Blazer::Query.find(params[:fork_query_id]).try(:statement)
  end
  if params[:upload_id]
    upload = Blazer::Upload.find(params[:upload_id])
    upload_settings = Blazer.settings["uploads"]
    @query.data_source ||= upload_settings["data_source"]
    @query.statement ||= "SELECT * FROM #{upload.table_name} LIMIT 10"
  end

  # Get schema information for the current data source
  data_source_key = @query.data_source || Blazer.data_sources.keys.first
  @data_source = Blazer.data_sources[data_source_key]
  if @data_source
    schema = @data_source.schema
    # Filter out internal/system tables that aren't relevant for users
    @schema = schema.reject do |table_info|
      table_name = table_info[:table].to_s.downcase
      table_name.start_with?("sage_", "blazer_") ||
      %w[ar_internal_metadata schema_migrations sqlite_sequence].include?(table_name)
    end
  end
end

#refreshObject



231
232
233
234
# File 'app/controllers/sage/queries_controller.rb', line 231

def refresh
  refresh_query(@query)
  redirect_to query_path(@query, params: variable_params(@query))
end

#runObject



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'app/controllers/sage/queries_controller.rb', line 135

def run
  # @query is set by before_action for member routes (GET /queries/:id/run)
  # For collection routes (POST /queries/run), load query if query_id is provided
  @query ||= Blazer::Query.find_by(id: params[:query_id]) if params[:query_id]

  # use query data source when present
  data_source = @query.data_source if @query && @query.data_source
  data_source ||= params[:data_source]
  @data_source = Blazer.data_sources[data_source]

  # Prefer params statement over query's saved statement (for live editing)
  statement = params[:statement].presence || @query&.statement
  @statement = Blazer::Statement.new(statement, @data_source)
  # before process_vars
  @cohort_analysis = @statement.cohort_analysis?

  # fallback for now for users with open tabs
  # TODO remove fallback in future version
  @var_params = request.request_parameters["variables"] || request.request_parameters
  @success = process_vars(@statement, @var_params)
  @only_chart = params[:only_chart]
  @run_id = blazer_params[:run_id]

  run_cohort_analysis if @cohort_analysis

  query_running = !@run_id.nil?

  if query_running
    @timestamp = blazer_params[:timestamp].to_i

    @result = @data_source.run_results(@run_id)
    @success = !@result.nil?

    if @success
      @data_source.delete_results(@run_id)
      @columns = @result.columns
      @rows = @result.rows
      @error = @result.error
      @just_cached = !@result.error && @result.cached_at.present?
      @cached_at = nil
      params[:data_source] = nil
      render_run
    elsif Time.now > Time.at(@timestamp + (@data_source.timeout || 600).to_i + 5)
      # query lost
      Rails.logger.info "[blazer lost query] #{@run_id}"
      @error = "We lost your query :("
      @rows = []
      @columns = []
      render_run
    else
      continue_run
    end
  elsif @success
    @run_id = blazer_run_id

    async = Blazer.async

    options = { user: blazer_user, query: @query, refresh_cache: params[:check], run_id: @run_id, async: async }
    if async && request.format.symbol != :csv
      Blazer::RunStatementJob.perform_later(@data_source.id, @statement.statement, options.merge(values: @statement.values))
      wait_start = Blazer.monotonic_time
      loop do
        sleep(0.1)
        @result = @data_source.run_results(@run_id)
        break if @result || Blazer.monotonic_time - wait_start > 3
      end
    else
      @result = Blazer::RunStatement.new.perform(@statement, options)
    end

    if @result
      @data_source.delete_results(@run_id) if @run_id && async

      @columns = @result.columns
      @rows = @result.rows
      @error = @result.error
      @cached_at = @result.cached_at
      @just_cached = @result.just_cached

      @forecast = @query && @result.forecastable? && params[:forecast]
      if @forecast
        @result.forecast
        @forecast_error = @result.forecast_error
        @forecast = @forecast_error.nil?
      end

      render_run
    else
      @timestamp = Time.now.to_i
      continue_run
    end
  else
    render layout: false
  end
end

#schemaObject



267
268
269
# File 'app/controllers/sage/queries_controller.rb', line 267

def schema
  @schema = @data_source.schema
end

#showObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'app/controllers/sage/queries_controller.rb', line 108

def show
  @statement = @query.statement_object
  @success = process_vars(@statement)

  @smart_vars = {}
  @sql_errors = []
  @bind_vars.each do |var|
    smart_var, error = parse_smart_variables(var, @statement.data_source)
    @smart_vars[var] = smart_var if smart_var
    @sql_errors << error if error
  end

  @query.update!(status: "active") if @query.respond_to?(:status) && @query.status.in?([ "archived", nil ])

  add_cohort_analysis_vars if @query.cohort_analysis?

  if @success
    @run_data = { statement: @query.statement, query_id: @query.id, data_source: @query.data_source, variables: variable_params(@query) }
    @run_data[:forecast] = "t" if params[:forecast]
    @run_data[:cohort_period] = params[:cohort_period] if params[:cohort_period]
  end
end

#table_schemaObject



271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'app/controllers/sage/queries_controller.rb', line 271

def table_schema
  table_name = params[:table_name]
  data_source_key = params[:data_source] || Blazer.data_sources.keys.first
  @data_source = Blazer.data_sources[data_source_key]

  if @data_source && table_name.present?
    schema = @data_source.schema
    @table_info = schema.find { |table| table[:table] == table_name }
    @table_display_name = table_name.to_s.gsub("_", " ").titleize
  end

  render layout: false
end

#tablesObject



257
258
259
# File 'app/controllers/sage/queries_controller.rb', line 257

def tables
  render json: @data_source.tables
end

#updateObject



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'app/controllers/sage/queries_controller.rb', line 236

def update
  if params[:commit] == "Fork"
    @query = Blazer::Query.new
    @query.creator = blazer_user if @query.respond_to?(:creator)
  end
  @query.status = "active" if @query.respond_to?(:status)
  unless @query.editable?(blazer_user)
    @query.errors.add(:base, "Sorry, permission denied")
  end
  if @query.errors.empty? && @query.update(query_params)
    redirect_to query_path(@query, params: variable_params(@query))
  else
    render_errors @query
  end
end