@malloy-publisher/sdk 0.12.0 → 0.12.2

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 (214) hide show
  1. package/README.md +79 -6
  2. package/dist/{RenderedResult-SgDlxzs9.cjs.js → RenderedResult-Cgw4iqev.cjs.js} +1 -1
  3. package/dist/{RenderedResult-D8bCgThO.es.js → RenderedResult-DEjFM1DL.es.js} +2 -2
  4. package/dist/ServerProvider-BRQl_cBo.cjs.js +1 -0
  5. package/dist/{ServerProvider-DBw-thY0.es.js → ServerProvider-RnliA2Ao.es.js} +1084 -723
  6. package/dist/builder/index.cjs.js +1 -1
  7. package/dist/builder/index.es.js +3 -3
  8. package/dist/client/api.d.ts +754 -41
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +120 -110
  11. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +16 -1
  12. package/dist/components/Model/ExplorerPage.d.ts +9 -0
  13. package/dist/components/Model/Model.d.ts +27 -11
  14. package/dist/components/ModelViewer/AccessChips.d.ts +34 -0
  15. package/dist/components/ModelViewer/EmptyRow.d.ts +23 -0
  16. package/dist/components/ModelViewer/Facts.d.ts +15 -0
  17. package/dist/components/ModelViewer/FieldGroup.d.ts +31 -0
  18. package/dist/components/ModelViewer/FieldRow.d.ts +69 -0
  19. package/dist/components/ModelViewer/GivenFacts.d.ts +21 -0
  20. package/dist/components/ModelViewer/HeaderBar.d.ts +75 -0
  21. package/dist/components/ModelViewer/InlineDoc.d.ts +13 -0
  22. package/dist/components/ModelViewer/ModelGivensSection.d.ts +32 -0
  23. package/dist/components/ModelViewer/ModelSection.d.ts +21 -0
  24. package/dist/components/ModelViewer/ModelViewer.d.ts +91 -0
  25. package/dist/components/ModelViewer/QueriesGroup.d.ts +15 -0
  26. package/dist/components/ModelViewer/RowGlyph.d.ts +27 -0
  27. package/dist/components/ModelViewer/RunResult.d.ts +46 -0
  28. package/dist/components/ModelViewer/SampleValues.d.ts +20 -0
  29. package/dist/components/ModelViewer/SchemaJoin.d.ts +51 -0
  30. package/dist/components/ModelViewer/SchemaView.d.ts +52 -0
  31. package/dist/components/ModelViewer/SegmentIcons.d.ts +70 -0
  32. package/dist/components/ModelViewer/SourcesDropdown.d.ts +53 -0
  33. package/dist/components/ModelViewer/SourcesNav.d.ts +25 -0
  34. package/dist/components/ModelViewer/StatusPill.d.ts +56 -0
  35. package/dist/components/ModelViewer/ValueChip.d.ts +17 -0
  36. package/dist/components/ModelViewer/ViewRow.d.ts +36 -0
  37. package/dist/components/ModelViewer/clickableBox.d.ts +29 -0
  38. package/dist/components/ModelViewer/codeDisplay.d.ts +44 -0
  39. package/dist/components/ModelViewer/docAnnotations.d.ts +90 -0
  40. package/dist/components/ModelViewer/explorerModel.d.ts +12 -0
  41. package/dist/components/ModelViewer/extensions.d.ts +94 -0
  42. package/dist/components/ModelViewer/fieldCode.d.ts +74 -0
  43. package/dist/components/ModelViewer/fieldEntities.d.ts +45 -0
  44. package/dist/components/ModelViewer/fieldExpansion.d.ts +41 -0
  45. package/dist/components/ModelViewer/givenUsage.d.ts +71 -0
  46. package/dist/components/ModelViewer/headerCard.d.ts +31 -0
  47. package/dist/components/ModelViewer/httpStatus.d.ts +4 -0
  48. package/dist/components/ModelViewer/icons.d.ts +31 -0
  49. package/dist/components/ModelViewer/index.d.ts +9 -0
  50. package/dist/components/ModelViewer/joinAccess.d.ts +52 -0
  51. package/dist/components/ModelViewer/malloyRunText.d.ts +22 -0
  52. package/dist/components/ModelViewer/malloyText.d.ts +21 -0
  53. package/dist/components/ModelViewer/modelGivens.d.ts +61 -0
  54. package/dist/components/ModelViewer/modelGivensContext.d.ts +9 -0
  55. package/dist/components/ModelViewer/modelHeaderPresentation.d.ts +28 -0
  56. package/dist/components/ModelViewer/modelTextDeclarations.d.ts +32 -0
  57. package/dist/components/ModelViewer/modelTextParse.d.ts +27 -0
  58. package/dist/components/ModelViewer/namedQueryCode.d.ts +12 -0
  59. package/dist/components/ModelViewer/offSurface.d.ts +54 -0
  60. package/dist/components/ModelViewer/rowLayers.d.ts +30 -0
  61. package/dist/components/ModelViewer/runGate.d.ts +49 -0
  62. package/dist/components/ModelViewer/schemaModel.d.ts +109 -0
  63. package/dist/components/ModelViewer/sectionOpenCommand.d.ts +45 -0
  64. package/dist/components/ModelViewer/sourceAccess.d.ts +67 -0
  65. package/dist/components/ModelViewer/sourceLineage.d.ts +14 -0
  66. package/dist/components/ModelViewer/sourcePicker.d.ts +66 -0
  67. package/dist/components/ModelViewer/surface.d.ts +47 -0
  68. package/dist/components/ModelViewer/text.d.ts +6 -0
  69. package/dist/components/ModelViewer/theme.d.ts +63 -0
  70. package/dist/components/ModelViewer/tokens.d.ts +52 -0
  71. package/dist/components/ModelViewer/ui.d.ts +48 -0
  72. package/dist/components/ModelViewer/useDimensionSamples.d.ts +76 -0
  73. package/dist/components/ModelViewer/useModelSources.d.ts +92 -0
  74. package/dist/components/ModelViewer/useRunQuery.d.ts +115 -0
  75. package/dist/components/ReportBuilder/loadMalloy.d.ts +4 -0
  76. package/dist/components/ServerProvider.d.ts +17 -2
  77. package/dist/components/filter/utils.d.ts +1 -1
  78. package/dist/components/given/GivenInput.d.ts +7 -1
  79. package/dist/components/given/GivensPanel.d.ts +3 -1
  80. package/dist/components/given/filterSummary.d.ts +6 -0
  81. package/dist/components/given/useGivenUrlParams.d.ts +11 -0
  82. package/dist/components/index.d.ts +2 -1
  83. package/dist/components/modelPage.d.ts +36 -0
  84. package/dist/hooks/useDimensionalFilterRangeData.d.ts +9 -0
  85. package/dist/hooks/useSuggestOptions.d.ts +26 -2
  86. package/dist/index.cjs.js +47 -19
  87. package/dist/index.es.js +14137 -9697
  88. package/dist/useCompiledDocument-D88_2cGS.cjs.js +143 -0
  89. package/dist/{useCompiledDocument-CXMPtJkJ.es.js → useCompiledDocument-Dmm6xkom.es.js} +6975 -6893
  90. package/dist/utils/filterCondition.d.ts +14 -0
  91. package/dist/utils/malloyLiteral.d.ts +20 -1
  92. package/package.json +2 -2
  93. package/src/components/Materializations/MaterializationDetailDialog.tsx +33 -7
  94. package/src/components/Materializations/Materializations.tsx +47 -4
  95. package/src/components/Materializations/Materializations.versions.spec.tsx +140 -1
  96. package/src/components/Model/ExplorerPage.tsx +269 -0
  97. package/src/components/Model/Model.tsx +66 -250
  98. package/src/components/Model/ModelExplorer.spec.tsx +64 -1
  99. package/src/components/ModelViewer/AccessChips.tsx +149 -0
  100. package/src/components/ModelViewer/EmptyRow.tsx +71 -0
  101. package/src/components/ModelViewer/Facts.tsx +46 -0
  102. package/src/components/ModelViewer/FieldGroup.tsx +137 -0
  103. package/src/components/ModelViewer/FieldRow.tsx +566 -0
  104. package/src/components/ModelViewer/GivenFacts.tsx +89 -0
  105. package/src/components/ModelViewer/HeaderBar.tsx +362 -0
  106. package/src/components/ModelViewer/InlineDoc.tsx +50 -0
  107. package/src/components/ModelViewer/ModelGivensSection.tsx +142 -0
  108. package/src/components/ModelViewer/ModelSection.tsx +98 -0
  109. package/src/components/ModelViewer/ModelViewer.spec.tsx +937 -0
  110. package/src/components/ModelViewer/ModelViewer.tsx +777 -0
  111. package/src/components/ModelViewer/QueriesGroup.tsx +107 -0
  112. package/src/components/ModelViewer/RowGlyph.tsx +138 -0
  113. package/src/components/ModelViewer/RunResult.tsx +298 -0
  114. package/src/components/ModelViewer/SampleValues.tsx +97 -0
  115. package/src/components/ModelViewer/SchemaJoin.tsx +258 -0
  116. package/src/components/ModelViewer/SchemaView.tsx +222 -0
  117. package/src/components/ModelViewer/SegmentIcons.tsx +129 -0
  118. package/src/components/ModelViewer/SourcesDropdown.tsx +265 -0
  119. package/src/components/ModelViewer/SourcesNav.tsx +75 -0
  120. package/src/components/ModelViewer/StatusPill.tsx +145 -0
  121. package/src/components/ModelViewer/ValueChip.tsx +39 -0
  122. package/src/components/ModelViewer/ViewRow.tsx +274 -0
  123. package/src/components/ModelViewer/clickableBox.ts +59 -0
  124. package/src/components/ModelViewer/codeDisplay.spec.ts +176 -0
  125. package/src/components/ModelViewer/codeDisplay.ts +118 -0
  126. package/src/components/ModelViewer/docAnnotations.spec.ts +181 -0
  127. package/src/components/ModelViewer/docAnnotations.ts +244 -0
  128. package/src/components/ModelViewer/docAnnotations.typeDetail.spec.ts +114 -0
  129. package/src/components/ModelViewer/explorerModel.spec.ts +43 -0
  130. package/src/components/ModelViewer/explorerModel.ts +31 -0
  131. package/src/components/ModelViewer/extensions.tsx +112 -0
  132. package/src/components/ModelViewer/fieldCode.spec.ts +168 -0
  133. package/src/components/ModelViewer/fieldCode.ts +118 -0
  134. package/src/components/ModelViewer/fieldEntities.ts +63 -0
  135. package/src/components/ModelViewer/fieldExpansion.spec.ts +116 -0
  136. package/src/components/ModelViewer/fieldExpansion.ts +95 -0
  137. package/src/components/ModelViewer/givenUsage.spec.ts +304 -0
  138. package/src/components/ModelViewer/givenUsage.ts +325 -0
  139. package/src/components/ModelViewer/headerCard.tsx +102 -0
  140. package/src/components/ModelViewer/httpStatus.ts +15 -0
  141. package/src/components/ModelViewer/icons.tsx +67 -0
  142. package/src/components/ModelViewer/index.ts +26 -0
  143. package/src/components/ModelViewer/joinAccess.spec.ts +95 -0
  144. package/src/components/ModelViewer/joinAccess.ts +54 -0
  145. package/src/components/ModelViewer/malloyRunText.spec.ts +48 -0
  146. package/src/components/ModelViewer/malloyRunText.ts +51 -0
  147. package/src/components/ModelViewer/malloyText.spec.ts +47 -0
  148. package/src/components/ModelViewer/malloyText.ts +77 -0
  149. package/src/components/ModelViewer/modelGivens.ts +228 -0
  150. package/src/components/ModelViewer/modelGivensContext.ts +13 -0
  151. package/src/components/ModelViewer/modelHeaderPresentation.spec.ts +31 -0
  152. package/src/components/ModelViewer/modelHeaderPresentation.ts +41 -0
  153. package/src/components/ModelViewer/modelTextDeclarations.spec.ts +336 -0
  154. package/src/components/ModelViewer/modelTextDeclarations.ts +228 -0
  155. package/src/components/ModelViewer/modelTextParse.ts +112 -0
  156. package/src/components/ModelViewer/namedQueryCode.spec.ts +58 -0
  157. package/src/components/ModelViewer/namedQueryCode.ts +26 -0
  158. package/src/components/ModelViewer/offSurface.tsx +124 -0
  159. package/src/components/ModelViewer/rowLayers.tsx +104 -0
  160. package/src/components/ModelViewer/runGate.spec.ts +219 -0
  161. package/src/components/ModelViewer/runGate.ts +145 -0
  162. package/src/components/ModelViewer/schemaModel.defaultSource.spec.ts +126 -0
  163. package/src/components/ModelViewer/schemaModel.queries.spec.ts +37 -0
  164. package/src/components/ModelViewer/schemaModel.ts +300 -0
  165. package/src/components/ModelViewer/sectionOpenCommand.tsx +125 -0
  166. package/src/components/ModelViewer/sourceAccess.spec.ts +130 -0
  167. package/src/components/ModelViewer/sourceAccess.ts +194 -0
  168. package/src/components/ModelViewer/sourceLineage.spec.ts +73 -0
  169. package/src/components/ModelViewer/sourceLineage.ts +38 -0
  170. package/src/components/ModelViewer/sourcePicker.spec.ts +294 -0
  171. package/src/components/ModelViewer/sourcePicker.ts +162 -0
  172. package/src/components/ModelViewer/surface.ts +51 -0
  173. package/src/components/ModelViewer/text.tsx +33 -0
  174. package/src/components/ModelViewer/theme.spec.ts +38 -0
  175. package/src/components/ModelViewer/theme.ts +58 -0
  176. package/src/components/ModelViewer/tokens.ts +87 -0
  177. package/src/components/ModelViewer/ui.tsx +201 -0
  178. package/src/components/ModelViewer/useDimensionSamples.spec.tsx +139 -0
  179. package/src/components/ModelViewer/useDimensionSamples.ts +220 -0
  180. package/src/components/ModelViewer/useModelSources.spec.ts +110 -0
  181. package/src/components/ModelViewer/useModelSources.ts +238 -0
  182. package/src/components/ModelViewer/useRunQuery.spec.ts +50 -0
  183. package/src/components/ModelViewer/useRunQuery.ts +223 -0
  184. package/src/components/Package/Package.agents.spec.tsx +5 -4
  185. package/src/components/Package/Package.tsx +8 -1
  186. package/src/components/ReportBuilder/emptyStart.spec.ts +8 -0
  187. package/src/components/ReportBuilder/loadMalloy.ts +8 -1
  188. package/src/components/ServerProvider.tsx +29 -3
  189. package/src/components/filter/utils.ts +4 -60
  190. package/src/components/given/FilterButton.tsx +4 -1
  191. package/src/components/given/GivenInput.tsx +8 -0
  192. package/src/components/given/GivensPanel.tsx +6 -1
  193. package/src/components/given/filterSummary.spec.ts +31 -1
  194. package/src/components/given/filterSummary.ts +41 -19
  195. package/src/components/given/useGivenUrlParams.spec.tsx +32 -0
  196. package/src/components/given/useGivenUrlParams.ts +49 -14
  197. package/src/components/index.ts +6 -1
  198. package/src/components/legacy/malloynb/Notebook.spec.tsx +38 -4
  199. package/src/components/legacy/malloynb/NotebookCell.tsx +8 -2
  200. package/src/components/modelPage.spec.ts +79 -0
  201. package/src/components/modelPage.ts +48 -0
  202. package/src/hooks/useDimensionFilters.ts +3 -58
  203. package/src/hooks/useDimensionFiltersQuery.ts +3 -58
  204. package/src/hooks/useDimensionalFilterRangeData.spec.ts +57 -0
  205. package/src/hooks/useDimensionalFilterRangeData.ts +8 -63
  206. package/src/hooks/useSuggestOptions.dom.spec.ts +54 -1
  207. package/src/hooks/useSuggestOptions.spec.ts +71 -0
  208. package/src/hooks/useSuggestOptions.ts +102 -12
  209. package/src/utils/filterCondition.spec.ts +87 -0
  210. package/src/utils/filterCondition.ts +66 -0
  211. package/src/utils/malloyLiteral.spec.ts +53 -1
  212. package/src/utils/malloyLiteral.ts +47 -12
  213. package/dist/ServerProvider-BHfg1Ed6.cjs.js +0 -1
  214. package/dist/useCompiledDocument-D7X_K6YU.cjs.js +0 -142
