@contractspec/example.analytics-dashboard 3.9.8 → 3.9.10
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.
- package/dist/browser/dashboard/dashboard.enum.js +1 -34
- package/dist/browser/dashboard/dashboard.operation.js +1 -289
- package/dist/browser/dashboard/dashboard.presentation.js +1 -200
- package/dist/browser/dashboard/dashboard.schema.js +1 -126
- package/dist/browser/dashboard/dashboard.test-spec.js +1 -213
- package/dist/browser/dashboard/index.js +1 -299
- package/dist/browser/dashboard.feature.js +1 -683
- package/dist/browser/datasource/posthog-datasource.js +4 -289
- package/dist/browser/docs/analytics-dashboard.docblock.js +5 -49
- package/dist/browser/docs/index.js +5 -49
- package/dist/browser/events.js +1 -81
- package/dist/browser/example.js +1 -42
- package/dist/browser/handlers/analytics.handlers.js +4 -278
- package/dist/browser/handlers/index.js +7 -571
- package/dist/browser/handlers/query.handlers.js +4 -294
- package/dist/browser/index.js +12 -2317
- package/dist/browser/query/index.js +1 -159
- package/dist/browser/query/query.enum.js +1 -11
- package/dist/browser/query/query.operation.js +1 -154
- package/dist/browser/query/query.presentation.js +1 -122
- package/dist/browser/query/query.schema.js +1 -70
- package/dist/browser/query/query.test-spec.js +1 -113
- package/dist/browser/query-engine/index.js +4 -491
- package/dist/browser/seeders/index.js +2 -20
- package/dist/browser/ui/AnalyticsDashboard.js +1 -1115
- package/dist/browser/ui/AnalyticsDashboard.widgets.js +1 -94
- package/dist/browser/ui/AnalyticsQueriesTable.js +1 -188
- package/dist/browser/ui/hooks/index.js +1 -660
- package/dist/browser/ui/hooks/useAnalyticsData.js +1 -657
- package/dist/browser/ui/index.js +5 -1283
- package/dist/browser/ui/renderers/analytics.markdown.js +5 -756
- package/dist/browser/ui/renderers/index.js +5 -756
- package/dist/browser/visualizations/catalog.js +1 -457
- package/dist/browser/visualizations/index.js +1 -611
- package/dist/browser/visualizations/specs.breakdown.js +1 -140
- package/dist/browser/visualizations/specs.performance.js +1 -198
- package/dist/browser/visualizations/widgets.js +1 -595
- package/dist/dashboard/dashboard.enum.js +1 -34
- package/dist/dashboard/dashboard.operation.js +1 -289
- package/dist/dashboard/dashboard.presentation.js +1 -200
- package/dist/dashboard/dashboard.schema.js +1 -126
- package/dist/dashboard/dashboard.test-spec.js +1 -213
- package/dist/dashboard/index.js +1 -299
- package/dist/dashboard.feature.js +1 -683
- package/dist/datasource/posthog-datasource.js +4 -289
- package/dist/docs/analytics-dashboard.docblock.js +5 -49
- package/dist/docs/index.js +5 -49
- package/dist/events.js +1 -81
- package/dist/example.js +1 -42
- package/dist/handlers/analytics.handlers.js +4 -278
- package/dist/handlers/index.js +7 -571
- package/dist/handlers/query.handlers.js +4 -294
- package/dist/index.js +12 -2317
- package/dist/node/dashboard/dashboard.enum.js +1 -34
- package/dist/node/dashboard/dashboard.operation.js +1 -289
- package/dist/node/dashboard/dashboard.presentation.js +1 -200
- package/dist/node/dashboard/dashboard.schema.js +1 -126
- package/dist/node/dashboard/dashboard.test-spec.js +1 -213
- package/dist/node/dashboard/index.js +1 -299
- package/dist/node/dashboard.feature.js +1 -683
- package/dist/node/datasource/posthog-datasource.js +4 -289
- package/dist/node/docs/analytics-dashboard.docblock.js +5 -49
- package/dist/node/docs/index.js +5 -49
- package/dist/node/events.js +1 -81
- package/dist/node/example.js +1 -42
- package/dist/node/handlers/analytics.handlers.js +4 -278
- package/dist/node/handlers/index.js +7 -571
- package/dist/node/handlers/query.handlers.js +4 -294
- package/dist/node/index.js +12 -2317
- package/dist/node/query/index.js +1 -159
- package/dist/node/query/query.enum.js +1 -11
- package/dist/node/query/query.operation.js +1 -154
- package/dist/node/query/query.presentation.js +1 -122
- package/dist/node/query/query.schema.js +1 -70
- package/dist/node/query/query.test-spec.js +1 -113
- package/dist/node/query-engine/index.js +4 -491
- package/dist/node/seeders/index.js +2 -20
- package/dist/node/ui/AnalyticsDashboard.js +1 -1115
- package/dist/node/ui/AnalyticsDashboard.widgets.js +1 -94
- package/dist/node/ui/AnalyticsQueriesTable.js +1 -188
- package/dist/node/ui/hooks/index.js +1 -660
- package/dist/node/ui/hooks/useAnalyticsData.js +1 -657
- package/dist/node/ui/index.js +5 -1283
- package/dist/node/ui/renderers/analytics.markdown.js +5 -756
- package/dist/node/ui/renderers/index.js +5 -756
- package/dist/node/visualizations/catalog.js +1 -457
- package/dist/node/visualizations/index.js +1 -611
- package/dist/node/visualizations/specs.breakdown.js +1 -140
- package/dist/node/visualizations/specs.performance.js +1 -198
- package/dist/node/visualizations/widgets.js +1 -595
- package/dist/query/index.js +1 -159
- package/dist/query/query.enum.js +1 -11
- package/dist/query/query.operation.js +1 -154
- package/dist/query/query.presentation.js +1 -122
- package/dist/query/query.schema.js +1 -70
- package/dist/query/query.test-spec.js +1 -113
- package/dist/query-engine/index.js +4 -491
- package/dist/seeders/index.js +2 -20
- package/dist/ui/AnalyticsDashboard.js +1 -1115
- package/dist/ui/AnalyticsDashboard.widgets.js +1 -94
- package/dist/ui/AnalyticsQueriesTable.js +1 -188
- package/dist/ui/hooks/index.js +1 -660
- package/dist/ui/hooks/useAnalyticsData.js +1 -657
- package/dist/ui/index.js +5 -1283
- package/dist/ui/renderers/analytics.markdown.js +5 -756
- package/dist/ui/renderers/index.js +5 -756
- package/dist/visualizations/catalog.js +1 -457
- package/dist/visualizations/index.js +1 -611
- package/dist/visualizations/specs.breakdown.js +1 -140
- package/dist/visualizations/specs.performance.js +1 -198
- package/dist/visualizations/widgets.js +1 -595
- package/package.json +13 -13
|
@@ -1,571 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
}
|
|
9
|
-
async execute(definition, params) {
|
|
10
|
-
const startTime = Date.now();
|
|
11
|
-
const validation = this.validateQuery(definition);
|
|
12
|
-
if (!validation.valid) {
|
|
13
|
-
return {
|
|
14
|
-
data: [],
|
|
15
|
-
columns: [],
|
|
16
|
-
rowCount: 0,
|
|
17
|
-
executionTimeMs: Date.now() - startTime,
|
|
18
|
-
cached: false,
|
|
19
|
-
error: validation.errors.join(", ")
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
if (!this.reader.queryHogQL) {
|
|
23
|
-
return {
|
|
24
|
-
data: [],
|
|
25
|
-
columns: [],
|
|
26
|
-
rowCount: 0,
|
|
27
|
-
executionTimeMs: Date.now() - startTime,
|
|
28
|
-
cached: false,
|
|
29
|
-
error: "Analytics reader does not support HogQL queries."
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
try {
|
|
33
|
-
const result = await this.executeHogQL(definition, params);
|
|
34
|
-
return {
|
|
35
|
-
data: result.data,
|
|
36
|
-
columns: result.columns,
|
|
37
|
-
rowCount: result.rowCount,
|
|
38
|
-
executionTimeMs: Date.now() - startTime,
|
|
39
|
-
cached: false
|
|
40
|
-
};
|
|
41
|
-
} catch (error) {
|
|
42
|
-
return {
|
|
43
|
-
data: [],
|
|
44
|
-
columns: [],
|
|
45
|
-
rowCount: 0,
|
|
46
|
-
executionTimeMs: Date.now() - startTime,
|
|
47
|
-
cached: false,
|
|
48
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
validateQuery(definition) {
|
|
53
|
-
const errors = [];
|
|
54
|
-
if (definition.type === "SQL" && !definition.sql) {
|
|
55
|
-
errors.push("SQL query is missing.");
|
|
56
|
-
}
|
|
57
|
-
if (definition.type === "AGGREGATION" && !definition.aggregation) {
|
|
58
|
-
errors.push("Aggregation definition is missing.");
|
|
59
|
-
}
|
|
60
|
-
if (definition.type === "METRIC" && !definition.metricIds?.length) {
|
|
61
|
-
errors.push("Metric IDs are missing.");
|
|
62
|
-
}
|
|
63
|
-
if (definition.type === "CUSTOM" && !definition.custom?.handler) {
|
|
64
|
-
errors.push("Custom handler is missing.");
|
|
65
|
-
}
|
|
66
|
-
return { valid: errors.length === 0, errors };
|
|
67
|
-
}
|
|
68
|
-
async executeHogQL(definition, params) {
|
|
69
|
-
if (!this.reader.queryHogQL) {
|
|
70
|
-
throw new Error("Analytics reader does not support HogQL queries.");
|
|
71
|
-
}
|
|
72
|
-
if (definition.type === "SQL") {
|
|
73
|
-
const result = await this.reader.queryHogQL({
|
|
74
|
-
query: definition.sql ?? "",
|
|
75
|
-
values: params.parameters ?? {}
|
|
76
|
-
});
|
|
77
|
-
return mapHogqlResult(result);
|
|
78
|
-
}
|
|
79
|
-
if (definition.type === "AGGREGATION" && definition.aggregation) {
|
|
80
|
-
const { query, values } = buildAggregationQuery(definition.aggregation, params);
|
|
81
|
-
const result = await this.reader.queryHogQL({ query, values });
|
|
82
|
-
return mapHogqlResult(result);
|
|
83
|
-
}
|
|
84
|
-
if (definition.type === "METRIC" && definition.metricIds) {
|
|
85
|
-
const { query, values } = buildMetricQuery(definition.metricIds, params);
|
|
86
|
-
const result = await this.reader.queryHogQL({ query, values });
|
|
87
|
-
return mapHogqlResult(result);
|
|
88
|
-
}
|
|
89
|
-
throw new Error("Unsupported query type for PostHog datasource.");
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
function createPosthogQueryEngine(reader, options) {
|
|
93
|
-
return new PosthogQueryEngine(reader, options);
|
|
94
|
-
}
|
|
95
|
-
function buildMetricQuery(metricIds, params) {
|
|
96
|
-
const range = resolveDateRange(params);
|
|
97
|
-
const values = {
|
|
98
|
-
dateFrom: range?.from.toISOString(),
|
|
99
|
-
dateTo: range?.to.toISOString()
|
|
100
|
-
};
|
|
101
|
-
const metricClauses = metricIds.map((metricId, index) => {
|
|
102
|
-
values[`metric${index}`] = metricId;
|
|
103
|
-
return `event = {metric${index}}`;
|
|
104
|
-
});
|
|
105
|
-
const whereClauses = [
|
|
106
|
-
metricClauses.length ? `(${metricClauses.join(" or ")})` : "",
|
|
107
|
-
range ? "timestamp >= {dateFrom} and timestamp < {dateTo}" : ""
|
|
108
|
-
].filter(Boolean).join(" and ");
|
|
109
|
-
return {
|
|
110
|
-
query: [
|
|
111
|
-
"select",
|
|
112
|
-
" event as metric,",
|
|
113
|
-
" count() as total",
|
|
114
|
-
"from events",
|
|
115
|
-
whereClauses ? `where ${whereClauses}` : "",
|
|
116
|
-
"group by metric"
|
|
117
|
-
].filter(Boolean).join(`
|
|
118
|
-
`),
|
|
119
|
-
values
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
function buildAggregationQuery(aggregation, params) {
|
|
123
|
-
const measures = aggregation.measures.map((measure) => ({
|
|
124
|
-
...measure,
|
|
125
|
-
expression: buildMeasureExpression(measure.field, measure.aggregation)
|
|
126
|
-
}));
|
|
127
|
-
const dimensions = aggregation.dimensions.map((dimension) => ({
|
|
128
|
-
...dimension,
|
|
129
|
-
expression: buildDimensionExpression(dimension.field, dimension.type, dimension.granularity)
|
|
130
|
-
}));
|
|
131
|
-
const selections = [
|
|
132
|
-
...dimensions.map((dimension) => `${dimension.expression} as ${dimension.name}`),
|
|
133
|
-
...measures.map((measure) => `${measure.expression} as ${measure.name}`)
|
|
134
|
-
];
|
|
135
|
-
const values = {};
|
|
136
|
-
const filters = buildFilterClauses(aggregation, params, values);
|
|
137
|
-
const limit = aggregation.limit ?? 100;
|
|
138
|
-
const orderBy = aggregation.orderBy?.length ? `order by ${aggregation.orderBy.map((order) => `${order.field} ${order.direction}`).join(", ")}` : "";
|
|
139
|
-
return {
|
|
140
|
-
query: [
|
|
141
|
-
"select",
|
|
142
|
-
` ${selections.join(`,
|
|
143
|
-
`)}`,
|
|
144
|
-
`from ${aggregation.source}`,
|
|
145
|
-
filters.length ? `where ${filters.join(" and ")}` : "",
|
|
146
|
-
dimensions.length ? `group by ${dimensions.map((d) => d.name).join(", ")}` : "",
|
|
147
|
-
orderBy,
|
|
148
|
-
`limit ${limit}`
|
|
149
|
-
].filter(Boolean).join(`
|
|
150
|
-
`),
|
|
151
|
-
values
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
function buildMeasureExpression(field, aggregation) {
|
|
155
|
-
switch (aggregation) {
|
|
156
|
-
case "COUNT":
|
|
157
|
-
return field === "*" ? "count()" : `count(${field})`;
|
|
158
|
-
case "COUNT_DISTINCT":
|
|
159
|
-
return `countDistinct(${field})`;
|
|
160
|
-
case "SUM":
|
|
161
|
-
return `sum(${field})`;
|
|
162
|
-
case "AVG":
|
|
163
|
-
return `avg(${field})`;
|
|
164
|
-
case "MIN":
|
|
165
|
-
return `min(${field})`;
|
|
166
|
-
case "MAX":
|
|
167
|
-
return `max(${field})`;
|
|
168
|
-
default:
|
|
169
|
-
return `count(${field})`;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
function buildDimensionExpression(field, type, granularity) {
|
|
173
|
-
if (type === "TIME") {
|
|
174
|
-
switch (granularity) {
|
|
175
|
-
case "HOUR":
|
|
176
|
-
return `toStartOfHour(${field})`;
|
|
177
|
-
case "WEEK":
|
|
178
|
-
return `toStartOfWeek(${field})`;
|
|
179
|
-
case "MONTH":
|
|
180
|
-
return `toStartOfMonth(${field})`;
|
|
181
|
-
case "YEAR":
|
|
182
|
-
return `toStartOfYear(${field})`;
|
|
183
|
-
case "DAY":
|
|
184
|
-
default:
|
|
185
|
-
return `toStartOfDay(${field})`;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return field;
|
|
189
|
-
}
|
|
190
|
-
function buildFilterClauses(aggregation, params, values) {
|
|
191
|
-
const clauses = [];
|
|
192
|
-
const range = resolveDateRange(params);
|
|
193
|
-
if (range) {
|
|
194
|
-
values.dateFrom = range.from.toISOString();
|
|
195
|
-
values.dateTo = range.to.toISOString();
|
|
196
|
-
clauses.push(`timestamp >= {dateFrom} and timestamp < {dateTo}`);
|
|
197
|
-
}
|
|
198
|
-
aggregation.filters?.forEach((filter, index) => {
|
|
199
|
-
const key = `filter${index}`;
|
|
200
|
-
switch (filter.operator) {
|
|
201
|
-
case "eq":
|
|
202
|
-
values[key] = filter.value;
|
|
203
|
-
clauses.push(`${filter.field} = {${key}}`);
|
|
204
|
-
break;
|
|
205
|
-
case "neq":
|
|
206
|
-
values[key] = filter.value;
|
|
207
|
-
clauses.push(`${filter.field} != {${key}}`);
|
|
208
|
-
break;
|
|
209
|
-
case "gt":
|
|
210
|
-
values[key] = filter.value;
|
|
211
|
-
clauses.push(`${filter.field} > {${key}}`);
|
|
212
|
-
break;
|
|
213
|
-
case "gte":
|
|
214
|
-
values[key] = filter.value;
|
|
215
|
-
clauses.push(`${filter.field} >= {${key}}`);
|
|
216
|
-
break;
|
|
217
|
-
case "lt":
|
|
218
|
-
values[key] = filter.value;
|
|
219
|
-
clauses.push(`${filter.field} < {${key}}`);
|
|
220
|
-
break;
|
|
221
|
-
case "lte":
|
|
222
|
-
values[key] = filter.value;
|
|
223
|
-
clauses.push(`${filter.field} <= {${key}}`);
|
|
224
|
-
break;
|
|
225
|
-
case "contains":
|
|
226
|
-
values[key] = filter.value;
|
|
227
|
-
clauses.push(`${filter.field} LIKE '%' || {${key}} || '%'`);
|
|
228
|
-
break;
|
|
229
|
-
case "between": {
|
|
230
|
-
if (Array.isArray(filter.value) && filter.value.length >= 2) {
|
|
231
|
-
values[`${key}Start`] = filter.value[0];
|
|
232
|
-
values[`${key}End`] = filter.value[1];
|
|
233
|
-
clauses.push(`${filter.field} BETWEEN {${key}Start} AND {${key}End}`);
|
|
234
|
-
}
|
|
235
|
-
break;
|
|
236
|
-
}
|
|
237
|
-
case "in":
|
|
238
|
-
case "nin":
|
|
239
|
-
if (Array.isArray(filter.value)) {
|
|
240
|
-
const placeholders = [];
|
|
241
|
-
filter.value.forEach((value, valueIndex) => {
|
|
242
|
-
const valueKey = `${key}_${valueIndex}`;
|
|
243
|
-
values[valueKey] = value;
|
|
244
|
-
placeholders.push(`{${valueKey}}`);
|
|
245
|
-
});
|
|
246
|
-
if (placeholders.length) {
|
|
247
|
-
clauses.push(`${filter.field} ${filter.operator === "in" ? "IN" : "NOT IN"} (${placeholders.join(", ")})`);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
break;
|
|
251
|
-
default:
|
|
252
|
-
break;
|
|
253
|
-
}
|
|
254
|
-
});
|
|
255
|
-
return clauses;
|
|
256
|
-
}
|
|
257
|
-
function resolveDateRange(params) {
|
|
258
|
-
const range = params.dateRange;
|
|
259
|
-
if (!range)
|
|
260
|
-
return null;
|
|
261
|
-
return { from: range.start, to: range.end };
|
|
262
|
-
}
|
|
263
|
-
function mapHogqlResult(result) {
|
|
264
|
-
if (!Array.isArray(result.results) || !Array.isArray(result.columns)) {
|
|
265
|
-
return { data: [], columns: [], rowCount: 0 };
|
|
266
|
-
}
|
|
267
|
-
const columns = result.columns.map((name) => ({
|
|
268
|
-
name,
|
|
269
|
-
type: "STRING"
|
|
270
|
-
}));
|
|
271
|
-
const data = result.results.map((row) => {
|
|
272
|
-
if (!Array.isArray(row))
|
|
273
|
-
return {};
|
|
274
|
-
const record = {};
|
|
275
|
-
result.columns?.forEach((column, index) => {
|
|
276
|
-
record[column] = row[index];
|
|
277
|
-
});
|
|
278
|
-
return record;
|
|
279
|
-
});
|
|
280
|
-
return {
|
|
281
|
-
data,
|
|
282
|
-
columns,
|
|
283
|
-
rowCount: data.length
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// src/handlers/analytics.handlers.ts
|
|
288
|
-
import { web } from "@contractspec/lib.runtime-sandbox";
|
|
289
|
-
var { generateId } = web;
|
|
290
|
-
function rowToDashboard(row) {
|
|
291
|
-
return {
|
|
292
|
-
id: row.id,
|
|
293
|
-
projectId: row.projectId,
|
|
294
|
-
organizationId: row.organizationId,
|
|
295
|
-
name: row.name,
|
|
296
|
-
slug: row.slug,
|
|
297
|
-
description: row.description ?? undefined,
|
|
298
|
-
status: row.status,
|
|
299
|
-
refreshInterval: row.refreshInterval,
|
|
300
|
-
isPublic: row.isPublic === 1,
|
|
301
|
-
shareToken: row.shareToken ?? undefined,
|
|
302
|
-
createdAt: new Date(row.createdAt),
|
|
303
|
-
updatedAt: new Date(row.updatedAt)
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
function rowToWidget(row) {
|
|
307
|
-
return {
|
|
308
|
-
id: row.id,
|
|
309
|
-
dashboardId: row.dashboardId,
|
|
310
|
-
name: row.name,
|
|
311
|
-
type: row.type,
|
|
312
|
-
gridX: row.gridX,
|
|
313
|
-
gridY: row.gridY,
|
|
314
|
-
gridWidth: row.gridWidth,
|
|
315
|
-
gridHeight: row.gridHeight,
|
|
316
|
-
queryId: row.queryId ?? undefined,
|
|
317
|
-
config: row.config ? JSON.parse(row.config) : undefined,
|
|
318
|
-
createdAt: new Date(row.createdAt),
|
|
319
|
-
updatedAt: new Date(row.updatedAt)
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
function rowToQuery(row) {
|
|
323
|
-
return {
|
|
324
|
-
id: row.id,
|
|
325
|
-
projectId: row.projectId,
|
|
326
|
-
organizationId: row.organizationId,
|
|
327
|
-
name: row.name,
|
|
328
|
-
description: row.description ?? undefined,
|
|
329
|
-
type: row.type,
|
|
330
|
-
definition: JSON.parse(row.definition),
|
|
331
|
-
sql: row.sql ?? undefined,
|
|
332
|
-
cacheTtlSeconds: row.cacheTtlSeconds,
|
|
333
|
-
isShared: row.isShared === 1,
|
|
334
|
-
createdAt: new Date(row.createdAt),
|
|
335
|
-
updatedAt: new Date(row.updatedAt)
|
|
336
|
-
};
|
|
337
|
-
}
|
|
338
|
-
function createAnalyticsHandlers(db) {
|
|
339
|
-
async function listDashboards(input) {
|
|
340
|
-
const { projectId, status, search, limit = 20, offset = 0 } = input;
|
|
341
|
-
let whereClause = "WHERE projectId = ?";
|
|
342
|
-
const params = [projectId];
|
|
343
|
-
if (status && status !== "all") {
|
|
344
|
-
whereClause += " AND status = ?";
|
|
345
|
-
params.push(status);
|
|
346
|
-
}
|
|
347
|
-
if (search) {
|
|
348
|
-
whereClause += " AND (name LIKE ? OR description LIKE ?)";
|
|
349
|
-
params.push(`%${search}%`, `%${search}%`);
|
|
350
|
-
}
|
|
351
|
-
const countResult = (await db.query(`SELECT COUNT(*) as count FROM analytics_dashboard ${whereClause}`, params)).rows;
|
|
352
|
-
const total = countResult[0]?.count ?? 0;
|
|
353
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
|
|
354
|
-
return {
|
|
355
|
-
dashboards: rows.map(rowToDashboard),
|
|
356
|
-
total
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
async function createDashboard(input, context) {
|
|
360
|
-
const id = generateId("dash");
|
|
361
|
-
const now = new Date().toISOString();
|
|
362
|
-
await db.execute(`INSERT INTO analytics_dashboard (id, projectId, organizationId, name, slug, description, status, refreshInterval, isPublic, createdAt, updatedAt)
|
|
363
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
364
|
-
id,
|
|
365
|
-
context.projectId,
|
|
366
|
-
context.organizationId,
|
|
367
|
-
input.name,
|
|
368
|
-
input.slug,
|
|
369
|
-
input.description ?? null,
|
|
370
|
-
"DRAFT",
|
|
371
|
-
input.refreshInterval ?? "NONE",
|
|
372
|
-
0,
|
|
373
|
-
now,
|
|
374
|
-
now
|
|
375
|
-
]);
|
|
376
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard WHERE id = ?`, [id])).rows;
|
|
377
|
-
return rowToDashboard(rows[0]);
|
|
378
|
-
}
|
|
379
|
-
async function getDashboard(input) {
|
|
380
|
-
let whereClause = "";
|
|
381
|
-
const params = [];
|
|
382
|
-
if (input.dashboardId) {
|
|
383
|
-
whereClause = "WHERE id = ?";
|
|
384
|
-
params.push(input.dashboardId);
|
|
385
|
-
} else if (input.slug) {
|
|
386
|
-
whereClause = "WHERE slug = ?";
|
|
387
|
-
params.push(input.slug);
|
|
388
|
-
} else if (input.shareToken) {
|
|
389
|
-
whereClause = "WHERE shareToken = ?";
|
|
390
|
-
params.push(input.shareToken);
|
|
391
|
-
} else {
|
|
392
|
-
return null;
|
|
393
|
-
}
|
|
394
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard ${whereClause}`, params)).rows;
|
|
395
|
-
return rows[0] ? rowToDashboard(rows[0]) : null;
|
|
396
|
-
}
|
|
397
|
-
async function updateDashboard(dashboardId, updates) {
|
|
398
|
-
const now = new Date().toISOString();
|
|
399
|
-
const setClauses = ["updatedAt = ?"];
|
|
400
|
-
const params = [now];
|
|
401
|
-
if (updates.name !== undefined) {
|
|
402
|
-
setClauses.push("name = ?");
|
|
403
|
-
params.push(updates.name);
|
|
404
|
-
}
|
|
405
|
-
if (updates.description !== undefined) {
|
|
406
|
-
setClauses.push("description = ?");
|
|
407
|
-
params.push(updates.description);
|
|
408
|
-
}
|
|
409
|
-
if (updates.status !== undefined) {
|
|
410
|
-
setClauses.push("status = ?");
|
|
411
|
-
params.push(updates.status);
|
|
412
|
-
}
|
|
413
|
-
if (updates.refreshInterval !== undefined) {
|
|
414
|
-
setClauses.push("refreshInterval = ?");
|
|
415
|
-
params.push(updates.refreshInterval);
|
|
416
|
-
}
|
|
417
|
-
if (updates.isPublic !== undefined) {
|
|
418
|
-
setClauses.push("isPublic = ?");
|
|
419
|
-
params.push(updates.isPublic ? 1 : 0);
|
|
420
|
-
if (updates.isPublic) {
|
|
421
|
-
setClauses.push("shareToken = ?");
|
|
422
|
-
params.push(generateId("share"));
|
|
423
|
-
} else {
|
|
424
|
-
setClauses.push("shareToken = NULL");
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
params.push(dashboardId);
|
|
428
|
-
await db.execute(`UPDATE analytics_dashboard SET ${setClauses.join(", ")} WHERE id = ?`, params);
|
|
429
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard WHERE id = ?`, [
|
|
430
|
-
dashboardId
|
|
431
|
-
])).rows;
|
|
432
|
-
return rowToDashboard(rows[0]);
|
|
433
|
-
}
|
|
434
|
-
async function getWidgets(dashboardId) {
|
|
435
|
-
const rows = (await db.query(`SELECT * FROM analytics_widget WHERE dashboardId = ? ORDER BY gridY, gridX`, [dashboardId])).rows;
|
|
436
|
-
return rows.map(rowToWidget);
|
|
437
|
-
}
|
|
438
|
-
async function addWidget(input) {
|
|
439
|
-
const id = generateId("widget");
|
|
440
|
-
const now = new Date().toISOString();
|
|
441
|
-
await db.execute(`INSERT INTO analytics_widget (id, dashboardId, name, type, gridX, gridY, gridWidth, gridHeight, queryId, config, createdAt, updatedAt)
|
|
442
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
443
|
-
id,
|
|
444
|
-
input.dashboardId,
|
|
445
|
-
input.name,
|
|
446
|
-
input.type,
|
|
447
|
-
input.gridX ?? 0,
|
|
448
|
-
input.gridY ?? 0,
|
|
449
|
-
input.gridWidth ?? 6,
|
|
450
|
-
input.gridHeight ?? 4,
|
|
451
|
-
input.queryId ?? null,
|
|
452
|
-
input.config ? JSON.stringify(input.config) : null,
|
|
453
|
-
now,
|
|
454
|
-
now
|
|
455
|
-
]);
|
|
456
|
-
const rows = (await db.query(`SELECT * FROM analytics_widget WHERE id = ?`, [id])).rows;
|
|
457
|
-
return rowToWidget(rows[0]);
|
|
458
|
-
}
|
|
459
|
-
async function updateWidget(widgetId, updates) {
|
|
460
|
-
const now = new Date().toISOString();
|
|
461
|
-
const setClauses = ["updatedAt = ?"];
|
|
462
|
-
const params = [now];
|
|
463
|
-
if (updates.name !== undefined) {
|
|
464
|
-
setClauses.push("name = ?");
|
|
465
|
-
params.push(updates.name);
|
|
466
|
-
}
|
|
467
|
-
if (updates.gridX !== undefined) {
|
|
468
|
-
setClauses.push("gridX = ?");
|
|
469
|
-
params.push(updates.gridX);
|
|
470
|
-
}
|
|
471
|
-
if (updates.gridY !== undefined) {
|
|
472
|
-
setClauses.push("gridY = ?");
|
|
473
|
-
params.push(updates.gridY);
|
|
474
|
-
}
|
|
475
|
-
if (updates.gridWidth !== undefined) {
|
|
476
|
-
setClauses.push("gridWidth = ?");
|
|
477
|
-
params.push(updates.gridWidth);
|
|
478
|
-
}
|
|
479
|
-
if (updates.gridHeight !== undefined) {
|
|
480
|
-
setClauses.push("gridHeight = ?");
|
|
481
|
-
params.push(updates.gridHeight);
|
|
482
|
-
}
|
|
483
|
-
if (updates.queryId !== undefined) {
|
|
484
|
-
setClauses.push("queryId = ?");
|
|
485
|
-
params.push(updates.queryId ?? null);
|
|
486
|
-
}
|
|
487
|
-
if (updates.config !== undefined) {
|
|
488
|
-
setClauses.push("config = ?");
|
|
489
|
-
params.push(updates.config ? JSON.stringify(updates.config) : null);
|
|
490
|
-
}
|
|
491
|
-
params.push(widgetId);
|
|
492
|
-
await db.execute(`UPDATE analytics_widget SET ${setClauses.join(", ")} WHERE id = ?`, params);
|
|
493
|
-
const rows = (await db.query(`SELECT * FROM analytics_widget WHERE id = ?`, [widgetId])).rows;
|
|
494
|
-
return rowToWidget(rows[0]);
|
|
495
|
-
}
|
|
496
|
-
async function deleteWidget(widgetId) {
|
|
497
|
-
await db.execute(`DELETE FROM analytics_widget WHERE id = ?`, [widgetId]);
|
|
498
|
-
}
|
|
499
|
-
async function listQueries(input) {
|
|
500
|
-
const { projectId, type, isShared, search, limit = 20, offset = 0 } = input;
|
|
501
|
-
let whereClause = "WHERE projectId = ?";
|
|
502
|
-
const params = [projectId];
|
|
503
|
-
if (type && type !== "all") {
|
|
504
|
-
whereClause += " AND type = ?";
|
|
505
|
-
params.push(type);
|
|
506
|
-
}
|
|
507
|
-
if (isShared !== undefined) {
|
|
508
|
-
whereClause += " AND isShared = ?";
|
|
509
|
-
params.push(isShared ? 1 : 0);
|
|
510
|
-
}
|
|
511
|
-
if (search) {
|
|
512
|
-
whereClause += " AND (name LIKE ? OR description LIKE ?)";
|
|
513
|
-
params.push(`%${search}%`, `%${search}%`);
|
|
514
|
-
}
|
|
515
|
-
const countResult = (await db.query(`SELECT COUNT(*) as count FROM analytics_query ${whereClause}`, params)).rows;
|
|
516
|
-
const total = countResult[0]?.count ?? 0;
|
|
517
|
-
const rows = (await db.query(`SELECT * FROM analytics_query ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
|
|
518
|
-
return {
|
|
519
|
-
queries: rows.map(rowToQuery),
|
|
520
|
-
total
|
|
521
|
-
};
|
|
522
|
-
}
|
|
523
|
-
async function createQuery(input, context) {
|
|
524
|
-
const id = generateId("query");
|
|
525
|
-
const now = new Date().toISOString();
|
|
526
|
-
await db.execute(`INSERT INTO analytics_query (id, projectId, organizationId, name, description, type, definition, sql, cacheTtlSeconds, isShared, createdAt, updatedAt)
|
|
527
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
528
|
-
id,
|
|
529
|
-
context.projectId,
|
|
530
|
-
context.organizationId,
|
|
531
|
-
input.name,
|
|
532
|
-
input.description ?? null,
|
|
533
|
-
input.type,
|
|
534
|
-
JSON.stringify(input.definition),
|
|
535
|
-
input.sql ?? null,
|
|
536
|
-
input.cacheTtlSeconds ?? 300,
|
|
537
|
-
input.isShared ? 1 : 0,
|
|
538
|
-
now,
|
|
539
|
-
now
|
|
540
|
-
]);
|
|
541
|
-
const rows = (await db.query(`SELECT * FROM analytics_query WHERE id = ?`, [id])).rows;
|
|
542
|
-
return rowToQuery(rows[0]);
|
|
543
|
-
}
|
|
544
|
-
async function getQuery(queryId) {
|
|
545
|
-
const rows = (await db.query(`SELECT * FROM analytics_query WHERE id = ?`, [queryId])).rows;
|
|
546
|
-
return rows[0] ? rowToQuery(rows[0]) : null;
|
|
547
|
-
}
|
|
548
|
-
return {
|
|
549
|
-
listDashboards,
|
|
550
|
-
createDashboard,
|
|
551
|
-
getDashboard,
|
|
552
|
-
updateDashboard,
|
|
553
|
-
getWidgets,
|
|
554
|
-
addWidget,
|
|
555
|
-
updateWidget,
|
|
556
|
-
deleteWidget,
|
|
557
|
-
listQueries,
|
|
558
|
-
createQuery,
|
|
559
|
-
getQuery
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
// src/handlers/query.handlers.ts
|
|
564
|
-
async function executePosthogQuery(input) {
|
|
565
|
-
const engine = createPosthogQueryEngine(input.reader);
|
|
566
|
-
return engine.execute(input.definition, input.params);
|
|
567
|
-
}
|
|
568
|
-
export {
|
|
569
|
-
executePosthogQuery,
|
|
570
|
-
createAnalyticsHandlers
|
|
571
|
-
};
|
|
1
|
+
class M{reader;defaultLimit;constructor(n,t={}){this.reader=n,this.defaultLimit=t.defaultLimit??100}async execute(n,t){let c=Date.now(),i=this.validateQuery(n);if(!i.valid)return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-c,cached:!1,error:i.errors.join(", ")};if(!this.reader.queryHogQL)return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-c,cached:!1,error:"Analytics reader does not support HogQL queries."};try{let l=await this.executeHogQL(n,t);return{data:l.data,columns:l.columns,rowCount:l.rowCount,executionTimeMs:Date.now()-c,cached:!1}}catch(l){return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-c,cached:!1,error:l instanceof Error?l.message:"Unknown error"}}}validateQuery(n){let t=[];if(n.type==="SQL"&&!n.sql)t.push("SQL query is missing.");if(n.type==="AGGREGATION"&&!n.aggregation)t.push("Aggregation definition is missing.");if(n.type==="METRIC"&&!n.metricIds?.length)t.push("Metric IDs are missing.");if(n.type==="CUSTOM"&&!n.custom?.handler)t.push("Custom handler is missing.");return{valid:t.length===0,errors:t}}async executeHogQL(n,t){if(!this.reader.queryHogQL)throw Error("Analytics reader does not support HogQL queries.");if(n.type==="SQL"){let c=await this.reader.queryHogQL({query:n.sql??"",values:t.parameters??{}});return q(c)}if(n.type==="AGGREGATION"&&n.aggregation){let{query:c,values:i}=T(n.aggregation,t),l=await this.reader.queryHogQL({query:c,values:i});return q(l)}if(n.type==="METRIC"&&n.metricIds){let{query:c,values:i}=P(n.metricIds,t),l=await this.reader.queryHogQL({query:c,values:i});return q(l)}throw Error("Unsupported query type for PostHog datasource.")}}function H(n,t){return new M(n,t)}function P(n,t){let c=N(t),i={dateFrom:c?.from.toISOString(),dateTo:c?.to.toISOString()},l=n.map((a,m)=>{return i[`metric${m}`]=a,`event = {metric${m}}`}),y=[l.length?`(${l.join(" or ")})`:"",c?"timestamp >= {dateFrom} and timestamp < {dateTo}":""].filter(Boolean).join(" and ");return{query:["select"," event as metric,"," count() as total","from events",y?`where ${y}`:"","group by metric"].filter(Boolean).join(`
|
|
2
|
+
`),values:i}}function T(n,t){let c=n.measures.map((s)=>({...s,expression:x(s.field,s.aggregation)})),i=n.dimensions.map((s)=>({...s,expression:j(s.field,s.type,s.granularity)})),l=[...i.map((s)=>`${s.expression} as ${s.name}`),...c.map((s)=>`${s.expression} as ${s.name}`)],y={},a=G(n,t,y),m=n.limit??100,u=n.orderBy?.length?`order by ${n.orderBy.map((s)=>`${s.field} ${s.direction}`).join(", ")}`:"";return{query:["select",` ${l.join(`,
|
|
3
|
+
`)}`,`from ${n.source}`,a.length?`where ${a.join(" and ")}`:"",i.length?`group by ${i.map((s)=>s.name).join(", ")}`:"",u,`limit ${m}`].filter(Boolean).join(`
|
|
4
|
+
`),values:y}}function x(n,t){switch(t){case"COUNT":return n==="*"?"count()":`count(${n})`;case"COUNT_DISTINCT":return`countDistinct(${n})`;case"SUM":return`sum(${n})`;case"AVG":return`avg(${n})`;case"MIN":return`min(${n})`;case"MAX":return`max(${n})`;default:return`count(${n})`}}function j(n,t,c){if(t==="TIME")switch(c){case"HOUR":return`toStartOfHour(${n})`;case"WEEK":return`toStartOfWeek(${n})`;case"MONTH":return`toStartOfMonth(${n})`;case"YEAR":return`toStartOfYear(${n})`;case"DAY":default:return`toStartOfDay(${n})`}return n}function G(n,t,c){let i=[],l=N(t);if(l)c.dateFrom=l.from.toISOString(),c.dateTo=l.to.toISOString(),i.push("timestamp >= {dateFrom} and timestamp < {dateTo}");return n.filters?.forEach((y,a)=>{let m=`filter${a}`;switch(y.operator){case"eq":c[m]=y.value,i.push(`${y.field} = {${m}}`);break;case"neq":c[m]=y.value,i.push(`${y.field} != {${m}}`);break;case"gt":c[m]=y.value,i.push(`${y.field} > {${m}}`);break;case"gte":c[m]=y.value,i.push(`${y.field} >= {${m}}`);break;case"lt":c[m]=y.value,i.push(`${y.field} < {${m}}`);break;case"lte":c[m]=y.value,i.push(`${y.field} <= {${m}}`);break;case"contains":c[m]=y.value,i.push(`${y.field} LIKE '%' || {${m}} || '%'`);break;case"between":{if(Array.isArray(y.value)&&y.value.length>=2)c[`${m}Start`]=y.value[0],c[`${m}End`]=y.value[1],i.push(`${y.field} BETWEEN {${m}Start} AND {${m}End}`);break}case"in":case"nin":if(Array.isArray(y.value)){let u=[];if(y.value.forEach((s,h)=>{let R=`${m}_${h}`;c[R]=s,u.push(`{${R}}`)}),u.length)i.push(`${y.field} ${y.operator==="in"?"IN":"NOT IN"} (${u.join(", ")})`)}break;default:break}}),i}function N(n){let t=n.dateRange;if(!t)return null;return{from:t.start,to:t.end}}function q(n){if(!Array.isArray(n.results)||!Array.isArray(n.columns))return{data:[],columns:[],rowCount:0};let t=n.columns.map((i)=>({name:i,type:"STRING"})),c=n.results.map((i)=>{if(!Array.isArray(i))return{};let l={};return n.columns?.forEach((y,a)=>{l[y]=i[a]}),l});return{data:c,columns:t,rowCount:c.length}}import{web as B}from"@contractspec/lib.runtime-sandbox";var{generateId:v}=B;function k(n){return{id:n.id,projectId:n.projectId,organizationId:n.organizationId,name:n.name,slug:n.slug,description:n.description??void 0,status:n.status,refreshInterval:n.refreshInterval,isPublic:n.isPublic===1,shareToken:n.shareToken??void 0,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt)}}function O(n){return{id:n.id,dashboardId:n.dashboardId,name:n.name,type:n.type,gridX:n.gridX,gridY:n.gridY,gridWidth:n.gridWidth,gridHeight:n.gridHeight,queryId:n.queryId??void 0,config:n.config?JSON.parse(n.config):void 0,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt)}}function S(n){return{id:n.id,projectId:n.projectId,organizationId:n.organizationId,name:n.name,description:n.description??void 0,type:n.type,definition:JSON.parse(n.definition),sql:n.sql??void 0,cacheTtlSeconds:n.cacheTtlSeconds,isShared:n.isShared===1,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt)}}function K(n){async function t(r){let{projectId:e,status:$,search:o,limit:g=20,offset:A=0}=r,Q="WHERE projectId = ?",f=[e];if($&&$!=="all")Q+=" AND status = ?",f.push($);if(o)Q+=" AND (name LIKE ? OR description LIKE ?)",f.push(`%${o}%`,`%${o}%`);let D=(await n.query(`SELECT COUNT(*) as count FROM analytics_dashboard ${Q}`,f)).rows[0]?.count??0;return{dashboards:(await n.query(`SELECT * FROM analytics_dashboard ${Q} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...f,g,A])).rows.map(k),total:D}}async function c(r,e){let $=v("dash"),o=new Date().toISOString();await n.execute(`INSERT INTO analytics_dashboard (id, projectId, organizationId, name, slug, description, status, refreshInterval, isPublic, createdAt, updatedAt)
|
|
5
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$,e.projectId,e.organizationId,r.name,r.slug,r.description??null,"DRAFT",r.refreshInterval??"NONE",0,o,o]);let g=(await n.query("SELECT * FROM analytics_dashboard WHERE id = ?",[$])).rows;return k(g[0])}async function i(r){let e="",$=[];if(r.dashboardId)e="WHERE id = ?",$.push(r.dashboardId);else if(r.slug)e="WHERE slug = ?",$.push(r.slug);else if(r.shareToken)e="WHERE shareToken = ?",$.push(r.shareToken);else return null;let o=(await n.query(`SELECT * FROM analytics_dashboard ${e}`,$)).rows;return o[0]?k(o[0]):null}async function l(r,e){let $=new Date().toISOString(),o=["updatedAt = ?"],g=[$];if(e.name!==void 0)o.push("name = ?"),g.push(e.name);if(e.description!==void 0)o.push("description = ?"),g.push(e.description);if(e.status!==void 0)o.push("status = ?"),g.push(e.status);if(e.refreshInterval!==void 0)o.push("refreshInterval = ?"),g.push(e.refreshInterval);if(e.isPublic!==void 0)if(o.push("isPublic = ?"),g.push(e.isPublic?1:0),e.isPublic)o.push("shareToken = ?"),g.push(v("share"));else o.push("shareToken = NULL");g.push(r),await n.execute(`UPDATE analytics_dashboard SET ${o.join(", ")} WHERE id = ?`,g);let A=(await n.query("SELECT * FROM analytics_dashboard WHERE id = ?",[r])).rows;return k(A[0])}async function y(r){return(await n.query("SELECT * FROM analytics_widget WHERE dashboardId = ? ORDER BY gridY, gridX",[r])).rows.map(O)}async function a(r){let e=v("widget"),$=new Date().toISOString();await n.execute(`INSERT INTO analytics_widget (id, dashboardId, name, type, gridX, gridY, gridWidth, gridHeight, queryId, config, createdAt, updatedAt)
|
|
6
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e,r.dashboardId,r.name,r.type,r.gridX??0,r.gridY??0,r.gridWidth??6,r.gridHeight??4,r.queryId??null,r.config?JSON.stringify(r.config):null,$,$]);let o=(await n.query("SELECT * FROM analytics_widget WHERE id = ?",[e])).rows;return O(o[0])}async function m(r,e){let $=new Date().toISOString(),o=["updatedAt = ?"],g=[$];if(e.name!==void 0)o.push("name = ?"),g.push(e.name);if(e.gridX!==void 0)o.push("gridX = ?"),g.push(e.gridX);if(e.gridY!==void 0)o.push("gridY = ?"),g.push(e.gridY);if(e.gridWidth!==void 0)o.push("gridWidth = ?"),g.push(e.gridWidth);if(e.gridHeight!==void 0)o.push("gridHeight = ?"),g.push(e.gridHeight);if(e.queryId!==void 0)o.push("queryId = ?"),g.push(e.queryId??null);if(e.config!==void 0)o.push("config = ?"),g.push(e.config?JSON.stringify(e.config):null);g.push(r),await n.execute(`UPDATE analytics_widget SET ${o.join(", ")} WHERE id = ?`,g);let A=(await n.query("SELECT * FROM analytics_widget WHERE id = ?",[r])).rows;return O(A[0])}async function u(r){await n.execute("DELETE FROM analytics_widget WHERE id = ?",[r])}async function s(r){let{projectId:e,type:$,isShared:o,search:g,limit:A=20,offset:Q=0}=r,f="WHERE projectId = ?",E=[e];if($&&$!=="all")f+=" AND type = ?",E.push($);if(o!==void 0)f+=" AND isShared = ?",E.push(o?1:0);if(g)f+=" AND (name LIKE ? OR description LIKE ?)",E.push(`%${g}%`,`%${g}%`);let L=(await n.query(`SELECT COUNT(*) as count FROM analytics_query ${f}`,E)).rows[0]?.count??0;return{queries:(await n.query(`SELECT * FROM analytics_query ${f} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...E,A,Q])).rows.map(S),total:L}}async function h(r,e){let $=v("query"),o=new Date().toISOString();await n.execute(`INSERT INTO analytics_query (id, projectId, organizationId, name, description, type, definition, sql, cacheTtlSeconds, isShared, createdAt, updatedAt)
|
|
7
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$,e.projectId,e.organizationId,r.name,r.description??null,r.type,JSON.stringify(r.definition),r.sql??null,r.cacheTtlSeconds??300,r.isShared?1:0,o,o]);let g=(await n.query("SELECT * FROM analytics_query WHERE id = ?",[$])).rows;return S(g[0])}async function R(r){let e=(await n.query("SELECT * FROM analytics_query WHERE id = ?",[r])).rows;return e[0]?S(e[0]):null}return{listDashboards:t,createDashboard:c,getDashboard:i,updateDashboard:l,getWidgets:y,addWidget:a,updateWidget:m,deleteWidget:u,listQueries:s,createQuery:h,getQuery:R}}async function V(n){return H(n.reader).execute(n.definition,n.params)}export{V as executePosthogQuery,K as createAnalyticsHandlers};
|