-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.ts
More file actions
293 lines (254 loc) · 7.33 KB
/
examples.ts
File metadata and controls
293 lines (254 loc) · 7.33 KB
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
import { DatabaseSDK } from "./src/sdk/client.js";
interface User {
id: number;
name: string;
email: string;
role: string;
department: string;
salary: number;
hireDate: Date;
status: string;
experience: number;
lastName: string;
}
interface Order {
id: number;
userId: number;
total: number;
status: string;
createdAt: Date;
revenue: number;
}
interface Product {
id: number;
name: string;
price: number;
category: string;
stock: number;
}
// Initialize SDK
const db = new DatabaseSDK("http://localhost:3000");
// Helper function to run examples
async function runExample(name: string, fn: () => Promise<any>) {
console.log(`\n=== Running ${name} ===`);
try {
const result = await fn();
console.log(`✅ ${name} completed successfully`);
displayResults(name, result);
} catch (error) {
console.error(`❌ ${name} failed:`, error);
}
}
// Function to display results
function displayResults(name: string, data: any) {
console.log(`\n📋 Results for ${name}:`);
console.log(JSON.stringify(data, null, 2));
}
// Main function to run examples
async function main() {
// await runExample("Basic Queries", basicQueries);
// await runExample("Advanced Filtering", advancedFiltering);
// await runExample("Aggregations and Grouping", aggregationsAndGrouping);
// await runExample("Window Functions", windowFunctions);
await runExample("CTEs", cteExamples);
// await runExample("Transformations", transformations);
// await runExample("Complex Real-World Examples", realWorldExamples);
}
// Basic Queries
async function basicQueries() {
const results = {
activeUsers: await db
.table<User>("users")
.where("status", "active")
.execute(),
seniorManagers: await db
.table<User>("users")
.where("role", "manager")
.where("experience", ">=", 5)
.execute(),
sortedUsers: await db
.table<User>("users")
.orderBy("lastName", "asc")
.orderBy({ field: "salary", direction: "desc", nulls: "first" })
.execute(),
pagedResults: await db.table<User>("users").offset(20).limit(10).execute(),
userEmails: await db
.table<User>("users")
.select("id", "email")
.where("status", "active")
.execute(),
rankedSalaries: await db
.table<User>("users")
.select("firstName", "department", "salary")
.window("rank", "salary_rank", {
partitionBy: ["department"],
orderBy: [{ field: "salary", direction: "desc" }],
})
.execute(),
departmentStats: await db
.table<User>("users")
.select("department")
.groupBy("department")
.count("id", "total_employees")
.avg("salary", "avg_salary")
.execute(),
};
return results;
}
// Aggregations and Grouping
async function aggregationsAndGrouping() {
// Basic aggregation
const orderStats = await db
.table<Order>("orders")
.groupBy("status")
.count("id", "order_count")
.sum("total", "total_amount")
.avg("total", "average_amount")
.execute();
// Having clause
const highValueOrderGroups = await db
.table<Order>("orders")
.groupBy("userId")
.having("total_amount", ">", 1000)
.sum("total", "total_amount")
.execute();
// Multiple aggregations with complex grouping
const detailedStats = await db
.table<Order>("orders")
.groupBy("department", "status")
.count("id", "order_count")
.sum("total", "revenue")
.avg("total", "avg_order_value")
.min("total", "min_order")
.max("total", "max_order")
.having("order_count", ">", 1)
.orderBy("revenue", "desc")
.execute();
return { orderStats, highValueOrderGroups, detailedStats };
}
// Window Functions
async function windowFunctions() {
// Row number
const rankedUsers = await db
.table<User>("users")
.select("firstName", "department", "salary")
.rowNumber("rank", ["department"], [{ field: "salary", direction: "desc" }])
.execute();
// Multiple window functions
const analyzedSalaries = await db
.table<User>("users")
.select("firstName", "department", "salary")
.window("rank", "salary_rank", {
partitionBy: ["department"],
orderBy: [{ field: "salary", direction: "desc" }],
})
.window("lag", "prev_salary", {
field: "salary",
partitionBy: ["department"],
orderBy: [{ field: "hireDate", direction: "asc" }],
})
.execute();
// Advanced window function
const advancedAnalysis = await db
.table<User>("users")
.select("id", "firstName", "lastName", "department", "salary", "hireDate")
.windowAdvanced("sum", "running_total", {
field: "salary",
over: {
partitionBy: ["department"],
orderBy: [{ field: "hireDate", direction: "asc" }],
frame: {
type: "ROWS",
start: "UNBOUNDED PRECEDING",
end: "CURRENT ROW",
},
},
})
.orderBy("department", "asc")
.orderBy("hireDate", "asc")
.execute();
return { advancedAnalysis, rankedUsers, analyzedSalaries };
}
// Advanced Filtering
async function advancedFiltering() {
// Complex grouped conditions
const filteredUsers = await db
.table<User>("users")
.where("status", "active")
.andWhere((query) => {
query.where("role", "admin").orWhere((subQuery) => {
subQuery.where("role", "manager").where("department", "IT");
});
})
.execute();
// Where between
const salaryRange = await db
.table<User>("users")
.whereBetween("salary", [50000, 100000])
.execute();
// Where in
const specificDepts = await db
.table<User>("users")
.whereIn("department", ["IT", "HR", "Finance"])
.execute();
// Where exists
// TODO: needs fixing in the sdk to prevent SQL injection
// const usersWithOrders = await db
// .table<User>("users")
// .whereExists(
// "SELECT 1 FROM orders WHERE orders.user_id = users.id AND total > ?",
// [1000]
// )
// .execute();
return { filteredUsers, salaryRange, specificDepts };
}
// CTEs (Common Table Expressions)
//TODO: not yet working well on the server side
async function cteExamples() {
// Simple CTE
const highPaidUsers = db.table<User>("users").where("salary", ">", 100000);
const result = await db
.table<User>("users")
.with("high_paid", highPaidUsers)
.execute();
// Recursive CTE
const initialQuery = db
.table<Product>("products")
.where("category", "Electronics");
const recursiveQuery = db
.table<Product>("products")
.where("price", ">", 1000);
const recursiveResult = await db
.table<Product>("products")
.withRecursive("product_hierarchy", initialQuery, recursiveQuery, {
unionAll: true,
})
.execute();
return { result, recursiveResult };
}
async function transformations() {
// Implement transformations example
return [];
}
async function realWorldExamples() {
// Implement complex real-world example
return [];
}
// Update the module execution check for ES modules
const isMainModule = import.meta.url === `file://${process.argv[1]}`;
if (isMainModule) {
main().catch((error) => {
console.error("Error running examples:", error);
process.exit(1);
});
}
// Export the examples for individual running
export const examples = {
basicQueries,
advancedFiltering,
aggregationsAndGrouping,
windowFunctions,
cteExamples,
transformations,
realWorldExamples,
};