nquery 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +36 -0
  3. data/README.md +54 -0
  4. data/app/assets/builds/nquery/application.css +110 -6
  5. data/app/assets/builds/nquery/application.js +401 -37
  6. data/app/controllers/concerns/nquery/breadcrumbs.rb +2 -13
  7. data/app/controllers/concerns/nquery/chart_actions.rb +5 -5
  8. data/app/controllers/concerns/nquery/chart_results.rb +70 -9
  9. data/app/controllers/concerns/nquery/sharing_page.rb +38 -0
  10. data/app/controllers/nquery/application_controller.rb +2 -0
  11. data/app/controllers/nquery/dashboard/cards_controller.rb +28 -0
  12. data/app/controllers/nquery/dashboards_controller.rb +56 -11
  13. data/app/controllers/nquery/embed/charts_controller.rb +15 -13
  14. data/app/controllers/nquery/embed/dashboards_controller.rb +34 -8
  15. data/app/controllers/nquery/public/charts_controller.rb +19 -0
  16. data/app/controllers/nquery/public/dashboards_controller.rb +33 -0
  17. data/app/controllers/nquery/public_resources_controller.rb +79 -0
  18. data/app/controllers/nquery/queries_controller.rb +25 -48
  19. data/app/controllers/nquery/sharing/base_controller.rb +89 -0
  20. data/app/controllers/nquery/sharing/embed_tokens_controller.rb +41 -0
  21. data/app/controllers/nquery/sharing/embeddings_controller.rb +17 -0
  22. data/app/controllers/nquery/sharing/public_links_controller.rb +21 -0
  23. data/app/helpers/nquery/charts_helper.rb +13 -0
  24. data/app/helpers/nquery/sharing_helper.rb +67 -0
  25. data/app/javascript/nquery/controllers/chart_preview_controller.js +19 -1
  26. data/app/javascript/nquery/controllers/clipboard_controller.js +23 -0
  27. data/app/models/concerns/nquery/shareable.rb +43 -0
  28. data/app/models/nquery/chart.rb +18 -2
  29. data/app/models/nquery/dashboard.rb +131 -0
  30. data/app/models/nquery/data_source.rb +1 -1
  31. data/app/models/nquery/query.rb +72 -0
  32. data/app/services/nquery/application_service.rb +9 -0
  33. data/app/services/nquery/dashboards/card_parameters.rb +37 -0
  34. data/app/services/nquery/dashboards/filters.rb +75 -0
  35. data/app/services/nquery/dashboards/parameter_charts.rb +31 -0
  36. data/app/services/nquery/dashboards/parameter_rows.rb +60 -0
  37. data/app/views/layouts/nquery/application.html.erb +8 -0
  38. data/app/views/layouts/nquery/embed.html.erb +3 -1
  39. data/app/views/nquery/charts/_builder_form.html.erb +13 -6
  40. data/app/views/nquery/charts/_variable_row.html.erb +10 -0
  41. data/app/views/nquery/charts/_variables.html.erb +28 -0
  42. data/app/views/nquery/charts/embed.html.erb +5 -11
  43. data/app/views/nquery/charts/new.html.erb +2 -1
  44. data/app/views/nquery/charts/update.turbo_stream.erb +3 -0
  45. data/app/views/nquery/dashboard/charts/new.html.erb +2 -1
  46. data/app/views/nquery/dashboards/_chart_card.html.erb +27 -1
  47. data/app/views/nquery/dashboards/_parameter_chart_ids.html.erb +6 -0
  48. data/app/views/nquery/dashboards/_parameters.html.erb +159 -0
  49. data/app/views/nquery/dashboards/edit.html.erb +10 -0
  50. data/app/views/nquery/dashboards/embed.html.erb +9 -0
  51. data/app/views/nquery/dashboards/show.html.erb +41 -1
  52. data/app/views/nquery/embed/charts/show.html.erb +7 -8
  53. data/app/views/nquery/embed/dashboards/show.html.erb +12 -6
  54. data/app/views/nquery/embed/unavailable.html.erb +1 -0
  55. data/app/views/nquery/shared/_icon.html.erb +10 -0
  56. data/app/views/nquery/shared/_shared_chart_card.html.erb +20 -0
  57. data/app/views/nquery/shared/_sharing_panel.html.erb +94 -0
  58. data/app/views/nquery/shared/_sidebar.html.erb +1 -1
  59. data/app/views/nquery/shared/_topbar.html.erb +3 -0
  60. data/config/routes.rb +24 -1
  61. data/db/migrate/20260907120000_add_sharing_to_nquery_charts_and_dashboards.rb +19 -0
  62. data/db/migrate/20260907130000_remove_embedding_params_from_nquery_charts_and_dashboards.rb +8 -0
  63. data/db/migrate/20261005145000_add_parameters_to_nquery_dashboards.rb +7 -0
  64. data/db/migrate/20261005190000_add_parameters_to_nquery_queries.rb +7 -0
  65. data/lib/nquery/boolean.rb +9 -0
  66. data/lib/nquery/configuration.rb +6 -0
  67. data/lib/nquery/dashboard_parameters.rb +56 -0
  68. data/lib/nquery/data_sources/adapter.rb +10 -1
  69. data/lib/nquery/data_sources/mysql_adapter.rb +2 -2
  70. data/lib/nquery/data_sources/postgresql_adapter.rb +2 -2
  71. data/lib/nquery/data_sources/rails_adapter.rb +2 -7
  72. data/lib/nquery/data_sources/row_limit.rb +211 -0
  73. data/lib/nquery/embed_token_service.rb +10 -5
  74. data/lib/nquery/encryption.rb +1 -1
  75. data/lib/nquery/parameter_value.rb +97 -0
  76. data/lib/nquery/query_runner.rb +37 -4
  77. data/lib/nquery/seeder.rb +29 -7
  78. data/lib/nquery/statement_binds.rb +112 -0
  79. data/lib/nquery/version.rb +1 -1
  80. data/lib/nquery.rb +5 -0
  81. data/nquery.gemspec +2 -2
  82. metadata +40 -9
  83. data/app/javascript/nquery/controllers/query_editor_controller.js +0 -41
  84. data/app/views/nquery/queries/edit.html.erb +0 -40
  85. data/app/views/nquery/queries/new.html.erb +0 -37
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ module Sharing
5
+ class BaseController < ApplicationController
6
+ before_action :set_shareable
7
+ before_action :authorize_shareable_publish!, only: %i[create update]
8
+ before_action :authorize_shareable_revoke!, only: %i[destroy]
9
+
10
+ private
11
+
12
+ def set_shareable
13
+ @shareable = if params[:chart_id]
14
+ Chart.find(params[:chart_id])
15
+ else
16
+ Dashboard.find(params[:dashboard_id])
17
+ end
18
+ end
19
+
20
+ def authorize_shareable_publish!
21
+ authorize_shareable_collection!
22
+ return if performed?
23
+
24
+ if shareable_missing_data_source?
25
+ deny_collection_access!(missing_data_source_message)
26
+ return
27
+ end
28
+
29
+ shareable_data_sources.each do |data_source|
30
+ authorize_data_source_access!(data_source)
31
+ return if performed?
32
+ end
33
+ end
34
+
35
+ def authorize_shareable_revoke!
36
+ authorize_shareable_collection!
37
+ end
38
+
39
+ def authorize_shareable_collection!
40
+ return if permission_resolver.admin?
41
+
42
+ if @shareable.collection.nil?
43
+ deny_collection_access!("You do not have permission to access this collection.")
44
+ return
45
+ end
46
+
47
+ authorize_collection_access!(@shareable.collection, required: :curate)
48
+ end
49
+
50
+ def shareable_charts
51
+ if @shareable.is_a?(Chart)
52
+ [@shareable]
53
+ else
54
+ @shareable.dashboard_cards
55
+ .joins(:chart)
56
+ .merge(Chart.active)
57
+ .includes(chart: { query: :data_source })
58
+ .map(&:chart)
59
+ end
60
+ end
61
+
62
+ def shareable_data_sources
63
+ shareable_charts.filter_map(&:data_source).uniq
64
+ end
65
+
66
+ def shareable_missing_data_source?
67
+ shareable_charts.any? { |chart| chart.query && chart.data_source.nil? }
68
+ end
69
+
70
+ def missing_data_source_message
71
+ if @shareable.is_a?(Chart)
72
+ "This chart has no data source."
73
+ else
74
+ "A chart on this dashboard has no data source."
75
+ end
76
+ end
77
+
78
+ def sharing_page_path
79
+ if params[:chart_id] && params[:dashboard_id]
80
+ embed_dashboard_chart_path(params[:dashboard_id], params[:chart_id])
81
+ elsif params[:chart_id]
82
+ embed_chart_path(params[:chart_id])
83
+ else
84
+ embed_dashboard_path(params[:dashboard_id])
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ module Sharing
5
+ class EmbedTokensController < BaseController
6
+ def create
7
+ unless Nquery.configuration.static_embedding_enabled
8
+ return redirect_to sharing_page_path, alert: "Static embedding is disabled."
9
+ end
10
+
11
+ @shareable.embed_tokens.active.find_each { |token| EmbedTokenService.revoke!(token) }
12
+ EmbedTokenService.sign(
13
+ resource_type: @shareable.class.name,
14
+ resource_id: @shareable.id,
15
+ creator: current_nquery_user,
16
+ expires_at: expires_at_from_param
17
+ )
18
+ @shareable.update!(enable_embedding: true) unless @shareable.enable_embedding?
19
+
20
+ redirect_to sharing_page_path, notice: "Embed token generated."
21
+ end
22
+
23
+ def destroy
24
+ token = @shareable.embed_tokens.find(params[:id])
25
+ EmbedTokenService.revoke!(token)
26
+ redirect_to sharing_page_path, notice: "Embed token revoked."
27
+ end
28
+
29
+ private
30
+
31
+ def expires_at_from_param
32
+ case params[:expires_in]
33
+ when "1.day" then 1.day.from_now
34
+ when "30.days" then 30.days.from_now
35
+ when "never" then nil
36
+ else 1.hour.from_now
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ module Sharing
5
+ class EmbeddingsController < BaseController
6
+ def update
7
+ unless Nquery.configuration.static_embedding_enabled
8
+ return redirect_to sharing_page_path, alert: "Static embedding is disabled."
9
+ end
10
+
11
+ enabled = Nquery::Boolean.cast(params[:enable_embedding])
12
+ @shareable.update!(enable_embedding: enabled)
13
+ redirect_to sharing_page_path, notice: enabled ? "Embedding enabled." : "Embedding disabled."
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ module Sharing
5
+ class PublicLinksController < BaseController
6
+ def create
7
+ unless Nquery.configuration.public_sharing_enabled
8
+ return redirect_to sharing_page_path, alert: "Public sharing is disabled."
9
+ end
10
+
11
+ @shareable.share_publicly!(user: current_nquery_user)
12
+ redirect_to sharing_page_path, notice: "Public link created."
13
+ end
14
+
15
+ def destroy
16
+ @shareable.unshare_publicly!
17
+ redirect_to sharing_page_path, notice: "Public link removed."
18
+ end
19
+ end
20
+ end
21
+ end
@@ -18,6 +18,10 @@ module Nquery
18
18
  dashboard ? embed_dashboard_chart_path(dashboard, chart) : embed_chart_path(chart)
