ganncamp
(G Ann Campbell)
3월 5, 2025, 7:08오후
1
I have a Data Explorer query that accepts a ‘group_name’ parameter
I would like to automate running it for each relevant group and sending the group the results once a week.
But for the life of me, I cannot figure out the syntax to use for the parameter. Here’s what I’m presented for that in a brand new automation:
I find this… unhelpful.
I’ve tried several variations here. When I don’t get an error from my attempts (found in the error logs), I seem to get nothing at all.
If I use a query with no parameters, it runs like greased lightning. How do I make it work for queries that do need parameters?
2개의 좋아요
저도 해당 문제를 재현할 수 있습니다.
예를 들어, 질문하신 예시에서 moderators와 admins 그룹을 확인하려는 경우, 다음과 같이 설정해야 합니다:
키: group_name
값: moderators,admins
참고를 위한 기술적인 내용입니다. 무시하셔도 됩니다.
코드를 살펴보다가 여기 문제가 있는 것 같다고 생각합니다:
result = DataExplorer.run_query(query, params)
query.update!(last_run_at: Time.now)
return [] if opts[:skip_empty] && result[:pg_result].values.empty?
table =
ResultToMarkdown.convert(result[:pg_result], render_url_columns: opts[:render_url_columns])
build_report_pms(query, table, recipients, attach_csv: opts[:attach_csv], result:)
end
def self.generate_post(query_id, query_params, opts = {})
query = DiscourseDataExplorer::Query.find(query_id)
return {} if !query
params = params_to_hash(query_params)
result = DataExplorer.run_query(query, params)
query.update!(last_run_at: Time.now)
return {} if opts[:skip_empty] && result[:pg_result].values.empty?
build_report_post(query, table, attach_csv: opts[:attach_csv], result:)
end
def self.params_to_hash(query_params)
params = JSON.parse(query_params)
params.map { |p| p.is_a?(Hash) ? [p["key"], p["value"]] : p }.to_h
end
def self.build_report_pms(query, table = "", targets = [], attach_csv: false, result: nil)
pms = []
upload = create_csv_upload(query, result) if attach_csv
targets.each do |target|
name = target[0]
pm_type = "target_#{target[1]}s"
pm = {}
pm["title"] = I18n.t(
run_query가 호출되기 전에 파라미터가 변환됩니다.
다음과 같은 원래 값이 있다고 가정해 보겠습니다:
[{"key":"group_names","value":"admins,moderators"}]
변환된 값은 다음과 같습니다:
{{"key"=>"group_names", "value"=>"admins,moderators"}=>nil}
def self.run_query(query, req_params = {}, opts = {})
# Safety checks
# see test 'doesn't allow you to modify the database #2'
if query.sql =~ /;/
err = ValidationError.new(I18n.t("js.errors.explorer.no_semicolons"))
return { error: err, duration_nanos: 0 }
end
query_args = {}
begin
query_args = query.cast_params req_params
rescue ValidationError => e
return { error: e, duration_nanos: 0 }
end
time_start, time_end, explain, err, result = nil
begin
ActiveRecord::Base.connection.transaction do
# Setting transaction to read only prevents shoot-in-foot actions like SELECT FOR UPDATE
# see test 'doesn't allow you to modify the database #1'
DB.exec "SET TRANSACTION READ ONLY"
그러나 cast_params는 {"group_names"=>"admins,moderators"} 형식을 기대하는 것 같습니다.
이 단순한 변경 사항을 테스트해 보았더니 파라미터가 정상적으로 작동했습니다.
def self.params_to_hash(query_params)
params = JSON.parse(query_params)
params_hash = {}
params.each do |param|
key = param["key"]
value = param["value"]
params_hash[key] = value
end
params_hash
end
7개의 좋아요
sam
(Sam Saffron)
3월 6, 2025, 10:03오후
3
와, 디버깅 도와줘서 고마워요 다음 주에 이 부분을 확인해볼게요.
5개의 좋아요
ted
(Ted Johansson)
3월 13, 2025, 7:47오전
8
@Arkshine ! 정말 훌륭한 코드 탐사네요!
지금 이 부분을 확인하고 있습니다. 원본 코드를 읽어보니 파라미터가 배열의 배열(array of arrays) 형태를 기대하는 것 같은 인상을 받았습니다. 그래서 기존 코드를 단순히 제거하는 것은 조금 망설여집니다. 이런 상황이 언제 발생하는지 알아볼 예정입니다.
무언가 발견하면 여기서 공유하겠습니다.
1개의 좋아요
ted
(Ted Johansson)
3월 13, 2025, 10:01오전
9
실제로 여기에는 버그가 있었고, @Arkshine의 조사 덕분에 비교적 쉽게 수정할 수 있었습니다:
main ← fix/report-generator-parameters
merged 09:50AM - 13 Mar 25 UTC
### What is the problem?
When setting up an automation to create a DM or a po… st with a report on a recurring basis, and using a Data Explorer query that has parameters, we encounter an error.
### Why is this happening?
The `.params_to_hash` currently expects an array of arrays for the parameters, e.g.:
```ruby
[["group_name", "admins"]]
```
but in reality they seem to be arrays of hashes:
```ruby
[{ "key" => "group_name", "value" => "admins" }]
```
### How come we only found out now?
We do have tests for the report generator, and we do pass query parameters to it, but 1) we hard-code the parameters as an array of arrays and 2) the parameters aren't in the query used as a fixture.
### How does this fix it?
This change makes `ReportGenerator.params_to_hash` work with arrays of hashes. It also preserves the ability to work with nested arrays in case this is used somewhere else.
이미 병합(Merge)되었으므로, 사이트 배포가 완료되면 @ganncamp 님의 문제가 해결될 것입니다.
제 이해가 맞다면, 그룹과 그 리포트 간의 1:1 매핑이 되는 자동화를 원하시는 건가요? (즉, group_a는 group_a 데이터가 포함된 리포트를 받는 식으로)
현재 수신자 목록과 리포트 파라미터 사이에는 연결이 없으므로, 이를 달성하려면 그룹별로 자동화를 하나씩 설정해야 합니다. 이 경우 파라미터를 group_id로 변경하는 것이 좋을 수 있습니다.
3개의 좋아요
ganncamp
(G Ann Campbell)
3월 13, 2025, 11:51오전
11
좋은 소식입니다, @ted !
네, 그룹 집합에 대해 foreach를 사용할 수 있기를 제 다음 요청 사항으로 삼으려 했었습니다
3개의 좋아요
ted
(Ted Johansson)
3월 14, 2025, 2:19오전
12
정말 유용한 기능이네요. 특히 그룹이 매우 많은 사이트에서는 더욱 그렇습니다. 요청 사항을 기록해 두겠습니다. 다만, 언제 처리할 수 있을지는 말씀드리기 어렵습니다.
3개의 좋아요
j.jaffeux
(Joffrey Jaffeux)
에 닫힘
3월 17, 2025, 10:09오전
14
이 주제는 마지막 답변 후 3일 만에 자동으로 닫혔습니다. 더 이상 답변을 작성할 수 없습니다.