Query Builder
Build complex SQL queries with a fluent, type-safe API that protects against SQL injection.
Basic Usage
Create a query builder instance using your database adapter:
1import { QueryBuilder } from 'foundry-orm';
2import connection from './db/connection';
3
4const adapter = connection.getAdapter();
5const qb = new QueryBuilder(adapter);
6
7const results = await qb
8 .select('*')
9 .from('users')
10 .execute();Select Queries
Select All Columns
1const users = await qb
2 .select('*')
3 .from('users')
4 .execute();Select Specific Columns
1const users = await qb
2 .select('id, name, email')
3 .from('users')
4 .execute();Select with Aliases
1const results = await qb
2 .select('u.id, u.name as username, u.email')
3 .from('users u')
4 .execute();Where Clauses
Simple Where
1const activeUsers = await qb
2 .select('*')
3 .from('users')
4 .where('status', '=', 'active')
5 .execute();Multiple Where Clauses
1const results = await qb
2 .select('*')
3 .from('users')
4 .where('status', '=', 'active')
5 .where('age', '>=', 18)
6 .where('country', '=', 'USA')
7 .execute();Different Operators
1// Equals
2qb.where('status', '=', 'active')
3
4// Not equals
5qb.where('status', '!=', 'deleted')
6
7// Greater than
8qb.where('age', '>', 18)
9
10// Greater than or equal
11qb.where('age', '>=', 18)
12
13// Less than
14qb.where('price', '<', 100)
15
16// Less than or equal
17qb.where('price', '<=', 100)
18
19// LIKE pattern matching
20qb.where('email', 'LIKE', '%@gmail.com')
21
22// IN clause
23qb.where('status', 'IN', ['active', 'pending'])
24
25// IS NULL
26qb.where('deleted_at', 'IS NULL', null)Sorting
Order By Single Column
1const users = await qb
2 .select('*')
3 .from('users')
4 .orderBy('created_at', 'DESC')
5 .execute();Order By Multiple Columns
1const users = await qb
2 .select('*')
3 .from('users')
4 .orderBy('last_name', 'ASC')
5 .orderBy('first_name', 'ASC')
6 .execute();Pagination
Limit
1const topUsers = await qb
2 .select('*')
3 .from('users')
4 .orderBy('score', 'DESC')
5 .limit(10)
6 .execute();Limit with Offset
1// Get page 3 (assuming 20 items per page)
2const page3 = await qb
3 .select('*')
4 .from('users')
5 .orderBy('created_at', 'DESC')
6 .limit(20)
7 .offset(40) // Skip first 40 records
8 .execute();Complex Queries
Search and Filter
1const searchResults = await qb
2 .select('id, name, email, created_at')
3 .from('users')
4 .where('status', '=', 'active')
5 .where('email', 'LIKE', '%@company.com')
6 .where('created_at', '>=', '2024-01-01')
7 .orderBy('name', 'ASC')
8 .limit(50)
9 .execute();Joining Tables
1// Manual join using raw query
2const adapter = connection.getAdapter();
3const usersWithPosts = await adapter.query(`
4 SELECT
5 u.id,
6 u.name,
7 u.email,
8 COUNT(p.id) as post_count
9 FROM users u
10 LEFT JOIN posts p ON u.id = p.author_id
11 WHERE u.status = ?
12 GROUP BY u.id, u.name, u.email
13 ORDER BY post_count DESC
14`, ['active']);Aggregate Functions
1// Count
2const countResult = await adapter.query(
3 'SELECT COUNT(*) as total FROM users WHERE status = ?',
4 ['active']
5);
6const totalUsers = countResult[0].total;
7
8// Average
9const avgResult = await adapter.query(
10 'SELECT AVG(price) as avg_price FROM products'
11);
12
13// Sum
14const sumResult = await adapter.query(
15 'SELECT SUM(amount) as total_revenue FROM orders WHERE status = ?',
16 ['completed']
17);
18
19// Min and Max
20const rangeResult = await adapter.query(
21 'SELECT MIN(price) as min_price, MAX(price) as max_price FROM products'
22);Building vs Executing
Build SQL String
1const qb = new QueryBuilder(adapter);
2qb.select('*')
3 .from('users')
4 .where('status', '=', 'active')
5 .orderBy('created_at', 'DESC')
6 .limit(10);
7
8// Get the SQL string and parameters
9const { sql, params } = qb.build();
10console.log('SQL:', sql);
11console.log('Params:', params);
12
13// Execute later
14const results = await qb.execute();SQL Injection Protection
The Query Builder automatically uses parameterized queries to protect against SQL injection:
1// SAFE - parameters are properly escaped
2const userInput = "admin'; DROP TABLE users--";
3const results = await qb
4 .select('*')
5 .from('users')
6 .where('username', '=', userInput)
7 .execute();
8
9// This generates a safe query:
10// SQL: SELECT * FROM users WHERE username = ?
11// Params: ["admin'; DROP TABLE users--"]Warning
Never concatenate user input directly into SQL queries. Always use the Query Builder or parameterized queries to prevent SQL injection attacks.
Practical Examples
User Search
services/userSearch.ts
1import { QueryBuilder } from 'foundry-orm';
2import connection from '../db/connection';
3
4export async function searchUsers(
5 searchTerm: string,
6 status?: string,
7 page: number = 1,
8 perPage: number = 20
9) {
10 const adapter = connection.getAdapter();
11 const qb = new QueryBuilder(adapter);
12
13 qb.select('id, username, email, created_at')
14 .from('users')
15 .where('username', 'LIKE', `%${searchTerm}%`);
16
17 if (status) {
18 qb.where('status', '=', status);
19 }
20
21 qb.orderBy('created_at', 'DESC')
22 .limit(perPage)
23 .offset((page - 1) * perPage);
24
25 return await qb.execute();
26}Product Filtering
services/productFilter.ts
1export async function filterProducts(filters: {
2 category?: string;
3 minPrice?: number;
4 maxPrice?: number;
5 inStock?: boolean;
6 sortBy?: 'price' | 'name' | 'created';
7 sortOrder?: 'ASC' | 'DESC';
8}) {
9 const adapter = connection.getAdapter();
10 const qb = new QueryBuilder(adapter);
11
12 qb.select('*').from('products');
13
14 if (filters.category) {
15 qb.where('category', '=', filters.category);
16 }
17
18 if (filters.minPrice !== undefined) {
19 qb.where('price', '>=', filters.minPrice);
20 }
21
22 if (filters.maxPrice !== undefined) {
23 qb.where('price', '<=', filters.maxPrice);
24 }
25
26 if (filters.inStock) {
27 qb.where('stock', '>', 0);
28 }
29
30 const sortColumn = filters.sortBy || 'created_at';
31 const sortOrder = filters.sortOrder || 'DESC';
32 qb.orderBy(sortColumn, sortOrder);
33
34 return await qb.execute();
35}Best Practices
Tips
- Always use the Query Builder or parameterized queries
- Select only the columns you need instead of using SELECT *
- Use indexes on columns in WHERE and ORDER BY clauses
- Implement pagination for large result sets
- Use LIMIT to prevent accidental full table scans
- Test queries with EXPLAIN to optimize performance