19
19
  end
20
20
 
21
+ def dashboard_embed_path(dashboard)
22
+ embed_dashboard_path(dashboard)
23
+ end
24
+
21
25
  def chart_archive_path(chart, dashboard: chart_dashboard)
22
26
  dashboard ? archive_dashboard_chart_path(dashboard, chart) : archive_chart_path(chart)
23
27
  end
@@ -29,5 +33,14 @@ module Nquery
29
33
  def chart_builder_chart_types
30
34
  Chart::CHART_TYPES - %w[table]
31
35
  end
36
+
37
+ def chart_builder_data(chart, result: nil)
38
+ {
39
+ controller: "chart-builder",
40
+ query_save_url: chart.query&.persisted? ? query_path(chart.query) : nil,
41
+ query_run_url: run_queries_path,
42
+ query_schema_url: schema_queries_path
43
+ }.tap { |data| data[:initial_result] = result if result.present? }
44
+ end
32
45
  end
33
46
  end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ module SharingHelper
5
+ EMBED_EXPIRY_OPTIONS = [
6
+ ["1 hour", "1.hour"],
7
+ ["1 day", "1.day"],
8
+ ["30 days", "30.days"],
9
+ ["Never", "never"]
10
+ ].freeze
11
+
12
+ def shareable_public_link_path(resource)
13
+ case resource
14
+ when Chart
15
+ chart_dashboard ? dashboard_chart_public_link_path(chart_dashboard, resource) : chart_public_link_path(resource)
16
+ when Dashboard
17
+ dashboard_public_link_path(resource)
18
+ end
19
+ end
20
+
21
+ def shareable_embedding_path(resource)
22
+ case resource
23
+ when Chart
24
+ chart_dashboard ? dashboard_chart_embedding_path(chart_dashboard, resource) : chart_embedding_path(resource)
25
+ when Dashboard
26
+ dashboard_embedding_path(resource)
27
+ end
28
+ end
29
+
30
+ def shareable_embed_tokens_path(resource)
31
+ case resource
32
+ when Chart
33
+ chart_dashboard ? dashboard_chart_embed_tokens_path(chart_dashboard, resource) : chart_embed_tokens_path(resource)
34
+ when Dashboard
35
+ dashboard_embed_tokens_path(resource)
36
+ end
37
+ end
38
+
39
+ def shareable_embed_token_path(resource, token)
40
+ case resource
41
+ when Chart
42
+ if chart_dashboard
43
+ dashboard_chart_embed_token_path(chart_dashboard, resource, token)
44
+ else
45
+ chart_embed_token_path(resource, token)
46
+ end
47
+ when Dashboard
48
+ dashboard_embed_token_path(resource, token)
49
+ end
50
+ end
51
+
52
+ def can_curate_shareable?(resource)
53
+ return true if permission_resolver.admin?
54
+ return false if resource.collection.nil?
55
+
56
+ permission_resolver.collection_access(resource.collection) == :curate
57
+ end
58
+
59
+ def share_iframe_snippet(url, height: 600)
60
+ %(<iframe src="#{url}" width="800" height="#{height}" frameborder="0" loading="lazy"></iframe>)
61
+ end
62
+
63
+ def share_iframe_height(resource)
64
+ resource.is_a?(Dashboard) ? 800 : 600
65
+ end
66
+ end
67
+ end
@@ -1,5 +1,13 @@
1
1
  import { Controller } from "@hotwired/stimulus"
