Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add current_user_id parameter type to Data Explorer (#36655)

Régis Hanol72e55caa64e6
diff --git a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
index 16249db2988..c404f4d520e 100644
--- a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
@@ -157,7 +157,7 @@ module DiscourseDataExplorer
params[:params].is_a?(String) ? MultiJson.load(params[:params]) : params[:params]
end
- opts = { current_user: current_user&.username }
+ opts = { current_user: current_user }
opts[:explain] = true if params[:explain] == "true"
opts[:limit] = if params[:format] == "csv"
diff --git a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
index 253a62095d6..bd40db01878 100644
--- a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
+++ b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
@@ -34,10 +34,10 @@ module DiscourseDataExplorer
@params ||= Parameter.create_from_sql(sql)
end
- def cast_params(input_params)
+ def cast_params(input_params, opts = {})
result = {}.with_indifferent_access
self.params.each do |pobj|
- result[pobj.identifier] = pobj.cast_to_ruby input_params[pobj.identifier]
+ result[pobj.identifier] = pobj.cast_to_ruby(input_params[pobj.identifier], opts)
end
result
end
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input-form.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input-form.gjs
index da073aa6364..a6465d29741 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input-form.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input-form.gjs
@@ -155,6 +155,11 @@ export default class ParamInputForm extends Component {
initializeParams() {
this.args.paramInfo.forEach((info) => {
+ // Skip internal types - they are auto-injected server-side
+ if (info.internal) {
+ return;
+ }
+
const identifier = info.identifier;
const pinfo = this.createParamInfo(info);
@@ -393,6 +398,10 @@ export default class ParamInputForm extends Component {
@action
async submit() {
+ // No visible params to validate - return empty object
+ if (this.paramInfo.length === 0) {
+ return {};
+ }
if (this.form == null) {
throw "No form";
}
@@ -422,32 +431,34 @@ export default class ParamInputForm extends Component {
}
<template>
- <div class="query-params">
- <Form
- @data={{this.data}}
- @onRegisterApi={{this.onRegisterApi}}
- @onSubmit={{this.onSubmit}}
- class="params-form"
- as |form|
- >
- {{#each this.paramInfo as |info|}}
- <div class="param">
- <form.Field
- @name={{info.identifier}}
- @title={{info.identifier}}
- @validation={{info.validation}}
- @validate={{info.validate}}
- as |field|
- >
- <info.component @field={{field}} @info={{info}} />
- <ConditionalLoadingSpinner
- @condition={{info.loading}}
- @size="small"
- />
- </form.Field>
- </div>
- {{/each}}
- </Form>
- </div>
+ {{#if this.paramInfo.length}}
+ <div class="query-params">
+ <Form
+ @data={{this.data}}
+ @onRegisterApi={{this.onRegisterApi}}
+ @onSubmit={{this.onSubmit}}
+ class="params-form"
+ as |form|
+ >
+ {{#each this.paramInfo as |info|}}
+ <div class="param">
+ <form.Field
+ @name={{info.identifier}}
+ @title={{info.identifier}}
+ @validation={{info.validation}}
+ @validate={{info.validate}}
+ as |field|
+ >
+ <info.component @field={{field}} @info={{info}} />
+ <ConditionalLoadingSpinner
+ @condition={{info.loading}}
+ @size="small"
+ />
+ </form.Field>
+ </div>
+ {{/each}}
+ </Form>
+ </div>
+ {{/if}}
</template>
}
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index 2bd978788c4..ed5a2e3f87a 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -43,6 +43,7 @@ en:
<li><b>text</b> - variable-length character string</li>
<li><b>boolean</b> – true/false</li>
<li><b>date</b> - calendar date (year, month, day)</li>
+ <li><b>current_user_id</b> - ID of the user running the query (auto-injected, useful for group reports)</li>
</ul>
<p>For more information on data types, visit
<a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>this website</a>.</p>"
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
index 73ba38d9c53..6fabb3cea57 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
@@ -28,7 +28,7 @@ module DiscourseDataExplorer
query_args = {}
begin
- query_args = query.cast_params req_params
+ query_args = query.cast_params(req_params, opts)
rescue ValidationError => e
return { error: e, duration_nanos: 0 }
end
@@ -43,17 +43,18 @@ module DiscourseDataExplorer
DB.exec "SET LOCAL statement_timeout = 10000"
# SQL comments are for the benefits of the slow queries log
- sql = <<-SQL
- /*
- * DiscourseDataExplorer Query
- * Query: /admin/plugins/explorer/queries/#{query.id}
- * Started by: #{opts[:current_user]}
- */
- WITH query AS (
- #{query.sql}
- ) SELECT * FROM query
- LIMIT #{opts[:limit] || SiteSetting.data_explorer_query_result_limit}
- SQL
+ started_by = opts[:current_user]&.username
+ sql = <<~SQL
+ /*
+ * DiscourseDataExplorer Query
+ * Query: /admin/plugins/explorer/queries/#{query.id}
+ #{"* Started by: #{started_by}" if started_by}
+ */
+ WITH query AS (
+ #{query.sql}
+ ) SELECT * FROM query
+ LIMIT #{opts[:limit] || SiteSetting.data_explorer_query_result_limit}
+ SQL
time_start = Time.now
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb
index 71755f3f96c..20978346f08 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb
@@ -34,7 +34,13 @@ module DiscourseDataExplorer
end
def to_hash
- { identifier: @identifier, type: @type, default: @default, nullable: @nullable }
+ {
+ identifier: @identifier,
+ type: @type,
+ default: @default,
+ nullable: @nullable,
+ internal: internal?,
+ }
end
def self.types
@@ -61,9 +67,19 @@ module DiscourseDataExplorer
:string_list,
:user_list,
:group_list,
+ # System-injected (value set by server, not user input)
+ :current_user_id,
)
end
+ def self.internal_types
+ @internal_types ||= %i[current_user_id]
+ end
+
+ def internal?
+ self.class.internal_types.include?(@type)
+ end
+
def self.type_aliases
@type_aliases ||= { integer: :int, text: :string, timestamp: :datetime }
end
@@ -108,7 +124,20 @@ module DiscourseDataExplorer
ret_params
end
- def cast_to_ruby(string)
+ def cast_to_ruby(string, opts = {})
+ # Handle system-injected types first - they ignore user input
+ if @type == :current_user_id
+ current_user = opts[:current_user]
+ if current_user.nil?
+ if @nullable
+ return nil
+ else
+ raise ValidationError.new("Parameter #{identifier} requires a logged in user")
+ end
+ end
+ return current_user.id
+ end
+
string = @default unless string
# Since we allow passing a JSON object for the params, the most straightforward way to
# check that the value is valid is to convert it back to a string.
diff --git a/plugins/discourse-data-explorer/spec/data_explorer_spec.rb b/plugins/discourse-data-explorer/spec/data_explorer_spec.rb
index 9fa562bbc3a..a317800ca4a 100644
--- a/plugins/discourse-data-explorer/spec/data_explorer_spec.rb
+++ b/plugins/discourse-data-explorer/spec/data_explorer_spec.rb
@@ -58,6 +58,57 @@ describe DiscourseDataExplorer::DataExplorer do
expect(result[:pg_result][0]["id"]).to eq(topic2.id)
end
+ describe "current_user_id parameter" do
+ fab!(:user)
+
+ it "injects the current user's id, ignoring user-provided values" do
+ sql = <<~SQL
+ -- [params]
+ -- current_user_id :me
+ SELECT id FROM users WHERE id = :me
+ SQL
+
+ query = DiscourseDataExplorer::Query.create!(name: "test", sql: sql)
+ other_user = Fabricate(:user)
+
+ result =
+ described_class.run_query(query, { "me" => other_user.id.to_s }, { current_user: user })
+
+ expect(result[:error]).to eq(nil)
+ expect(result[:pg_result][0]["id"]).to eq(user.id)
+ end
+
+ it "returns an error when not nullable and no current user" do
+ sql = <<~SQL
+ -- [params]
+ -- current_user_id :me
+ SELECT id FROM users WHERE id = :me
+ SQL
+
+ query = DiscourseDataExplorer::Query.create!(name: "test", sql: sql)
+
+ result = described_class.run_query(query, {}, {})
+
+ expect(result[:error]).to be_a(DiscourseDataExplorer::ValidationError)
+ expect(result[:error].message).to include("requires a logged in user")
+ end
+
+ it "allows null when nullable and no current user" do
+ sql = <<~SQL
+ -- [params]
+ -- null current_user_id :me
+ SELECT COALESCE(:me, -1) AS user_id
+ SQL
+
+ query = DiscourseDataExplorer::Query.create!(name: "test", sql: sql)
+
+ result = described_class.run_query(query, {}, {})
+
+ expect(result[:error]).to eq(nil)
+ expect(result[:pg_result][0]["user_id"]).to eq(-1)
+ end
+ end
+
describe ".add_extra_data" do
it "treats any column with payload in the name as 'json'" do
Fabricate(:reviewable_queued_post)
diff --git a/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb b/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb
index c639f833f7d..89e049134bd 100644
--- a/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb
+++ b/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb
@@ -113,6 +113,28 @@ RSpec.describe DiscourseDataExplorer::Parameter do
expect(param("user_id", :user_id, nil, false).cast_to_ruby(user.email)).to eq(user.id)
end
end
+
+ describe "current_user_id type" do
+ fab!(:user)
+ let(:current_user_param) { param("me", :current_user_id, nil, false) }
+
+ it "returns the current user's id, ignoring user-provided values" do
+ expect(current_user_param.cast_to_ruby(nil, current_user: user)).to eq(user.id)
+ expect(current_user_param.cast_to_ruby("999999", current_user: user)).to eq(user.id)
+ end
+
+ it "raises an error when not nullable and no current user" do
+ expect { current_user_param.cast_to_ruby(nil, {}) }.to raise_error(
+ DiscourseDataExplorer::ValidationError,
+ /requires a logged in user/,
+ )
+ end
+
+ it "returns nil when nullable and no current user" do
+ nullable_param = param("me", :current_user_id, nil, true)
+ expect(nullable_param.cast_to_ruby(nil, {})).to eq(nil)
+ end
+ end
end
describe ".create_from_sql" do
diff --git a/plugins/discourse-data-explorer/spec/system/explorer_spec.rb b/plugins/discourse-data-explorer/spec/system/explorer_spec.rb
index 7442eaf2ba9..1505d7a393b 100644
--- a/plugins/discourse-data-explorer/spec/system/explorer_spec.rb
+++ b/plugins/discourse-data-explorer/spec/system/explorer_spec.rb
@@ -95,4 +95,23 @@ RSpec.describe "Explorer", type: :system do
)
end
end
+
+ context "with a current_user_id param" do
+ fab!(:query) { Fabricate(:query, name: "My current user query", sql: <<~SQL, user: admin) }
+ -- [params]
+ -- current_user_id :me
+ SELECT id, username FROM users WHERE id = :me
+ SQL
+
+ it "auto-injects the current user's id without showing an input field" do
+ visit("/admin/plugins/explorer/queries/#{query.id}")
+
+ expect(page).to have_no_css(".query-params")
+ find(".query-run .btn-primary").click
+
+ expect(page).to have_css(".query-results .result-header")
+ expect(page).to have_css(".query-results tbody tr", count: 1)
+ expect(page).to have_css(".query-results tbody td", text: admin.username)
+ end
+ end
end