@@ -0,0 +1,304 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ givensDeclaredIn,
7
+ givensForSource,
8
+ givensInheritedBy,
9
+ givensReadBy,
10
+ scanGivensForSource,
11
+ scanGivensOfNamedQuery,
12
+ } from "./givenUsage";
13
+
14
+ const g = (name: string) => ({ name, type: "number", modelFile: "m.malloy" });
15
+ const GIVENS = [g("MIN_AMOUNT"), g("CATEGORY"), g("UNUSED"), g("MIN")];
16
+
17
+ describe("givensReadBy", () => {
18
+ it("finds each declared given a definition reads by $NAME, whole names only", () => {
19
+ expect(
20
+ givensReadBy("is_large is amount >= $MIN_AMOUNT", GIVENS).map(
21
+ (x) => x.name,
22
+ ),
23
+ ).toEqual(["MIN_AMOUNT"]);
24
+ expect(
25
+ givensReadBy(
26
+ "where: category ~ $CATEGORY and amount > $MIN",
27
+ GIVENS,
28
+ ).map((x) => x.name),
29
+ ).toEqual(["CATEGORY", "MIN"]);
30
+ expect(givensReadBy("order_count is count()", GIVENS)).toEqual([]);
31
+ expect(givensReadBy(undefined, GIVENS)).toEqual([]);
32
+ });
33
+
34
+ it("ignores a $NAME in a comment", () => {
35
+ expect(givensReadBy("count() // not $CATEGORY", GIVENS)).toEqual([]);
36
+ });
37
+
38
+ it("ignores a $NAME in a block comment or a string, and reads past a -- inside a string", () => {
39
+ expect(givensReadBy("count() /* was $CATEGORY */", GIVENS)).toEqual([]);
40
+ expect(givensReadBy("note is '$CATEGORY'", GIVENS)).toEqual([]);
41
+ expect(
42
+ givensReadBy(
43
+ "where: code = 'A--B' and amount > $MIN_AMOUNT",
44
+ GIVENS,
45
+ ).map((x) => x.name),
46
+ ).toEqual(["MIN_AMOUNT"]);
47
+ });
48
+ });
49
+
50
+ const TEXT = `##! experimental.givens
51
+ given:
52
+ MIN_AMOUNT :: number is 100
53
+ CATEGORY :: filter<string> is f''
54
+ UNUSED :: number is 1
55
+
56
+ source: orders is pg.table('public.orders') extend {
57
+ dimension: is_large is amount >= $MIN_AMOUNT
58
+ }
59
+
60
+ #(authorize) 'finance' in $GROUPS
61
+ source: targets is pg.sql("SELECT 1") extend {
62
+ measure: n is count()
63
+ }
64
+
65
+ source: narrowed is orders extend {
66
+ where: category ~ $CATEGORY
67
+ }
68
+
69
+ source: vs_targets is targets extend {
70
+ join_one: o is narrowed with category
71
+ }
72
+
73
+ query: q is orders -> { where: amount > $MIN; aggregate: n is count() }
74
+ `;
75
+ const names = (list: ReadonlyArray<{ name: string }>) =>
76
+ list.map((x) => x.name).sort();
77
+
78
+ describe("givensForSource", () => {
79
+ it("keeps reading a source's body past an annotation at column 0 inside it", () => {
80
+ // `a` reads CATEGORY only after a `#(doc)` at column 0 inside its
81
+ // `extend { … }`; `b` reads it too, so it is not a model-wide given.
82
+ const text = [
83
+ "source: a is duckdb.table('a') extend {",
84
+ '#(doc) "The big ones"',
85
+ " dimension: big is category ~ $CATEGORY",
86
+ "}",
87
+ "source: b is duckdb.table('b') extend {",
88
+ " where: category ~ $CATEGORY",
89
+ "}",
90
+ ].join("\n");
91
+ expect(
92
+ givensForSource(text, "a", [g("CATEGORY")]).map((x) => x.name),
93
+ ).toEqual(["CATEGORY"]);
94
+ });
95
+
96
+ it("keeps the givens the source reads, through what it extends, plus those no source reads", () => {
97
+ // UNUSED and MIN are read by no source: model-wide, shown everywhere.
98
+ expect(names(givensForSource(TEXT, "orders", GIVENS))).toEqual([
99
+ "MIN",
100
+ "MIN_AMOUNT",
101
+ "UNUSED",
102
+ ]);
103
+ expect(names(givensForSource(TEXT, "narrowed", GIVENS))).toEqual([
104
+ "CATEGORY",
105
+ "MIN",
106
+ "MIN_AMOUNT",
107
+ "UNUSED",
108
+ ]);
109
+ expect(names(givensForSource(TEXT, "targets", GIVENS))).toEqual([
110
+ "MIN",
111
+ "UNUSED",
112
+ ]);
113
+ });
114
+
115
+ it("follows a join to the source it joins", () => {
116
+ expect(names(givensForSource(TEXT, "vs_targets", GIVENS))).toEqual([
117
+ "CATEGORY",
118
+ "MIN",
119
+ "MIN_AMOUNT",
120
+ "UNUSED",
121
+ ]);
122
+ });
123
+
124
+ it("keeps every given when the text is absent or the source isn't found", () => {
125
+ expect(givensForSource(undefined, "orders", GIVENS)).toEqual(GIVENS);
126
+ expect(givensForSource(TEXT, "missing", GIVENS)).toEqual(GIVENS);
127
+ });
128
+
129
+ it("keeps every given when a source builds on or joins what the file doesn't declare", () => {
130
+ // `regional` comes from the import and may read REGION; `local` reads it
131
+ // here, so without the fallback the scan would settle that only `local`
132
+ // does, and a run on the others would go out without it.
133
+ const text = `import "regions.malloy"
134
+ source: local is duckdb.table('l') extend {
135
+ where: region = $REGION
136
+ }
137
+ source: other is duckdb.table('o') extend {
138
+ where: code = $CODE
139
+ }
140
+ source: on_local is local extend {
141
+ measure: n is count()
142
+ }
143
+ query: by_region is local -> { group_by: region }
144
+ source: via_import is regional extend {
145
+ measure: n is count()
146
+ }
147
+ source: via_include is regional include {
148
+ public: *
149
+ }
150
+ source: via_join is duckdb.table('t') extend {
151
+ join_one: r is regional on r.id = id
152
+ }
153
+ source: via_join_by_name is duckdb.table('t') extend {
154
+ join_one: regional with region_id
155
+ }
156
+ source: via_query is by_region extend {
157
+ measure: n is count()
158
+ }
159
+ source: via_compose is compose(local, regional)
160
+ `;
161
+ const given = [g("REGION"), g("CODE")];
162
+ for (const source of [
163
+ "via_import",
164
+ "via_include",
165
+ "via_join",
166
+ "via_join_by_name",
167
+ "via_query",
168
+ "via_compose",
169
+ ]) {
170
+ expect([source, names(givensForSource(text, source, given))]).toEqual([
171
+ source,
172
+ ["CODE", "REGION"],
173
+ ]);
174
+ }
175
+ // What the file does declare still narrows: a table, and its own source.
176
+ expect(names(givensForSource(text, "local", given))).toEqual(["REGION"]);
177
+ expect(names(givensForSource(text, "on_local", given))).toEqual([
178
+ "REGION",
179
+ ]);
180
+ });
181
+
182
+ it("names the givens it can't tie to the source either way", () => {
183
+ const text = `import { regional } from "regions.malloy"
184
+ source: local is duckdb.table('l') extend {
185
+ where: region = $REGION
186
+ }
187
+ source: overview is regional extend {
188
+ where: region = $REGION
189
+ }
190
+ source: via_import is regional extend {
191
+ measure: n is count()
192
+ }
193
+ `;
194
+ const given = [g("REGION"), g("CODE")];
195
+ const unknown = (source: string) => [
196
+ ...scanGivensForSource(text, source, given).unknown,
197
+ ];
198
+ // Its own text reads REGION; what `regional` reads, it can't see.
199
+ expect(unknown("overview")).toEqual(["CODE"]);
200
+ expect(unknown("via_import")).toEqual(["REGION", "CODE"]);
201
+ // A source declared in another file: none of them.
202
+ expect(unknown("regional")).toEqual(["REGION", "CODE"]);
203
+ // Traced to the end: it can tell.
204
+ expect(unknown("local")).toEqual([]);
205
+ });
206
+
207
+ it("reaches a given an unexported source reads, through what extends or joins it", () => {
208
+ const text = `source: base_orders is pg.table('public.orders') extend {
209
+ where: amount >= $MIN_AMOUNT
210
+ }
211
+
212
+ source: orders is base_orders extend {
213
+ measure: n is count()
214
+ }
215
+
216
+ source: by_target is pg.sql("SELECT 1") extend {
217
+ join_one: b is base_orders with id
218
+ }
219
+ `;
220
+ expect(names(givensForSource(text, "orders", GIVENS))).toContain(
221
+ "MIN_AMOUNT",
222
+ );
223
+ expect(names(givensForSource(text, "by_target", GIVENS))).toContain(
224
+ "MIN_AMOUNT",
225
+ );
226
+ // base_orders isn't exported, so the section says where MIN_AMOUNT comes from.
227
+ const exported = new Set(["orders", "by_target"]);
228
+ expect(givensInheritedBy(text, "orders", GIVENS, exported)).toEqual(
229
+ new Map([["MIN_AMOUNT", ["base_orders"]]]),
230
+ );
231
+ // An exported upstream is a page the reader can open: nothing to name.
232
+ expect(
233
+ givensInheritedBy(
234
+ text,
235
+ "orders",
236
+ GIVENS,
237
+ new Set([...exported, "base_orders"]),
238
+ ),
239
+ ).toEqual(new Map());
240
+ });
241
+ });
242
+
243
+ describe("scanGivensOfNamedQuery", () => {
244
+ const given = [g("REGION"), g("CODE"), g("MIN")];
245
+ const names = (list: ReadonlyArray<{ name: string }>) =>
246
+ list.map((x) => x.name).sort();
247
+ // `items` is a model source whose own scan couldn't tie CODE to it.
248
+ const bySource = new Map([["items", [g("REGION"), g("CODE")]]]);
249
+ const unknownBySource = new Map([["items", new Set(["CODE"])]]);
250
+
251
+ it("takes a source it names, with what that source's scan couldn't tie", () => {
252
+ const scan = scanGivensOfNamedQuery(
253
+ "query: q is items -> { group_by: name }",
254
+ given,
255
+ bySource,
256
+ unknownBySource,
257
+ );
258
+ expect(names(scan.givens)).toEqual(["CODE", "REGION"]);
259
+ expect([...scan.unknown]).toEqual(["CODE"]);
260
+ });
261
+
262
+ it("can't tie any given it doesn't read itself when it runs over what the model doesn't hold", () => {
263
+ // `regional` comes from an import the model doesn't export.
264
+ const scan = scanGivensOfNamedQuery(
265
+ "query: q is regional -> { where: amount > $MIN; group_by: name }",
266
+ given,
267
+ bySource,
268
+ unknownBySource,
269
+ );
270
+ expect(names(scan.givens)).toEqual(["CODE", "MIN", "REGION"]);
271
+ expect([...scan.unknown].sort()).toEqual(["CODE", "REGION"]);
272
+ });
273
+
274
+ it("knows a query over a table reads only what its text does", () => {
275
+ const scan = scanGivensOfNamedQuery(
276
+ "query: q is duckdb.table('t') -> { where: amount > $MIN }",
277
+ given,
278
+ bySource,
279
+ unknownBySource,
280
+ );
281
+ expect(names(scan.givens)).toEqual(["MIN"]);
282
+ expect(scan.unknown.size).toBe(0);
283
+ });
284
+
285
+ it("is every given, none known, without its text", () => {
286
+ const scan = scanGivensOfNamedQuery(undefined, given, bySource);
287
+ expect(names(scan.givens)).toEqual(["CODE", "MIN", "REGION"]);
288
+ expect(scan.unknown.size).toBe(3);
289
+ });
290
+ });
291
+
292
+ describe("givensDeclaredIn", () => {
293
+ it("names the givens a file declares itself, not those it imports", () => {
294
+ const text = `import { CODE } from "codes.malloy"
295
+ // MIN :: number in a comment is not a declaration
296
+ given:
297
+ REGION :: filter<string> is f''
298
+ `;
299
+ expect([
300
+ ...givensDeclaredIn(text, [g("REGION"), g("CODE"), g("MIN")]),
301
+ ]).toEqual(["REGION"]);
302
+ expect(givensDeclaredIn(undefined, [g("REGION")]).size).toBe(0);
303
+ });
304
+ });
@@ -0,0 +1,325 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { escapeRegExp, maskCommentsAndStrings } from "./malloyText";
5
+ import type { GivenInfo } from "./modelGivens";
6
+
7
+ /**
8
+ * Which givens a piece of Malloy reads, found in its text.
9
+ *
10
+ * The compiled model lists a model's givens but not where each is used, so
11
+ * this reads the definitions the page already has: a
12
+ * field's or view's code, and the model file's text. A given is referenced as
13
+ * `$NAME` and its name is a declared identifier, so a whole-name match against
14
+ * the declared list is reliable; comments and strings are masked first
15
+ * (`maskCommentsAndStrings`) so a mention there is not a use. Host-filled givens never reach here (the viewer leaves out its
16
+ * `hostGivenNames`), so `$GROUPS` in a gate is not a reader's given.
17
+ */
18
+ export function givensReadBy(
19
+ code: string | undefined,
20
+ givens: ReadonlyArray<GivenInfo>,
21
+ ): GivenInfo[] {
22
+ if (!code || givens.length === 0) return [];
23
+ const text = maskCommentsAndStrings(code);
24
+ return givens.filter((g) =>
25
+ new RegExp(`\\$${escapeRegExp(g.name)}(?![A-Za-z0-9_])`).test(text),
26
+ );
27
+ }
28
+
29
+ /**
30
+ * The names of the givens a model file declares itself (`NAME :: type`), as
31
+ * opposed to ones it holds because it imports them: the compiled model lists
32
+ * both, and doesn't say which file declared each.
33
+ */
34
+ export function givensDeclaredIn(
35
+ sourceText: string | undefined,
36
+ givens: ReadonlyArray<GivenInfo>,
37
+ ): Set<string> {
38
+ if (!sourceText) return new Set();
39
+ const text = maskCommentsAndStrings(sourceText);
40
+ return new Set(
41
+ givens
42
+ .filter((g) =>
43
+ new RegExp(
44
+ `(?<![A-Za-z0-9_$.])\`?${escapeRegExp(g.name)}\`?\\s*::`,
45
+ ).test(text),
46
+ )
47
+ .map((g) => g.name),
48
+ );
49
+ }
50
+
51
+ /**
52
+ * The givens a named query reads when the model doesn't say which source it
53
+ * runs against: those its declaration names, plus those of every source of
54
+ * the model it names (`givensBySource`, what a run on that source gates on).
55
+ * Undefined without its declaration's text, where every given is the only
56
+ * safe answer.
57
+ */
58
+ export function givensOfNamedQuery(
59
+ code: string | undefined,
60
+ givens: ReadonlyArray<GivenInfo>,
61
+ givensBySource: ReadonlyMap<string, ReadonlyArray<GivenInfo>> | undefined,
62
+ ): GivenInfo[] | undefined {
63
+ if (!code) return undefined;
64
+ return scanGivensOfNamedQuery(code, givens, givensBySource).givens;
65
+ }
66
+
67
+ /**
68
+ * {@link givensOfNamedQuery}, and which of its givens the page can't tie to
69
+ * the query either way (`unknown`): those of a source it names that the scan
70
+ * couldn't follow (`unknownBySource`), and, when the query runs over something
71
+ * that isn't one of the model's sources (an imported source the model doesn't
72
+ * export, another query, a `compose(…)`), every given its own text doesn't
73
+ * read, all of which it then returns. Without its text, every given, none
74
+ * known.
75
+ */
76
+ export function scanGivensOfNamedQuery(
77
+ code: string | undefined,
78
+ givens: ReadonlyArray<GivenInfo>,
79
+ givensBySource: ReadonlyMap<string, ReadonlyArray<GivenInfo>> | undefined,
80
+ unknownBySource?: ReadonlyMap<string, ReadonlySet<string>>,
81
+ ): { givens: GivenInfo[]; unknown: ReadonlySet<string> } {
82
+ if (!code) {
83
+ return {
84
+ givens: [...givens],
85
+ unknown: new Set(givens.map((g) => g.name)),
86
+ };
87
+ }
88
+ const text = maskCommentsAndStrings(code);
89
+ const readHere = new Set(givensReadBy(code, givens).map((g) => g.name));
90
+ const read = new Set(readHere);
91
+ const unknown = new Set<string>();
92
+ const maybe = (name: string) => {
93
+ read.add(name);
94
+ if (!readHere.has(name)) unknown.add(name);
95
+ };
96
+ for (const [source, sourceGivens] of givensBySource ?? []) {
97
+ const named = new RegExp(
98
+ `(?<![A-Za-z0-9_$.])\`?${escapeRegExp(source)}\`?(?![A-Za-z0-9_])`,
99
+ );
100
+ if (!named.test(text)) continue;
101
+ for (const g of sourceGivens) read.add(g.name);
102
+ for (const name of unknownBySource?.get(source) ?? []) maybe(name);
103
+ }
104
+ const head = /^\s*query\s*:\s*`?[A-Za-z_]\w*`?\s+is\s+/.exec(text);
105
+ const base = head
106
+ ? sourceExpressionTarget(text.slice(head[0].length))
107
+ : undefined;
108
+ if (base === undefined || (base !== null && !givensBySource?.has(base))) {
109
+ for (const g of givens) maybe(g.name);
110
+ }
111
+ return { givens: givens.filter((g) => read.has(g.name)), unknown };
112
+ }
113
+
114
+ /**
115
+ * The givens that matter on one source's page: those its own declaration reads
116
+ * (and the sources it extends, derives from or joins, which its queries run
117
+ * through — exported or not), plus the model-wide ones no source reads — a
118
+ * given used only by a top-level query, or by nothing yet, belongs to every
119
+ * page. Falls back to every given when the model's text is absent, when the
120
+ * source's declaration is not one this can find, and when the source builds on
121
+ * something the text doesn't declare (an imported source, a query, a
122
+ * `compose(…)`), whose reads it can't see: a page never hides a control it
123
+ * might need, and a run never goes out without a value it reads.
124
+ */
125
+ export function givensForSource(
126
+ sourceText: string | undefined,
127
+ sourceName: string,
128
+ givens: GivenInfo[],
129
+ ): GivenInfo[] {
130
+ return scanGivensForSource(sourceText, sourceName, givens).givens;
131
+ }
132
+
133
+ /**
134
+ * {@link givensForSource}, and which of the givens it returns the scan can't
135
+ * tie to the source either way (`unknown`), so the page can say a value set for
136
+ * one may not apply. Where it fell back to every given, that is each one the
137
+ * source's own text in this file doesn't read: a source built on an import that
138
+ * reads a given itself is known to read it. Empty where the scan could tell.
139
+ */
140
+ export function scanGivensForSource(
141
+ sourceText: string | undefined,
142
+ sourceName: string,
143
+ givens: GivenInfo[],
144
+ ): { givens: GivenInfo[]; unknown: ReadonlySet<string> } {
145
+ if (givens.length === 0) return { givens: [], unknown: new Set() };
146
+ const walk = walkSource(sourceText, sourceName, givens);
147
+ if (!walk) {
148
+ return {
149
+ givens: [...givens],
150
+ unknown: new Set(givens.map((g) => g.name)),
151
+ };
152
+ }
153
+ if (walk.unresolved) {
154
+ return {
155
+ givens: [...givens],
156
+ unknown: new Set(
157
+ givens.filter((g) => !walk.readHere.has(g.name)).map((g) => g.name),
158
+ ),
159
+ };
160
+ }
161
+ return {
162
+ givens: givens.filter(
163
+ (g) => walk.readHere.has(g.name) || !walk.readByAnySource.has(g.name),
164
+ ),
165
+ unknown: new Set(),
166
+ };
167
+ }
168
+
169
+ /**
170
+ * The givens a source's page shows only because a source it builds on reads
171
+ * them, where that source isn't one the page can open (the model doesn't
172
+ * export it): given name → the unexported sources that read it. A reader sees
173
+ * the control with no field on the page that uses it, so the section names
174
+ * where the given comes from.
175
+ */
176
+ export function givensInheritedBy(
177
+ sourceText: string | undefined,
178
+ sourceName: string,
179
+ givens: GivenInfo[],
180
+ knownSources: ReadonlySet<string>,
181
+ ): Map<string, string[]> {
182
+ const out = new Map<string, string[]>();
183
+ const walk = walkSource(sourceText, sourceName, givens);
184
+ if (!walk) return out;
185
+ const readByShown = new Set<string>();
186
+ for (const name of walk.reached) {
187
+ if (name !== sourceName && !knownSources.has(name)) continue;
188
+ for (const g of givensReadBy(walk.blocks.get(name), givens))
189
+ readByShown.add(g.name);
190
+ }
191
+ for (const name of walk.reached) {
192
+ if (name === sourceName || knownSources.has(name)) continue;
193
+ for (const g of givensReadBy(walk.blocks.get(name), givens)) {
194
+ if (readByShown.has(g.name)) continue;
195
+ out.set(g.name, [...(out.get(g.name) ?? []), name]);
196
+ }
197
+ }
198
+ return out;
199
+ }
200
+
201
+ /** Every source a source's queries run through, and the givens they read. */
202
+ function walkSource(
203
+ sourceText: string | undefined,
204
+ sourceName: string,
205
+ givens: GivenInfo[],
206
+ ) {
207
+ if (!sourceText || givens.length === 0) return undefined;
208
+ const blocks = sourceBlocks(maskCommentsAndStrings(sourceText));
209
+ if (!blocks.has(sourceName)) return undefined;
210
+
211
+ const readByAnySource = new Set<string>();
212
+ for (const block of blocks.values()) {
213
+ for (const g of givensReadBy(block, givens)) readByAnySource.add(g.name);
214
+ }
215
+ // Through every source the model declares, exported or not: a given an
216
+ // unexported base reads is still one this source's queries need.
217
+ const reached = new Set<string>();
218
+ let unresolved = false;
219
+ const visit = (name: string) => {
220
+ if (reached.has(name)) return;
221
+ reached.add(name);
222
+ const block = blocks.get(name);
223
+ if (!block) return;
224
+ const upstream = upstreamOf(block, name, blocks);
225
+ if (upstream.unresolved) unresolved = true;
226
+ for (const source of upstream.sources) visit(source);
227
+ };
228
+ visit(sourceName);
229
+ const readHere = new Set<string>();
230
+ for (const name of reached) {
231
+ for (const g of givensReadBy(blocks.get(name), givens))
232
+ readHere.add(g.name);
233
+ }
234
+ return { blocks, reached, readHere, readByAnySource, unresolved };
235
+ }
236
+
237
+ /** A top-level statement's first line: a declaration keyword or an annotation at column 0. */
238
+ const STATEMENT_START = /^(?:source|query|run|given|import)\b|^#/;
239
+
240
+ /**
241
+ * Source name → its declaration's text, from `source: NAME is` to the next
242
+ * top-level statement. Reads text already masked (`maskCommentsAndStrings`),
243
+ * so its braces are code: a statement starts only outside every brace, and an
244
+ * annotation at column 0 inside `extend { … }` (`#(doc)`, `# bar_chart`) is
245
+ * part of the source it sits in.
246
+ */
247
+ function sourceBlocks(masked: string): Map<string, string> {
248
+ const blocks = new Map<string, string>();
249
+ let current: { name: string; lines: string[] } | undefined;
250
+ let depth = 0;
251
+ const close = () => {
252
+ if (current) blocks.set(current.name, current.lines.join("\n"));
253
+ current = undefined;
254
+ };
255
+ for (const line of masked.split("\n")) {
256
+ const head =
257
+ depth === 0
258
+ ? /^source\s*:\s*`?([A-Za-z_]\w*)`?\s+is\b/.exec(line)
259
+ : null;
260
+ if (head) {
261
+ close();
262
+ current = { name: head[1], lines: [line] };
263
+ } else if (depth === 0 && STATEMENT_START.test(line)) {
264
+ close();
265
+ } else if (current) {
266
+ current.lines.push(line);
267
+ }
268
+ for (const char of line) {
269
+ if (char === "{") depth += 1;
270
+ else if (char === "}") depth = Math.max(0, depth - 1);
271
+ }
272
+ }
273
+ close();
274
+ return blocks;
275
+ }
276
+
277
+ /**
278
+ * What a declaration builds on, its base and its joins' targets: the model's
279
+ * own sources among them, and whether any is something else the text doesn't
280
+ * declare as a source (an imported source, a query, a `compose(…)`), whose
281
+ * givens it can't see. A connection's table or SQL (`duckdb.table(…)`) reads
282
+ * none.
283
+ */
284
+ function upstreamOf(
285
+ block: string,
286
+ name: string,
287
+ declared: ReadonlyMap<string, string>,
288
+ ): { sources: string[]; unresolved: boolean } {
289
+ const sources: string[] = [];
290
+ let unresolved = false;
291
+ const add = (target: string | null | undefined) => {
292
+ if (target === null || target === name) return;
293
+ if (target !== undefined && declared.has(target)) sources.push(target);
294
+ else unresolved = true;
295
+ };
296
+ const head = new RegExp(
297
+ `source\\s*:\\s*\`?${escapeRegExp(name)}\`?\\s+is\\s+`,
298
+ ).exec(block);
299
+ if (head)
300
+ add(sourceExpressionTarget(block.slice(head.index + head[0].length)));
301
+ const join = /join_\w+\s*:\s*`?([A-Za-z_]\w*)`?(\s+is\s+)?/g;
302
+ for (let m = join.exec(block); m; m = join.exec(block)) {
303
+ add(
304
+ m[2]
305
+ ? sourceExpressionTarget(block.slice(m.index + m[0].length))
306
+ : m[1],
307
+ );
308
+ }
309
+ return { sources, unresolved };
310
+ }
311
+
312
+ /**
313
+ * The source a source expression starts from: a name; `null` for a
314
+ * connection's table or SQL (`duckdb.table(…)`), which reads no given; and
315
+ * `undefined` for anything else (`compose(…)`, a parenthesized query), which
316
+ * this can't follow.
317
+ */
318
+ function sourceExpressionTarget(expression: string): string | null | undefined {
319
+ const start = /^`?([A-Za-z_]\w*)`?/.exec(expression);
320
+ if (!start) return undefined;
321
+ const next = expression.slice(start[0].length).trimStart();
322
+ if (next.startsWith(".")) return null;
323
+ if (next.startsWith("(")) return undefined;
324
+ return start[1];
325
+ }