2022-10-09 21:03:37 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-03-22 17:29:08 -04:00
|
|
|
describe DiscourseDataExplorer::DataExplorer do
|
2022-12-29 07:31:29 -05:00
|
|
|
describe ".run_query" do
|
2022-10-09 21:03:37 -04:00
|
|
|
fab!(:topic) { Fabricate(:topic) }
|
|
|
|
|
2022-12-29 07:31:29 -05:00
|
|
|
it "should run a query that includes PG template patterns" do
|
2022-10-09 21:03:37 -04:00
|
|
|
sql = <<~SQL
|
|
|
|
WITH query AS (
|
|
|
|
SELECT TO_CHAR(created_at, 'yyyy:mm:dd') AS date FROM topics
|
|
|
|
) SELECT * FROM query
|
|
|
|
SQL
|
|
|
|
|
2023-03-22 17:29:08 -04:00
|
|
|
query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
|
2022-10-09 21:03:37 -04:00
|
|
|
|
|
|
|
result = described_class.run_query(query)
|
|
|
|
|
|
|
|
expect(result[:error]).to eq(nil)
|
|
|
|
expect(result[:pg_result][0]["date"]).to eq(topic.created_at.strftime("%Y:%m:%d"))
|
|
|
|
end
|
|
|
|
|
2022-12-29 07:31:29 -05:00
|
|
|
it "should run a query containing a question mark in the comment" do
|
2022-10-09 21:03:37 -04:00
|
|
|
sql = <<~SQL
|
|
|
|
WITH query AS (
|
|
|
|
SELECT id FROM topics -- some SQL ? comment ?
|
|
|
|
) SELECT * FROM query
|
|
|
|
SQL
|
|
|
|
|
2023-03-22 17:29:08 -04:00
|
|
|
query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
|
2022-10-09 21:03:37 -04:00
|
|
|
|
|
|
|
result = described_class.run_query(query)
|
|
|
|
|
|
|
|
expect(result[:error]).to eq(nil)
|
|
|
|
expect(result[:pg_result][0]["id"]).to eq(topic.id)
|
|
|
|
end
|
|
|
|
|
2022-12-29 07:31:29 -05:00
|
|
|
it "can run a query with params interpolation" do
|
2022-10-09 21:03:37 -04:00
|
|
|
topic2 = Fabricate(:topic)
|
|
|
|
|
|
|
|
sql = <<~SQL
|
|
|
|
-- [params]
|
|
|
|
-- int :topic_id = 99999999
|
|
|
|
WITH query AS (
|
|
|
|
SELECT
|
|
|
|
id,
|
|
|
|
TO_CHAR(created_at, 'yyyy:mm:dd') AS date
|
|
|
|
FROM topics
|
|
|
|
WHERE topics.id = :topic_id
|
|
|
|
) SELECT * FROM query
|
|
|
|
SQL
|
|
|
|
|
2023-03-22 17:29:08 -04:00
|
|
|
query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
|
2022-10-09 21:03:37 -04:00
|
|
|
|
|
|
|
result = described_class.run_query(query, { "topic_id" => topic2.id.to_s })
|
|
|
|
|
|
|
|
expect(result[:error]).to eq(nil)
|
|
|
|
expect(result[:pg_result].to_a.size).to eq(1)
|
|
|
|
expect(result[:pg_result][0]["id"]).to eq(topic2.id)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|