Skip to content
This repository was archived by the owner on Aug 22, 2025. It is now read-only.

Commit a289c6d

Browse files
author
Michael Liebmann
committed
fix: add numeric calculation rules to prevent ROUND function errors
1 parent bb2e769 commit a289c6d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/actions/chatWithYourDb.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,13 @@ async function generateSqlQuery(apiKey: string, schemaInfo: string, question: st
270270
- Filter early in CTEs
271271
- Use indexes (typically primary keys) when available
272272
273+
9. Numeric Calculations:
274+
- Always CAST numeric inputs before ROUND: ROUND(CAST(value AS NUMERIC), 2)
275+
- For percentages: ROUND(CAST(value * 100.0 AS NUMERIC), 2)
276+
- For monetary values: ROUND(CAST(value AS NUMERIC), 2)
277+
- For ratios/divisions: ROUND(CAST(CAST(numerator AS NUMERIC) / NULLIF(denominator, 0) AS NUMERIC), 2)
278+
- Handle NULLs: COALESCE(value, 0)
279+
273280
IMPLEMENTATION REQUIREMENTS:
274281
- Generate only SELECT queries (no modifications)
275282
- Include LIMIT ${maxRows} in final results
@@ -432,6 +439,25 @@ function formatQueryResponse(sqlQuery: string): string {
432439
* - Include simple aggregation pattern
433440
* - Avoid unnecessary JOINs for simple calculations
434441
*
442+
* 9. "function round(double precision, integer) does not exist"
443+
* Problem: PostgreSQL type mismatch with ROUND function
444+
* Solution:
445+
* - Always CAST to NUMERIC before ROUND
446+
* - Use proper numeric calculation patterns:
447+
* * Percentages: ROUND(CAST(value * 100.0 AS NUMERIC), 2)
448+
* * Money: ROUND(CAST(value AS NUMERIC), 2)
449+
* * Ratios: ROUND(CAST(CAST(num AS NUMERIC) / NULLIF(denom, 0) AS NUMERIC), 2)
450+
* Example fix:
451+
* Instead of:
452+
* ROUND(price * quantity, 2)
453+
* Use:
454+
* ROUND(CAST(price * quantity AS NUMERIC), 2)
455+
* Testing:
456+
* - Test with decimal values
457+
* - Test with integer values
458+
* - Test with NULL values
459+
* - Test with zero denominators in divisions
460+
*
435461
* IMPLEMENTATION REQUIREMENTS:
436462
* 1. Schema Awareness
437463
* - All queries must be built using actual schema information

0 commit comments

Comments
 (0)