This repository has been archived by the owner on Feb 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquery.ts
132 lines (110 loc) · 3.51 KB
/
query.ts
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
import { logger, task } from "@trigger.dev/sdk/v3";
const TINYBIRD_TOKEN = process.env.TINYBIRD_TOKEN ?? undefined;
interface QueryPayload {
sql: string;
params?: Record<string, string | number | boolean>;
format?: string;
token?: string;
}
interface TinybirdErrorResponse {
error: string;
detail?: string;
}
interface TinybirdJSONResponse {
meta: {
name: string;
type: string;
}[];
data: Record<string, any>[];
rows: number;
statistics: {
elapsed: number;
rows_read: number;
bytes_read: number;
};
}
type TinybirdSuccessResponse = Format extends Format.JSON ? TinybirdJSONResponse : any;
export enum Format {
CSV = "CSV",
CSVWithNames = "CSVWithNames",
JSON = "JSON",
TSV = "TSV",
TSVWithNames = "TSVWithNames",
PrettyCompact = "PrettyCompact",
JSONEachRow = "JSONEachRow",
Parquet = "Parquet"
}
function isValidFormat(format: string): format is Format {
return Object.values(Format).includes(format as Format);
}
function extractFormat(query: string): Format | null {
const match = query.trim().match(/FORMAT\s+(\w+)$/i);
if (!match) return null;
const format = match[1].toUpperCase();
return isValidFormat(format) ? format as Format : null;
}
export const tinybirdQueryTask = task({
id: "tinybird-query",
run: async (payload: QueryPayload) => {
const token = TINYBIRD_TOKEN ?? payload.token;
if (!token) {
throw new Error("Tinybird API token not found. Either set the TINYBIRD_TOKEN environment variable, or provide a token in the task payload.");
}
if (!payload.sql) {
throw new Error("SQL query is required");
}
let query = payload.sql;
const queryFormat = extractFormat(query);
// Validate payload format if provided
if (payload.format && !isValidFormat(payload.format.toUpperCase())) {
throw new Error(`Invalid format: ${payload.format}. Valid formats are: ${Object.values(Format).join(", ")}`);
}
// Use format from payload if specified, otherwise use format from query, fallback to JSON
const format = (payload.format?.toUpperCase() ?? queryFormat ?? Format.JSON) as Format;
// Only append format if it's not already in the query
if (!queryFormat) {
query += ` FORMAT ${format}`;
}
try {
const response = await fetch(
`https://api.tinybird.co/v0/sql`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
q: query,
...payload.params,
}),
}
);
const result = await response.json();
console.log(result);
if (response.status !== 200) {
let errorResponse: TinybirdErrorResponse = {
error: "error",
};
if ("error" in result) {
errorResponse = result as TinybirdErrorResponse;
logger.error("Tinybird query failed", {
error: errorResponse.error,
detail: errorResponse.detail,
});
}
throw new Error(`Tinybird query failed: ${errorResponse.error}`);
}
const successResponse = result as TinybirdSuccessResponse;
logger.info("Query executed successfully", successResponse);
return successResponse;
} catch (error) {
logger.error("Failed to execute Tinybird query", {
error: error instanceof Error ? error.message : "Unknown error",
sql: payload.sql,
});
throw error;
}
},
});