A platform for community discussion. Free, open, simple.
FIX: bind declared Data Explorer parameters with their real Postgres type (#43255)
David Taylorf5a6526dcc49
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.rbindex f574ea3fcde..8dc0a7bd154 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@@ -19,6 +19,9 @@ module DiscourseDataExplorerPG_TYPE_OID_JSONB,PG_TYPE_OID_JSONB_ARRAY,]+ PG_TYPE_OID_TEXT = 25+ PG_TYPE_OID_DATE = 1082+ PG_TYPE_OID_TIMESTAMP = 1114# Run a data explorer query on the currently connected database.#@@ -52,7 +55,8 @@ module DiscourseDataExplorerexecutable_sql = nilbinds = []begin- executable_sql, binds = rewrite_to_binds(strip_comments(query.sql), values)+ executable_sql, binds =+ rewrite_to_binds(strip_comments(query.sql), values, bind_oid_hints(query))rescue ValidationError => ereturn { error: e, duration_nanos: 0 }end@@ -157,7 +161,7 @@ module DiscourseDataExplorer# of placeholders so `IN (:ids)` keeps working, and an empty list becomes# `NULL`. A marker inside a dollar-quoted literal cannot be bound at all, so# it is rejected rather than silently left as literal text.- def self.rewrite_to_binds(sql, params)+ def self.rewrite_to_binds(sql, params, bind_oid_hints = {})return sql, [] if params.blank?values = params.transform_keys(&:to_s)@@ -170,7 +174,11 @@ module DiscourseDataExplorerwhen :coderesult << text.gsub(PARAM_REGEX) do |matched|name = $1- values.key?(name) ? (slots[name] ||= placeholders_for(values[name], binds)) : matched+ if values.key?(name)+ slots[name] ||= placeholders_for(values[name], binds, bind_oid_hints[name])+ else+ matched+ endendwhen :dollar_quoteif text.scan(PARAM_REGEX).any? { |match| values.key?(match.first) }@@ -185,17 +193,38 @@ module DiscourseDataExplorer[result, binds]end- def self.placeholders_for(value, binds)+ # Postgres can't infer a type for a parameter used only somewhere like a+ # bare `:param IS NULL`, so bind these declared types explicitly rather+ # than leaving them unknown. `time` is left out: its value is formatted as+ # a full timestamp string, which isn't valid input for a bare `time` column.+ DECLARED_TYPE_OIDS = {+ string: PG_TYPE_OID_TEXT,+ string_list: PG_TYPE_OID_TEXT,+ date: PG_TYPE_OID_DATE,+ datetime: PG_TYPE_OID_TIMESTAMP,+ }.freeze++ def self.bind_oid_hints(query)+ query+ .params+ .each_with_object({}) do |param, hints|+ oid = DECLARED_TYPE_OIDS[param.type]+ hints[param.identifier.to_s] = oid if oid+ end+ end+ private_class_method :bind_oid_hints++ def self.placeholders_for(value, binds, oid_hint)if value.is_a?(Array)return "NULL" if value.empty?value.map do |element|- binds << bind_for(element)+ binds << bind_for(element, oid_hint)"$#{binds.length}"end.join(", ")else- binds << bind_for(value)+ binds << bind_for(value, oid_hint)"$#{binds.length}"endend@@ -204,8 +233,8 @@ module DiscourseDataExplorer# Mirror how an inlined literal used to be typed: numbers and booleans carry# their PostgreSQL type so results decode back to the same Ruby class, while# everything else binds as an unknown-typed literal that the surrounding- # expression coerces and that reads back as text.- def self.bind_for(value)+ # expression coerces and that reads back as text, unless `oid_hint` overrides it.+ def self.bind_for(value, oid_hint = nil)case valuewhen Integer{ value: value.to_s, type: 20 }@@ -214,11 +243,11 @@ module DiscourseDataExplorerwhen true, false{ value: value.to_s, type: 16 }when nil- { value: nil, type: 0 }+ { value: nil, type: oid_hint || 0 }when Time- { value: value.utc.iso8601, type: 0 }+ { value: value.utc.iso8601, type: oid_hint || 0 }else- { value: value.to_s, type: 0 }+ { value: value.to_s, type: oid_hint || 0 }endendprivate_class_method :bind_fordiff --git a/plugins/discourse-data-explorer/spec/data_explorer_spec.rb b/plugins/discourse-data-explorer/spec/data_explorer_spec.rbindex d5164e29fd0..4068091b940 100644--- a/plugins/discourse-data-explorer/spec/data_explorer_spec.rb+++ b/plugins/discourse-data-explorer/spec/data_explorer_spec.rb@@ -146,6 +146,32 @@ describe DiscourseDataExplorer::DataExplorer doexpect(result[:pg_result].to_a.map { |row| row["id"] }).to eq([topic.id, topic3.id].sort)end+ it "runs a query that checks a declared string parameter against IS NULL, with no cast needed" do+ query = DiscourseDataExplorer::Query.create!(name: "is null query", sql: <<~SQL)+ -- [params]+ -- string :site = hosted+ SELECT (:site) IS NULL AS is_null+ SQL++ result = described_class.run_query(query, { "site" => "hosted" })++ expect(result[:error]).to eq(nil)+ expect(result[:pg_result][0]["is_null"]).to eq(false)+ end++ it "still compares a declared date parameter against a timestamp column with no cast" do+ query = DiscourseDataExplorer::Query.create!(name: "date compare query", sql: <<~SQL)+ -- [params]+ -- date :start_date+ SELECT id FROM topics WHERE created_at >= :start_date ORDER BY id+ SQL++ result = described_class.run_query(query, { "start_date" => "2020-01-01" })++ expect(result[:error]).to eq(nil)+ expect(result[:pg_result].to_a.map { |row| row["id"] }).to include(topic.id)+ end+it "rejects, without executing, a parameter inside a dollar-quoted literal" doquery = DiscourseDataExplorer::Query.create!(name: "dollar query", sql: <<~SQL)-- [params]diff --git a/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rb b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rbindex 5254870626a..3e1aaa39e0d 100644--- a/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rb+++ b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rb@@ -350,7 +350,7 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider dopayload = result[query.id.to_s]expect(payload[:success]).to eq(true)- expect(payload[:rows]).to eq([["2026-01-01"]])+ expect(payload[:rows]).to eq([[Date.parse("2026-01-01")]])endend