2
2
 
3
+ function escapeHtml(value) {
4
+ return String(value)
5
+ .replace(/&/g, "&amp;")
6
+ .replace(/</g, "&lt;")
7
+ .replace(/>/g, "&gt;")
8
+ .replace(/"/g, "&quot;")
9
+ }
10
+
3
11
  function columnIndex(columns, name) {
4
12
  const index = columns.indexOf(name)
5
13
  return index >= 0 ? index : 0
@@ -72,10 +80,20 @@ export default class extends Controller {
72
80
  connect() {
73
81
  if (typeof Chart === "undefined") return
74
82
 
83
+ Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
84
+ Chart.defaults.color = document.body.classList.contains("nq-embed-theme-night") ? "#e2e8f0" : "#1e293b"
85
+
75
86
  const demo = this.hasDataValue ? this.dataValue : {
76
87
  columns: ["month", "revenue"],
77
88
  rows: [["Jan", 1200], ["Feb", 1800], ["Mar", 2400]]
78
89
  }
90
+
91
+ if (demo.error) {
92
+ this.element.classList.add("is-error")
93
+ this.element.innerHTML = `<div class="nq-chart-error">${escapeHtml(demo.error)}</div>`
94
+ return
95
+ }
96
+
79
97
  const type = this.typeValue || "bar"
80
98
  const xCol = this.hasXValue ? this.xValue : ""
81
99
  const yCol = this.hasYValue ? this.yValue : ""
@@ -84,7 +102,7 @@ export default class extends Controller {
84
102
  const yIndex = columnIndex(demo.columns || [], yCol || demo.columns?.[1] || demo.columns?.[0])
85
103
  const value = demo.rows?.[0]?.[yIndex] ?? "—"
86
104
  this.element.classList.add("is-number")
87
- this.element.innerHTML = `<div class="nq-number-display">${value}</div>`
105
+ this.element.innerHTML = `<div class="nq-number-display">${escapeHtml(value)}</div>`
88
106
  return
89
107
  }
90
108
 
@@ -0,0 +1,23 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+
3
+ export default class extends Controller {
4
+ static values = { text: String }
5
+
6
+ async copy(event) {
7
+ event.preventDefault()
8
+ const button = event.currentTarget
9
+ const targetSelector = button.dataset.copyTarget
10
+ const target = targetSelector ? document.querySelector(targetSelector) : null
11
+ const text = target ? target.textContent : this.textValue
12
+ const original = button.textContent
13
+
14
+ try {
15
+ await navigator.clipboard.writeText(text.trim())
16
+ button.textContent = "Copied"
17
+ } catch {
18
+ button.textContent = "Copy failed"
19
+ }
20
+
21
+ setTimeout(() => { button.textContent = original }, 1500)
22
+ }
23
+ }
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ module Shareable
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ resource_class_name = name
9
+
10
+ belongs_to :made_public_by, class_name: "Nquery::User", optional: true
11
+ has_many :embed_tokens, -> { where(resource_type: resource_class_name) },
12
+ class_name: "Nquery::EmbedToken", foreign_key: :resource_id, dependent: :destroy
13
+
14
+ scope :publicly_shared, -> { where.not(public_uuid: nil) }
15
+ scope :embedding_enabled, -> { where(enable_embedding: true) }
16
+
17
+ validates :public_uuid, uniqueness: true, allow_nil: true
18
+ end
19
+
20
+ def publicly_shared?
21
+ public_uuid.present?
22
+ end
23
+
24
+ def share_publicly!(user:)
25
+ return self if publicly_shared?
26
+
27
+ update!(
28
+ public_uuid: SecureRandom.uuid,
29
+ made_public_by: user,
30
+ public_shared_at: Time.current
31
+ )
32
+ self
33
+ end
34
+
35
+ def unshare_publicly!
36
+ update!(public_uuid: nil, made_public_by: nil, public_shared_at: nil)
37
+ end
38
+
39
+ def active_embed_token
40
+ embed_tokens.active.order(created_at: :desc).first
41
+ end
42
+ end
43
+ end
@@ -4,12 +4,12 @@ module Nquery
4
4
  class Chart < ApplicationRecord
5
5
  CHART_TYPES = %w[table number bar line area pie scatter].freeze
6
6
 
7
+ include Shareable
8
+
7
9
  belongs_to :query, class_name: "Nquery::Query", optional: true
8
10
  belongs_to :collection, class_name: "Nquery::Collection", optional: true
9
11
  belongs_to :creator, class_name: "Nquery::User", optional: true
10
12
  has_many :dashboard_cards, class_name: "Nquery::DashboardCard", dependent: :destroy
11
- has_many :embed_tokens, -> { where(resource_type: "Nquery::Chart") },
12
- class_name: "Nquery::EmbedToken", foreign_key: :resource_id, dependent: :destroy
13
13
 
14
14
  accepts_nested_attributes_for :query
15
15
 
@@ -33,5 +33,21 @@ module Nquery
33
33
  def chart_type
34
34
  visualization["type"] || "bar"
35
35
  end
36
+
37
+ def statement
38
+ query&.statement
39
+ end
40
+
41
+ def statement?
42
+ query&.statement? || false
43
+ end
44
+
45
+ def uses_parameter?(name)
46
+ statement.to_s.match?(/\{\{\s*#{Regexp.escape(name)}\s*\}\}/)
47
+ end
48
+
49
+ def data_source
50
+ query&.data_source
51
+ end
36
52
  end
37
53
  end
@@ -2,15 +2,66 @@
2
2
 
3
3
  module Nquery
4
4
  class Dashboard < ApplicationRecord
5
+ include Shareable
6
+
5
7
  belongs_to :collection, class_name: "Nquery::Collection"
6
8
  belongs_to :creator, class_name: "Nquery::User", optional: true
7
9
  has_many :dashboard_cards, class_name: "Nquery::DashboardCard", dependent: :destroy
8
10
  has_many :charts, through: :dashboard_cards, class_name: "Nquery::Chart"
9
11
 
12
+ PARAMETER_NAME_FORMAT = /\A[a-z][a-z0-9_]*\z/
13
+ RESERVED_PARAMETER_NAMES = %w[token titled bordered theme wire id action controller format].freeze
14
+
10
15
  scope :active, -> { where(archived_at: nil) }
11
16
  scope :archived, -> { where.not(archived_at: nil) }
12
17
 
13
18
  validates :name, presence: true
19
+ validate :parameters_are_declared
20
+
21
+ before_validation :normalize_parameters
22
+
23
+ def parameter_definitions
24
+ normalized_parameter_rows(parameters)
25
+ end
26
+
27
+ def parameter_names
28
+ parameter_definitions.map { |row| row["name"] }
29
+ end
30
+
31
+ def with_agreed_chart_variables
32
+ loaded_charts = charts.includes(:query).to_a
33
+ charts_by_id = loaded_charts.index_by(&:id)
34
+ rows = parameter_definitions.map { |row| agreed_chart_variable_row(row, loaded_charts, charts_by_id) }
35
+ return self if rows == parameter_definitions
36
+
37
+ copy = dup
38
+ copy.id = id
39
+ copy.parameters = rows
40
+ copy.readonly!
41
+ copy
42
+ end
43
+
44
+ def parameter_linked_to_chart?(row, chart)
45
+ return true unless row.key?("chart_ids")
46
+
47
+ Array(row["chart_ids"]).map(&:to_i).include?(chart.id)
48
+ end
49
+
50
+ def linked_chart_ids(row)
51
+ if row.key?("chart_ids")
52
+ Array(row["chart_ids"]).map(&:to_i)
53
+ else
54
+ charts.select { |chart| chart.uses_parameter?(row["name"]) }.map(&:id)
55
+ end
56
+ end
57
+
58
+ def parameters_for_chart(chart, resolved)
59
+ names = parameter_definitions.select { |row| parameter_linked_to_chart?(row, chart) }.map { |row| row["name"] }
60
+ DashboardParameters::Result.new(
61
+ values: resolved.values.slice(*names),
62
+ invalid_names: Array(resolved.invalid_names) & names
63
+ )
64
+ end
14
65
 
15
66
  def archived?
16
67
  archived_at.present?
@@ -23,5 +74,85 @@ module Nquery
23
74
  def unarchive!
24
75
  update!(archived_at: nil)
25
76
  end
77
+
78
+ private
79
+
80
+ def normalize_parameters
81
+ self.parameters = parameter_definitions
82
+ end
83
+
84
+ def normalized_parameter_rows(value)
85
+ Array(value).filter_map { |row| normalized_parameter_row(row) }
86
+ end
87
+
88
+ def normalized_parameter_row(row)
89
+ return unless row.respond_to?(:stringify_keys)
90
+
91
+ attrs = row.stringify_keys
92
+ name = attrs["name"].to_s.strip
93
+ return if name.blank?
94
+
95
+ row = {
96
+ "name" => name,
97
+ "type" => attrs["type"].to_s.strip,
98
+ "default" => attrs["default"].to_s.strip
99
+ }
100
+ row["chart_ids"] = chart_ids_for(attrs["chart_ids"]) if attrs.key?("chart_ids")
101
+ row
102
+ end
103
+
104
+ def chart_ids_for(value)
105
+ Array(value).filter_map { |chart_id| Integer(chart_id, exception: false) }.uniq
106
+ end
107
+
108
+ def agreed_chart_variable_row(row, loaded_charts, charts_by_id)
109
+ definitions = linked_variable_definitions(row, loaded_charts, charts_by_id)
110
+ return row if definitions.empty?
111
+
112
+ types = definitions.map { |definition| definition["type"] }.uniq
113
+ defaults = definitions.map { |definition| definition["default"] }.uniq
114
+ return row unless types.one? && defaults.one?
115
+
116
+ row.merge("type" => types.first, "default" => defaults.first)
117
+ end
118
+
119
+ def linked_variable_definitions(row, loaded_charts, charts_by_id)
120
+ chart_ids_for_row(row, loaded_charts).filter_map do |chart_id|
121
+ charts_by_id[chart_id]&.query&.stored_parameter_definitions&.find { |definition| definition["name"] == row["name"] }
122
+ end
123
+ end
124
+
125
+ def chart_ids_for_row(row, loaded_charts)
126
+ if row.key?("chart_ids")
127
+ Array(row["chart_ids"]).map(&:to_i)
128
+ else
129
+ loaded_charts.select { |chart| chart.uses_parameter?(row["name"]) }.map(&:id)
130
+ end
131
+ end
132
+
133
+ def parameters_are_declared
134
+ names = []
135
+ parameter_definitions.each do |row|
136
+ name = row["name"]
137
+ unless name.match?(PARAMETER_NAME_FORMAT)
138
+ errors.add(:parameters, "include an invalid name")
139
+ next
140
+ end
141
+
142
+ errors.add(:parameters, "cannot use #{name}") if RESERVED_PARAMETER_NAMES.include?(name)
143
+
144
+ if names.include?(name)
145
+ errors.add(:parameters, "include a duplicate name")
146
+ else
147
+ names << name
148
+ end
149
+
150
+ if ParameterValue::TYPES.exclude?(row["type"])
151
+ errors.add(:parameters, "must be string, integer, date, datetime, uuid, or boolean")
152
+ elsif !ParameterValue.valid_default?(row["type"], row["default"])
153
+ errors.add(:parameters, "include an invalid default")
154
+ end
155
+ end
156
+ end
26
157
  end
27
158
  end
@@ -42,7 +42,7 @@ module Nquery
42
42
  scope :active, -> { all }
43
43
 
44
44
  def connection_fields_submitted?
45
- ActiveModel::Type::Boolean.new.cast(connection_fields_submitted)
45
+ Nquery::Boolean.cast(connection_fields_submitted)
46
46
  end
47
47
 
48
48
  def connection_config_hash
@@ -8,17 +8,89 @@ module Nquery
8
8
  has_one :chart, class_name: "Nquery::Chart", dependent: :destroy
9
9
  has_many :audits, class_name: "Nquery::Audit", dependent: :nullify
10
10
 
11
+ PARAMETER_NAME_FORMAT = /\A[a-z][a-z0-9_]*\z/
12
+ RESERVED_PARAMETER_NAMES = %w[token titled bordered theme wire id action controller format].freeze
13
+
11
14
  validates :name, presence: true, on: :update
12
15
  validate :statement_must_be_readonly
16
+ validate :parameters_are_declared
13
17
 
14
18
  before_validation :set_default_name, on: :create
19
+ before_validation :normalize_parameters
15
20
 
16
21
  def set_default_name
17
22
  self.name ||= "Untitled query"
18
23
  end
19
24
 
25
+ def statement?
26
+ statement.present?
27
+ end
28
+
29
+ def statement_parameter_names
30
+ statement.to_s.scan(StatementBinds::PLACEHOLDER).flatten.uniq
31
+ end
32
+
33
+ def stored_parameter_definitions
34
+ stored = normalized_parameter_rows(parameters).index_by { |row| row["name"] }
35
+ statement_parameter_names.filter_map { |name| stored[name] }
36
+ end
37
+
38
+ def parameter_definitions
39
+ stored = stored_parameter_definitions.index_by { |row| row["name"] }
40
+ statement_parameter_names.map do |name|
41
+ stored[name] || { "name" => name, "type" => "string", "default" => "" }
42
+ end
43
+ end
44
+
20
45
  private
21
46
 
47
+ def normalize_parameters
48
+ self.parameters = stored_parameter_definitions
49
+ end
50
+
51
+ def normalized_parameter_rows(value)
52
+ Array(value).filter_map { |row| normalized_parameter_row(row) }
53
+ end
54
+
55
+ def normalized_parameter_row(row)
56
+ return unless row.respond_to?(:stringify_keys)
57
+
58
+ attrs = row.stringify_keys
59
+ name = attrs["name"].to_s.strip
60
+ return if name.blank?
61
+
62
+ {
63
+ "name" => name,
64
+ "type" => attrs["type"].to_s.strip,
65
+ "default" => attrs["default"].to_s.strip
66
+ }
67
+ end
68
+
69
+ def parameters_are_declared
70
+ names = []
71
+ parameter_definitions.each do |row|
72
+ name = row["name"]
73
+ unless name.match?(PARAMETER_NAME_FORMAT)
74
+ errors.add(:parameters, "include an invalid name")
75
+ next
76
+ end
77
+
78
+ errors.add(:parameters, "cannot use #{name}") if RESERVED_PARAMETER_NAMES.include?(name)
79
+
80
+ if names.include?(name)
81
+ errors.add(:parameters, "include a duplicate name")
82
+ else
83
+ names << name
84
+ end
85
+
86
+ if ParameterValue::TYPES.exclude?(row["type"])
87
+ errors.add(:parameters, "must be string, integer, date, datetime, uuid, or boolean")
88
+ elsif !ParameterValue.valid_default?(row["type"], row["default"])
89
+ errors.add(:parameters, "include an invalid default")
90
+ end
91
+ end
92
+ end
93
+
22
94
  def statement_must_be_readonly
23
95
  message = ReadonlySql.error_message(statement, allow_blank: true)
24
96
  errors.add(:statement, message) if message
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nquery
4
+ class ApplicationService
5
+ def self.call(...)
6
+ new(...).call
7
+ end
8
+ end
9
+ end