-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
core.clj
1303 lines (1187 loc) · 55.1 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns metabase.automagic-dashboards.core
"Automatically generate questions and dashboards based on predefined
heuristics."
(:require [buddy.core.codecs :as codecs]
[cheshire.core :as json]
[clj-time
[core :as t]
[format :as t.format]]
[clojure
[string :as str]
[walk :as walk]]
[clojure.math.combinatorics :as combo]
[clojure.tools.logging :as log]
[kixi.stats
[core :as stats]
[math :as math]]
[medley.core :as m]
[metabase
[driver :as driver]
[related :as related]
[util :as u]]
[metabase.automagic-dashboards
[filters :as filters]
[populate :as populate]
[rules :as rules]]
[metabase.mbql
[normalize :as normalize]
[util :as mbql.u]]
[metabase.models
[card :as card :refer [Card]]
[database :refer [Database]]
[field :as field :refer [Field]]
[interface :as mi]
[metric :as metric :refer [Metric]]
[query :refer [Query]]
[segment :refer [Segment]]
[table :refer [Table]]]
[metabase.query-processor.util :as qp.util]
[metabase.sync.analyze.classify :as classify]
[metabase.util
[date :as date]
[i18n :as ui18n :refer [trs tru]]]
[ring.util.codec :as codec]
[schema.core :as s]
[toucan.db :as db])
(:import java.util.TimeZone))
(def ^:private public-endpoint "/auto/dashboard/")
(def ^:private ^{:arglists '([field])} id-or-name
(some-fn :id :name))
(defn ->field
"Return `Field` instance for a given ID or name in the context of root."
[root id-or-name]
(let [id-or-name (if (sequential? id-or-name)
(filters/field-reference->id id-or-name)
id-or-name)]
(if (->> root :source (instance? (type Table)))
(Field id-or-name)
(when-let [field (->> root
:source
:result_metadata
(m/find-first (comp #{id-or-name} :name)))]
(-> field
(update :base_type keyword)
(update :special_type keyword)
field/map->FieldInstance
(classify/run-classifiers {}))))))
(def ^{:arglists '([root])} source-name
"Return the (display) name of the soruce of a given root object."
(comp (some-fn :display_name :name) :source))
(def ^:private op->name
{:sum (tru "sum")
:avg (tru "average")
:min (tru "minumum")
:max (tru "maximum")
:count (tru "number")
:distinct (tru "distinct count")
:stddev (tru "standard deviation")
:cum-count (tru "cumulative count")
:cum-sum (tru "cumulative sum")})
(def ^:private ^{:arglists '([metric])} saved-metric?
(every-pred (partial mbql.u/is-clause? :metric)
(complement mbql.u/ga-metric-or-segment?)))
(def ^:private ^{:arglists '([metric])} custom-expression?
(partial mbql.u/is-clause? :named))
(def ^:private ^{:arglists '([metric])} adhoc-metric?
(complement (some-fn saved-metric? custom-expression?)))
(defn metric-name
"Return the name of the metric or name by describing it."
[[op & args :as metric]]
(cond
(mbql.u/ga-metric-or-segment? metric) (-> args first str (subs 3) str/capitalize)
(adhoc-metric? metric) (-> op qp.util/normalize-token op->name)
(saved-metric? metric) (-> args first Metric :name)
:else (second args)))
(defn metric-op
"Return the name op of the metric"
[[op & args :as metric]]
(if (saved-metric? metric)
(-> args first Metric (get-in [:definition :aggregation 0 0]))
op))
(defn- join-enumeration
[xs]
(if (next xs)
(tru "{0} and {1}" (str/join ", " (butlast xs)) (last xs))
(first xs)))
(defn- metric->description
[root aggregation-clause]
(join-enumeration
(for [metric (if (sequential? (first aggregation-clause))
aggregation-clause
[aggregation-clause])]
(if (adhoc-metric? metric)
(tru "{0} of {1}" (metric-name metric) (or (some->> metric
second
(->field root)
:display_name)
(source-name root)))
(metric-name metric)))))
(defn- question-description
[root question]
(let [aggregations (->> (get-in question [:dataset_query :query :aggregation])
(metric->description root))
dimensions (->> (get-in question [:dataset_query :query :breakout])
(mapcat filters/collect-field-references)
(map (comp :display_name
(partial ->field root)))
join-enumeration)]
(if dimensions
(tru "{0} by {1}" aggregations dimensions)
aggregations)))
(def ^{:arglists '([x])} encode-base64-json
"Encode given object as base-64 encoded JSON."
(comp codec/base64-encode codecs/str->bytes json/encode))
(defn- ga-table?
[table]
(isa? (:entity_type table) :entity/GoogleAnalyticsTable))
(defmulti
^{:doc ""
:arglists '([entity])}
->root type)
(defmethod ->root (type Table)
[table]
{:entity table
:full-name (if (ga-table? table)
(:display_name table)
(tru "{0} table" (:display_name table)))
:short-name (:display_name table)
:source table
:database (:db_id table)
:url (format "%stable/%s" public-endpoint (u/get-id table))
:rules-prefix ["table"]})
(defmethod ->root (type Segment)
[segment]
(let [table (-> segment :table_id Table)]
{:entity segment
:full-name (tru "{0} in the {1} segment" (:display_name table) (:name segment))
:short-name (:display_name table)
:comparison-name (tru "{0} segment" (:name segment))
:source table
:database (:db_id table)
:query-filter [:segment (u/get-id segment)]
:url (format "%ssegment/%s" public-endpoint (u/get-id segment))
:rules-prefix ["table"]}))
(defmethod ->root (type Metric)
[metric]
(let [table (-> metric :table_id Table)]
{:entity metric
:full-name (if (:id metric)
(tru "{0} metric" (:name metric))
(:name metric))
:short-name (:name metric)
:source table
:database (:db_id table)
;; We use :id here as it might not be a concrete field but rather one from a nested query which
;; does not have an ID.
:url (format "%smetric/%s" public-endpoint (:id metric))
:rules-prefix ["metric"]}))
(defmethod ->root (type Field)
[field]
(let [table (field/table field)]
{:entity field
:full-name (tru "{0} field" (:display_name field))
:short-name (:display_name field)
:source table
:database (:db_id table)
;; We use :id here as it might not be a concrete metric but rather one from a nested query
;; which does not have an ID.
:url (format "%sfield/%s" public-endpoint (:id field))
:rules-prefix ["field"]}))
(def ^:private ^{:arglists '([card-or-question])} nested-query?
(comp qp.util/query->source-card-id :dataset_query))
(def ^:private ^{:arglists '([card-or-question])} native-query?
(comp #{:native} qp.util/normalize-token #(get-in % [:dataset_query :type])))
(def ^:private ^{:arglists '([card-or-question])} source-question
(comp Card qp.util/query->source-card-id :dataset_query))
(defn- table-like?
[card-or-question]
(nil? (get-in card-or-question [:dataset_query :query :aggregation])))
(defn- table-id
"Get the Table ID from `card-or-question`, which can be either a Card from the DB (which has a `:table_id` property)
or an ad-hoc query (referred to as a 'question' in this namespace) created with the
`metabase.models.query/adhoc-query` function, which has a `:table-id` property."
;; TODO - probably better if we just changed `adhoc-query` to use the same keys as Cards (e.g. `:table_id`) so we
;; didn't need this function, seems like something that would be too easy to forget
[card-or-question]
(or (:table_id card-or-question)
(:table-id card-or-question)))
(defn- source
[card]
(cond
(nested-query? card) (-> card
source-question
(assoc :entity_type :entity/GenericTable))
(native-query? card) (-> card (assoc :entity_type :entity/GenericTable))
:else (-> card table-id Table)))
(defmethod ->root (type Card)
[card]
(let [source (source card)]
{:entity card
:source source
:database (:database_id card)
:query-filter (get-in card [:dataset_query :query :filter])
:full-name (tru "\"{0}\" question" (:name card))
:short-name (source-name {:source source})
:url (format "%squestion/%s" public-endpoint (u/get-id card))
:rules-prefix [(if (table-like? card)
"table"
"question")]}))
(defmethod ->root (type Query)
[query]
(let [source (source query)]
{:entity query
:source source
:database (:database-id query)
:query-filter (get-in query [:dataset_query :query :filter])
:full-name (cond
(native-query? query) (tru "Native query")
(table-like? query) (-> source ->root :full-name)
:else (question-description {:source source} query))
:short-name (source-name {:source source})
:url (format "%sadhoc/%s" public-endpoint (encode-base64-json (:dataset_query query)))
:rules-prefix [(if (table-like? query)
"table"
"question")]}))
(defmulti
^{:doc "Get a reference for a given model to be injected into a template
(either MBQL, native query, or string)."
:arglists '([template-type model])
:private true}
->reference (fn [template-type model]
[template-type (type model)]))
(defn- optimal-datetime-resolution
[field]
(if-let [[earliest latest] (some->> field
:fingerprint
:type
:type/DateTime
((juxt :earliest :latest))
(map date/str->date-time))]
(condp > (t/in-hours (t/interval earliest latest))
3 :minute
(* 24 7) :hour
(* 24 30 6) :day
(* 24 30 12 10) :month
:year)
:day))
(defmethod ->reference [:mbql (type Field)]
[_ {:keys [fk_target_field_id id link aggregation name base_type] :as field}]
(let [reference (cond
link [:fk-> link id]
fk_target_field_id [:fk-> id fk_target_field_id]
id [:field-id id]
:else [:field-literal name base_type])]
(cond
(isa? base_type :type/DateTime)
[:datetime-field reference (or aggregation
(optimal-datetime-resolution field))]
(and aggregation
(isa? base_type :type/Number))
[:binning-strategy reference aggregation]
:else
reference)))
(defmethod ->reference [:string (type Field)]
[_ {:keys [display_name full-name]}]
(or full-name display_name))
(defmethod ->reference [:string (type Table)]
[_ {:keys [display_name full-name]}]
(or full-name display_name))
(defmethod ->reference [:string (type Metric)]
[_ {:keys [name full-name]}]
(or full-name name))
(defmethod ->reference [:mbql (type Metric)]
[_ {:keys [id definition]}]
(if id
[:metric id]
(-> definition :aggregation first)))
(defmethod ->reference [:native (type Field)]
[_ field]
(field/qualified-name field))
(defmethod ->reference [:native (type Table)]
[_ {:keys [name]}]
name)
(defmethod ->reference :default
[_ form]
(or (cond-> form
(map? form) ((some-fn :full-name :name) form))
form))
(defn- field-isa?
[{:keys [base_type special_type]} t]
(or (isa? (keyword special_type) t)
(isa? (keyword base_type) t)))
(defn- key-col?
"Workaround for our leaky type system which conflates types with properties."
[{:keys [base_type special_type name]}]
(and (isa? base_type :type/Number)
(or (#{:type/PK :type/FK} special_type)
(let [name (str/lower-case name)]
(or (= name "id")
(str/starts-with? name "id_")
(str/ends-with? name "_id"))))))
(def ^:private field-filters
{:fieldspec (fn [fieldspec]
(if (and (string? fieldspec)
(rules/ga-dimension? fieldspec))
(comp #{fieldspec} :name)
(fn [{:keys [special_type target] :as field}]
(cond
;; This case is mostly relevant for native queries
(#{:type/PK :type/FK} fieldspec)
(isa? special_type fieldspec)
target
(recur target)
:else
(and (not (key-col? field))
(field-isa? field fieldspec))))))
:named (fn [name-pattern]
(comp (->> name-pattern
str/lower-case
re-pattern
(partial re-find))
str/lower-case
:name))
:max-cardinality (fn [cardinality]
(fn [field]
(some-> field
(get-in [:fingerprint :global :distinct-count])
(<= cardinality))))})
(defn- filter-fields
"Find all fields belonging to table `table` for which all predicates in
`preds` are true."
[preds fields]
(filter (->> preds
(keep (fn [[k v]]
(when-let [pred (field-filters k)]
(some-> v pred))))
(apply every-pred))
fields))
(defn- filter-tables
[tablespec tables]
(filter #(-> % :entity_type (isa? tablespec)) tables))
(defn- fill-templates
[template-type {:keys [root tables]} bindings s]
(let [bindings (some-fn (merge {"this" (-> root
:entity
(assoc :full-name (:full-name root)))}
bindings)
(comp first #(filter-tables % tables) rules/->entity)
identity)]
(str/replace s #"\[\[(\w+)(?:\.([\w\-]+))?\]\]"
(fn [[_ identifier attribute]]
(let [entity (bindings identifier)
attribute (some-> attribute qp.util/normalize-token)]
(str (or (and (ifn? entity) (entity attribute))
(root attribute)
(->reference template-type entity))))))))
(defn- field-candidates
[context {:keys [field_type links_to named max_cardinality] :as constraints}]
(if links_to
(filter (comp (->> (filter-tables links_to (:tables context))
(keep :link)
set)
u/get-id)
(field-candidates context (dissoc constraints :links_to)))
(let [[tablespec fieldspec] field_type]
(if fieldspec
(mapcat (fn [table]
(some->> table
:fields
(filter-fields {:fieldspec fieldspec
:named named
:max-cardinality max_cardinality})
(map #(assoc % :link (:link table)))))
(filter-tables tablespec (:tables context)))
(filter-fields {:fieldspec tablespec
:named named
:max-cardinality max_cardinality}
(-> context :source :fields))))))
(defn- make-binding
[context [identifier definition]]
(->> definition
(field-candidates context)
(map #(->> (merge % definition)
vector ; we wrap these in a vector to make merging easier (see `bind-dimensions`)
(assoc definition :matches)
(hash-map (name identifier))))))
(def ^:private ^{:arglists '([definitions])} most-specific-definition
"Return the most specific defintion among `definitions`.
Specificity is determined based on:
1) how many ancestors `field_type` has (if field_type has a table prefix,
ancestors for both table and field are counted);
2) if there is a tie, how many additional filters (`named`, `max_cardinality`,
`links_to`, ...) are used;
3) if there is still a tie, `score`."
(comp last (partial sort-by (comp (fn [[_ definition]]
[(transduce (map (comp count ancestors))
+
(:field_type definition))
(count definition)
(:score definition)])
first))))
(defn- bind-dimensions
"Bind fields to dimensions and resolve overloading.
Each field will be bound to only one dimension. If multiple dimension definitions
match a single field, the field is bound to the most specific definition used
(see `most-specific-defintion` for details)."
[context dimensions]
(->> dimensions
(mapcat (comp (partial make-binding context) first))
(group-by (comp id-or-name first :matches val first))
(map (comp most-specific-definition val))
(apply merge-with (fn [a b]
(case (compare (:score a) (:score b))
1 a
0 (update a :matches concat (:matches b))
-1 b))
{})))
(defn- build-order-by
[dimensions metrics order-by]
(let [dimensions (set dimensions)]
(for [[identifier ordering] (map first order-by)]
[(if (= ordering "ascending")
:asc
:desc)
(if (dimensions identifier)
[:dimension identifier]
[:aggregation (u/index-of #{identifier} metrics)])])))
(defn- build-query
([context bindings filters metrics dimensions limit order_by]
(walk/postwalk
(fn [subform]
(if (rules/dimension-form? subform)
(let [[_ identifier opts] subform]
(->reference :mbql (-> identifier bindings (merge opts))))
subform))
{:type :query
:database (-> context :root :database)
:query (cond-> {:source-table (if (->> context :source (instance? (type Table)))
(-> context :source u/get-id)
(->> context :source u/get-id (str "card__")))}
(seq filters)
(assoc :filter (apply
vector
:and
(map (comp (partial normalize/normalize-fragment [:query :filter])
:filter)
filters)))
(seq dimensions)
(assoc :breakout dimensions)
(seq metrics)
(assoc :aggregation (map :metric metrics))
limit
(assoc :limit limit)
(seq order_by)
(assoc :order-by order_by))}))
([context bindings query]
{:type :native
:native {:query (fill-templates :native context bindings query)}
:database (-> context :root :database)}))
(defn- has-matches?
[dimensions definition]
(->> definition
rules/collect-dimensions
(every? (partial get dimensions))))
(defn- resolve-overloading
"Find the overloaded definition with the highest `score` for which all referenced dimensions have at least one
matching field."
[{:keys [dimensions]} definitions]
(apply merge-with (fn [a b]
(case (map (partial has-matches? dimensions) [a b])
[true false] a
[false true] b
(max-key :score a b)))
definitions))
(defn- instantate-visualization
[[k v] dimensions metrics]
(let [dimension->name (comp vector :name dimensions)
metric->name (comp vector first :metric metrics)]
[k (-> v
(u/update-when :map.latitude_column dimension->name)
(u/update-when :map.longitude_column dimension->name)
(u/update-when :graph.metrics metric->name)
(u/update-when :graph.dimensions dimension->name))]))
(defn capitalize-first
"Capitalize only the first letter in a given string."
[s]
(let [s (str s)]
(str (str/upper-case (subs s 0 1)) (subs s 1))))
(defn- instantiate-metadata
[x context bindings]
(-> (walk/postwalk
(fn [form]
(if (ui18n/localized-string? form)
(let [s (str form)
new-s (fill-templates :string context bindings s)]
(if (not= new-s s)
(capitalize-first new-s)
s))
form))
x)
(u/update-when :visualization #(instantate-visualization % bindings (:metrics context)))))
(defn- valid-breakout-dimension?
[{:keys [base_type engine fingerprint aggregation]}]
(or (nil? aggregation)
(not (isa? base_type :type/Number))
(and (driver/supports? engine :binning)
(-> fingerprint :type :type/Number :min))))
(defn- singular-cell-dimensions
[root]
(letfn [(collect-dimensions [[op & args]]
(case (some-> op qp.util/normalize-token)
:and (mapcat collect-dimensions args)
:= (filters/collect-field-references args)
nil))]
(->> root
:cell-query
collect-dimensions
(map filters/field-reference->id)
set)))
(defn- card-candidates
"Generate all potential cards given a card definition and bindings for
dimensions, metrics, and filters."
[context {:keys [metrics filters dimensions score limit order_by query] :as card}]
(let [order_by (build-order-by dimensions metrics order_by)
metrics (map (partial get (:metrics context)) metrics)
filters (cond-> (map (partial get (:filters context)) filters)
(:query-filter context) (conj {:filter (:query-filter context)}))
score (if query
score
(* (or (->> dimensions
(map (partial get (:dimensions context)))
(concat filters metrics)
(transduce (keep :score) stats/mean))
rules/max-score)
(/ score rules/max-score)))
dimensions (map (comp (partial into [:dimension]) first) dimensions)
used-dimensions (rules/collect-dimensions [dimensions metrics filters query])
cell-dimension? (->> context :root singular-cell-dimensions)]
(->> used-dimensions
(map (some-fn #(get-in (:dimensions context) [% :matches])
(comp #(filter-tables % (:tables context)) rules/->entity)))
(apply combo/cartesian-product)
(map (partial zipmap used-dimensions))
(filter (fn [bindings]
(->> dimensions
(map (fn [[_ identifier opts]]
(merge (bindings identifier) opts)))
(every? (every-pred valid-breakout-dimension?
(complement (comp cell-dimension? id-or-name)))))))
(map (fn [bindings]
(let [query (if query
(build-query context bindings query)
(build-query context bindings
filters
metrics
dimensions
limit
order_by))]
(-> card
(instantiate-metadata context (->> metrics
(map :name)
(zipmap (:metrics card))
(merge bindings)))
(assoc :dataset_query query
:metrics (for [metric metrics]
{:name ((some-fn :name (comp metric-name :metric)) metric)
:op (-> metric :metric metric-op)})
:dimensions (map (comp :name bindings second) dimensions)
:score score))))))))
(defn- matching-rules
"Return matching rules orderd by specificity.
Most specific is defined as entity type specification the longest ancestor
chain."
[rules {:keys [source entity]}]
(let [table-type (or (:entity_type source) :entity/GenericTable)]
(->> rules
(filter (fn [{:keys [applies_to]}]
(let [[entity-type field-type] applies_to]
(and (isa? table-type entity-type)
(or (nil? field-type)
(field-isa? entity field-type))))))
(sort-by :specificity >))))
(defn- linked-tables
"Return all tables accessable from a given table with the paths to get there.
If there are multiple FKs pointing to the same table, multiple entries will
be returned."
[table]
(for [{:keys [id target]} (field/with-targets
(db/select Field
:table_id (u/get-id table)
:fk_target_field_id [:not= nil]
:active true))
:when (some-> target mi/can-read?)]
(-> target field/table (assoc :link id))))
(def ^:private ^{:arglists '([source])} source->engine
(comp :engine Database (some-fn :db_id :database_id)))
(defmulti
^{:private true
:arglists '([context entity])}
inject-root (fn [_ entity] (type entity)))
(defmethod inject-root (type Field)
[context field]
(let [field (assoc field
:link (->> context
:tables
(m/find-first (comp #{(:table_id field)} u/get-id))
:link)
:engine (-> context :source source->engine))]
(update context :dimensions
(fn [dimensions]
(->> dimensions
(keep (fn [[identifier definition]]
(when-let [matches (->> definition
:matches
(remove (comp #{(id-or-name field)} id-or-name))
not-empty)]
[identifier (assoc definition :matches matches)])))
(concat [["this" {:matches [field]
:name (:display_name field)
:score rules/max-score}]])
(into {}))))))
(defmethod inject-root (type Metric)
[context metric]
(update context :metrics assoc "this" {:metric (->reference :mbql metric)
:name (:name metric)
:score rules/max-score}))
(defmethod inject-root :default
[context _]
context)
(s/defn ^:private make-context
[root, rule :- rules/Rule]
{:pre [(:source root)]}
(let [source (:source root)
tables (concat [source] (when (instance? (type Table) source)
(linked-tables source)))
engine (source->engine source)
table->fields (if (instance? (type Table) source)
(comp (->> (db/select Field
:table_id [:in (map u/get-id tables)]
:visibility_type "normal"
:active true)
field/with-targets
(map #(assoc % :engine engine))
(group-by :table_id))
u/get-id)
(->> source
:result_metadata
(map (fn [field]
(-> field
(update :base_type keyword)
(update :special_type keyword)
field/map->FieldInstance
(classify/run-classifiers {})
(assoc :engine engine))))
constantly))]
(as-> {:source (assoc source :fields (table->fields source))
:root root
:tables (map #(assoc % :fields (table->fields %)) tables)
:query-filter (filters/inject-refinement (:query-filter root)
(:cell-query root))} context
(assoc context :dimensions (bind-dimensions context (:dimensions rule)))
(assoc context :metrics (resolve-overloading context (:metrics rule)))
(assoc context :filters (resolve-overloading context (:filters rule)))
(inject-root context (:entity root)))))
(defn- make-cards
[context {:keys [cards]}]
(some->> cards
(map first)
(map-indexed (fn [position [identifier card]]
(some->> (assoc card :position position)
(card-candidates context)
not-empty
(hash-map (name identifier)))))
(apply merge-with (partial max-key (comp :score first)) {})
vals
(apply concat)))
(defn- make-dashboard
([root rule]
(make-dashboard root rule {:tables [(:source root)]
:root root}))
([root rule context]
(-> rule
(select-keys [:title :description :transient_title :groups])
(cond->
(:comparison? root)
(update :groups (partial m/map-vals (fn [{:keys [title comparison_title] :as group}]
(assoc group :title (or comparison_title title))))))
(instantiate-metadata context {}))))
(s/defn ^:private apply-rule
[root, rule :- rules/Rule]
(let [context (make-context root rule)
dashboard (make-dashboard root rule context)
filters (->> rule
:dashboard_filters
(mapcat (comp :matches (:dimensions context)))
(remove (comp (singular-cell-dimensions root) id-or-name)))
cards (make-cards context rule)]
(when (or (not-empty cards)
(-> rule :cards nil?))
[(assoc dashboard
:filters filters
:cards cards)
rule
context])))
(def ^:private ^:const ^Long max-related 8)
(def ^:private ^:const ^Long max-cards 15)
(defn ->related-entity
"Turn `entity` into an entry in `:related.`"
[entity]
(let [root (->root entity)
rule (->> root
(matching-rules (rules/get-rules (:rules-prefix root)))
first)
dashboard (make-dashboard root rule)]
{:url (:url root)
:title (:full-name root)
:description (:description dashboard)}))
(defn- related-entities
[root]
(-> root
:entity
related/related
(update :fields (partial remove key-col?))
(->> (m/map-vals (comp (partial map ->related-entity) rules/ensure-seq)))))
(s/defn ^:private indepth
[root, rule :- (s/maybe rules/Rule)]
(->> (rules/get-rules (concat (:rules-prefix root) [(:rule rule)]))
(keep (fn [indepth]
(when-let [[dashboard _ _] (apply-rule root indepth)]
{:title ((some-fn :short-title :title) dashboard)
:description (:description dashboard)
:url (format "%s/rule/%s/%s" (:url root) (:rule rule) (:rule indepth))})))
(hash-map :indepth)))
(defn- drilldown-fields
[context]
(when (and (->> context :root :source (instance? (type Table)))
(-> context :root :entity ga-table? not))
(->> context
:dimensions
vals
(mapcat :matches)
filters/interesting-fields
(map ->related-entity)
(hash-map :drilldown-fields))))
(defn- comparisons
[root]
{:compare (concat
(for [segment (->> root :entity related/related :segments (map ->root))]
{:url (str (:url root) "/compare/segment/" (-> segment :entity u/get-id))
:title (tru "Compare with {0}" (:comparison-name segment))
:description ""})
(when ((some-fn :query-filter :cell-query) root)
[{:url (if (->> root :source (instance? (type Table)))
(str (:url root) "/compare/table/" (-> root :source u/get-id))
(str (:url root) "/compare/adhoc/"
(encode-base64-json
{:database (:database root)
:type :query
:query {:source-table (->> root
:source
u/get-id
(str "card__" ))}})))
:title (tru "Compare with entire dataset")
:description ""}]))})
(defn- fill-related
"We fill available slots round-robin style. Each selector is a list of fns that are tried against
`related` in sequence until one matches."
[available-slots selectors related]
(let [pop-first (fn [m ks]
(loop [[k & ks] ks]
(let [item (-> k m first)]
(cond
item [item (update m k rest)]
(empty? ks) [nil m]
:else (recur ks)))))
count-leafs (comp count (partial mapcat val))
[selected related] (reduce-kv
(fn [[selected related] k v]
(loop [[selector & remaining-selectors] v
related related
selected selected]
(let [[next related] (pop-first related (mapcat shuffle selector))
num-selected (count-leafs selected)]
(cond
(= num-selected available-slots)
(reduced [selected related])
next
(recur remaining-selectors related (update selected k conj next))
(empty? remaining-selectors)
[selected related]
:else
(recur remaining-selectors related selected)))))
[{} related]
selectors)
num-selected (count-leafs selected)]
(if (pos? num-selected)
(merge-with concat
selected
(fill-related (- available-slots num-selected) selectors related))
{})))
(def ^:private related-selectors
{(type Table) (let [down [[:indepth] [:segments :metrics] [:drilldown-fields]]
sideways [[:linking-to :linked-from] [:tables]]
compare [[:compare]]]
{:zoom-in [down down down down]
:related [sideways sideways]
:compare [compare compare]})
(type Segment) (let [down [[:indepth] [:segments :metrics] [:drilldown-fields]]
sideways [[:linking-to] [:tables]]
up [[:table]]
compare [[:compare]]]
{:zoom-in [down down down]
:zoom-out [up]
:related [sideways sideways]
:compare [compare compare]})
(type Metric) (let [down [[:drilldown-fields]]
sideways [[:metrics :segments]]
up [[:table]]
compare [[:compare]]]
{:zoom-in [down down]
:zoom-out [up]
:related [sideways sideways sideways]
:compare [compare compare]})
(type Field) (let [sideways [[:fields]]
up [[:table] [:metrics :segments]]
compare [[:compare]]]
{:zoom-out [up]
:related [sideways sideways]
:compare [compare]})
(type Card) (let [down [[:drilldown-fields]]
sideways [[:metrics] [:similar-questions :dashboard-mates]]
up [[:table]]
compare [[:compare]]]
{:zoom-in [down down]
:zoom-out [up]
:related [sideways sideways sideways]
:compare [compare compare]})
(type Query) (let [down [[:drilldown-fields]]
sideways [[:metrics] [:similar-questions]]
up [[:table]]
compare [[:compare]]]
{:zoom-in [down down]
:zoom-out [up]
:related [sideways sideways sideways]
:compare [compare compare]})})
(s/defn ^:private related
"Build a balanced list of related X-rays. General composition of the list is determined for each
root type individually via `related-selectors`. That recepie is then filled round-robin style."
[{:keys [root] :as context}, rule :- (s/maybe rules/Rule)]
(->> (merge (indepth root rule)
(drilldown-fields context)
(related-entities root)
(comparisons root))
(fill-related max-related (related-selectors (-> root :entity type)))))
(defn- filter-referenced-fields
"Return a map of fields referenced in filter cluase."
[root filter-clause]
(->> filter-clause
filters/collect-field-references
(mapcat (fn [[_ & ids]]
(for [id ids]
[id (->field root id)])))
(remove (comp nil? second))
(into {})))
(defn- automagic-dashboard
"Create dashboards for table `root` using the best matching heuristics."
[{:keys [rule show rules-prefix full-name] :as root}]
(if-let [[dashboard rule context] (if rule
(apply-rule root (rules/get-rule rule))
(->> root
(matching-rules (rules/get-rules rules-prefix))
(keep (partial apply-rule root))
;; `matching-rules` returns an `ArraySeq` (via `sort-by`)
;; so `first` realises one element at a time
;; (no chunking).
first))]
(let [show (or show max-cards)]
(log/infof (str (trs "Applying heuristic {0} to {1}." (:rule rule) full-name)))
(log/infof (str (trs "Dimensions bindings:\n{0}"
(->> context
:dimensions
(m/map-vals #(update % :matches (partial map :name)))
u/pprint-to-str))))
(log/infof (str (trs "Using definitions:\nMetrics:\n{0}\nFilters:\n{1}"
(->> context :metrics (m/map-vals :metric) u/pprint-to-str)
(-> context :filters u/pprint-to-str))))
(-> dashboard
(populate/create-dashboard show)
(assoc :related (related context rule)
:more (when (and (not= show :all)