This advanced example demonstrates the power of combining:
- SQL Views - for complex data aggregation and analytics
- JavaScript expressions in SQL templates - for dynamic query parts
- Parameterized queries - for type safety and SQL injection prevention
- Conditional filters - that can be included or excluded at runtime
This example simulates a simple e-commerce analytics system with:
- Order Analytics View: Aggregates order data per user (counts, totals, dates)
- Product Reviews View: Aggregates product reviews (average ratings, review counts)
- Dynamic filters: Can be included or excluded based on runtime conditions
- Dynamic sorting: Can change sort fields and direction based on user preferences
const getOrderAnalytics = sql`
SELECT * FROM "ORDER_TOTAL"
WHERE
${props => props.minTotal ? createFilter('total_amount', '>=')(props) : '1=1'}
AND ${props => props.afterDate ? createFilter('last_order_date', '>=')(props) : '1=1'}
ORDER BY ${props => props.orderBy || 'total_amount'} ${props => props.orderDirection || 'DESC'}
`;// Create models from Views
const OrderAnalytics = sql.createQueryFromSchema(orderAnalyticsView, "ORDER_TOTAL");
const ProductReviews = sql.createQueryFromSchema(productReviewsView, "PRODUCT_REVIEWS");
// Using the models
const allAnalytics = await OrderAnalytics.find();const topProducts = await getTopProducts({
minRating: 4.5, // Float type
minReviews: 50, // Integer type
limit: 5 // Integer type
});# From the project root
npm run ts-node examples/advanced-example.tsThe example will show the generated SQL queries and simulated results, demonstrating how the library:
- Transforms JavaScript expressions into SQL parts
- Properly parameterizes values to prevent SQL injection
- Creates model classes from view definitions
- Supports complex conditional logic in queries