2.4 KiB
2.4 KiB
TaylorDB Pitfalls & Best Practices
This document captures common mistakes and recommended patterns when using the TaylorDB query builder.
Common Pitfalls
❌ Pitfall: Not Using exactDay for Dates
// ❌ WRONG
.where("date", "=", "2024-01-15")
// ✅ CORRECT
.where("date", "=", ["exactDay", "2024-01-15"])
❌ Pitfall: Ignoring Nullable Fields
// ❌ WRONG (assumes field is always present)
const user = await queryBuilder
.selectFrom("users")
.where("id", "=", 1)
.executeTakeFirst();
console.log(user.email); // Could be undefined!
// ✅ CORRECT
const user = await queryBuilder
.selectFrom("users")
.where("id", "=", 1)
.executeTakeFirst();
if (user && user.email) {
console.log(user.email);
}
❌ Pitfall: Using execute() for Single Record
// ❌ WRONG (returns array)
const user = await queryBuilder
.selectFrom("users")
.where("id", "=", 1)
.execute();
console.log(user.name); // Error: user is an array!
// ✅ CORRECT
const user = await queryBuilder
.selectFrom("users")
.where("id", "=", 1)
.executeTakeFirst();
if (user) {
console.log(user.name);
}
❌ Pitfall: Not Handling Empty Arrays
// ❌ WRONG (fails if users is empty)
const ages = users.map((u) => u.age);
const avg = ages.reduce((a, b) => a + b) / ages.length; // Division by zero!
// ✅ CORRECT
if (users.length === 0) {
return { average: null };
}
const ages = users
.map((u) => u.age)
.filter((a): a is number => a !== undefined);
const avg = ages.reduce((a, b) => a + b, 0) / ages.length;
Best Practices
- Always handle
undefinedandnullwhen working with query results. - Use TypeScript types from
taylordb/types.tsfor type safety. - Use
executeTakeFirst()when you expect a single record. - Filter nullish values before aggregations.
- Provide defaults for optional fields.
- Use
["exactDay", date]format for date comparisons. - Group related queries in the same function file.
- Export functions, not raw queries.
- Document complex queries with JSDoc comments.
For more topics, see:
TAYLORDB_BASIC_QUERIES.mdfor basic reads and filteringTAYLORDB_WRITE_OPERATIONS.mdfor inserts, updates, and deletesTAYLORDB_ADVANCED_PATTERNS.mdfor aggregations, pagination, and conditional queriesTAYLORDB_FIELD_TYPES.mdfor field type handling and enums