Skip to content

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

DEV: Move discourse-data-explorer to core (#33570)

Jarek Radosze65677f217cd
diff --git a/.github/labeler.yml b/.github/labeler.yml
index 5f1e061598f..ce7a26613e9 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -78,6 +78,10 @@ discourse-chat-integration:
- changed-files:
- any-glob-to-any-file: plugins/discourse-chat-integration/**/*
+discourse-data-explorer:
+ - changed-files:
+ - any-glob-to-any-file: plugins/discourse-data-explorer/**/*
+
footnote:
- changed-files:
- any-glob-to-any-file: plugins/footnote/**/*
diff --git a/.gitignore b/.gitignore
index 5c11d58cd13..15ec2b54586 100644
--- a/.gitignore
+++ b/.gitignore
@@ -62,6 +62,7 @@
!/plugins/discourse-rss-polling
!/plugins/discourse-math
!/plugins/discourse-chat-integration
+!/plugins/discourse-data-explorer
/plugins/*/auto_generated
/spec/fixtures/plugins/my_plugin/auto_generated
diff --git a/plugins/discourse-data-explorer/README.md b/plugins/discourse-data-explorer/README.md
new file mode 100644
index 00000000000..69e6959afcc
--- /dev/null
+++ b/plugins/discourse-data-explorer/README.md
@@ -0,0 +1,6 @@
+# Data Explorer Plugin
+
+This plugin allows admins to run SQL queries against the live Discourse database,
+including parameterized queries and formatting for several common column types.
+
+For more information, please see: https://meta.discourse.org/t/data-explorer-plugin/32566
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
new file mode 100644
index 00000000000..a395dcf0fc5
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
@@ -0,0 +1,236 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryController < ApplicationController
+ requires_plugin PLUGIN_NAME
+
+ before_action :set_group, only: %i[group_reports_index group_reports_show group_reports_run]
+ before_action :set_query, only: %i[group_reports_show group_reports_run show update]
+ before_action :ensure_admin
+
+ skip_before_action :check_xhr, only: %i[show group_reports_run run]
+ skip_before_action :ensure_admin,
+ only: %i[group_reports_index group_reports_show group_reports_run]
+
+ def index
+ queries = Query.where(hidden: false).order(:last_run_at, :name).includes(:groups).to_a
+
+ database_queries_ids = Query.pluck(:id)
+ Queries.default.each do |params|
+ attributes = params.last
+ next if database_queries_ids.include?(attributes["id"])
+ query = Query.new
+ query.id = attributes["id"]
+ query.sql = attributes["sql"]
+ query.name = attributes["name"]
+ query.description = attributes["description"]
+ query.user_id = Discourse::SYSTEM_USER_ID.to_s
+ queries << query
+ end
+
+ render_serialized queries, QuerySerializer, root: "queries"
+ end
+
+ def show
+ check_xhr unless params[:export]
+
+ if params[:export]
+ response.headers["Content-Disposition"] = "attachment; filename=#{@query.slug}.dcquery.json"
+ response.sending_file = true
+ end
+
+ return raise Discourse::NotFound if !guardian.user_can_access_query?(@query) || @query.hidden
+ render_serialized @query, QueryDetailsSerializer, root: "query"
+ end
+
+ def groups
+ render json: Group.all.select(:id, :name).as_json(only: %i[id name]), root: false
+ end
+
+ def group_reports_index
+ return raise Discourse::NotFound unless guardian.user_is_a_member_of_group?(@group)
+
+ respond_to do |format|
+ format.json do
+ queries = Query.for_group(@group)
+ render_serialized(queries, QuerySerializer, root: "queries")
+ end
+ end
+ end
+
+ def group_reports_show
+ if !guardian.group_and_user_can_access_query?(@group, @query) || @query.hidden
+ return raise Discourse::NotFound
+ end
+
+ respond_to do |format|
+ format.json do
+ query_group = QueryGroup.find_by(query_id: @query.id, group_id: @group.id)
+
+ render json: {
+ query: serialize_data(@query, QueryDetailsSerializer, root: nil),
+ query_group: serialize_data(query_group, QueryGroupSerializer, root: nil),
+ }
+ end
+ end
+ end
+
+ def group_reports_run
+ if !guardian.group_and_user_can_access_query?(@group, @query) || @query.hidden
+ return raise Discourse::NotFound
+ end
+
+ run
+ end
+
+ def create
+ query =
+ Query.create!(
+ params
+ .require(:query)
+ .permit(:name, :description, :sql)
+ .merge(user_id: current_user.id, last_run_at: Time.now),
+ )
+ group_ids = params.require(:query)[:group_ids]
+ group_ids&.each { |group_id| query.query_groups.find_or_create_by!(group_id: group_id) }
+ render_serialized query, QueryDetailsSerializer, root: "query"
+ end
+
+ def update
+ ActiveRecord::Base.transaction do
+ @query.update!(
+ params.require(:query).permit(:name, :sql, :description).merge(hidden: false),
+ )
+
+ group_ids = params.require(:query)[:group_ids]
+ QueryGroup.where.not(group_id: group_ids).where(query_id: @query.id).delete_all
+ group_ids&.each { |group_id| @query.query_groups.find_or_create_by!(group_id: group_id) }
+ end
+
+ render_serialized @query, QueryDetailsSerializer, root: "query"
+ rescue ValidationError => e
+ render_json_error e.message
+ end
+
+ def destroy
+ query = Query.where(id: params[:id]).first_or_initialize
+ query.update!(hidden: true)
+
+ render json: { success: true, errors: [] }
+ end
+
+ def schema
+ schema_version = DB.query_single("SELECT max(version) AS tag FROM schema_migrations").first
+ if stale?(public: true, etag: schema_version, template: false)
+ render json: DataExplorer.schema
+ end
+ end
+
+ # Return value:
+ # success - true/false. if false, inspect the errors value.
+ # errors - array of strings.
+ # params - hash. Echo of the query parameters as executed.
+ # duration - float. Time to execute the query, in milliseconds, to 1 decimal place.
+ # columns - array of strings. Titles of the returned columns, in order.
+ # explain - string. (Optional - pass explain=true in the request) Postgres query plan, UNIX newlines.
+ # rows - array of array of strings. Results of the query. In the same order as 'columns'.
+ def run
+ rate_limit_query_runs!
+
+ check_xhr unless params[:download]
+
+ query = Query.find(params[:id].to_i)
+ query.update!(last_run_at: Time.now)
+
+ response.sending_file = true if params[:download]
+
+ query_params = {}
+ query_params = MultiJson.load(params[:params]) if params[:params]
+
+ opts = { current_user: current_user&.username }
+ opts[:explain] = true if params[:explain] == "true"
+
+ opts[:limit] = if params[:format] == "csv"
+ if params[:limit].present?
+ limit = params[:limit].to_i
+ limit = QUERY_RESULT_MAX_LIMIT if limit > QUERY_RESULT_MAX_LIMIT
+ limit
+ else
+ QUERY_RESULT_MAX_LIMIT
+ end
+ elsif params[:limit].present?
+ params[:limit] == "ALL" ? "ALL" : params[:limit].to_i
+ end
+
+ result = DataExplorer.run_query(query, query_params, opts)
+
+ if result[:error]
+ err = result[:error]
+
+ # Pretty printing logic
+ err_class = err.class
+ err_msg = err.message
+ if err.is_a? ActiveRecord::StatementInvalid
+ err_class = err.original_exception.class
+ err_msg.gsub!("#{err_class}:", "")
+ else
+ err_msg = "#{err_class}: #{err_msg}"
+ end
+
+ render json: { success: false, errors: [err_msg] }, status: 422
+ else
+ content_disposition =
+ "attachment; filename=#{query.slug}@#{Slug.for(Discourse.current_hostname, "discourse")}-#{Date.today}.dcqresult"
+
+ respond_to do |format|
+ format.json do
+ response.headers["Content-Disposition"] = "#{content_disposition}.json" if params[
+ :download
+ ]
+
+ render json:
+ ResultFormatConverter.convert(
+ :json,
+ result,
+ query_params:,
+ download: params[:download],
+ explain: params[:explain] == "true",
+ )
+ end
+ format.csv do
+ response.headers["Content-Disposition"] = "#{content_disposition}.csv"
+
+ render plain: ResultFormatConverter.convert(:csv, result)
+ end
+ end
+ end
+ end
+
+ private
+
+ def rate_limit_query_runs!
+ return if !is_api? && !is_user_api?
+
+ RateLimiter.new(
+ nil,
+ "api-query-run-10-sec",
+ GlobalSetting.max_data_explorer_api_reqs_per_10_seconds,
+ 10.seconds,
+ ).performed!
+ rescue RateLimiter::LimitExceeded => e
+ if GlobalSetting.max_data_explorer_api_req_mode.include?("warn")
+ Discourse.warn("Query run 10 second rate limit exceeded", query_id: params[:id])
+ end
+ raise e if GlobalSetting.max_data_explorer_api_req_mode.include?("block")
+ end
+
+ def set_group
+ @group = Group.find_by(name: params["group_name"])
+ end
+
+ def set_query
+ @query = Query.find(params[:id])
+ raise Discourse::NotFound unless @query
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/jobs/scheduled/delete_hidden_queries.rb b/plugins/discourse-data-explorer/app/jobs/scheduled/delete_hidden_queries.rb
new file mode 100644
index 00000000000..6dac3add8d1
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/jobs/scheduled/delete_hidden_queries.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module Jobs
+ class DeleteHiddenQueries < ::Jobs::Scheduled
+ every 7.days
+
+ def execute(args)
+ return unless SiteSetting.data_explorer_enabled
+
+ DiscourseDataExplorer::Query
+ .where("id > 0")
+ .where(hidden: true)
+ .where(
+ "(last_run_at IS NULL OR last_run_at < :days_ago) AND updated_at < :days_ago",
+ days_ago: 7.days.ago,
+ )
+ .delete_all
+ end
+ end
+end
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
new file mode 100644
index 00000000000..bf23fb9a02d
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryFinder
+ def self.find(id)
+ default_query = Queries.default[id.to_s]
+ return raise ActiveRecord::RecordNotFound unless default_query
+
+ query = Query.find_by(id: id) || Query.new
+ query.attributes = default_query
+ query.user_id = Discourse::SYSTEM_USER_ID.to_s
+ query
+ end
+ end
+
+ class Query < ActiveRecord::Base
+ self.table_name = "data_explorer_queries"
+
+ has_many :query_groups
+ has_many :groups, through: :query_groups
+ belongs_to :user
+ validates :name, presence: true
+
+ scope :for_group,
+ ->(group) do
+ where(hidden: false).joins(
+ "INNER JOIN data_explorer_query_groups
+ ON data_explorer_query_groups.query_id = data_explorer_queries.id
+ AND data_explorer_query_groups.group_id = #{group.id}",
+ )
+ end
+
+ def params
+ @params ||= Parameter.create_from_sql(sql)
+ end
+
+ def cast_params(input_params)
+ result = {}.with_indifferent_access
+ self.params.each do |pobj|
+ result[pobj.identifier] = pobj.cast_to_ruby input_params[pobj.identifier]
+ end
+ result
+ end
+
+ def slug
+ Slug.for(name).presence || "query-#{id}"
+ end
+
+ def self.find(id)
+ return super if id.to_i >= 0
+ QueryFinder.find(id)
+ end
+
+ private
+
+ # for `Query.unscoped.find`
+ class ActiveRecord_Relation
+ def find(id)
+ return super if id.to_i >= 0
+ QueryFinder.find(id)
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: data_explorer_queries
+#
+# id :bigint not null, primary key
+# name :string
+# description :text
+# sql :text default("SELECT 1"), not null
+# user_id :integer
+# last_run_at :datetime
+# hidden :boolean default(FALSE), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+#
diff --git a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query_group.rb b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query_group.rb
new file mode 100644
index 00000000000..b261f1448ac
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query_group.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryGroup < ActiveRecord::Base
+ self.table_name = "data_explorer_query_groups"
+
+ belongs_to :query
+ belongs_to :group
+
+ has_many :bookmarks, as: :bookmarkable
+ end
+end
+
+# == Schema Information
+#
+# Table name: data_explorer_query_groups
+#
+# id :bigint not null, primary key
+# query_id :bigint
+# group_id :integer
+#
+# Indexes
+#
+# index_data_explorer_query_groups_on_group_id (group_id)
+# index_data_explorer_query_groups_on_query_id (query_id)
+# index_data_explorer_query_groups_on_query_id_and_group_id (query_id,group_id) UNIQUE
+#
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb
new file mode 100644
index 00000000000..d211777b9a0
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryDetailsSerializer < QuerySerializer
+ attributes :sql, :param_info, :created_at, :hidden
+
+ def param_info
+ object&.params&.uniq { |p| p.identifier }&.map(&:to_hash)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_group_bookmark_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_group_bookmark_serializer.rb
new file mode 100644
index 00000000000..3e45f70f4a2
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_group_bookmark_serializer.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryGroupBookmarkSerializer < UserBookmarkBaseSerializer
+ def title
+ fancy_title
+ end
+
+ def fancy_title
+ data_explorer_query.name
+ end
+
+ def cooked
+ data_explorer_query.description
+ end
+
+ def bookmarkable_user
+ @bookmarkable_user ||= data_explorer_query.user
+ end
+
+ def bookmarkable_url
+ "/g/#{data_explorer_query_group.group.name}/reports/#{data_explorer_query_group.query_id}"
+ end
+
+ def excerpt
+ return nil unless cooked
+ @excerpt ||= PrettyText.excerpt(cooked, 300, keep_emoji_images: true)
+ end
+
+ private
+
+ def data_explorer_query
+ data_explorer_query_group.query
+ end
+
+ def data_explorer_query_group
+ object.bookmarkable
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_group_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_group_serializer.rb
new file mode 100644
index 00000000000..a99c26d66d7
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_group_serializer.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryGroupSerializer < ActiveModel::Serializer
+ attributes :id, :group_id, :query_id, :bookmark
+
+ def query_group_bookmark
+ @query_group_bookmark ||= Bookmark.find_by(user: scope.user, bookmarkable: object)
+ end
+
+ def include_bookmark?
+ query_group_bookmark.present?
+ end
+
+ def bookmark
+ {
+ id: query_group_bookmark.id,
+ reminder_at: query_group_bookmark.reminder_at,
+ name: query_group_bookmark.name,
+ auto_delete_preference: query_group_bookmark.auto_delete_preference,
+ bookmarkable_id: query_group_bookmark.bookmarkable_id,
+ bookmarkable_type: query_group_bookmark.bookmarkable_type,
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_serializer.rb
new file mode 100644
index 00000000000..724e2556ea7
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_serializer.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QuerySerializer < ActiveModel::Serializer
+ attributes :id, :name, :description, :username, :group_ids, :last_run_at, :user_id
+
+ def username
+ object&.user&.username
+ end
+
+ def group_ids
+ object.groups.map(&:id)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/small_badge_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/small_badge_serializer.rb
new file mode 100644
index 00000000000..27679b0aceb
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/small_badge_serializer.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class DiscourseDataExplorer::SmallBadgeSerializer < ApplicationSerializer
+ attributes :id, :name, :display_name, :badge_type, :description, :icon
+end
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/small_post_with_excerpt_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/small_post_with_excerpt_serializer.rb
new file mode 100644
index 00000000000..1663de4d3c5
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/small_post_with_excerpt_serializer.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class SmallPostWithExcerptSerializer < ApplicationSerializer
+ attributes :id, :topic_id, :post_number, :excerpt, :username, :avatar_template
+
+ def excerpt
+ Post.excerpt(object.cooked, 70)
+ end
+
+ def username
+ object.user && object.user.username
+ end
+
+ def avatar_template
+ object.user && object.user.avatar_template
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/assets/javascripts/admin/adapters/query.js b/plugins/discourse-data-explorer/assets/javascripts/admin/adapters/query.js
new file mode 100644
index 00000000000..88c92e1d48c
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/admin/adapters/query.js
@@ -0,0 +1,3 @@
+import buildPluginAdapter from "admin/adapters/build-plugin";
+
+export default buildPluginAdapter("explorer").extend({});
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/code-view.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/code-view.gjs
new file mode 100644
index 00000000000..934a7fc07a2
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/code-view.gjs
@@ -0,0 +1,5 @@
+const CodeView = <template>
+ <pre><code class={{@codeClass}}>{{@value}}</code></pre>
+</template>;
+
+export default CodeView;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-bar-chart.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-bar-chart.gjs
new file mode 100644
index 00000000000..e38ce827b5b
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-bar-chart.gjs
@@ -0,0 +1,101 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { bind } from "discourse/lib/decorators";
+import loadScript from "discourse/lib/load-script";
+import themeColor from "../lib/themeColor";
+
+export default class DataExplorerBarChart extends Component {
+ chart;
+ barsColor = themeColor("--tertiary");
+ barsHoverColor = themeColor("--tertiary-high");
+ gridColor = themeColor("--primary-low");
+ labelsColor = themeColor("--primary-medium");
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.chart.destroy();
+ }
+
+ get config() {
+ const data = this.data;
+ const options = this.options;
+ return {
+ type: "bar",
+ data,
+ options,
+ };
+ }
+
+ get data() {
+ const labels = this.args.labels;
+ return {
+ labels,
+ datasets: [
+ {
+ label: this.args.datasetName,
+ data: this.args.values,
+ backgroundColor: this.barsColor,
+ hoverBackgroundColor: this.barsHoverColor,
+ },
+ ],
+ };
+ }
+
+ get options() {
+ return {
+ scales: {
+ legend: {
+ labels: {
+ fontColor: this.labelsColor,
+ },
+ },
+ xAxes: [
+ {
+ gridLines: {
+ color: this.gridColor,
+ zeroLineColor: this.gridColor,
+ },
+ ticks: {
+ fontColor: this.labelsColor,
+ },
+ },
+ ],
+ yAxes: [
+ {
+ gridLines: {
+ color: this.gridColor,
+ zeroLineColor: this.gridColor,
+ },
+ ticks: {
+ beginAtZero: true,
+ fontColor: this.labelsColor,
+ },
+ },
+ ],
+ },
+ };
+ }
+
+ @bind
+ async initChart(canvas) {
+ await loadScript("/javascripts/Chart.min.js");
+ const context = canvas.getContext("2d");
+ // eslint-disable-next-line
+ this.chart = new Chart(context, this.config);
+ }
+
+ @action
+ updateChartData() {
+ this.chart.data = this.data;
+ this.chart.update();
+ }
+
+ <template>
+ <canvas
+ {{didInsert this.initChart}}
+ {{on "change" this.updateChartData}}
+ ></canvas>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs
new file mode 100644
index 00000000000..fcbb9260f32
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs
@@ -0,0 +1,177 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { isBlank, isEmpty } from "@ember/utils";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import { debounce } from "discourse/lib/decorators";
+import OneTable from "./explorer-schema/one-table";
+
+export default class ExplorerSchema extends Component {
+ @tracked filter;
+ @tracked loading;
+ @tracked hideSchema = this.args.hideSchema;
+
+ get transformedSchema() {
+ const schema = this.args.schema;
+ for (const key in schema) {
+ if (!schema.hasOwnProperty(key)) {
+ continue;
+ }
+
+ schema[key].forEach((col) => {
+ const notes_components = [];
+ if (col.primary) {
+ notes_components.push("primary key");
+ }
+ if (col.is_nullable) {
+ notes_components.push("null");
+ }
+ if (col.column_default) {
+ notes_components.push("default " + col.column_default);
+ }
+ if (col.fkey_info) {
+ notes_components.push("fkey " + col.fkey_info);
+ }
+ if (col.denormal) {
+ notes_components.push("denormal " + col.denormal);
+ }
+ const notes = notes_components.join(", ");
+
+ if (notes) {
+ col.notes = notes;
+ }
+
+ if (col.enum || col.column_desc) {
+ col.havepopup = true;
+ }
+
+ col.havetypeinfo = !!(col.notes || col.enum || col.column_desc);
+ });
+ }
+ return schema;
+ }
+
+ get filteredTables() {
+ let tables = [];
+ let filter = this.filter;
+
+ try {
+ if (!isBlank(this.filter)) {
+ filter = new RegExp(this.filter);
+ }
+ } catch {
+ filter = null;
+ }
+
+ const haveFilter = !!filter;
+
+ for (const key in this.transformedSchema) {
+ if (!this.transformedSchema.hasOwnProperty(key)) {
+ continue;
+ }
+ if (!haveFilter) {
+ tables.push({
+ name: key,
+ columns: this.transformedSchema[key],
+ open: false,
+ });
+ continue;
+ }
+
+ // Check the table name vs the filter
+ if (filter.source === key || filter.source + "s" === key) {
+ tables.unshift({
+ name: key,
+ columns: this.transformedSchema[key],
+ open: haveFilter,
+ });
+ } else if (filter.test(key)) {
+ // whole table matches
+ tables.push({
+ name: key,
+ columns: this.transformedSchema[key],
+ open: haveFilter,
+ });
+ } else {
+ // filter the columns
+ let filterCols = [];
+ this.transformedSchema[key].forEach((col) => {
+ if (filter.source === col.column_name) {
+ filterCols.unshift(col);
+ } else if (filter.test(col.column_name)) {
+ filterCols.push(col);
+ }
+ });
+ if (!isEmpty(filterCols)) {
+ tables.push({
+ name: key,
+ columns: filterCols,
+ open: haveFilter,
+ });
+ }
+ }
+ }
+ return tables;
+ }
+
+ @debounce(500)
+ updateFilter(value) {
+ this.filter = value.toLowerCase();
+ this.loading = false;
+ }
+
+ @action
+ filterChanged(value) {
+ this.loading = true;
+ this.updateFilter(value);
+ }
+
+ @action
+ collapseSchema() {
+ this.hideSchema = true;
+ this.args.updateHideSchema(true);
+ }
+
+ @action
+ expandSchema() {
+ this.hideSchema = false;
+ this.args.updateHideSchema(false);
+ }
+
+ <template>
+ {{#if this.hideSchema}}
+ <DButton
+ @action={{this.expandSchema}}
+ @icon="chevron-left"
+ class="no-text unhide"
+ />
+ {{else}}
+ <div class="schema">
+ <div class="schema-search inline-form full-width">
+ <input
+ type="text"
+ {{! template-lint-disable no-action }}
+ {{on "input" (action "filterChanged" value="target.value")}}
+ />
+ <DButton
+ @action={{this.collapseSchema}}
+ @icon="chevron-right"
+ class="no-text"
+ />
+ </div>
+
+ <div class="schema-container">
+ <ConditionalLoadingSpinner @condition={{this.loading}}>
+ <ul>
+ {{#each this.filteredTables as |table|}}
+ <OneTable @table={{table}} />
+ {{/each}}
+ </ul>
+ </ConditionalLoadingSpinner>
+ </div>
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema/enum-info.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema/enum-info.gjs
new file mode 100644
index 00000000000..bbd7eae1c72
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema/enum-info.gjs
@@ -0,0 +1,20 @@
+import Component from "@glimmer/component";
+
+export default class EnumInfo extends Component {
+ get enuminfo() {
+ return Object.entries(this.args.col.enum).map(([value, name]) => ({
+ value,
+ name,
+ }));
+ }
+
+ <template>
+ <ol>
+ {{#each this.enuminfo as |enum|}}
+ <li value={{enum.value}}>
+ {{enum.name}}
+ </li>
+ {{/each}}
+ </ol>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema/one-table.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema/one-table.gjs
new file mode 100644
index 00000000000..85fb1c8ee36
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema/one-table.gjs
@@ -0,0 +1,78 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import icon from "discourse/helpers/d-icon";
+import { bind } from "discourse/lib/decorators";
+import { i18n } from "discourse-i18n";
+import EnumInfo from "./enum-info";
+
+export default class OneTable extends Component {
+ @tracked open = this.args.table.open;
+
+ get styles() {
+ return this.open ? "open" : "";
+ }
+
+ @bind
+ toggleOpen() {
+ this.open = !this.open;
+ }
+
+ <template>
+ <li class="schema-table {{this.styles}}">
+ {{! template-lint-enable no-invalid-interactive }}
+ <div
+ class="schema-table-name"
+ role="button"
+ {{on "click" this.toggleOpen}}
+ >
+ {{#if this.open}}
+ {{icon "caret-down"}}
+ {{else}}
+ {{icon "caret-right"}}
+ {{/if}}
+ {{@table.name}}
+ </div>
+
+ <div class="schema-table-cols">
+ {{#if this.open}}
+ <dl>
+ {{#each @table.columns as |col|}}
+ <div>
+ <dt
+ class={{if col.sensitive "sensitive"}}
+ title={{if col.sensitive (i18n "explorer.schema.sensitive")}}
+ >
+ {{#if col.sensitive}}
+ {{icon "triangle-exclamation"}}
+ {{/if}}
+ {{col.column_name}}
+ </dt>
+ <dd>
+ {{col.data_type}}
+ {{#if col.havetypeinfo}}
+ <br />
+ {{#if col.havepopup}}
+ <div class="popup-info">
+ {{icon "info"}}
+ <div class="popup">
+ {{col.column_desc}}
+ {{#if col.enum}}
+ <EnumInfo @col={{col}} />
+ {{/if}}
+ </div>
+ </div>
+ {{/if}}
+ <span class="schema-typenotes">
+ {{col.notes}}
+ </span>
+ {{/if}}
+ </dd>
+ </div>
+ {{/each}}
+ </dl>
+ {{/if}}
+ </div>
+ </li>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/modal/query-help.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/modal/query-help.gjs
new file mode 100644
index 00000000000..6d6daa3971a
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/modal/query-help.gjs
@@ -0,0 +1,19 @@
+import { htmlSafe } from "@ember/template";
+import DModal from "discourse/components/d-modal";
+import { i18n } from "discourse-i18n";
+
+const QueryHelp = <template>
+ <DModal
+ @title={{i18n "explorer.help.modal_title"}}
+ @closeModal={{@closeModal}}
+ >
+ <:body>
+ {{htmlSafe (i18n "explorer.help.auto_resolution")}}
+ {{htmlSafe (i18n "explorer.help.custom_params")}}
+ {{htmlSafe (i18n "explorer.help.default_values")}}
+ {{htmlSafe (i18n "explorer.help.data_types")}}
+ </:body>
+ </DModal>
+</template>;
+
+export default QueryHelp;
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
new file mode 100644
index 00000000000..da073aa6364
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input-form.gjs
@@ -0,0 +1,453 @@
+import Component from "@glimmer/component";
+import EmberObject, { action } from "@ember/object";
+import { service } from "@ember/service";
+import { dasherize } from "@ember/string";
+import { isEmpty } from "@ember/utils";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import Form from "discourse/components/form";
+import Category from "discourse/models/category";
+import { i18n } from "discourse-i18n";
+import BooleanThree from "./param-input/boolean-three";
+import CategoryIdInput from "./param-input/category-id-input";
+import GroupInput from "./param-input/group-input";
+import UserIdInput from "./param-input/user-id-input";
+import UserListInput from "./param-input/user-list-input";
+
+export class ParamValidationError extends Error {}
+
+const layoutMap = {
+ int: "int",
+ bigint: "string",
+ boolean: "boolean",
+ string: "string",
+ time: "time",
+ date: "date",
+ datetime: "datetime",
+ double: "string",
+ user_id: "user_id",
+ post_id: "string",
+ topic_id: "generic",
+ category_id: "category_id",
+ group_id: "group_list",
+ badge_id: "generic",
+ int_list: "generic",
+ string_list: "generic",
+ user_list: "user_list",
+ group_list: "group_list",
+};
+
+export const ERRORS = {
+ REQUIRED: i18n("form_kit.errors.required"),
+ NOT_AN_INTEGER: i18n("form_kit.errors.not_an_integer"),
+ NOT_A_NUMBER: i18n("form_kit.errors.not_a_number"),
+ OVERFLOW_HIGH: i18n("form_kit.errors.too_high", { count: 2147484647 }),
+ OVERFLOW_LOW: i18n("form_kit.errors.too_low", { count: -2147484648 }),
+ INVALID: i18n("explorer.form.errors.invalid"),
+ NO_SUCH_CATEGORY: i18n("explorer.form.errors.no_such_category"),
+ NO_SUCH_GROUP: i18n("explorer.form.errors.no_such_group"),
+ INVALID_DATE: (date) => i18n("explorer.form.errors.invalid_date", { date }),
+ INVALID_TIME: (time) => i18n("explorer.form.errors.invalid_time", { time }),
+};
+
+function digitalizeCategoryId(value) {
+ value = String(value || "");
+ const isPositiveInt = /^\d+$/.test(value);
+ if (!isPositiveInt && value.trim()) {
+ return Category.asyncFindBySlugPath(dasherize(value))
+ .then((res) => res.id)
+ .catch((err) => {
+ if (err.jqXHR?.status === 404) {
+ throw new ParamValidationError(
+ `${ERRORS.NO_SUCH_CATEGORY}: ${value}`
+ );
+ } else {
+ throw new Error(err.errorThrow || err.message);
+ }
+ });
+ }
+ return value;
+}
+
+function serializeValue(type, value) {
+ switch (type) {
+ case "string":
+ case "int":
+ return value != null ? String(value) : "";
+ case "boolean":
+ return String(value);
+ case "group_list":
+ case "user_list":
+ return value?.join(",");
+ case "group_id":
+ return value[0];
+ case "datetime":
+ return value?.replaceAll("T", " ");
+ default:
+ return value?.toString();
+ }
+}
+
+function validationOf(info) {
+ switch (layoutMap[info.type]) {
+ case "boolean":
+ return info.nullable ? "required" : "";
+ case "string":
+ case "string_list":
+ case "generic":
+ return info.nullable ? "" : "required:trim";
+ default:
+ return info.nullable ? "" : "required";
+ }
+}
+
+const components = {
+ int: <template>
+ <@field.Input @type="number" name={{@info.identifier}} />
+ </template>,
+ boolean: <template><@field.Checkbox name={{@info.identifier}} /></template>,
+ boolean_three: BooleanThree,
+ category_id: CategoryIdInput, // TODO
+ user_id: UserIdInput,
+ user_list: UserListInput,
+ group_list: GroupInput,
+ date: <template>
+ <@field.Input @type="date" name={{@info.identifier}} />
+ </template>,
+ time: <template>
+ <@field.Input @type="time" name={{@info.identifier}} />
+ </template>,
+ datetime: <template>
+ <@field.Input @type="datetime-local" name={{@info.identifier}} />
+ </template>,
+ default: <template><@field.Input name={{@info.identifier}} /></template>,
+};
+
+function componentOf(info) {
+ let type = layoutMap[info.type] || "generic";
+ if (info.nullable && type === "boolean") {
+ type = "boolean_three";
+ }
+ return components[type] || components.default;
+}
+
+export default class ParamInputForm extends Component {
+ @service site;
+
+ data = {};
+ paramInfo = [];
+ infoOf = {};
+ form = null;
+
+ promiseNormalizations = [];
+ formLoaded = new Promise((res) => {
+ this.__form_load_callback = res;
+ });
+
+ constructor() {
+ super(...arguments);
+ this.initializeParams();
+
+ this.args.onRegisterApi?.({
+ submit: this.submit,
+ allNormalized: Promise.allSettled(this.promiseNormalizations),
+ });
+ }
+
+ initializeParams() {
+ this.args.paramInfo.forEach((info) => {
+ const identifier = info.identifier;
+ const pinfo = this.createParamInfo(info);
+
+ this.paramInfo.push(pinfo);
+ this.infoOf[identifier] = info;
+
+ const normalized = this.getNormalizedValue(info);
+
+ if (normalized instanceof Promise) {
+ this.handlePromiseNormalization(normalized, pinfo);
+ } else {
+ this.data[identifier] = normalized;
+ }
+ });
+ }
+
+ createParamInfo(info) {
+ return EmberObject.create({
+ ...info,
+ validation: validationOf(info),
+ validate: this.validatorOf(info),
+ component: componentOf(info),
+ });
+ }
+
+ @action
+ async addError(identifier, message) {
+ await this.formLoaded;
+ this.form.addError(identifier, {
+ title: identifier,
+ message,
+ });
+ }
+
+ @action
+ normalizeValue(info, value) {
+ switch (info.type) {
+ case "category_id":
+ return digitalizeCategoryId(value);
+ case "boolean":
+ if (value == null || value === "#null") {
+ return info.nullable ? "#null" : false;
+ }
+ return value === "true";
+ case "group_id":
+ case "group_list":
+ const normalized = this.normalizeGroups(value);
+ if (normalized.errorMsg) {
+ this.addError(info.identifier, normalized.errorMsg);
+ }
+ return info.type === "group_id"
+ ? normalized.value.slice(0, 1)
+ : normalized.value;
+ case "user_list":
+ if (Array.isArray(value)) {
+ return value || null;
+ }
+ return value?.split(",") || null;
+ case "user_id":
+ if (Array.isArray(value)) {
+ return value[0];
+ }
+ return value;
+ case "date":
+ try {
+ if (!value) {
+ return null;
+ }
+ return moment(value).format("YYYY-MM-DD");
+ } catch {
+ this.addError(info.identifier, ERRORS.INVALID_DATE(String(value)));
+ return null;
+ }
+ case "time":
+ try {
+ if (!value) {
+ return null;
+ }
+ return moment(new Date(`1970/01/01 ${value}`).toISOString()).format(
+ "HH:mm"
+ );
+ } catch {
+ this.addError(info.identifier, ERRORS.INVALID_TIME(String(value)));
+ return null;
+ }
+ case "datetime":
+ try {
+ if (!value) {
+ return null;
+ }
+ return moment(new Date(value).toISOString()).format(
+ "YYYY-MM-DD HH:mm"
+ );
+ } catch {
+ this.addError(info.identifier, ERRORS.INVALID_TIME(String(value)));
+ return null;
+ }
+ default:
+ return value;
+ }
+ }
+
+ getNormalizedValue(info) {
+ const initialValues = this.args.initialValues;
+ const identifier = info.identifier;
+ return this.normalizeValue(
+ info,
+ initialValues && identifier in initialValues
+ ? initialValues[identifier]
+ : info.default
+ );
+ }
+
+ handlePromiseNormalization(promise, pinfo) {
+ this.promiseNormalizations.push(promise);
+ pinfo.set("loading", true);
+ this.data[pinfo.identifier] = null;
+
+ promise
+ .then((res) => this.form.set(pinfo.identifier, res))
+ .catch((err) => this.addError(pinfo.identifier, err.message))
+ .finally(() => pinfo.set("loading", false));
+ }
+
+ @action
+ normalizeGroups(values) {
+ values ||= [];
+ if (typeof values === "string") {
+ values = values.split(",");
+ }
+
+ const GroupNames = new Set(this.site.get("groups").map((g) => g.name));
+ const GroupNameOf = Object.fromEntries(
+ this.site.get("groups").map((g) => [g.id, g.name])
+ );
+
+ const valid_groups = [];
+ const invalid_groups = [];
+
+ for (const val of values) {
+ if (GroupNames.has(val)) {
+ valid_groups.push(val);
+ } else if (GroupNameOf[Number(val)]) {
+ valid_groups.push(GroupNameOf[Number(val)]);
+ } else {
+ invalid_groups.push(String(val));
+ }
+ }
+
+ return {
+ value: valid_groups,
+ errorMsg:
+ invalid_groups.length !== 0
+ ? `${ERRORS.NO_SUCH_GROUP}: ${invalid_groups.join(", ")}`
+ : null,
+ };
+ }
+
+ getErrorFn(info) {
+ const isPositiveInt = (value) => /^\d+$/.test(value);
+ const VALIDATORS = {
+ int: (value) => {
+ if (value >= 2147483648) {
+ return ERRORS.OVERFLOW_HIGH;
+ }
+ if (value <= -2147483649) {
+ return ERRORS.OVERFLOW_LOW;
+ }
+ return null;
+ },
+ bigint: (value) => {
+ if (isNaN(parseInt(value, 10))) {
+ return ERRORS.NOT_A_NUMBER;
+ }
+ return /^-?\d+$/.test(value) ? null : ERRORS.NOT_AN_INTEGER;
+ },
+ boolean: (value) => {
+ return /^Y|N|#null|true|false/.test(String(value))
+ ? null
+ : ERRORS.INVALID;
+ },
+ double: (value) => {
+ if (isNaN(parseFloat(value))) {
+ if (/^(-?)Inf(inity)?$/i.test(value) || /^(-?)NaN$/i.test(value)) {
+ return null;
+ }
+ return ERRORS.NOT_A_NUMBER;
+ }
+ return null;
+ },
+ int_list: (value) => {
+ return value.split(",").every((i) => /^(-?\d+|null)$/.test(i.trim()))
+ ? null
+ : ERRORS.INVALID;
+ },
+ post_id: (value) => {
+ return isPositiveInt(value) ||
+ /\d+\/\d+(\?u=.*)?$/.test(value) ||
+ /\/t\/[^/]+\/(\d+)(\?u=.*)?/.test(value)
+ ? null
+ : ERRORS.INVALID;
+ },
+ topic_id: (value) => {
+ return isPositiveInt(value) || /\/t\/[^/]+\/(\d+)/.test(value)
+ ? null
+ : ERRORS.INVALID;
+ },
+ category_id: (value) => {
+ return this.site.categoriesById.get(Number(value))
+ ? null
+ : ERRORS.NO_SUCH_CATEGORY;
+ },
+ group_list: (value) => {
+ return this.normalizeGroups(value).errorMsg;
+ },
+ group_id: (value) => {
+ return this.normalizeGroups(value).errorMsg;
+ },
+ };
+ return VALIDATORS[info.type] ?? (() => null);
+ }
+
+ validatorOf(info) {
+ const getError = this.getErrorFn(info);
+ return (name, value, { addError }) => {
+ // skip require validation for we have used them in @validation
+ if (isEmpty(value) || value == null) {
+ return;
+ }
+ const message = getError(value);
+ if (message != null) {
+ addError(name, { title: info.identifier, message });
+ }
+ };
+ }
+
+ @action
+ async submit() {
+ if (this.form == null) {
+ throw "No form";
+ }
+ this.serializedData = null;
+ await this.form.submit();
+ if (this.serializedData == null) {
+ throw new ParamValidationError("validation_failed");
+ } else {
+ return this.serializedData;
+ }
+ }
+
+ @action
+ onRegisterApi(form) {
+ this.__form_load_callback();
+ this.form = form;
+ }
+
+ @action
+ onSubmit(data) {
+ const serializedData = {};
+ for (const [id, val] of Object.entries(data)) {
+ serializedData[id] =
+ serializeValue(this.infoOf[id].type, val) ?? undefined;
+ }
+ this.serializedData = serializedData;
+ }
+
+ <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>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/boolean-three.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/boolean-three.gjs
new file mode 100644
index 00000000000..70951ca644c
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/boolean-three.gjs
@@ -0,0 +1,17 @@
+import { i18n } from "discourse-i18n";
+
+const BooleanThree = <template>
+ <@field.Select name={{@info.identifier}} as |select|>
+ <select.Option @value="Y">
+ {{i18n "explorer.types.bool.true"}}
+ </select.Option>
+ <select.Option @value="N">
+ {{i18n "explorer.types.bool.false"}}
+ </select.Option>
+ <select.Option @value="#null">
+ {{i18n "explorer.types.bool.null_"}}
+ </select.Option>
+ </@field.Select>
+</template>;
+
+export default BooleanThree;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/category-id-input.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/category-id-input.gjs
new file mode 100644
index 00000000000..e626a6bed35
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/category-id-input.gjs
@@ -0,0 +1,28 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import CategoryChooser from "select-kit/components/category-chooser";
+
+export default class CategoryIdInput extends Component {
+ // CategoryChooser will try to modify the value of value,
+ // triggering a setting-on-hash error. So we have to do the dirty work.
+ get data() {
+ return {
+ value: this.args.field.value,
+ };
+ }
+
+ <template>
+ <@field.Custom id={{@field.id}}>
+ <CategoryChooser
+ @value={{this.data.value}}
+ @onChange={{@field.set}}
+ @options={{hash
+ allowUncategorized=null
+ autoInsertNoneItem=true
+ none=true
+ }}
+ name={{@info.identifier}}
+ />
+ </@field.Custom>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/group-input.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/group-input.gjs
new file mode 100644
index 00000000000..b7f4f8a6321
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/group-input.gjs
@@ -0,0 +1,33 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import GroupChooser from "select-kit/components/group-chooser";
+
+export default class GroupInput extends Component {
+ @service site;
+
+ get allGroups() {
+ return this.site.get("groups");
+ }
+
+ get groupChooserOption() {
+ return this.args.info.type === "group_id"
+ ? {
+ maximum: 1,
+ }
+ : {};
+ }
+
+ <template>
+ <@field.Custom id={{@field.id}}>
+ <GroupChooser
+ @content={{this.allGroups}}
+ @value={{@field.value}}
+ @labelProperty="name"
+ @valueProperty="name"
+ @onChange={{@field.set}}
+ @options={{this.groupChooserOption}}
+ name={{@info.identifier}}
+ />
+ </@field.Custom>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/user-id-input.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/user-id-input.gjs
new file mode 100644
index 00000000000..afcaccb424e
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/user-id-input.gjs
@@ -0,0 +1,15 @@
+import { hash } from "@ember/helper";
+import EmailGroupUserChooser from "select-kit/components/email-group-user-chooser";
+
+const UserIdInput = <template>
+ <@field.Custom id={{@field.id}}>
+ <EmailGroupUserChooser
+ @value={{@field.value}}
+ @options={{hash maximum=1}}
+ @onChange={{@field.set}}
+ name={{@info.identifier}}
+ />
+ </@field.Custom>
+</template>;
+
+export default UserIdInput;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/user-list-input.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/user-list-input.gjs
new file mode 100644
index 00000000000..46961d9b5f8
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/param-input/user-list-input.gjs
@@ -0,0 +1,13 @@
+import EmailGroupUserChooser from "select-kit/components/email-group-user-chooser";
+
+const UserListInput = <template>
+ <@field.Custom id={{@field.id}}>
+ <EmailGroupUserChooser
+ @value={{@field.value}}
+ @onChange={{@field.set}}
+ name={{@info.identifier}}
+ />
+ </@field.Custom>
+</template>;
+
+export default UserListInput;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
new file mode 100644
index 00000000000..70b40443c6c
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
@@ -0,0 +1,419 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { schedule } from "@ember/runloop";
+import { service } from "@ember/service";
+import { capitalize } from "@ember/string";
+import DButton from "discourse/components/d-button";
+import { ajax } from "discourse/lib/ajax";
+import getURL from "discourse/lib/get-url";
+import Badge from "discourse/models/badge";
+import Category from "discourse/models/category";
+import I18n, { i18n } from "discourse-i18n";
+import DataExplorerBarChart from "./data-explorer-bar-chart";
+import QueryRowContent from "./query-row-content";
+import BadgeViewComponent from "./result-types/badge";
+import CategoryViewComponent from "./result-types/category";
+import GroupViewComponent from "./result-types/group";
+import HtmlViewComponent from "./result-types/html";
+import JsonViewComponent from "./result-types/json";
+import PostViewComponent from "./result-types/post";
+import ReltimeViewComponent from "./result-types/reltime";
+import TagGroupViewComponent from "./result-types/tag-group";
+import TextViewComponent from "./result-types/text";
+import TopicViewComponent from "./result-types/topic";
+import UrlViewComponent from "./result-types/url";
+import UserViewComponent from "./result-types/user";
+
+const VIEW_COMPONENTS = {
+ topic: TopicViewComponent,
+ text: TextViewComponent,
+ post: PostViewComponent,
+ reltime: ReltimeViewComponent,
+ badge: BadgeViewComponent,
+ url: UrlViewComponent,
+ user: UserViewComponent,
+ group: GroupViewComponent,
+ html: HtmlViewComponent,
+ json: JsonViewComponent,
+ category: CategoryViewComponent,
+ tag_group: TagGroupViewComponent,
+};
+
+export default class QueryResult extends Component {
+ @service site;
+
+ @tracked chartDisplayed = false;
+
+ get colRender() {
+ return this.args.content.colrender || {};
+ }
+
+ get rows() {
+ return this.args.content.rows;
+ }
+
+ get columns() {
+ return this.args.content.columns;
+ }
+
+ get params() {
+ return this.args.content.params;
+ }
+
+ get explainText() {
+ return this.args.content.explain;
+ }
+
+ get chartDatasetName() {
+ return this.columnNames[1];
+ }
+
+ get columnNames() {
+ if (!this.columns) {
+ return [];
+ }
+ return this.columns.map((colName) => {
+ if (colName.endsWith("_id")) {
+ return colName.slice(0, -3);
+ }
+ const dIdx = colName.indexOf("$");
+ if (dIdx >= 0) {
+ return colName.substring(dIdx + 1);
+ }
+ return colName;
+ });
+ }
+
+ get columnComponents() {
+ if (!this.columns) {
+ return [];
+ }
+ return this.columns.map((_, idx) => {
+ let type = "text";
+ if (this.colRender[idx]) {
+ type = this.colRender[idx];
+ }
+ return { name: type, component: VIEW_COMPONENTS[type] };
+ });
+ }
+
+ get chartValues() {
+ // return an array with the second value of this.row
+ return this.rows.mapBy(1);
+ }
+
+ get colCount() {
+ return this.columns.length;
+ }
+
+ get resultCount() {
+ const count = this.args.content.result_count;
+ if (count === this.args.content.default_limit) {
+ return i18n("explorer.max_result_count", { count });
+ } else {
+ return i18n("explorer.result_count", { count });
+ }
+ }
+
+ get duration() {
+ return i18n("explorer.run_time", {
+ value: I18n.toNumber(this.args.content.duration, { precision: 1 }),
+ });
+ }
+
+ get parameterAry() {
+ let arr = [];
+ for (let key in this.params) {
+ if (this.params.hasOwnProperty(key)) {
+ arr.push({ key, value: this.params[key] });
+ }
+ }
+ return arr;
+ }
+
+ get transformedUserTable() {
+ return transformedRelTable(this.args.content.relations.user);
+ }
+
+ get transformedBadgeTable() {
+ return transformedRelTable(this.args.content.relations.badge, Badge);
+ }
+
+ get transformedPostTable() {
+ return transformedRelTable(this.args.content.relations.post);
+ }
+
+ get transformedTopicTable() {
+ return transformedRelTable(this.args.content.relations.topic);
+ }
+
+ get transformedTagGroupTable() {
+ return transformedRelTable(this.args.content.relations.tag_group);
+ }
+
+ get transformedGroupTable() {
+ return transformedRelTable(this.site.groups);
+ }
+
+ get canShowChart() {
+ const hasTwoColumns = this.colCount === 2;
+ const secondColumnContainsNumber =
+ this.resultCount[0] > 0 && typeof this.rows[0][1] === "number";
+ const secondColumnContainsId = this.colRender[1];
+
+ return (
+ hasTwoColumns && secondColumnContainsNumber && !secondColumnContainsId
+ );
+ }
+
+ get chartLabels() {
+ const labelSelectors = {
+ user: (user) => user.username,
+ badge: (badge) => badge.name,
+ topic: (topic) => topic.title,
+ group: (group) => group.name,
+ category: (category) => category.name,
+ };
+
+ const relationName = this.colRender[0];
+ if (relationName) {
+ const lookupFunc = this[`lookup${capitalize(relationName)}`];
+ const labelSelector = labelSelectors[relationName];
+
+ if (lookupFunc && labelSelector) {
+ return this.rows.map((r) => {
+ const relation = lookupFunc.call(this, r[0]);
+ const label = labelSelector(relation);
+ return this._cutChartLabel(label);
+ });
+ }
+ }
+
+ return this.rows.map((r) => this._cutChartLabel(r[0]));
+ }
+
+ lookupUser(id) {
+ return this.transformedUserTable[id];
+ }
+
+ lookupBadge(id) {
+ return this.transformedBadgeTable[id];
+ }
+
+ lookupPost(id) {
+ return this.transformedPostTable[id];
+ }
+
+ lookupTopic(id) {
+ return this.transformedTopicTable[id];
+ }
+
+ lookupTagGroup(id) {
+ return this.transformedTagGroupTable[id];
+ }
+
+ lookupGroup(id) {
+ return this.transformedGroupTable[id];
+ }
+
+ lookupCategory(id) {
+ return Category.findById(id);
+ }
+
+ _cutChartLabel(label) {
+ const labelString = label.toString();
+ if (labelString.length > 25) {
+ return `${labelString.substring(0, 25)}...`;
+ } else {
+ return labelString;
+ }
+ }
+
+ @action
+ downloadResultJson() {
+ this._downloadResult("json");
+ }
+
+ @action
+ downloadResultCsv() {
+ this._downloadResult("csv");
+ }
+
+ @action
+ showChart() {
+ this.chartDisplayed = true;
+ }
+
+ @action
+ hideChart() {
+ this.chartDisplayed = false;
+ }
+
+ _download_url() {
+ return this.args.group
+ ? `/g/${this.args.group.name}/reports/`
+ : "/admin/plugins/explorer/queries/";
+ }
+
+ _downloadResult(format) {
+ // Create a frame to submit the form in (?)
+ // to avoid leaving an about:blank behind
+ let windowName = randomIdShort();
+ const newWindowContents =
+ "<style>body{font-size:36px;display:flex;justify-content:center;align-items:center;}</style><body>Click anywhere to close this window once the download finishes.<script>window.onclick=function(){window.close()};</script>";
+
+ window.open("data:text/html;base64," + btoa(newWindowContents), windowName);
+
+ let form = document.createElement("form");
+ form.setAttribute("id", "query-download-result");
+ form.setAttribute("method", "post");
+ form.setAttribute(
+ "action",
+ getURL(
+ this._download_url() +
+ this.args.query.id +
+ "/run." +
+ format +
+ "?download=1"
+ )
+ );
+ form.setAttribute("target", windowName);
+ form.setAttribute("style", "display:none;");
+
+ function addInput(name, value) {
+ let field;
+ field = document.createElement("input");
+ field.setAttribute("name", name);
+ field.setAttribute("value", value);
+ form.appendChild(field);
+ }
+
+ addInput("params", JSON.stringify(this.params));
+ addInput("explain", this.explainText);
+ addInput("limit", "1000000");
+
+ ajax("/session/csrf.json").then((csrf) => {
+ addInput("authenticity_token", csrf.csrf);
+
+ document.body.appendChild(form);
+ form.submit();
+ schedule("afterRender", () => document.body.removeChild(form));
+ });
+ }
+
+ <template>
+ <article>
+ <header class="result-header">
+ <div class="result-info">
+ <DButton
+ @action={{this.downloadResultJson}}
+ @icon="download"
+ @label="explorer.download_json"
+ />
+
+ <DButton
+ @action={{this.downloadResultCsv}}
+ @icon="download"
+ @label="explorer.download_csv"
+ />
+
+ {{#if this.canShowChart}}
+ {{#if this.chartDisplayed}}
+ <DButton
+ @action={{this.hideChart}}
+ @icon="table"
+ @label="explorer.show_table"
+ />
+ {{else}}
+ <DButton
+ @action={{this.showChart}}
+ @icon="chart-bar"
+ @label="explorer.show_graph"
+ />
+ {{/if}}
+ {{/if}}
+ </div>
+
+ <div class="result-about">
+ {{this.resultCount}}
+ {{this.duration}}
+ </div>
+
+ <br />
+
+ {{~#if this.explainText}}
+ <pre class="result-explain">
+ <code>
+ {{~this.explainText}}
+ </code>
+ </pre>
+ {{~/if}}
+
+ <br />
+ </header>
+
+ <section>
+ {{#if this.chartDisplayed}}
+ <DataExplorerBarChart
+ @labels={{this.chartLabels}}
+ @values={{this.chartValues}}
+ @datasetName={{this.chartDatasetName}}
+ />
+ {{else}}
+ <table>
+ <thead>
+ <tr class="headers">
+ {{#each this.columnNames as |col|}}
+ <th>{{col}}</th>
+ {{/each}}
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.rows as |row|}}
+ <QueryRowContent
+ @row={{row}}
+ @columnComponents={{this.columnComponents}}
+ @lookupUser={{this.lookupUser}}
+ @lookupBadge={{this.lookupBadge}}
+ @lookupPost={{this.lookupPost}}
+ @lookupTopic={{this.lookupTopic}}
+ @lookupTagGroup={{this.lookupTagGroup}}
+ @lookupGroup={{this.lookupGroup}}
+ @lookupCategory={{this.lookupCategory}}
+ @transformedPostTable={{this.transformedPostTable}}
+ @transformedBadgeTable={{this.transformedBadgeTable}}
+ @transformedUserTable={{this.transformedUserTable}}
+ @transformedTagGroupTable={{this.transformedTagGroupTable}}
+ @transformedGroupTable={{this.transformedGroupTable}}
+ @transformedTopicTable={{this.transformedTopicTable}}
+ @site={{this.site}}
+ />
+ {{/each}}
+ </tbody>
+ </table>
+ {{/if}}
+ </section>
+ </article>
+ </template>
+}
+
+function randomIdShort() {
+ return "xxxxxxxx".replace(/[xy]/g, () => {
+ /*eslint-disable*/
+ return ((Math.random() * 16) | 0).toString(16);
+ /*eslint-enable*/
+ });
+}
+
+function transformedRelTable(table, modelClass) {
+ const result = {};
+ table?.forEach((item) => {
+ if (modelClass) {
+ result[item.id] = modelClass.create(item);
+ } else {
+ result[item.id] = item;
+ }
+ });
+ return result;
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs
new file mode 100644
index 00000000000..2d8ff905804
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs
@@ -0,0 +1,17 @@
+import QueryResult from "./query-result";
+
+const QueryResultsWrapper = <template>
+ {{#if @results}}
+ <div class="query-results">
+ {{#if @showResults}}
+ <QueryResult @query={{@query}} @content={{@results}} />
+ {{else}}
+ {{#each @results.errors as |err|}}
+ <pre class="query-error"><code>{{~err}}</code></pre>
+ {{/each}}
+ {{/if}}
+ </div>
+ {{/if}}
+</template>;
+
+export default QueryResultsWrapper;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-row-content.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-row-content.gjs
new file mode 100644
index 00000000000..bf7e4767fd2
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-row-content.gjs
@@ -0,0 +1,82 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { classify } from "@ember/string";
+import getURL from "discourse/lib/get-url";
+import { escapeExpression } from "discourse/lib/utilities";
+import TextViewComponent from "./result-types/text";
+
+export default class QueryRowContent extends Component {
+ @cached
+ get results() {
+ return this.args.columnComponents.map((componentDefinition, idx) => {
+ const value = this.args.row[idx],
+ id = parseInt(value, 10);
+
+ const ctx = {
+ value,
+ id,
+ baseuri: getURL(""),
+ };
+
+ if (this.args.row[idx] === null) {
+ return {
+ component: TextViewComponent,
+ textValue: "NULL",
+ };
+ } else if (componentDefinition.name === "text") {
+ return {
+ component: TextViewComponent,
+ textValue: escapeExpression(this.args.row[idx].toString()),
+ };
+ }
+
+ const lookupFunc =
+ this.args[`lookup${classify(componentDefinition.name)}`];
+ if (lookupFunc) {
+ ctx[componentDefinition.name] = lookupFunc.call(this.args, id);
+ }
+
+ if (componentDefinition.name === "url") {
+ let [url, name] = guessUrl(value);
+ ctx["href"] = url;
+ ctx["target"] = name;
+ }
+
+ try {
+ return {
+ component: componentDefinition.component || TextViewComponent,
+ ctx,
+ };
+ } catch {
+ return "error";
+ }
+ });
+ }
+
+ <template>
+ <tr>
+ {{#each this.results as |result|}}
+ <td>
+ <result.component
+ @ctx={{result.ctx}}
+ @params={{result.params}}
+ @textValue={{result.textValue}}
+ />
+ </td>
+ {{/each}}
+ </tr>
+ </template>
+}
+
+function guessUrl(columnValue) {
+ let [dest, name] = [columnValue, columnValue];
+
+ const split = columnValue.split(/,(.+)/);
+
+ if (split.length > 1) {
+ name = split[0];
+ dest = split[1];
+ }
+
+ return [dest, name];
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/badge.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/badge.gjs
new file mode 100644
index 00000000000..f51b5769dd6
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/badge.gjs
@@ -0,0 +1,31 @@
+import Component from "@glimmer/component";
+import { htmlSafe } from "@ember/template";
+import { isEmpty } from "@ember/utils";
+import { convertIconClass, iconHTML } from "discourse/lib/icon-library";
+
+export default class Badge extends Component {
+ get iconOrImageReplacement() {
+ if (isEmpty(this.args.ctx.badge.icon)) {
+ return "";
+ }
+
+ if (this.args.ctx.badge.icon.indexOf("fa-") > -1) {
+ const icon = iconHTML(convertIconClass(this.args.ctx.badge.icon));
+ return htmlSafe(icon);
+ } else {
+ return htmlSafe("<img src='" + this.args.ctx.badge.icon + "'>");
+ }
+ }
+
+ <template>
+ <a
+ href="{{@ctx.baseuri}}/badges/{{@ctx.badge.id}}/{{@ctx.badge.name}}"
+ class="user-badge {{@ctx.badge.badgeTypeClassName}}"
+ title={{@ctx.badge.display_name}}
+ data-badge-name={{@ctx.badge.name}}
+ >
+ {{this.iconOrImageReplacement}}
+ <span class="badge-display-name">{{@ctx.badge.display_name}}</span>
+ </a>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/category.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/category.gjs
new file mode 100644
index 00000000000..fdbc0430a17
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/category.gjs
@@ -0,0 +1,18 @@
+import Component from "@glimmer/component";
+import { categoryLinkHTML } from "discourse/helpers/category-link";
+
+export default class Category extends Component {
+ get categoryBadgeReplacement() {
+ return categoryLinkHTML(this.args.ctx.category, {
+ allowUncategorized: true,
+ });
+ }
+
+ <template>
+ {{#if @ctx.category}}
+ {{this.categoryBadgeReplacement}}
+ {{else}}
+ <a href="{{@ctx.baseuri}}/t/{{@ctx.id}}">{{@ctx.id}}</a>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/group.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/group.gjs
new file mode 100644
index 00000000000..941f70228f2
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/group.gjs
@@ -0,0 +1,11 @@
+const Group = <template>
+ {{#if @ctx.group}}
+ <a
+ href="{{@ctx.baseuri}}/groups/{{@ctx.group.name}}"
+ >{{@ctx.group.name}}</a>
+ {{else}}
+ {{@ctx.id}}
+ {{/if}}
+</template>;
+
+export default Group;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/html.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/html.gjs
new file mode 100644
index 00000000000..8f595a078f1
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/html.gjs
@@ -0,0 +1,5 @@
+import htmlSafe from "discourse/helpers/html-safe";
+
+const Html = <template>{{htmlSafe @ctx.value}}</template>;
+
+export default Html;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/json.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/json.gjs
new file mode 100644
index 00000000000..5ed68dc931b
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/json.gjs
@@ -0,0 +1,45 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import FullscreenCodeModal from "discourse/components/modal/fullscreen-code";
+
+export default class Json extends Component {
+ @service dialog;
+ @service modal;
+
+ @cached
+ get parsedJson() {
+ try {
+ return JSON.parse(this.args.ctx.value);
+ } catch {
+ return null;
+ }
+ }
+
+ @action
+ viewJson() {
+ this.modal.show(FullscreenCodeModal, {
+ model: {
+ code: this.parsedJson
+ ? JSON.stringify(this.parsedJson, null, 2)
+ : this.args.ctx.value,
+ codeClasses: "",
+ },
+ });
+ }
+
+ <template>
+ <div class="result-json">
+ <div class="result-json-value">{{@ctx.value}}</div>
+ <DButton
+ class="result-json-button"
+ {{! template-lint-disable no-action }}
+ @action={{action "viewJson"}}
+ @icon="ellipsis"
+ @title="explorer.view_json"
+ />
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/post.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/post.gjs
new file mode 100644
index 00000000000..b9419d219db
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/post.gjs
@@ -0,0 +1,41 @@
+import avatar from "discourse/helpers/avatar";
+import htmlSafe from "discourse/helpers/html-safe";
+
+const Post = <template>
+ {{#if @ctx.post}}
+ <aside
+ class="quote"
+ data-post={{@ctx.post.post_number}}
+ data-topic={{@ctx.post.topic_id}}
+ >
+ <div class="title">
+ <div class="quote-controls">
+ {{! template-lint-disable no-invalid-link-text }}
+ <a
+ href="/t/via-quote/{{@ctx.post.topic_id}}/{{@ctx.post.post_number}}"
+ title="go to the quoted post"
+ class="quote-other-topic"
+ >
+ </a>
+ </div>
+
+ <a
+ class="result-post-link"
+ href="/t/{{@ctx.post.topic_id}}/{{@ctx.post.post_number}}"
+ >
+ {{avatar @ctx.post imageSize="tiny"}}{{@ctx.post.username}}:
+ </a>
+ </div>
+
+ <blockquote>
+ <p>
+ {{htmlSafe @ctx.post.excerpt}}
+ </p>
+ </blockquote>
+ </aside>
+ {{else}}
+ {{@ctx.id}}
+ {{/if}}
+</template>;
+
+export default Post;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/reltime.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/reltime.gjs
new file mode 100644
index 00000000000..c44a61d1419
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/reltime.gjs
@@ -0,0 +1,13 @@
+import Component from "@glimmer/component";
+import { htmlSafe } from "@ember/template";
+import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
+
+export default class Reltime extends Component {
+ get boundDateReplacement() {
+ return htmlSafe(
+ autoUpdatingRelativeAge(new Date(this.args.ctx.value), { title: true })
+ );
+ }
+
+ <template>{{this.boundDateReplacement}}</template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/tag-group.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/tag-group.gjs
new file mode 100644
index 00000000000..177d10f4e2a
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/tag-group.gjs
@@ -0,0 +1,11 @@
+const Group = <template>
+ {{#if @ctx.tag_group}}
+ <a
+ href="{{@ctx.baseuri}}/tag_groups/{{@ctx.id}}"
+ >{{@ctx.tag_group.name}}</a>
+ {{else}}
+ {{@ctx.id}}
+ {{/if}}
+</template>;
+
+export default Group;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/text.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/text.gjs
new file mode 100644
index 00000000000..895ec2c2cbe
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/text.gjs
@@ -0,0 +1,3 @@
+const Text = <template>{{@textValue}}</template>;
+
+export default Text;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/topic.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/topic.gjs
new file mode 100644
index 00000000000..52402e40771
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/topic.gjs
@@ -0,0 +1,14 @@
+import htmlSafe from "discourse/helpers/html-safe";
+
+const Topic = <template>
+ {{#if @ctx.topic}}
+ <a href="{{@ctx.baseuri}}/t/{{@ctx.topic.slug}}/{{@ctx.topic.id}}">
+ {{htmlSafe @ctx.topic.fancy_title}}
+ </a>
+ ({{@ctx.topic.posts_count}})
+ {{else}}
+ <a href="{{@ctx.baseuri}}/t/{{@ctx.id}}">{{@ctx.id}}</a>
+ {{/if}}
+</template>;
+
+export default Topic;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/url.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/url.gjs
new file mode 100644
index 00000000000..ecfecd939f7
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/url.gjs
@@ -0,0 +1,5 @@
+const Url = <template>
+ <a href={{@ctx.href}}>{{@ctx.target}}</a>
+</template>;
+
+export default Url;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/user.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/user.gjs
new file mode 100644
index 00000000000..cba791674f8
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/result-types/user.gjs
@@ -0,0 +1,17 @@
+import avatar from "discourse/helpers/avatar";
+
+const User = <template>
+ {{#if @ctx.user}}
+ <a
+ href="{{@ctx.baseuri}}/u/{{@ctx.user.username}}/activity"
+ data-user-card={{@ctx.user.username}}
+ >
+ {{avatar @ctx.user imageSize="tiny"}}
+ {{@ctx.user.username}}
+ </a>
+ {{else}}
+ {{@ctx.id}}
+ {{/if}}
+</template>;
+
+export default User;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/share-report.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/share-report.gjs
new file mode 100644
index 00000000000..28a50d45d76
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/share-report.gjs
@@ -0,0 +1,101 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
+import DButton from "discourse/components/d-button";
+import icon from "discourse/helpers/d-icon";
+import { bind } from "discourse/lib/decorators";
+import getURL from "discourse/lib/get-url";
+import { i18n } from "discourse-i18n";
+
+export default class ShareReport extends Component {
+ @tracked visible = false;
+ element;
+
+ get link() {
+ return getURL(`/g/${this.args.group}/reports/${this.args.query.id}`);
+ }
+
+ @bind
+ mouseDownHandler(e) {
+ if (!this.element.contains(e.target)) {
+ this.close();
+ }
+ }
+
+ @bind
+ keyDownHandler(e) {
+ if (e.keyCode === 27) {
+ this.close();
+ }
+ }
+
+ @action
+ registerListeners(element) {
+ if (!element || this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.element = element;
+ document.addEventListener("mousedown", this.mouseDownHandler);
+ element.addEventListener("keydown", this.keyDownHandler);
+ }
+
+ @action
+ unregisterListeners(element) {
+ this.element = element;
+ document.removeEventListener("mousedown", this.mouseDownHandler);
+ element.removeEventListener("keydown", this.keyDownHandler);
+ }
+
+ @action
+ focusInput(e) {
+ e.select();
+ e.focus();
+ }
+
+ @action
+ open(e) {
+ e.preventDefault();
+ this.visible = true;
+ }
+
+ @action
+ close() {
+ this.visible = false;
+ }
+
+ <template>
+ <div class="share-report">
+ <a href="#" {{on "click" this.open}} class="share-report-button">
+ {{icon "link"}}
+ {{@group}}
+ </a>
+
+ {{#if this.visible}}
+ <div
+ class="popup"
+ {{didInsert this.registerListeners}}
+ {{willDestroy this.unregisterListeners}}
+ >
+ <label>{{i18n "explorer.link"}} {{@group}}</label>
+ <input
+ type="text"
+ value={{this.link}}
+ {{didInsert this.focusInput}}
+ />
+
+ <DButton
+ @action={{this.close}}
+ @icon="xmark"
+ @aria-label="share.close"
+ @title="share.close"
+ class="btn-flat close"
+ />
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/connectors/group-reports-nav-item/nav-item.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/connectors/group-reports-nav-item/nav-item.gjs
new file mode 100644
index 00000000000..64ffd843d25
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/connectors/group-reports-nav-item/nav-item.gjs
@@ -0,0 +1,19 @@
+import Component from "@ember/component";
+import { LinkTo } from "@ember/routing";
+import { classNames, tagName } from "@ember-decorators/component";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+@tagName("li")
+@classNames("group-reports-nav-item-outlet", "nav-item")
+export default class NavItem extends Component {
+ static shouldRender(args) {
+ return args.group.has_visible_data_explorer_queries;
+ }
+
+ <template>
+ <LinkTo @route="group.reports">
+ {{icon "chart-bar"}}{{i18n "group.reports"}}
+ </LinkTo>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins-explorer-index.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins-explorer-index.js
new file mode 100644
index 00000000000..3a64d5d1f9d
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins-explorer-index.js
@@ -0,0 +1,187 @@
+import { tracked } from "@glimmer/tracking";
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { Promise } from "rsvp";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { bind } from "discourse/lib/decorators";
+import { i18n } from "discourse-i18n";
+
+export default class PluginsExplorerController extends Controller {
+ @service dialog;
+ @service appEvents;
+ @service router;
+
+ @tracked sortByProperty = "last_run_at";
+ @tracked sortDescending = true;
+ @tracked params;
+ @tracked search;
+ @tracked newQueryName;
+ @tracked showCreate;
+ @tracked loading = false;
+
+ queryParams = ["id"];
+ explain = false;
+ acceptedImportFileTypes = ["application/json"];
+ order = null;
+ form = null;
+
+ get sortedQueries() {
+ const sortedQueries = this.model.sortBy(this.sortByProperty);
+ return this.sortDescending ? sortedQueries.reverse() : sortedQueries;
+ }
+
+ get parsedParams() {
+ return this.params ? JSON.parse(this.params) : null;
+ }
+
+ get filteredContent() {
+ const regexp = new RegExp(this.search, "i");
+ return this.sortedQueries.filter(
+ (result) => regexp.test(result.name) || regexp.test(result.description)
+ );
+ }
+
+ get createDisabled() {
+ return (this.newQueryName || "").trim().length === 0;
+ }
+
+ addCreatedRecord(record) {
+ this.model.pushObject(record);
+ this.router.transitionTo(
+ "adminPlugins.explorer.queries.details",
+ record.id
+ );
+ }
+
+ async _importQuery(file) {
+ const json = await this._readFileAsTextAsync(file);
+ const query = this._parseQuery(json);
+ const record = this.store.createRecord("query", query);
+ const response = await record.save();
+ return response.target;
+ }
+
+ _parseQuery(json) {
+ const parsed = JSON.parse(json);
+ const query = parsed.query;
+ if (!query || !query.sql) {
+ throw new TypeError();
+ }
+ query.id = 0; // 0 means no Id yet
+ return query;
+ }
+
+ _readFileAsTextAsync(file) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ resolve(reader.result);
+ };
+ reader.onerror = reject;
+
+ reader.readAsText(file);
+ });
+ }
+
+ @bind
+ dragMove(e) {
+ if (!e.movementY && !e.movementX) {
+ return;
+ }
+
+ const editPane = document.querySelector(".query-editor");
+ const target = editPane.querySelector(".panels-flex");
+ const grippie = editPane.querySelector(".grippie");
+
+ // we need to get the initial height / width of edit pane
+ // before we manipulate the size
+ if (!this.initialPaneWidth && !this.originalPaneHeight) {
+ this.originalPaneWidth = target.clientWidth;
+ this.originalPaneHeight = target.clientHeight;
+ }
+
+ const newHeight = Math.max(
+ this.originalPaneHeight,
+ target.clientHeight + e.movementY
+ );
+ const newWidth = Math.max(
+ this.originalPaneWidth,
+ target.clientWidth + e.movementX
+ );
+
+ target.style.height = newHeight + "px";
+ target.style.width = newWidth + "px";
+ grippie.style.width = newWidth + "px";
+ this.appEvents.trigger("ace:resize");
+ }
+
+ @bind
+ scrollTop() {
+ window.scrollTo(0, 0);
+ }
+
+ @action
+ async import(files) {
+ try {
+ this.loading = true;
+ const file = files[0];
+ const record = await this._importQuery(file);
+ this.addCreatedRecord(record);
+ } catch (e) {
+ if (e.jqXHR) {
+ popupAjaxError(e);
+ } else if (e instanceof SyntaxError) {
+ this.dialog.alert(i18n("explorer.import.unparseable_json"));
+ } else if (e instanceof TypeError) {
+ this.dialog.alert(i18n("explorer.import.wrong_json"));
+ } else {
+ this.dialog.alert(i18n("errors.desc.unknown"));
+ // eslint-disable-next-line no-console
+ console.error(e);
+ }
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ displayCreate() {
+ this.showCreate = true;
+ }
+
+ @action
+ updateSortProperty(property) {
+ if (this.sortByProperty === property) {
+ this.sortDescending = !this.sortDescending;
+ } else {
+ this.sortByProperty = property;
+ this.sortDescending = true;
+ }
+ }
+
+ @action
+ async create() {
+ try {
+ const name = this.newQueryName.trim();
+ this.loading = true;
+ this.showCreate = false;
+ const result = await this.store.createRecord("query", { name }).save();
+ this.addCreatedRecord(result.target);
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ updateSearch(value) {
+ this.search = value;
+ }
+
+ @action
+ updateNewQueryName(value) {
+ this.newQueryName = value;
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins-explorer-queries-details.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins-explorer-queries-details.js
new file mode 100644
index 00000000000..694cca379ba
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins-explorer-queries-details.js
@@ -0,0 +1,292 @@
+import { tracked } from "@glimmer/tracking";
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { Promise } from "rsvp";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { bind } from "discourse/lib/decorators";
+import QueryHelp from "discourse/plugins/discourse-data-explorer/discourse/components/modal/query-help";
+import { ParamValidationError } from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";
+import Query from "discourse/plugins/discourse-data-explorer/discourse/models/query";
+
+export default class PluginsExplorerController extends Controller {
+ @service modal;
+ @service appEvents;
+ @service router;
+
+ @tracked params;
+ @tracked editingName = false;
+ @tracked editingQuery = false;
+ @tracked loading = false;
+ @tracked showResults = false;
+ @tracked hideSchema = false;
+ @tracked results = this.model.results;
+ @tracked dirty = false;
+
+ queryParams = ["params"];
+ explain = false;
+ order = null;
+ form = null;
+
+ get saveDisabled() {
+ return !this.dirty;
+ }
+
+ get runDisabled() {
+ return this.dirty;
+ }
+
+ get parsedParams() {
+ return this.params ? JSON.parse(this.params) : null;
+ }
+
+ get editDisabled() {
+ return parseInt(this.model.id, 10) < 0 ? true : false;
+ }
+
+ get groupOptions() {
+ return this.groups
+ .filter((g) => g.id !== 0)
+ .map((g) => {
+ return { id: g.id, name: g.name };
+ });
+ }
+
+ @action
+ async save() {
+ try {
+ this.loading = true;
+ await this.model.save();
+
+ this.dirty = false;
+ this.editingName = false;
+ } catch (error) {
+ popupAjaxError(error);
+ throw error;
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ saveAndRun() {
+ this.save().then(() => this.run());
+ }
+
+ async _importQuery(file) {
+ const json = await this._readFileAsTextAsync(file);
+ const query = this._parseQuery(json);
+ const record = this.store.createRecord("query", query);
+ const response = await record.save();
+ return response.target;
+ }
+
+ _parseQuery(json) {
+ const parsed = JSON.parse(json);
+ const query = parsed.query;
+ if (!query || !query.sql) {
+ throw new TypeError();
+ }
+ query.id = 0; // 0 means no Id yet
+ return query;
+ }
+
+ _readFileAsTextAsync(file) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ resolve(reader.result);
+ };
+ reader.onerror = reject;
+
+ reader.readAsText(file);
+ });
+ }
+
+ @bind
+ dragMove(e) {
+ if (!e.movementY && !e.movementX) {
+ return;
+ }
+
+ const editPane = document.querySelector(".query-editor");
+ const target = editPane.querySelector(".panels-flex");
+ const grippie = editPane.querySelector(".grippie");
+
+ // we need to get the initial height / width of edit pane
+ // before we manipulate the size
+ if (!this.initialPaneWidth && !this.originalPaneHeight) {
+ this.originalPaneWidth = target.clientWidth;
+ this.originalPaneHeight = target.clientHeight;
+ }
+
+ const newHeight = Math.max(
+ this.originalPaneHeight,
+ target.clientHeight + e.movementY
+ );
+ const newWidth = Math.max(
+ this.originalPaneWidth,
+ target.clientWidth + e.movementX
+ );
+
+ target.style.height = newHeight + "px";
+ target.style.width = newWidth + "px";
+ grippie.style.width = newWidth + "px";
+ this.appEvents.trigger("ace:resize");
+ }
+
+ @bind
+ didStartDrag() {}
+
+ @bind
+ didEndDrag() {}
+
+ @action
+ updateGroupIds(value) {
+ this.dirty = true;
+ this.model.set("group_ids", value);
+ }
+
+ @action
+ updateHideSchema(value) {
+ this.hideSchema = value;
+ }
+
+ @action
+ editName() {
+ this.editingName = true;
+ }
+
+ @action
+ editQuery() {
+ this.editingQuery = true;
+ }
+
+ @action
+ download() {
+ window.open(this.model.downloadUrl, "_blank");
+ }
+
+ @action
+ goHome() {
+ this.router.transitionTo("adminPlugins.explorer");
+ }
+
+ @action
+ showHelpModal() {
+ this.modal.show(QueryHelp);
+ }
+
+ @action
+ resetParams() {
+ this.model.resetParams();
+ }
+
+ @action
+ async discard() {
+ try {
+ this.loading = true;
+ const result = await this.store.find("query", this.model.id);
+ this.model.setProperties(result.getProperties(Query.updatePropertyNames));
+ if (!this.model.group_ids || !Array.isArray(this.model.group_ids)) {
+ this.model.set("group_ids", []);
+ }
+ this.dirty = false;
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async destroyQuery() {
+ try {
+ this.loading = true;
+ this.showResults = false;
+ await this.store.destroyRecord("query", this.model);
+ this.model.set("destroyed", true);
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async recover() {
+ try {
+ this.loading = true;
+ this.showResults = true;
+ await this.model.save();
+ this.model.set("destroyed", false);
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ onRegisterApi(form) {
+ this.form = form;
+ }
+
+ @action
+ setDirty() {
+ this.dirty = true;
+ }
+
+ @action
+ exitEdit() {
+ this.editingName = false;
+ }
+
+ @action
+ async run() {
+ let params = null;
+ if (this.model.hasParams) {
+ try {
+ params = await this.form?.submit();
+ } catch (err) {
+ if (err instanceof ParamValidationError) {
+ return;
+ }
+ }
+ if (params == null) {
+ return;
+ }
+ }
+ this.setProperties({
+ loading: true,
+ showResults: false,
+ params: JSON.stringify(params),
+ });
+
+ ajax("/admin/plugins/explorer/queries/" + this.model.id + "/run", {
+ type: "POST",
+ data: {
+ params: JSON.stringify(params),
+ explain: this.explain,
+ },
+ })
+ .then((result) => {
+ this.results = result;
+ if (!result.success) {
+ this.showResults = false;
+ return;
+ }
+ this.showResults = true;
+ })
+ .catch((err) => {
+ this.showResults = false;
+ if (err.jqXHR && err.jqXHR.status === 422 && err.jqXHR.responseJSON) {
+ this.results = err.jqXHR.responseJSON;
+ } else {
+ popupAjaxError(err);
+ }
+ })
+ .finally(() => (this.loading = false));
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/group-reports-index.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/group-reports-index.js
new file mode 100644
index 00000000000..79caed15962
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/group-reports-index.js
@@ -0,0 +1,3 @@
+import Controller from "@ember/controller";
+
+export default class GroupReportsIndexController extends Controller {}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/group-reports-show.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/group-reports-show.js
new file mode 100644
index 00000000000..e499208b6fb
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/group-reports-show.js
@@ -0,0 +1,137 @@
+import { tracked } from "@glimmer/tracking";
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import BookmarkModal from "discourse/components/modal/bookmark";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { BookmarkFormData } from "discourse/lib/bookmark-form-data";
+import { bind } from "discourse/lib/decorators";
+import {
+ NO_REMINDER_ICON,
+ WITH_REMINDER_ICON,
+} from "discourse/models/bookmark";
+import { ParamValidationError } from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";
+
+export default class GroupReportsShowController extends Controller {
+ @service currentUser;
+ @service modal;
+ @service router;
+
+ @tracked showResults = false;
+ @tracked loading = false;
+ @tracked results = this.model.results;
+ @tracked queryGroupBookmark = this.queryGroup?.bookmark;
+
+ queryParams = ["params"];
+ form = null;
+ explain = false;
+
+ get parsedParams() {
+ return this.params ? JSON.parse(this.params) : null;
+ }
+
+ get hasParams() {
+ return this.model.param_info.length > 0;
+ }
+
+ get bookmarkLabel() {
+ return this.queryGroupBookmark
+ ? "bookmarked.edit_bookmark"
+ : "bookmarked.title";
+ }
+
+ get bookmarkIcon() {
+ if (this.queryGroupBookmark && this.queryGroupBookmark.reminder_at) {
+ return WITH_REMINDER_ICON;
+ }
+ return NO_REMINDER_ICON;
+ }
+
+ get bookmarkClassName() {
+ return this.queryGroupBookmark
+ ? ["query-group-bookmark", "bookmarked"].join(" ")
+ : "query-group-bookmark";
+ }
+
+ @bind
+ async run() {
+ try {
+ let params = null;
+ if (this.hasParams) {
+ params = await this.form.submit();
+ if (params == null) {
+ return;
+ }
+ }
+ this.loading = true;
+ this.showResults = false;
+ const stringifiedParams = JSON.stringify(params);
+ this.router.transitionTo({
+ queryParams: {
+ params: params ? stringifiedParams : null,
+ },
+ });
+ const response = await ajax(
+ `/g/${this.get("group.name")}/reports/${this.model.id}/run`,
+ {
+ type: "POST",
+ data: {
+ params: stringifiedParams,
+ explain: this.explain,
+ },
+ }
+ );
+
+ this.results = response;
+ if (!response.success) {
+ return;
+ }
+ this.showResults = true;
+ } catch (error) {
+ if (error.jqXHR?.status === 422 && error.jqXHR.responseJSON) {
+ this.results = error.jqXHR.responseJSON;
+ } else if (!(error instanceof ParamValidationError)) {
+ popupAjaxError(error);
+ }
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ toggleBookmark() {
+ const modalBookmark =
+ this.queryGroupBookmark ||
+ this.store.createRecord("bookmark", {
+ bookmarkable_type: "DiscourseDataExplorer::QueryGroup",
+ bookmarkable_id: this.queryGroup.id,
+ user_id: this.currentUser.id,
+ });
+ return this.modal.show(BookmarkModal, {
+ model: {
+ bookmark: new BookmarkFormData(modalBookmark),
+ afterSave: (bookmarkFormData) => {
+ const bookmark = this.store.createRecord(
+ "bookmark",
+ bookmarkFormData.saveData
+ );
+ this.queryGroupBookmark = bookmark;
+ this.appEvents.trigger(
+ "bookmarks:changed",
+ bookmarkFormData.saveData,
+ bookmark.attachedTo()
+ );
+ },
+ afterDelete: () => {
+ this.queryGroupBookmark = null;
+ },
+ },
+ });
+ }
+
+ @action
+ onRegisterApi(form) {
+ this.form = form;
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/explorer-route-map.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/explorer-route-map.js
new file mode 100644
index 00000000000..8b793f78f8f
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/explorer-route-map.js
@@ -0,0 +1,11 @@
+export default {
+ resource: "admin.adminPlugins",
+ path: "/plugins",
+ map() {
+ this.route("explorer", function () {
+ this.route("queries", function () {
+ this.route("details", { path: "/:query_id" });
+ });
+ });
+ },
+};
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/group-reports-route-map.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/group-reports-route-map.js
new file mode 100644
index 00000000000..d8a3bfe3669
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/group-reports-route-map.js
@@ -0,0 +1,9 @@
+export default {
+ resource: "group",
+
+ map() {
+ this.route("reports", function () {
+ this.route("show", { path: "/:query_id" });
+ });
+ },
+};
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/initializers/initialize-data-explorer.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/initializers/initialize-data-explorer.js
new file mode 100644
index 00000000000..dfceb42861e
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/initializers/initialize-data-explorer.js
@@ -0,0 +1,6 @@
+export default {
+ name: "initialize-data-explorer",
+ initialize(container) {
+ container.lookup("service:store").addPluralization("query", "queries");
+ },
+};
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/themeColor.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/themeColor.js
new file mode 100644
index 00000000000..84af962581b
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/themeColor.js
@@ -0,0 +1,4 @@
+export default function themeColor(name) {
+ const style = getComputedStyle(document.body);
+ return style.getPropertyValue(name);
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js
new file mode 100644
index 00000000000..b57fd41d93e
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js
@@ -0,0 +1,80 @@
+import { computed } from "@ember/object";
+import getURL from "discourse/lib/get-url";
+import RestModel from "discourse/models/rest";
+
+export default class Query extends RestModel {
+ static updatePropertyNames = [
+ "name",
+ "description",
+ "sql",
+ "user_id",
+ "created_at",
+ "group_ids",
+ "last_run_at",
+ ];
+
+ params = {};
+
+ constructor() {
+ super(...arguments);
+ this.param_info?.resetParams();
+ }
+
+ get downloadUrl() {
+ return getURL(`/admin/plugins/explorer/queries/${this.id}.json?export=1`);
+ }
+
+ @computed("param_info", "updating")
+ get hasParams() {
+ // When saving, we need to refresh the param-input component to clean up the old key
+ return this.param_info.length && !this.updating;
+ }
+
+ beforeUpdate() {
+ this.set("updating", true);
+ }
+
+ afterUpdate() {
+ this.set("updating", false);
+ }
+
+ resetParams() {
+ const newParams = {};
+ const oldParams = this.params;
+ this.param_info.forEach((pinfo) => {
+ const name = pinfo.identifier;
+ if (oldParams[pinfo.identifier]) {
+ newParams[name] = oldParams[name];
+ } else if (pinfo["default"] !== null) {
+ newParams[name] = pinfo["default"];
+ } else if (pinfo["type"] === "boolean") {
+ newParams[name] = "false";
+ } else if (pinfo["type"] === "user_id") {
+ newParams[name] = null;
+ } else if (pinfo["type"] === "user_list") {
+ newParams[name] = null;
+ } else if (pinfo["type"] === "group_list") {
+ newParams[name] = null;
+ } else {
+ newParams[name] = "";
+ }
+ });
+ this.params = newParams;
+ }
+
+ updateProperties() {
+ const props = this.getProperties(Query.updatePropertyNames);
+ if (this.destroyed) {
+ props.id = this.id;
+ }
+ return props;
+ }
+
+ createProperties() {
+ if (this.sql) {
+ // Importing
+ return this.updateProperties();
+ }
+ return this.getProperties("name");
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins-explorer-index.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins-explorer-index.js
new file mode 100644
index 00000000000..d3936f517f7
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins-explorer-index.js
@@ -0,0 +1,47 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class AdminPluginsExplorerIndex extends DiscourseRoute {
+ @service router;
+
+ beforeModel(transition) {
+ // Redirect old /explorer?id=123 route to /explorer/queries/123
+ if (transition.to.queryParams.id) {
+ this.router.transitionTo(
+ "adminPlugins.explorer.queries.details",
+ transition.to.queryParams.id
+ );
+ }
+ }
+
+ model() {
+ if (!this.currentUser.admin) {
+ // display "Only available to admins" message
+ return { model: null, schema: null, disallow: true, groups: null };
+ }
+
+ const groupPromise = ajax("/admin/plugins/explorer/groups.json");
+ const queryPromise = this.store.findAll("query");
+
+ return groupPromise.then((groups) => {
+ let groupNames = {};
+ groups.forEach((g) => {
+ groupNames[g.id] = g.name;
+ });
+ return queryPromise.then((model) => {
+ model.forEach((query) => {
+ query.set(
+ "group_names",
+ (query.group_ids || []).map((id) => groupNames[id])
+ );
+ });
+ return { model, groups };
+ });
+ });
+ }
+
+ setupController(controller, model) {
+ controller.setProperties(model);
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins-explorer-queries-details.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins-explorer-queries-details.js
new file mode 100644
index 00000000000..89536182861
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins-explorer-queries-details.js
@@ -0,0 +1,37 @@
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class AdminPluginsExplorerQueriesDetails extends DiscourseRoute {
+ model(params) {
+ if (!this.currentUser.admin) {
+ // display "Only available to admins" message
+ return { model: null, schema: null, disallow: true, groups: null };
+ }
+
+ const groupPromise = ajax("/admin/plugins/explorer/groups.json");
+ const schemaPromise = ajax("/admin/plugins/explorer/schema.json", {
+ cache: true,
+ });
+ const queryPromise = this.store.find("query", params.query_id);
+
+ return groupPromise.then((groups) => {
+ let groupNames = {};
+ groups.forEach((g) => {
+ groupNames[g.id] = g.name;
+ });
+ return schemaPromise.then((schema) => {
+ return queryPromise.then((model) => {
+ model.set(
+ "group_names",
+ (model.group_ids || []).map((id) => groupNames[id])
+ );
+ return { model, schema, groups };
+ });
+ });
+ });
+ }
+
+ setupController(controller, model) {
+ controller.setProperties(model);
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/group-reports-index.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/group-reports-index.js
new file mode 100644
index 00000000000..5e5339c5b1d
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/group-reports-index.js
@@ -0,0 +1,32 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class GroupReportsIndexRoute extends DiscourseRoute {
+ @service router;
+
+ model() {
+ const group = this.modelFor("group");
+ return ajax(`/g/${group.name}/reports`)
+ .then((queries) => {
+ return {
+ model: queries,
+ group,
+ };
+ })
+ .catch(() => this.router.transitionTo("group.members", group));
+ }
+
+ afterModel(model) {
+ if (
+ !model.group.get("is_group_user") &&
+ !(this.currentUser && this.currentUser.admin)
+ ) {
+ this.router.transitionTo("group.members", model.group);
+ }
+ }
+
+ setupController(controller, model) {
+ controller.setProperties(model);
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/group-reports-show.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/group-reports-show.js
new file mode 100644
index 00000000000..c1f150e78a2
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/group-reports-show.js
@@ -0,0 +1,37 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class GroupReportsShowRoute extends DiscourseRoute {
+ @service router;
+
+ model(params) {
+ const group = this.modelFor("group");
+ return ajax(`/g/${group.name}/reports/${params.query_id}`)
+ .then((response) => {
+ const query = response.query;
+ const queryGroup = response.query_group;
+
+ const queryParamInfo = query.param_info;
+ const queryParams = queryParamInfo.reduce((acc, param) => {
+ acc[param.identifier] = param.default;
+ return acc;
+ }, {});
+
+ return {
+ model: Object.assign({ params: queryParams }, query),
+ group,
+ queryGroup,
+ results: null,
+ showResults: false,
+ };
+ })
+ .catch(() => {
+ this.router.transitionTo("group.members", group);
+ });
+ }
+
+ setupController(controller, model) {
+ controller.setProperties(model);
+ }
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/admin/plugins-explorer-index.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/admin/plugins-explorer-index.gjs
new file mode 100644
index 00000000000..07a861a00aa
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/admin/plugins-explorer-index.gjs
@@ -0,0 +1,187 @@
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import RouteTemplate from "ember-route-template";
+import { not } from "truth-helpers";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import PickFilesButton from "discourse/components/pick-files-button";
+import TableHeaderToggle from "discourse/components/table-header-toggle";
+import TextField from "discourse/components/text-field";
+import boundDate from "discourse/helpers/bound-date";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import ShareReport from "../../components/share-report";
+
+export default RouteTemplate(
+ <template>
+ {{#if @controller.disallow}}
+ <h1>{{i18n "explorer.admins_only"}}</h1>
+ {{else}}
+ <div class="query-list">
+ <TextField
+ @value={{@controller.search}}
+ @placeholderKey="explorer.search_placeholder"
+ @onChange={{@controller.updateSearch}}
+ />
+ <DButton
+ @action={{@controller.displayCreate}}
+ @icon="plus"
+ class="no-text btn-right"
+ />
+ <PickFilesButton
+ @label="explorer.import.label"
+ @icon="upload"
+ @acceptedFormatsOverride={{@controller.acceptedImportFileTypes}}
+ @showButton="true"
+ @onFilesPicked={{@controller.import}}
+ class="import-btn"
+ />
+ </div>
+
+ {{#if @controller.showCreate}}
+ <div class="query-create">
+ <TextField
+ @value={{@controller.newQueryName}}
+ @placeholderKey="explorer.create_placeholder"
+ @onChange={{@controller.updateNewQueryName}}
+ />
+ <DButton
+ @action={{@controller.create}}
+ @disabled={{@controller.createDisabled}}
+ @label="explorer.create"
+ @icon="plus"
+ />
+ </div>
+ {{/if}}
+
+ {{#if @controller.othersDirty}}
+ <div class="warning">
+ {{icon "triangle-exclamation"}}
+ {{i18n "explorer.others_dirty"}}
+ </div>
+ {{/if}}
+
+ {{#if @controller.model.length}}
+ <ConditionalLoadingSpinner @condition={{@controller.loading}} />
+
+ <div class="container">
+ <table class="d-admin-table recent-queries">
+ <thead class="heading-container">
+ <th class="col heading name">
+ <div
+ role="button"
+ class="heading-toggle"
+ {{on "click" (fn @controller.updateSortProperty "name")}}
+ >
+ <TableHeaderToggle
+ @field="name"
+ @labelKey="explorer.query_name"
+ @order={{@controller.order}}
+ @asc={{not @controller.sortDescending}}
+ @automatic="true"
+ />
+ </div>
+ </th>
+ <th class="col heading created-by">
+ <div
+ role="button"
+ class="heading-toggle"
+ {{on "click" (fn @controller.updateSortProperty "username")}}
+ >
+ <TableHeaderToggle
+ @field="username"
+ @labelKey="explorer.query_user"
+ @order={{@controller.order}}
+ @asc={{not @controller.sortDescending}}
+ @automatic="true"
+ />
+ </div>
+ </th>
+ <th class="col heading group-names">
+ <div class="group-names-header">
+ {{i18n "explorer.query_groups"}}
+ </div>
+ </th>
+ <th class="col heading created-at">
+ <div
+ role="button"
+ class="heading-toggle"
+ {{on
+ "click"
+ (fn @controller.updateSortProperty "last_run_at")
+ }}
+ >
+ <TableHeaderToggle
+ @field="last_run_at"
+ @labelKey="explorer.query_time"
+ @order={{@controller.order}}
+ @asc={{not @controller.sortDescending}}
+ @automatic="true"
+ />
+ </div>
+ </th>
+ </thead>
+ <tbody>
+ {{#each @controller.filteredContent as |query|}}
+ <tr class="d-admin-row__content query-row">
+ <td class="d-admin-row__overview">
+ <a
+ {{on "click" @controller.scrollTop}}
+ href="/admin/plugins/explorer/queries/{{query.id}}"
+ >
+ <b class="query-name">{{query.name}}</b>
+ <span class="query-desc">{{query.description}}</span>
+ </a>
+ </td>
+ <td class="d-admin-row__detail query-created-by">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "explorer.query_user"}}
+ </div>
+ {{#if query.username}}
+ <div>
+ <a href="/u/{{query.username}}/activity">
+ <span>{{query.username}}</span>
+ </a>
+ </div>
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail query-group-names">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "explorer.query_groups"}}
+ </div>
+ <div class="group-names">
+ {{#each query.group_names as |group|}}
+ <ShareReport @group={{group}} @query={{query}} />
+ {{/each}}
+ </div>
+ </td>
+ <td class="d-admin-row__detail query-created-at">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "explorer.query_time"}}
+ </div>
+ {{#if query.last_run_at}}
+ <span>
+ {{boundDate query.last_run_at}}
+ </span>
+ {{else if query.created_at}}
+ <span>
+ {{boundDate query.created_at}}
+ </span>
+ {{/if}}
+ </td>
+ </tr>
+ {{else}}
+ <br />
+ <em class="no-search-results">
+ {{i18n "explorer.no_search_results"}}
+ </em>
+ {{/each}}
+ </tbody>
+ </table>
+ </div>
+
+ <div class="explorer-pad-bottom"></div>
+ {{/if}}
+ {{/if}}
+ </template>
+);
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/admin/plugins-explorer-queries-details.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/admin/plugins-explorer-queries-details.gjs
new file mode 100644
index 00000000000..0d412d2346e
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/admin/plugins-explorer-queries-details.gjs
@@ -0,0 +1,262 @@
+import { Input } from "@ember/component";
+import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import RouteTemplate from "ember-route-template";
+import AceEditor from "discourse/components/ace-editor";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import DTextarea from "discourse/components/d-textarea";
+import TextField from "discourse/components/text-field";
+import icon from "discourse/helpers/d-icon";
+import draggable from "discourse/modifiers/draggable";
+import { i18n } from "discourse-i18n";
+import MultiSelect from "select-kit/components/multi-select";
+import CodeView from "../../components/code-view";
+import ExplorerSchema from "../../components/explorer-schema";
+import ParamInputForm from "../../components/param-input-form";
+import QueryResultsWrapper from "../../components/query-results-wrapper";
+
+export default RouteTemplate(
+ <template>
+ {{#if @controller.disallow}}
+ <h1>{{i18n "explorer.admins_only"}}</h1>
+ {{else}}
+
+ <div class="query-edit {{if @controller.editingName 'editing'}}">
+ {{#if @controller.editingName}}
+ <div class="name">
+ <DButton
+ @action={{@controller.goHome}}
+ @icon="chevron-left"
+ class="previous"
+ />
+ <DButton
+ @action={{@controller.exitEdit}}
+ @icon="xmark"
+ class="previous"
+ />
+ <div class="name-text-field">
+ <TextField
+ @value={{@controller.model.name}}
+ @onChange={{@controller.setDirty}}
+ />
+ </div>
+ </div>
+
+ <div class="desc">
+ <DTextarea
+ @value={{@controller.model.description}}
+ @placeholder={{i18n "explorer.description_placeholder"}}
+ @input={{@controller.setDirty}}
+ />
+ </div>
+ {{else}}
+ <div class="name">
+ <DButton
+ @action={{@controller.goHome}}
+ @icon="chevron-left"
+ class="previous"
+ />
+
+ <h1>
+ <span>{{@controller.model.name}}</span>
+ {{#unless @controller.editDisabled}}
+ <DButton
+ @action={{@controller.editName}}
+ @icon="pencil"
+ class="edit-query-name btn-transparent"
+ />
+ {{/unless}}
+ </h1>
+ </div>
+
+ <div class="desc">
+ {{@controller.model.description}}
+ </div>
+ {{/if}}
+
+ {{#unless @controller.model.destroyed}}
+ <div class="groups">
+ <span class="label">{{i18n "explorer.allow_groups"}}</span>
+ <span>
+ <MultiSelect
+ @value={{@controller.model.group_ids}}
+ @content={{@controller.groupOptions}}
+ @options={{hash allowAny=false}}
+ @onChange={{@controller.updateGroupIds}}
+ />
+ </span>
+ </div>
+ {{/unless}}
+
+ <div class="clear"></div>
+
+ {{#if @controller.editingQuery}}
+ <div class="query-editor {{if @controller.hideSchema 'no-schema'}}">
+ <div class="panels-flex">
+ <div class="editor-panel">
+ <AceEditor
+ {{on "click" @controller.setDirty}}
+ @content={{@controller.model.sql}}
+ @onChange={{fn (mut @controller.model.sql)}}
+ @mode="sql"
+ @disabled={{@controller.model.destroyed}}
+ @save={{@controller.save}}
+ @submit={{@controller.saveAndRun}}
+ />
+ </div>
+
+ <div class="right-panel">
+ <ExplorerSchema
+ @schema={{@controller.schema}}
+ @hideSchema={{@controller.hideSchema}}
+ @updateHideSchema={{@controller.updateHideSchema}}
+ />
+ </div>
+ </div>
+
+ <div
+ class="grippie"
+ {{draggable
+ }}
+ >
+ {{icon "discourse-expand"}}
+ </div>
+
+ <div class="clear"></div>
+ </div>
+ {{else}}
+ <div class="sql">
+ <CodeView
+ @value={{@controller.model.sql}}
+ @codeClass="sql"
+ @setDirty={{@controller.setDirty}}
+ />
+ </div>
+ {{/if}}
+
+ <div class="clear"></div>
+
+ <div class="pull-left left-buttons">
+ {{#if @controller.editingQuery}}
+ <DButton
+ class="btn-save-query"
+ @action={{@controller.save}}
+ @label="explorer.save"
+ @disabled={{@controller.saveDisabled}}
+ />
+ {{else}}
+ {{#unless @controller.editDisabled}}
+ <DButton
+ class="btn-edit-query"
+ @action={{@controller.editQuery}}
+ @label="explorer.edit"
+ @icon="pencil"
+ />
+ {{/unless}}
+ {{/if}}
+
+ <DButton
+ @action={{@controller.download}}
+ @label="explorer.export"
+ @disabled={{@controller.runDisabled}}
+ @icon="download"
+ />
+
+ {{#if @controller.editingQuery}}
+ <DButton
+ @action={{@controller.showHelpModal}}
+ @label="explorer.help.label"
+ @icon="circle-question"
+ />
+ {{/if}}
+ </div>
+
+ <div class="pull-right right-buttons">
+ {{#if @controller.model.destroyed}}
+ <DButton
+ @action={{@controller.recover}}
+ @icon="arrow-rotate-left"
+ @label="explorer.recover"
+ />
+ {{else}}
+ {{#if @controller.editingQuery}}
+ <DButton
+ @action={{@controller.discard}}
+ @icon="arrow-rotate-left"
+ @label="explorer.undo"
+ @disabled={{@controller.saveDisabled}}
+ />
+ {{/if}}
+
+ <DButton
+ @action={{@controller.destroyQuery}}
+ @icon="trash-can"
+ @label="explorer.delete"
+ class="btn-danger"
+ />
+ {{/if}}
+ </div>
+ <div class="clear"></div>
+ </div>
+
+ <form class="query-run" {{on "submit" @controller.run}}>
+ {{#if @controller.model.hasParams}}
+ <ParamInputForm
+ @initialValues={{@controller.parsedParams}}
+ @paramInfo={{@controller.model.param_info}}
+ @onRegisterApi={{@controller.onRegisterApi}}
+ />
+ {{/if}}
+
+ {{#if @controller.runDisabled}}
+ {{#if @controller.saveDisabled}}
+ <DButton
+ @label="explorer.run"
+ @disabled="true"
+ class="btn-primary"
+ />
+ {{else}}
+ <DButton
+ @action={{@controller.saveAndRun}}
+ @icon="play"
+ @label="explorer.saverun"
+ class="btn-primary"
+ />
+ {{/if}}
+ {{else}}
+ <DButton
+ @action={{@controller.run}}
+ @icon="play"
+ @label="explorer.run"
+ @disabled={{@controller.runDisabled}}
+ @type="submit"
+ class="btn-primary"
+ />
+ {{/if}}
+
+ <label class="query-plan">
+ <Input
+ @type="checkbox"
+ @checked={{@controller.explain}}
+ name="explain"
+ />
+ {{i18n "explorer.explain_label"}}
+ </label>
+ </form>
+ <hr />
+
+ <ConditionalLoadingSpinner @condition={{@controller.loading}} />
+
+ <QueryResultsWrapper
+ @results={{@controller.results}}
+ @showResults={{@controller.showResults}}
+ @query={{@controller.model}}
+ @content={{@controller.results}}
+ />
+ {{/if}}
+ </template>
+);
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/group-reports-index.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/group-reports-index.gjs
new file mode 100644
index 00000000000..d7bf6db0724
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/group-reports-index.gjs
@@ -0,0 +1,45 @@
+import { array } from "@ember/helper";
+import { LinkTo } from "@ember/routing";
+import RouteTemplate from "ember-route-template";
+import boundDate from "discourse/helpers/bound-date";
+import { i18n } from "discourse-i18n";
+
+export default RouteTemplate(
+ <template>
+ <section class="user-content">
+ <table class="group-reports">
+ <thead>
+ <th>
+ {{i18n "explorer.report_name"}}
+ </th>
+ <th>
+ {{i18n "explorer.query_description"}}
+ </th>
+ <th>
+ {{i18n "explorer.query_time"}}
+ </th>
+ </thead>
+ <tbody>
+ {{#each @controller.model.queries as |query|}}
+ <tr>
+ <td>
+ <LinkTo
+ @route="group.reports.show"
+ @models={{array @controller.group.name query.id}}
+ >
+ {{query.name}}
+ </LinkTo>
+ </td>
+ <td>{{query.description}}</td>
+ <td>
+ {{#if query.last_run_at}}
+ {{boundDate query.last_run_at}}
+ {{/if}}
+ </td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ </section>
+ </template>
+);
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/group-reports-show.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/group-reports-show.gjs
new file mode 100644
index 00000000000..f23f9044700
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/templates/group-reports-show.gjs
@@ -0,0 +1,58 @@
+import { on } from "@ember/modifier";
+import RouteTemplate from "ember-route-template";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import ParamInputForm from "../components/param-input-form";
+import QueryResult from "../components/query-result";
+
+export default RouteTemplate(
+ <template>
+ <section class="user-content">
+ <h1>{{@controller.model.name}}</h1>
+ <p>{{@controller.model.description}}</p>
+
+ <form class="query-run" {{on "submit" @controller.run}}>
+ {{#if @controller.hasParams}}
+ <ParamInputForm
+ @initialValues={{@controller.parsedParams}}
+ @paramInfo={{@controller.model.param_info}}
+ @onRegisterApi={{@controller.onRegisterApi}}
+ />
+ {{/if}}
+
+ <DButton
+ @action={{@controller.run}}
+ @icon="play"
+ @label="explorer.run"
+ @type="submit"
+ class="btn-primary"
+ />
+
+ <DButton
+ @action={{@controller.toggleBookmark}}
+ @label={{@controller.bookmarkLabel}}
+ @icon={{@controller.bookmarkIcon}}
+ class={{@controller.bookmarkClassName}}
+ />
+ </form>
+
+ <ConditionalLoadingSpinner @condition={{@controller.loading}} />
+
+ {{#if @controller.results}}
+ <div class="query-results">
+ {{#if @controller.showResults}}
+ <QueryResult
+ @query={{@controller.model}}
+ @content={{@controller.results}}
+ @group={{@controller.group}}
+ />
+ {{else}}
+ {{#each @controller.results.errors as |err|}}
+ <pre class="query-error"><code>{{~err}}</code></pre>
+ {{/each}}
+ {{/if}}
+ </div>
+ {{/if}}
+ </section>
+ </template>
+);
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
new file mode 100644
index 00000000000..7c07d87322a
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -0,0 +1,568 @@
+@use "lib/viewport";
+
+table.group-reports {
+ width: 100%;
+ table-layout: fixed;
+
+ th:first-child {
+ width: 30%;
+ }
+
+ th:nth-child(2) {
+ width: 60%;
+ }
+
+ th:last-child {
+ width: 20%;
+ text-align: right;
+ }
+
+ tbody tr td {
+ padding: 0.5em;
+
+ &:first-child {
+ font-size: $font-up-1;
+ }
+
+ &:last-child {
+ text-align: right;
+ }
+ }
+}
+
+.https-warning {
+ color: var(--danger);
+}
+
+.query-editor {
+ margin-bottom: 15px;
+
+ .panels-flex {
+ display: flex;
+ height: 400px;
+ border: 1px solid var(--primary-very-low);
+ }
+
+ &.no-schema {
+ .editor-panel {
+ width: 100%;
+ }
+
+ .right-panel {
+ width: 0;
+
+ button.unhide {
+ position: absolute;
+ margin-left: -53px;
+ z-index: 1;
+ }
+ }
+ }
+
+ .editor-panel {
+ flex-grow: 1;
+
+ .ace-wrapper {
+ position: relative;
+ height: 100%;
+ width: 100%;
+ }
+
+ .ace_editor {
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ }
+ }
+
+ .right-panel {
+ flex-shrink: 0;
+ flex-grow: 0;
+ width: 345px;
+
+ .schema {
+ border-left: 1px solid var(--primary-low);
+ height: 100%;
+ overflow-y: scroll;
+ overflow-x: hidden;
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ position: relative;
+
+ .schema-search {
+ padding: 0.5em;
+ position: sticky;
+ background-color: var(--secondary);
+ top: 0;
+ z-index: 1;
+ }
+
+ .schema-table-name {
+ font-weight: bold;
+ border-bottom: 1px solid var(--primary-low);
+ padding-left: 5px;
+
+ .fa {
+ width: 6px;
+ }
+ }
+
+ ul {
+ list-style-type: none;
+ margin: 0;
+ }
+
+ dl {
+ margin: 0;
+ }
+
+ dl > div > * {
+ padding-top: 2px;
+ padding-bottom: 2px;
+ }
+
+ dl > div {
+ clear: both;
+ }
+
+ dt {
+ display: inline-block;
+ vertical-align: text-top;
+ overflow-wrap: break-word;
+ width: 110px;
+ margin-left: 5px;
+
+ &.sensitive {
+ color: var(--danger);
+ }
+ }
+
+ dd {
+ display: inline-block;
+ vertical-align: text-top;
+ width: 110px;
+ color: var(--tertiary);
+ margin: 0;
+ padding-left: 7px;
+ border-left: 1px dotted var(--primary-low-mid);
+
+ .schema-typenotes {
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ .popup-info {
+ color: var(--primary-medium);
+
+ .popup {
+ display: none;
+ width: 180px;
+ padding: 4px;
+ position: relative;
+ border: 1px solid;
+ background: var(--secondary);
+ padding-right: calc(5px + 0.5em);
+ }
+
+ &:hover .popup {
+ display: block;
+ }
+
+ &:focus .popup {
+ display: block;
+ }
+
+ .popup ol {
+ padding: 0;
+ position: relative;
+ list-style: none;
+
+ > li::before {
+ content: attr(value) ": ";
+ }
+ }
+ }
+ }
+ }
+ }
+
+ .grippie {
+ cursor: nwse-resize;
+ clear: both;
+ font-size: $font-down-2;
+ user-select: none;
+ color: var(--primary);
+ text-align: right;
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-very-low);
+
+ .d-icon {
+ transform: rotate(90deg);
+ }
+ }
+}
+
+.query-edit {
+ > .name {
+ display: flex;
+ align-items: center;
+ margin-bottom: 1em;
+
+ h1 {
+ display: inline-block;
+ margin: 0 0.5em 0 0;
+ color: var(--primary);
+
+ button .d-icon {
+ color: currentcolor;
+ }
+ }
+ }
+
+ button.previous {
+ margin-right: 0.5em;
+
+ .d-icon {
+ margin-left: -0.15em; // fixing fontawesome horizontal alignment
+ }
+ }
+
+ .name-text-field {
+ width: 100%;
+ }
+
+ .name input,
+ .desc textarea {
+ width: 100%;
+ margin: 0;
+ }
+
+ &:not(.editing) .desc {
+ margin: 10px 0;
+ }
+
+ .groups {
+ margin: 10px 0;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+
+ @include viewport.until(md) {
+ flex-direction: column;
+ align-items: flex-start;
+ }
+
+ .label {
+ margin-right: 10px;
+ color: var(--primary-high);
+ }
+
+ .name {
+ display: inline;
+ }
+
+ .select-kit.multi-select {
+ @include viewport.until(md) {
+ width: 360px;
+ }
+ }
+ }
+}
+
+.query-run {
+ margin-top: 25px;
+
+ .query-plan {
+ display: inline-block;
+ margin-left: 15px;
+ }
+}
+
+.clear {
+ clear: both;
+}
+
+.schema-title {
+ display: block;
+ margin: auto;
+}
+
+.query-params {
+ border: 1px solid var(--header_primary-medium);
+
+ .params-form {
+ margin: 5px;
+
+ html.desktop-view & {
+ flex-direction: row;
+ flex-wrap: wrap;
+ }
+ }
+
+ .param > input,
+ .param > .select-kit {
+ margin: 9px;
+ }
+
+ .invalid input {
+ background-color: var(--danger-low);
+ }
+
+ .invalid .ac-wrap {
+ background-color: var(--danger-low);
+ }
+
+ .param {
+ display: flex;
+ align-items: center;
+ flex: 0;
+
+ .ac-wrap {
+ display: inline-block;
+
+ input {
+ width: 100px !important; // override an inline style
+ }
+ }
+
+ input,
+ .select-kit {
+ width: auto;
+ max-width: 250px;
+ }
+ }
+}
+
+.query-list,
+.query-create,
+.query-edit,
+.query-results,
+.query-params,
+.https-warning {
+ margin: 10px 0;
+}
+
+.query-create {
+ display: flex;
+
+ input {
+ margin-right: 0.5em;
+ margin-bottom: 0;
+ }
+}
+
+.query-results {
+ section {
+ width: 100%;
+ overflow: auto;
+ max-height: 1000px;
+ }
+
+ table {
+ width: 100%;
+ margin-top: 10px;
+
+ td {
+ padding: 8px;
+ }
+ }
+
+ thead {
+ th {
+ position: sticky;
+ top: 0;
+ color: var(--primary);
+ background: var(--primary-low);
+ z-index: z("base");
+ }
+ }
+}
+
+.query-list {
+ display: flex;
+ align-items: flex-start;
+
+ .btn-left {
+ margin-right: 0.5em;
+ }
+
+ .btn-right {
+ margin-left: auto;
+ margin-right: 0.5em;
+ }
+
+ li.none {
+ display: none;
+ }
+
+ .import-btn {
+ display: flex;
+ }
+}
+
+.recent-queries {
+ thead {
+ .created-by {
+ width: 15%;
+ }
+
+ .group-names {
+ width: 15%;
+
+ .group-names-header {
+ position: absolute;
+ bottom: 8px;
+ left: 6px;
+ }
+ }
+
+ .created-at {
+ width: 15%;
+ }
+
+ .heading {
+ position: relative;
+ color: var(--primary-medium);
+ padding: 50px 0 0 0;
+
+ th.sortable {
+ font-weight: normal;
+ }
+
+ .heading-toggle {
+ bottom: 0;
+ position: absolute;
+ display: inline-block;
+ }
+ }
+ }
+
+ .query-row {
+ a {
+ width: 100%;
+ }
+
+ .query-name {
+ color: var(--primary);
+ }
+
+ .query-desc {
+ display: block;
+ color: var(--primary-high);
+ }
+
+ .query-created-by {
+ color: var(--primary-high);
+ }
+
+ .query-group-names {
+ color: var(--tertiary);
+
+ a {
+ display: inline;
+ }
+ }
+
+ .group-names {
+ @include viewport.until(md) {
+ text-align: right;
+ }
+ }
+
+ .query-created-at {
+ color: var(--primary-medium);
+ }
+ }
+
+ .query-row:hover {
+ background-color: inherit;
+ }
+
+ tr a {
+ color: inherit;
+ cursor: pointer;
+ display: inline-block;
+ }
+
+ .no-search-results {
+ color: var(--primary-medium);
+ }
+}
+
+.result-info {
+ float: left;
+}
+
+.result-about {
+ color: var(--primary-high);
+ float: right;
+}
+
+.result-explain {
+ padding-top: 1em;
+ margin-bottom: 0;
+}
+
+.result-post-link {
+ display: block;
+ color: inherit !important;
+}
+
+.result-json {
+ display: flex;
+}
+
+.result-json-value {
+ flex: 1;
+ margin-right: 0.5em;
+ max-width: 250px;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.explorer-pad-bottom {
+ margin-bottom: 200px;
+}
+
+.share-report {
+ cursor: pointer;
+
+ label {
+ color: var(--primary-high);
+ }
+
+ input {
+ margin-right: 4px;
+ }
+
+ .popup {
+ background-color: var(--secondary);
+ position: absolute;
+ box-shadow: var(--shadow-card);
+ padding: 12px;
+ z-index: 1;
+ }
+}
+
+.left-buttons,
+.right-buttons {
+ display: flex;
+ align-items: flex-start;
+}
+
+.left-buttons .btn {
+ margin-right: 0.5em;
+}
+
+.right-buttons .btn {
+ margin-left: 0.5em;
+}
+
+.query-group-bookmark {
+ &.bookmarked .d-icon {
+ color: var(--tertiary);
+ }
+}
diff --git a/plugins/discourse-data-explorer/config/locales/client.ar.yml b/plugins/discourse-data-explorer/config/locales/client.ar.yml
new file mode 100644
index 00000000000..4319d0bbe46
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ar.yml
@@ -0,0 +1,124 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ar:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "أزِل الفواصل المنقوطة من الاستعلام."
+ dirty: "يجب عليك حفظ الاستعلام قبل التشغيل."
+ explorer:
+ or: "أو"
+ admins_only: "مستكشف البيانات متاح للمسؤولين فقط."
+ allow_groups: "السماح للمجموعات بالوصول إلى هذا الاستعلام"
+ title: "مستكشف البيانات"
+ create: "إنشاء جديد"
+ create_placeholder: "اسم الاستعلام..."
+ description_placeholder: "أدخِل وصفًا هنا"
+ import:
+ label: "استيراد"
+ modal: "استيراد استعلام"
+ unparseable_json: "ملف JSON غير قابل للتحليل"
+ wrong_json: "ملف JSON خاطئ. يجب أن يحتوي ملف JSON على كائن \"استعلام\"، والذي يجب أن يحتوي على الأقل على خاصية \"sql\"."
+ help:
+ label: "المساعدة"
+ modal_title: "مساعدة مستكشف البيانات"
+ auto_resolution: "<h2>ربط السجلات التلقائي</h2> <p>عندما يؤدي الاستعلام إلى إرجاع مُعرِّف الكيان، فقد يستبدله مستكشف البيانات تلقائيًا باسم الكيان والمعلومات المفيدة الأخرى في نتائج الاستعلام. يتوفَّر الربط التلقائي لـ <i><b>user_id</b></i> و<i><b>group_id</b></i> و<i><b>topic_id</b></i> و<i><b>category_id</b></i> و<i><b>badge_id</b></i>. لتجربة ذلك، شغِّل هذا الاستعلام:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>إنشاء معلمات مخصَّصة</h2> <p>لإنشاء معلمات مخصَّصة لاستعلاماتك، ضع هذا في الجزء العلوي من استعلامك واتبع التنسيق:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>ملاحظة: السطر الأول الذي يحتوي على [params] مطلوب، بالإضافة إلى شرطتين قبله وكل معلمة مخصَّصة تريد الإعلان عنها.</i></p>"
+ default_values: "<h3>القيم الافتراضية</h3> <p>يمكنك إعلان المعلمات بقيم افتراضية أو من دونها. ستظهر القيم الافتراضية في حقلٍ نصي أسفل محرِّر الاستعلام، والذي يمكنك تعديله حسب احتياجاتك. ستظل المعلمات المعلنة دون قيم افتراضية تنشئ حقلًا نصيًا، لكنها ستكون فارغة ومظللة باللون الأحمر.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>أنواع البيانات</h3> <p>فيما يلي أنواع البيانات الشائعة التي يمكنك استخدامها:</p> <ul> <li><b>عدد صحيح</b> - عدد صحيح رباعي البايت مع مراعاة إشارته</li> <li><b>نص</b> - سلسلة أحرف متغيرة الطول</li> <li><b>قيمة منطقية</b> - صواب/خطأ</li> <li><b>تاريخ</b> - تاريخ تقويمي (سنة، شهر، يوم)</li> </ul> <p>لمزيد من المعلومات بشأن أنواع البيانات، انتقل إلى <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>هذا الموقع</a>.</p>"
+ schema:
+ title: "مخطط قاعدة البيانات"
+ filter: "بحث..."
+ sensitive: "قد تتضمَّن محتويات هذا العمود معلومات حساسة أو سرية بشكلٍ خاص. يُرجى توخي الحذر عند استخدام محتويات هذا العمود."
+ types:
+ bool:
+ yes: "نعم"
+ no: "لا"
+ null_: "فارغ"
+ export: "تصدير"
+ view_json: "عرض JSON"
+ save: "حفظ التغييرات"
+ saverun: "حفظ التغييرات والتشغيل"
+ run: "تشغيل"
+ undo: "تجاهل التغييرات"
+ edit: "تعديل"
+ delete: "حذف"
+ recover: "إلغاء حذف الاستعلام"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "جدول"
+ show_graph: "رسم بياني"
+ others_dirty: "يحتوي الاستعلام على تغييرات غير محفوظة سيتم فقدها إذا انتقلت بعيدًا."
+ run_time: "اكتمل الاستعلام في %{value} مللي ثانية."
+ result_count:
+ zero: "%{count} نتيجة."
+ one: "نتيجة واحدة (%{count})."
+ two: "نتيجتان (%{count})"
+ few: "%{count} نتائج."
+ many: "%{count} نتيجةً."
+ other: "%{count} نتيجة."
+ max_result_count:
+ zero: "جارٍ عرض أبرز %{count} نتيجة."
+ one: "جارٍ عرض أبرز نتيجة (%{count})."
+ two: "جارٍ عرض أبرز نتيجتين (%{count})."
+ few: "جارٍ عرض أبرز %{count} نتائج."
+ many: "جارٍ عرض أبرز %{count} نتيجةً."
+ other: "جارٍ عرض أبرز %{count} نتيجة."
+ query_name: "استعلام"
+ query_groups: "المجموعات"
+ link: "رابط لـ"
+ report_name: "تقرير"
+ query_description: "الوصف"
+ query_time: "آخر تشغيل"
+ query_user: "تم الإنشاء من قِبل"
+ column: "العمود %{number}"
+ explain_label: "هل تريد تضمين خطة الاستعلام؟"
+ save_params: "الضبط على الإعدادات الافتراضية"
+ reset_params: "إعادة التعيين"
+ search_placeholder: "بحث..."
+ no_search_results: "عذرًا، لم نتمكن من العثور على أي نتائج مطابقة لنصك."
+ form:
+ errors:
+ invalid: "غير صالح"
+ no_such_category: "لا توجد فئة بهذا الاسم"
+ no_such_group: "لا توجد مجموعة بهذا الاسم"
+ invalid_date: "%{date} هو تاريخ غير صالح"
+ invalid_time: "%{time} هو وقت غير صالح"
+ group:
+ reports: "التقارير"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "تشغيل استعلامات مستكشف البيانات. يمكنك تقييد مفتاح واجهة برمجة التطبيقات (API) إلى مجموعة من الاستعلامات عن طريق تحديد معرِّفات الاستعلامات."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: الإرسال إلى مستخدم أو مجموعة أو بريد إلكتروني
+ query_id:
+ label: استعلام مستكشف البيانات
+ query_params:
+ label: معلمات استعلام مستكشف البيانات
+ skip_empty:
+ label: تخطي إرسال رسالة شخصية إذا لم تكن هناك نتائج
+ attach_csv:
+ label: إرفاق ملف CSV بالرسالة الشخصية
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: الموضوع الذي سيتم نشر نتائج الاستعلام فيه
+ query_id:
+ label: استعلام مستكشف البيانات
+ query_params:
+ label: معلمات استعلام مستكشف البيانات
+ skip_empty:
+ label: تخطي النشر إذا لم تكن هناك نتائج
+ attach_csv:
+ label: إرفاق ملف CSV بالمنشور
diff --git a/plugins/discourse-data-explorer/config/locales/client.be.yml b/plugins/discourse-data-explorer/config/locales/client.be.yml
new file mode 100644
index 00000000000..2acfeec40dd
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.be.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+be:
+ js:
+ explorer:
+ or: "або"
+ types:
+ bool:
+ yes: "Так"
+ no: "Не"
+ export: "экспарт"
+ save: "Захаваць"
+ edit: "Рэдагаваць"
+ delete: "Выдаліць"
+ query_groups: "групы"
+ query_description: "апісанне"
+ reset_params: "скінуць"
+ group:
+ reports: "Справаздачы"
diff --git a/plugins/discourse-data-explorer/config/locales/client.bg.yml b/plugins/discourse-data-explorer/config/locales/client.bg.yml
new file mode 100644
index 00000000000..557d4fb7dc1
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.bg.yml
@@ -0,0 +1,31 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bg:
+ js:
+ explorer:
+ or: "или"
+ import:
+ label: "Импорт"
+ help:
+ label: "Помощ"
+ schema:
+ filter: "Търсене ... "
+ types:
+ bool:
+ yes: "Да"
+ no: "Не"
+ export: "Експорт "
+ save: "Запази промените"
+ edit: "Редактирай"
+ delete: "Изтрий"
+ result_count:
+ one: "%{count} резултат."
+ other: "%{count} резултата."
+ query_groups: "Групи"
+ query_description: "Описание"
+ reset_params: "Нулиране"
+ search_placeholder: "Търсене ... "
diff --git a/plugins/discourse-data-explorer/config/locales/client.bs_BA.yml b/plugins/discourse-data-explorer/config/locales/client.bs_BA.yml
new file mode 100644
index 00000000000..db4814804ff
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.bs_BA.yml
@@ -0,0 +1,28 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bs_BA:
+ js:
+ explorer:
+ or: "ili"
+ help:
+ label: "Pomoć"
+ schema:
+ filter: "Pretraga..."
+ types:
+ bool:
+ yes: "Da"
+ no: "Ne"
+ export: "Izvoz"
+ save: "Spremiti promjene"
+ edit: "Izmijeni"
+ delete: "Delete"
+ query_groups: "Grupa"
+ query_description: "Opis"
+ reset_params: "Resetovati"
+ search_placeholder: "Pretraga..."
+ group:
+ reports: "Izvještaji"
diff --git a/plugins/discourse-data-explorer/config/locales/client.ca.yml b/plugins/discourse-data-explorer/config/locales/client.ca.yml
new file mode 100644
index 00000000000..69635259538
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ca.yml
@@ -0,0 +1,63 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ca:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Elimina els punts i coma de la consulta."
+ dirty: "Cal desar la consulta abans d'executar-la"
+ explorer:
+ or: "o"
+ admins_only: "L'explorador de dades sols és disponible per a administradors."
+ title: "Explorador de dades"
+ create: "Crea'n un de nou"
+ create_placeholder: "Nom de consulta..."
+ description_placeholder: "Introduïu una descripció aquí"
+ import:
+ label: "Importa"
+ modal: "Importa una consulta"
+ help:
+ label: "Ajuda"
+ schema:
+ title: "Esquema de base de dades"
+ filter: "Cerca..."
+ sensitive: "El contingut d'aquesta columna pot contenir informació particularment sensible o privada. Tingueu precaució quan utilitzeu el contingut d'aquesta columna."
+ types:
+ bool:
+ yes: "Sí"
+ no: "No"
+ null_: "Nul"
+ export: "Exporta"
+ save: "Desa els canvis"
+ saverun: "Desa els canvis i executa"
+ run: "Executa"
+ undo: "Descarta els canvis"
+ edit: "Edita"
+ delete: "Suprimeix"
+ recover: "Restaura la consulta"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "Una consulta té canvis no desats que es perdran si continueu navegant."
+ run_time: "La consulta s'ha completat en %{value} ms."
+ result_count:
+ one: "%{count} resultat."
+ other: "%{count} resultats."
+ query_name: "Consulta"
+ query_groups: "Grups"
+ link: "Enllaç de"
+ report_name: "Report"
+ query_description: "Descripció"
+ query_time: "Darrera execució"
+ query_user: "Creat per"
+ column: "Columna %{number}"
+ explain_label: "Hi incloem pla de consulta?"
+ save_params: "Estableix valors per defecte"
+ reset_params: "Reinicia"
+ search_placeholder: "Cerca..."
+ no_search_results: "Ho sentim, no hem trobat cap resultat que coincideixi amb el vostre text."
+ group:
+ reports: "Reports"
diff --git a/plugins/discourse-data-explorer/config/locales/client.cs.yml b/plugins/discourse-data-explorer/config/locales/client.cs.yml
new file mode 100644
index 00000000000..67a03333df5
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.cs.yml
@@ -0,0 +1,39 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+cs:
+ js:
+ explorer:
+ or: "nebo"
+ create: "Vytvořit nový"
+ import:
+ label: "Import"
+ help:
+ label: "Nápověda"
+ schema:
+ filter: "Hledat..."
+ types:
+ bool:
+ yes: "Ano"
+ no: "Ne"
+ null_: "Null"
+ export: "Export"
+ save: "Uložit změny"
+ edit: "Upravit"
+ delete: "Smazat"
+ download_json: "JSON"
+ download_csv: "CSV"
+ result_count:
+ one: "%{count} výsledek."
+ few: "%{count} výsledky."
+ many: "%{count} výsledky."
+ other: "%{count} výsledků."
+ query_groups: "Skupiny"
+ query_description: "Popis"
+ reset_params: "obnovit výchozí"
+ search_placeholder: "Hledat..."
+ group:
+ reports: "Přehledy"
diff --git a/plugins/discourse-data-explorer/config/locales/client.da.yml b/plugins/discourse-data-explorer/config/locales/client.da.yml
new file mode 100644
index 00000000000..6652b9edda7
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.da.yml
@@ -0,0 +1,54 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+da:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Fjern semikoloner fra forespørgslen."
+ dirty: "Du skal gemme forespørgslen, før du kører den."
+ explorer:
+ or: "eller"
+ admins_only: "Data explorer er kun tilgængelige for administratorer."
+ allow_groups: "Tillad grupper at få adgang til denne forespørgsel"
+ title: "Data Udforsker"
+ create: "Opret Ny"
+ create_placeholder: "Navn på forespørgsel..."
+ description_placeholder: "Indtast en beskrivelse her"
+ import:
+ label: "Importer"
+ modal: "Importer en forespørgsel"
+ help:
+ label: "Hjælp"
+ modal_title: "Hjælp til Data Udforsker"
+ schema:
+ title: "Database Skema"
+ filter: "Søg..."
+ types:
+ bool:
+ yes: "Ja"
+ no: "Nej"
+ null_: "Null"
+ export: "Eksporter"
+ save: "Gem ændringer"
+ saverun: "Gem ændringer og kør"
+ run: "Kør"
+ undo: "Kassér Ændringer"
+ edit: "Rediger"
+ delete: "Slet"
+ recover: "Fortryd sletning af forespørgsel"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabel"
+ show_graph: "Graf"
+ query_name: "Forespørgsel"
+ query_groups: "grupper"
+ query_description: "Beskrivelse"
+ query_user: "Oprettet af"
+ reset_params: "Nulstil"
+ search_placeholder: "Søg..."
+ group:
+ reports: "Rapporter"
diff --git a/plugins/discourse-data-explorer/config/locales/client.de.yml b/plugins/discourse-data-explorer/config/locales/client.de.yml
new file mode 100644
index 00000000000..c31a3177efe
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.de.yml
@@ -0,0 +1,118 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+de:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Entferne die Semikolons aus der Anfrage."
+ dirty: "Du musst die Anfrage vor der Ausführung speichern."
+ explorer:
+ or: "oder"
+ admins_only: "Der Daten-Explorer ist nur für Administratoren verfügbar."
+ allow_groups: "Gruppen erlauben, auf diese Anfrage zuzugreifen"
+ title: "Daten-Explorer"
+ create: "Neu erstellen"
+ create_placeholder: "Name der Anfrage …"
+ description_placeholder: "Hier bitte eine Beschreibung eingeben"
+ import:
+ label: "Importieren"
+ modal: "Anfrage importieren"
+ unparseable_json: "JSON-Datei kann nicht verarbeitet werden."
+ wrong_json: "Falsche JSON-Datei. Eine JSON-Datei sollte ein „query“-Objekt enthalten, das zumindest eine „sql“-Eigenschaft haben sollte."
+ help:
+ label: "Hilfe"
+ modal_title: "Daten-Explorer-Hilfe"
+ auto_resolution: "<h2>Automatische Auflösung von Entitäten</h2> <p>Wenn deine Anfrage eine Entitäts-ID zurückgibt, kann der Daten-Explorer diese automatisch durch den Entitätsnamen und andere nützliche Informationen in den Anfrageergebnissen ersetzen. Die automatische Auflösung ist verfügbar für <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> und <i><b>badge_id</b></i>. Um dies auszuprobieren, führe diese Anfrage aus:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Benutzerdefinierte Parameter erstellen</h2> <p>Um benutzerdefinierte Parameter für deine Anfragen zu erstellen, füge Folgendes am Anfang deiner Anfrage ein und befolge das Format:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Hinweis: Die erste Zeile mit [params] ist erforderlich, zusammen mit zwei Bindestrichen davor und jedem benutzerdefinierten Parameter, den du deklarieren möchtest.</i></p>"
+ default_values: "<h3>Standardwerte</h3> <p>Du kannst Parameter mit oder ohne Standardwerte deklarieren. Die Standardwerte werden in einem Textfeld unter dem Anfrage-Editor angezeigt, das du beliebig bearbeiten kannst. Bei Parametern, die ohne Standardwerte angegeben werden, erscheint zwar immer noch ein Textfeld, aber es ist leer und rot markiert.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Datentypen</h3> <p>Hier sind gängige Datentypen, die du verwenden kannst:</p> <ul> <li><b>Ganzzahl</b> - vorzeichenbehaftete Vier-Byte-Ganzzahl</li> <li><b>Text</b> - Zeichenkette mit variabler Länge</li> <li><b>Boolean</b> – wahr/falsch</li> <li><b>Datum</b> - Kalenderdatum (Jahr, Monat, Tag)</li> </ul> <p>Weitere Informationen über Datentypen findest du auf <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>dieser Website</a>.</p>"
+ schema:
+ title: "Datenbank-Schema"
+ filter: "Suchen …"
+ sensitive: "Die Inhalte dieser Spalte enthalten möglicherweise besonders sensible oder persönliche Informationen. Bitte gehe behutsam mit den Inhalten dieser Spalte um."
+ types:
+ bool:
+ yes: "Ja"
+ no: "Nein"
+ null_: "Null"
+ export: "Exportieren"
+ view_json: "JSON anzeigen"
+ save: "Änderungen speichern"
+ saverun: "Änderungen speichern und ausführen"
+ run: "Ausführen"
+ undo: "Änderungen verwerfen"
+ edit: "Bearbeiten"
+ delete: "Löschen"
+ recover: "Anfrage wiederherstellen"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabelle"
+ show_graph: "Diagramm"
+ others_dirty: "Eine Anfrage hat nicht gespeicherte Änderungen, die verloren gehen, wenn du woanders hin navigierst."
+ run_time: "Anfrage in %{value} ms abgeschlossen."
+ result_count:
+ one: "%{count} Ergebnis."
+ other: "%{count} Ergebnisse."
+ max_result_count:
+ one: "Zeige das Top-%{count} Ergebnis."
+ other: "Zeige die Top-%{count} Ergebnisse."
+ query_name: "Anfrage"
+ query_groups: "Gruppen"
+ link: "Link für"
+ report_name: "Bericht"
+ query_description: "Beschreibung"
+ query_time: "Letzter Lauf"
+ query_user: "Erstellt von"
+ column: "Spalte %{number}"
+ explain_label: "Anfrageplan einbeziehen?"
+ save_params: "Standards festlegen"
+ reset_params: "Zurücksetzen"
+ search_placeholder: "Suchen …"
+ no_search_results: "Leider konnten wir keine Ergebnisse finden, die deinem Text entsprechen."
+ form:
+ errors:
+ invalid: "Ungültig"
+ no_such_category: "Keine solche Kategorie"
+ no_such_group: "Keine solche Gruppe"
+ invalid_date: "%{date} ist ein ungültiges Datum"
+ invalid_time: "%{time} ist eine ungültige Zeit"
+ group:
+ reports: "Berichte"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Daten-Explorer-Anfragen ausführen. Schränke den API-Schlüssel auf eine Reihe von Anfragen ein, indem du Anfrage-IDs angibst."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: An Benutzer, Gruppe oder E-Mail senden
+ query_id:
+ label: Daten-Explorer-Anfrage
+ query_params:
+ label: Daten-Explorer-Anfrageparameter
+ skip_empty:
+ label: Überspringe das Senden einer PN, wenn es keine Ergebnisse gibt
+ attach_csv:
+ label: Hänge die CSV-Datei an die PN an
+ users_from_group:
+ label: Senden jedem Gruppenmitglied eine individuelle PN
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: Das Thema, in dem die Anfrageergebnisse veröffentlicht werden
+ query_id:
+ label: Daten-Explorer-Anfrage
+ query_params:
+ label: Daten-Explorer-Anfrageparameter
+ skip_empty:
+ label: Überspringe die Veröffentlichung, wenn keine Ergebnisse vorliegen
+ attach_csv:
+ label: Hänge die CSV-Datei an den Beitrag an
diff --git a/plugins/discourse-data-explorer/config/locales/client.el.yml b/plugins/discourse-data-explorer/config/locales/client.el.yml
new file mode 100644
index 00000000000..49fff5c6231
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.el.yml
@@ -0,0 +1,31 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+el:
+ js:
+ explorer:
+ or: "ή"
+ import:
+ label: "Εισαγωγή"
+ help:
+ label: "Βοήθεια"
+ schema:
+ filter: "Αναζήτηση..."
+ types:
+ bool:
+ yes: "Ναι "
+ no: "Όχι"
+ export: "Εξαγωγή"
+ save: "Αποθήκευση Αλλαγών"
+ edit: "Επεξεργασία"
+ delete: "Σβήσιμο"
+ query_groups: "Ομάδες"
+ query_description: "Περιγραφή"
+ query_user: "Δημιουργήθηκε από"
+ reset_params: "Επαναφορά"
+ search_placeholder: "Αναζήτηση..."
+ group:
+ reports: "Αναφορές"
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
new file mode 100644
index 00000000000..2bd978788c4
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -0,0 +1,134 @@
+en:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Remove the semicolons from the query."
+ dirty: "You must save the query before running."
+ explorer:
+ or: "or"
+ admins_only: "The data explorer is only available to admins."
+ allow_groups: "Allow groups to access this query"
+ title: "Data Explorer"
+ create: "Create New"
+ create_placeholder: "Query name..."
+ description_placeholder: "Enter a description here"
+ import:
+ label: "Import"
+ modal: "Import A Query"
+ unparseable_json: "Unparseable JSON file."
+ wrong_json: "Wrong JSON file. A JSON file should contain a 'query' object, which should at least have an 'sql' property."
+ help:
+ label: "Help"
+ modal_title: "Data Explorer Help"
+ auto_resolution: "<h2>Automatic Entity Resolution</h2>
+ <p>When your query returns an entity id, Data Explorer may automatically substitute it with
+ the entity name and other useful information in query results. Automatic resolution is available for
+ <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i>
+ and <i><b>badge_id</b></i>. To try this out run this query:</p>
+ <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Creating Custom Parameters</h2>
+ <p>To create custom parameters for your queries, put this at the top of your query and follow the format:</p>
+ <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre>
+ <p><i>Note: the first line with [params] is required, along with two dashes preceding it and every
+ custom parameter you want to declare.</i></p>"
+ default_values: "<h3>Default Values</h3>
+ <p>You can declare parameters with or without default values. Default values will show up in a text field
+ below the query editor, which you can edit to your needs. Parameters declared without default values will
+ still generate a text field, but will be empty and highlighted red.</p>
+ <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Data Types</h3>
+ <p>Here are common data types you can use:</p>
+ <ul>
+ <li><b>integer</b> - signed four-byte Integer</li>
+ <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>
+ </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>"
+ schema:
+ title: "Database Schema"
+ filter: "Search..."
+ sensitive: "The contents of this column may contain particularly sensitive or private information. Please exercise caution when using the contents of this column."
+ types:
+ bool:
+ yes: "Yes"
+ no: "No"
+ null_: "Null"
+ export: "Export"
+ view_json: "View JSON"
+ save: "Save Changes"
+ saverun: "Save Changes and Run"
+ run: "Run"
+ undo: "Discard Changes"
+ edit: "Edit"
+ delete: "Delete"
+ recover: "Undelete Query"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Table"
+ show_graph: "Graph"
+ others_dirty: "A query has unsaved changes that will be lost if you navigate away."
+ run_time: "Query completed in %{value} ms."
+ result_count:
+ one: "%{count} result."
+ other: "%{count} results."
+ max_result_count:
+ one: "Showing top %{count} result."
+ other: "Showing top %{count} results."
+ query_name: "Query"
+ query_groups: "Groups"
+ link: "Link for"
+ report_name: "Report"
+ query_description: "Description"
+ query_time: "Last run"
+ query_user: "Created by"
+ column: "Column %{number}"
+ explain_label: "Include query plan?"
+ save_params: "Set Defaults"
+ reset_params: "Reset"
+ search_placeholder: "Search..."
+ no_search_results: "Sorry, we couldn't find any results matching your text."
+ form:
+ errors:
+ invalid: "Invalid"
+ no_such_category: "No such category"
+ no_such_group: "No such group"
+ invalid_date: "%{date} is a invalid date"
+ invalid_time: "%{time} is a invalid time"
+ group:
+ reports: "Reports"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Run Data Explorer queries. Restrict the API key to a set of queries by specifying queries IDs."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Send to User, Group or Email
+ query_id:
+ label: Data Explorer Query
+ query_params:
+ label: Data Explorer Query parameters
+ skip_empty:
+ label: Skip sending PM if there are no results
+ attach_csv:
+ label: Attach the CSV file to the PM
+ users_from_group:
+ label: Send individual PM to each group member
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: The topic to post query results in
+ query_id:
+ label: Data Explorer Query
+ query_params:
+ label: Data Explorer Query parameters
+ skip_empty:
+ label: Skip posting if there are no results
+ attach_csv:
+ label: Attach the CSV file to the post
diff --git a/plugins/discourse-data-explorer/config/locales/client.en_GB.yml b/plugins/discourse-data-explorer/config/locales/client.en_GB.yml
new file mode 100644
index 00000000000..8976ec8c162
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.en_GB.yml
@@ -0,0 +1,10 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+en_GB:
+ js:
+ explorer:
+ query_description: "Description"
diff --git a/plugins/discourse-data-explorer/config/locales/client.es.yml b/plugins/discourse-data-explorer/config/locales/client.es.yml
new file mode 100644
index 00000000000..f1c51a1a6b3
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.es.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+es:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Eliminar los punto y coma de la consulta."
+ dirty: "Debes guardar la consulta antes de ejecutarla."
+ explorer:
+ or: "o"
+ admins_only: "El explorador de datos solo esta disponible para administradores."
+ allow_groups: "Permitir a los grupos acceder a esta consulta"
+ title: "Explorador de datos"
+ create: "Crear nueva"
+ create_placeholder: "Nombre de la consulta..."
+ description_placeholder: "Escribe una descripción aquí"
+ import:
+ label: "Importar"
+ modal: "Importar una consulta"
+ unparseable_json: "Archivo JSON no analizable."
+ wrong_json: "Archivo JSON incorrecto. Debería contener un objeto «query», con al menos una propiedad «sql»."
+ help:
+ label: "Ayuda"
+ modal_title: "Ayuda sobre el explorador de datos"
+ auto_resolution: "<h2>Resolución automática de entidades</h2> <p>Cuando tu consulta devuelva el ID de una entidad, puede que el explorador de datos lo sustituya por el nombre de la entidad y otra información útil en los resultados de la consulta. La resolución automática está disponible para <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> y <i><b>badge_id</b></i>. Para probarla, ejecuta esta consulta:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Crear parámetros personalizados</h2><p>Para crear parámetros personalizados en tus consultas, pon lo siguiente al principio siguiendo el formato:</p><pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Nota: hay que incluir la primera línea con [params], además de los dos guiones que van al principio de la línea, y también debes incluir los guiones en cada parámetro personalizado que quieras declarar.</i></p>"
+ default_values: "<h3>Valores por defecto</h3> <p>Puedes declarar parámetros de manera que tengan o no un valor por defecto. Los valores por defecto aparecerán en un campo de texto debajo del editor de consultas, y puedes editarlos según lo necesites. Los parámetros declarados sin un valor por defecto también crearán un campo de texto, pero estará vacío y marcado en rojo.</p><pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Tipos de datos</h3> <p>Algunos tipos de datos que puedes usar:</p> <ul> <li><b>integer</b> - número entero de 4 bytes, positivo o negativo</li><li><b>text</b> - conjunto de caracteres de longitud variable</li><li><b>boolean</b> - true/false (verdadero/falso)</li><li><b>date</b> - date (año, mes, día)</li></ul><p>Para más información sobre los tipos de datos, visita <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>esta página</a>.</p>"
+ schema:
+ title: "Esquema de base de datos"
+ filter: "Buscar..."
+ sensitive: "Los contenidos de esta columna pueden incluir información particularmente sensible o privada. Ten cuidado cuando la uses."
+ types:
+ bool:
+ yes: "Sí"
+ no: "No"
+ null_: "Nulo"
+ export: "Exportar"
+ view_json: "Ver JSON"
+ save: "Guardar cambios"
+ saverun: "Guardar cambios y ejecutar"
+ run: "Ejecutar"
+ undo: "Descartar cambios"
+ edit: "Editar"
+ delete: "Eliminar"
+ recover: "Recuperar consulta"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabla"
+ show_graph: "Gráfico"
+ others_dirty: "Una consulta tiene cambios no guardados que se perderán si sales."
+ run_time: "Consulta completada en %{value} ms."
+ result_count:
+ one: "%{count} resultado."
+ other: "%{count} resultados."
+ max_result_count:
+ one: "Mostrando el mejor resultado (%{count})."
+ other: "Mostrando los mejores %{count} resultados."
+ query_name: "Consulta"
+ query_groups: "Grupos"
+ link: "Enlace para"
+ report_name: "Informe"
+ query_description: "Descripción"
+ query_time: "Última ejecución"
+ query_user: "Creado por"
+ column: "Columna %{number}"
+ explain_label: "¿Incluir plan de consulta?"
+ save_params: "Establecer configuración por defecto"
+ reset_params: "Restablecer"
+ search_placeholder: "Buscar..."
+ no_search_results: "Lo sentimos, no hemos podido encontrar ningún resultado que coincida con tu texto."
+ form:
+ errors:
+ invalid: "No válido"
+ no_such_category: "No existe dicha categoria"
+ no_such_group: "No existe dicho grupo"
+ invalid_date: "%{date} es una fecha no válida"
+ invalid_time: "%{time} es una hora no válida"
+ group:
+ reports: "Informes"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Ejecuta consultas del Explorador de Datos. Restringe la clave API a un conjunto de consultas especificando los ID de las mismas."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Enviar a usuario, grupo o correo electrónico
+ query_id:
+ label: Consulta del explorador de datos
+ query_params:
+ label: Parámetros de consulta del explorador de datos
+ skip_empty:
+ label: Omitir el envío de MP si no hay resultados
+ attach_csv:
+ label: Adjuntar el archivo CSV al MP
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: El tema en el que se publicarán los resultados de la consulta
+ query_id:
+ label: Consulta del Explorador de datos
+ query_params:
+ label: Parámetros de consulta del Explorador de datos
+ skip_empty:
+ label: Omitir la publicación si no hay resultados
+ attach_csv:
+ label: Adjuntar el archivo CSV a la publicación
diff --git a/plugins/discourse-data-explorer/config/locales/client.et.yml b/plugins/discourse-data-explorer/config/locales/client.et.yml
new file mode 100644
index 00000000000..a61b6af4411
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.et.yml
@@ -0,0 +1,40 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+et:
+ js:
+ explorer:
+ or: "või"
+ title: "Andmete eksportija"
+ create: "Loo uus"
+ create_placeholder: "Päringu nimi..."
+ import:
+ label: "Impordi"
+ modal: "Impordi päring"
+ help:
+ label: "Abi"
+ schema:
+ title: "Andmebaasi skeem"
+ filter: "Otsi..."
+ types:
+ bool:
+ yes: "Jah"
+ no: "Ei"
+ null_: "Nulli"
+ export: "Ekspordi"
+ save: "Salvesta muudatused"
+ saverun: "Salvesta muudatused ja käivita"
+ run: "Käivita"
+ undo: "Loobu muudatustest"
+ edit: "Muuda"
+ delete: "Kustuta"
+ download_json: "JSON"
+ download_csv: "CSV"
+ query_groups: "Grupid"
+ query_description: "Kirjeldus"
+ save_params: "Määra vaikeväärtused"
+ reset_params: "Nulli"
+ search_placeholder: "Otsi..."
diff --git a/plugins/discourse-data-explorer/config/locales/client.fa_IR.yml b/plugins/discourse-data-explorer/config/locales/client.fa_IR.yml
new file mode 100644
index 00000000000..1963b37fc23
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.fa_IR.yml
@@ -0,0 +1,41 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fa_IR:
+ js:
+ explorer:
+ or: "یا"
+ import:
+ label: "ورود داده‌ها"
+ help:
+ label: "کمک"
+ schema:
+ filter: "جستجو..."
+ types:
+ bool:
+ yes: "بله"
+ no: "خیر"
+ export: "خروجی گرفتن"
+ save: "ذخیره تغییرات"
+ run: "اجرا"
+ edit: "ویرایش"
+ delete: "حذف"
+ result_count:
+ one: "%{count} نتیجه."
+ other: "%{count} نتیجه."
+ max_result_count:
+ one: "نمایش %{count} نتیجه برتر."
+ other: "نمایش %{count} نتیجه برتر."
+ query_groups: "گروه ها"
+ link: "پیوند برای"
+ report_name: "گزارش"
+ query_description: "توضیح"
+ query_time: "آخرین اجرا"
+ query_user: "ایجاد شده توسط"
+ reset_params: "بازنشانی"
+ search_placeholder: "جستجو..."
+ group:
+ reports: "گزارشات"
diff --git a/plugins/discourse-data-explorer/config/locales/client.fi.yml b/plugins/discourse-data-explorer/config/locales/client.fi.yml
new file mode 100644
index 00000000000..9002c849ef4
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.fi.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fi:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Poista puolipisteet kyselystä."
+ dirty: "Kysely täytyy tallentaa ennen suorittamista."
+ explorer:
+ or: "tai"
+ admins_only: "Dataselain on vain ylläpitäjille."
+ allow_groups: "Salli ryhmien käyttää tätä kyselyä"
+ title: "Dataselain"
+ create: "Luo uusi"
+ create_placeholder: "Kyselyn nimi..."
+ description_placeholder: "Kirjoita kuvaus tähän"
+ import:
+ label: "Tuo"
+ modal: "Tuo kysely"
+ unparseable_json: "JSON-tiedosto ei ole jäsennettävissä."
+ wrong_json: "Väärä JSON-tiedosto. JSON-tiedoston tulisi sisältää query-objekti, jolla tulisi olla ainakin sql-ominaisuus."
+ help:
+ label: "Apua"
+ modal_title: "Dataselaimen ohje"
+ auto_resolution: "<h2>Automaattinen yksikön selvitys</h2> <p>Kun kyselysi palauttaa yksikön, Dataselain voi korvata sen automaattisesti yksikön nimellä ja muilla hyödyllisillä tiedoilla kyselyn tuloksissa. Automaattinen selvitys on käytettävissä <i><b>user_id</b></i>-, <i><b>group_id</b></i>-, <i><b>topic_id</b></i>-, <i><b>category_id</b></i>- ja <i><b>badge_id</b></i>-tietueissa. Voit kokeilla tätä suorittamalla tämän kyselyn:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Mukautettujen parametrien luominen</h2> <p>Voit luoda mukautettuja parametreja kyselyillesi lisäämällä tämän kyselysi yläosaan ja käyttämällä muotoa:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Huomautus: ensimmäinen rivi, jossa on [params], on pakollinen yhdessä sitä edeltävien väliviivojen kanssa, sekä jokainen mukautettu parametri, jonka haluat esitellä.</i></p>"
+ default_values: "<h3>Oletusarvot</h3> <p>Voit esitellä parametreja oletusarvoilla tai ilman. Oletusarvot näkyvät tekstikentässä kyselyeditorin alla, ja voit muokata niitä tarpeidesi mukaan. Ilman oletusarvoja esitellyt parametrit luovat tekstikentän, mutta ne ovat tyhjiä ja korostettu punaisena.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Datatyyppejä</h3> <p>Nämä ovat yleisiä datatyyppejä, joita voit käyttää:</p> <ul> <li><b>kokonaisluku</b> – etumerkillinen nelitavuinen kokonaisluku</li> <li><b>teksti</b> – vaihtelevanpituinen merkkijono</li> <li><b>totuusarvo</b> – tosi/epätosi</li> <li><b>päivämäärä</b> – kalenteripäivä (vuosi, kuukausi, päivä)</li> </ul> <p>Lisätietoja datatyypeistä saat <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>tältä verkkosivustolta</a>.</p>"
+ schema:
+ title: "Tietokannan rakenne"
+ filter: "Hae..."
+ sensitive: "Tämän sarakkeen sisältö voi sisältää erityisen arkaluontoista tai yksityistä tietoa. Noudata erityistä harkintaa käyttäessäsi sarakkeen sisältämää tietoa."
+ types:
+ bool:
+ yes: "Kyllä"
+ no: "Ei"
+ null_: "Tyhjä"
+ export: "Vie"
+ view_json: "Näytä JSON"
+ save: "Tallenna muutokset"
+ saverun: "Tallenna muutokset ja suorita"
+ run: "Suorita"
+ undo: "Kumoa muutokset"
+ edit: "Muokkaa"
+ delete: "Poista"
+ recover: "Palauta poistettu kysely"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Taulukko"
+ show_graph: "Kaavio"
+ others_dirty: "Kyselyyn tehdyt tallentamattomat muutokset menetetään, jos navigoit pois."
+ run_time: "Kysely suoritettu %{value} millisekunnissa."
+ result_count:
+ one: "%{count} tulos."
+ other: "%{count} tulosta."
+ max_result_count:
+ one: "Näytetään osuvin %{count} tulos."
+ other: "Näytetään osuvimmat %{count} tulosta."
+ query_name: "Kysely"
+ query_groups: "Ryhmät"
+ link: "Linkki:"
+ report_name: "Raportti"
+ query_description: "Kuvaus"
+ query_time: "Viimeksi suoritettu"
+ query_user: "Luonut"
+ column: "Sarake %{number}"
+ explain_label: "Sisällytä kyselysuunnitelma?"
+ save_params: "Aseta oletusarvot"
+ reset_params: "Nollaa"
+ search_placeholder: "Hae..."
+ no_search_results: "Pahoittelut, emme löytäneet tekstiäsi vastaavia tuloksia."
+ form:
+ errors:
+ invalid: "Virheellinen"
+ no_such_category: "Tällaista luokkaa ei ole"
+ no_such_group: "Tällaista ryhmää ei ole"
+ invalid_date: "%{date} on virheellinen päivämäärä"
+ invalid_time: "%{time} on virheellinen aika"
+ group:
+ reports: "Raportit"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Suorita Dataselaimen kyselyitä. Rajoita API-avain tiettyihin kyselyihin määrittämällä kyselyiden tunnuksia."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Lähetä käyttäjälle, ryhmälle tai sähköpostiosoitteeseen
+ query_id:
+ label: Dataselaimen kysely
+ query_params:
+ label: Dataselaimen kyselyparametrit
+ skip_empty:
+ label: Ohita yksityisviestin lähettäminen, jos tuloksia ei ole
+ attach_csv:
+ label: Liitä CSV-tiedosto yksityisviestiin
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: Ketju, johon kyselyn tulokset lähetetään
+ query_id:
+ label: Dataselaimen kysely
+ query_params:
+ label: Dataselaimen kyselyparametrit
+ skip_empty:
+ label: Ohita viestin lähettäminen, jos tuloksia ei ole
+ attach_csv:
+ label: Liitä CSV-tiedosto viestiin
diff --git a/plugins/discourse-data-explorer/config/locales/client.fr.yml b/plugins/discourse-data-explorer/config/locales/client.fr.yml
new file mode 100644
index 00000000000..b2d912cdd22
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.fr.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fr:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Supprimez les points-virgules de la requête."
+ dirty: "Vous devez enregistrer la requête avant de l'exécuter."
+ explorer:
+ or: "ou"
+ admins_only: "L'explorateur de données n'est disponible que pour les administrateurs."
+ allow_groups: "Autoriser les groupes à accéder à cette requête"
+ title: "Explorateur de données"
+ create: "Nouvelle requête"
+ create_placeholder: "Nom de la requête…"
+ description_placeholder: "Saisissez une description ici"
+ import:
+ label: "Importer"
+ modal: "Importer une requête"
+ unparseable_json: "Fichier JSON non analysable."
+ wrong_json: "Fichier JSON incorrect. Un fichier JSON doit contenir un objet « query », qui doit au moins avoir une propriété « sql »."
+ help:
+ label: "Aide"
+ modal_title: "Aide de l'explorateur de données"
+ auto_resolution: "<h2>Résolution d'entité automatique</h2> <p>Lorsque votre requête renvoie un identifiant d'entité, l'explorateur de données peut le remplacer automatiquement par le nom de l'entité et d'autres informations utiles dans les résultats de la requête. La résolution automatique est disponible pour <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> et <i><b>badge_id</b></i>. Pour essayer cette fonction, exécutez cette requête :</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Création de paramètres personnalisés</h2> <p>Pour créer des paramètres personnalisés pour vos requêtes, placez ceci en haut de votre requête et respectez le format :</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Remarque : la première ligne avec [params] est requise, ainsi que les deux tirets qui la précèdent et chaque paramètre personnalisé que vous souhaitez déclarer.</i></p>"
+ default_values: "<h3>Valeurs par défaut</h3> <p>Vous pouvez déclarer des paramètres avec ou sans valeurs par défaut. Les valeurs par défaut s'afficheront dans un champ de texte sous l'éditeur de requête, que vous pourrez modifier selon vos besoins. Les paramètres déclarés sans valeurs par défaut généreront toujours un champ de texte, mais seront vides et surlignés en rouge.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Types de données</h3> <p>Voici les types de données courants que vous pouvez utiliser :</p> <ul> <li><b>integer</b> - entier signé à quatre octets</li> <li><b>text</b> - chaîne de caractères de longueur variable</li> <li><b>boolean</b> - vrai/faux</li> <li><b>date</b> - date calendaire (année, mois, jour)</li> </ul> <p>Pour plus d'informations concernant les types de données, visitez <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>ce site Web</a>.</p>"
+ schema:
+ title: "Schéma de la base de données"
+ filter: "Recherche…"
+ sensitive: "Le contenu de cette colonne peut contenir des informations particulièrement sensibles ou privées. Veuillez faire preuve de prudence lorsque vous utilisez ce contenu."
+ types:
+ bool:
+ yes: "Oui"
+ no: "Non"
+ null_: "Nul"
+ export: "Exporter"
+ view_json: "Afficher JSON"
+ save: "Enregistrer les modifications"
+ saverun: "Enregistrer les modifications et exécuter"
+ run: "Exécuter"
+ undo: "Annuler les modifications"
+ edit: "Modifier"
+ delete: "Supprimer"
+ recover: "Annuler la suppression de la requête"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tableau"
+ show_graph: "Graphique"
+ others_dirty: "Une requête comporte des modifications non enregistrées qui seront perdues si vous quittez la page"
+ run_time: "Requête exécutée en %{value} millisecondes."
+ result_count:
+ one: "%{count} résultat."
+ other: "%{count} résultats."
+ max_result_count:
+ one: "Affichage du premier (%{count}) résultat."
+ other: "Affichage des %{count} premiers résultats."
+ query_name: "Requête"
+ query_groups: "Groupes"
+ link: "Lien pour"
+ report_name: "Rapport"
+ query_description: "Description"
+ query_time: "Dernière exécution"
+ query_user: "Créée par"
+ column: "Colonne %{number}"
+ explain_label: "Inclure le plan d'exécution ?"
+ save_params: "Définir les valeurs par défaut"
+ reset_params: "Réinitialiser"
+ search_placeholder: "Recherche…"
+ no_search_results: "Désolé, nous n'avons trouvé aucun résultat correspondant à votre texte."
+ form:
+ errors:
+ invalid: "Invalide"
+ no_such_category: "Aucune catégorie de ce type"
+ no_such_group: "Aucun groupe de ce type"
+ invalid_date: "%{date} est une date invalide"
+ invalid_time: "%{time} est une heure invalide"
+ group:
+ reports: "Rapports"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Exécutez des requêtes de l'explorateur de données. Limitez la clé API à un ensemble de requêtes en spécifiant des ID de requêtes."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Envoyer à l'utilisateur, au groupe ou à l'adresse e-mail
+ query_id:
+ label: Requête de l'explorateur de données
+ query_params:
+ label: Paramètres de requête de l'explorateur de données
+ skip_empty:
+ label: Ignorer l'envoi d'un MP s'il n'y a aucun résultat
+ attach_csv:
+ label: Joindre le fichier CSV au MD
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: Le sujet dans lequel les résultats de la requête doivent être affichés
+ query_id:
+ label: Requête de l'explorateur de données
+ query_params:
+ label: Paramètres de requête de l'explorateur de données
+ skip_empty:
+ label: Ignorer la publication s'il n'y a aucun résultat
+ attach_csv:
+ label: Joindre le fichier CSV à la publication
diff --git a/plugins/discourse-data-explorer/config/locales/client.gl.yml b/plugins/discourse-data-explorer/config/locales/client.gl.yml
new file mode 100644
index 00000000000..1703ead27b3
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.gl.yml
@@ -0,0 +1,31 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+gl:
+ js:
+ explorer:
+ or: "ou"
+ import:
+ label: "Importar"
+ help:
+ label: "Axuda"
+ schema:
+ filter: "Buscar..."
+ types:
+ bool:
+ yes: "Si"
+ no: "Non"
+ export: "Exportar"
+ save: "Gardar os cambios"
+ edit: "Editar"
+ delete: "Eliminar"
+ query_groups: "Grupos"
+ query_description: "Descrición"
+ query_user: "Creado por"
+ reset_params: "Restabelecer"
+ search_placeholder: "Buscar..."
+ group:
+ reports: "Informes"
diff --git a/plugins/discourse-data-explorer/config/locales/client.he.yml b/plugins/discourse-data-explorer/config/locales/client.he.yml
new file mode 100644
index 00000000000..0d50dabf2dc
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.he.yml
@@ -0,0 +1,122 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+he:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "הסרת הנקודה פסיק מהשאילתה."
+ dirty: "עליך לשמור את השאילתה בטרם ההרצה."
+ explorer:
+ or: "או"
+ admins_only: "דפדפן הנתונים זמין למנהלים בלבד."
+ allow_groups: "לאפשר לקבוצות לגשת לשאילתה הזאת"
+ title: "דפדפן נתונים"
+ create: "יצירת חדשה"
+ create_placeholder: "שם השאילתה…"
+ description_placeholder: "יש להקליד תיאור כאן"
+ import:
+ label: "ייבוא"
+ modal: "ייבוא שאילתה"
+ unparseable_json: "קובץ JSON שאינו ניתן לפענוח."
+ wrong_json: "קובץ JSON שגוי. קובץ JSON צריך להכיל רכיב ‚query’, שצריך לכלול לפחות מאפיין ‚sql’."
+ help:
+ label: "עזרה"
+ modal_title: "עזרה עם דפדפן הנתונים"
+ auto_resolution: "<h2>אבחנת יישות אוטומטית</h2> <p>כאשר השאילתה שלך מחזירה מזהה יישות, סייר הנתונים עשוי להחליף אותו בשם היישות ובפרטים מועילים נוספים אוטומטית בתוצאות השאילתה. אבחנה אוטומטית זמינה עבור <i><b>user_id</b></i>,‏ <i><b>group_id</b></i>,‏ <i><b>topic_id</b></i>,‏ <i><b>category_id</b></i> ו־<i><b>badge_id</b></i>. כדי לנסות זאת יש להריץ את השאילתה הבאה:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>יצירת משתנים מותאמים אישית</h2> <p>כדי ליצור משתנים מותאמים אישית לשאילתות שלך, יש להציב זאת בראש השאילתה ולהיצמד לתבנית:</p> ‎<pre><code>‎-- [params]\n‎-- int :num = 1\n\nSELECT :num</code></pre> <p><i>לתשומך לבך: השורה הראשונה עם [params] נחוצה, בצירוף שני מינוסים לפניה וכל משתנה מותאם אישית שעליו ברצונך להכריז.</i></p>"
+ default_values: "<h3>ערכי בררת מחדל</h3> <p>ניתן להכריז על משתנים עם או בלי ערכי בררת מחדל. ערכי בררת מחדל יופיעו בשדה טקסט מעל לעורך השאילתות אותם ניתן לערוך בהתאם לצורך. משתנים שמוכרזים ללא ערכי בררת מחדל עדיין ייצרו שדה טקסט אך הם יהיו ריקים ויודגשו באדום.</p> <pre><code>‎-- [params]\n‎-- text :username = my_username\n‎-- int :age</code></pre>"
+ data_types: "<h3>סוגי נתונים</h3> <p>להלן סוגי הנתונים הנפוצים בהם ניתן להשתמש:</p> <ul> <li><b>integer</b> - מספר שלם וחיובי בגודל ארבעה בתים</li> <li><b>text</b> - מחרוזת תווים באורך משתנה</li> <li><b>boolean</b> – אמת/שקר</li> <li><b>date</b> - תאריך בלוח השנה (שנה, חודש, יום)</li> </ul> <p>למידע נוסף על סוגי נתונים ניתן לבקר <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>באתר הזה</a>.</p>"
+ schema:
+ title: "סכמת מסד הנתונים"
+ filter: "חיפוש…"
+ sensitive: "תכני העמודה הזו עשויים להכיל מידע רגיש או פרטי. נא לנקוט במשנה זהירות בעת השימוש בעמודה זו."
+ types:
+ bool:
+ yes: "כן"
+ no: "לא"
+ null_: "ריק"
+ export: "ייצוא"
+ view_json: "הצגת JSON"
+ save: "שמירת שינויים"
+ saverun: "שמירת השינויים והרצה"
+ run: "הרצה"
+ undo: "התעלמות מהשינויים"
+ edit: "עריכה"
+ delete: "מחיקה"
+ recover: "ביטול מחיקת השאילתה"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "טבלה"
+ show_graph: "תרשים"
+ others_dirty: "בשאילתה נערכו שינויים שטרם נשמרו ועשויים ללכת לאיבוד עקב ניווט למקום אחר."
+ run_time: "השאילתה הושלמה תוך %{value} מילישניות."
+ result_count:
+ one: "תוצאה אחת."
+ two: "2 תוצאות."
+ many: "%{count} תוצאות."
+ other: "%{count} תוצאות."
+ max_result_count:
+ one: "התוצאה המובילה מופיעה (%{count})."
+ two: "%{count} התוצאות המובילות מופיעות."
+ many: "%{count} התוצאות המובילות מופיעות."
+ other: "%{count} התוצאות המובילות מופיעות."
+ query_name: "שאילתה"
+ query_groups: "קבוצות"
+ link: "קישור אל"
+ report_name: "דוח"
+ query_description: "תיאור"
+ query_time: "הרצה אחרונה"
+ query_user: "נוצר על ידי"
+ column: "עמודה %{number}"
+ explain_label: "לכלול תכנית שאילתה?"
+ save_params: "הגדרת בררות מחדל"
+ reset_params: "איפוס"
+ search_placeholder: "חיפוש…"
+ no_search_results: "לא הצלחנו למצוא תוצאות שעונות לטקסט שלך, עמך הסליחה."
+ form:
+ errors:
+ invalid: "שגוי"
+ no_such_category: "אין קטגוריה כזו"
+ no_such_group: "אין קבוצה כזו"
+ invalid_date: "%{date} הוא תאריך שגוי"
+ invalid_time: "%{time} היא שעה שגויה"
+ group:
+ reports: "דוחות"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "הרצת שאילתות של סייר נתונים. ניתן להגביל את מפתח ה־API לסדרה של שאילתות על ידי ציון מזהה שאילתה."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: שליחה למשתמש, לקבוצה או לדוא״ל
+ query_id:
+ label: שאילתת דפדפן נתונים
+ query_params:
+ label: משתני שאילתת דפדפן נתונים
+ skip_empty:
+ label: דילוג על שליחת הודעה פרטית אם אין תוצאות
+ attach_csv:
+ label: צירוף קובץ ה־CSV להודעה הפרטית
+ users_from_group:
+ label: שליחת הודעה פרטית לכל חבר בקבוצה
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: הנושא לפרסום תוצאות השאילתה אליו
+ query_id:
+ label: שאילתת דפדפן נתונים
+ query_params:
+ label: משתני שאילתת דפדפן נתונים
+ skip_empty:
+ label: דילוג על פרסום אם אין תוצאות
+ attach_csv:
+ label: צירוף קובץ ה־CSV לפוסט
diff --git a/plugins/discourse-data-explorer/config/locales/client.hr.yml b/plugins/discourse-data-explorer/config/locales/client.hr.yml
new file mode 100644
index 00000000000..dad01a41b77
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.hr.yml
@@ -0,0 +1,33 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hr:
+ js:
+ explorer:
+ or: "ili"
+ help:
+ label: "Pomoć"
+ schema:
+ filter: "Pretraži..."
+ types:
+ bool:
+ yes: "Da"
+ no: "Ne"
+ export: "Izvoz"
+ save: "Zabilježi promjene"
+ edit: "Izmijeni"
+ delete: "Pobriši"
+ result_count:
+ one: "%{count} rezultat."
+ few: "%{count} rezultata."
+ other: "%{count} rezultata."
+ query_groups: "Grupe"
+ query_description: "Opis"
+ query_user: "Napravio"
+ reset_params: "Resetirati"
+ search_placeholder: "Pretraži..."
+ group:
+ reports: "Izvještaji"
diff --git a/plugins/discourse-data-explorer/config/locales/client.hu.yml b/plugins/discourse-data-explorer/config/locales/client.hu.yml
new file mode 100644
index 00000000000..18a659075c5
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.hu.yml
@@ -0,0 +1,73 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hu:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Pontosvesszők eltávolítása a lekérdezésből."
+ dirty: "Futtatás előtt el kell mentenie a lekérdezést."
+ explorer:
+ or: "vagy"
+ admins_only: "Az adatfelfedező csak az adminok számára érhető el."
+ allow_groups: "Engedélyezés csoportok számára, hogy hozzáférjenek ehhez a lekérdezéshez"
+ title: "Adatfelfedező"
+ create: "Új létrehozása"
+ create_placeholder: "Lekérdezés neve…"
+ description_placeholder: "Adjon meg egy leírást"
+ import:
+ label: "Importálás"
+ modal: "Lekérdezés importálása"
+ unparseable_json: "Nem értelmezhető JSON-fájl."
+ wrong_json: "Hibás JSON-fájl. A JSON-fájlnak kellene tartalmaznia egy „query” objektumot, amelynek legalább egy „sql” tulajdonsággal kell rendelkeznie."
+ help:
+ label: "Súgó"
+ modal_title: "Adatfelfedező súgó"
+ auto_resolution: "<h2>Automatikus entitásfeloldás</h2> <p>Ha egy lekérdezés egy entitásazonosítót ad vissza, akkor az Adatfelfedező automatikusan lecserélheti az entitás nevére és más hasznos információkra a találatokban. Az automatikus feloldás ezeknél érhető el: <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> és <i><b>badge_id</b></i>. Próbálja ki ezen lekérdezés futtatásával:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Egyéni paraméterek létrehozása</h2> <p>Hogy egyéni paramétereket hozzon létre a lekérdezéseihez, tegye ezt a lekérdezés fölé, és kövesse a formátumot:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Megjegyzés: a [params] sor kötelező, az azt megelőző két kötőjellel együtt, és deklarálnia kell minden egyes egyéni paramétert.</i></p>"
+ default_values: "<h3>Alapértelmezett értékek</h3> <p>Deklarálhatja a paramétereket alapértelmezett értékkel vagy azok nélkül. Az alapértelmezett értékek meg fognak jelenni a szövegmezőben, a lekérdezésszerkesztő alatt, amellyel a céljainak megfelelően szerkesztheti azokat. Az alapértelmezett érték nélküli paraméterek is szövegmezőt fognak kapni, de üresek lesznek, és pirossal lesznek kiemelve..</p> <pre><code>-- [params]\n-- text :username = saját_felhasználónév\n-- int :age</code></pre>"
+ data_types: "<h3>Adattípusok</h3> <p>Itt szerepel néhány gyakori használható adattípus:</p> <ul> <li><b>integer</b> - előjeles négybájtos egész</li> <li><b>text</b> - változó hosszúságú karakterlánc</li> <li><b>boolean</b> – igaz/hamis</li> <li><b>date</b> - naptári dátum (év, hó, nap)</li> </ul> <p>További információkért az adattípusokról, keresse fel <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>ezt a weboldalt</a>.</p>"
+ schema:
+ title: "Adatbázis-séma"
+ filter: "Keresés…"
+ sensitive: "Az oszlop tartalma különösen érzékeny vagy privát információkat tartalmazhat. Legyen óvatos az oszlop tartalmának használatakor."
+ types:
+ bool:
+ yes: "Igen"
+ no: "Nem"
+ null_: "Null"
+ export: "Exportálás"
+ save: "Módosítások mentése"
+ saverun: "Módosítások mentése és futtatása"
+ run: "Futtatás"
+ undo: "Módosítások elvetése"
+ edit: "Szerkesztés"
+ delete: "Törlés"
+ recover: "Lekérdezés törlésének visszavonása"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tábla"
+ show_graph: "Grafikon"
+ others_dirty: "A lekérdezés nem mentett módosításokat tartalmaz, amelyek elvesznek, ha elnavigál."
+ run_time: "A lekérdezés %{value} ms alatt fejeződött be."
+ result_count:
+ one: "%{count} találat."
+ other: "%{count} találat."
+ query_name: "Lekérdezés"
+ query_groups: "Csoportok"
+ link: "Hivatkozás ehhez:"
+ report_name: "Jelentés"
+ query_description: "Leírás"
+ query_time: "Utolsó futás"
+ query_user: "Létrehozta:"
+ column: "%{number}. oszlop"
+ explain_label: "Beleveszi a lekérdezési tervet?"
+ save_params: "Alapértékek beállítása"
+ reset_params: "Alaphelyzet"
+ search_placeholder: "Keresés…"
+ no_search_results: "Sajnos nem találtunk a szövegének megfelelő találatot."
+ group:
+ reports: "Jelentések"
diff --git a/plugins/discourse-data-explorer/config/locales/client.hy.yml b/plugins/discourse-data-explorer/config/locales/client.hy.yml
new file mode 100644
index 00000000000..1a3902df8bc
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.hy.yml
@@ -0,0 +1,59 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hy:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Հեռացրեք կետ-ստորակատերերը հարցումից"
+ dirty: "Դուք պետք է պահպանեք հարցումը գործարկելուց առաջ"
+ explorer:
+ or: "կամ"
+ admins_only: "Տվյալների ուսումնասիրումը հասանելի է միասյն ադմիններին:"
+ title: "Տվյալների Ուսումնասիրում"
+ create: "Ստեղծել Նոր"
+ create_placeholder: "Հարցման անուն..."
+ description_placeholder: "Մուտքագրեք նկարագրություն այստեղ"
+ import:
+ label: "Ներմուծել"
+ modal: "Ներմուծել Հարցում"
+ help:
+ label: "Օգնություն"
+ schema:
+ title: "Տվյալների Բազայի Սխեմա"
+ filter: "Որոնում..."
+ sensitive: "Այս սյունակը կարող է պարունակել մասնակի անձնական կամ անձնական տեղեկություններ: Խնդրում ենք ուշադիր լինել այս սյունակի բովանդակությունն օգտագործելիս:"
+ types:
+ bool:
+ yes: "Այո"
+ no: "Ոչ"
+ null_: "Զրոյական"
+ export: "Արտահանել"
+ save: "Պահպանել Փոփոխությունները"
+ saverun: "Պահպանել փոփոխությունները և Գործարկել"
+ run: "Գործարկել"
+ undo: "Չեղարկել Փոփոխությունները"
+ edit: "Խմբագրել"
+ delete: "Ջնջել"
+ recover: "Վերականգնել Հարցումը"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "Հարցումն ունի չպահպանված փոփոխություններ, որոնք կկորչեն, եթե Դուք տեղափոխվեք:"
+ result_count:
+ one: "%{count} արդյունք"
+ other: "%{count} արդյունք"
+ query_name: "Հարցում"
+ query_groups: "Խմբեր"
+ query_description: "Նկարագրություն"
+ query_time: "Վերջին գործարկումը"
+ query_user: "Ստեղծել է՝"
+ explain_label: "Ներառե՞լ հարցման պլանը:"
+ save_params: "Սահմանել Լռելյայններ"
+ reset_params: "Վերահաստատե;"
+ search_placeholder: "Որոնում..."
+ no_search_results: "Ներողություն, մենք չկարողացանք գտնել Ձեր տեքստի հետ համընկնող որևէ արդյունք:"
+ group:
+ reports: "Հաշվետվություններ"
diff --git a/plugins/discourse-data-explorer/config/locales/client.id.yml b/plugins/discourse-data-explorer/config/locales/client.id.yml
new file mode 100644
index 00000000000..f9a91c5f7ba
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.id.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+id:
+ js:
+ explorer:
+ or: "atau"
+ help:
+ label: "Bantuan"
+ schema:
+ filter: "Cari..."
+ types:
+ bool:
+ yes: "Ya"
+ no: "Tidak"
+ export: "Ekspor"
+ save: "Simpan perubahan"
+ edit: "Ubah"
+ delete: "Hapus"
+ query_groups: "Grup"
+ query_description: "Deskripsi"
+ reset_params: "Reset"
+ search_placeholder: "Cari..."
diff --git a/plugins/discourse-data-explorer/config/locales/client.it.yml b/plugins/discourse-data-explorer/config/locales/client.it.yml
new file mode 100644
index 00000000000..c8e74ffb58e
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.it.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+it:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Rimuovi i punti e virgola dalla query."
+ dirty: "È necessario salvare la query prima di eseguirla."
+ explorer:
+ or: "oppure"
+ admins_only: "Data explorer è disponibile solo per gli amministratori."
+ allow_groups: "Consenti ai gruppi di accedere a questa query"
+ title: "Data Explorer"
+ create: "Crea Nuovo"
+ create_placeholder: "Nome query..."
+ description_placeholder: "Inserisci una descrizione qui"
+ import:
+ label: "Importa"
+ modal: "Importa una query"
+ unparseable_json: "File JSON non analizzabile."
+ wrong_json: "File JSON errato. Un file JSON dovrebbe contenere un oggetto \"query\" contenente almeno una proprietà \"sql\"."
+ help:
+ label: "Guida"
+ modal_title: "Guida di Data Explorer"
+ auto_resolution: "<h2>Risoluzione automatica dell'entità</h2> <p>Quando la query restituisce l'ID di un'entità, Data Explorer può sostituirla automaticamente con il nome dell'entità e altre informazioni utili nei risultati delle query. La risoluzione automatica è disponibile per i dati <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> e <i><b>badge_id</b></i>. Fai una prova, eseguendo questa query:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Creazione di parametri personalizzati</h2> <p>Per creare parametri personalizzati per le query, inserisci questo codice nella parte superiore della query e segui il formato:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Nota: la prima riga con [params] è obbligatoria, come i due trattini che precedono e tutti i parametri personalizzati che intendi dichiarare.</i></p>"
+ default_values: "<h3>Valori predefiniti</h3> <p>È possibile dichiarare parametri con o senza valori predefiniti. I valori predefiniti verranno visualizzati in un campo di testo sotto l'editor di query, che può essere modificato in base alle esigenze. I parametri dichiarati senza valori predefiniti genereranno comunque un campo di testo, ma saranno vuoti ed evidenziati in rosso.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Tipi di dati</h3> <p>Di seguito sono riportati i tipi di dati comuni che puoi utilizzare:</p> <ul> <li><b>integer</b> - intero a quattro byte con segno</li> <li><b>text</b> - stringa di caratteri di lunghezza variabile</li> <li><b>boolean</b> – valore vero/falso</li> <li><b>data</b> - data di calendario (anno, mese, giorno)</li> </ul> <p>Per ulteriori informazioni sui tipi di dati, visita <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>questo sito web</a>.</p>"
+ schema:
+ title: "Schema del Database "
+ filter: "Ricerca..."
+ sensitive: "Questa colonna potrebbe contenere dati sensibili o informazioni private. Occorre prestare particolare attenzione nell'uso dei contenuti di questa colonna."
+ types:
+ bool:
+ yes: "Sì"
+ no: "No"
+ null_: "Null"
+ export: "Esporta"
+ view_json: "Visualizza JSON"
+ save: "Salva Modifiche"
+ saverun: "Salva modifiche ed esegui"
+ run: "Esegui"
+ undo: "Annulla Modifiche"
+ edit: "Modifica"
+ delete: "Elimina"
+ recover: "Ripristina Query"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabella"
+ show_graph: "Grafico"
+ others_dirty: "Una query ha modifiche non salvate che andranno perse se esci."
+ run_time: "Query completata in %{value} ms."
+ result_count:
+ one: "%{count} risultato."
+ other: "%{count} risultati."
+ max_result_count:
+ one: "Visualizzazione del primo (%{count}) risultato"
+ other: "Visualizzazione dei primi %{count} risultati."
+ query_name: "Query"
+ query_groups: "Gruppi"
+ link: "Collegamento per"
+ report_name: "Rapporto"
+ query_description: "Descrizione"
+ query_time: "Ultima esecuzione"
+ query_user: "Creato da"
+ column: "Colonna %{number}"
+ explain_label: "Includere il piano query?"
+ save_params: "Imposta Predefiniti"
+ reset_params: "Reimposta"
+ search_placeholder: "Ricerca..."
+ no_search_results: "Spiacenti, non abbiamo trovato alcun risultato che corrisponda al tuo testo."
+ form:
+ errors:
+ invalid: "Non valido"
+ no_such_category: "Categoria inesistente"
+ no_such_group: "Gruppo inesistente"
+ invalid_date: "%{date} è una data non valida"
+ invalid_time: "%{time} è un orario non valido"
+ group:
+ reports: "Rapporti"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Esegui le query di Data Explorer. Limita la chiave API a un insieme di query specificando i loro ID."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Invia a utente, gruppo o e-mail
+ query_id:
+ label: Query di Data Explorer
+ query_params:
+ label: Parametri della query di Data Explorer
+ skip_empty:
+ label: Salta l'invio di MP se non ci sono risultati
+ attach_csv:
+ label: Allega il file CSV al MP
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: L'argomento in cui pubblicare i risultati della query
+ query_id:
+ label: Query di Data Explorer
+ query_params:
+ label: Parametri della query di Data Explorer
+ skip_empty:
+ label: Salta la pubblicazione se non ci sono risultati
+ attach_csv:
+ label: Allega il file CSV all'argomento
diff --git a/plugins/discourse-data-explorer/config/locales/client.ja.yml b/plugins/discourse-data-explorer/config/locales/client.ja.yml
new file mode 100644
index 00000000000..ccd239003f2
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ja.yml
@@ -0,0 +1,114 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ja:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "クエリからセミコロンを削除します。"
+ dirty: "クエリは保存してから実行する必要があります。"
+ explorer:
+ or: "または"
+ admins_only: "データエクスプローラーは管理者のみが利用できます。"
+ allow_groups: "このクエリへのアクセスをグループに許可する"
+ title: "データエクスプローラー"
+ create: "新規作成"
+ create_placeholder: "クエリ名..."
+ description_placeholder: "説明をここに入力"
+ import:
+ label: "インポート"
+ modal: "クエリをインポート"
+ unparseable_json: "解析不能な JSON ファイルです。"
+ wrong_json: "不正な JSON ファイル。JSON ファイルには 'query' オブジェクトと、その中に少なくとも 'sql' プロパティが含まれている必要があります。"
+ help:
+ label: "ヘルプ"
+ modal_title: "データエクスプローラーのヘルプ"
+ auto_resolution: "<h2>エンティティの自動解決</h2> <p>クエリがエンティティ ID を返す場合、データエクスプローラーはクエリ結果において、それを自動的にエンティティ名とその他の有用な情報に置き換えることができます。自動解決は、<i><b>user_id</b></i>、<i><b>group_id</b></i>、<i><b>topic_id</b></i>、<i><b>category_id</b></i>、および <i><b>badge_id</b></i> で利用できます。次のクエリを実行して試してください。</p>\n<pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>カスタムパラメーターの作成</h2> <p>クエリのカスタムパラメーターを作成するには、次のコードをクエリの先頭に配置し、フォーマットに従います。</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>注意: 最初の [params] の行は必須です。また、その前と宣言するカスタムパラメーターの前に 2 つのダッシュが必要です。</i></p>"
+ default_values: "<h3>デフォルト値</h3> <p>パラメーターはデフォルト値の有無に関係なく宣言できます。デフォルト値はクエリエディターの下のテキストフィールドに表示され、必要に応じて編集することができます。パラメーターはデフォルト値なしで宣言された場合でもテキストフィールドを生成しますが、空となり、赤でハイライトされます。</p>\n<pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>データ型</h3> <p>以下は、使用できる共通のデータ型です。</p> <ul> <li><b>整数</b> - 符号付き 4 バイト整数</li> <li><b>テキスト</b> - 可変長文字列</li> <li><b>ブール</b> – true/false</li> <li><b>日付</b> - 暦日(年、月、日)</li> </ul> <p>データ型の詳細については、<a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>こちらのウェブサイト</a>をご覧ください。</p>"
+ schema:
+ title: "データベーススキーマ"
+ filter: "検索..."
+ sensitive: "この列のコンテンツには、機密性の特に高い情報または個人情報が含まれることがあります。この列のコンテンツを使用する際には十分注意してください。"
+ types:
+ bool:
+ yes: "はい"
+ no: "いいえ"
+ null_: "Null"
+ export: "エクスポート"
+ view_json: "JSON を表示"
+ save: "変更を保存"
+ saverun: "変更を保存して実行"
+ run: "実行"
+ undo: "変更を破棄"
+ edit: "編集"
+ delete: "削除"
+ recover: "クエリの削除を取り消す"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "テーブル"
+ show_graph: "グラフ"
+ others_dirty: "クエリには保存されていない変更があり、移動すると失われます。"
+ run_time: "クエリは %{value} ミリ秒で完了しました。"
+ result_count:
+ other: "%{count} 件の結果。"
+ max_result_count:
+ other: "上位 %{count} 件を表示中。"
+ query_name: "クエリ"
+ query_groups: "グループ"
+ link: "リンク"
+ report_name: "レポート"
+ query_description: "説明"
+ query_time: "最終実行"
+ query_user: "作成者"
+ column: "列 %{number}"
+ explain_label: "クエリプランを含めますか?"
+ save_params: "デフォルトを設定"
+ reset_params: "リセット"
+ search_placeholder: "検索..."
+ no_search_results: "残念ながら、テキストに一致する結果は見つかりませんでした。"
+ form:
+ errors:
+ invalid: "無効です"
+ no_such_category: "そのようなカテゴリはありません"
+ no_such_group: "そのようなグループはありません"
+ invalid_date: "%{date} は無効な日付です"
+ invalid_time: "%{time} は無効な時刻です"
+ group:
+ reports: "レポート"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "データエクスプローラーのクエリを実行します。クエリ ID を指定して、API キーを一連のクエリに制限します。"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: ユーザー、グループ、またはメールに送る
+ query_id:
+ label: データエクスプローラーのクエリ
+ query_params:
+ label: データエクスプローラーのクエリパラメーター
+ skip_empty:
+ label: 結果がない場合は PM の送信をスキップする
+ attach_csv:
+ label: CSV ファイルを PM に添付する
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: クエリ結果を投稿するトピック
+ query_id:
+ label: データエクスプローラーのクエリ
+ query_params:
+ label: データエクスプローラーのクエリパラメーター
+ skip_empty:
+ label: 結果が無い場合は投稿をスキップする
+ attach_csv:
+ label: CSV ファイルを投稿に添付する
diff --git a/plugins/discourse-data-explorer/config/locales/client.ko.yml b/plugins/discourse-data-explorer/config/locales/client.ko.yml
new file mode 100644
index 00000000000..daafaf511e0
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ko.yml
@@ -0,0 +1,61 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ko:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "쿼리에서 세미콜론을 제거하십시오."
+ dirty: "실행하기 전에 쿼리를 저장해야합니다."
+ explorer:
+ or: "또는"
+ admins_only: "데이터 탐색기는 관리자 만 사용할 수 있습니다."
+ allow_groups: "그룹이이 쿼리에 액세스하도록 허용"
+ title: "데이터 탐색기"
+ create: "새로 만들기"
+ create_placeholder: "검색어 이름 ..."
+ description_placeholder: "여기에 설명을 입력하세요"
+ import:
+ label: "가져오기"
+ modal: "검색어 가져 오기"
+ help:
+ label: "도움말"
+ schema:
+ title: "데이터베이스 스키마"
+ filter: "검색..."
+ sensitive: "이 열의 내용에는 특히 민감한 정보 또는 개인 정보가 포함될 수 있습니다. 이 열의 내용을 사용할 때는주의하십시오."
+ types:
+ bool:
+ yes: "네"
+ no: "아니오"
+ null_: "없는"
+ export: "내보내기"
+ save: "변경사항 저장"
+ saverun: "변경 사항 저장 및 실행"
+ run: "운영"
+ undo: "변경 사항을 취소"
+ edit: "수정"
+ delete: "삭제"
+ recover: "삭제 취소 쿼리"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "검색어에 저장하지 않은 변경 사항이있어 이동하면 사라집니다."
+ result_count:
+ other: "%{count}개의 결과."
+ query_name: "쿼리"
+ query_groups: "그룹"
+ link: "링크"
+ report_name: "보고서"
+ query_description: "설명"
+ query_time: "마지막 실행"
+ query_user: "작성자"
+ explain_label: "쿼리 계획을 포함 하시겠습니까?"
+ save_params: "기본값 설정"
+ reset_params: "리셋"
+ search_placeholder: "검색..."
+ no_search_results: "죄송합니다. 귀하의 텍스트와 일치하는 결과를 찾을 수 없습니다."
+ group:
+ reports: "보고서"
diff --git a/plugins/discourse-data-explorer/config/locales/client.lt.yml b/plugins/discourse-data-explorer/config/locales/client.lt.yml
new file mode 100644
index 00000000000..b7df6e8574f
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.lt.yml
@@ -0,0 +1,36 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lt:
+ js:
+ explorer:
+ or: "arba"
+ import:
+ label: "Importuoti"
+ help:
+ label: "Pagalba"
+ schema:
+ filter: "Paieška..."
+ types:
+ bool:
+ yes: "Taip"
+ no: "Ne"
+ export: "Eksportuoti"
+ save: "Išsaugoti pakeitimus"
+ edit: "Redaguoti"
+ delete: "Pašalinti"
+ result_count:
+ one: "%{count} rezultatas."
+ few: "%{count} rezultatai."
+ many: "%{count} rezultatai."
+ other: "%{count} rezultatai."
+ query_groups: "Grupės"
+ query_description: "Aprašymas"
+ query_user: "Sukurta"
+ reset_params: "Atstatyti"
+ search_placeholder: "Paieška..."
+ group:
+ reports: "Pranešimai"
diff --git a/plugins/discourse-data-explorer/config/locales/client.lv.yml b/plugins/discourse-data-explorer/config/locales/client.lv.yml
new file mode 100644
index 00000000000..50260326fc9
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.lv.yml
@@ -0,0 +1,28 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lv:
+ js:
+ explorer:
+ or: "vai"
+ import:
+ label: "Importēt"
+ help:
+ label: "Palīdzība"
+ schema:
+ filter: "Meklēt..."
+ types:
+ bool:
+ yes: "Jā"
+ no: "Nē"
+ export: "Eksportēt"
+ save: "Saglabāt izmaiņas"
+ edit: "Labot"
+ delete: "Dzēst"
+ query_groups: "Grupas"
+ query_description: "Apraksts"
+ reset_params: "Atlikt"
+ search_placeholder: "Meklēt..."
diff --git a/plugins/discourse-data-explorer/config/locales/client.nb_NO.yml b/plugins/discourse-data-explorer/config/locales/client.nb_NO.yml
new file mode 100644
index 00000000000..3b3884d45c2
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.nb_NO.yml
@@ -0,0 +1,47 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nb_NO:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Fjern semikolonene fra spørringen."
+ dirty: "Du må lagre spørringen før du kjører den."
+ explorer:
+ or: "eller"
+ admins_only: "Datautforskeren er kun tilgjengelig for administratorer."
+ title: "Datautforsker"
+ create: "Opprett ny"
+ create_placeholder: "Spørringsnavn…"
+ import:
+ label: "Importer"
+ modal: "Importer en spørring"
+ help:
+ label: "Hjelp"
+ schema:
+ filter: "Søk…"
+ types:
+ bool:
+ yes: "Ja"
+ no: "Nei"
+ null_: "Null"
+ export: "Eksporter"
+ save: "Lagre endringer"
+ undo: "Forkast endringer"
+ edit: "Rediger"
+ delete: "Slett"
+ recover: "Angre sletting av spørring"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "En spørring har ulagrede endringer, og vil gå tapt hvis du navigerer vekk."
+ query_groups: "Grupper"
+ query_description: "Beskrivelse"
+ explain_label: "Inkluder spørringsplan?"
+ save_params: "Sett forvalg"
+ reset_params: "Tilbakestill"
+ search_placeholder: "Søk…"
+ group:
+ reports: "Rapporter"
diff --git a/plugins/discourse-data-explorer/config/locales/client.nl.yml b/plugins/discourse-data-explorer/config/locales/client.nl.yml
new file mode 100644
index 00000000000..617a63090d5
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.nl.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nl:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Verwijder de puntkomma's uit de query."
+ dirty: "Je moet de query opslaan voordat je deze uitvoert."
+ explorer:
+ or: "of"
+ admins_only: "De gegevensverkenner is alleen beschikbaar voor beheerders."
+ allow_groups: "Groepen hebben toegang tot deze query"
+ title: "Gegevensverkenner"
+ create: "Nieuwe maken"
+ create_placeholder: "Querynaam..."
+ description_placeholder: "Voer hier een beschrijving in"
+ import:
+ label: "Importeren"
+ modal: "Een query importeren"
+ unparseable_json: "Onparseerbaar JSON-bestand."
+ wrong_json: "Onjuist JSON-bestand. Een JSON-bestand moet een 'query'-object bevatten, dat minimaal een 'sql'-eigenschap moet hebben."
+ help:
+ label: "Help"
+ modal_title: "Gegevensverkenner-help"
+ auto_resolution: "<h2>Automatische omzetting van entiteiten</h2> <p>Wanneer je query een entiteit-ID retourneert, kan Gegevensverkenner deze automatisch vervangen door de entiteitnaam en andere nuttige informatie in queryresultaten. Automatische omzetting is beschikbaar voor <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> en <i><b>badge_id</b></i>. Voer deze query uit om dit te proberen:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Aangepaste parameters maken</h2> <p>Om aangepaste parameters te maken voor je query's, plaats je dit bovenaan je query en volg je de notatie:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Opmerking : de eerste regel met [params] is vereist, samen met twee streepjes ervoor en elke aangepaste parameter die je wilt declareren.</i></p>"
+ default_values: "<h3>Standaardwaarden</h3> <p>Je kunt parameters declareren met of zonder standaardwaarde. Standaardwaarden worden weergegeven in een tekstveld onder de query-editor, die je naar wens kunt bewerken. Parameters die zijn gedeclareerd zonder standaardwaarde leveren nog steeds een tekstveld op, maar zijn leeg en rood gemarkeerd.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Gegevenstypen</h3> <p>Hier volgen algemene gegevenstypen die je kunt gebruiken:</p> <ul> <li><b>integer</b> - positief of negatief geheel getal van vier bytes</li> <li><b>text</b> - tekenreeks met variabele lengte</li> <li><b>boolean</b> – true/false</li> <li><b>date</b> - kalenderdatum (jaar, maand, dag)</li> </ul> <p>Ga voor meer informatie over gegevenstypen naar <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>deze website</a>.</p>"
+ schema:
+ title: "Databaseschema"
+ filter: "Zoeken..."
+ sensitive: "De inhoud van deze kolom kan bijzonder gevoelige of privégegevens bevatten. Wees voorzichtig bij gebruik van de inhoud van deze kolom."
+ types:
+ bool:
+ yes: "Ja"
+ no: "Nee"
+ null_: "Null"
+ export: "Exporteren"
+ view_json: "JSON weergeven"
+ save: "Wijzigingen opslaan"
+ saverun: "Wijzigingen opslaan en uitvoeren"
+ run: "Uitvoeren"
+ undo: "Wijzigingen negeren"
+ edit: "Bewerken"
+ delete: "Verwijderen"
+ recover: "Query verwijderen ongedaan maken"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabel"
+ show_graph: "Grafiek"
+ others_dirty: "Een query heeft niet-opgeslagen wijzigingen die verloren gaan als je de pagina verlaat."
+ run_time: "Query voltooid in %{value} ms."
+ result_count:
+ one: "%{count} resultaat."
+ other: "%{count} resultaten."
+ max_result_count:
+ one: "Eerste %{count} resultaat wordt weergegeven."
+ other: "Eerste %{count} resultaten worden weergegeven."
+ query_name: "Query"
+ query_groups: "Groepen"
+ link: "Link voor"
+ report_name: "Rapport"
+ query_description: "Beschrijving"
+ query_time: "Laatste uitvoering"
+ query_user: "Gemaakt door"
+ column: "Kolom %{number}"
+ explain_label: "Queryplan bijvoegen?"
+ save_params: "Standaardwaarden instellen"
+ reset_params: "Herstellen"
+ search_placeholder: "Zoeken..."
+ no_search_results: "Er zijn geen resultaten gevonden voor je tekst."
+ form:
+ errors:
+ invalid: "Ongeldig"
+ no_such_category: "Geen dergelijke categorie"
+ no_such_group: "Geen dergelijke groep"
+ invalid_date: "%{date} is een ongeldige datum"
+ invalid_time: "%{time} is een ongeldige tijd"
+ group:
+ reports: "Rapporten"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Voer Gegevensverkenner-query's uit. Beperk de API-sleutel tot een reeks query's door query-ID's op te geven."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Verzenden naar gebruiker, groep of e-mailadres
+ query_id:
+ label: Gegevensverkenner-query
+ query_params:
+ label: Gegevensverkenner-queryparameters
+ skip_empty:
+ label: PB verzenden overslaan als er geen resultaten zijn
+ attach_csv:
+ label: Voeg het CSV-bestand bij de PB
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: Het topic om queryresultaten in te plaatsen
+ query_id:
+ label: Gegevensverkenner-query
+ query_params:
+ label: Gegevensverkenner-queryparameters
+ skip_empty:
+ label: Plaatsen overslaan als er geen resultaten zijn
+ attach_csv:
+ label: Voeg het CSV-bestand bij het bericht
diff --git a/plugins/discourse-data-explorer/config/locales/client.pl_PL.yml b/plugins/discourse-data-explorer/config/locales/client.pl_PL.yml
new file mode 100644
index 00000000000..232c4f54d3a
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.pl_PL.yml
@@ -0,0 +1,98 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pl_PL:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Usuń średniki z zapytania."
+ dirty: "Musisz zapisać zapytanie zanim je wykonasz."
+ explorer:
+ or: "lub"
+ admins_only: "Eksplorator danych jest dostępny wyłącznie dla administratorów."
+ allow_groups: "Zezwól grupom na dostęp do tego zapytania"
+ title: "Eksplorator danych"
+ create: "Stwórz nowy"
+ create_placeholder: "Nazwa zapytania…"
+ description_placeholder: "Wprowadź opis zapytania"
+ import:
+ label: "Import"
+ modal: "Importuj zapytanie"
+ unparseable_json: "Nieprzetwarzalny plik JSON."
+ wrong_json: "Nieprawidłowy plik JSON. Plik JSON powinien zawierać obiekt 'query', który powinien mieć przynajmniej właściwość 'sql'."
+ help:
+ label: "Pomoc"
+ modal_title: "Pomoc eksploratora danych"
+ auto_resolution: "<h2>Automatyczne rozpoznawanie encji</h2> <p>Gdy Twoje zapytanie zwróci identyfikator encji, eksplorator danych może automatycznie zastąpić go nazwą encji i innymi przydatnymi informacjami w wynikach zapytania. Automatyczne rozpoznawanie jest dostępne dla <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> i <i><b>badge_id</b></i>. Aby to wypróbować, wykonaj następujące zapytanie:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Tworzenie niestandardowych parametrów</h2> <p>Aby utworzyć niestandardowe parametry dla zapytań, umieść to na początku zapytania i postępuj zgodnie z formatem:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Uwaga: pierwszy wiersz z [params] jest wymagany, wraz z dwoma myślnikami poprzedzającymi go i każdym niestandardowym parametrem, który chcesz zadeklarować.</i></p>"
+ default_values: "<h3>Wartości domyślne</h3> <p>Możesz zadeklarować parametry z wartościami domyślnymi lub bez nich. Wartości domyślne pojawią się w polu tekstowym poniżej edytora zapytań, które możesz edytować zgodnie z własnymi potrzebami. Parametry zadeklarowane bez wartości domyślnych nadal będą generować pole tekstowe, ale będzie ono puste i podświetlone na czerwono.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Typy danych</h3> <p>Tutaj są powszechnie używane typy danych, których możesz użyć:</p> <ul> <li><b>liczba całkowita</b> - podpisane czterobajtowe liczby całkowite</li> <li><b>tekst</b> - ciąg znaków o zmiennej długości</li> <li><b>liczba logiczna</b> - prawda/fałsz</li> <li><b>data</b> - data kalendarzowa (rok, miesiąc, dzień)</li> </ul> <p>Aby uzyskać więcej informacji na temat typów danych, odwiedź <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>tę stronę</a></p>"
+ schema:
+ title: "Schemat bazy danych"
+ filter: "Wyszukiwanie..."
+ sensitive: "Zawartość tej kolumny może zawierać szczególnie wrażliwe lub prywatne dane. Prosimy o zachowanie ostrożności przy używaniu tych danych."
+ types:
+ bool:
+ yes: "Tak"
+ no: "Nie"
+ null_: "Null"
+ export: "Eksport"
+ view_json: "Wyświetl JSON"
+ save: "Zapisz zmiany"
+ saverun: "Zapisz zmiany i wykonaj"
+ run: "Wykonaj"
+ undo: "Odrzuć zmiany"
+ edit: "Edytuj"
+ delete: "Usuń"
+ recover: "Przywróć zapytanie"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabela"
+ show_graph: "Wykres"
+ others_dirty: "Zapytanie ma niezapisane zmiany, które utracisz, jeśli przejdziesz w inne miejsce."
+ run_time: "Zapytanie zakończone w %{value} ms."
+ result_count:
+ one: "%{count}wynik."
+ few: "%{count}wyniki."
+ many: "%{count}wyników."
+ other: "%{count}wyników."
+ query_name: "Zapytanie"
+ query_groups: "Grupy"
+ link: "Link do"
+ report_name: "Zgłoszenie"
+ query_description: "Opis"
+ query_time: "Ostatnio wykonano"
+ query_user: "Stworzone przez"
+ column: "Kolumna %{number}"
+ explain_label: "Dołączyć plan zapytania?"
+ save_params: "Ustaw domyślne"
+ reset_params: "Przywróć"
+ search_placeholder: "Wyszukiwanie..."
+ no_search_results: "Nie znaleziono żadnych wyników."
+ group:
+ reports: "Zgłoszenia"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Uruchamiaj zapytania eksploratora danych. Ogranicz klucz API do zestawu zapytań, określając identyfikatory zapytań."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Wyślij do użytkownika, grupy lub na adres e-mail
+ query_id:
+ label: Zapytanie eksploratora danych
+ query_params:
+ label: Parametry zapytania eksploratora danych
+ recurring_data_explorer_result_topic:
+ fields:
+ query_id:
+ label: Zapytanie eksploratora danych
+ query_params:
+ label: Parametry zapytania eksploratora danych
diff --git a/plugins/discourse-data-explorer/config/locales/client.pt.yml b/plugins/discourse-data-explorer/config/locales/client.pt.yml
new file mode 100644
index 00000000000..c87d3906c80
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.pt.yml
@@ -0,0 +1,55 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Remova os pontos e vírgulas da consulta."
+ dirty: "Deve guardar a consulta antes de executar."
+ explorer:
+ or: "ou"
+ admins_only: "O explorador de dados está disponível apenas para os administradores."
+ title: "Explorador de Dados"
+ create: "Criar Nova"
+ create_placeholder: "Nome da consulta..."
+ import:
+ label: "Importar"
+ modal: "Importar Uma Consulta"
+ help:
+ label: "Ajuda"
+ schema:
+ title: "Esquema da Base de Dados"
+ filter: "Pesquisar..."
+ sensitive: "O conteúdo desta coluna pode conter informação particularmente sensível ou privada. Por favor, tenha cuidado ao utilizar os conteúdos desta coluna."
+ types:
+ bool:
+ yes: "Sim"
+ no: "Não"
+ export: "Exportar"
+ save: "Guardar alterações"
+ saverun: "Guardar Alterações e Executar"
+ run: "Executar"
+ undo: "Ignorar Alterações"
+ edit: "Editar"
+ delete: "Eliminar"
+ recover: "Recuperar Consulta"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "Uma consulta tem alterações não guardadas que serão perdidas se navegar para outro lado."
+ run_time: "Consulta concluída em %{value} ms."
+ result_count:
+ one: "%{count} resultado."
+ other: "%{count} resultados."
+ query_groups: "Grupos"
+ query_description: "Descrição"
+ column: "Coluna %{number}"
+ explain_label: "Incluir plano de consulta?"
+ save_params: "Definir Predefinições"
+ reset_params: "Repor"
+ search_placeholder: "Pesquisar..."
+ group:
+ reports: "Relatórios"
diff --git a/plugins/discourse-data-explorer/config/locales/client.pt_BR.yml b/plugins/discourse-data-explorer/config/locales/client.pt_BR.yml
new file mode 100644
index 00000000000..7075372b873
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.pt_BR.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt_BR:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Remover os pontos e vírgulas da consulta."
+ dirty: "Você precisa salvar a consulta antes de executar."
+ explorer:
+ or: "ou"
+ admins_only: "O explorador de dados só está disponível para administradores."
+ allow_groups: "Permitir que grupos acessem esta consulta"
+ title: "Explorador de Dados"
+ create: "Criar Nova"
+ create_placeholder: "Nome da consulta…"
+ description_placeholder: "Insira uma descrição aqui"
+ import:
+ label: "Importar"
+ modal: "Importar Uma Consulta"
+ unparseable_json: "Arquivo JSON não analisável"
+ wrong_json: "Arquivo JSON incorreto. Um arquivo JSON deve conter um objeto \"consulta\", que deve ter pelo menos a propriedade \"sql\""
+ help:
+ label: "Ajuda"
+ modal_title: "Ajuda do Explorador de Dados"
+ auto_resolution: "<h2>Resolução de entidade automática</h2> <p>Quando a sua consulta retorna uma id de entidade, o Explorador de Dados pode substituí-la automaticamente pelo nome da entidade e outras informações úteis nos resultados da consulta. A resolução automática está disponível para <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> e <i><b>badge_id</b></i>. Para tentar isso, execute esta consulta:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Criação de parâmetros personalizados/h2> <p>Para criar parâmetros personalizados para suas consultas, insira isto no topo da sua consulta e siga o formato:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Observação: a primeira linha com [params] é necessária, junto com dois traços antes dela e de cada parâmetro personalizado que você deseja criar.</i></p>"
+ default_values: "<h3>Valores padrão</h3> <p>Você pode declarar parâmetros com ou sem valores padrão. Valores padrão serão exibidos em um campo de texto abaixo do editor de consultas, que pode ser editado conforme necessário. Parâmetros declarados sem valores padrão ainda irão gerar um campo de texto, mas estarão vazios e destacados em vermelho.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Tipos de dados</h3> <p>Estes são os tipos de dados comuns que você pode usar:</p> <ul> <li><b>integer</b> - Integer assinado de quatro bytes</li> <li><b>text</b> - cadeia de caracteres de tamanho variado</li> <li><b>boolean</b> – verdadeiro/falso</li> <li><b>data</b> - data do calendário (ano, mês, dia)</li> </ul> <p>Para mais informações sobre tipos de dados, acesse <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>este site</a>.</p>"
+ schema:
+ title: "Esquema de Banco de Dados"
+ filter: "Pesquisar…"
+ sensitive: "O conteúdo desta coluna pode conter informações particularmente sensíveis ou privadas. Por favor, tenha cuidado ao usar o conteúdo desta coluna."
+ types:
+ bool:
+ yes: "Sim"
+ no: "Não"
+ null_: "Nulo"
+ export: "Exportar"
+ view_json: "Visualizar JSON"
+ save: "Salvar Mudanças"
+ saverun: "Salvar Mudanças e Executar"
+ run: "Executar"
+ undo: "Descartar Mudanças"
+ edit: "Editar"
+ delete: "Apagar"
+ recover: "Desfazer Exclusão da Consulta"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabela"
+ show_graph: "Gráfico"
+ others_dirty: "Uma consulta tem alterações não salvas que serão perdidas se você sair desta página."
+ run_time: "Consulta concluída em %{value} ms."
+ result_count:
+ one: "%{count} resultado."
+ other: "%{count} resultados."
+ max_result_count:
+ one: "Mostrando melhor %{count} resultado."
+ other: "Mostrando melhores %{count} resultados."
+ query_name: "Consulta"
+ query_groups: "Grupos"
+ link: "Link para"
+ report_name: "Reportar"
+ query_description: "Descrição"
+ query_time: "Última execução"
+ query_user: "Criado por"
+ column: "Coluna %{number}"
+ explain_label: "Incluir plano de consulta?"
+ save_params: "Definir Padrões"
+ reset_params: "Redefinir"
+ search_placeholder: "Pesquisar..."
+ no_search_results: "Desculpe, não conseguimos encontrar nenhum resultado contendo o seu texto."
+ form:
+ errors:
+ invalid: "Inválido"
+ no_such_category: "Não há esta categoria"
+ no_such_group: "Não há este grupo"
+ invalid_date: "%{date} é uma data inválida"
+ invalid_time: "%{time} é um horário inválido"
+ group:
+ reports: "Relatórios"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Execute consultas do Explorador de Dados. Restrinja a chave de API a um conjunto de consultas ao especificar suas IDs."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Enviar ao(à) usuário(a), grupo ou e-mail
+ query_id:
+ label: Consulta do explorador de dados
+ query_params:
+ label: Parâmetros da consulta do explorador de dados
+ skip_empty:
+ label: Pular envio de PM se não houver resultados
+ attach_csv:
+ label: Anexe um arquivo CSV à MP
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: O tópico no qual postar os resultados da consulta
+ query_id:
+ label: Consulta do Data Explorer
+ query_params:
+ label: Parâmetros da consulta do Data Explorer
+ skip_empty:
+ label: Pular postagem se não houver resultados
+ attach_csv:
+ label: Anexe um arquivo CSV à postagem
diff --git a/plugins/discourse-data-explorer/config/locales/client.ro.yml b/plugins/discourse-data-explorer/config/locales/client.ro.yml
new file mode 100644
index 00000000000..12ad4dc0c91
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ro.yml
@@ -0,0 +1,30 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ro:
+ js:
+ explorer:
+ or: "sau"
+ import:
+ label: "Importă"
+ help:
+ label: "Ajutor"
+ schema:
+ filter: "Caută..."
+ types:
+ bool:
+ yes: "Da"
+ no: "Nu"
+ export: "Exportă"
+ save: "Salvează schimbările"
+ edit: "Editează"
+ delete: "Șterge"
+ query_groups: "Grupuri"
+ query_description: "Descriere"
+ reset_params: "Resetează"
+ search_placeholder: "Caută..."
+ group:
+ reports: "Rapoarte"
diff --git a/plugins/discourse-data-explorer/config/locales/client.ru.yml b/plugins/discourse-data-explorer/config/locales/client.ru.yml
new file mode 100644
index 00000000000..9b553b37343
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ru.yml
@@ -0,0 +1,120 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ru:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Удалите точку с запятой из запроса."
+ dirty: "Вы должны сохранить запрос перед его выполнением."
+ explorer:
+ or: "или"
+ admins_only: "Исследование данных доступно только для администраторов."
+ allow_groups: "Разрешить группам доступ к этому запросу"
+ title: "Проводник данных"
+ create: "Создать"
+ create_placeholder: "Имя запроса..."
+ description_placeholder: "Введите описание"
+ import:
+ label: "Импорт"
+ modal: "Импорт запроса"
+ unparseable_json: "Невозможно распарсить JSON-файл."
+ wrong_json: "Неверный формат JSON-файла. Файл должен содержать объект 'запрос', у которого как минимум должно быть свойство 'sql'."
+ help:
+ label: "Справка"
+ modal_title: "Проводник данных. Справка."
+ auto_resolution: "<h2>Автоматическое разрешение</h2> <p>Когда запрос возвращает идентификатор объекта, проводник данных может автоматически заменить его именем объекта и другой полезной информацией в результатах запроса. Автоматическое разрешение доступно для <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> и <i><b>badge_id</b></i>. Для пробы запустите этот запрос:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Создание настраиваемых параметров</h2> <p>Чтобы создать настраиваемые параметры для запроса, поместите эти данные в верхней части запроса, придерживаясь следующего формата:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Примечание: первая строка с [params] обязательна, с двумя дефисами перед ней и всеми настраиваемыми параметрами, которые вы хотите объявить.</i></p>"
+ default_values: "<h3>Значения по умолчанию</h3> <p>Вы можете объявлять параметры со значениями по умолчанию или без таковых. Значения по умолчанию будут отображаться в текстовом поле под редактором запросов, эти значения вы можете менять по своему усмотрению. Параметры, объявленные без значений по умолчанию, по-прежнему будут создавать текстовое поле, но такие поля будут пустыми и будут выделены красным цветом.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Типы данных</h3> <p>Основные типы данных, которые можно использовать:</p> <ul> <li><b>целое число</b> — знаковое четырехбайтовое целое число,</li> <li><b>текст</b> — строка символов переменной длины,</li> <li><b>логическое значение</b> — истина, ложь,</li> <li><b>дата</b> — календарная дата (год, месяц, день).</li> </ul> <p>Подробнее о типах данных смотрите на <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>этом веб-сайте</a>.</p>"
+ schema:
+ title: "Схема базы данных"
+ filter: "Поиск..."
+ sensitive: "Эта колонка может содержать конфиденциальную информацию. Будьте осторожны при использовании её содержимого."
+ types:
+ bool:
+ yes: "Да"
+ no: "Нет"
+ null_: "Null"
+ export: "Экспорт"
+ view_json: "Просмотреть JSON"
+ save: "Сохранить изменения"
+ saverun: "Сохранить изменения и выполнить запрос"
+ run: "Выполнить запрос"
+ undo: "Отменить изменения"
+ edit: "Редактировать"
+ delete: "Удалить"
+ recover: "Восстановить запрос"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Таблица"
+ show_graph: "График"
+ others_dirty: "Запрос имеет несохранённые изменения, которые будут потеряны, если вы уйдёте со страницы."
+ run_time: "Запрос завершен за %{value} мс."
+ result_count:
+ one: "%{count} результат."
+ few: "%{count} результата."
+ many: "%{count} результатов."
+ other: "%{count} результатов."
+ max_result_count:
+ one: "Показан %{count} лучший результат."
+ few: "Показаны %{count} лучших результата."
+ many: "Показаны %{count} лучших результатов."
+ other: "Показаны %{count} лучшего результата."
+ query_name: "Запрос"
+ query_groups: "Группы"
+ link: "Ссылка для"
+ report_name: "Отчёт"
+ query_description: "Описание"
+ query_time: "Время выполнения последнего запроса"
+ query_user: "Создано"
+ column: "Колонка %{number}"
+ explain_label: "Отобразить план запроса"
+ save_params: "Установка значений по умолчанию"
+ reset_params: "Сброс"
+ search_placeholder: "Поиск..."
+ no_search_results: "К сожалению, мы не смогли найти результаты, соответствующие вашему запросу."
+ form:
+ errors:
+ invalid: "Недопустимое значение"
+ no_such_category: "Нет такой категории"
+ no_such_group: "Нет такой группы"
+ invalid_date: "%{date} — недопустимая дата"
+ invalid_time: "%{time} — недопустимое время"
+ group:
+ reports: "Отчёты"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Выполнение запросов проводника данных. Ограничьте ключ API набором запросов, указав идентификаторы запросов."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Отправить пользователю, в группу или на адрес электронной почты
+ query_id:
+ label: Запрос проводника данных
+ query_params:
+ label: Параметры запроса проводника данных
+ skip_empty:
+ label: Пропустить отправку личного сообщения, если нет результатов
+ attach_csv:
+ label: Прикрепить CSV-файл к личному сообщению
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: Тема для публикации результатов запроса
+ query_id:
+ label: Запрос проводника данных
+ query_params:
+ label: Параметры запроса для проводника данных
+ skip_empty:
+ label: Пропустить публикацию, если нет результатов
+ attach_csv:
+ label: Прикрепить CSV-файл к публикации
diff --git a/plugins/discourse-data-explorer/config/locales/client.sk.yml b/plugins/discourse-data-explorer/config/locales/client.sk.yml
new file mode 100644
index 00000000000..c1711752b89
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.sk.yml
@@ -0,0 +1,42 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sk:
+ js:
+ explorer:
+ or: "alebo"
+ admins_only: "Prieskumník údajov je dostupný iba administrátorom."
+ title: "Prieskumník údajov"
+ create: "Vztvoriť novú"
+ import:
+ label: "Import"
+ help:
+ label: "Pomoc"
+ schema:
+ filter: "Hľadať"
+ types:
+ bool:
+ yes: "Áno"
+ no: "Nie"
+ export: "Exportovať"
+ save: "Uložiť zmeny"
+ edit: "Upraviť"
+ delete: "Zmazať"
+ download_json: "JSON"
+ download_csv: "CSV"
+ result_count:
+ one: "%{count} výsledok."
+ few: "%{count} výsledkov."
+ many: "%{count} výsledky."
+ other: "%{count} výsledky."
+ query_groups: "Skupiny"
+ query_description: "Popis"
+ query_user: "Vytvoril"
+ save_params: "Predvolené"
+ reset_params: "Resetovať"
+ search_placeholder: "Hľadať"
+ group:
+ reports: "Hlásenia"
diff --git a/plugins/discourse-data-explorer/config/locales/client.sl.yml b/plugins/discourse-data-explorer/config/locales/client.sl.yml
new file mode 100644
index 00000000000..cb30d6e7e76
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.sl.yml
@@ -0,0 +1,68 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sl:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Odstranite podpičja iz poizvedbe."
+ dirty: "Pred zagonom morate poizvedbo shraniti."
+ explorer:
+ or: "ali"
+ admins_only: "Raziskovalec podatkov je na voljo samo skrbnikom."
+ allow_groups: "Dovoli skupinam dostop do te poizvedbe"
+ title: "Raziskovalec podatkov"
+ create: "Ustvari novo"
+ create_placeholder: "Ime poizvedbe..."
+ description_placeholder: "Vnesite opis tukaj"
+ import:
+ label: "Uvozi"
+ modal: "Uvozi poizvedbo"
+ help:
+ label: "Pomoč"
+ schema:
+ title: "Shema zbirke podatkov"
+ filter: "Išči..."
+ sensitive: "Vsebina tega stolpca lahko vsebuje posebno občutljive ali zasebne podatke. Pri uporabi vsebine tega stolpca bodite previdni."
+ types:
+ bool:
+ yes: "Da"
+ no: "Ne"
+ null_: "Null"
+ export: "Izvozi"
+ save: "Shrani spremembe"
+ saverun: "Shrani spremembe in zaženi"
+ run: "Zaženi"
+ undo: "Zavrzi spremembe"
+ edit: "Uredi"
+ delete: "Izbriši"
+ recover: "Povrni poizvedbo"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabela"
+ show_graph: "Graf"
+ others_dirty: "Poizvedba ima neshranjene spremembe, ki se bodo izgubile, če boste šli drugam."
+ run_time: "Poizvedba končana v %{value} ms."
+ result_count:
+ one: "%{count} zadetek."
+ two: "%{count} zadetka."
+ few: "%{count} zadetki."
+ other: "%{count} zadetkov."
+ query_name: "Poizvedba"
+ query_groups: "Skupine"
+ link: "Povezava za"
+ report_name: "Poročilo"
+ query_description: "Opis"
+ query_time: "Zadnja izvedba"
+ query_user: "Ustvaril"
+ column: "Stolpec %{number}"
+ explain_label: "Vključi načrt poizvedbe?"
+ save_params: "Nastavi privzete vrednosti"
+ reset_params: "Ponastavi"
+ search_placeholder: "Išči..."
+ no_search_results: "Oprostite, nismo našli nobenega zadetka, ki bi ustrezal vaši poizvedbi."
+ group:
+ reports: "Poročila"
diff --git a/plugins/discourse-data-explorer/config/locales/client.sq.yml b/plugins/discourse-data-explorer/config/locales/client.sq.yml
new file mode 100644
index 00000000000..ff5c5d1948b
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.sq.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sq:
+ js:
+ explorer:
+ or: "ose"
+ import:
+ label: "Importo"
+ types:
+ bool:
+ yes: "Po"
+ no: "Jo"
+ export: "Eksporto"
+ save: "Ruaj ndryshimet"
+ edit: "Redakto"
+ delete: "Fshij"
+ query_groups: "Grupet"
+ query_description: "Përshkrimi"
+ reset_params: "Rivendos"
diff --git a/plugins/discourse-data-explorer/config/locales/client.sr.yml b/plugins/discourse-data-explorer/config/locales/client.sr.yml
new file mode 100644
index 00000000000..3e8341aea46
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.sr.yml
@@ -0,0 +1,20 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sr:
+ js:
+ explorer:
+ or: "ili"
+ types:
+ bool:
+ yes: "Da"
+ no: "Ne"
+ export: "Izvoz"
+ save: "Sačuvaj izmene"
+ edit: "Izmeni"
+ delete: "Obriši"
+ query_groups: "Grupe"
+ query_description: "Opis"
diff --git a/plugins/discourse-data-explorer/config/locales/client.sv.yml b/plugins/discourse-data-explorer/config/locales/client.sv.yml
new file mode 100644
index 00000000000..69334e1e221
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.sv.yml
@@ -0,0 +1,82 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sv:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Ta bort semikolon från sökningen."
+ dirty: "Du måste spara sökningen innan du kör."
+ explorer:
+ or: "eller"
+ admins_only: "Datautforskaren är endast tillgänglig för administratörer."
+ allow_groups: "Tillåt att grupper går till denna sökning"
+ title: "Datautforskaren"
+ create: "Skapa ny"
+ create_placeholder: "Sökningsnamn..."
+ description_placeholder: "Ange en beskrivning här"
+ import:
+ label: "Importera"
+ modal: "Importera en sökning"
+ unparseable_json: "JSON-fil kan inte tolkas."
+ wrong_json: "Fel JSON-fil. En JSON-fil bör innehålla ett 'query'-objekt, som åtminstone bör ha en 'sql'-egenskap."
+ help:
+ label: "Hjälp"
+ modal_title: "Hjälp med Datautforskaren"
+ auto_resolution: "<h2>Automatisk enhetsmatchning</h2> <p>När din fråga returnerar ett enhets-ID kan Datautforskaren automatiskt ersätta det med enhetens namn och annan användbar information i frågeresultaten. Automatisk matchning finns tillgängligt för <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> och <i><b>badge_id</b></i>. För att prova detta kör du den här frågan:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Skapa anpassade parametrar</h2> <p>För att skapa anpassade parametrar för dina sökfrågor skriver du detta högst upp i din sökfråga, enligt formatet:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Obs: Den första raden med [params] krävs, med två bindestreck före den och varje anpassad parameter som du vill ange.</i></p>"
+ default_values: "<h3>Standardvärden</h3> <p>Du kan ange parametrar med eller utan standardvärden. Standardvärden kommer att visas i ett textfält under frågeredigeraren, som du kan redigera enligt dina behov. Parametrar som anges utan standardvärden kommer fortfarande att generera ett textfält, men kommer att vara tomma och rödmarkerade.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Datatyper</h3> <p>Här är vanliga datatyper som du kan använda:</p> <ul> <li><b>heltal</b> - signerat fyra byte-heltal</li> <li><b>text</b> - teckensträng av varierande längd</li> <li><b>boolesk</b> – sant/falsk</li> <li><b>datum</b> - kalenderdatum (år, månad, dag)</li> </ul> <p>För mer information om datatyper, besök <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>denna webbplats</a>.</p>"
+ schema:
+ title: "Databasschema"
+ filter: "Sök..."
+ sensitive: "Innehållet i denna kolumn kan innehålla särskilt känslig eller privat information. Var försiktig när du använder innehållet i denna kolumn."
+ types:
+ bool:
+ yes: "Ja"
+ no: "Nej"
+ null_: "Tomt"
+ export: "Exportera"
+ save: "Spara ändringar"
+ saverun: "Spara ändringar och kör"
+ run: "Kör"
+ undo: "Ignorera ändringar"
+ edit: "Redigera"
+ delete: "Radera"
+ recover: "Återställ sökning"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tabell"
+ show_graph: "Graf"
+ others_dirty: "En sökning har ändringar som inte har sparats och kommer att förloras om du lämnar sidan."
+ run_time: "Sökning slutförd efter %{value} ms."
+ result_count:
+ one: "%{count} resultat."
+ other: "%{count} resultat."
+ max_result_count:
+ one: "Visar det %{count} översta resultatet."
+ other: "Visar de %{count} översta resultaten."
+ query_name: "Sökning"
+ query_groups: "Grupper"
+ link: "Länk för"
+ report_name: "Rapport"
+ query_description: "Beskrivning"
+ query_time: "Senast körd"
+ query_user: "Skapad av"
+ column: "Kolumn %{number}"
+ explain_label: "Inkludera sökningsplan?"
+ save_params: "Ange förvalda värden"
+ reset_params: "Återställ"
+ search_placeholder: "Sök..."
+ no_search_results: "Tyvärr kunde vi inte hitta några resultat som stämmer överens med din text."
+ group:
+ reports: "Rapporter"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Kör frågor för datautforskaren. Begränsa API-nyckeln till en viss uppsättning frågor genom att specificera fråge-ID:n."
diff --git a/plugins/discourse-data-explorer/config/locales/client.sw.yml b/plugins/discourse-data-explorer/config/locales/client.sw.yml
new file mode 100644
index 00000000000..1aceddef94c
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.sw.yml
@@ -0,0 +1,50 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sw:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Ondoa alama ya mkato kwenye swali."
+ dirty: "Lazima uhifadhi taarifa kabla ya kutekeleza."
+ explorer:
+ or: "au"
+ admins_only: "Uwezo wa kupitia taarifa zote unapatikana kwa viongozi tu."
+ title: "Utafiti wa Taarifa"
+ create: "Tengeneza Mpya"
+ create_placeholder: "Jina la ulizo..."
+ description_placeholder: "Andika maelezo hapa"
+ import:
+ label: "Imeingizwa kutoka sehemu nyingine"
+ modal: "Ingiza Ulizo"
+ help:
+ label: "Msaada"
+ schema:
+ title: "Mpango wa kuhifadhidata"
+ filter: "Tafuta..."
+ sensitive: "Taarifa zilizomo ndani ya safuwima zinaweza kuwa za kibinafsi au zinazozingatiwa. Tafadhali kuwa makini na mwangalifu unapotumia hizi taarifa. "
+ types:
+ bool:
+ yes: "Ndio"
+ no: "Hapana"
+ null_: "Hamna Kitu"
+ export: "Hamisha"
+ save: "Hifadhi Mabadiliko"
+ undo: "Kataa Mabadiliko"
+ edit: "Hariri"
+ delete: "Futa"
+ recover: "Rejesha Suala"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "Mabaliko uliyofanya kwenye ulizo hayajahifadhiwa, hifadhi kabla ya kwenda kwingine."
+ query_name: "Swali"
+ query_groups: "Makundi"
+ query_description: "Maelezo"
+ query_user: "Imetengenezwa na"
+ explain_label: "pamoja na mpango wa swala?"
+ save_params: "Seti Chaguo-misingi"
+ reset_params: "Weka/Anzisha Upya"
+ search_placeholder: "Tafuta"
diff --git a/plugins/discourse-data-explorer/config/locales/client.te.yml b/plugins/discourse-data-explorer/config/locales/client.te.yml
new file mode 100644
index 00000000000..35591db95e2
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.te.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+te:
+ js:
+ explorer:
+ or: "లేదా"
+ help:
+ label: "సహాయం"
+ types:
+ bool:
+ yes: "అవును"
+ no: "లేదు"
+ export: "ఎగుమతి"
+ save: "మార్పులను భద్రపరచు"
+ edit: "సవరించు"
+ delete: "తొలగించు"
+ query_groups: "గుంపులు"
+ query_description: "వివరణ"
+ query_user: "సృష్టికర్త"
+ reset_params: "రీసెట్ చేయండి"
+ group:
+ reports: "నివేదికలు"
diff --git a/plugins/discourse-data-explorer/config/locales/client.th.yml b/plugins/discourse-data-explorer/config/locales/client.th.yml
new file mode 100644
index 00000000000..4a8397bb200
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.th.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+th:
+ js:
+ explorer:
+ or: "หรือ"
+ help:
+ label: "ช่วยเหลือ"
+ schema:
+ filter: "ค้นหา..."
+ types:
+ bool:
+ yes: "ใช่"
+ no: "ไม่ใช่"
+ export: "ส่งออก"
+ save: "บันทึกการเปลี่ยนแปลง"
+ edit: "แก้ไข"
+ delete: "ลบ"
+ query_groups: "กลุ่ม"
+ query_description: "รายละเอียด"
+ query_user: "สร้างโดย"
+ search_placeholder: "ค้นหา..."
diff --git a/plugins/discourse-data-explorer/config/locales/client.tr_TR.yml b/plugins/discourse-data-explorer/config/locales/client.tr_TR.yml
new file mode 100644
index 00000000000..16af0c50553
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.tr_TR.yml
@@ -0,0 +1,116 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+tr_TR:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Noktalı virgülleri sorgudan kaldırın."
+ dirty: "Çalıştırmadan önce sorguyu kaydetmeniz gerekir."
+ explorer:
+ or: "veya"
+ admins_only: "Veri gezgini yalnızca yöneticiler tarafından kullanılabilir."
+ allow_groups: "Grupların bu sorguya erişmesine izin ver"
+ title: "Veri Gezgini"
+ create: "Yeni Oluştur"
+ create_placeholder: "Sorgu adı ..."
+ description_placeholder: "Buraya bir açıklama girin"
+ import:
+ label: "İçe Aktar"
+ modal: "Sorguyu İçe Aktar"
+ unparseable_json: "Ayrıştırılamayan JSON dosyası."
+ wrong_json: "Yanlış JSON dosyası. Bir JSON dosyası, en azından bir \"sql\" özelliğine sahip olması gereken bir \"query\" nesnesi içermelidir."
+ help:
+ label: "Yardım"
+ modal_title: "Veri Gezgini Yardımı"
+ auto_resolution: "<h2>Otomatik Varlık Çözünürlüğü</h2> <p>Sorgunuz bir varlık kimliği döndürdüğünde, Veri Gezgini bunu otomatik olarak varlık adı ve sorgu sonuçlarındaki diğer yararlı bilgilerle değiştirebilir. Otomatik çözümleme <i><b>user_id</b></i>, <i><b>group_id</b></i>, <i><b>topic_id</b></i>, <i><b>category_id</b></i> ve <i><b>badge_id</b></i> için kullanılabilir. Bunu denemek için şu sorguyu çalıştırın:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>Özel Parametreler Oluşturma</h2> <p>Sorgularınıza özel parametreler oluşturmak için şunu sorgunuzun en üstüne koyun ve formatı izleyin:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>Not: [params] ile başlayan ilk satır, önündeki iki tire ve bildirmek istediğiniz her özel parametre ile birlikte gereklidir.</i></p>"
+ default_values: "<h3>Varsayılan Değerler</h3> <p>Parametreleri varsayılan değerlerle ya da varsayılan değerler olmadan bildirebilirsiniz. Varsayılan değerler, sorgu düzenleyicisinin altında, ihtiyaçlarınıza göre düzenleyebileceğiniz bir metin alanında görünür. Varsayılan değerler olmadan bildirilen parametreler yine bir metin alanı oluşturur, ancak boş olacak ve kırmızı renkle vurgulanır.</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>Veri Türleri</h3> <p>İşte kullanabileceğiniz yaygın veri türleri:</p> <ul> <li><b>integer</b> - signed four-byte Integer</li> <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> </ul> <p>Veri türleri hakkında daha fazla bilgi için <a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>bu web sitesini</a> ziyaret edin.</p>"
+ schema:
+ title: "Veritabanı Şeması"
+ filter: "Ara..."
+ sensitive: "Bu sütunun içeriği hassas veya özel bilgiler içerebilir. Lütfen bu sütunun içeriğini kullanırken dikkatli olun."
+ types:
+ bool:
+ yes: "Evet"
+ no: "Hayır"
+ null_: "Boş"
+ export: "Dışarı Aktar"
+ view_json: "JSON'u görüntüle"
+ save: "Değişiklikleri Kaydet"
+ saverun: "Değişiklikleri Kaydet ve Çalıştır"
+ run: "Çalıştır"
+ undo: "Değişiklikleri At"
+ edit: "Düzenle"
+ delete: "Sil"
+ recover: "Sorguyu Silme İşlemini Geri Al"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "Tablo"
+ show_graph: "Grafik"
+ others_dirty: "Sorgu üzerinde yaptığınız değişiklikleri kaydetmezseniz bağlantınızın kopması durumunda yapılan değişiklikler kaybolur."
+ run_time: "Sorgu %{value} ms'de tamamlandı."
+ result_count:
+ one: "%{count} sonuç."
+ other: "%{count} sonuç."
+ max_result_count:
+ one: "En iyi %{count} sonuç gösteriliyor."
+ other: "En iyi %{count} sonuç gösteriliyor."
+ query_name: "Sorgu"
+ query_groups: "Gruplar"
+ link: "Şunun için bağlantı:"
+ report_name: "Rapor"
+ query_description: "Açıklama"
+ query_time: "Son çalıştırma"
+ query_user: "Oluşturan"
+ column: "%{number}. sütun"
+ explain_label: "Sorgu planı dahil edilsin mi?"
+ save_params: "Varsayılanları Ayarla"
+ reset_params: "Sıfırla"
+ search_placeholder: "Ara..."
+ no_search_results: "Üzgünüz, metninizle eşleşen bir sonuç bulamadık."
+ form:
+ errors:
+ invalid: "Geçersiz"
+ no_such_category: "Böyle bir kategori yok"
+ no_such_group: "Böyle bir grup yok"
+ invalid_date: "%{date} geçersiz bir tarih"
+ invalid_time: "%{time} geçersiz bir saat"
+ group:
+ reports: "Raporlar"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "Veri Gezgini sorgularını çalıştırın. Sorgu kimliklerini belirterek API anahtarını bir sorgu kümesiyle sınırlandırın."
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: Kullanıcıya, Gruba veya E-postaya gönder
+ query_id:
+ label: Veri Gezgini Sorgusu
+ query_params:
+ label: Veri Gezgini Sorgu parametreleri
+ skip_empty:
+ label: Sonuç yoksa kişisel mesaj göndermeyi atlayın
+ attach_csv:
+ label: CSV dosyasını kişisel mesaja ekleyin
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: Sorgu sonuçlarının gönderileceği konu
+ query_id:
+ label: Veri Gezgini Sorgusu
+ query_params:
+ label: Veri Gezgini Sorgu parametreleri
+ skip_empty:
+ label: Sonuç yoksa göndermeyi atlayın
+ attach_csv:
+ label: CSV dosyasını gönderiye ekleyin
diff --git a/plugins/discourse-data-explorer/config/locales/client.ug.yml b/plugins/discourse-data-explorer/config/locales/client.ug.yml
new file mode 100644
index 00000000000..356d93aa22e
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ug.yml
@@ -0,0 +1,29 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ug:
+ js:
+ explorer:
+ or: "ياكى"
+ help:
+ label: "ياردەم"
+ types:
+ bool:
+ yes: "ھەئە"
+ no: "ياق"
+ export: "چىقار"
+ save: "ئۆزگەرتىشنى ساقلا"
+ edit: "تەھرىر"
+ delete: "ئۆچۈر"
+ result_count:
+ one: "%{count} نەتىجە."
+ other: "%{count} نەتىجە."
+ query_groups: "گۇرۇپپا"
+ query_description: "چۈشەندۈرۈش"
+ query_user: "قۇرغۇچى"
+ reset_params: "ئەسلىگە قايتۇر"
+ group:
+ reports: "دوكلات"
diff --git a/plugins/discourse-data-explorer/config/locales/client.uk.yml b/plugins/discourse-data-explorer/config/locales/client.uk.yml
new file mode 100644
index 00000000000..31aa53d1bc4
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.uk.yml
@@ -0,0 +1,63 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+uk:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "Вилучіть крапки з комою з запиту."
+ dirty: "Ви повинні зберегти запит перед запуском."
+ explorer:
+ or: "або"
+ admins_only: "Data explorer доступний лише адміністраторам."
+ title: "Data Explorer"
+ create: "Створити новий"
+ create_placeholder: "Назва запиту..."
+ description_placeholder: "Введіть тут опис"
+ import:
+ label: "Імпорт"
+ modal: "Імпорт запиту"
+ help:
+ label: "Довідка"
+ schema:
+ title: "Схема бази даних"
+ filter: "Пошук..."
+ sensitive: "Вміст цього стовпця може містити особливо чутливу або приватну інформацію. Будьте обережні, використовуючи вміст цього стовпця."
+ types:
+ bool:
+ yes: "Так"
+ no: "Ні"
+ null_: "Null"
+ export: "Експорт"
+ save: "Зберегти зміни"
+ saverun: "Збережіть зміни та запустіть"
+ run: "Запуск"
+ undo: "Скасувати зміни"
+ edit: "Редагувати"
+ delete: "Видалити"
+ recover: "Видалити запит"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "У запиті є не збережені зміни, які будуть втрачені, якщо ви перейдете далі."
+ result_count:
+ one: "%{count} результат."
+ few: "%{count} результатів."
+ many: "%{count} результатів."
+ other: "%{count} результатів."
+ query_name: "Запит"
+ query_groups: "Групи"
+ link: "Посилання для"
+ report_name: "Звіт"
+ query_description: "Опис"
+ query_time: "Останній запуск"
+ query_user: "Створено"
+ explain_label: "Включити план запитів?"
+ save_params: "Встановити значення за замовчуванням"
+ reset_params: "Скинути"
+ search_placeholder: "Пошук ..."
+ no_search_results: "На жаль, не вдалося знайти жодного результату, відповідного вашому тексту."
+ group:
+ reports: "Звіти"
diff --git a/plugins/discourse-data-explorer/config/locales/client.ur.yml b/plugins/discourse-data-explorer/config/locales/client.ur.yml
new file mode 100644
index 00000000000..ad4204565dd
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.ur.yml
@@ -0,0 +1,60 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ur:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "کمانڈ سے semicolons ہٹا دیں۔"
+ dirty: "چلانے سے پہلے آپ کا کمانڈ کو محفوظ کرنا لازمی ہے۔"
+ explorer:
+ or: "یا"
+ admins_only: "ڈیٹا ایکسپلورر صرف ایڈمنوں کو دستیاب ہے۔"
+ title: "ڈیٹا ایکسپلورر"
+ create: "نیا بنائیں"
+ create_placeholder: "ڈیٹا کمانڈ کا نام..."
+ description_placeholder: "یہاں تفصیل درج کریں"
+ import:
+ label: "درآمد"
+ modal: "ڈیٹا کمانڈ درآمد کریں"
+ help:
+ label: "مدد"
+ schema:
+ title: "ڈیٹا بیس سکیمہ"
+ filter: "تلاش کریں..."
+ sensitive: "اس کالم کے مواد میں خاص طور پر حساس یا نِجی معلومات موجود ہوسکتی ہے۔ براہ مہربانی، اِس کالم کے مواد کا استعمال کرتے وقت احتیاط کریں۔"
+ types:
+ bool:
+ yes: "ہاں "
+ no: "نہیں "
+ null_: "خالی"
+ export: "برآمد"
+ save: "تبدیلیاں محفوظ کریں"
+ saverun: "تبدیلیاں محفوظ کریں اور چلائیں"
+ run: "چلائیں"
+ undo: "تبدیلیاں منسوخ کریں"
+ edit: "ترمیم کریں"
+ delete: "حذف کریں"
+ recover: "ڈیٹا کمانڈ کا حذف کرنا منسوخ کریں"
+ download_json: "JSON"
+ download_csv: "CSV"
+ others_dirty: "ایک ڈیٹا کمانڈ کی غیرمحفوظ کردہ تبدیلیاں موجود ہیں جو آپ کے یہاں سے جانے کے بعد کھو جائیں گی۔"
+ result_count:
+ one: "%{count} نتیجہ۔"
+ other: "%{count} نتائج۔"
+ query_name: "ڈیٹا کمانڈ"
+ query_groups: "گروپس"
+ report_name: "رپورٹ"
+ query_description: "تفصیل"
+ query_time: "چلا آخری دفعہ"
+ query_user: "نے بنایا"
+ explain_label: "ڈیٹا کمانڈ پلَین شامل کریں؟"
+ save_params: "ڈیفالٹس سَیٹ کریں"
+ reset_params: "رِی سَیٹ"
+ search_placeholder: "تلاش کریں..."
+ no_search_results: "معذرت، ہمیں آپ کے متن سے ملتے ہوے کوئی نتائج نہ مل سکے۔"
+ group:
+ reports: "رپورٹیں"
diff --git a/plugins/discourse-data-explorer/config/locales/client.vi.yml b/plugins/discourse-data-explorer/config/locales/client.vi.yml
new file mode 100644
index 00000000000..626acc09d1e
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.vi.yml
@@ -0,0 +1,33 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+vi:
+ js:
+ explorer:
+ or: "hoặc"
+ import:
+ label: "Nhập"
+ help:
+ label: "Giúp "
+ schema:
+ filter: "Tìm kiến..."
+ types:
+ bool:
+ yes: "Đồng ý"
+ no: "Không"
+ export: "Xuất"
+ save: "Lưu thay đổi"
+ edit: "Sửa"
+ delete: "Xóa"
+ result_count:
+ other: "%{count} kết quả."
+ query_groups: "Nhóm"
+ query_description: "Mô tả"
+ query_user: "Tạo bởi"
+ reset_params: "Cài lại"
+ search_placeholder: "Tìm kiến..."
+ group:
+ reports: "Báo cáo"
diff --git a/plugins/discourse-data-explorer/config/locales/client.zh_CN.yml b/plugins/discourse-data-explorer/config/locales/client.zh_CN.yml
new file mode 100644
index 00000000000..38488223abd
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.zh_CN.yml
@@ -0,0 +1,114 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_CN:
+ js:
+ errors:
+ explorer:
+ no_semicolons: "从查询中移除分号。"
+ dirty: "您必须先保存查询,然后才能运行。"
+ explorer:
+ or: "或者"
+ admins_only: "数据资源管理器仅供管理员使用。"
+ allow_groups: "允许群组访问此查询"
+ title: "数据资源管理器"
+ create: "创建新查询"
+ create_placeholder: "查询名称…"
+ description_placeholder: "在此处输入描述"
+ import:
+ label: "导入"
+ modal: "导入查询"
+ unparseable_json: "无法解析的 JSON 文件。"
+ wrong_json: "错误的 JSON 文件。JSON 文件应包含一个 'query' 对象,该对象至少应具有一个 'sql' 属性。"
+ help:
+ label: "帮助"
+ modal_title: "数据资源管理器帮助"
+ auto_resolution: "<h2>自动实体解析</h2> <p>当您的查询返回实体 ID 时,数据资源管理器可能会自动将其替换为查询结果中的实体名称和其他有用信息。自动解析适用于 <i><b>USER_ID</b></i>、<i><b>GROUP_ID</b></i>、<i><b>topic_id</b></i>、<i><b>CATEGORY_ID</b></i> 和 <i><b>badge_id</b></i>。要尝试此操作,请运行以下查询:</p> <pre><code>SELECT user_id\nFROM posts</code></pre>"
+ custom_params: "<h2>创建自定义参数</h2> <p>要为您的查询创建自定义参数,请将其放在查询的顶部并遵循以下格式:</p> <pre><code>-- [params]\n-- int :num = 1\n\nSELECT :num</code></pre> <p><i>注意:包含 [params] 以及它前面的两个破折号和您要声明的每个自定义参数的第一行是必需的。</i></p>"
+ default_values: "<h3>默认值</h3> <p>您可以声明带或不带默认值的参数。默认值将显示在查询编辑器下方的文本字段中,您可以根据需要对其进行编辑。没有默认值声明的参数仍将生成一个文本字段,但将为空并以红色突出显示。</p> <pre><code>-- [params]\n-- text :username = my_username\n-- int :age</code></pre>"
+ data_types: "<h3>数据类型</h3> <p>以下是您可以使用的常见数据类型:</p> <ul> <li><b>整数</b> - 有符号四字节整数</li> <li><b>文本</b> - 可变长度字符字符串</li> <li><b>布尔值</b> – true/false</li> <li><b>日期</b> - 日历日期(年、月、日)</li> </ul> <p>有关数据类型的更多信息,请访问<a href='http://www.postgresql.org/docs/9.3/static/datatype.html#DATATYPE-TABLE' target='_blank'>此网站</a>。</p>"
+ schema:
+ title: "数据库架构"
+ filter: "搜索…"
+ sensitive: "此列的内容可能包含特别敏感或私人的信息。使用此列的内容时请谨慎。"
+ types:
+ bool:
+ yes: "是"
+ no: "否"
+ null_: "空"
+ export: "导出"
+ view_json: "查看 JSON"
+ save: "保存变更"
+ saverun: "保存变更并运行"
+ run: "运行"
+ undo: "舍弃变更"
+ edit: "编辑"
+ delete: "删除"
+ recover: "取消删除查询"
+ download_json: "JSON"
+ download_csv: "CSV"
+ show_table: "表"
+ show_graph: "图表"
+ others_dirty: "查询具有未保存的更改,如果您离开,这些更改将丢失。"
+ run_time: "查询在 %{value} 毫秒内完成。"
+ result_count:
+ other: "%{count} 个结果。"
+ max_result_count:
+ other: "显示前 %{count} 个结果。"
+ query_name: "查询"
+ query_groups: "群组"
+ link: "链接"
+ report_name: "报告"
+ query_description: "描述"
+ query_time: "最后运行"
+ query_user: "创建者"
+ column: "第 %{number} 列"
+ explain_label: "包括查询计划?"
+ save_params: "设置默认值"
+ reset_params: "重置"
+ search_placeholder: "搜索…"
+ no_search_results: "抱歉,我们找不到任何与您的文本匹配的结果。"
+ form:
+ errors:
+ invalid: "无效"
+ no_such_category: "没有此类类别"
+ no_such_group: "没有此类群组"
+ invalid_date: "%{date} 是无效日期"
+ invalid_time: "%{time} 是无效时间"
+ group:
+ reports: "报告"
+ admin:
+ api:
+ scopes:
+ descriptions:
+ discourse_data_explorer:
+ run_queries: "运行数据资源管理器查询。通过指定查询 ID 将 API 密钥限制为一组查询。"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ fields:
+ recipients:
+ label: 发送至用户、群组或电子邮件
+ query_id:
+ label: 数据资源管理器查询
+ query_params:
+ label: 数据资源管理器查询参数
+ skip_empty:
+ label: 如果没有结果,则跳过发送 PM
+ attach_csv:
+ label: 将 CSV 文件附加到私信
+ recurring_data_explorer_result_topic:
+ fields:
+ topic_id:
+ label: 发布查询结果的话题
+ query_id:
+ label: 数据资源管理器查询
+ query_params:
+ label: 数据资源管理器查询参数
+ skip_empty:
+ label: 如果没有结果,则跳过发布
+ attach_csv:
+ label: 将 CSV 文件附加到帖子
diff --git a/plugins/discourse-data-explorer/config/locales/client.zh_TW.yml b/plugins/discourse-data-explorer/config/locales/client.zh_TW.yml
new file mode 100644
index 00000000000..2ee7e8cf1eb
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/client.zh_TW.yml
@@ -0,0 +1,30 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_TW:
+ js:
+ explorer:
+ or: "或"
+ import:
+ label: "匯入"
+ help:
+ label: "幫助"
+ schema:
+ filter: "搜尋..."
+ types:
+ bool:
+ yes: "是"
+ no: "否"
+ export: "匯出"
+ save: "儲存變更"
+ edit: "編輯"
+ delete: "刪除"
+ query_groups: "群組"
+ query_description: "描述"
+ reset_params: "重置"
+ search_placeholder: "搜尋..."
+ group:
+ reports: "報告"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ar.yml b/plugins/discourse-data-explorer/config/locales/server.ar.yml
new file mode 100644
index 00000000000..8b7e35c97c4
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ar.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ar:
+ site_settings:
+ data_explorer_enabled: "تفعيل مستكشف البيانات في /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: جدولة رسالة خاصة بنتائج مستكشف البيانات
+ description: احصل على تقارير مجدولة يتم إرسالها إلى رسائلك
+ no_csv_allowed: "عند استخدام الحقل `attach_csv`، يجب إضافة `csv` إلى قائمة الامتدادات المعتمدة في إعدادات الموقع."
+ recurring_data_explorer_result_topic:
+ title: جدولة منشور في موضوع باستخدام نتائج مستكشف البيانات
+ description: احصل على تقارير مجدولة يتم نشرها في موضوع معيَّن
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "تقرير مجدول للاستعلام %{query_name}"
+ upload_appendix: "الملحق: [%{filename}|مرفق](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.be.yml b/plugins/discourse-data-explorer/config/locales/server.be.yml
new file mode 100644
index 00000000000..2ea77a0d350
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.be.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+be:
diff --git a/plugins/discourse-data-explorer/config/locales/server.bg.yml b/plugins/discourse-data-explorer/config/locales/server.bg.yml
new file mode 100644
index 00000000000..52333529d3c
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.bg.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bg:
diff --git a/plugins/discourse-data-explorer/config/locales/server.bs_BA.yml b/plugins/discourse-data-explorer/config/locales/server.bs_BA.yml
new file mode 100644
index 00000000000..c43c0c106ea
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.bs_BA.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bs_BA:
+ site_settings:
+ data_explorer_enabled: "Omogućite Data Explorer u / admin / plugins / explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ca.yml b/plugins/discourse-data-explorer/config/locales/server.ca.yml
new file mode 100644
index 00000000000..0dcdee77bd5
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ca.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ca:
+ site_settings:
+ data_explorer_enabled: "Activa l'Explorador de dades en /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.cs.yml b/plugins/discourse-data-explorer/config/locales/server.cs.yml
new file mode 100644
index 00000000000..d3b7263c7bf
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.cs.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+cs:
+ site_settings:
+ data_explorer_enabled: "Povolit Data Explorer v /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.da.yml b/plugins/discourse-data-explorer/config/locales/server.da.yml
new file mode 100644
index 00000000000..1fbc30f6850
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.da.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+da:
+ site_settings:
+ data_explorer_enabled: "Aktivér Data Explorer ved /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.de.yml b/plugins/discourse-data-explorer/config/locales/server.de.yml
new file mode 100644
index 00000000000..1abfa253245
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.de.yml
@@ -0,0 +1,45 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+de:
+ site_settings:
+ data_explorer_enabled: "Aktiviere den Daten-Explorer unter /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Plane eine PN mit den Ergebnissen des Daten-Explorers
+ description: Geplante Berichte an deine Nachrichten schicken
+ no_csv_allowed: "Wenn das Feld `attach_csv` verwendet wird, muss `csv` zur Liste der autorisierten Erweiterungen in den Website-Einstellungen hinzugefügt werden."
+ recurring_data_explorer_result_topic:
+ title: Einen Beitrag in einem Thema mit Daten-Explorer-Ergebnissen planen
+ description: Geplante Berichte zu einem bestimmten Thema veröffentlichen
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Geplanter Bericht für %{query_name}"
+ body: |
+ Hallo %{recipient_name}, dein Daten Explorer Bericht ist fertig.
+
+ Anfragename:
+ %{query_name}
+
+ Hier sind die Ergebnisse:
+ %{table}
+
+ <a href='%{base_url}/admin/plugins/explorer/queries/%{query_id}'>Abfrage im Daten-Explorer anzeigen</a>
+
+ Bericht erstellt um %{created_at} (%{timezone})
+ post:
+ body: |
+ ### Geplanter Bericht für %{query_name}
+
+ Hier sind die Ergebnisse:
+ %{table}
+
+ <a href='%{base_url}/admin/plugins/explorer/queries/%{query_id}'>Abfrage im Data Explorer anzeigen</a>
+
+ Bericht erstellt um %{created_at} (%{timezone})
+ upload_appendix: "Anhang: [%{filename}|attachment](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.el.yml b/plugins/discourse-data-explorer/config/locales/server.el.yml
new file mode 100644
index 00000000000..d872d0ecc40
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.el.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+el:
diff --git a/plugins/discourse-data-explorer/config/locales/server.en.yml b/plugins/discourse-data-explorer/config/locales/server.en.yml
new file mode 100644
index 00000000000..55cf55f0f78
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.en.yml
@@ -0,0 +1,39 @@
+en:
+ site_settings:
+ data_explorer_enabled: "Enable the Data Explorer at /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Schedule a PM with Data Explorer results
+ description: Get scheduled reports sent to your messages
+ no_csv_allowed: "When using `attach_csv` field, `csv` must be added to the list of authorized extensions in the site settings."
+ recurring_data_explorer_result_topic:
+ title: Schedule a post in a topic with Data Explorer results
+ description: Get scheduled reports posted to a specific topic
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Scheduled report for %{query_name}"
+ body: |
+ Hi %{recipient_name}, your Data Explorer report is ready.
+
+ Query name:
+ %{query_name}
+
+ Here are the results:
+ %{table}
+
+ <a href='%{base_url}/admin/plugins/explorer/queries/%{query_id}'>View query in Data Explorer</a>
+
+ Report created at %{created_at} (%{timezone})
+ post:
+ body: |
+ ### Scheduled report for %{query_name}
+
+ Here are the results:
+ %{table}
+
+ <a href='%{base_url}/admin/plugins/explorer/queries/%{query_id}'>View query in Data Explorer</a>
+
+ Report created at %{created_at} (%{timezone})
+ upload_appendix: "Appendix: [%{filename}|attachment](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.en_GB.yml b/plugins/discourse-data-explorer/config/locales/server.en_GB.yml
new file mode 100644
index 00000000000..2d4fa180ec7
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.en_GB.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+en_GB:
diff --git a/plugins/discourse-data-explorer/config/locales/server.es.yml b/plugins/discourse-data-explorer/config/locales/server.es.yml
new file mode 100644
index 00000000000..6d8a017d79e
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.es.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+es:
+ site_settings:
+ data_explorer_enabled: "Habilita el explorador de datos en /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Programar un MP con los resultados del explorador de datos
+ description: Recibir informes programados enviados a tus mensajes
+ no_csv_allowed: "Cuando utilices el campo `attach_csv`, debe añadirse `csv` a la lista de extensiones autorizadas en los ajustes del sitio."
+ recurring_data_explorer_result_topic:
+ title: Programar una publicación en un tema con los resultados del Explorador de datos
+ description: Obtener informes programados publicados en un tema específico
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Informe programado para %{query_name}"
+ upload_appendix: "Apéndice: [%{filename}|archivo adjunto](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.et.yml b/plugins/discourse-data-explorer/config/locales/server.et.yml
new file mode 100644
index 00000000000..0ea0b6d554b
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.et.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+et:
diff --git a/plugins/discourse-data-explorer/config/locales/server.fa_IR.yml b/plugins/discourse-data-explorer/config/locales/server.fa_IR.yml
new file mode 100644
index 00000000000..d81c3666dfa
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.fa_IR.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fa_IR:
+ site_settings:
+ data_explorer_enabled: "Data Explorer را در /admin/plugins/explorer فعال کنید"
diff --git a/plugins/discourse-data-explorer/config/locales/server.fi.yml b/plugins/discourse-data-explorer/config/locales/server.fi.yml
new file mode 100644
index 00000000000..98302a42f82
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.fi.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fi:
+ site_settings:
+ data_explorer_enabled: "Ota käyttöön Dataselain, ilmestyy polkuun /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Ajoita yksityisviesti Dataselaimen tuloksilla
+ description: Vastaanota ajoitettuja raportteja viesteihisi
+ no_csv_allowed: "Kun käytät attach_csv-kenttää, \"csv\" täytyy lisätä sallittujen päätteiden luetteloon sivustoasetuksissa."
+ recurring_data_explorer_result_topic:
+ title: Ajoita viesti ketjussa Dataselaimen tuloksilla
+ description: Vastaanota ajoitettuja raportteja tiettyyn ketjuun
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Kyselyn %{query_name} ajoitettu raportti"
+ upload_appendix: "Liite: [%{filename}|attachment](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.fr.yml b/plugins/discourse-data-explorer/config/locales/server.fr.yml
new file mode 100644
index 00000000000..4ae3d44eb87
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.fr.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fr:
+ site_settings:
+ data_explorer_enabled: "Activer l'explorateur de données dans /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Planifier un MP avec les résultats de l'explorateur de données
+ description: Recevez des rapports planifiés dans vos messages
+ no_csv_allowed: "Lors de l'utilisation du champ `attach_csv`, `csv` doit être ajouté à la liste des extensions autorisées dans les paramètres du site."
+ recurring_data_explorer_result_topic:
+ title: Planifier une publication dans un sujet avec les résultats de l'explorateur de données
+ description: Recevoir des rapports planifiés sur un sujet spécifique
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Rapport planifié pour %{query_name}"
+ upload_appendix: "Annexe : [%{filename}|pièce jointe](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.gl.yml b/plugins/discourse-data-explorer/config/locales/server.gl.yml
new file mode 100644
index 00000000000..fb911ce1635
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.gl.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+gl:
diff --git a/plugins/discourse-data-explorer/config/locales/server.he.yml b/plugins/discourse-data-explorer/config/locales/server.he.yml
new file mode 100644
index 00000000000..d89aa1149c8
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.he.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+he:
+ site_settings:
+ data_explorer_enabled: "הפעלת דפדפן הנתונים תחת ‎/admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: תזמון הודעה פרטית עם תוצאות דפדפן נתונים
+ description: קבלת דוחות מתוזמנים להודעות שלך
+ no_csv_allowed: "בעת שימוש בשדה `attach_csv` (הצמדת CSV), יש להוסיף `csv` לרשימת ההרחבות המורשות בהגדרות האתר."
+ recurring_data_explorer_result_topic:
+ title: תזמון פוסט בנושא עם תוצאות דפדפן נתונים
+ description: קבלת דוחות מתוזמנים מפורסמים בנושא מסוים
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "דוח מתוזמן עבור %{query_name}"
+ upload_appendix: "נספח: [%{filename}|attachment](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.hr.yml b/plugins/discourse-data-explorer/config/locales/server.hr.yml
new file mode 100644
index 00000000000..a2e7498a5f9
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.hr.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hr:
+ site_settings:
+ data_explorer_enabled: "Uključi \"Data Explorer\" na /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.hu.yml b/plugins/discourse-data-explorer/config/locales/server.hu.yml
new file mode 100644
index 00000000000..86c27cc1993
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.hu.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hu:
+ site_settings:
+ data_explorer_enabled: "Adatfelfedező engedélyezése az /admin/plugins/explorer oldalon"
diff --git a/plugins/discourse-data-explorer/config/locales/server.hy.yml b/plugins/discourse-data-explorer/config/locales/server.hy.yml
new file mode 100644
index 00000000000..8493d684d8a
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.hy.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hy:
+ site_settings:
+ data_explorer_enabled: "Միացնել Տվյալների Ուսումնասիրումը այստեղ՝ /ադմին/պլագիններ/ուսումնասիրում"
diff --git a/plugins/discourse-data-explorer/config/locales/server.id.yml b/plugins/discourse-data-explorer/config/locales/server.id.yml
new file mode 100644
index 00000000000..596e36b2e13
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.id.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+id:
diff --git a/plugins/discourse-data-explorer/config/locales/server.it.yml b/plugins/discourse-data-explorer/config/locales/server.it.yml
new file mode 100644
index 00000000000..536b31aaf7f
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.it.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+it:
+ site_settings:
+ data_explorer_enabled: "Abilitare il plugin Data Explorer su /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Pianifica un MP con i risultati di Data Explorer
+ description: Ricevi report pianificati inviati ai tuoi messaggi
+ no_csv_allowed: "Quando si utilizza il campo `attach_csv`, `csv` deve essere aggiunto all'elenco delle estensioni autorizzate nelle impostazioni del sito."
+ recurring_data_explorer_result_topic:
+ title: Pianifica un messaggio a un argomento con i risultati di Data Explorer
+ description: Ricevi report programmati pubblicati su un argomento specifico
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Report programmato per %{query_name}"
+ upload_appendix: "Appendice: [%{filename}|allegato](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ja.yml b/plugins/discourse-data-explorer/config/locales/server.ja.yml
new file mode 100644
index 00000000000..5f64070daa1
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ja.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ja:
+ site_settings:
+ data_explorer_enabled: "/admin/plugins/explorer のデータエクスプローラーを許可する"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: データエクスプローラーの結果で PM をスケジュールする
+ description: 定期レポートをメッセージで送信します
+ no_csv_allowed: "`attach_csv` フィールドを使用する場合は、`csv` がサイト設定の承認済み拡張機能のリストに追加されている必要があります。"
+ recurring_data_explorer_result_topic:
+ title: データエクスプローラーの結果を使用してトピックへの投稿をスケジュールする
+ description: 定期レポートを特定のトピックに投稿します
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "%{query_name} の定期レポート"
+ upload_appendix: "付録: [%{filename}|添付ファイル](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ko.yml b/plugins/discourse-data-explorer/config/locales/server.ko.yml
new file mode 100644
index 00000000000..a9e10b245e8
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ko.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ko:
+ site_settings:
+ data_explorer_enabled: "/ admin / plugins / explorer에서 데이터 탐색기를 활성화하십시오."
diff --git a/plugins/discourse-data-explorer/config/locales/server.lt.yml b/plugins/discourse-data-explorer/config/locales/server.lt.yml
new file mode 100644
index 00000000000..16bb19758dc
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.lt.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lt:
diff --git a/plugins/discourse-data-explorer/config/locales/server.lv.yml b/plugins/discourse-data-explorer/config/locales/server.lv.yml
new file mode 100644
index 00000000000..59e0ef6f4ed
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.lv.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lv:
diff --git a/plugins/discourse-data-explorer/config/locales/server.nb_NO.yml b/plugins/discourse-data-explorer/config/locales/server.nb_NO.yml
new file mode 100644
index 00000000000..2e2224d1472
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.nb_NO.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nb_NO:
diff --git a/plugins/discourse-data-explorer/config/locales/server.nl.yml b/plugins/discourse-data-explorer/config/locales/server.nl.yml
new file mode 100644
index 00000000000..47af66d713a
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.nl.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nl:
+ site_settings:
+ data_explorer_enabled: "Gegevensverkenner op /admin/plugins/explorer inschakelen"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Plan een PB met de resultaten van Gegevensverkenner
+ description: Laat geplande rapporten naar je berichten sturen
+ no_csv_allowed: "Als het veld 'attach_csv' wordt gebruikt, moet 'csv' worden toegevoegd aan de lijst van toegestane extensies in de site-instellingen."
+ recurring_data_explorer_result_topic:
+ title: Plaats een bericht in een topic met Gegevensverkenner-resultaten
+ description: Ontvang geplande rapporten over een specifiek topic
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Gepland rapport voor %{query_name}"
+ upload_appendix: "Bijlage: [%{filename}|bijlage](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.pl_PL.yml b/plugins/discourse-data-explorer/config/locales/server.pl_PL.yml
new file mode 100644
index 00000000000..e269e59f029
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.pl_PL.yml
@@ -0,0 +1,13 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pl_PL:
+ site_settings:
+ data_explorer_enabled: "Włącz eksplorator danych w /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Zaplanuj PW z wynikami eksploratora danych
diff --git a/plugins/discourse-data-explorer/config/locales/server.pt.yml b/plugins/discourse-data-explorer/config/locales/server.pt.yml
new file mode 100644
index 00000000000..e35a16a9701
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.pt.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt:
+ site_settings:
+ data_explorer_enabled: "Ativar o «Explorador de Dados» em \"/admin/plugins/explorer\""
diff --git a/plugins/discourse-data-explorer/config/locales/server.pt_BR.yml b/plugins/discourse-data-explorer/config/locales/server.pt_BR.yml
new file mode 100644
index 00000000000..aff723c149a
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.pt_BR.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt_BR:
+ site_settings:
+ data_explorer_enabled: "Ativar o Explorador de Dados em /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Agendar uma MP com os resultados do explorador de dados
+ description: Obter relatórios agendados enviados às suas mensagens
+ no_csv_allowed: "Ao usar o campo \"attach_csv\", é preciso acrescentar \"csv\" à lista de extensões autorizadas nas configurações do site."
+ recurring_data_explorer_result_topic:
+ title: Agendar uma postagem em um tópico com resultados do Data Explorer
+ description: Obter relatórios programados publicados em um tópico específico
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Relatório programado para %{query_name}"
+ upload_appendix: "Apêndice: [%{filename}|anexo](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ro.yml b/plugins/discourse-data-explorer/config/locales/server.ro.yml
new file mode 100644
index 00000000000..08a77f812ee
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ro.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ro:
diff --git a/plugins/discourse-data-explorer/config/locales/server.ru.yml b/plugins/discourse-data-explorer/config/locales/server.ru.yml
new file mode 100644
index 00000000000..87a52d133d1
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ru.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ru:
+ site_settings:
+ data_explorer_enabled: "Включить проводник данных в /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Запланировать личное сообщение с результатами от проводника данных
+ description: Отправка запланированных отчетов сообщением
+ no_csv_allowed: "При использовании поля `attach_csv` необходимо добавить `csv` в список разрешенных расширений в настройках сайта."
+ recurring_data_explorer_result_topic:
+ title: Запланировать публикацию в теме с результатами от проводника данных
+ description: Отправка запланированных отчетов через публикацию в определенной теме
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "Запланированный отчет по запросу «%{query_name}»"
+ upload_appendix: "Приложение: [%{filename}|вложение](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.sk.yml b/plugins/discourse-data-explorer/config/locales/server.sk.yml
new file mode 100644
index 00000000000..4702a280d12
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.sk.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sk:
+ site_settings:
+ data_explorer_enabled: "Povoľ \"Data explorer\" v /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.sl.yml b/plugins/discourse-data-explorer/config/locales/server.sl.yml
new file mode 100644
index 00000000000..cdff80b7bb6
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.sl.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sl:
+ site_settings:
+ data_explorer_enabled: "Omogočite vtičnik Raziskovalec podatkov na /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.sq.yml b/plugins/discourse-data-explorer/config/locales/server.sq.yml
new file mode 100644
index 00000000000..7f051b7a7cf
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.sq.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sq:
diff --git a/plugins/discourse-data-explorer/config/locales/server.sr.yml b/plugins/discourse-data-explorer/config/locales/server.sr.yml
new file mode 100644
index 00000000000..88d63d6ae1a
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.sr.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sr:
diff --git a/plugins/discourse-data-explorer/config/locales/server.sv.yml b/plugins/discourse-data-explorer/config/locales/server.sv.yml
new file mode 100644
index 00000000000..60df277b99d
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.sv.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sv:
+ site_settings:
+ data_explorer_enabled: "Aktivera Datautforskaren på /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.sw.yml b/plugins/discourse-data-explorer/config/locales/server.sw.yml
new file mode 100644
index 00000000000..369eb73053c
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.sw.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sw:
+ site_settings:
+ data_explorer_enabled: "Ruhusu Utafiti wa taarifa kwenye /kiongozi/programu jalizi/utafutaji"
diff --git a/plugins/discourse-data-explorer/config/locales/server.te.yml b/plugins/discourse-data-explorer/config/locales/server.te.yml
new file mode 100644
index 00000000000..03967bdbb07
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.te.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+te:
diff --git a/plugins/discourse-data-explorer/config/locales/server.th.yml b/plugins/discourse-data-explorer/config/locales/server.th.yml
new file mode 100644
index 00000000000..7de85ff91c4
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.th.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+th:
diff --git a/plugins/discourse-data-explorer/config/locales/server.tr_TR.yml b/plugins/discourse-data-explorer/config/locales/server.tr_TR.yml
new file mode 100644
index 00000000000..d0c53644fed
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.tr_TR.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+tr_TR:
+ site_settings:
+ data_explorer_enabled: "Veri gezginini şuradan etkinleştirin: /admin/plugins/explorer"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: Veri Gezgini sonuçlarıyla kişisel mesaj planlayın
+ description: Mesajlarınıza gönderilen planlanmış raporları alın
+ no_csv_allowed: "`attach_csv` alanını kullanırken site ayarlarında izin verilen uzantılar listesine `csv` eklenmelidir."
+ recurring_data_explorer_result_topic:
+ title: Veri Gezgini sonuçlarını içeren bir konuda gönderi planlayın
+ description: Belirli bir konuya gönderilen planlanmış raporları alın
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "%{query_name} için planlanmış rapor"
+ upload_appendix: "Ek: [%{filename}|ek](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ug.yml b/plugins/discourse-data-explorer/config/locales/server.ug.yml
new file mode 100644
index 00000000000..a6bf0185ae2
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ug.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ug:
diff --git a/plugins/discourse-data-explorer/config/locales/server.uk.yml b/plugins/discourse-data-explorer/config/locales/server.uk.yml
new file mode 100644
index 00000000000..1a6e526e72a
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.uk.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+uk:
+ site_settings:
+ data_explorer_enabled: "Увімкніть Data Explorer в /admin/plugins/explorer"
diff --git a/plugins/discourse-data-explorer/config/locales/server.ur.yml b/plugins/discourse-data-explorer/config/locales/server.ur.yml
new file mode 100644
index 00000000000..285de9c6780
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.ur.yml
@@ -0,0 +1,9 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ur:
+ site_settings:
+ data_explorer_enabled: "ڈیٹا ایکسپلورر کو /admin/plugins/explorer پر فعال کریں"
diff --git a/plugins/discourse-data-explorer/config/locales/server.vi.yml b/plugins/discourse-data-explorer/config/locales/server.vi.yml
new file mode 100644
index 00000000000..f629dcf5329
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.vi.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+vi:
diff --git a/plugins/discourse-data-explorer/config/locales/server.zh_CN.yml b/plugins/discourse-data-explorer/config/locales/server.zh_CN.yml
new file mode 100644
index 00000000000..889d4fcc408
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.zh_CN.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_CN:
+ site_settings:
+ data_explorer_enabled: "请在 /admin/plugins/explorer 下启用数据资源管理器"
+ discourse_automation:
+ scriptables:
+ recurring_data_explorer_result_pm:
+ title: 使用数据资源管理器结果安排 PM
+ description: 将定时报告发送到您的消息中
+ no_csv_allowed: "使用 `attach_csv` 字段时,必须将 `csv` 添加到网站设置中的授权扩展程序列表中。"
+ recurring_data_explorer_result_topic:
+ title: 使用数据资源管理器结果安排某一话题的帖子
+ description: 将定时报告发布到特定话题
+ data_explorer:
+ report_generator:
+ private_message:
+ title: "%{query_name} 的定时报告"
+ upload_appendix: "附录:[%{filename}|附件](%{short_url})"
diff --git a/plugins/discourse-data-explorer/config/locales/server.zh_TW.yml b/plugins/discourse-data-explorer/config/locales/server.zh_TW.yml
new file mode 100644
index 00000000000..7e15fab0018
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/locales/server.zh_TW.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_TW:
diff --git a/plugins/discourse-data-explorer/config/routes.rb b/plugins/discourse-data-explorer/config/routes.rb
new file mode 100644
index 00000000000..d3434be4184
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/routes.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+DiscourseDataExplorer::Engine.routes.draw do
+ root to: "query#index"
+ get "queries" => "query#index"
+ get "queries/:id" => "query#show"
+
+ scope "/", defaults: { format: :json } do
+ get "schema" => "query#schema"
+ get "groups" => "query#groups"
+ post "queries" => "query#create"
+ put "queries/:id" => "query#update"
+ delete "queries/:id" => "query#destroy"
+ post "queries/:id/run" => "query#run", :constraints => { format: /(json|csv)/ }
+ end
+end
+
+Discourse::Application.routes.draw do
+ get "/g/:group_name/reports" => "discourse_data_explorer/query#group_reports_index"
+ get "/g/:group_name/reports/:id" => "discourse_data_explorer/query#group_reports_show"
+ post "/g/:group_name/reports/:id/run" => "discourse_data_explorer/query#group_reports_run"
+
+ mount DiscourseDataExplorer::Engine, at: "/admin/plugins/explorer"
+end
diff --git a/plugins/discourse-data-explorer/config/settings.yml b/plugins/discourse-data-explorer/config/settings.yml
new file mode 100644
index 00000000000..74fa545732d
--- /dev/null
+++ b/plugins/discourse-data-explorer/config/settings.yml
@@ -0,0 +1,8 @@
+plugins:
+ data_explorer_enabled:
+ default: false
+ client: true
+ data_explorer_query_result_limit:
+ default: 1000
+ hidden: true
+ max: 10000
diff --git a/plugins/discourse-data-explorer/db/migrate/20200810053843_create_data_explorer_queries.rb b/plugins/discourse-data-explorer/db/migrate/20200810053843_create_data_explorer_queries.rb
new file mode 100644
index 00000000000..a96638751f2
--- /dev/null
+++ b/plugins/discourse-data-explorer/db/migrate/20200810053843_create_data_explorer_queries.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+class CreateDataExplorerQueries < ActiveRecord::Migration[6.0]
+ def up
+ create_table :data_explorer_queries do |t|
+ t.string :name
+ t.text :description
+ t.text :sql, default: "SELECT 1", null: false
+ t.integer :user_id
+ t.datetime :last_run_at
+ t.boolean :hidden, default: false, null: false
+ t.timestamps
+ end
+
+ create_table :data_explorer_query_groups do |t|
+ t.integer :query_id
+ t.integer :group_id
+ t.index :query_id
+ t.index :group_id
+ end
+ add_index(:data_explorer_query_groups, %i[query_id group_id], unique: true)
+
+ DB.exec <<~SQL, now: Time.zone.now
+ INSERT INTO data_explorer_queries(id, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at)
+ SELECT
+ (replace(key, 'q:',''))::integer,
+ value::json->>'name',
+ value::json->>'description',
+ value::json->>'sql',
+ CASE WHEN (value::json->'created_by')::text = 'null' THEN
+ null
+ WHEN (value::json->'created_by')::text = '""' THEN
+ null
+ WHEN (value::jsonb ? 'created_by') THEN
+ (value::json->>'created_by')::integer
+ ELSE
+ null
+ END,
+ CASE WHEN (value::json->'last_run_at')::text = 'null' THEN
+ null
+ WHEN (value::json->'last_run_at')::text = '""' THEN
+ null
+ ELSE
+ (value::json->'last_run_at')::text::timestamptz
+ END,
+ CASE WHEN (value::json->'hidden')::text = 'null' THEN
+ false
+ WHEN (value::jsonb ? 'hidden') THEN
+ (value::json->'hidden')::text::boolean
+ ELSE
+ false
+ END,
+ :now,
+ :now
+ FROM plugin_store_rows
+ WHERE plugin_name = 'discourse-data-explorer' AND type_name = 'JSON'
+ SQL
+
+ DB
+ .query(
+ "SELECT * FROM plugin_store_rows WHERE plugin_name = 'discourse-data-explorer' AND type_name = 'JSON'",
+ )
+ .each do |row|
+ json = JSON.parse(row.value)
+ next if json["group_ids"].blank?
+ query_id =
+ DB
+ .query(
+ "SELECT id FROM data_explorer_queries WHERE
+ name = ? AND sql = ?",
+ json["name"],
+ json["sql"],
+ )
+ .first
+ .id
+
+ json["group_ids"].each do |group_id|
+ next if group_id.blank? || query_id.blank?
+ DB.exec <<~SQL
+ INSERT INTO data_explorer_query_groups(query_id, group_id)
+ VALUES(#{query_id}, #{group_id})
+ SQL
+ end
+ end
+
+ DB.exec <<~SQL
+ SELECT
+ setval(
+ pg_get_serial_sequence('data_explorer_queries', 'id'),
+ (select greatest(max(id), 1) from data_explorer_queries)
+ );
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-data-explorer/db/migrate/20200902225712_fix_query_ids.rb b/plugins/discourse-data-explorer/db/migrate/20200902225712_fix_query_ids.rb
new file mode 100644
index 00000000000..e566c963d93
--- /dev/null
+++ b/plugins/discourse-data-explorer/db/migrate/20200902225712_fix_query_ids.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class FixQueryIds < ActiveRecord::Migration[6.0]
+ def up
+ Rake::Task["data_explorer:fix_query_ids"].invoke
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-data-explorer/db/migrate/20230227102505_rename_data_explorer_namespace.rb b/plugins/discourse-data-explorer/db/migrate/20230227102505_rename_data_explorer_namespace.rb
new file mode 100644
index 00000000000..ce0bce3adbd
--- /dev/null
+++ b/plugins/discourse-data-explorer/db/migrate/20230227102505_rename_data_explorer_namespace.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+class RenameDataExplorerNamespace < ActiveRecord::Migration[7.0]
+ def up
+ execute <<~SQL
+ UPDATE api_key_scopes
+ SET resource = 'discourse_data_explorer'
+ WHERE resource = 'data_explorer'
+ SQL
+
+ execute <<~SQL
+ UPDATE bookmarks
+ SET bookmarkable_type = 'DiscourseDataExplorer::QueryGroup'
+ WHERE bookmarkable_type = 'DataExplorer::QueryGroup'
+ SQL
+ end
+
+ def down
+ execute <<~SQL
+ UPDATE api_key_scopes
+ SET resource = 'data_explorer'
+ WHERE resource = 'discourse_data_explorer'
+ SQL
+
+ execute <<~SQL
+ UPDATE bookmarks
+ SET bookmarkable_type = 'DiscourseDataExplorer::QueryGroup'
+ WHERE bookmarkable_type = 'DataExplorer::QueryGroup'
+ SQL
+ end
+end
diff --git a/plugins/discourse-data-explorer/db/migrate/20241009161603_alter_query_id_to_bigint.rb b/plugins/discourse-data-explorer/db/migrate/20241009161603_alter_query_id_to_bigint.rb
new file mode 100644
index 00000000000..6368f471ef6
--- /dev/null
+++ b/plugins/discourse-data-explorer/db/migrate/20241009161603_alter_query_id_to_bigint.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class AlterQueryIdToBigint < ActiveRecord::Migration[7.1]
+ def up
+ change_column :data_explorer_query_groups, :query_id, :bigint
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
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
new file mode 100644
index 00000000000..ff43fa5da23
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
@@ -0,0 +1,581 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ module DataExplorer
+ # Used for ftype calls, see https://www.rubydoc.info/gems/pg/0.17.1/PG%2FResult:ftype
+ # and /usr/include/postgresql/server/catalog/pg_type_d.h
+ PG_TYPE_OID_JSON = 114
+
+ # Run a data explorer query on the currently connected database.
+ #
+ # @param [Query] query the Query object to run
+ # @param [Hash] params the colon-style query parameters for the query
+ # @param [Hash] opts hash of options
+ # explain - include a query plan in the result
+ # @return [Hash]
+ # error - any exception that was raised in the execution. Check this
+ # first before looking at any other fields.
+ # pg_result - the PG::Result object
+ # duration_nanos - the query duration, in nanoseconds
+ # explain - the query
+ 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"
+ # Set a statement timeout so we can't tie up the server
+ 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
+
+ time_start = Time.now
+
+ # Using MiniSql::InlineParamEncoder directly instead of DB.param_encoder because current implementation of
+ # DB.param_encoder is meant for SQL fragments and not an entire SQL string.
+ sql =
+ MiniSql::InlineParamEncoder.new(ActiveRecord::Base.connection.raw_connection).encode(
+ sql,
+ query_args,
+ )
+
+ result = ActiveRecord::Base.connection.raw_connection.async_exec(sql)
+ result.check # make sure it's done
+ time_end = Time.now
+
+ if opts[:explain]
+ explain =
+ DB
+ .query_hash("EXPLAIN #{query.sql}", query_args)
+ .map { |row| row["QUERY PLAN"] }.join "\n"
+ end
+
+ # All done. Issue a rollback anyways, just in case
+ # see test 'doesn't allow you to modify the database #1'
+ raise ActiveRecord::Rollback
+ end
+ rescue Exception => ex
+ err = ex
+ time_end = Time.now
+ end
+
+ {
+ error: err,
+ pg_result: result,
+ duration_secs: time_end - time_start,
+ explain: explain,
+ params_full: query_args,
+ }
+ end
+
+ def self.extra_data_pluck_fields
+ @extra_data_pluck_fields ||= {
+ user: {
+ class: User,
+ fields: %i[id username uploaded_avatar_id],
+ serializer: BasicUserSerializer,
+ },
+ badge: {
+ class: Badge,
+ fields: %i[id name badge_type_id description icon],
+ include: [:badge_type],
+ serializer: SmallBadgeSerializer,
+ },
+ post: {
+ class: Post,
+ fields: %i[id topic_id post_number cooked user_id],
+ include: [:user],
+ serializer: SmallPostWithExcerptSerializer,
+ },
+ topic: {
+ class: Topic,
+ fields: %i[id title slug posts_count locale],
+ serializer: BasicTopicSerializer,
+ },
+ tag_group: {
+ class: TagGroup,
+ fields: %i[id name],
+ only: %i[id name],
+ },
+ group: {
+ class: Group,
+ ignore: true,
+ },
+ category: {
+ class: Category,
+ ignore: true,
+ },
+ reltime: {
+ ignore: true,
+ },
+ html: {
+ ignore: true,
+ },
+ json: {
+ ignore: true,
+ },
+ }
+ end
+
+ def self.column_regexes
+ @column_regexes ||=
+ extra_data_pluck_fields
+ .map { |key, val| /(#{val[:class].to_s.underscore})_id$/ if val[:class] }
+ .compact
+ end
+
+ def self.add_extra_data(pg_result)
+ needed_classes = {}
+ ret = {}
+ col_map = {}
+ pg_result.fields.each_with_index do |col, idx|
+ rgx = column_regexes.find { |r| r.match col }
+ if rgx
+ cls = (rgx.match col)[1].to_sym
+ needed_classes[cls] ||= []
+ needed_classes[cls] << idx
+ elsif col =~ /^(\w+)\$/
+ cls = $1.to_sym
+ needed_classes[cls] ||= []
+ needed_classes[cls] << idx
+ elsif col =~ /^\w+_url$/
+ col_map[idx] = "url"
+ elsif col =~ /^\w+_payload$/ || col == "payload" || pg_result.ftype(idx) == PG_TYPE_OID_JSON
+ col_map[idx] = "json"
+ end
+ end
+
+ needed_classes.each do |cls, column_nums|
+ next if column_nums.blank?
+ support_info = extra_data_pluck_fields[cls]
+ next unless support_info
+
+ column_nums.each { |col_n| col_map[col_n] = cls }
+
+ if support_info[:ignore]
+ ret[cls] = []
+ next
+ end
+
+ ids = Set.new
+ column_nums.each { |col_n| ids.merge(pg_result.column_values(col_n)) }
+ ids.delete nil
+ ids.map! &:to_i
+
+ object_class = support_info[:class]
+ all_objs = object_class
+ all_objs = all_objs.with_deleted if all_objs.respond_to? :with_deleted
+ all_objs =
+ all_objs
+ .select(support_info[:fields])
+ .where(id: ids.to_a.sort)
+ .includes(support_info[:include])
+ .order(:id)
+
+ opts = { each_serializer: support_info[:serializer] }
+ opts[:only] = support_info[:only] if support_info[:only]
+ ret[cls] = ActiveModel::ArraySerializer.new(all_objs, **opts)
+ end
+ [ret, col_map]
+ end
+
+ def self.sensitive_column_names
+ %w[
+ #_IP_Addresses
+ topic_views.ip_address
+ users.ip_address
+ users.registration_ip_address
+ incoming_links.ip_address
+ topic_link_clicks.ip_address
+ user_histories.ip_address
+ #_Emails
+ email_tokens.email
+ users.email
+ invites.email
+ user_histories.email
+ email_logs.to_address
+ posts.raw_email
+ badge_posts.raw_email
+ #_Secret_Tokens
+ email_tokens.token
+ email_logs.reply_key
+ api_keys.key
+ site_settings.value
+ users.auth_token
+ users.password_hash
+ users.salt
+ #_Authentication_Info
+ user_open_ids.email
+ oauth2_user_infos.uid
+ oauth2_user_infos.email
+ facebook_user_infos.facebook_user_id
+ facebook_user_infos.email
+ twitter_user_infos.twitter_user_id
+ github_user_infos.github_user_id
+ single_sign_on_records.external_email
+ single_sign_on_records.external_id
+ google_user_infos.google_user_id
+ google_user_infos.email
+ ]
+ end
+
+ def self.schema
+ # No need to expire this, because the server processes get restarted on upgrade
+ # refer user to http://www.postgresql.org/docs/9.3/static/datatype.html
+ @schema ||=
+ begin
+ results = DB.query_hash <<~SQL
+ select
+ c.column_name column_name,
+ c.data_type data_type,
+ c.character_maximum_length character_maximum_length,
+ c.is_nullable is_nullable,
+ c.column_default column_default,
+ c.table_name table_name,
+ pgd.description column_desc
+ from INFORMATION_SCHEMA.COLUMNS c
+ inner join pg_catalog.pg_statio_all_tables st on (c.table_schema = st.schemaname and c.table_name = st.relname)
+ left outer join pg_catalog.pg_description pgd on (pgd.objoid = st.relid and pgd.objsubid = c.ordinal_position)
+ where c.table_schema = 'public'
+ ORDER BY c.table_name, c.ordinal_position
+ SQL
+
+ by_table = {}
+ # Massage the results into a nicer form
+ results.each do |hash|
+ full_col_name = "#{hash["table_name"]}.#{hash["column_name"]}"
+
+ if hash["is_nullable"] == "YES"
+ hash["is_nullable"] = true
+ else
+ hash.delete("is_nullable")
+ end
+ clen = hash.delete "character_maximum_length"
+ dt = hash["data_type"]
+ if hash["column_name"] == "id"
+ hash["data_type"] = "serial"
+ hash["primary"] = true
+ elsif dt == "character varying"
+ hash["data_type"] = "varchar(#{clen.to_i})"
+ elsif dt == "timestamp without time zone"
+ hash["data_type"] = "timestamp"
+ elsif dt == "double precision"
+ hash["data_type"] = "double"
+ end
+ default = hash["column_default"]
+ if default.nil? || default =~ /^nextval\(/
+ hash.delete "column_default"
+ elsif default =~ /^'(.*)'::(character varying|text)/
+ hash["column_default"] = $1
+ end
+ hash.delete("column_desc") unless hash["column_desc"]
+
+ hash["sensitive"] = true if sensitive_column_names.include? full_col_name
+ hash["enum"] = enum_info[full_col_name] if enum_info.include? full_col_name
+ if denormalized_columns.include? full_col_name
+ hash["denormal"] = denormalized_columns[full_col_name]
+ end
+ fkey = fkey_info(hash["table_name"], hash["column_name"])
+ hash["fkey_info"] = fkey if fkey
+
+ table_name = hash.delete("table_name")
+ by_table[table_name] ||= []
+ by_table[table_name] << hash
+ end
+
+ # this works for now, but no big loss if the tables aren't quite sorted
+ favored_order = %w[
+ posts
+ topics
+ users
+ categories
+ badges
+ groups
+ notifications
+ post_actions
+ site_settings
+ ]
+ sorted_by_table = {}
+ favored_order.each { |tbl| sorted_by_table[tbl] = by_table[tbl] }
+ by_table.keys.sort.each do |tbl|
+ next if favored_order.include? tbl
+ sorted_by_table[tbl] = by_table[tbl]
+ end
+ sorted_by_table
+ end
+ end
+
+ def self.enums
+ return @enums if @enums
+
+ @enums = {
+ "application_requests.req_type": ApplicationRequest.req_types,
+ "badges.badge_type_id": Enum.new(:gold, :silver, :bronze, start: 1),
+ "bookmarks.auto_delete_preference": Bookmark.auto_delete_preferences,
+ "category_groups.permission_type": CategoryGroup.permission_types,
+ "category_users.notification_level": CategoryUser.notification_levels,
+ "directory_items.period_type": DirectoryItem.period_types,
+ "email_change_requests.change_state": EmailChangeRequest.states,
+ "groups.id": Group::AUTO_GROUPS,
+ "groups.mentionable_level": Group::ALIAS_LEVELS,
+ "groups.messageable_level": Group::ALIAS_LEVELS,
+ "groups.members_visibility_level": Group.visibility_levels,
+ "groups.visibility_level": Group.visibility_levels,
+ "groups.default_notification_level": GroupUser.notification_levels,
+ "group_histories.action": GroupHistory.actions,
+ "group_users.notification_level": GroupUser.notification_levels,
+ "imap_sync_logs.level": ImapSyncLog.levels,
+ "invites.emailed_status": Invite.emailed_status_types,
+ "notifications.notification_type": Notification.types,
+ "polls.results": Poll.results,
+ "polls.status": Poll.statuses,
+ "polls.type": Poll.types,
+ "polls.visibility": Poll.visibilities,
+ "post_action_types.id": PostActionType.types,
+ "post_actions.post_action_type_id": PostActionType.types,
+ "posts.cook_method": Post.cook_methods,
+ "posts.hidden_reason_id": Post.hidden_reasons,
+ "posts.post_type": Post.types,
+ "reviewables.status": Reviewable.statuses,
+ "reviewable_histories.reviewable_history_type": ReviewableHistory.types,
+ "reviewable_scores.status": ReviewableScore.statuses,
+ "screened_emails.action_type": ScreenedEmail.actions,
+ "screened_ip_addresses.action_type": ScreenedIpAddress.actions,
+ "screened_urls.action_type": ScreenedUrl.actions,
+ "search_logs.search_result_type": SearchLog.search_result_types,
+ "search_logs.search_type": SearchLog.search_types,
+ "site_settings.data_type": SiteSetting.types,
+ "skipped_email_logs.reason_type": SkippedEmailLog.reason_types,
+ "tag_group_permissions.permission_type": TagGroupPermission.permission_types,
+ "theme_fields.type_id": ThemeField.types,
+ "theme_settings.data_type": ThemeSetting.types,
+ "topic_timers.status_type": TopicTimer.types,
+ "topic_users.notification_level": TopicUser.notification_levels,
+ "topic_users.notifications_reason_id": TopicUser.notification_reasons,
+ "uploads.verification_status": Upload.verification_statuses,
+ "user_actions.action_type": UserAction.types,
+ "user_histories.action": UserHistory.actions,
+ "user_options.email_previous_replies": UserOption.previous_replies_type,
+ "user_options.like_notification_frequency": UserOption.like_notification_frequency_type,
+ "user_options.text_size_key": UserOption.text_sizes,
+ "user_options.title_count_mode_key": UserOption.title_count_modes,
+ "user_options.email_level": UserOption.email_level_types,
+ "user_options.email_messages_level": UserOption.email_level_types,
+ "user_second_factors.method": UserSecondFactor.methods,
+ "user_security_keys.factor_type": UserSecurityKey.factor_types,
+ "users.trust_level": TrustLevel.levels,
+ "watched_words.action": WatchedWord.actions,
+ "web_hooks.content_type": WebHook.content_types,
+ "web_hooks.last_delivery_status": WebHook.last_delivery_statuses,
+ }.with_indifferent_access
+
+ # QueuedPost is removed in recent Discourse releases
+ @enums["queued_posts.state"] = QueuedPost.states if defined?(QueuedPost)
+
+ @enums
+ end
+
+ def self.enum_info
+ @enum_info ||=
+ begin
+ enum_info = {}
+ enums.map do |key, enum|
+ # https://stackoverflow.com/questions/10874356/reverse-a-hash-in-ruby
+ enum_info[key] = Hash[enum.to_a.map(&:reverse)]
+ end
+ enum_info
+ end
+ end
+
+ def self.fkey_info(table, column)
+ full_name = "#{table}.#{column}"
+
+ if fkey_defaults[column]
+ fkey_defaults[column]
+ elsif column =~ /_by_id$/ || column =~ /_user_id$/
+ :users
+ elsif foreign_keys[full_name]
+ foreign_keys[full_name]
+ else
+ nil
+ end
+ end
+
+ def self.foreign_keys
+ @fkey_columns ||= {
+ "posts.last_editor_id": :users,
+ "posts.version": :"post_revisions.number",
+ "topics.featured_user1_id": :users,
+ "topics.featured_user2_id": :users,
+ "topics.featured_user3_id": :users,
+ "topics.featured_user4_id": :users,
+ "topics.featured_user5_id": :users,
+ "users.seen_notification_id": :notifications,
+ "users.uploaded_avatar_id": :uploads,
+ "users.primary_group_id": :groups,
+ "categories.latest_post_id": :posts,
+ "categories.latest_topic_id": :topics,
+ "categories.parent_category_id": :categories,
+ "badges.badge_grouping_id": :badge_groupings,
+ "post_actions.related_post_id": :posts,
+ "color_scheme_colors.color_scheme_id": :color_schemes,
+ "color_schemes.versioned_id": :color_schemes,
+ "incoming_links.incoming_referer_id": :incoming_referers,
+ "incoming_referers.incoming_domain_id": :incoming_domains,
+ "post_replies.reply_id": :posts,
+ "quoted_posts.quoted_post_id": :posts,
+ "topic_link_clicks.topic_link_id": :topic_links,
+ "topic_link_clicks.link_topic_id": :topics,
+ "topic_link_clicks.link_post_id": :posts,
+ "user_actions.target_topic_id": :topics,
+ "user_actions.target_post_id": :posts,
+ "user_avatars.custom_upload_id": :uploads,
+ "user_avatars.gravatar_upload_id": :uploads,
+ "user_badges.notification_id": :notifications,
+ "user_profiles.card_image_badge_id": :badges,
+ }.with_indifferent_access
+ end
+
+ def self.fkey_defaults
+ @fkey_defaults ||= {
+ user_id: :users,
+ # :*_by_id => :users,
+ # :*_user_id => :users,
+ category_id: :categories,
+ group_id: :groups,
+ post_id: :posts,
+ post_action_id: :post_actions,
+ topic_id: :topics,
+ upload_id: :uploads,
+ }.with_indifferent_access
+ end
+
+ def self.denormalized_columns
+ {
+ "posts.reply_count": :post_replies,
+ "posts.quote_count": :quoted_posts,
+ "posts.incoming_link_count": :topic_links,
+ "posts.word_count": :posts,
+ "posts.avg_time": :post_timings,
+ "posts.reads": :post_timings,
+ "posts.like_score": :post_actions,
+ "posts.like_count": :post_actions,
+ "posts.bookmark_count": :post_actions,
+ "posts.vote_count": :post_actions,
+ "posts.off_topic_count": :post_actions,
+ "posts.notify_moderators_count": :post_actions,
+ "posts.spam_count": :post_actions,
+ "posts.illegal_count": :post_actions,
+ "posts.inappropriate_count": :post_actions,
+ "posts.notify_user_count": :post_actions,
+ "topics.views": :topic_views,
+ "topics.posts_count": :posts,
+ "topics.reply_count": :posts,
+ "topics.incoming_link_count": :topic_links,
+ "topics.moderator_posts_count": :posts,
+ "topics.participant_count": :posts,
+ "topics.word_count": :posts,
+ "topics.last_posted_at": :posts,
+ "topics.last_post_user_idt": :posts,
+ "topics.avg_time": :post_timings,
+ "topics.highest_post_number": :posts,
+ "topics.image_url": :posts,
+ "topics.excerpt": :posts,
+ "topics.like_count": :post_actions,
+ "topics.bookmark_count": :post_actions,
+ "topics.vote_count": :post_actions,
+ "topics.off_topic_count": :post_actions,
+ "topics.notify_moderators_count": :post_actions,
+ "topics.spam_count": :post_actions,
+ "topics.illegal_count": :post_actions,
+ "topics.inappropriate_count": :post_actions,
+ "topics.notify_user_count": :post_actions,
+ "categories.topic_count": :topics,
+ "categories.post_count": :posts,
+ "categories.latest_post_id": :posts,
+ "categories.latest_topic_id": :topics,
+ "categories.description": :posts,
+ "categories.read_restricted": :category_groups,
+ "categories.topics_year": :topics,
+ "categories.topics_month": :topics,
+ "categories.topics_week": :topics,
+ "categories.topics_day": :topics,
+ "categories.posts_year": :posts,
+ "categories.posts_month": :posts,
+ "categories.posts_week": :posts,
+ "categories.posts_day": :posts,
+ "badges.grant_count": :user_badges,
+ "groups.user_count": :group_users,
+ "directory_items.likes_received": :post_actions,
+ "directory_items.likes_given": :post_actions,
+ "directory_items.topics_entered": :user_stats,
+ "directory_items.days_visited": :user_stats,
+ "directory_items.posts_read": :user_stats,
+ "directory_items.topic_count": :topics,
+ "directory_items.post_count": :posts,
+ "post_search_data.search_data": :posts,
+ "top_topics.yearly_posts_count": :posts,
+ "top_topics.monthly_posts_count": :posts,
+ "top_topics.weekly_posts_count": :posts,
+ "top_topics.daily_posts_count": :posts,
+ "top_topics.yearly_views_count": :topic_views,
+ "top_topics.monthly_views_count": :topic_views,
+ "top_topics.weekly_views_count": :topic_views,
+ "top_topics.daily_views_count": :topic_views,
+ "top_topics.yearly_likes_count": :post_actions,
+ "top_topics.monthly_likes_count": :post_actions,
+ "top_topics.weekly_likes_count": :post_actions,
+ "top_topics.daily_likes_count": :post_actions,
+ "top_topics.yearly_op_likes_count": :post_actions,
+ "top_topics.monthly_op_likes_count": :post_actions,
+ "top_topics.weekly_op_likes_count": :post_actions,
+ "top_topics.daily_op_likes_count": :post_actions,
+ "top_topics.all_score": :posts,
+ "top_topics.yearly_score": :posts,
+ "top_topics.monthly_score": :posts,
+ "top_topics.weekly_score": :posts,
+ "top_topics.daily_score": :posts,
+ "topic_links.clicks": :topic_link_clicks,
+ "topic_search_data.search_data": :topics,
+ "topic_users.liked": :post_actions,
+ "topic_users.bookmarked": :post_actions,
+ "user_stats.posts_read_count": :post_timings,
+ "user_stats.topic_reply_count": :posts,
+ "user_stats.first_post_created_at": :posts,
+ "user_stats.post_count": :posts,
+ "user_stats.topic_count": :topics,
+ "user_stats.likes_given": :post_actions,
+ "user_stats.likes_received": :post_actions,
+ "user_search_data.search_data": :user_profiles,
+ "users.last_posted_at": :posts,
+ "users.previous_visit_at": :user_visits,
+ }.with_indifferent_access
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/engine.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/engine.rb
new file mode 100644
index 00000000000..0b423308efb
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/engine.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class Engine < ::Rails::Engine
+ engine_name PLUGIN_NAME
+ isolate_namespace DiscourseDataExplorer
+ config.autoload_paths << File.join(config.root, "lib")
+ scheduled_job_dir = "#{config.root}/app/jobs/scheduled"
+ config.to_prepare { Rails.autoloaders.main.eager_load_dir(scheduled_job_dir) }
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb
new file mode 100644
index 00000000000..961962531c4
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/parameter.rb
@@ -0,0 +1,268 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class Parameter
+ attr_accessor :identifier, :type, :default, :nullable
+
+ def initialize(identifier, type, default, nullable, validate: true)
+ unless identifier
+ raise ValidationError.new("Parameter declaration error - identifier is missing")
+ end
+
+ raise ValidationError.new("Parameter declaration error - type is missing") unless type
+
+ # process aliases
+ type = type.to_sym
+
+ type = Parameter.type_aliases[type] if Parameter.type_aliases[type]
+
+ unless Parameter.types[type]
+ raise ValidationError.new("Parameter declaration error - unknown type #{type}")
+ end
+
+ @identifier = identifier
+ @type = type
+ @default = default
+ @nullable = nullable
+ begin
+ cast_to_ruby default if default.present? && validate
+ rescue ValidationError
+ raise ValidationError.new(
+ "Parameter declaration error - the default value is not a valid #{type}",
+ )
+ end
+ end
+
+ def to_hash
+ { identifier: @identifier, type: @type, default: @default, nullable: @nullable }
+ end
+
+ def self.types
+ @types ||=
+ Enum.new(
+ # Normal types
+ :int,
+ :bigint,
+ :boolean,
+ :string,
+ :date,
+ :time,
+ :datetime,
+ :double,
+ # Selection help
+ :user_id,
+ :post_id,
+ :topic_id,
+ :category_id,
+ :group_id,
+ :badge_id,
+ # Arrays
+ :int_list,
+ :string_list,
+ :user_list,
+ :group_list,
+ )
+ end
+
+ def self.type_aliases
+ @type_aliases ||= { integer: :int, text: :string, timestamp: :datetime }
+ end
+
+ def self.create_from_sql(sql, opts = {})
+ in_params = false
+ ret_params = []
+ sql.lines.find do |line|
+ line.chomp!
+
+ if in_params
+ # -- (ident) :(ident) (= (ident))?
+
+ if line =~ /^\s*--\s*([a-zA-Z_ ]+)\s*:([a-z_]+)\s*(?:=\s+(.*)\s*)?$/
+ type = $1
+ ident = $2
+ default = $3
+ nullable = false
+ if type =~ /^(null)?(.*?)(null)?$/i
+ nullable = true if $1 || $3
+ type = $2
+ end
+ type = type.strip
+
+ begin
+ ret_params << Parameter.new(ident, type, default, nullable, validate: opts[:strict])
+ rescue StandardError
+ raise if opts[:strict]
+ end
+
+ false
+ elsif line =~ /^\s+$/
+ false
+ else
+ true
+ end
+ else
+ in_params = true if line =~ /^\s*--\s*\[params\]\s*$/
+ false
+ end
+ end
+ ret_params
+ end
+
+ def cast_to_ruby(string)
+ string = @default unless string
+
+ if string.blank?
+ if @nullable
+ return nil
+ else
+ raise ValidationError.new("Missing parameter #{identifier} of type #{type}")
+ end
+ end
+ return nil if string.downcase == "#null"
+
+ value = nil
+
+ case @type
+ when :int
+ invalid_format string, "Not an integer" unless string =~ /^-?\d+$/
+ value = string.to_i
+ invalid_format string, "Too large" unless Integer === value
+ when :bigint
+ invalid_format string, "Not an integer" unless string =~ /^-?\d+$/
+ value = string.to_i
+ when :boolean
+ value = !!(string =~ /t|true|y|yes|1/i)
+ when :string
+ value = string
+ when :time
+ begin
+ value = Time.parse string
+ rescue ArgumentError => e
+ invalid_format string, e.message
+ end
+ when :date
+ begin
+ value = Date.parse string
+ rescue ArgumentError => e
+ invalid_format string, e.message
+ end
+ when :datetime
+ begin
+ value = DateTime.parse string
+ rescue ArgumentError => e
+ invalid_format string, e.message
+ end
+ when :double
+ if string.strip =~ /^-?\d*\.?\d+$/
+ value = Float(string)
+ elsif string =~ /^(-?)Inf(inity)?$/i
+ if $1.present?
+ value = -Float::INFINITY
+ else
+ value = Float::INFINITY
+ end
+ elsif string =~ /^(-?)NaN$/i
+ if $1.present?
+ value = -Float::NAN
+ else
+ value = Float::NAN
+ end
+ else
+ invalid_format string
+ end
+ when :category_id
+ if string =~ %r{(.*)/(.*)}
+ parent_name = $1
+ child_name = $2
+ parent = Category.query_parent_category(parent_name)
+ invalid_format string, "Could not find category named #{parent_name}" unless parent
+ object = Category.query_category(child_name, parent)
+ if object.blank?
+ invalid_format string,
+ "Could not find subcategory of #{parent_name} named #{child_name}"
+ end
+ else
+ object =
+ Category.where(id: string.to_i).first || Category.where(slug: string).first ||
+ Category.where(name: string).first
+ invalid_format string, "Could not find category named #{string}" if object.blank?
+ end
+
+ value = object.id
+ when :user_id, :post_id, :topic_id, :group_id, :badge_id
+ if string.gsub(/[ _]/, "") =~ /^-?\d+$/
+ klass_name = (/^(.*)_id$/.match(type.to_s)[1].classify.to_sym)
+ begin
+ finder =
+ if type == :post_id || type == :topic_id
+ Object.const_get(klass_name).with_deleted
+ else
+ Object.const_get(klass_name)
+ end
+ object = finder.find(string.gsub(/[ _]/, "").to_i)
+ value = object.id
+ rescue ActiveRecord::RecordNotFound
+ invalid_format string, "The specified #{klass_name} was not found"
+ end
+ elsif type == :user_id
+ object = User.find_by_username_or_email(string)
+ invalid_format string, "The user named #{string} was not found" if object.blank?
+ value = object.id
+ elsif type == :post_id
+ if string =~ %r{/t/[^/]+/(\d+)(\?u=.*)?$}
+ object = Post.with_deleted.find_by(topic_id: $1, post_number: 1)
+ invalid_format string, "The first post for topic:#{$1} was not found" if object.blank?
+ value = object.id
+ elsif string =~ %r{(\d+)/(\d+)(\?u=.*)?$}
+ object = Post.with_deleted.find_by(topic_id: $1, post_number: $2)
+ if object.blank?
+ invalid_format string, "The post at topic:#{$1} post_number:#{$2} was not found"
+ end
+ value = object.id
+ end
+ elsif type == :topic_id
+ if string =~ %r{/t/[^/]+/(\d+)}
+ begin
+ object = Topic.with_deleted.find($1)
+ value = object.id
+ rescue ActiveRecord::RecordNotFound
+ invalid_format string, "The topic with id #{$1} was not found"
+ end
+ end
+ elsif type == :group_id
+ object = Group.where(name: string).first
+ invalid_format string, "The group named #{string} was not found" if object.blank?
+ value = object.id
+ else
+ invalid_format string
+ end
+ when :int_list
+ value = string.split(",").map { |s| s.downcase == "#null" ? nil : s.to_i }
+ invalid_format string, "can't be empty" if value.length == 0
+ when :string_list
+ value = string.split(",").map { |s| s.downcase == "#null" ? nil : s }
+ invalid_format string, "can't be empty" if value.length == 0
+ when :user_list
+ value = string.split(",").map { |s| User.find_by_username_or_email(s).id }
+ invalid_format string, "can't be empty" if value.length == 0
+ when :group_list
+ value = string.split(",").map { |s| Group.where(name: s).first.name }
+ invalid_format string, "The group with id #{string} was not found" if value.length == 0
+ else
+ raise TypeError.new("unknown parameter type??? should not get here")
+ end
+
+ value
+ end
+
+ private
+
+ def invalid_format(string, msg = nil)
+ if msg
+ raise ValidationError.new("'#{string}' is an invalid #{type} - #{msg}")
+ else
+ raise ValidationError.new("'#{string}' is an invalid value for #{type}")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rb
new file mode 100644
index 00000000000..2849aa65d0f
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rb
@@ -0,0 +1,596 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class Queries
+ def self.default
+ # WARNING: Edit the query hash carefully
+ # For each query, add id, name and description here and add sql below
+ # Feel free to add new queries at the bottom of the hash in numerical order
+ # If any query has been run on an instance, it is then saved in the local db
+ # Locally stored queries are updated from the below data only when they are run again
+ # eg. If you update a query with id=-1 in this file and the query has been run on a site,
+ # you must run the query with id=-1 on the site again to update these changes in the site db
+
+ queries = {
+ "most-common-likers": {
+ id: -1,
+ name: "Most Common Likers",
+ description: "Which users like particular other users the most?",
+ },
+ "most-messages": {
+ id: -2,
+ name: "Who has been sending the most messages in the last week?",
+ description: "tracking down suspicious PM activity",
+ },
+ "edited-post-spam": {
+ id: -3,
+ name: "Last 500 posts that were edited by TL0/TL1 users",
+ description: "fighting human-driven copy-paste spam",
+ },
+ "new-topics": {
+ id: -4,
+ name: "New Topics by Category",
+ description:
+ "Lists all new topics ordered by category and creation_date. The query accepts a ‘months_ago’ parameter. It defaults to 0 to give you the stats for the current month.",
+ },
+ "active-topics": {
+ id: -5,
+ name: "Top 100 Active Topics",
+ description:
+ "based on the number of replies, it accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ },
+ "top-likers": {
+ id: -6,
+ name: "Top 100 Likers",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ },
+ "quality-users": {
+ id: -7,
+ name: "Top 50 Quality Users",
+ description:
+ "based on post score calculated using reply count, likes, incoming links, bookmarks, time spent and read count.",
+ },
+ "user-participation": {
+ id: -8,
+ name: "User Participation Statistics",
+ description: "Detailed statistics for the most active users.",
+ },
+ "largest-uploads": {
+ id: -9,
+ name: "Top 50 Largest Uploads",
+ description: "sorted by file size.",
+ },
+ "inactive-users": {
+ id: -10,
+ name: "Inactive Users with no posts",
+ description: "analyze pre-Discourse signups.",
+ },
+ "active-lurkers": {
+ id: -11,
+ name: "Most Active Lurkers",
+ description:
+ "active users without posts and excessive read times, it accepts a post_read_count parameter that sets the threshold for posts read.",
+ },
+ "topic-user-notification-level": {
+ id: -12,
+ name: "List of topics a user is watching/tracking/muted",
+ description:
+ "The query requires a ‘notification_level’ parameter. Use 0 for muted, 1 for regular, 2 for tracked and 3 for watched topics.",
+ },
+ "assigned-topics-report": {
+ id: -13,
+ name: "List of assigned topics by user",
+ description: "This report requires the assign plugin, it will find all assigned topics",
+ },
+ "group-members-reply-count": {
+ id: -14,
+ name: "Group Members Reply Count",
+ description:
+ "Number of replies by members of a group over a given time period. Requires 'group_name', 'start_date', and 'end_date' parameters. Dates need to be in the form 'yyyy-mm-dd'. Accepts an 'include_pms' parameter.",
+ },
+ "total-assigned-topics-report": {
+ id: -15,
+ name: "Total topics assigned per user",
+ description: "Count of assigned topis per user linking to assign list",
+ },
+ "poll-results": {
+ id: -16,
+ name: "Poll results report",
+ description:
+ "Details of a poll result, including details about each vote and voter, useful for analyzing results in external software.",
+ },
+ "top-tags-per-year": {
+ id: -17,
+ name: "Top tags per year",
+ description: "List the top tags per year.",
+ },
+ number_of_replies_by_category: {
+ id: -18,
+ name: "Number of replies by category",
+ description: "List the number of replies by category.",
+ },
+ "poll-results-ranked-choice": {
+ id: -19,
+ name: "Poll results report (for Ranked Choice polls)",
+ description:
+ "Details of a Ranked Choice poll result, including details about each vote and voter inc. rank, useful for analyzing results in external software.",
+ },
+ }.with_indifferent_access
+
+ queries["most-common-likers"]["sql"] = <<~SQL
+ WITH pairs AS (
+ SELECT p.user_id liked, pa.user_id liker
+ FROM post_actions pa
+ LEFT JOIN posts p ON p.id = pa.post_id
+ WHERE post_action_type_id = 2
+ )
+ SELECT liker liker_user_id, liked liked_user_id, count(*)
+ FROM pairs
+ GROUP BY liked, liker
+ ORDER BY count DESC
+ SQL
+
+ queries["most-messages"]["sql"] = <<~SQL
+ SELECT user_id, count(*) AS message_count
+ FROM topics
+ WHERE archetype = 'private_message' AND subtype = 'user_to_user'
+ AND age(created_at) < interval '7 days'
+ GROUP BY user_id
+ ORDER BY message_count DESC
+ SQL
+
+ queries["edited-post-spam"]["sql"] = <<~SQL
+ SELECT
+ p.id AS post_id,
+ topic_id
+ FROM posts p
+ JOIN users u
+ ON u.id = p.user_id
+ JOIN topics t
+ ON t.id = p.topic_id
+ WHERE p.last_editor_id = p.user_id
+ AND p.self_edits > 0
+ AND (u.trust_level = 0 OR u.trust_level = 1)
+ AND p.deleted_at IS NULL
+ AND t.deleted_at IS NULL
+ AND t.archetype = 'regular'
+ ORDER BY p.updated_at DESC
+ LIMIT 500
+ SQL
+
+ queries["new-topics"]["sql"] = <<~SQL
+ -- [params]
+ -- int :months_ago = 1
+
+ WITH query_period as (
+ SELECT
+ date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,
+ date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end
+ )
+
+ SELECT
+ t.id as topic_id,
+ t.category_id
+ FROM topics t
+ RIGHT JOIN query_period qp
+ ON t.created_at >= qp.period_start
+ AND t.created_at <= qp.period_end
+ WHERE t.user_id > 0
+ AND t.category_id IS NOT NULL
+ ORDER BY t.category_id, t.created_at DESC
+ SQL
+
+ queries["active-topics"]["sql"] = <<~SQL
+ -- [params]
+ -- int :months_ago = 1
+
+ WITH query_period AS
+ (SELECT date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' AS period_start,
+ date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' AS period_end)
+ SELECT t.id AS topic_id,
+ t.category_id,
+ COUNT(p.id) AS reply_count
+ FROM topics t
+ JOIN posts p ON t.id = p.topic_id
+ JOIN query_period qp ON p.created_at >= qp.period_start
+ AND p.created_at <= qp.period_end
+ WHERE t.archetype = 'regular'
+ AND t.user_id > 0
+ GROUP BY t.id
+ ORDER BY COUNT(p.id) DESC, t.score DESC
+ LIMIT 100
+ SQL
+
+ queries["top-likers"]["sql"] = <<~SQL
+ -- [params]
+ -- int :months_ago = 1
+
+ WITH query_period AS (
+ SELECT
+ date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,
+ date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end
+ )
+
+ SELECT
+ ua.user_id,
+ count(1) AS like_count
+ FROM user_actions ua
+ INNER JOIN query_period qp
+ ON ua.created_at >= qp.period_start
+ AND ua.created_at <= qp.period_end
+ WHERE ua.action_type = 1
+ GROUP BY ua.user_id
+ ORDER BY like_count DESC
+ LIMIT 100
+ SQL
+
+ queries["quality-users"]["sql"] = <<~SQL
+ SELECT sum(p.score) / count(p) AS "average score per post",
+ count(p.id) AS post_count,
+ p.user_id
+ FROM posts p
+ JOIN users u ON u.id = p.user_id
+ WHERE p.created_at >= CURRENT_DATE - INTERVAL '6 month'
+ AND NOT u.admin
+ AND u.active
+ GROUP BY user_id,
+ u.views
+ HAVING count(p.id) > 50
+ ORDER BY sum(p.score) / count(p) DESC
+ LIMIT 50
+ SQL
+
+ queries["user-participation"]["sql"] = <<~SQL
+ -- [params]
+ -- int :from_days_ago = 0
+ -- int :duration_days = 30
+ WITH t AS (
+ SELECT CURRENT_TIMESTAMP - ((:from_days_ago + :duration_days) * (INTERVAL '1 days')) AS START,
+ CURRENT_TIMESTAMP - (:from_days_ago * (INTERVAL '1 days')) AS END
+ ),
+ pr AS (
+ SELECT user_id, COUNT(1) AS visits,
+ SUM(posts_read) AS posts_read
+ FROM user_visits, t
+ WHERE posts_read > 0
+ AND visited_at > t.START
+ AND visited_at < t.
+ END
+ GROUP BY
+ user_id
+ ),
+ pc AS (
+ SELECT user_id, COUNT(1) AS posts_created
+ FROM posts, t
+ WHERE
+ created_at > t.START
+ AND created_at < t.
+ END
+ GROUP BY
+ user_id
+ ),
+ ttopics AS (
+ SELECT user_id, posts_count
+ FROM topics, t
+ WHERE created_at > t.START
+ AND created_at < t.
+ END
+ ),
+ tc AS (
+ SELECT user_id, COUNT(1) AS topics_created
+ FROM ttopics
+ GROUP BY user_id
+ ),
+ twr AS (
+ SELECT user_id, COUNT(1) AS topics_with_replies
+ FROM ttopics
+ WHERE posts_count > 1
+ GROUP BY user_id
+ ),
+ tv AS (
+ SELECT user_id,
+ COUNT(DISTINCT(topic_id)) AS topics_viewed
+ FROM topic_views, t
+ WHERE viewed_at > t.START
+ AND viewed_at < t.
+ END
+ GROUP BY user_id
+ ),
+ likes AS (
+ SELECT post_actions.user_id AS given_by_user_id,
+ posts.user_id AS received_by_user_id
+ FROM t,
+ post_actions
+ LEFT JOIN
+ posts
+ ON post_actions.post_id = posts.id
+ WHERE
+ post_actions.created_at > t.START
+ AND post_actions.created_at < t.
+ END
+ AND post_action_type_id = 2
+ ),
+ lg AS (
+ SELECT given_by_user_id AS user_id,
+ COUNT(1) AS likes_given
+ FROM likes
+ GROUP BY user_id
+ ),
+ lr AS (
+ SELECT received_by_user_id AS user_id,
+ COUNT(1) AS likes_received
+ FROM likes
+ GROUP BY user_id
+ ),
+ e AS (
+ SELECT email, user_id
+ FROM user_emails u
+ WHERE u.PRIMARY = TRUE
+ )
+ SELECT
+ pr.user_id,
+ username,
+ name,
+ email,
+ visits,
+ COALESCE(topics_viewed, 0) AS topics_viewed,
+ COALESCE(posts_read, 0) AS posts_read,
+ COALESCE(posts_created, 0) AS posts_created,
+ COALESCE(topics_created, 0) AS topics_created,
+ COALESCE(topics_with_replies, 0) AS topics_with_replies,
+ COALESCE(likes_given, 0) AS likes_given,
+ COALESCE(likes_received, 0) AS likes_received
+ FROM pr
+ LEFT JOIN tv USING (user_id)
+ LEFT JOIN pc USING (user_id)
+ LEFT JOIN tc USING (user_id)
+ LEFT JOIN twr USING (user_id)
+ LEFT JOIN lg USING (user_id)
+ LEFT JOIN lr USING (user_id)
+ LEFT JOIN e USING (user_id)
+ LEFT JOIN users ON pr.user_id = users.id
+ ORDER BY
+ visits DESC,
+ posts_read DESC,
+ posts_created DESC
+ SQL
+
+ queries["largest-uploads"]["sql"] = <<~SQL
+ SELECT posts.id AS post_id,
+ uploads.original_filename,
+ ROUND(uploads.filesize / 1000000.0, 2) AS size_in_mb,
+ uploads.extension,
+ uploads.created_at,
+ uploads.url
+ FROM upload_references
+ JOIN uploads ON uploads.id = upload_references.upload_id
+ JOIN posts ON posts.id = upload_references.target_id AND upload_references.target_type = 'Post'
+ ORDER BY uploads.filesize DESC
+ LIMIT 50
+ SQL
+
+ queries["inactive-users"]["sql"] = <<~SQL
+ SELECT
+ u.id,
+ u.username_lower AS "username",
+ u.created_at,
+ u.last_seen_at
+ FROM users u
+ WHERE u.active = false
+ ORDER BY u.id
+ SQL
+
+ queries["active-lurkers"]["sql"] = <<~SQL
+ -- [params]
+ -- int :post_read_count = 100
+ WITH posts_by_user AS (
+ SELECT COUNT(*) AS posts, user_id
+ FROM posts
+ GROUP BY user_id
+ ), posts_read_by_user AS (
+ SELECT SUM(posts_read) AS posts_read, user_id
+ FROM user_visits
+ GROUP BY user_id
+ )
+ SELECT
+ u.id,
+ u.username_lower AS "username",
+ u.created_at,
+ u.last_seen_at,
+ COALESCE(pbu.posts, 0) AS "posts_created",
+ COALESCE(prbu.posts_read, 0) AS "posts_read"
+ FROM users u
+ LEFT JOIN posts_by_user pbu ON pbu.user_id = u.id
+ LEFT JOIN posts_read_by_user prbu ON prbu.user_id = u.id
+ WHERE u.active = true
+ AND posts IS NULL
+ AND posts_read > :post_read_count
+ ORDER BY u.id
+ SQL
+
+ queries["topic-user-notification-level"]["sql"] = <<~SQL
+ -- [params]
+ -- null int :user
+ -- null int :notification_level
+
+ SELECT t.category_id AS category_id, t.id AS topic_id, tu.last_visited_at AS topic_last_visited_at
+ FROM topics t
+ JOIN topic_users tu ON tu.topic_id = t.id AND tu.user_id = :user AND tu.notification_level = :notification_level
+ ORDER BY tu.last_visited_at DESC
+ SQL
+
+ queries["assigned-topics-report"]["sql"] = <<~SQL
+ SELECT a.assigned_to_id user_id, a.topic_id
+ FROM assignments a
+ JOIN topics t on t.id = a.topic_id
+ JOIN users u on u.id = a.assigned_to_id
+ WHERE a.assigned_to_type = 'User'
+ AND t.deleted_at IS NULL
+ ORDER BY username, topic_id
+ SQL
+
+ queries["group-members-reply-count"]["sql"] = <<~SQL
+ -- [params]
+ -- date :start_date
+ -- date :end_date
+ -- string :group_name
+ -- boolean :include_pms = false
+
+ WITH target_users AS (
+ SELECT
+ u.id AS user_id
+ FROM users u
+ JOIN group_users gu
+ ON gu.user_id = u.id
+ JOIN groups g
+ ON g.id = gu.group_id
+ WHERE g.name = :group_name
+ AND gu.created_at::date <= :end_date
+ ),
+ target_posts AS (
+ SELECT
+ p.id,
+ p.user_id
+ FROM posts p
+ JOIN topics t
+ ON t.id = p.topic_id
+ WHERE CASE WHEN :include_pms THEN true ELSE t.archetype = 'regular' END
+ AND t.deleted_at IS NULL
+ AND p.deleted_at IS NULL
+ AND p.created_at::date >= :start_date
+ AND p.created_at::date <= :end_date
+ AND p.post_number > 1
+ )
+
+ SELECT
+ tu.user_id,
+ COALESCE(COUNT(tp.id), 0) AS reply_count
+ FROM target_users tu
+ LEFT OUTER JOIN target_posts tp
+ ON tp.user_id = tu.user_id
+ GROUP BY tu.user_id
+ ORDER BY reply_count DESC, tu.user_id
+ SQL
+
+ queries["total-assigned-topics-report"]["sql"] = <<~SQL
+ SELECT a.assigned_to_id AS user_id,
+ count(*)::varchar || ',/u/' || username_lower || '/activity/assigned' assigned_url
+ FROM assignments a
+ JOIN topics t on t.id = a.topic_id
+ JOIN users u on u.id = a.assigned_to_id
+ WHERE a.assigned_to_type = 'User'
+ AND t.deleted_at IS NULL
+ GROUP BY a.assigned_to_id, username_lower
+ ORDER BY count(*) DESC, username_lower
+ SQL
+
+ queries["poll-results"]["sql"] = <<~SQL
+ -- [params]
+ -- string :poll_name
+ -- int :post_id
+
+ SELECT
+ poll_votes.updated_at AS vote_time,
+ poll_votes.poll_option_id AS vote_option,
+ users.id AS user_id,
+ users.username,
+ users.name,
+ users.trust_level,
+ poll_options.html AS vote_option_full
+ FROM
+ poll_votes
+ INNER JOIN
+ polls ON polls.id = poll_votes.poll_id
+ INNER JOIN
+ users ON users.id = poll_votes.user_id
+ INNER JOIN
+ poll_options ON poll_votes.poll_id = poll_options.poll_id AND poll_votes.poll_option_id = poll_options.id
+ WHERE
+ polls.name = :poll_name AND
+ polls.post_id = :post_id
+ SQL
+
+ queries["poll-results-ranked-choice"]["sql"] = <<~SQL
+ -- [params]
+ -- string :poll_name
+ -- int :post_id
+
+ SELECT
+ poll_votes.updated_at AS vote_time,
+ poll_votes.poll_option_id AS vote_option,
+ poll_votes.rank AS vote_rank,
+ users.id AS user_id,
+ users.username,
+ users.name,
+ users.trust_level,
+ poll_options.html AS vote_option_full
+ FROM
+ poll_votes
+ INNER JOIN
+ polls ON polls.id = poll_votes.poll_id
+ INNER JOIN
+ users ON users.id = poll_votes.user_id
+ INNER JOIN
+ poll_options ON poll_votes.poll_id = poll_options.poll_id AND poll_votes.poll_option_id = poll_options.id
+ WHERE
+ polls.name = :poll_name AND
+ polls.post_id = :post_id
+ SQL
+
+ queries["top-tags-per-year"]["sql"] = <<~SQL
+ -- [params]
+ -- integer :rank_max = 5
+
+ WITH data AS (SELECT
+ tag_id,
+ EXTRACT(YEAR FROM created_at) AS year
+ FROM topic_tags)
+
+ SELECT year, rank, name, qt FROM (
+ SELECT
+ tag_id,
+ COUNT(tag_id) AS qt,
+ year,
+ rank() OVER (PARTITION BY year ORDER BY COUNT(tag_id) DESC) AS rank
+ FROM
+ data
+ GROUP BY year, tag_id) as rnk
+ INNER JOIN tags ON tags.id = rnk.tag_id
+ WHERE rank <= :rank_max
+ ORDER BY year DESC, qt DESC
+ SQL
+
+ queries["number_of_replies_by_category"]["sql"] = <<~SQL
+ -- [params]
+ -- boolean :enable_null_category = false
+
+ WITH post AS (SELECT
+ id AS post_id,
+ topic_id,
+ EXTRACT(YEAR FROM created_at) AS year
+ FROM posts
+ WHERE post_type = 1
+ AND deleted_at ISNULL
+ AND post_number != 1)
+
+ SELECT
+ p.year,
+ t.category_id AS id,
+ c.name category,
+ COUNT(p.post_id) AS qt
+ FROM post p
+ INNER JOIN topics t ON t.id = p.topic_id
+ LEFT JOIN categories c ON c.id = t.category_id
+ WHERE t.deleted_at ISNULL
+ AND (:enable_null_category = true OR t.category_id NOTNULL)
+ GROUP BY t.category_id, c.name, p.year
+ ORDER BY p.year DESC, qt DESC
+ SQL
+
+ # convert query ids from "mostcommonlikers" to "-1", "mostmessages" to "-2" etc.
+ queries.transform_keys!.with_index { |key, idx| "-#{idx + 1}" }
+ queries
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_group_bookmarkable.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_group_bookmarkable.rb
new file mode 100644
index 00000000000..b63d86f3efa
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_group_bookmarkable.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class QueryGroupBookmarkable < BaseBookmarkable
+ def self.model
+ QueryGroup
+ end
+
+ def self.serializer
+ QueryGroupBookmarkSerializer
+ end
+
+ def self.preload_associations
+ %i[data_explorer_queries groups]
+ end
+
+ def self.list_query(user, guardian)
+ group_ids = []
+ if !user.admin?
+ group_ids = user.visible_groups.pluck(:id)
+ return if group_ids.empty?
+ end
+
+ query =
+ user
+ .bookmarks_of_type("DiscourseDataExplorer::QueryGroup")
+ .joins(
+ "INNER JOIN data_explorer_query_groups ON data_explorer_query_groups.id = bookmarks.bookmarkable_id",
+ )
+ .joins(
+ "LEFT JOIN data_explorer_queries ON data_explorer_queries.id = data_explorer_query_groups.query_id",
+ )
+ query = query.where("data_explorer_query_groups.group_id IN (?)", group_ids) if !user.admin?
+ query
+ end
+
+ # Searchable only by data_explorer_queries name
+ def self.search_query(bookmarks, query, ts_query, &bookmarkable_search)
+ bookmarkable_search.call(bookmarks, "data_explorer_queries.name ILIKE :q")
+ end
+
+ def self.reminder_handler(bookmark)
+ send_reminder_notification(
+ bookmark,
+ data: {
+ title: bookmark.bookmarkable.query.name,
+ bookmarkable_url:
+ "/g/#{bookmark.bookmarkable.group.name}/reports/#{bookmark.bookmarkable.query.id}",
+ },
+ )
+ end
+
+ def self.reminder_conditions(bookmark)
+ bookmark.bookmarkable.present?
+ end
+
+ def self.can_see?(guardian, bookmark)
+ can_see_bookmarkable?(guardian, bookmark.bookmarkable)
+ end
+
+ def self.can_see_bookmarkable?(guardian, bookmarkable)
+ return false if !bookmarkable.group
+ guardian.user_is_a_member_of_group?(bookmarkable.group)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/report_generator.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/report_generator.rb
new file mode 100644
index 00000000000..a518b1422d4
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/report_generator.rb
@@ -0,0 +1,162 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class ReportGenerator
+ def self.generate(query_id, query_params, recipients, opts = {})
+ query = DiscourseDataExplorer::Query.find(query_id)
+ return [] if !query || recipients.empty?
+
+ recipients =
+ filter_recipients_by_query_access(
+ recipients,
+ query,
+ users_from_group: opts[:users_from_group],
+ )
+ 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?
+ 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?
+ table =
+ ResultToMarkdown.convert(result[:pg_result], render_url_columns: opts[:render_url_columns])
+
+ 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(
+ "data_explorer.report_generator.private_message.title",
+ query_name: query.name,
+ )
+ pm[pm_type] = Array(name)
+ pm["raw"] = I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: name,
+ query_name: query.name,
+ table: table,
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ )
+ if upload
+ pm["raw"] << "\n\n" +
+ I18n.t(
+ "data_explorer.report_generator.upload_appendix",
+ filename: upload.original_filename,
+ short_url: upload.short_url,
+ )
+ end
+ pms << pm
+ end
+ pms
+ end
+
+ def self.build_report_post(query, table = "", attach_csv: false, result: nil)
+ upload = create_csv_upload(query, result) if attach_csv
+
+ post = {}
+ post["raw"] = I18n.t(
+ "data_explorer.report_generator.post.body",
+ recipient_name: name,
+ query_name: query.name,
+ table: table,
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ )
+
+ if upload
+ post["raw"] << "\n\n" +
+ I18n.t(
+ "data_explorer.report_generator.upload_appendix",
+ filename: upload.original_filename,
+ short_url: upload.short_url,
+ )
+ end
+
+ post
+ end
+
+ def self.create_csv_upload(query, result)
+ tmp_filename =
+ "#{query.slug}@#{Slug.for(Discourse.current_hostname, "discourse")}-#{Date.today}.dcqresult.csv"
+ tmp = Tempfile.new(tmp_filename)
+ tmp.write(ResultFormatConverter.convert(:csv, result))
+ tmp.rewind
+ UploadCreator.new(tmp, tmp_filename, type: "csv_export").create_for(Discourse.system_user.id)
+ end
+
+ def self.filter_recipients_by_query_access(recipients, query, users_from_group: false)
+ users = User.where(username: recipients)
+ groups = Group.where(name: recipients)
+ emails = recipients - users.pluck(:username) - groups.pluck(:name)
+ result = []
+
+ query_group_ids = [Group::AUTO_GROUPS[:admins]].concat(query.groups.pluck(:group_id)).uniq
+
+ if users_from_group
+ result.concat(
+ User
+ .joins(:group_users)
+ .where(group_users: { group_id: groups.ids })
+ .where(
+ "users.admin OR EXISTS (
+ SELECT 1 FROM group_users gu
+ WHERE gu.user_id = users.id
+ AND gu.group_id IN (?)
+ )",
+ query_group_ids,
+ )
+ .distinct
+ .pluck(:username)
+ .map { |username| [username, "username"] },
+ )
+ else
+ groups.each do |group|
+ result << [group.name, "group_name"] if query_group_ids.include?(group.id)
+ end
+ end
+
+ users.each do |user|
+ result << [user.username, "username"] if Guardian.new(user).user_can_access_query?(query)
+ end
+
+ emails.each { |email| result << [email, "email"] if Email.is_valid?(email) }
+
+ result
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb
new file mode 100644
index 00000000000..258f07fbabd
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+module ::DiscourseDataExplorer
+ class ResultFormatConverter
+ def self.convert(file_type, result, opts = {})
+ self.new(result, opts).send("to_#{file_type}")
+ end
+
+ def initialize(result, opts)
+ @result = result
+ @opts = opts
+ end
+
+ private
+
+ attr_reader :result
+ attr_reader :opts
+
+ def pg_result
+ @pg_result ||= @result[:pg_result]
+ end
+
+ def cols
+ @cols ||= pg_result.fields
+ end
+
+ def to_csv
+ require "csv"
+ CSV.generate do |csv|
+ csv << cols
+ pg_result.values.each { |row| csv << row }
+ end
+ end
+
+ def to_json
+ json = {
+ success: true,
+ errors: [],
+ duration: (result[:duration_secs].to_f * 1000).round(1),
+ result_count: pg_result.values.length || 0,
+ params: opts[:query_params],
+ columns: cols,
+ default_limit: SiteSetting.data_explorer_query_result_limit,
+ }
+ json[:explain] = result[:explain] if opts[:explain]
+
+ if !opts[:download]
+ relations, colrender = DataExplorer.add_extra_data(pg_result)
+ json[:relations] = relations
+ json[:colrender] = colrender
+ end
+
+ json[:rows] = pg_result.values
+
+ json
+ end
+
+ #TODO: we can move ResultToMarkdown here
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_to_markdown.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_to_markdown.rb
new file mode 100644
index 00000000000..bc4acd778d5
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_to_markdown.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+include HasSanitizableFields
+
+module ::DiscourseDataExplorer
+ class ResultToMarkdown
+ def self.convert(pg_result, render_url_columns = false)
+ relations, colrender = DataExplorer.add_extra_data(pg_result)
+ result_data = []
+
+ # column names to search in place of id columns (topic_id, user_id etc)
+ cols = %w[name title username]
+
+ # find values from extra data, based on result id
+ pg_result.values.each do |row|
+ row_data = []
+
+ row.each_with_index do |col, col_index|
+ col_name = pg_result.fields[col_index]
+ col_render = colrender[col_index]
+ related = relations.dig(col_render.to_sym) if col_render.present?
+
+ if related.is_a?(ActiveModel::ArraySerializer)
+ related_row = related.object.find_by(id: col)
+ if col_name.include?("_id")
+ column = cols.find { |c| related_row.try c }
+ else
+ column = related_row.try(col_name)
+ end
+
+ if column.nil?
+ row_data[col_index] = col
+ else
+ row_data[col_index] = "#{related_row[column]} (#{col})"
+ end
+ elsif col_render == "url" && render_url_columns
+ url, text = guess_url(col)
+ row_data[col_index] = "[#{text}](#{url})"
+ else
+ row_data[col_index] = col
+ end
+ end
+
+ result_data << row_data.map { |c| "| #{sanitize_field(c.to_s)} " }.join + "|\n"
+ end
+
+ table_headers = pg_result.fields.map { |c| " #{c.gsub("_id", "")} |" }.join
+ table_body = pg_result.fields.size.times.map { " :----- |" }.join
+
+ "|#{table_headers}\n|#{table_body}\n#{result_data.join}"
+ end
+
+ def self.guess_url(column_value)
+ text, url = column_value.split(/,(.+)/)
+
+ [url || column_value, text || column_value]
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/validation_error.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/validation_error.rb
new file mode 100644
index 00000000000..ba15df8d63c
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/validation_error.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+
+module ::DiscourseDataExplorer
+ class ValidationError < StandardError
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/tasks/data_explorer.rake b/plugins/discourse-data-explorer/lib/tasks/data_explorer.rake
new file mode 100644
index 00000000000..bf0747f78f9
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/tasks/data_explorer.rake
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+# rake data_explorer:list_hidden_queries
+desc "Shows a list of hidden queries"
+task "data_explorer:list_hidden_queries" => :environment do |t|
+ puts "\nHidden Queries\n\n"
+
+ hidden_queries = DiscourseDataExplorer::Query.where(hidden: false)
+
+ hidden_queries.each do |query|
+ puts "Name: #{query.name}"
+ puts "Description: #{query.description}"
+ puts "ID: #{query.id}\n\n"
+ end
+end
+
+# rake data_explorer[-1]
+# rake data_explorer[1,-2,3,-4,5]
+desc "Hides one or multiple queries by ID"
+task "data_explorer" => :environment do |t, args|
+ args.extras.each do |arg|
+ id = arg.to_i
+ query = DiscourseDataExplorer::Query.find_by(id: id)
+ if query
+ puts "\nFound query with id #{id}"
+ query.update!(hidden: true)
+ puts "Query no.#{id} is now hidden"
+ else
+ puts "\nError finding query with id #{id}"
+ end
+ end
+ puts ""
+end
+
+# rake data_explorer:unhide_query[-1]
+# rake data_explorer:unhide_query[1,-2,3,-4,5]
+desc "Unhides one or multiple queries by ID"
+task "data_explorer:unhide_query" => :environment do |t, args|
+ args.extras.each do |arg|
+ id = arg.to_i
+ query = DiscourseDataExplorer::Query.find_by(id: id)
+ if query
+ puts "\nFound query with id #{id}"
+ query.update!(hidden: false)
+ puts "Query no.#{id} is now visible"
+ else
+ puts "\nError finding query with id #{id}"
+ end
+ end
+ puts ""
+end
+
+# rake data_explorer:hard_delete[-1]
+# rake data_explorer:hard_delete[1,-2,3,-4,5]
+desc "Hard deletes one or multiple queries by ID"
+task "data_explorer:hard_delete" => :environment do |t, args|
+ args.extras.each do |arg|
+ id = arg.to_i
+ query = DiscourseDataExplorer::Query.find_by(id: id)
+ if query
+ puts "\nFound query with id #{id}"
+
+ if query.hidden
+ query.destroy!
+ puts "Query no.#{id} has been deleted"
+ else
+ puts "Query no.#{id} must be hidden in order to hard delete"
+ puts "To hide the query, run: " + "rake data_explorer[#{id}]"
+ end
+ else
+ puts "\nError finding query with id #{id}"
+ end
+ end
+ puts ""
+end
diff --git a/plugins/discourse-data-explorer/lib/tasks/fix_query_ids.rake b/plugins/discourse-data-explorer/lib/tasks/fix_query_ids.rake
new file mode 100644
index 00000000000..6b47cefd55c
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/tasks/fix_query_ids.rake
@@ -0,0 +1,131 @@
+# frozen_string_literal: true
+
+desc "Fix query IDs to match the old ones used in the plugin store (q:id)"
+task "data_explorer:fix_query_ids" => :environment do
+ ActiveRecord::Base.transaction do
+ # Only queries with unique title can be fixed
+ movements = DB.query <<~SQL
+ SELECT deq.id AS from, (replace(plugin_store_rows.key, 'q:',''))::integer AS to
+ FROM plugin_store_rows
+ INNER JOIN data_explorer_queries deq ON deq.name = plugin_store_rows.value::json->>'name'
+ WHERE
+ (replace(plugin_store_rows.key, 'q:',''))::integer != deq.id AND
+ plugin_store_rows.plugin_name = 'discourse-data-explorer' AND
+ plugin_store_rows.type_name = 'JSON' AND
+ (SELECT COUNT(*) from data_explorer_queries deq2 WHERE deq.name = deq2.name) = 1
+ SQL
+
+ if movements.present?
+ # If there are new queries, they still may have conflict
+ # We just want to move their ids to safe space and we will not move them back
+ additional_conflicts =
+ DB.query(<<~SQL, from: movements.map { |m| m.from }, to: movements.map { |m| m.to })
+ SELECT id FROM data_explorer_queries
+ WHERE id IN (:to)
+ AND id NOT IN (:from)
+ SQL
+ additional_conflicts = additional_conflicts.map(&:id)
+
+ # Create temporary tables
+ DB.exec <<~SQL
+ CREATE TEMPORARY TABLE tmp_data_explorer_queries(
+ id INTEGER PRIMARY KEY,
+ name VARCHAR,
+ description TEXT,
+ sql TEXT,
+ user_id INTEGER,
+ last_run_at TIMESTAMP,
+ hidden BOOLEAN,
+ created_at TIMESTAMP,
+ updated_at TIMESTAMP
+ ) ON COMMIT DROP
+ SQL
+
+ DB.exec <<-SQL
+ CREATE TEMPORARY TABLE tmp_data_explorer_query_groups(
+ id INTEGER PRIMARY KEY,
+ query_id INTEGER,
+ group_id INTEGER
+ ) ON COMMIT DROP
+ SQL
+
+ movements.each do |movement|
+ # insert movements to temporary tables
+ DB.exec <<-SQL
+ INSERT INTO tmp_data_explorer_queries(id, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at)
+ SELECT #{movement.to}, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at
+ FROM data_explorer_queries
+ WHERE id = #{movement.from}
+ SQL
+
+ DB.exec <<-SQL
+ INSERT INTO tmp_data_explorer_query_groups(id, query_id, group_id)
+ SELECT id, #{movement.to}, group_id
+ FROM data_explorer_query_groups
+ WHERE query_id = #{movement.from}
+ SQL
+ end
+
+ # insert rest to temporary tables
+ already_moved_ids = movements.map(&:from) | additional_conflicts
+ DB.exec(<<-SQL, already_moved_ids: already_moved_ids)
+ INSERT INTO tmp_data_explorer_queries(id, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at)
+ SELECT id, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at
+ FROM data_explorer_queries
+ WHERE id NOT IN (:already_moved_ids)
+ SQL
+
+ DB.exec(<<-SQL, already_moved_ids: already_moved_ids)
+ INSERT INTO tmp_data_explorer_query_groups(id, query_id, group_id)
+ SELECT id, query_id, group_id
+ FROM data_explorer_query_groups
+ WHERE query_id NOT IN (:already_moved_ids)
+ SQL
+
+ # insert additional_conflicts to temporary tables
+ new_id =
+ DB.query("select greatest(max(id), 1) from tmp_data_explorer_queries").first.greatest + 1
+ additional_conflicts.each do |conflict_id|
+ DB.exec <<-SQL
+ INSERT INTO tmp_data_explorer_queries(id, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at)
+ SELECT #{new_id}, name, description, sql, user_id, last_run_at, hidden, created_at, updated_at
+ FROM data_explorer_queries
+ WHERE id = #{conflict_id}
+ SQL
+
+ DB.exec <<~SQL
+ INSERT INTO tmp_data_explorer_query_groups(id, query_id, group_id)
+ SELECT id, #{new_id}, group_id
+ FROM data_explorer_query_groups
+ WHERE query_id = #{conflict_id}
+ SQL
+
+ new_id = new_id + 1
+ end
+
+ # clear original tables and copy data from temporary tables
+ DB.exec("DELETE FROM data_explorer_queries")
+ DB.exec("INSERT INTO data_explorer_queries SELECT * FROM tmp_data_explorer_queries")
+
+ DB.exec("DELETE FROM data_explorer_query_groups")
+ DB.exec("INSERT INTO data_explorer_query_groups SELECT * FROM tmp_data_explorer_query_groups")
+
+ # Update id sequences
+ DB.exec <<~SQL
+ SELECT
+ setval(
+ pg_get_serial_sequence('data_explorer_queries', 'id'),
+ (select greatest(max(id), 1) from data_explorer_queries)
+ );
+ SQL
+
+ DB.exec <<~SQL
+ SELECT
+ setval(
+ pg_get_serial_sequence('data_explorer_query_groups', 'id'),
+ (select greatest(max(id), 1) from data_explorer_query_groups)
+ );
+ SQL
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rb
new file mode 100644
index 00000000000..12aa8eef098
--- /dev/null
+++ b/plugins/discourse-data-explorer/plugin.rb
@@ -0,0 +1,192 @@
+# frozen_string_literal: true
+
+# name: discourse-data-explorer
+# about: Allows you to make SQL queries against your live database, allowing for up-to-the-minute stats reporting.
+# meta_topic_id: 32566
+# version: 0.3
+# authors: Riking
+# url: https://github.com/discourse/discourse/tree/main/plugins/discourse-data-explorer
+
+enabled_site_setting :data_explorer_enabled
+
+register_asset "stylesheets/explorer.scss"
+
+register_svg_icon "caret-down"
+register_svg_icon "caret-right"
+register_svg_icon "chevron-left"
+register_svg_icon "circle-exclamation"
+register_svg_icon "info"
+register_svg_icon "pencil"
+register_svg_icon "upload"
+
+add_admin_route "explorer.title", "explorer"
+
+module ::DiscourseDataExplorer
+ PLUGIN_NAME = "discourse-data-explorer"
+
+ # This should always match the max value for the
+ # data_explorer_query_result_limit site setting
+ QUERY_RESULT_MAX_LIMIT = 10_000
+end
+
+require_relative "lib/discourse_data_explorer/engine"
+
+after_initialize do
+ GlobalSetting.add_default(:max_data_explorer_api_reqs_per_10_seconds, 2)
+
+ # Available options:
+ # - warn
+ # - warn+block
+ # - block
+ GlobalSetting.add_default(:max_data_explorer_api_req_mode, "warn")
+
+ add_to_class(:guardian, :user_is_a_member_of_group?) do |group|
+ return false if !current_user
+ return true if current_user.admin?
+ current_user.group_ids.include?(group.id)
+ end
+
+ add_to_class(:guardian, :user_can_access_query?) do |query|
+ return false if !current_user
+ return true if current_user.admin?
+ query.groups.blank? || query.groups.any? { |group| user_is_a_member_of_group?(group) }
+ end
+
+ add_to_class(:guardian, :group_and_user_can_access_query?) do |group, query|
+ return false if !current_user
+ return true if current_user.admin?
+ user_is_a_member_of_group?(group) && query.groups.exists?(id: group.id)
+ end
+
+ add_to_serializer(
+ :group_show,
+ :has_visible_data_explorer_queries,
+ include_condition: -> { scope.user_is_a_member_of_group?(object) },
+ ) { DiscourseDataExplorer::Query.for_group(object).exists? }
+
+ register_bookmarkable(DiscourseDataExplorer::QueryGroupBookmarkable)
+
+ add_api_key_scope(
+ :discourse_data_explorer,
+ { run_queries: { actions: %w[discourse_data_explorer/query#run], params: %i[id] } },
+ )
+
+ reloadable_patch do
+ if defined?(DiscourseAutomation)
+ add_automation_scriptable("recurring_data_explorer_result_pm") do
+ queries =
+ DiscourseDataExplorer::Query
+ .where(hidden: false)
+ .map { |q| { id: q.id, translated_name: q.name } }
+ field :recipients, component: :email_group_user, required: true
+ field :query_id, component: :choices, required: true, extra: { content: queries }
+ field :query_params, component: :"key-value", accepts_placeholders: true
+ field :skip_empty, component: :boolean
+ field :users_from_group, component: :boolean
+ field :attach_csv,
+ component: :boolean,
+ validator: ->(attach_csv) do
+ return if !attach_csv
+
+ extensions = SiteSetting.authorized_extensions.split("|")
+ if (extensions & %w[csv *]).empty?
+ I18n.t(
+ "discourse_automation.scriptables.recurring_data_explorer_result_pm.no_csv_allowed",
+ )
+ end
+ end
+
+ version 1
+ triggerables [:recurring]
+
+ script do |_, fields, automation|
+ recipients = Array(fields.dig("recipients", "value")).uniq
+ query_id = fields.dig("query_id", "value")
+ query_params = fields.dig("query_params", "value") || {}
+ skip_empty = fields.dig("skip_empty", "value") || false
+ users_from_group = fields.dig("users_from_group", "value") || false
+ attach_csv = fields.dig("attach_csv", "value") || false
+
+ unless SiteSetting.data_explorer_enabled
+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - plugin must be enabled to run automation #{automation.id}"
+ next
+ end
+
+ if recipients.blank?
+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - couldn't find any recipients for automation #{automation.id}"
+ next
+ end
+
+ DiscourseDataExplorer::ReportGenerator
+ .generate(
+ query_id,
+ query_params,
+ recipients,
+ { skip_empty:, users_from_group:, attach_csv:, render_url_columns: true },
+ )
+ .each do |pm|
+ begin
+ utils.send_pm(pm, automation_id: automation.id, prefers_encrypt: false)
+ rescue ActiveRecord::RecordNotSaved => e
+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - couldn't send PM for automation #{automation.id}: #{e.message}"
+ end
+ end
+ end
+ end
+
+ add_automation_scriptable("recurring_data_explorer_result_topic") do
+ queries =
+ DiscourseDataExplorer::Query
+ .where(hidden: false)
+ .map { |q| { id: q.id, translated_name: q.name } }
+ field :topic_id, component: :text, required: true
+ field :query_id, component: :choices, required: true, extra: { content: queries }
+ field :query_params, component: :"key-value", accepts_placeholders: true
+ field :skip_empty, component: :boolean
+ field :attach_csv, component: :boolean
+
+ version 1
+ triggerables [:recurring]
+
+ script do |_, fields, automation|
+ topic_id = fields.dig("topic_id", "value")
+ query_id = fields.dig("query_id", "value")
+ query_params = fields.dig("query_params", "value") || {}
+ skip_empty = fields.dig("skip_empty", "value") || false
+ attach_csv = fields.dig("attach_csv", "value") || false
+
+ unless SiteSetting.data_explorer_enabled
+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - plugin must be enabled to run automation #{automation.id}"
+ next
+ end
+
+ topic = Topic.find_by(id: topic_id)
+ if topic.blank?
+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - couldn't find topic ID (#{topic_id}) for automation #{automation.id}"
+ next
+ end
+
+ begin
+ post =
+ DiscourseDataExplorer::ReportGenerator.generate_post(
+ query_id,
+ query_params,
+ { skip_empty:, attach_csv:, render_url_columns: true },
+ )
+
+ next if post.empty?
+
+ PostCreator.create!(
+ Discourse.system_user,
+ topic_id: topic.id,
+ raw: post["raw"],
+ skip_validations: true,
+ )
+ rescue ActiveRecord::RecordNotSaved => e
+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - couldn't reply to topic ID #{topic_id} for automation #{automation.id}: #{e.message}"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/automation/recurring_data_explorer_result_pm_spec.rb b/plugins/discourse-data-explorer/spec/automation/recurring_data_explorer_result_pm_spec.rb
new file mode 100644
index 00000000000..377231fb6a9
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/automation/recurring_data_explorer_result_pm_spec.rb
@@ -0,0 +1,152 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe "RecurringDataExplorerResultPM" do
+ fab!(:admin)
+
+ fab!(:user)
+ fab!(:another_user) { Fabricate(:user) }
+ fab!(:group_user) { Fabricate(:user) }
+ fab!(:not_allowed_user) { Fabricate(:user) }
+
+ fab!(:group) { Fabricate(:group, users: [user, another_user]) }
+ fab!(:another_group) { Fabricate(:group, users: [group_user]) }
+
+ fab!(:automation) do
+ Fabricate(:automation, script: "recurring_data_explorer_result_pm", trigger: "recurring")
+ end
+ fab!(:query) { Fabricate(:query, sql: "SELECT 'testabcd' AS data") }
+ fab!(:query_group) { Fabricate(:query_group, query: query, group: group) }
+ fab!(:query_group_2) { Fabricate(:query_group, query: query, group: another_group) }
+
+ let!(:recipients) do
+ [user.username, not_allowed_user.username, another_user.username, another_group.name]
+ end
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.discourse_automation_enabled = true
+
+ automation.upsert_field!("query_id", "choices", { value: query.id })
+ automation.upsert_field!("recipients", "email_group_user", { value: recipients })
+ automation.upsert_field!(
+ "query_params",
+ "key-value",
+ { value: [%w[from_days_ago 0], %w[duration_days 15]] },
+ )
+ automation.upsert_field!(
+ "recurrence",
+ "period",
+ { value: { interval: 1, frequency: "day" } },
+ target: "trigger",
+ )
+ automation.upsert_field!("start_date", "date_time", { value: 2.minutes.ago }, target: "trigger")
+ end
+
+ context "when using recurring trigger" do
+ it "sends the pm at recurring date_date" do
+ freeze_time 1.day.from_now do
+ expect { Jobs::DiscourseAutomation::Tracker.new.execute }.to change { Topic.count }.by(3)
+
+ title =
+ I18n.t("data_explorer.report_generator.private_message.title", query_name: query.name)
+ expect(Topic.last(3).pluck(:title)).to eq([title, title, title])
+ end
+ end
+
+ it "ensures only allowed users in recipients field receive reports via pm" do
+ expect do
+ automation.update(last_updated_by_id: admin.id)
+ automation.trigger!
+ end.to change { Topic.count }.by(3)
+
+ user_topics = Topic.last(2)
+ group_topics = Topic.first(1)
+ expect(Topic.last(3).pluck(:archetype)).to eq(
+ [Archetype.private_message, Archetype.private_message, Archetype.private_message],
+ )
+ expect(user_topics.map { |t| t.allowed_users.pluck(:username).sort }).to match_array(
+ [
+ [user.username, Discourse.system_user.username],
+ [another_user.username, Discourse.system_user.username],
+ ],
+ )
+ expect(group_topics.map { |t| t.allowed_groups.pluck(:name).sort }).to match_array(
+ [[another_group.name]],
+ )
+ end
+
+ it "has appropriate content from the report generator" do
+ freeze_time
+
+ automation.update(last_updated_by_id: admin.id)
+ automation.trigger!
+
+ expect(Post.first.raw).to eq(
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: another_group.name,
+ query_name: query.name,
+ table: "| data |\n| :----- |\n| testabcd |\n",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ).chomp,
+ )
+ end
+
+ it "does not send the PM if skip_empty" do
+ query.update!(sql: "SELECT NULL LIMIT 0")
+ automation.upsert_field!("skip_empty", "boolean", { value: true })
+
+ automation.update(last_updated_by_id: admin.id)
+
+ expect { automation.trigger! }.to_not change { Post.count }
+ end
+
+ it "works with a query that returns URLs in a number,url format" do
+ freeze_time
+ query.update!(sql: "SELECT 3 || ',https://test.com' AS some_url")
+ automation.update(last_updated_by_id: admin.id)
+ automation.trigger!
+
+ expect(Post.first.raw).to eq(
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: another_group.name,
+ query_name: query.name,
+ table: "| some_url |\n| :----- |\n| [3](https://test.com) |\n",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ).chomp,
+ )
+ end
+ end
+
+ context "when using attach_csv" do
+ it "requires csv to be in authorized extensions" do
+ SiteSetting.authorized_extensions = "pdf|txt"
+
+ expect { automation.upsert_field!("attach_csv", "boolean", { value: true }) }.to raise_error(
+ ActiveRecord::RecordInvalid,
+ /#{I18n.t("discourse_automation.scriptables.recurring_data_explorer_result_pm.no_csv_allowed")}/,
+ )
+
+ SiteSetting.authorized_extensions = "pdf|txt|csv"
+
+ expect {
+ automation.upsert_field!("attach_csv", "boolean", { value: true })
+ }.to_not raise_error
+
+ SiteSetting.authorized_extensions = "*"
+
+ expect {
+ automation.upsert_field!("attach_csv", "boolean", { value: true })
+ }.to_not raise_error
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/automation/recurring_data_explorer_result_topic_spec.rb b/plugins/discourse-data-explorer/spec/automation/recurring_data_explorer_result_topic_spec.rb
new file mode 100644
index 00000000000..7a2cde9e2d7
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/automation/recurring_data_explorer_result_topic_spec.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe "RecurringDataExplorerResultTopic" do
+ fab!(:admin)
+
+ fab!(:user)
+ fab!(:another_user) { Fabricate(:user) }
+ fab!(:group_user) { Fabricate(:user) }
+ fab!(:not_allowed_user) { Fabricate(:user) }
+ fab!(:topic)
+
+ fab!(:group) { Fabricate(:group, users: [user, another_user]) }
+
+ fab!(:automation) do
+ Fabricate(:automation, script: "recurring_data_explorer_result_topic", trigger: "recurring")
+ end
+ fab!(:query) { Fabricate(:query, sql: "SELECT 'testabcd' AS data") }
+ fab!(:query_group) { Fabricate(:query_group, query: query, group: group) }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.discourse_automation_enabled = true
+
+ automation.upsert_field!("query_id", "choices", { value: query.id })
+ automation.upsert_field!("topic_id", "text", { value: topic.id })
+ automation.upsert_field!(
+ "query_params",
+ "key-value",
+ { value: [%w[from_days_ago 0], %w[duration_days 15]] },
+ )
+ automation.upsert_field!(
+ "recurrence",
+ "period",
+ { value: { interval: 1, frequency: "day" } },
+ target: "trigger",
+ )
+ automation.upsert_field!("start_date", "date_time", { value: 2.minutes.ago }, target: "trigger")
+ end
+
+ context "when using recurring trigger" do
+ it "sends the post at recurring date_date" do
+ freeze_time 1.day.from_now do
+ expect { Jobs::DiscourseAutomation::Tracker.new.execute }.to change {
+ topic.reload.posts.count
+ }.by(1)
+
+ expect(topic.posts.last.raw).to eq(
+ I18n.t(
+ "data_explorer.report_generator.post.body",
+ query_name: query.name,
+ table: "| data |\n| :----- |\n| testabcd |\n",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ).chomp,
+ )
+ end
+ end
+
+ it "has appropriate content from the report generator" do
+ freeze_time
+ automation.update(last_updated_by_id: admin.id)
+ automation.trigger!
+
+ expect(topic.posts.last.raw).to eq(
+ I18n.t(
+ "data_explorer.report_generator.post.body",
+ query_name: query.name,
+ table: "| data |\n| :----- |\n| testabcd |\n",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ).chomp,
+ )
+ end
+
+ it "does not create the post if skip_empty" do
+ query.update!(sql: "SELECT NULL LIMIT 0")
+ automation.upsert_field!("skip_empty", "boolean", { value: true })
+
+ automation.update(last_updated_by_id: admin.id)
+
+ expect { automation.trigger! }.to_not change { Post.count }
+ end
+
+ it "works with a query that returns URLs in a number,url format" do
+ freeze_time
+ query.update!(sql: "SELECT 3 || ',https://test.com' AS some_url")
+ automation.update(last_updated_by_id: admin.id)
+ automation.trigger!
+
+ expect(topic.posts.last.raw).to eq(
+ I18n.t(
+ "data_explorer.report_generator.post.body",
+ query_name: query.name,
+ table: "| some_url |\n| :----- |\n| [3](https://test.com) |\n",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ).chomp,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/data_explorer_spec.rb b/plugins/discourse-data-explorer/spec/data_explorer_spec.rb
new file mode 100644
index 00000000000..9fa562bbc3a
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/data_explorer_spec.rb
@@ -0,0 +1,127 @@
+# frozen_string_literal: true
+
+describe DiscourseDataExplorer::DataExplorer do
+ describe ".run_query" do
+ fab!(:topic)
+
+ it "should run a query that includes PG template patterns" do
+ sql = <<~SQL
+ WITH query AS (
+ SELECT TO_CHAR(created_at, 'yyyy:mm:dd') AS date FROM topics
+ ) SELECT * FROM query
+ SQL
+
+ query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
+
+ 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
+
+ it "should run a query containing a question mark in the comment" do
+ sql = <<~SQL
+ WITH query AS (
+ SELECT id FROM topics -- some SQL ? comment ?
+ ) SELECT * FROM query
+ SQL
+
+ query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
+
+ result = described_class.run_query(query)
+
+ expect(result[:error]).to eq(nil)
+ expect(result[:pg_result][0]["id"]).to eq(topic.id)
+ end
+
+ it "can run a query with params interpolation" do
+ 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
+
+ query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
+
+ 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
+
+ describe ".add_extra_data" do
+ it "treats any column with payload in the name as 'json'" do
+ Fabricate(:reviewable_queued_post)
+ sql = <<~SQL
+ SELECT id, payload FROM reviewables LIMIT 10
+ SQL
+ query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
+ result = described_class.run_query(query)
+ _, colrender = DiscourseDataExplorer::DataExplorer.add_extra_data(result[:pg_result])
+ expect(colrender).to eq({ 1 => "json" })
+ end
+
+ it "treats columns with the actual json data type as 'json'" do
+ ApiKeyScope.create(
+ resource: "topics",
+ action: "update",
+ api_key_id: Fabricate(:api_key).id,
+ allowed_parameters: {
+ "category_id" => ["#{topic.category_id}"],
+ },
+ )
+ sql = <<~SQL
+ SELECT id, allowed_parameters FROM api_key_scopes LIMIT 10
+ SQL
+ query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
+ result = described_class.run_query(query)
+ _, colrender = DiscourseDataExplorer::DataExplorer.add_extra_data(result[:pg_result])
+ expect(colrender).to eq({ 1 => "json" })
+ end
+
+ describe "serializing models to serializer" do
+ it "serializes correctly to BasicTopicSerializer for topic relations" do
+ topic = Fabricate(:topic, locale: "ja")
+ query = Fabricate(:query, sql: "SELECT id AS topic_id FROM topics WHERE id = #{topic.id}")
+
+ pg_result = described_class.run_query(query)[:pg_result]
+ relations, _ = DiscourseDataExplorer::DataExplorer.add_extra_data(pg_result)
+
+ expect {
+ records = relations[:topic].object
+ records.map { |t| BasicTopicSerializer.new(t, root: false).as_json }
+ }.not_to raise_error
+
+ json = relations[:topic].as_json
+ expect(json).to include(BasicTopicSerializer.new(topic, root: false).as_json)
+ end
+
+ it "chooses the correct serializer for tag_group" do
+ tag_group = Fabricate(:tag_group)
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
+ tag_group.tags = [tag1, tag2]
+
+ query = Fabricate(:query, sql: "SELECT tag_id, tag_group_id FROM tag_group_memberships")
+
+ pg_result = described_class.run_query(query)[:pg_result]
+ relations, colrender = DiscourseDataExplorer::DataExplorer.add_extra_data(pg_result)
+
+ expect(colrender).to eq({ 1 => :tag_group })
+ expect(relations[:tag_group].as_json).to include(
+ { "id" => tag_group.id, "name" => tag_group.name },
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/fabricators/query_fabricator.rb b/plugins/discourse-data-explorer/spec/fabricators/query_fabricator.rb
new file mode 100644
index 00000000000..4309b7da789
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/fabricators/query_fabricator.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+Fabricator(:query, from: DiscourseDataExplorer::Query) do
+ name { sequence(:name) { |i| "cat#{i}" } }
+ description { sequence(:desc) { |i| "description #{i}" } }
+ sql { sequence(:sql) { |i| "SELECT * FROM users WHERE id > 0 LIMIT #{i}" } }
+ user
+end
+
+Fabricator(:query_group, from: DiscourseDataExplorer::QueryGroup) do
+ query
+ group
+end
diff --git a/plugins/discourse-data-explorer/spec/guardian_spec.rb b/plugins/discourse-data-explorer/spec/guardian_spec.rb
new file mode 100644
index 00000000000..be1c4709f08
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/guardian_spec.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe Guardian do
+ before { SiteSetting.data_explorer_enabled = true }
+
+ def make_query(group_ids = [])
+ query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Query number #{Fabrication::Sequencer.sequence("query-id", 1)}",
+ sql: "SELECT 1",
+ )
+
+ group_ids.each { |group_id| query.query_groups.create!(group_id: group_id) }
+
+ query
+ end
+
+ let(:user) { build(:user) }
+ let(:admin) { build(:admin) }
+ fab!(:group)
+
+ describe "#user_is_a_member_of_group?" do
+ it "is true when the user is an admin" do
+ expect(Guardian.new(admin).user_is_a_member_of_group?(group)).to eq(true)
+ end
+
+ it "is true when the user is not an admin, but is a member of the group" do
+ group.add(user)
+
+ expect(Guardian.new(user).user_is_a_member_of_group?(group)).to eq(true)
+ end
+
+ it "is false when the user is not an admin, and is not a member of the group" do
+ expect(Guardian.new(user).user_is_a_member_of_group?(group)).to eq(false)
+ end
+ end
+
+ describe "#group_and_user_can_access_query?" do
+ it "is true if the user is an admin" do
+ expect(Guardian.new(admin).group_and_user_can_access_query?(group, make_query)).to eq(true)
+ end
+
+ it "is true if the user is a member of the group, and query contains the group id" do
+ query = make_query(["#{group.id}"])
+ group.add(user)
+
+ expect(Guardian.new(user).group_and_user_can_access_query?(group, query)).to eq(true)
+ end
+
+ it "is false if the query does not contain the group id" do
+ group.add(user)
+
+ expect(Guardian.new(user).group_and_user_can_access_query?(group, make_query)).to eq(false)
+ end
+
+ it "is false if the user is not member of the group" do
+ query = make_query(["#{group.id}"])
+
+ expect(Guardian.new(user).group_and_user_can_access_query?(group, query)).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rb b/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rb
new file mode 100644
index 00000000000..d072320fbb6
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/integration/custom_api_key_scopes_spec.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe "API keys scoped to query#run" do
+ before { SiteSetting.data_explorer_enabled = true }
+
+ fab!(:query1) do
+ DiscourseDataExplorer::Query.create!(name: "Query 1", sql: "SELECT 1 AS query1_res")
+ end
+ fab!(:query2) do
+ DiscourseDataExplorer::Query.create!(name: "Query 2", sql: "SELECT 1 AS query2_res")
+ end
+ fab!(:admin)
+
+ let(:all_queries_api_key) do
+ key = ApiKey.create!
+ ApiKeyScope.create!(
+ resource: "discourse_data_explorer",
+ action: "run_queries",
+ api_key_id: key.id,
+ )
+ key
+ end
+
+ let(:single_query_api_key) do
+ key = ApiKey.create!
+ ApiKeyScope.create!(
+ resource: "discourse_data_explorer",
+ action: "run_queries",
+ api_key_id: key.id,
+ allowed_parameters: {
+ "id" => [query1.id.to_s],
+ },
+ )
+ key
+ end
+
+ it "cannot hit any other endpoints" do
+ get "/latest.json",
+ headers: {
+ "Api-Key" => all_queries_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ expect(response.status).to eq(403)
+
+ get "/latest.json",
+ headers: {
+ "Api-Key" => single_query_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ expect(response.status).to eq(403)
+
+ get "/u/#{admin.username}.json",
+ headers: {
+ "Api-Key" => all_queries_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ expect(response.status).to eq(403)
+
+ get "/u/#{admin.username}.json",
+ headers: {
+ "Api-Key" => single_query_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ expect(response.status).to eq(403)
+ end
+
+ it "can only run the queries they're allowed to run" do
+ expect {
+ post "/admin/plugins/explorer/queries/#{query1.id}/run.json",
+ headers: {
+ "Api-Key" => single_query_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ }.to change { query1.reload.last_run_at }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq(true)
+ expect(response.parsed_body["columns"]).to eq(["query1_res"])
+
+ expect {
+ post "/admin/plugins/explorer/queries/#{query2.id}/run.json",
+ headers: {
+ "Api-Key" => single_query_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ }.not_to change { query2.reload.last_run_at }
+ expect(response.status).to eq(403)
+ end
+
+ it "can run all queries if they're not restricted to any queries" do
+ expect {
+ post "/admin/plugins/explorer/queries/#{query1.id}/run.json",
+ headers: {
+ "Api-Key" => all_queries_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ }.to change { query1.reload.last_run_at }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq(true)
+ expect(response.parsed_body["columns"]).to eq(["query1_res"])
+
+ expect {
+ post "/admin/plugins/explorer/queries/#{query2.id}/run.json",
+ headers: {
+ "Api-Key" => all_queries_api_key.key,
+ "Api-Username" => admin.username,
+ }
+ }.to change { query2.reload.last_run_at }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq(true)
+ expect(response.parsed_body["columns"]).to eq(["query2_res"])
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/jobs/scheduled/delete_hidden_queries_spec.rb b/plugins/discourse-data-explorer/spec/jobs/scheduled/delete_hidden_queries_spec.rb
new file mode 100644
index 00000000000..924d13ed378
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/jobs/scheduled/delete_hidden_queries_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe Jobs::DeleteHiddenQueries do
+ before do
+ Jobs.run_immediately!
+ SiteSetting.data_explorer_enabled = true
+ end
+
+ it "will correctly destroy old hidden queries" do
+ DiscourseDataExplorer::Query.create!(
+ id: 1,
+ name: "A",
+ description: "A description for A",
+ sql: "SELECT 1 as value",
+ hidden: false,
+ last_run_at: 2.days.ago,
+ updated_at: 2.days.ago,
+ )
+ DiscourseDataExplorer::Query.create!(
+ id: 2,
+ name: "B",
+ description: "A description for B",
+ sql: "SELECT 1 as value",
+ hidden: true,
+ last_run_at: 8.days.ago,
+ updated_at: 8.days.ago,
+ )
+ DiscourseDataExplorer::Query.create!(
+ id: 3,
+ name: "C",
+ description: "A description for C",
+ sql: "SELECT 1 as value",
+ hidden: true,
+ last_run_at: 4.days.ago,
+ updated_at: 4.days.ago,
+ )
+ DiscourseDataExplorer::Query.create!(
+ id: 4,
+ name: "D",
+ description: "A description for D",
+ sql: "SELECT 1 as value",
+ hidden: true,
+ last_run_at: nil,
+ updated_at: 10.days.ago,
+ )
+ DiscourseDataExplorer::Query.create!(
+ id: 5,
+ name: "E",
+ description: "A description for E",
+ sql: "SELECT 1 as value",
+ hidden: true,
+ last_run_at: 5.days.ago,
+ updated_at: 10.days.ago,
+ )
+ DiscourseDataExplorer::Query.create!(
+ id: 6,
+ name: "F",
+ description: "A description for F",
+ sql: "SELECT 1 as value",
+ hidden: true,
+ last_run_at: 10.days.ago,
+ updated_at: 5.days.ago,
+ )
+
+ described_class.new.execute(nil)
+ expect(DiscourseDataExplorer::Query.all.length).to eq(4)
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/lib/data_explorer/query_group_bookmarkable_spec.rb b/plugins/discourse-data-explorer/spec/lib/data_explorer/query_group_bookmarkable_spec.rb
new file mode 100644
index 00000000000..c688c17898c
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/data_explorer/query_group_bookmarkable_spec.rb
@@ -0,0 +1,189 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseDataExplorer::QueryGroupBookmarkable do
+ subject(:registered_bookmarkable) do
+ RegisteredBookmarkable.new(DiscourseDataExplorer::QueryGroupBookmarkable)
+ end
+
+ fab!(:admin_user) { Fabricate(:admin) }
+ fab!(:user)
+ fab!(:guardian) { Guardian.new(user) }
+ fab!(:group0) { Fabricate(:group) }
+ fab!(:group1) { Fabricate(:group) }
+ fab!(:group2) { Fabricate(:group) }
+ fab!(:group3) { Fabricate(:group) }
+ fab!(:query1) do
+ Fabricate(
+ :query,
+ name: "My First Query",
+ description: "This is the description of my 1st query.",
+ sql: "Not really important",
+ user: admin_user,
+ )
+ end
+ fab!(:query2) do
+ Fabricate(
+ :query,
+ name: "My Second Query",
+ description: "This is my 2nd query's description.",
+ sql: "Not really important",
+ user: admin_user,
+ )
+ end
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ register_test_bookmarkable(DiscourseDataExplorer::QueryGroupBookmarkable)
+ end
+
+ after { DiscoursePluginRegistry.reset_register!(:bookmarkables) }
+
+ # Groups 0 and 1 have access to the Query 1.
+ let!(:query_group1) { Fabricate(:query_group, query: query1, group: group0) }
+ let!(:query_group2) { Fabricate(:query_group, query: query1, group: group1) }
+ # User is member of both groups.
+ let!(:group_user1) { Fabricate(:group_user, user: user, group: group0) }
+ let!(:group_user2) { Fabricate(:group_user, user: user, group: group1) }
+
+ # Group 1 also has access to query2.
+ let!(:query_group3) { Fabricate(:query_group, query: query2, group: group1) }
+
+ # Group 2 has access to query 1. User is NOT a member of this group.
+ let!(:query_group4) { Fabricate(:query_group, query: query1, group: group2) }
+
+ # User is a member of Group 3, which has no access to Query 1.
+ let!(:group_user3) { Fabricate(:group_user, user: user, group: group3) }
+
+ # User bookmarked the same Query 1 twice, from different Groups (0 and 1)
+ let!(:bookmark1) do
+ Fabricate(:bookmark, user: user, bookmarkable: query_group1, name: "something i gotta do")
+ end
+ let!(:bookmark2) do
+ Fabricate(
+ :bookmark,
+ user: user,
+ bookmarkable: query_group2,
+ name: "something else i have to do",
+ )
+ end
+
+ # User also bookmarked Query 2 from Group 1.
+ let!(:bookmark3) do
+ Fabricate(
+ :bookmark,
+ user: user,
+ bookmarkable: query_group3,
+ name: "this is the other query I needed.",
+ )
+ end
+
+ # User previously bookmarked Query 1 from Group 2, of which she is no longer a member.
+ let!(:bookmark4) do
+ Fabricate(:bookmark, user: user, bookmarkable: query_group4, name: "something i gotta do also")
+ end
+
+ describe "#perform_list_query" do
+ it "returns all the user's bookmarks" do
+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array(
+ [bookmark1.id, bookmark2.id, bookmark3.id],
+ )
+ end
+
+ it "does not return bookmarks made from groups that the user is no longer a member of" do
+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).not_to include(
+ bookmark4.id,
+ )
+
+ # remove user from the other groups from which they bookmarked a query
+ group_user1.delete
+ group_user2.delete
+
+ # bookmarks is now empty, because user is not a member of any Groups with permission to see the query
+ expect(registered_bookmarkable.perform_list_query(user, guardian)).to be_empty
+ end
+ end
+
+ describe "#perform_search_query" do
+ before { SearchIndexer.enable }
+
+ it "returns bookmarks that match by name" do
+ ts_query = Search.ts_query(term: "gotta", ts_config: "simple")
+ expect(
+ registered_bookmarkable.perform_search_query(
+ registered_bookmarkable.perform_list_query(user, guardian),
+ "%gotta%",
+ ts_query,
+ ).map(&:id),
+ ).to match_array([bookmark1.id])
+ end
+
+ it "returns bookmarks that match by Query name" do
+ ts_query = Search.ts_query(term: "First", ts_config: "simple")
+ expect(
+ registered_bookmarkable.perform_search_query(
+ registered_bookmarkable.perform_list_query(user, guardian),
+ "%First%",
+ ts_query,
+ ).map(&:id),
+ ).to match_array([bookmark1.id, bookmark2.id])
+ end
+ end
+
+ describe "#can_send_reminder?" do
+ it "cannot send the reminder if the group is revoked access to the query" do
+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(true)
+ bookmark1.bookmarkable.delete
+ bookmark1.reload
+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)
+ end
+ end
+
+ describe "#reminder_handler" do
+ it "creates a notification for the user with the correct details" do
+ expect { registered_bookmarkable.send_reminder_notification(bookmark1) }.to change {
+ Notification.count
+ }.by(1)
+ notification = user.notifications.last
+ expect(notification.notification_type).to eq(Notification.types[:bookmark_reminder])
+ expect(notification.data).to eq(
+ {
+ title: bookmark1.bookmarkable.query.name,
+ bookmarkable_url:
+ "/g/#{bookmark1.bookmarkable.group.name}/reports/#{bookmark1.bookmarkable.query.id}",
+ display_username: bookmark1.user.username,
+ bookmark_name: bookmark1.name,
+ bookmark_id: bookmark1.id,
+ bookmarkable_type: bookmark1.bookmarkable_type,
+ bookmarkable_id: bookmark1.bookmarkable_id,
+ }.to_json,
+ )
+ end
+ end
+
+ describe "#can_see?" do
+ it "returns false if the user is not a member of the group from which they created the bookmark" do
+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(true) # Query 1, Group 0
+ expect(registered_bookmarkable.can_see?(guardian, bookmark2)).to eq(true) # Query 1, Group 1
+ expect(registered_bookmarkable.can_see?(guardian, bookmark3)).to eq(true) # Query 2, Group 1
+ expect(registered_bookmarkable.can_see?(guardian, bookmark4)).to eq(false) # Query 1, Group 2
+
+ # remove from Groups 0 and 1
+ group_user1.delete # Group 0
+ group_user2.delete # Group 1
+ guardian.user.reload
+
+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(false)
+ expect(registered_bookmarkable.can_see?(guardian, bookmark2)).to eq(false)
+ expect(registered_bookmarkable.can_see?(guardian, bookmark3)).to eq(false)
+ expect(registered_bookmarkable.can_see?(guardian, bookmark4)).to eq(false)
+
+ # And adding the user back to the group, just to be sure.
+ Fabricate(:group_user, user: user, group: group2)
+ guardian.user.reload
+
+ expect(registered_bookmarkable.can_see?(guardian, bookmark4)).to eq(true)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb b/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb
new file mode 100644
index 00000000000..ea300038b63
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/parameter_spec.rb
@@ -0,0 +1,135 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::Parameter do
+ def param(identifier, type, default, nullable)
+ described_class.new(identifier, type, default, nullable)
+ end
+
+ describe ".cast_to_ruby" do
+ it "returns nil for nullable blank string" do
+ expect(param("param123", :string, nil, true).cast_to_ruby("")).to eq(nil)
+ end
+
+ it "raises error for not-nullable blank string" do
+ expect { param("param123", :string, nil, false).cast_to_ruby("") }.to raise_error(
+ ::DiscourseDataExplorer::ValidationError,
+ )
+ end
+
+ describe "double type" do
+ let!(:double_param) { param("double", :double, nil, false) }
+
+ it "raises an error if not a double" do
+ expect { double_param.cast_to_ruby("abcd") }.to raise_error(
+ ::DiscourseDataExplorer::ValidationError,
+ )
+ end
+
+ it "returns the float number if it can be a valid double" do
+ expect(double_param.cast_to_ruby("3.14")).to eq(3.14)
+ expect(double_param.cast_to_ruby(".314")).to eq(0.314)
+ expect(double_param.cast_to_ruby("1")).to eq(1.0)
+ expect(double_param.cast_to_ruby("Inf")).to eq(Float::INFINITY)
+ expect(double_param.cast_to_ruby("-Infinity")).to eq(-Float::INFINITY)
+ expect(double_param.cast_to_ruby("-NaN").nan?).to eq(true)
+ expect(double_param.cast_to_ruby("NaN").nan?).to eq(true)
+ end
+ end
+
+ describe "post_id type" do
+ fab!(:post)
+
+ context "when the value provided is a post share URL" do
+ it "returns the found post id" do
+ expect(param("post_id", :post_id, nil, false).cast_to_ruby(post.url)).to eq(post.id)
+ end
+
+ it "returns the found post id when there is a share user param" do
+ expect(
+ param("post_id", :post_id, nil, false).cast_to_ruby(
+ "#{post.url}?u=#{post.user.username}",
+ ),
+ ).to eq(post.id)
+ end
+
+ it "returns the found post id when no post number is provided" do
+ expect(
+ param("post_id", :post_id, nil, false).cast_to_ruby("#{post.url(share_url: true)}"),
+ ).to eq(post.id)
+ end
+
+ it "raises an error if no such post exists" do
+ post.destroy
+ expect { param("post_id", :post_id, nil, false).cast_to_ruby(post.url) }.to raise_error(
+ ::DiscourseDataExplorer::ValidationError,
+ )
+ end
+ end
+
+ context "when the value provided is an integer" do
+ it "raises an error if no such post exists" do
+ expect { param("post_id", :post_id, nil, false).cast_to_ruby("-999") }.to raise_error(
+ ::DiscourseDataExplorer::ValidationError,
+ )
+ end
+
+ it "returns the post id if the post exists" do
+ expect(param("post_id", :post_id, nil, false).cast_to_ruby(post.id.to_s)).to eq(post.id)
+ end
+ end
+ end
+
+ describe "group_id type" do
+ fab!(:group)
+
+ context "when the value provided is an integer" do
+ it "raises an error if no such group exists" do
+ expect { param("group_id", :group_id, nil, false).cast_to_ruby("-999") }.to raise_error(
+ ::DiscourseDataExplorer::ValidationError,
+ )
+ end
+
+ it "returns the group id if the group exists" do
+ expect(param("group_id", :group_id, nil, false).cast_to_ruby(group.id.to_s)).to eq(
+ group.id,
+ )
+ end
+ end
+ end
+
+ describe "user_id type" do
+ fab!(:user)
+ it "raises an error if no such user exists" do
+ expect {
+ param("user_id", :user_id, nil, false).cast_to_ruby("user_not_exist")
+ }.to raise_error(::DiscourseDataExplorer::ValidationError)
+ expect {
+ param("user_id", :user_id, nil, false).cast_to_ruby("[email protected]")
+ }.to raise_error(::DiscourseDataExplorer::ValidationError)
+ end
+
+ it "returns the user id if the user exists" do
+ expect(param("user_id", :user_id, nil, false).cast_to_ruby(user.username)).to eq(user.id)
+ expect(param("user_id", :user_id, nil, false).cast_to_ruby(user.email)).to eq(user.id)
+ end
+ end
+ end
+
+ describe ".create_from_sql" do
+ it "should not validate default value" do
+ TEST_SQL = <<~SQL
+ -- [params]
+ -- user_id :user_id = user_not_exists
+ -- post_id :post_id = /t/should-not-exist/33554432/1
+ -- topic_id :topic_id = /t/should-not-exist/2147483646
+ -- category_id :category_id = category_not_exists
+ -- group_id :group_id = group_not_exists
+ -- group_list :group_list = group_not_exists1,group_not_exists1
+ -- user_list :mul_users = user_not_exists1,user_not_exists2
+ SELECT 1
+ SQL
+
+ expect(described_class.create_from_sql(TEST_SQL).length).to eq(7)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/models/query_spec.rb b/plugins/discourse-data-explorer/spec/models/query_spec.rb
new file mode 100644
index 00000000000..e3c020399dc
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/models/query_spec.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::Query do
+ before { SiteSetting.data_explorer_enabled = true }
+
+ describe ".find" do
+ it "returns default queries" do
+ expect(DiscourseDataExplorer::Query.find(-1)).to be_present
+ end
+ end
+
+ describe "unscoped .find" do
+ it "returns default queries" do
+ expect(DiscourseDataExplorer::Query.unscoped.find(-1)).to be_present
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/report_generator_spec.rb b/plugins/discourse-data-explorer/spec/report_generator_spec.rb
new file mode 100644
index 00000000000..694be1fb7fc
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/report_generator_spec.rb
@@ -0,0 +1,333 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseDataExplorer::ReportGenerator do
+ fab!(:user)
+ fab!(:unauthorised_user) { Fabricate(:user) }
+ fab!(:unauthorised_group) { Fabricate(:group) }
+ fab!(:group) { Fabricate(:group, users: [user]) }
+
+ fab!(:query) { DiscourseDataExplorer::Query.find(-1) }
+
+ let(:query_params) { [%w[from_days_ago 0], %w[duration_days 15]] }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.authorized_extensions = "csv"
+ end
+
+ describe ".generate" do
+ it "returns [] if the recipient is not in query group" do
+ Fabricate(:query_group, query: query, group: group)
+ result =
+ described_class.generate(
+ query.id,
+ query_params,
+ [unauthorised_user.username, unauthorised_group.name],
+ )
+
+ expect(result).to eq []
+ end
+
+ it "returns a list of pms for authorised users" do
+ SiteSetting.personal_message_enabled_groups = group.id
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ result = described_class.generate(query.id, query_params, [user.username])
+
+ expect(result).to eq(
+ [
+ {
+ "title" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.title",
+ query_name: query.name,
+ ),
+ "target_usernames" => [user.username],
+ "raw" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: user.username,
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ),
+ },
+ ],
+ )
+ end
+
+ it "still returns a list of pms if a group or user does not exist" do
+ Fabricate(:query_group, query: query, group: group)
+
+ SiteSetting.personal_message_enabled_groups = group.id
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ result = described_class.generate(query.id, query_params, [group.name, "non-existent-group"])
+ expect(result).to eq(
+ [
+ {
+ "title" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.title",
+ query_name: query.name,
+ ),
+ "target_group_names" => [group.name],
+ "raw" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: group.name,
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ),
+ },
+ ],
+ )
+ end
+
+ it "works with email recipients" do
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ email = "[email protected]"
+ result = described_class.generate(query.id, query_params, [email])
+
+ expect(result).to eq(
+ [
+ {
+ "title" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.title",
+ query_name: query.name,
+ ),
+ "target_emails" => [email],
+ "raw" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: email,
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ),
+ },
+ ],
+ )
+ end
+
+ it "works with duplicate recipients" do
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ result = described_class.generate(query.id, query_params, [user.username, user.username])
+
+ expect(result).to eq(
+ [
+ {
+ "title" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.title",
+ query_name: query.name,
+ ),
+ "target_usernames" => [user.username],
+ "raw" =>
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: user.username,
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ),
+ },
+ ],
+ )
+ end
+
+ it "works with multiple recipient types" do
+ Fabricate(:query_group, query: query, group: group)
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+
+ result =
+ described_class.generate(
+ query.id,
+ query_params,
+ [group.name, user.username, "[email protected]"],
+ )
+
+ expect(result.length).to eq(3)
+ expect(result[0]["target_group_names"]).to eq([group.name])
+ expect(result[1]["target_usernames"]).to eq([user.username])
+ expect(result[2]["target_emails"]).to eq(["[email protected]"])
+ end
+
+ describe "with users_from_group" do
+ fab!(:valid_group) { Fabricate(:group, users: [user]) }
+ fab!(:invalid_group) { Fabricate(:group, users: []) }
+
+ describe "when true" do
+ let(:opts) { { users_from_group: true } }
+
+ it "does not work when no query groups are set" do
+ result = described_class.generate(query.id, query_params, [group.name], opts)
+ expect(result).to eq []
+ end
+
+ it "works when user is a member of automation group and query group" do
+ Fabricate(:query_group, query: query, group: valid_group)
+ result = described_class.generate(query.id, query_params, [group.name], opts)
+
+ expect(result.length).to eq(1)
+ expect(result[0]["target_usernames"]).to eq([user.username])
+ end
+
+ it "does not work when user is a member of automation group but not query group" do
+ Fabricate(:query_group, query: query, group: invalid_group)
+ result = described_class.generate(query.id, query_params, [group.name], opts)
+
+ expect(result).to eq []
+ end
+
+ it "works when user has access to one group in query groups" do
+ Fabricate(:query_group, query: query, group: valid_group)
+ Fabricate(:query_group, query: query, group: invalid_group)
+
+ result = described_class.generate(query.id, query_params, [group.name], opts)
+
+ expect(result.length).to eq(1)
+ expect(result[0]["target_usernames"]).to eq([user.username])
+ end
+ end
+
+ describe "when false" do
+ let(:opts) { { users_from_group: false } }
+
+ it "works when group has query access" do
+ Fabricate(:query_group, query: query, group: group)
+ result = described_class.generate(query.id, query_params, [group.name], opts)
+
+ expect(result.length).to eq(1)
+ expect(result[0]["target_group_names"]).to eq([group.name])
+ end
+
+ it "doesn't work when group doesn't have query access" do
+ result = described_class.generate(query.id, query_params, [group.name], opts)
+
+ expect(result).to eq []
+ end
+ end
+ end
+
+ it "works with attached csv file" do
+ SiteSetting.personal_message_enabled_groups = group.id
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ result =
+ described_class.generate(query.id, query_params, [user.username], { attach_csv: true })
+
+ filename =
+ "#{query.slug}@#{Slug.for(Discourse.current_hostname, "discourse")}-#{Date.today}.dcqresult.csv"
+
+ expect(result[0]["raw"]).to eq(
+ I18n.t(
+ "data_explorer.report_generator.private_message.body",
+ recipient_name: user.username,
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ) + "\n\n" +
+ I18n.t(
+ "data_explorer.report_generator.upload_appendix",
+ filename: filename,
+ short_url: Upload.find_by(original_filename: filename).short_url,
+ ),
+ )
+ end
+ end
+
+ describe ".generate_post" do
+ it "works without attached csv file" do
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ result = described_class.generate_post(query.id, query_params)
+
+ expect(result["raw"]).to eq(
+ I18n.t(
+ "data_explorer.report_generator.post.body",
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ),
+ )
+ end
+
+ it "works with attached csv file" do
+ DiscourseDataExplorer::ResultToMarkdown.expects(:convert).returns("le table")
+ freeze_time
+
+ result = described_class.generate_post(query.id, query_params, { attach_csv: true })
+
+ filename =
+ "#{query.slug}@#{Slug.for(Discourse.current_hostname, "discourse")}-#{Date.today}.dcqresult.csv"
+
+ expect(result["raw"]).to eq(
+ I18n.t(
+ "data_explorer.report_generator.post.body",
+ query_name: query.name,
+ table: "le table",
+ base_url: Discourse.base_url,
+ query_id: query.id,
+ created_at: Time.zone.now.strftime("%Y-%m-%d at %H:%M:%S"),
+ timezone: Time.zone.name,
+ ) + "\n\n" +
+ I18n.t(
+ "data_explorer.report_generator.upload_appendix",
+ filename: filename,
+ short_url: Upload.find_by(original_filename: filename).short_url,
+ ),
+ )
+ end
+ end
+
+ describe ".params_to_hash" do
+ context "when passing nothing" do
+ let(:query_params) { "[]" }
+
+ it { expect(described_class.params_to_hash(query_params)).to eq({}) }
+ end
+
+ context "when passing an array of arrays" do
+ let(:query_params) { '[["foo", 1], ["bar", 2]]' }
+
+ it { expect(described_class.params_to_hash(query_params)).to eq({ "foo" => 1, "bar" => 2 }) }
+ end
+
+ context "when passing an array of hashes" do
+ let(:query_params) { '[{ "key": "foo", "value": 1 }, { "key": "bar", "value": 2 }]' }
+
+ it { expect(described_class.params_to_hash(query_params)).to eq({ "foo" => 1, "bar" => 2 }) }
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/requests/group_spec.rb b/plugins/discourse-data-explorer/spec/requests/group_spec.rb
new file mode 100644
index 00000000000..96fa8602837
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/requests/group_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe "Data explorer group serializer additions" do
+ fab!(:group_user) { Fabricate(:user) }
+ fab!(:other_user) { Fabricate(:user) }
+ fab!(:group)
+ let!(:query) { DiscourseDataExplorer::Query.create!(name: "My query", sql: "") }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ group.add(group_user)
+ DiscourseDataExplorer::QueryGroup.create!(group: group, query: query)
+ end
+
+ it "query boolean is true for group user" do
+ sign_in group_user
+ get "/g/#{group.name}.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["group"]["has_visible_data_explorer_queries"]).to eq(true)
+ end
+
+ it "query boolean is false for group user when there are no queries" do
+ query.destroy!
+ sign_in group_user
+ get "/g/#{group.name}.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["group"]["has_visible_data_explorer_queries"]).to eq(false)
+ end
+
+ it "does not include query boolean for anon" do
+ get "/g/#{group.name}.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["group"]["has_visible_data_explorer_queries"]).to eq(nil)
+ end
+
+ it "does not include query boolean for non-group user" do
+ sign_in other_user
+ get "/g/#{group.name}.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["group"]["has_visible_data_explorer_queries"]).to eq(nil)
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb b/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb
new file mode 100644
index 00000000000..6e7080e19fa
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb
@@ -0,0 +1,577 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseDataExplorer::QueryController do
+ def response_json
+ response.parsed_body
+ end
+
+ before { SiteSetting.data_explorer_enabled = true }
+
+ def make_query(sql, opts = {}, group_ids = [])
+ query =
+ DiscourseDataExplorer::Query.create!(
+ name: opts[:name] || "Query number",
+ description: "A description for query number",
+ sql: sql,
+ hidden: opts[:hidden] || false,
+ )
+ group_ids.each { |group_id| query.query_groups.create!(group_id: group_id) }
+ query
+ end
+
+ describe "Admin" do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ describe "when disabled" do
+ before { SiteSetting.data_explorer_enabled = false }
+
+ it "denies every request" do
+ get "/admin/plugins/explorer/queries.json"
+ expect(response.status).to eq(404)
+
+ get "/admin/plugins/explorer/schema.json"
+ expect(response.status).to eq(404)
+
+ get "/admin/plugins/explorer/queries/3.json"
+ expect(response.status).to eq(404)
+
+ post "/admin/plugins/explorer/queries.json", params: { id: 3 }
+ expect(response.status).to eq(404)
+
+ post "/admin/plugins/explorer/queries/3/run.json"
+ expect(response.status).to eq(404)
+
+ put "/admin/plugins/explorer/queries/3.json"
+ expect(response.status).to eq(404)
+
+ delete "/admin/plugins/explorer/queries/3.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "#index" do
+ it "behaves nicely with no user created queries" do
+ DiscourseDataExplorer::Query.destroy_all
+ get "/admin/plugins/explorer/queries.json"
+ expect(response.status).to eq(200)
+ expect(response_json["queries"].count).to eq(DiscourseDataExplorer::Queries.default.count)
+ end
+
+ it "shows all available queries in alphabetical order" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", name: "B")
+ make_query("SELECT 1 as value", name: "A")
+ get "/admin/plugins/explorer/queries.json"
+ expect(response.status).to eq(200)
+ expect(response_json["queries"].length).to eq(
+ DiscourseDataExplorer::Queries.default.count + 2,
+ )
+ expect(response_json["queries"][0]["name"]).to eq("A")
+ expect(response_json["queries"][1]["name"]).to eq("B")
+ end
+
+ it "doesn't show hidden/deleted queries" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", name: "A", hidden: false)
+ make_query("SELECT 1 as value", name: "B", hidden: true)
+ make_query("SELECT 1 as value", name: "C", hidden: true)
+ get "/admin/plugins/explorer/queries.json"
+ expect(response.status).to eq(200)
+ expect(response_json["queries"].length).to eq(
+ DiscourseDataExplorer::Queries.default.count + 1,
+ )
+ end
+ end
+
+ describe "#update" do
+ fab!(:user2) { Fabricate(:user) }
+ fab!(:group2) { Fabricate(:group, users: [user2]) }
+
+ it "allows group to access system query" do
+ query = DiscourseDataExplorer::Query.find(-4)
+ put "/admin/plugins/explorer/queries/#{query.id}.json",
+ params: {
+ "query" => {
+ "name" => query.name,
+ "description" => query.description,
+ "sql" => query.sql,
+ "user_id" => query.user_id,
+ "created_at" => query.created_at,
+ "group_ids" => [group2.id],
+ "last_run_at" => query.last_run_at,
+ },
+ "id" => query.id,
+ }
+
+ expect(response.status).to eq(200)
+ end
+
+ it "returns a proper json error for invalid updates" do
+ query = DiscourseDataExplorer::Query.find(-4)
+ put "/admin/plugins/explorer/queries/#{query.id}",
+ params: {
+ "query" => {
+ "name" => "",
+ },
+ "id" => query.id,
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to eq(["Name can't be blank"])
+ end
+ end
+
+ describe "#run" do
+ def run_query(id, params = {}, explain = false)
+ params = Hash[params.map { |a| [a[0], a[1].to_s] }]
+ post "/admin/plugins/explorer/queries/#{id}/run.json",
+ params: {
+ params: params.to_json,
+ explain: explain,
+ }
+ end
+
+ it "can run queries" do
+ query = make_query("SELECT 23 as my_value")
+ run_query query.id
+ expect(response.status).to eq(200)
+ expect(response_json["success"]).to eq(true)
+ expect(response_json["errors"]).to eq([])
+ expect(response_json["columns"]).to eq(["my_value"])
+ expect(response_json["rows"]).to eq([[23]])
+ expect(response_json["explain"]).to be_nil
+ end
+
+ it "can run and explain queries" do
+ query = make_query("SELECT 23 as my_value")
+ run_query query.id, {}, true
+ expect(response.status).to eq(200)
+ expect(response_json["success"]).to eq(true)
+ expect(response_json["errors"]).to eq([])
+ expect(response_json["columns"]).to eq(["my_value"])
+ expect(response_json["rows"]).to eq([[23]])
+ expect(response_json["explain"]).to match("Result ")
+ end
+
+ it "can process parameters" do
+ query = make_query <<~SQL
+ -- [params]
+ -- int :foo = 34
+ SELECT :foo as my_value
+ SQL
+
+ run_query query.id, foo: 23
+ expect(response.status).to eq(200)
+ expect(response_json["errors"]).to eq([])
+ expect(response_json["success"]).to eq(true)
+ expect(response_json["columns"]).to eq(["my_value"])
+ expect(response_json["rows"]).to eq([[23]])
+
+ run_query query.id
+ expect(response.status).to eq(200)
+ expect(response_json["errors"]).to eq([])
+ expect(response_json["success"]).to eq(true)
+ expect(response_json["columns"]).to eq(["my_value"])
+ expect(response_json["rows"]).to eq([[34]])
+
+ # 2.3 is not an integer
+ run_query query.id, foo: "2.3"
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/ValidationError/)
+ end
+
+ context "when rate limited" do
+ def unlimited_request(query_id, headers = {})
+ post "/admin/plugins/explorer/queries/#{query_id}/run.json",
+ params: {
+ params: {}.to_json,
+ },
+ headers: headers
+
+ expect(response.status).to eq(200)
+ end
+
+ def limited_request(query_id, headers = {})
+ post "/admin/plugins/explorer/queries/#{query_id}/run.json",
+ params: {
+ params: {}.to_json,
+ },
+ headers: headers
+
+ expect(response.status).to eq(429)
+ expect(response.parsed_body["extras"]).to eq(
+ { "wait_seconds" => 9, "time_left" => "9 seconds" },
+ )
+ end
+
+ before { RateLimiter.enable }
+
+ it "limits query runs from API when using block mode" do
+ global_setting :max_data_explorer_api_reqs_per_10_seconds, 1
+ global_setting :max_data_explorer_api_req_mode, "block"
+
+ admin = Fabricate(:admin)
+ api_key = Fabricate(:api_key, user: admin)
+
+ query = make_query("SELECT 23 as my_value")
+
+ headers = { HTTP_API_KEY: api_key.key, HTTP_API_USERNAME: admin.username }
+
+ now = Time.now
+ freeze_time(now)
+
+ unlimited_request(query.id, headers)
+
+ freeze_time(now + 1.second)
+
+ limited_request(query.id, headers)
+
+ freeze_time(now + 10.seconds)
+
+ unlimited_request(query.id, headers)
+ end
+
+ it "does not limit query runs from API when using warn mode" do
+ global_setting :max_data_explorer_api_reqs_per_10_seconds, 1
+ global_setting :max_data_explorer_api_req_mode, "warn"
+
+ admin = Fabricate(:admin)
+ api_key = Fabricate(:api_key, user: admin)
+
+ query = make_query("SELECT 23 as my_value")
+
+ headers = { HTTP_API_KEY: api_key.key, HTTP_API_USERNAME: admin.username }
+
+ freeze_time
+
+ unlimited_request(query.id, headers)
+
+ Discourse.expects(:warn).once
+
+ unlimited_request(query.id, headers)
+ end
+
+ it "does not limit query runs from UI" do
+ global_setting :max_data_explorer_api_reqs_per_10_seconds, 1
+ global_setting :max_data_explorer_api_req_mode, "block"
+
+ query = make_query("SELECT 23 as my_value")
+
+ freeze_time
+
+ unlimited_request(query.id)
+ unlimited_request(query.id)
+ end
+ end
+
+ it "doesn't allow you to modify the database #1" do
+ p = create_post
+
+ query = make_query <<~SQL
+ UPDATE posts SET cooked = '<p>you may already be a winner!</p>' WHERE id = #{p.id}
+ RETURNING id
+ SQL
+
+ run_query query.id
+ p.reload
+
+ # Manual Test - comment out the following lines:
+ # DB.exec "SET TRANSACTION READ ONLY"
+ # raise ActiveRecord::Rollback
+ # This test should fail on the below check.
+ expect(p.cooked).to_not match(/winner/)
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/read-only transaction/)
+ end
+
+ it "doesn't allow you to modify the database #2" do
+ p = create_post
+
+ query = make_query <<~SQL
+ SELECT 1
+ )
+ SELECT * FROM query;
+ RELEASE SAVEPOINT active_record_1;
+ SET TRANSACTION READ WRITE;
+ UPDATE posts SET cooked = '<p>you may already be a winner!</p>' WHERE id = #{p.id};
+ SAVEPOINT active_record_1;
+ SET TRANSACTION READ ONLY;
+ WITH query AS (
+ SELECT 1
+ SQL
+
+ run_query query.id
+ p.reload
+
+ # Manual Test - change out the following line:
+ #
+ # module ::DiscourseDataExplorer
+ # def self.run_query(...)
+ # if query.sql =~ /;/
+ #
+ # to
+ #
+ # if false && query.sql =~ /;/
+ #
+ # Afterwards, this test should fail on the below check.
+ expect(p.cooked).to_not match(/winner/)
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/semicolon/)
+ end
+
+ it "doesn't allow you to lock rows" do
+ query = make_query <<~SQL
+ SELECT id FROM posts FOR UPDATE
+ SQL
+
+ run_query query.id
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/read-only transaction/)
+ end
+
+ it "doesn't allow you to create a table" do
+ query = make_query <<~SQL
+ CREATE TABLE mytable (id serial)
+ SQL
+
+ run_query query.id
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/read-only transaction|syntax error/)
+ end
+
+ it "doesn't allow you to break the transaction" do
+ query = make_query <<~SQL
+ COMMIT
+ SQL
+
+ run_query query.id
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/syntax error/)
+
+ query.sql = <<~SQL
+ )
+ SQL
+
+ run_query query.id
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/syntax error/)
+
+ query.sql = <<~SQL
+ RELEASE SAVEPOINT active_record_1
+ SQL
+
+ run_query query.id
+ expect(response.status).to eq(422)
+ expect(response_json["errors"]).to_not eq([])
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"].first).to match(/syntax error/)
+ end
+
+ it "can export data in CSV format" do
+ query = make_query("SELECT 23 as my_value")
+ post "/admin/plugins/explorer/queries/#{query.id}/run.json", params: { download: 1 }
+ expect(response.status).to eq(200)
+ end
+
+ context "with the `limit` parameter" do
+ before do
+ create_post
+ create_post
+ create_post
+ end
+
+ it "should limit the results in JSON response" do
+ SiteSetting.data_explorer_query_result_limit = 2
+ query = make_query <<~SQL
+ SELECT id FROM posts
+ SQL
+
+ run_query query.id
+ expect(response_json["rows"].count).to eq(2)
+
+ post "/admin/plugins/explorer/queries/#{query.id}/run.json", params: { limit: 1 }
+ expect(response_json["rows"].count).to eq(1)
+
+ post "/admin/plugins/explorer/queries/#{query.id}/run.json", params: { limit: "ALL" }
+ expect(response_json["rows"].count).to eq(3)
+ end
+
+ it "should limit the results in CSV download" do
+ begin
+ original_const = DiscourseDataExplorer::QUERY_RESULT_MAX_LIMIT
+ DiscourseDataExplorer.send(:remove_const, "QUERY_RESULT_MAX_LIMIT")
+ DiscourseDataExplorer.const_set("QUERY_RESULT_MAX_LIMIT", 2)
+
+ query = make_query <<~SQL
+ SELECT id FROM posts
+ SQL
+
+ post "/admin/plugins/explorer/queries/#{query.id}/run.csv", params: { download: 1 }
+ expect(response.body.split("\n").count).to eq(3)
+
+ post "/admin/plugins/explorer/queries/#{query.id}/run.csv",
+ params: {
+ download: 1,
+ limit: 1,
+ }
+ expect(response.body.split("\n").count).to eq(2)
+
+ # The value `ALL` is not supported in csv exports.
+ post "/admin/plugins/explorer/queries/#{query.id}/run.csv",
+ params: {
+ download: 1,
+ limit: "ALL",
+ }
+ expect(response.body.split("\n").count).to eq(1)
+ ensure
+ DiscourseDataExplorer.send(:remove_const, "QUERY_RESULT_MAX_LIMIT")
+ DiscourseDataExplorer.const_set("QUERY_RESULT_MAX_LIMIT", original_const)
+ end
+ end
+ end
+ end
+ end
+
+ describe "Non-Admin" do
+ fab!(:user)
+ fab!(:group) { Fabricate(:group, users: [user]) }
+
+ before { sign_in(user) }
+
+ describe "when disabled" do
+ before { SiteSetting.data_explorer_enabled = false }
+
+ it "denies every request" do
+ get "/g/1/reports.json"
+ expect(response.status).to eq(404)
+
+ get "/g/1/reports/1.json"
+ expect(response.status).to eq(404)
+
+ post "/g/1/reports/1/run.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ it "cannot access admin endpoints" do
+ query = make_query("SELECT 1 as value")
+ post "/admin/plugins/explorer/queries/#{query.id}/run.json"
+ expect(response.status).to eq(403)
+ end
+
+ describe "#group_reports_index" do
+ it "only returns queries that the group has access to" do
+ group.add(user)
+ make_query("SELECT 1 as value", { name: "A" }, ["#{group.id}"])
+
+ get "/g/#{group.name}/reports.json"
+ expect(response.status).to eq(200)
+ expect(response_json["queries"].length).to eq(1)
+ expect(response_json["queries"][0]["name"]).to eq("A")
+ end
+
+ it "returns a 404 when the user should not have access to the query " do
+ other_user = Fabricate(:user)
+ sign_in(other_user)
+
+ get "/g/#{group.name}/reports.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "return a 200 when the user has access the the query" do
+ group.add(user)
+
+ get "/g/#{group.name}/reports.json"
+ expect(response.status).to eq(200)
+ end
+
+ it "does not return hidden queries" do
+ group.add(user)
+ make_query("SELECT 1 as value", { name: "A", hidden: true }, ["#{group.id}"])
+ make_query("SELECT 1 as value", { name: "B" }, ["#{group.id}"])
+
+ get "/g/#{group.name}/reports.json"
+ expect(response.status).to eq(200)
+ expect(response_json["queries"].length).to eq(1)
+ expect(response_json["queries"][0]["name"]).to eq("B")
+ end
+ end
+
+ describe "#group_reports_run" do
+ it "runs the query" do
+ query = make_query("SELECT 1828 as value", { name: "B" }, ["#{group.id}"])
+
+ post "/g/#{group.name}/reports/#{query.id}/run.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq(true)
+ expect(response.parsed_body["columns"]).to eq(["value"])
+ expect(response.parsed_body["rows"]).to eq([[1828]])
+ end
+
+ it "returns a 404 when the user should not have access to the query " do
+ group.add(user)
+ query = make_query("SELECT 1 as value", {}, [])
+
+ post "/g/#{group.name}/reports/#{query.id}/run.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "return a 200 when the user has access the the query" do
+ group.add(user)
+ query = make_query("SELECT 1 as value", {}, [group.id.to_s])
+
+ post "/g/#{group.name}/reports/#{query.id}/run.json"
+ expect(response.status).to eq(200)
+ end
+
+ it "return a 404 when the query is hidden" do
+ group.add(user)
+ query = make_query("SELECT 1 as value", { hidden: true }, [group.id.to_s])
+
+ post "/g/#{group.name}/reports/#{query.id}/run.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "#group_reports_show" do
+ it "returns a 404 when the user should not have access to the query " do
+ query = make_query("SELECT 1 as value", {}, [])
+
+ get "/g/#{group.name}/reports/#{query.id}.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "return a 200 when the user has access the the query" do
+ query = make_query("SELECT 1 as value", {}, [group.id.to_s])
+
+ get "/g/#{group.name}/reports/#{query.id}.json"
+ expect(response.status).to eq(200)
+ end
+
+ it "return a 404 when the query is hidden" do
+ query = make_query("SELECT 1 as value", { hidden: true }, [group.id.to_s])
+
+ get "/g/#{group.name}/reports/#{query.id}.json"
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/result_format_converter_spec.rb b/plugins/discourse-data-explorer/spec/result_format_converter_spec.rb
new file mode 100644
index 00000000000..5ea2f24d2fd
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/result_format_converter_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+describe DiscourseDataExplorer::ResultFormatConverter do
+ fab!(:user)
+ fab!(:post)
+ fab!(:query) { DiscourseDataExplorer::Query.find(-1) }
+
+ let(:query_params) { [{ from_days_ago: 0 }, { duration_days: 15 }] }
+ let(:query_result) { DiscourseDataExplorer::DataExplorer.run_query(query, query_params) }
+
+ before { SiteSetting.data_explorer_enabled = true }
+
+ describe ".convert" do
+ context "for csv files" do
+ it "format results as a csv table with headers and columns" do
+ result = described_class.convert(:csv, query_result)
+
+ table = <<~CSV
+ liker_user_id,liked_user_id,count
+ CSV
+
+ expect(result).to include(table)
+ end
+ end
+
+ context "for json files" do
+ it "format results as a json file" do
+ result = described_class.convert(:json, query_result, { query_params: })
+
+ expect(result[:columns]).to contain_exactly("liker_user_id", "liked_user_id", "count")
+ expect(result[:params]).to eq(query_params)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/result_to_markdown_spec.rb b/plugins/discourse-data-explorer/spec/result_to_markdown_spec.rb
new file mode 100644
index 00000000000..3e581404459
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/result_to_markdown_spec.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+describe DiscourseDataExplorer::ResultToMarkdown do
+ fab!(:user)
+ fab!(:post)
+ fab!(:query) { DiscourseDataExplorer::Query.find(-1) }
+
+ let(:query_params) { [{ from_days_ago: 0 }, { duration_days: 15 }] }
+ let(:query_result) { DiscourseDataExplorer::DataExplorer.run_query(query, query_params) }
+
+ before { SiteSetting.data_explorer_enabled = true }
+
+ describe ".convert" do
+ it "format results as a markdown table with headers and columns" do
+ result = described_class.convert(query_result[:pg_result])
+
+ table = <<~MD
+ | liker_user | liked_user | count |
+ | :----- | :----- | :----- |
+ MD
+
+ expect(result).to include(table)
+ end
+
+ it "enriches result data within the table rows" do
+ PostActionCreator.new(user, post, PostActionType.types[:like]).perform
+ result = described_class.convert(query_result[:pg_result])
+
+ expect(result).to include(
+ "| #{user.username} (#{user.id}) | #{post.user.username} (#{post.user.id}) | 1 |\n",
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/system/bookmark_spec.rb b/plugins/discourse-data-explorer/spec/system/bookmark_spec.rb
new file mode 100644
index 00000000000..34395c92d59
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/bookmark_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+describe "Bookmarking reports attached to a group", type: :system do
+ fab!(:current_user) { Fabricate(:admin) }
+ fab!(:query_1) do
+ Fabricate(
+ :query,
+ name: "My query",
+ description: "Test query",
+ sql: "SELECT * FROM users",
+ user: current_user,
+ )
+ end
+ fab!(:group) { Fabricate(:group, name: "group") }
+ fab!(:group_user) { Fabricate(:group_user, user: current_user, group: group) }
+ fab!(:query_group_1) { Fabricate(:query_group, query: query_1, group: group) }
+ let(:bookmark_modal) { PageObjects::Modals::Bookmark.new }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ sign_in(current_user)
+ end
+
+ it "allows the user to bookmark a group report" do
+ visit("/g/group/reports/#{query_1.id}")
+ find(".query-group-bookmark").click
+ expect(bookmark_modal).to be_open
+ bookmark_modal.click_primary_button
+ expect(page).to have_css(".query-group-bookmark.bookmarked")
+ expect(Bookmark.exists?(user: current_user, bookmarkable: query_group_1)).to eq(true)
+ end
+
+ it "allows the user to edit and delete a group report bookmark" do
+ bookmark =
+ Fabricate(:bookmark, user: current_user, bookmarkable: query_group_1, reminder_at: nil)
+
+ visit("/g/group/reports/#{query_1.id}")
+ find(".query-group-bookmark").click
+ expect(bookmark_modal).to be_open
+ bookmark_modal.fill_name("Remember this query")
+ bookmark_modal.click_primary_button
+ expect(bookmark_modal).to be_closed
+ expect(bookmark.reload.name).to eq("Remember this query")
+
+ find(".query-group-bookmark").click
+ expect(bookmark_modal).to be_open
+ bookmark_modal.delete
+ expect(bookmark_modal).to be_closed
+ expect(page).not_to have_css(".query-group-bookmark.bookmarked")
+ expect(Bookmark.exists?(user: current_user, bookmarkable: query_group_1)).to eq(false)
+ end
+
+ it "shows bookmarked group reports in the user bookmark list" do
+ bookmark = Fabricate(:bookmark, user: current_user, bookmarkable: query_group_1)
+ visit("/u/#{current_user.username_lower}/activity/bookmarks")
+ expect(page.find(".bookmark-list")).to have_content("My query")
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/system/core_features_spec.rb b/plugins/discourse-data-explorer/spec/system/core_features_spec.rb
new file mode 100644
index 00000000000..db86db283bd
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/core_features_spec.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+RSpec.describe "Core features", type: :system do
+ before { enable_current_plugin }
+
+ it_behaves_like "having working core features"
+end
diff --git a/plugins/discourse-data-explorer/spec/system/explorer_spec.rb b/plugins/discourse-data-explorer/spec/system/explorer_spec.rb
new file mode 100644
index 00000000000..4449eb55823
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/explorer_spec.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+RSpec.describe "Explorer", type: :system, js: true do
+ fab!(:admin)
+ fab!(:group) { Fabricate(:group, name: "group") }
+ fab!(:group_user) { Fabricate(:group_user, user: admin, group: group) }
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ sign_in admin
+ end
+
+ context "with a query using a default param" do
+ fab!(:query_1) do
+ Fabricate(
+ :query,
+ name: "My default param query",
+ description: "Test default param query",
+ sql: "-- [params]\n-- string :limit = 42\n\nSELECT * FROM users LIMIT :limit",
+ user: admin,
+ )
+ end
+ fab!(:query_group_1) { Fabricate(:query_group, query: query_1, group: group) }
+
+ it "pre-fills the field with the default param" do
+ visit("/g/group/reports/#{query_1.id}")
+
+ expect(page).to have_field("limit", with: 42)
+ end
+
+ it "allows to edit custom name" do
+ visit("/admin/plugins/explorer/queries/#{query_1.id}")
+ find(".query-run .btn-primary").click
+ find(".edit-query-name").click
+ find(".name-text-field input").fill_in(with: "My custom name edited")
+ find(".btn-primary").click
+ find("button span", text: "Save Changes and Run").click
+ expect(page.find(".name h1")).to have_content("My custom name edited")
+ end
+ end
+
+ context "with the old url format" do
+ fab!(:query_1) do
+ Fabricate(
+ :query,
+ name: "My query",
+ description: "Test query",
+ sql: "SELECT * FROM users",
+ user: admin,
+ )
+ end
+
+ it "redirects to the new url format" do
+ visit("/admin/plugins/explorer/?id=#{query_1.id}")
+
+ expect(page).to have_current_path("/admin/plugins/explorer/queries/#{query_1.id}")
+ end
+
+ it "redirects to the new url format with params" do
+ visit("/admin/plugins/explorer/?id=#{query_1.id}&params=%7B%22limit%22%3A%2210%22%7D")
+
+ expect(page).to have_current_path(
+ "/admin/plugins/explorer/queries/#{query_1.id}?params=%7B%22limit%22%3A%2210%22%7D",
+ )
+ end
+ end
+
+ context "with a group_list param" do
+ fab!(:q2) do
+ Fabricate(
+ :query,
+ name: "My query with group_list",
+ description: "Test group_list query",
+ sql:
+ "-- [params]\n-- group_list :groups\n\nSELECT g.id,g.name FROM groups g WHERE g.name IN(:groups) ORDER BY g.name ASC",
+ user: admin,
+ )
+ end
+
+ it "supports setting a group_list param" do
+ visit(
+ "/admin/plugins/explorer/queries/#{q2.id}?params=%7B\"groups\"%3A\"admins%2Ctrust_level_1\"%7D",
+ )
+ find(".query-run .btn-primary").click
+
+ expect(page).to have_css(".query-results .result-header")
+
+ expect(page).to have_css(
+ ".query-results tbody tr:nth-child(1) td:nth-child(2)",
+ text: "admins",
+ )
+ expect(page).to have_css(
+ ".query-results tbody tr:nth-child(2) td:nth-child(2)",
+ text: "trust_level_1",
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/system/param_input_spec.rb b/plugins/discourse-data-explorer/spec/system/param_input_spec.rb
new file mode 100644
index 00000000000..fe6efdd2a47
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/param_input_spec.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+RSpec.describe "Param input", type: :system, js: true do
+ ALL_PARAMS_SQL = <<~SQL
+ -- [params]
+ -- int :int
+ -- bigint :bigint
+ -- boolean :boolean
+ -- null boolean :boolean_three
+ -- string :string
+ -- date :date
+ -- time :time
+ -- datetime :datetime
+ -- double :double
+ -- string :inet
+ -- user_id :user_id
+ -- post_id :post_id
+ -- topic_id :topic_id
+ -- int_list :int_list
+ -- string_list :string_list
+ -- category_id :category_id
+ -- group_id :group_id
+ -- group_list :group_list
+ -- user_list :mul_users
+ -- int :int_with_default = 3
+ -- bigint :bigint_with_default = 12345678912345
+ -- boolean :boolean
+ -- null boolean :boolean_three_with_default = #null
+ -- boolean :boolean_with_default = true
+ -- string :string_with_default = little bunny foo foo
+ -- date :date_with_default = 14 jul 2015
+ -- time :time_with_default = 5:02 pm
+ -- datetime :datetime_with_default = 14 jul 2015 5:02 pm
+ -- double :double_with_default = 3.1415
+ -- string :inet_with_default = 127.0.0.1/8
+ -- user_id :user_id_with_default = system
+ -- post_id :post_id_with_default = http://localhost:3000/t/adsfdsfajadsdafdsds-sf-awerjkldfdwe/21/1?u=system
+ -- topic_id :topic_id_with_default = /t/-/21
+ -- int_list :int_list_with_default = 1,2,3
+ -- string_list :string_list_with_default = a,b,c
+ -- category_id :category_id_with_default = general
+ -- group_id :group_id_with_default = staff
+ -- group_list :group_list_with_default = trust_level_0,trust_level_1
+ -- user_list :mul_users_with_default = system,discobot
+ SELECT 1
+ SQL
+
+ fab!(:current_user) { Fabricate(:admin) }
+ fab!(:all_params_query) do
+ Fabricate(
+ :query,
+ name: "All params query",
+ description: "",
+ sql: ALL_PARAMS_SQL,
+ user: current_user,
+ )
+ end
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ sign_in(current_user)
+ end
+
+ it "correctly displays parameter input boxes" do
+ visit("/admin/plugins/explorer/queries/#{all_params_query.id}")
+
+ ::DiscourseDataExplorer::Parameter
+ .create_from_sql(ALL_PARAMS_SQL)
+ .each do |param|
+ expect(page).to have_css(".query-params .param [name=\"#{param.identifier}\"]")
+
+ # select-kit fields
+ ignore_fields = %i[user_id post_id topic_id category_id group_id group_list user_list]
+
+ if param.default.present? && ignore_fields.exclude?(param.type)
+ expect(page).to have_field(
+ param.identifier,
+ with: simple_normalize(param.type, param.default),
+ )
+ end
+ end
+ end
+end
+
+def simple_normalize(type, value)
+ case type
+ when :date
+ value.to_date.to_s
+ when :time
+ value.to_time.strftime("%H:%M")
+ when :datetime
+ value.to_datetime.strftime("%Y-%m-%dT%H:%M")
+ when :boolean
+ value == "#null" ? "#null" : value ? "on" : "off"
+ when :boolean_three
+ value == "#null" ? "#null" : value ? "Y" : "N"
+ else
+ value.to_s
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/system/reports_spec.rb b/plugins/discourse-data-explorer/spec/system/reports_spec.rb
new file mode 100644
index 00000000000..a0da064d7e3
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/reports_spec.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+RSpec.describe "Reports", type: :system, js: true do
+ fab!(:group) { Fabricate(:group, name: "group") }
+ fab!(:user) { Fabricate(:admin) }
+ fab!(:group_user) { Fabricate(:group_user, user: user, group: group) }
+ fab!(:query_1) do
+ Fabricate(
+ :query,
+ name: "My First Query",
+ description: "This is the description of my 1st query.",
+ sql: "SELECT * FROM users limit 1",
+ user: user,
+ )
+ end
+ fab!(:query_2) do
+ Fabricate(
+ :query,
+ name: "My Second Query",
+ description: "This is my 2nd query's description.",
+ sql: "SELECT * FROM users limit 1",
+ user: user,
+ )
+ end
+ fab!(:query_group_1) { Fabricate(:query_group, query: query_1, group: group) }
+ fab!(:query_group_2) { Fabricate(:query_group, query: query_2, group: group) }
+
+ before { SiteSetting.data_explorer_enabled = true }
+
+ it "allows user to switch between reports" do
+ sign_in(user)
+ visit("/g/group/reports/#{query_2.id}")
+ expect(find(".user-content h1")).to have_content("My Second Query")
+ expect(page).not_to have_css(".query-results .result-header")
+ find(".query-run .btn-primary").click
+ expect(page).to have_css(".query-results .result-header")
+
+ find(".group-reports-nav-item-outlet a").click
+ all(".group-reports a ").last.click
+ expect(find(".user-content h1")).to have_content("My Second Query")
+ expect(page).not_to have_css(".query-results .result-header")
+ find(".query-run .btn-primary").click
+ expect(page).to have_css(".query-results .result-header")
+ end
+
+ it "allows user to run a report with a JSON column and open a fullscreen code viewer" do
+ Fabricate(:reviewable_queued_post)
+ sql = <<~SQL
+ SELECT id, payload FROM reviewables LIMIT 10
+ SQL
+ json_query = DiscourseDataExplorer::Query.create!(name: "some query", sql: sql)
+ sign_in(user)
+ visit("/g/group/reports/#{json_query.id}")
+ find(".query-run .btn-primary").click
+ expect(page).to have_css(".query-results .result-json")
+ first(".query-results .result-json .btn.result-json-button").click
+ expect(page).to have_css(".fullscreen-code-modal")
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/tasks/data_explorer_spec.rb b/plugins/discourse-data-explorer/spec/tasks/data_explorer_spec.rb
new file mode 100644
index 00000000000..d7ec62e0bd3
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/tasks/data_explorer_spec.rb
@@ -0,0 +1,188 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe "Data Explorer rake tasks" do
+ before do
+ Rake::Task.clear
+ Discourse::Application.load_tasks
+ end
+
+ def make_query(sql, opts = {}, group_ids = [])
+ query =
+ DiscourseDataExplorer::Query.create!(
+ id: opts[:id],
+ name: opts[:name] || "Query number",
+ description: "A description for query number",
+ sql: sql,
+ hidden: opts[:hidden] || false,
+ )
+ group_ids.each { |group_id| query.query_groups.create!(group_id: group_id) }
+ query
+ end
+
+ def hidden_queries
+ DiscourseDataExplorer::Query.where(hidden: true).order(:id)
+ end
+
+ describe "data_explorer" do
+ it "hides a single query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A")
+ make_query("SELECT 1 as value", id: 2, name: "B")
+ # rake data_explorer[1] => hide query with ID 1
+ silence_stdout { Rake::Task["data_explorer"].invoke(1) }
+
+ # Soft deletion: PluginStoreRow should not be modified
+ expect(DiscourseDataExplorer::Query.all.length).to eq(2)
+ # Array of hidden queries should have exactly 1 element
+ expect(hidden_queries.length).to eq(1)
+ # That one element should have the same ID as the one invoked to be hidden
+ expect(hidden_queries[0].id).to eq(1)
+ end
+
+ it "hides multiple queries" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A")
+ make_query("SELECT 1 as value", id: 2, name: "B")
+ make_query("SELECT 1 as value", id: 3, name: "C")
+ make_query("SELECT 1 as value", id: 4, name: "D")
+ # rake data_explorer[1,2,4] => hide queries with IDs 1, 2 and 4
+ silence_stdout { Rake::Task["data_explorer"].invoke(1, 2, 4) }
+
+ # Soft deletion: PluginStoreRow should not be modified
+ expect(DiscourseDataExplorer::Query.all.length).to eq(4)
+ # Array of hidden queries should have the same number of elements invoked to be hidden
+ expect(hidden_queries.length).to eq(3)
+ # The elements should have the same ID as the ones invoked to be hidden
+ expect(hidden_queries[0].id).to eq(1)
+ expect(hidden_queries[1].id).to eq(2)
+ expect(hidden_queries[2].id).to eq(4)
+ end
+
+ context "when query does not exist in PluginStore" do
+ it "should not hide the query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A")
+ make_query("SELECT 1 as value", id: 2, name: "B")
+ # rake data_explorer[3] => try to hide query with ID 3
+ silence_stdout { Rake::Task["data_explorer"].invoke(3) }
+ # rake data_explorer[3,4,5] => try to hide queries with IDs 3, 4 and 5
+ silence_stdout { Rake::Task["data_explorer"].invoke(3, 4, 5) }
+
+ # Array of hidden queries should be empty
+ expect(hidden_queries.length).to eq(0)
+ end
+ end
+ end
+
+ describe "#unhide_query" do
+ it "unhides a single query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A", hidden: true)
+ make_query("SELECT 1 as value", id: 2, name: "B", hidden: true)
+ # rake data_explorer:unhide_query[1] => unhide query with ID 1
+ silence_stdout { Rake::Task["data_explorer:unhide_query"].invoke(1) }
+
+ # Soft deletion: PluginStoreRow should not be modified
+ expect(DiscourseDataExplorer::Query.all.length).to eq(2)
+ # Array of hidden queries should have exactly 1 element
+ expect(hidden_queries.length).to eq(1)
+ # There should be one remaining element that is still hidden
+ expect(hidden_queries[0].id).to eq(2)
+ end
+
+ it "unhides multiple queries" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A", hidden: true)
+ make_query("SELECT 1 as value", id: 2, name: "B", hidden: true)
+ make_query("SELECT 1 as value", id: 3, name: "C", hidden: true)
+ make_query("SELECT 1 as value", id: 4, name: "D", hidden: true)
+ # rake data_explorer:unhide_query[1,2,4] => unhide queries with IDs 1, 2 and 4
+ silence_stdout { Rake::Task["data_explorer:unhide_query"].invoke(1, 2, 4) }
+
+ # Soft deletion: PluginStoreRow should not be modified
+ expect(DiscourseDataExplorer::Query.all.length).to eq(4)
+ # Array of hidden queries should have exactly 1 element
+ expect(hidden_queries.length).to eq(1)
+ # There should be one remaining element that is still hidden
+ expect(hidden_queries[0].id).to eq(3)
+ end
+
+ context "when query does not exist in PluginStore" do
+ it "should not unhide the query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A", hidden: true)
+ make_query("SELECT 1 as value", id: 2, name: "B", hidden: true)
+ # rake data_explorer:unhide_query[3] => try to unhide query with ID 3
+ silence_stdout { Rake::Task["data_explorer:unhide_query"].invoke(3) }
+ # rake data_explorer:unhide_query[3,4,5] => try to unhide queries with IDs 3, 4 and 5
+ silence_stdout { Rake::Task["data_explorer:unhide_query"].invoke(3, 4, 5) }
+
+ # Array of hidden queries shouldn't change
+ expect(hidden_queries.length).to eq(2)
+ end
+ end
+ end
+
+ describe "#hard_delete" do
+ it "hard deletes a single query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A", hidden: true)
+ make_query("SELECT 1 as value", id: 2, name: "B", hidden: true)
+ # rake data_explorer:hard_delete[1] => hard delete query with ID 1
+ silence_stdout { Rake::Task["data_explorer:hard_delete"].invoke(1) }
+
+ # Hard deletion: query list should be shorter by 1
+ expect(DiscourseDataExplorer::Query.all.length).to eq(1)
+ # Array of hidden queries should have exactly 1 element
+ expect(hidden_queries.length).to eq(1)
+ # There should be one remaining hidden element
+ expect(hidden_queries[0].id).to eq(2)
+ end
+
+ it "hard deletes multiple queries" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A", hidden: true)
+ make_query("SELECT 1 as value", id: 2, name: "B", hidden: true)
+ make_query("SELECT 1 as value", id: 3, name: "C", hidden: true)
+ make_query("SELECT 1 as value", id: 4, name: "D", hidden: true)
+ # rake data_explorer:hard_delete[1,2,4] => hard delete queries with IDs 1, 2 and 4
+ silence_stdout { Rake::Task["data_explorer:hard_delete"].invoke(1, 2, 4) }
+
+ # Hard deletion: query list should be shorter by 3
+ expect(DiscourseDataExplorer::Query.all.length).to eq(1)
+ # Array of hidden queries should have exactly 1 element
+ expect(hidden_queries.length).to eq(1)
+ # There should be one remaining hidden element
+ expect(hidden_queries[0].id).to eq(3)
+ end
+
+ context "when query does not exist in PluginStore" do
+ it "should not hard delete the query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A", hidden: true)
+ make_query("SELECT 1 as value", id: 2, name: "B", hidden: true)
+ # rake data_explorer:hard_delete[3] => try to hard delete query with ID 3
+ silence_stdout { Rake::Task["data_explorer:hard_delete"].invoke(3) }
+ # rake data_explorer:hard_delete[3,4,5] => try to hard delete queries with IDs 3, 4 and 5
+ silence_stdout { Rake::Task["data_explorer:hard_delete"].invoke(3, 4, 5) }
+
+ # Array of hidden queries shouldn't change
+ expect(hidden_queries.length).to eq(2)
+ end
+ end
+
+ context "when query is not hidden" do
+ it "should not hard delete the query" do
+ DiscourseDataExplorer::Query.destroy_all
+ make_query("SELECT 1 as value", id: 1, name: "A")
+ # rake data_explorer:hard_delete[1] => try to hard delete query with ID 1
+ silence_stdout { Rake::Task["data_explorer:hard_delete"].invoke(1) }
+
+ # List of queries shouldn't change
+ expect(DiscourseDataExplorer::Query.all.length).to eq(1)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb b/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb
new file mode 100644
index 00000000000..af4cee81a1b
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb
@@ -0,0 +1,148 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe "fix query ids rake task" do
+ before do
+ Rake::Task.clear
+ Discourse::Application.load_tasks
+ end
+
+ let(:query_name) { "Awesome query" }
+
+ it "fixes the ID of the query if they share the same name" do
+ original_query_id = 4
+ create_plugin_store_row(query_name, original_query_id)
+ create_query(query_name)
+
+ run_task
+
+ expect(find(query_name).id).to eq(original_query_id)
+ end
+
+ it "only fixes queries with unique name" do
+ original_query_id = 4
+ create_plugin_store_row(query_name, original_query_id)
+ create_query(query_name)
+ create_query(query_name)
+
+ run_task
+
+ expect(find(query_name).id).not_to eq(original_query_id)
+ end
+
+ it "skips queries that already have the same ID" do
+ db_query = create_query(query_name)
+ last_updated_at = db_query.updated_at
+ create_plugin_store_row(query_name, db_query.id)
+
+ run_task
+
+ expect(find(query_name).updated_at).to eq_time(last_updated_at)
+ end
+
+ it "keeps queries the rest of the queries" do
+ original_query_id = 4
+ different_query_name = "Another query"
+ create_plugin_store_row(query_name, original_query_id)
+ create_query(query_name)
+ create_query(different_query_name)
+
+ run_task
+
+ expect(find(different_query_name)).not_to be_nil
+ end
+
+ it "works even if they are additional conflicts" do
+ different_query_name = "Another query"
+ additional_conflict = create_query(different_query_name)
+ create_query(query_name)
+ create_plugin_store_row(query_name, additional_conflict.id)
+
+ run_task
+
+ expect(find(different_query_name).id).not_to eq(additional_conflict.id)
+ expect(find(query_name).id).to eq(additional_conflict.id)
+ end
+
+ describe "query groups" do
+ let(:group) { Fabricate(:group) }
+
+ it "fixes the query group's query_id" do
+ original_query_id = 4
+ create_query(query_name, [group.id])
+ create_plugin_store_row(query_name, original_query_id, [group.id])
+
+ run_task
+
+ expect(find_query_group(original_query_id)).not_to be_nil
+ end
+
+ it "works with additional conflicts" do
+ different_query_name = "Another query"
+ additional_conflict = create_query(different_query_name, [group.id])
+ create_query(query_name, [group.id])
+ create_plugin_store_row(query_name, additional_conflict.id, [group.id])
+
+ run_task
+
+ conflict = find(different_query_name).query_groups.first
+ fixed = find_query_group(additional_conflict.id)
+
+ expect(conflict.query_id).not_to eq(additional_conflict.id)
+ expect(fixed.query_id).to eq(additional_conflict.id)
+ end
+
+ def find_query_group(id)
+ DiscourseDataExplorer::QueryGroup.find_by(query_id: id)
+ end
+ end
+
+ it "changes the serial sequence for future queries" do
+ original_query_id = 4
+ create_plugin_store_row(query_name, original_query_id)
+ create_query(query_name)
+
+ run_task
+ post_fix_query = create_query(query_name)
+
+ expect(post_fix_query.id).to eq(original_query_id + 1)
+ end
+
+ def run_task
+ Rake::Task["data_explorer:fix_query_ids"].invoke
+ end
+
+ def create_plugin_store_row(name, id, group_ids = [])
+ key = "q:#{id}"
+
+ PluginStore.set(
+ DiscourseDataExplorer::PLUGIN_NAME,
+ key,
+ attributes(name).merge(group_ids: group_ids, id: id),
+ )
+ end
+
+ def create_query(name, group_ids = [])
+ DiscourseDataExplorer::Query
+ .create!(attributes(name))
+ .tap { |query| group_ids.each { |group_id| query.query_groups.create!(group_id: group_id) } }
+ end
+
+ def attributes(name)
+ {
+ id:
+ DiscourseDataExplorer::Query.count == 0 ? 5 : DiscourseDataExplorer::Query.maximum(:id) + 1,
+ name: name,
+ description: "A Query",
+ sql: "SELECT 1",
+ created_at: 3.hours.ago,
+ last_run_at: 1.hour.ago,
+ hidden: false,
+ }
+ end
+
+ def find(name)
+ DiscourseDataExplorer::Query.find_by(name: name)
+ end
+end
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/list-queries-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/list-queries-test.js
new file mode 100644
index 00000000000..af74c99cdb5
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/list-queries-test.js
@@ -0,0 +1,74 @@
+import { visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
+
+acceptance("Data Explorer Plugin | List Queries", function (needs) {
+ needs.user();
+ needs.settings({ data_explorer_enabled: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/plugins/explorer/groups.json", () => {
+ return helper.response([]);
+ });
+
+ server.get("/admin/plugins/explorer/queries", () => {
+ return helper.response({
+ queries: [
+ {
+ id: -5,
+ name: "Top 100 Active Topics",
+ description:
+ "based on the number of replies, it accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-08T15:37:49.188Z",
+ user_id: -1,
+ },
+ {
+ id: -6,
+ name: "Top 100 Likers",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ user_id: -1,
+ },
+ ],
+ });
+ });
+ });
+
+ test("renders the page with the list of queries", async function (assert) {
+ await visit("/admin/plugins/explorer");
+
+ assert
+ .dom("div.query-list input.ember-text-field")
+ .hasAttribute(
+ "placeholder",
+ i18n("explorer.search_placeholder"),
+ "the search box was rendered"
+ );
+
+ assert
+ .dom("div.query-list button.btn-icon svg.d-icon-plus")
+ .exists("the add query button was rendered");
+
+ assert
+ .dom("div.query-list button.btn-icon-text span.d-button-label")
+ .hasText(i18n("explorer.import.label"), "the import button was rendered");
+
+ assert
+ .dom("div.container table.recent-queries tbody tr")
+ .exists({ count: 2 }, "the list of queries was rendered");
+
+ assert
+ .dom("div.container table.recent-queries tbody tr:nth-child(1) td a")
+ .hasText(/^\s*Top 100 Likers/, "The first query was rendered");
+
+ assert
+ .dom("div.container table.recent-queries tbody tr:nth-child(2) td a")
+ .hasText(/^\s*Top 100 Active Topics/, "The second query was rendered");
+ });
+});
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js
new file mode 100644
index 00000000000..344f8a581bd
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js
@@ -0,0 +1,88 @@
+import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Data Explorer Plugin | New Query", function (needs) {
+ needs.user();
+ needs.settings({ data_explorer_enabled: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/plugins/explorer/groups.json", () => {
+ return helper.response([]);
+ });
+
+ server.get("/admin/plugins/explorer/schema.json", () => {
+ return helper.response({});
+ });
+
+ server.get("/admin/plugins/explorer/queries", () => {
+ return helper.response({
+ queries: [],
+ });
+ });
+
+ server.post("/admin/plugins/explorer/queries", () => {
+ return helper.response({
+ query: {
+ id: -15,
+ sql: "-- [params]\n-- int :months_ago = 1\n\nWITH query_period AS\n(SELECT date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' AS period_start,\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' AS period_end)\nSELECT t.id AS topic_id,\n t.category_id,\n COUNT(p.id) AS reply_count\nFROM topics t\nJOIN posts p ON t.id = p.topic_id\nJOIN query_period qp ON p.created_at >= qp.period_start\nAND p.created_at <= qp.period_end\nWHERE t.archetype = 'regular'\nAND t.user_id > 0\nGROUP BY t.id\nORDER BY COUNT(p.id) DESC, t.score DESC\nLIMIT 100\n",
+ name: "foo",
+ description:
+ "based on the number of replies, it accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ param_info: [
+ {
+ identifier: "months_ago",
+ type: "int",
+ default: "1",
+ nullable: false,
+ },
+ ],
+ created_at: "2021-02-05T16:42:45.572Z",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-08T15:37:49.188Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/-15", () => {
+ return helper.response({
+ query: {
+ id: -15,
+ sql: "-- [params]\n-- int :months_ago = 1\n\nWITH query_period AS\n(SELECT date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' AS period_start,\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' AS period_end)\nSELECT t.id AS topic_id,\n t.category_id,\n COUNT(p.id) AS reply_count\nFROM topics t\nJOIN posts p ON t.id = p.topic_id\nJOIN query_period qp ON p.created_at >= qp.period_start\nAND p.created_at <= qp.period_end\nWHERE t.archetype = 'regular'\nAND t.user_id > 0\nGROUP BY t.id\nORDER BY COUNT(p.id) DESC, t.score DESC\nLIMIT 100\n",
+ name: "foo",
+ description:
+ "based on the number of replies, it accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ param_info: [
+ {
+ identifier: "months_ago",
+ type: "int",
+ default: "1",
+ nullable: false,
+ },
+ ],
+ created_at: "2021-02-05T16:42:45.572Z",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-08T15:37:49.188Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+ });
+
+ test("creates a new query", async function (assert) {
+ await visit("/admin/plugins/explorer");
+
+ // select new query button
+ await click(".query-list button");
+ await fillIn(".query-create input", "foo");
+ // select create new query button
+ await click(".query-create button");
+
+ assert.strictEqual(currentURL(), "/admin/plugins/explorer/queries/-15");
+ });
+});
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js
new file mode 100644
index 00000000000..fd066555da7
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js
@@ -0,0 +1,432 @@
+import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import Category from "discourse/models/category";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+
+async function runQuery() {
+ await click("form.query-run button");
+}
+
+acceptance("Data Explorer Plugin | Param Input", function (needs) {
+ needs.user();
+ needs.settings({ data_explorer_enabled: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/plugins/explorer/groups.json", () => {
+ return helper.response([]);
+ });
+
+ server.get("/admin/plugins/explorer/schema.json", () => {
+ return helper.response({});
+ });
+
+ server.get("/admin/plugins/explorer/queries", () => {
+ return helper.response({
+ queries: [
+ {
+ id: -6,
+ name: "Top 100 Likers",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ user_id: -1,
+ },
+ {
+ id: -7,
+ name: "Invalid Query",
+ description: "",
+ username: "bianca",
+ group_ids: [],
+ last_run_at: "2022-01-14T16:47:34.244Z",
+ user_id: 1,
+ },
+ {
+ id: 3,
+ name: "Params test",
+ description: "test for params.",
+ username: "system",
+ group_ids: [41],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ user_id: -1,
+ },
+ ],
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/-6", () => {
+ return helper.response({
+ query: {
+ id: -6,
+ sql: "-- [params]\n-- int :months_ago = 1\n\nWITH query_period AS (\n SELECT\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end\n )\n\n SELECT\n ua.user_id,\n count(1) AS like_count\n FROM user_actions ua\n INNER JOIN query_period qp\n ON ua.created_at >= qp.period_start\n AND ua.created_at <= qp.period_end\n WHERE ua.action_type = 1\n GROUP BY ua.user_id\n ORDER BY like_count DESC\n LIMIT 100\n",
+ name: "Top 100 Likers",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ param_info: [
+ {
+ identifier: "months_ago",
+ type: "int",
+ default: "1",
+ nullable: false,
+ },
+ ],
+ created_at: "2021-02-02T12:21:11.449Z",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+
+ server.put("/admin/plugins/explorer/queries/-6", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 27.5,
+ result_count: 2,
+ columns: ["user_id", "like_count"],
+ default_limit: 1000,
+ relations: {
+ user: [
+ {
+ id: -2,
+ username: "discobot",
+ name: null,
+ avatar_template: "/user_avatar/localhost/discobot/{size}/2_2.png",
+ },
+ {
+ id: 2,
+ username: "andrey1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ ],
+ },
+ colrender: {
+ 0: "user",
+ },
+ rows: [
+ [-2, 2],
+ [2, 2],
+ ],
+ });
+ });
+
+ server.post("/admin/plugins/explorer/queries/-6/run", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 27.5,
+ result_count: 2,
+ params: { months_ago: "1" },
+ columns: ["user_id", "like_count"],
+ default_limit: 1000,
+ relations: {
+ user: [
+ {
+ id: -2,
+ username: "discobot",
+ name: null,
+ avatar_template: "/user_avatar/localhost/discobot/{size}/2_2.png",
+ },
+ {
+ id: 2,
+ username: "andrey1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ ],
+ },
+ colrender: {
+ 0: "user",
+ },
+ rows: [
+ [-2, 2],
+ [2, 2],
+ ],
+ });
+ });
+
+ server.get("/g/discourse/reports/-8", () => {
+ return helper.response({
+ query: {
+ id: -8,
+ sql: "-- [params]\n-- int :months_ago = 1\n\nWITH query_period AS (\n SELECT\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end\n )\n\n SELECT\n ua.user_id,\n count(1) AS like_count\n FROM user_actions ua\n INNER JOIN query_period qp\n ON ua.created_at >= qp.period_start\n AND ua.created_at <= qp.period_end\n WHERE ua.action_type = 1\n GROUP BY ua.user_id\n ORDER BY like_count DESC\n LIMIT 100\n",
+ name: "Top 100 Likers Report",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ param_info: [
+ {
+ identifier: "months_ago",
+ type: "int",
+ default: "1",
+ nullable: false,
+ },
+ ],
+ created_at: "2021-02-02T12:21:11.449Z",
+ username: "system",
+ group_ids: [41],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/-7", () => {
+ return helper.response({
+ query: {
+ id: -7,
+ sql: "-- [params]\n-- user_id :user\n\nSELECT :user_id\n\n",
+ name: "Invalid Query",
+ description: "",
+ param_info: [
+ {
+ identifier: "user",
+ type: "user_id",
+ default: null,
+ nullable: false,
+ },
+ ],
+ created_at: "2022-01-14T16:40:05.458Z",
+ username: "bianca",
+ group_ids: [],
+ last_run_at: "2022-01-14T16:47:34.244Z",
+ hidden: false,
+ user_id: 1,
+ },
+ });
+ });
+
+ server.post("/admin/plugins/explorer/queries/-7/run", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 27.5,
+ params: { user_id: "null" },
+ columns: ["user_id"],
+ default_limit: 1000,
+ relations: {
+ user: [
+ {
+ id: 2,
+ username: "andrey1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ ],
+ },
+ colrender: {
+ 0: "user",
+ },
+ rows: [],
+ });
+ });
+
+ server.post("/g/discourse/reports/-8/run", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 27.5,
+ result_count: 2,
+ params: { months_ago: "1" },
+ columns: ["user_id", "like_count"],
+ default_limit: 1000,
+ relations: {
+ user: [
+ {
+ id: -2,
+ username: "discobot",
+ name: null,
+ avatar_template: "/user_avatar/localhost/discobot/{size}/2_2.png",
+ },
+ {
+ id: 2,
+ username: "andrey1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ ],
+ },
+ colrender: {
+ 0: "user",
+ },
+ rows: [
+ [-2, 2],
+ [2, 2],
+ ],
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/3", () => {
+ return helper.response({
+ query: {
+ id: 3,
+ sql: "SELECT 1",
+ name: "Params test",
+ description: "test for params.",
+ param_info: [],
+ created_at: "2021-02-02T12:21:11.449Z",
+ username: "system",
+ group_ids: [41],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+
+ server.put("/admin/plugins/explorer/queries/3", () => {
+ return helper.response({
+ query: {
+ id: 3,
+ sql: "-- [params]\n-- int :months_ago = 1\n\nSELECT 1",
+ name: "Params test",
+ description: "test for params.",
+ param_info: [
+ {
+ identifier: "months_ago",
+ type: "int",
+ default: "1",
+ nullable: false,
+ },
+ ],
+ created_at: "2021-02-02T12:21:11.449Z",
+ username: "system",
+ group_ids: [41],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/4", () => {
+ return helper.response({
+ query: {
+ id: 4,
+ sql: "-- [params]\n-- null category_id :category\n\nSELECT 1",
+ name: "Params test - category_id chooser",
+ description: "Test for category_id param.",
+ param_info: [
+ {
+ identifier: "category",
+ type: "category_id",
+ default: null,
+ nullable: true,
+ },
+ ],
+ created_at: "2025-06-03T09:05:59.337Z",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2025-06-03T09:05:59.337Z",
+ hidden: false,
+ category_id: null,
+ },
+ });
+ });
+
+ server.post("/admin/plugins/explorer/queries/4/run", () => {
+ return helper.response({});
+ });
+ });
+
+ function getSearchParam(param) {
+ const searchParams = new URLSearchParams(currentURL().split("?")[1]);
+ return JSON.parse(searchParams.get("params"))[param];
+ }
+
+ test("puts params for the query into the url", async function (assert) {
+ await visit("/admin/plugins/explorer/queries/-6");
+ const monthsAgoValue = "2";
+ await fillIn(".query-params input", monthsAgoValue);
+ await runQuery();
+
+ assert.strictEqual(getSearchParam("months_ago"), monthsAgoValue);
+ });
+
+ test("puts params for the query into the url for group reports", async function (assert) {
+ await visit("/g/discourse/reports/-8");
+ const monthsAgoValue = "2";
+ await fillIn(".query-params input", monthsAgoValue);
+ await runQuery();
+
+ assert.strictEqual(getSearchParam("months_ago"), monthsAgoValue);
+ });
+
+ test("loads the page if one of the parameter is null", async function (assert) {
+ await visit('/admin/plugins/explorer/queries/-7?params={"user":null}');
+ assert.dom(".query-params .user-chooser").exists();
+ assert.dom(".query-run .btn.btn-primary").exists();
+ });
+
+ test("loads the page if one of the parameter is null for group reports", async function (assert) {
+ await visit('/g/discourse/reports/-8?params={"months_ago":null}');
+ assert.dom(".query-params input").exists();
+ assert.dom(".query-run .btn.btn-primary").exists();
+ });
+
+ test("applies params when running a report", async function (assert) {
+ await visit("/g/discourse/reports/-8");
+ const monthsAgoValue = "2";
+ await fillIn(".query-params input", monthsAgoValue);
+ await runQuery();
+ assert.dom(".query-params input").hasValue(monthsAgoValue);
+ });
+
+ test("creates input boxes if has parameters when save", async function (assert) {
+ await visit("/admin/plugins/explorer/queries/3");
+ assert.dom(".query-params input").doesNotExist();
+ await click(".query-edit .btn-edit-query");
+ await fillIn(
+ ".query-editor .ace_text-input",
+ "-- [params]\n-- int :months_ago = 1\n\nSELECT 1"
+ );
+ await click(".query-editor .ace_text-input"); // enables `Save Changes` button
+ await click(".query-edit .btn-save-query");
+ assert.dom(".query-params input").exists();
+ });
+
+ test("nullable category_id param", async function (assert) {
+ await visit("/admin/plugins/explorer/queries/4");
+ const catChooser = selectKit(".category-chooser");
+
+ assert.strictEqual(catChooser.header().value(), null);
+
+ await runQuery();
+
+ assert.strictEqual(getSearchParam("category"), "");
+
+ const category = Category.findById(6);
+ await catChooser.expand();
+ await catChooser.selectRowByValue(category.id);
+
+ assert.strictEqual(catChooser.header().label(), category.name);
+
+ await runQuery();
+
+ assert.strictEqual(
+ getSearchParam("category"),
+ category.id.toString(),
+ "it updates the URL with the selected category id"
+ );
+
+ await catChooser.expand();
+ await catChooser.selectRowByIndex(0);
+ await runQuery();
+
+ assert.strictEqual(
+ getSearchParam("category"),
+ undefined,
+ "it removes the category id from the URL when selecting the first row (null value)"
+ );
+ });
+});
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js
new file mode 100644
index 00000000000..acb301be517
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js
@@ -0,0 +1,345 @@
+/* eslint-disable qunit/no-loose-assertions */
+import { click, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import sinon from "sinon";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
+
+acceptance("Data Explorer Plugin | Run Query", function (needs) {
+ needs.user();
+ needs.settings({ data_explorer_enabled: true });
+
+ needs.hooks.beforeEach(() => {
+ sinon.stub(window, "open");
+ });
+
+ needs.hooks.afterEach(() => {
+ window.open.restore();
+ });
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/plugins/explorer/groups.json", () => {
+ return helper.response([
+ {
+ id: 1,
+ name: "admins",
+ },
+ {
+ id: 2,
+ name: "moderators",
+ },
+ {
+ id: 3,
+ name: "staff",
+ },
+ {
+ id: 0,
+ name: "everyone",
+ },
+ {
+ id: 10,
+ name: "trust_level_0",
+ },
+ {
+ id: 11,
+ name: "trust_level_1",
+ },
+ {
+ id: 12,
+ name: "trust_level_2",
+ },
+ {
+ id: 13,
+ name: "trust_level_3",
+ },
+ {
+ id: 14,
+ name: "trust_level_4",
+ },
+ ]);
+ });
+
+ server.get("/admin/plugins/explorer/schema.json", () => {
+ return helper.response({
+ anonymous_users: [
+ {
+ column_name: "id",
+ data_type: "serial",
+ primary: true,
+ },
+ {
+ column_name: "user_id",
+ data_type: "integer",
+ fkey_info: "users",
+ },
+ {
+ column_name: "master_user_id",
+ data_type: "integer",
+ fkey_info: "users",
+ },
+ {
+ column_name: "active",
+ data_type: "boolean",
+ },
+ {
+ column_name: "created_at",
+ data_type: "timestamp",
+ },
+ {
+ column_name: "updated_at",
+ data_type: "timestamp",
+ },
+ ],
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries", () => {
+ return helper.response({
+ queries: [
+ {
+ id: -6,
+ name: "Top 100 Likers",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ user_id: -1,
+ },
+ {
+ id: 2,
+ name: "What about 0?",
+ description: "",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2023-05-04T22:16:23.858Z",
+ user_id: 1,
+ },
+ ],
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/-6", () => {
+ return helper.response({
+ query: {
+ id: -6,
+ sql: "-- [params]\n-- int :months_ago = 1\n\nWITH query_period AS (\n SELECT\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,\n date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end\n )\n\n SELECT\n ua.user_id,\n count(1) AS like_count\n FROM user_actions ua\n INNER JOIN query_period qp\n ON ua.created_at >= qp.period_start\n AND ua.created_at <= qp.period_end\n WHERE ua.action_type = 1\n GROUP BY ua.user_id\n ORDER BY like_count DESC\n LIMIT 100\n",
+ name: "Top 100 Likers",
+ description:
+ "returns the top 100 likers for a given monthly period ordered by like_count. It accepts a ‘months_ago’ parameter, defaults to 1 to give results for the last calendar month.",
+ param_info: [
+ {
+ identifier: "months_ago",
+ type: "int",
+ default: "1",
+ nullable: false,
+ },
+ ],
+ created_at: "2021-02-02T12:21:11.449Z",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2021-02-11T08:29:59.337Z",
+ hidden: false,
+ user_id: -1,
+ },
+ });
+ });
+
+ server.get("/admin/plugins/explorer/queries/2", () => {
+ return helper.response({
+ query: {
+ id: 2,
+ sql: 'SELECT 0 zero, null "null", false "false"',
+ name: "What about 0?",
+ description: "",
+ param_info: [],
+ created_at: "2023-05-04T22:16:06.007Z",
+ username: "system",
+ group_ids: [],
+ last_run_at: "2023-05-04T22:16:23.858Z",
+ hidden: false,
+ user_id: 1,
+ },
+ });
+ });
+
+ server.post("/admin/plugins/explorer/queries/-6/run", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 27.5,
+ result_count: 2,
+ params: { months_ago: "1" },
+ columns: ["user_id", "like_count"],
+ default_limit: 1000,
+ relations: {
+ user: [
+ {
+ id: -2,
+ username: "discobot",
+ name: null,
+ avatar_template: "/user_avatar/localhost/discobot/{size}/2_2.png",
+ },
+ {
+ id: 2,
+ username: "andrey1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ ],
+ },
+ colrender: {
+ 0: "user",
+ },
+ rows: [
+ [-2, 2],
+ [2, 2],
+ ],
+ });
+ });
+
+ server.post("/admin/plugins/explorer/queries/2/run", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 1.0,
+ result_count: 1,
+ params: {},
+ columns: ["zero", "null", "false"],
+ default_limit: 1000,
+ relations: {},
+ colrender: {},
+ rows: [[0, null, false]],
+ });
+ });
+
+ server.get("/session/csrf.json", function () {
+ return helper.response({
+ csrf: "mgk906YLagHo2gOgM1ddYjAN4hQolBdJCqlY6jYzAYs= ",
+ });
+ });
+ });
+
+ test("runs query and renders data and a chart", async function (assert) {
+ await visit("/admin/plugins/explorer/queries/-6");
+
+ assert
+ .dom("div.name h1")
+ .hasText("Top 100 Likers", "the query name was rendered");
+
+ assert.dom("div.query-edit").exists("the query code was rendered");
+
+ assert
+ .dom("form.query-run button span")
+ .hasText(i18n("explorer.run"), "the run button was rendered");
+
+ await click("form.query-run button");
+
+ assert
+ .dom("div.query-results table tbody tr")
+ .exists({ count: 2 }, "the table with query results was rendered");
+
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(i18n("explorer.show_graph"), "the chart button was rendered");
+
+ await click("div.result-info button:nth-child(3)");
+
+ assert.dom("canvas").exists("the chart was rendered");
+ });
+
+ test("runs query and is able to download the results", async function (assert) {
+ await visit("/admin/plugins/explorer/queries/-6");
+
+ await click("form.query-run button");
+
+ const createElement = document.createElement.bind(document);
+ const appendChild = document.body.appendChild.bind(document.body);
+ const removeChild = document.body.removeChild.bind(document.body);
+
+ const finishedForm = sinon.promise();
+
+ let formElement;
+
+ const formStub = sinon
+ .stub(document, "createElement")
+ .callsFake((tagName) => {
+ if (tagName === "form") {
+ formElement = {
+ fakeForm: true,
+ setAttribute: sinon.stub(),
+ appendChild: sinon.stub(),
+ submit: sinon.stub().callsFake(finishedForm.resolve),
+ };
+
+ return formElement;
+ }
+
+ return createElement(tagName);
+ });
+
+ const appendChildStub = sinon
+ .stub(document.body, "appendChild")
+ .callsFake((el) => {
+ if (!el.fakeForm) {
+ return appendChild(el);
+ }
+ });
+
+ const removeChildStub = sinon
+ .stub(document.body, "removeChild")
+ .callsFake((el) => {
+ if (!el.fakeForm) {
+ return removeChild(el);
+ }
+ });
+
+ await click("div.result-info button:nth-child(1)");
+
+ await finishedForm;
+
+ formStub.restore();
+ appendChildStub.restore();
+ removeChildStub.restore();
+
+ assert.ok(window.open.called, "window.open was called for downloading");
+ assert.ok(formStub.called, "form was created for downloading");
+ assert.ok(formElement.submit.called, "form was submitted for downloading");
+
+ assert.ok(
+ formElement.setAttribute.calledWith("action"),
+ "form action attribute was set"
+ );
+ assert.ok(
+ formElement.setAttribute.calledWith("method", "post"),
+ "form method attribute was set to POST"
+ );
+ });
+
+ test("runs query and renders 0, false, and NULL values correctly", async function (assert) {
+ await visit("/admin/plugins/explorer/queries/2");
+
+ assert
+ .dom("div.name h1 span")
+ .hasText("What about 0?", "the query name was rendered");
+
+ assert
+ .dom("form.query-run button span")
+ .hasText(i18n("explorer.run"), "the run button was rendered");
+
+ await click("form.query-run button");
+
+ assert
+ .dom("div.query-results tbody td:nth-child(1)")
+ .hasText("0", "renders '0' values");
+
+ assert
+ .dom("div.query-results tbody td:nth-child(2)")
+ .hasText("NULL", "renders 'NULL' values");
+
+ assert
+ .dom("div.query-results tbody td:nth-child(3)")
+ .hasText("false", "renders 'false' values");
+ });
+});
diff --git a/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs b/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs
new file mode 100644
index 00000000000..8f0b036786b
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs
@@ -0,0 +1,69 @@
+import { fillIn, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import ExplorerSchema from "discourse/plugins/discourse-data-explorer/discourse/components/explorer-schema";
+
+const schema = {
+ posts: [
+ {
+ column_name: "id",
+ data_type: "serial",
+ primary: true,
+ notes: "primary key",
+ havetypeinfo: true,
+ },
+ {
+ column_name: "raw",
+ data_type: "text",
+ column_desc: "The raw Markdown that the user entered into the composer.",
+ havepopup: true,
+ havetypeinfo: true,
+ },
+ ],
+ categories: [
+ {
+ column_name: "id",
+ data_type: "serial",
+ primary: true,
+ notes: "primary key",
+ havetypeinfo: true,
+ },
+ {
+ column_name: "name",
+ data_type: "varchar(50)",
+ havetypeinfo: false,
+ },
+ ],
+};
+
+module("Data Explorer Plugin | Component | explorer-schema", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("will automatically convert to lowercase", async function (assert) {
+ const self = this;
+
+ this.setProperties({
+ schema,
+ hideSchema: false,
+ updateHideSchema: () => {},
+ });
+
+ await render(
+ <template>
+ <ExplorerSchema
+ @schema={{self.schema}}
+ @hideSchema={{self.hideSchema}}
+ @updateHideSchema={{self.updateHideSchema}}
+ />
+ </template>
+ );
+
+ await fillIn(`.schema-search input`, "Cat");
+
+ assert.dom(".schema-table").exists();
+
+ await fillIn(`.schema-search input`, "NotExist");
+
+ assert.dom(".schema-table").doesNotExist();
+ });
+});
diff --git a/plugins/discourse-data-explorer/test/javascripts/components/param-input-test.gjs b/plugins/discourse-data-explorer/test/javascripts/components/param-input-test.gjs
new file mode 100644
index 00000000000..41f43e1ec53
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/components/param-input-test.gjs
@@ -0,0 +1,409 @@
+import { fillIn, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import ParamInputForm, {
+ ERRORS,
+} from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";
+
+const InputTestCases = [
+ {
+ type: "string",
+ default: "foo",
+ initial: "bar",
+ tests: [
+ { input: "", data_null: "", error: ERRORS.REQUIRED },
+ { input: " ", data_null: " ", error: ERRORS.REQUIRED },
+ { input: "str", data: "str" },
+ ],
+ },
+ {
+ type: "int",
+ default: "123",
+ initial: "456",
+ tests: [
+ { input: "", data_null: "", error: ERRORS.REQUIRED },
+ { input: "1234", data: "1234" },
+ { input: "0", data: "0" },
+ { input: "-2147483648", data: "-2147483648" },
+ { input: "2147483649", error: ERRORS.OVERFLOW_HIGH },
+ { input: "-2147483649", error: ERRORS.OVERFLOW_LOW },
+ ],
+ },
+ {
+ type: "bigint",
+ default: "123",
+ initial: "456",
+ tests: [
+ { input: "", data_null: undefined, error: ERRORS.REQUIRED },
+ { input: "123", data: "123" },
+ { input: "0", data: "0" },
+ { input: "-2147483649", data: "-2147483649" },
+ { input: "2147483649", data: "2147483649" },
+ { input: "abcd", error: ERRORS.NOT_A_NUMBER },
+ { input: "114.514", error: ERRORS.NOT_AN_INTEGER },
+ ],
+ },
+ {
+ type: "category_id",
+ default: "4",
+ initial: "3",
+ tests: [
+ {
+ input: null,
+ data_null: "",
+ error: ERRORS.REQUIRED,
+ },
+ {
+ input: async () => {
+ const categoryChooser = selectKit(".category-chooser");
+
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+ },
+ data: "2",
+ },
+ ],
+ },
+ {
+ type: "group_id",
+ default: "trust_level_1",
+ initial: "trust_level_3",
+ tests: [
+ {
+ input: null,
+ data_null: undefined,
+ error: ERRORS.REQUIRED,
+ },
+ {
+ input: async () => {
+ const groupChooser = selectKit(".group-chooser");
+ await groupChooser.expand();
+ await groupChooser.selectRowByValue("trust_level_2");
+ },
+ data: "trust_level_2",
+ },
+ ],
+ },
+ {
+ type: "group_list",
+ default: "trust_level_1",
+ initial: "trust_level_3,trust_level_4",
+ tests: [
+ {
+ input: null,
+ data_null: "",
+ error: ERRORS.REQUIRED,
+ },
+ ],
+ },
+ {
+ type: "date",
+ default: "2024-07-13",
+ initial: "1970-01-01",
+ tests: [
+ {
+ input: null,
+ data_null: undefined,
+ error: ERRORS.REQUIRED,
+ },
+ {
+ input: "2038-01-20",
+ data: "2038-01-20",
+ },
+ ],
+ },
+ {
+ type: "time",
+ default: "12:34",
+ initial: "11:45",
+ tests: [
+ {
+ input: null,
+ data_null: undefined,
+ error: ERRORS.REQUIRED,
+ },
+ {
+ input: "03:14",
+ data: "03:14",
+ },
+ ],
+ },
+ {
+ type: "datetime",
+ default: "2024-07-13 12:00",
+ initial: "1970-01-01 00:00",
+ tests: [
+ {
+ input: null,
+ data_null: undefined,
+ error: ERRORS.REQUIRED,
+ },
+ {
+ input: "2038-01-19 03:15",
+ data: "2038-01-19 03:15",
+ },
+ ],
+ },
+];
+
+module("Data Explorer Plugin | Component | param-input", function (hooks) {
+ setupRenderingTest(hooks);
+
+ for (const testcase of InputTestCases) {
+ for (const config of [
+ { default: testcase.default },
+ { nullable: false, initial: testcase.initial },
+ { nullable: false, default: testcase.default, initial: testcase.initial },
+ { nullable: true },
+ ]) {
+ const testName = ["type"];
+ if (config.nullable) {
+ testName.push("nullable");
+ }
+ testName.push(testcase.type);
+ if (config.initial) {
+ testName.push("with initial value");
+ }
+ if (config.initial) {
+ testName.push("with default");
+ }
+
+ test(testName.join(" "), async function (assert) {
+ const self = this;
+
+ this.setProperties({
+ param_info: [
+ {
+ identifier: testcase.type,
+ type: testcase.type,
+ default: config.default ?? null,
+ nullable: config.nullable,
+ },
+ ],
+ initialValues: config.initial
+ ? { [testcase.type]: config.initial }
+ : {},
+ onRegisterApi: ({ submit, allNormalized }) => {
+ this.submit = submit;
+ this.allNormalized = allNormalized;
+ },
+ });
+
+ await render(
+ <template>
+ <ParamInputForm
+ @hasParams="true"
+ @initialValues={{self.initialValues}}
+ @paramInfo={{self.param_info}}
+ @onRegisterApi={{self.onRegisterApi}}
+ />
+ </template>
+ );
+
+ await this.allNormalized;
+
+ if (config.initial || config.default) {
+ const data = await this.submit();
+ const val = config.initial || config.default;
+ assert.strictEqual(
+ data[testcase.type],
+ val,
+ `has initial/default value "${val}"`
+ );
+ }
+
+ for (const t of testcase.tests) {
+ if (t.input == null && (config.initial || config.default)) {
+ continue;
+ }
+ await formKit().reset();
+ if (t.input != null) {
+ if (typeof t.input === "function") {
+ await t.input();
+ } else {
+ await fillIn(`[name="${testcase.type}"]`, t.input);
+ }
+ }
+
+ if (config.nullable && "data_null" in t) {
+ const data = await this.submit();
+ assert.strictEqual(
+ data[testcase.type],
+ t.data_null,
+ `should have null data`
+ );
+ } else if (t.error) {
+ await formKit().submit();
+ assert.form().field(testcase.type).hasError(t.error);
+ } else {
+ const data = await this.submit();
+ assert.strictEqual(
+ data[testcase.type],
+ t.data,
+ `data should be "${t.data}"`
+ );
+ }
+ }
+ });
+ }
+ }
+
+ test("empty form will reject submit", async function (assert) {
+ const self = this;
+
+ this.setProperties({
+ param_info: [
+ {
+ identifier: "string",
+ type: "string",
+ default: null,
+ nullable: false,
+ },
+ ],
+ initialValues: {},
+ onRegisterApi: ({ submit }) => {
+ this.submit = submit;
+ },
+ });
+
+ await render(
+ <template>
+ <ParamInputForm
+ @initialValues={{self.initialValues}}
+ @paramInfo={{self.param_info}}
+ @onRegisterApi={{self.onRegisterApi}}
+ />
+ </template>
+ );
+
+ assert.rejects(this.submit());
+
+ // After successfully submitting the test once, edit and submit again.
+ await fillIn(`[name="string"]`, "foo");
+ await this.submit();
+ await fillIn(`[name="string"]`, "");
+ assert.rejects(this.submit());
+ });
+
+ test("async normalization", async function (assert) {
+ const self = this;
+
+ this.setProperties({
+ param_info: [
+ {
+ identifier: "category_id",
+ type: "category_id",
+ default: "support",
+ nullable: false,
+ },
+ ],
+ initialValues: {},
+ onRegisterApi: (paramInputApi) => {
+ this.paramInputApi = paramInputApi;
+ },
+ });
+
+ await render(
+ <template>
+ <ParamInputForm
+ @initialValues={{self.initialValues}}
+ @paramInfo={{self.param_info}}
+ @onRegisterApi={{self.onRegisterApi}}
+ />
+ </template>
+ );
+
+ await this.paramInputApi.allNormalized;
+
+ this.paramInputApi.submit().then((res) => {
+ assert.strictEqual(res.category_id, "1003");
+ });
+ });
+
+ test("show error message when default value is invalid", async function (assert) {
+ const self = this;
+
+ this.setProperties({
+ param_info: [
+ {
+ identifier: "group_id",
+ type: "group_id",
+ default: "invalid_group_name",
+ nullable: false,
+ },
+ ],
+ initialValues: {},
+ onRegisterApi: () => {},
+ });
+
+ await render(
+ <template>
+ <ParamInputForm
+ @initialValues={{self.initialValues}}
+ @paramInfo={{self.param_info}}
+ @onRegisterApi={{self.onRegisterApi}}
+ />
+ </template>
+ );
+
+ assert
+ .form()
+ .field("group_id")
+ .hasError(`${ERRORS.NO_SUCH_GROUP}: invalid_group_name`);
+ });
+
+ test("date, time, datetime with initial value in other formats", async function (assert) {
+ const self = this;
+
+ this.setProperties({
+ param_info: [
+ {
+ identifier: "date",
+ type: "date",
+ default: null,
+ nullable: false,
+ },
+ {
+ identifier: "time",
+ type: "time",
+ default: null,
+ nullable: false,
+ },
+ {
+ identifier: "datetime",
+ type: "datetime",
+ default: null,
+ nullable: false,
+ },
+ ],
+ initialValues: {
+ date: "19 January 2038",
+ time: "3:15 am",
+ datetime: "19 January 2038 3:15 am",
+ },
+ onRegisterApi: ({ submit }) => {
+ this.submit = submit;
+ },
+ });
+
+ await render(
+ <template>
+ <ParamInputForm
+ @initialValues={{self.initialValues}}
+ @paramInfo={{self.param_info}}
+ @onRegisterApi={{self.onRegisterApi}}
+ />
+ </template>
+ );
+
+ this.submit().then((res) => {
+ assert.deepEqual(res, {
+ date: "2038-01-19",
+ time: "03:15",
+ datetime: "2038-01-19 03:15",
+ });
+ });
+ });
+});
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-bar-chart-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-bar-chart-test.gjs
new file mode 100644
index 00000000000..6b7547631d7
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-bar-chart-test.gjs
@@ -0,0 +1,26 @@
+import { array } from "@ember/helper";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DataExplorerBarChart from "../../discourse/components/data-explorer-bar-chart";
+
+module(
+ "Data Explorer Plugin | Integration | Component | data-explorer-bar-chart",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders a chart", async function (assert) {
+ await render(
+ <template>
+ <DataExplorerBarChart
+ @labels={{array "label_1" "label_2"}}
+ @values={{array 115 1000}}
+ @datasetName="data"
+ />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a canvas");
+ });
+ }
+);
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
new file mode 100644
index 00000000000..235b716ce91
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
@@ -0,0 +1,265 @@
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { i18n } from "discourse-i18n";
+import QueryResult from "../../discourse/components/query-result";
+
+module(
+ "Data Explorer Plugin | Integration | Component | query-result",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders query results", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user_name", "like_count"],
+ rows: [
+ ["user1", 10],
+ ["user2", 20],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("div.result-info button:nth-child(1) span")
+ .hasText(i18n("explorer.download_json"), "renders the JSON button");
+
+ assert
+ .dom("div.result-info button:nth-child(2) span")
+ .hasText(i18n("explorer.download_csv"), "renders the CSV button");
+
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(i18n("explorer.show_graph"), "renders the chart button");
+
+ assert.dom("div.result-about").exists("renders a query summary");
+
+ assert.dom("table thead tr th:nth-child(1)").hasText("user_name");
+ assert.dom("table thead tr th:nth-child(2)").hasText("like_count");
+ assert
+ .dom("table tbody tr:nth-child(1) td:nth-child(1)")
+ .hasText("user1");
+ assert.dom("table tbody tr:nth-child(1) td:nth-child(2)").hasText("10");
+ assert
+ .dom("table tbody tr:nth-child(2) td:nth-child(1)")
+ .hasText("user2");
+ assert.dom("table tbody tr:nth-child(2) td:nth-child(2)").hasText("20");
+ });
+
+ test("renders badge names in query results", async function (assert) {
+ const content = {
+ colrender: { 0: "badge" },
+ relations: {
+ badge: [
+ {
+ description: "description",
+ icon: "user",
+ id: 1,
+ name: "badge name",
+ display_name: "badge display name",
+ },
+ ],
+ },
+ result_count: 1,
+ columns: ["badge_id"],
+ rows: [[1]],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("table tbody tr:nth-child(1) td:nth-child(1) span")
+ .hasText("badge display name");
+ });
+
+ test("renders a post in query results", async function (assert) {
+ const content = {
+ colrender: { 0: "post" },
+ relations: {
+ post: [
+ {
+ description: "description",
+ id: 1,
+ topic_id: 1,
+ post_number: 1,
+ excerpt: "foo",
+ username: "user1",
+ avatar_template: "",
+ },
+ ],
+ },
+ result_count: 1,
+ columns: [""],
+ rows: [[1]],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("table tbody tr:nth-child(1) td:nth-child(1) aside")
+ .hasAttribute("data-post", "1");
+ assert
+ .dom("table tbody tr:nth-child(1) td:nth-child(1) aside")
+ .hasAttribute("data-topic", "1");
+ });
+
+ test("renders a category_id in query results", async function (assert) {
+ const content = {
+ colrender: { 0: "category" },
+ relations: {
+ category: [
+ {
+ id: 1,
+ name: "foo",
+ slug: "foo",
+ topic_count: 0,
+ position: 1,
+ description: "a category",
+ can_edit: true,
+ },
+ ],
+ },
+ result_count: 1,
+ columns: [""],
+ rows: [[1]],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom(
+ "table tbody tr:nth-child(1) td:nth-child(1) .badge-category__name"
+ )
+ .exists();
+ });
+ }
+);
+
+module(
+ "Data Explorer Plugin | Integration | Component | query-result | chart",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("navigation between a table and a chart works", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user_name", "like_count"],
+ rows: [
+ ["user1", 10],
+ ["user2", 20],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(i18n("explorer.show_graph"), "the chart button was rendered");
+ assert.dom("table").exists("the table was rendered");
+
+ await click("div.result-info button:nth-child(3)");
+
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(
+ i18n("explorer.show_table"),
+ "the chart button was changed to the table button"
+ );
+ assert.dom("canvas").exists("the chart was rendered");
+
+ await click("div.result-info button:nth-child(3)");
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(
+ i18n("explorer.show_graph"),
+ "the table button was changed to the chart button"
+ );
+ assert.dom("table").exists("the table was rendered");
+ });
+
+ test("renders a chart button when data has two columns and numbers in the second column", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user_name", "like_count"],
+ rows: [
+ ["user1", 10],
+ ["user2", 20],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(i18n("explorer.show_graph"));
+ });
+
+ test("doesn't render a chart button when data contains identifiers in the second column", async function (assert) {
+ const content = {
+ colrender: { 1: "user" },
+ relations: {
+ user: [
+ { id: 1, username: "user1" },
+ { id: 2, username: "user2" },
+ ],
+ },
+ result_count: 2,
+ columns: ["topic_id", "user_id"],
+ rows: [
+ [1, 10],
+ [2, 20],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert.dom("div.result-info button:nth-child(3)").doesNotExist();
+ });
+
+ test("doesn't render a chart button when data contains one column", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user_name"],
+ rows: [["user1"], ["user2"]],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert.dom("div.result-info button:nth-child(3)").doesNotExist();
+ });
+
+ test("doesn't render a chart button when data contains more than two columns", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user_name", "like_count", "post_count"],
+ rows: [
+ ["user1", 10, 1],
+ ["user2", 20, 2],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert.dom("div.result-info button:nth-child(3)").doesNotExist();
+ });
+
+ test("handles no results", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 0,
+ columns: ["user_name", "like_count", "post_count"],
+ rows: [],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert.dom("table tbody tr").doesNotExist("renders no results");
+ });
+ }
+);
diff --git a/translator.yml b/translator.yml
index 271c319550c..f8cec85d0f0 100644
--- a/translator.yml
+++ b/translator.yml
@@ -199,3 +199,10 @@ files:
- source_path: plugins/discourse-chat-integration/config/locales/server.en.yml
destination_path: plugins/chat-integration/server.yml
label: chat-integration
+
+ - source_path: plugins/discourse-data-explorer/config/locales/client.en.yml
+ destination_path: plugins/data-explorer/client.yml
+ label: data-explorer
+ - source_path: plugins/discourse-data-explorer/config/locales/server.en.yml
+ destination_path: plugins/data-explorer/server.yml
+ label: data-explorer