From 5808df831a426f9740a1d471c1f09831c0f7f1cc Mon Sep 17 00:00:00 2001 From: Christoph Auer Date: Tue, 3 Nov 2026 20:18:22 +0100 Subject: [PATCH] Add landing page and extend the SQL to Delphi converter - Fix AND/OR precedence: the MySQL, PostgreSQL and SQLite grammars group AND/OR left to right, so A OR B AND C was converted as (A OR B) AND C. The converter now restores SQL precedence and keeps explicit parentheses. - Emit flat fluent chains for AND/OR sequences; nest callbacks only where the operator changes. - Support COUNT/SUM/AVG/MIN/MAX, aggregates in HAVING and ORDER BY, subqueries in IN, NOT IN, EXISTS, NOT EXISTS and comparisons, and NOT (...). - Error messages quote the unsupported SQL fragment and suggest the fluent or raw method to use instead. - New landing page; the README becomes the Getting started guide. - Convert button between input and output; page transitions no longer fade content in from transparent. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 ++ README.md | 2 + docs/WEBSITE.md | 7 + website/app.mjs | 2 + website/build.mjs | 28 +- website/converter.html | 11 +- website/converter.mjs | 398 ++++++++++++++++++-------- website/generate-smoke.mjs | 2 +- website/index.html | 30 ++ website/smoke-cases.mjs | 3 + website/style.css | 172 ++++++++++- website/test/browser/website.spec.mjs | 36 ++- website/test/converter.test.mjs | 70 ++++- website/test/site.test.mjs | 10 +- 14 files changed, 641 insertions(+), 154 deletions(-) create mode 100644 website/index.html diff --git a/CHANGELOG.md b/CHANGELOG.md index f2539b7..b2d244f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,30 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- SQL → Delphi converter: `A OR B AND C` was converted as `(A OR B) AND C` for + MySQL, PostgreSQL and SQLite input, because the parser groups AND/OR left to + right. The converter now restores SQL precedence (AND before OR) and keeps + explicit parentheses. + +### Added + +- Website landing page with an example, highlights, installation steps and a + link to the converter. The README is now the **Getting started** guide. +- Converter support for COUNT/SUM/AVG/MIN/MAX (`SelectCount` and so on), + aggregates in HAVING and ORDER BY (`HavingRaw`, `OrderByRaw`), subqueries in + IN, NOT IN, EXISTS, NOT EXISTS and comparisons, and `NOT (…)` groups. + +### Changed + +- The converter emits flat fluent chains for AND or OR sequences and nests a + callback only where the operator changes. +- Converter error messages quote the unsupported SQL fragment and suggest the + fluent or raw method to use instead, without internal parser terms. +- The convert button sits between the SQL input and the Delphi output. Page + transitions no longer fade content in from transparent. + ## [2.0.0] - 2026-10-31 Object mapping, nullable DTO round trips, parameterized fluent compilation and diff --git a/README.md b/README.md index 2984fd0..3baeb20 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,10 @@ Current release: **[v2.0.0](https://github.com/auchri/QueryBuilder4Delphi/releas See the [changelog](CHANGELOG.md) for release details and the [migration guide](docs/MIGRATION.md) when upgrading from v1.0.0. + **[Documentation website](https://auchri.github.io/QueryBuilder4Delphi/)** · **[SQL → Delphi converter](https://auchri.github.io/QueryBuilder4Delphi/converter.html)** + Version 2 adds fluent object mapping, nullable read/write DTOs and explicit SQL NULL policies. `Compile` now returns parameterized SQL and bindings; diff --git a/docs/WEBSITE.md b/docs/WEBSITE.md index b1aff43..106db61 100644 --- a/docs/WEBSITE.md +++ b/docs/WEBSITE.md @@ -12,6 +12,13 @@ point back to GitHub. The generated pages include syntax highlighting, an on-page contents list, and a link to their original Markdown source. The generated `website/dist/` directory is ignored by Git. +The start page (`index.html`) is a short landing page built from +`website/index.html`. Its code example and generated SQL are read from the +README's `SearchBooks` example, so they stay checked against the compiler. The +README itself becomes `guide.html` (**Getting started**). README content that +only makes sense on GitHub, such as links to this website, is wrapped in +`` … `` and left out of the guide. + The footer on every page links to the current GitHub release. Its version is read from the `Current release` declaration in `README.md`, so updating that declaration also updates the website. The changelog and diff --git a/website/app.mjs b/website/app.mjs index 708958b..fb162bf 100644 --- a/website/app.mjs +++ b/website/app.mjs @@ -6,6 +6,8 @@ const examples = { basic: 'SELECT Id, Title\nFROM Books\nWHERE AuthorId = 42\nORDER BY Title;', join: "SELECT b.Id, b.Title, a.Name AS AuthorName\nFROM Books AS b\nLEFT JOIN Authors AS a ON a.Id = b.AuthorId\nWHERE b.Price >= 10\nORDER BY b.Title;", group: "SELECT Id, Title\nFROM Books\nWHERE (AuthorId = 42 OR AuthorId = 7)\n AND Price BETWEEN 10 AND 50\n AND DeletedAt IS NULL\nORDER BY Title DESC;", + aggregate: 'SELECT AuthorId, COUNT(*) AS BookCount, AVG(Price) AS AveragePrice\nFROM Books\nWHERE DeletedAt IS NULL\nGROUP BY AuthorId\nHAVING COUNT(*) >= 5\nORDER BY BookCount DESC;', + subquery: "SELECT Id, Title\nFROM Books\nWHERE AuthorId IN (SELECT Id FROM Authors WHERE Country = 'AT')\n AND NOT EXISTS (SELECT 1 FROM Orders o WHERE o.BookId = Books.Id);", paging: 'SELECT Id, Title\nFROM Books\nORDER BY Title, Id\nLIMIT 20 OFFSET 40;', }; const editors = createEditors({ diff --git a/website/build.mjs b/website/build.mjs index 54c00fc..c448851 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -14,7 +14,8 @@ const release = (await readFile(path.join(root, 'README.md'), 'utf8')).match(/Cu if (!release) throw new Error('README.md must declare the current release.'); const escape = s => String(s).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"'); export const documents = ['README.md', 'CHANGELOG.md', ...(await readdir(path.join(root, 'docs'))).filter(f => f.endsWith('.md')).map(f => `docs/${f}`)]; -const target = source => source === 'README.md' ? 'index.html' : source.replace(/\.md$/, '.html'); +// index.html is the hand-written landing page; the README becomes the guide. +const target = source => source === 'README.md' ? 'guide.html' : source.replace(/\.md$/, '.html'); export function linkTo(href, source) { if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(href)) return href; const match = href.match(/^([^?#]*)(.*)$/); @@ -23,7 +24,7 @@ export function linkTo(href, source) { return path.posix.relative(path.posix.dirname(target(source)), target(resolved)) + match[2]; } const menu = [ - ['README.md', 'Overview'], ['converter.html', 'SQL → Delphi'], + ['index.html', 'Home'], ['README.md', 'Getting started'], ['converter.html', 'SQL → Delphi'], ['docs/EXAMPLES.md', 'Examples'], ['docs/API.md', 'API reference'], ['docs/OBJECT_MAPPING.md', 'Object mapping'], ['docs/PORTING.md', 'Porting'], ['docs/MIGRATION.md', 'Upgrade to v2'], @@ -36,22 +37,23 @@ function shell(title, body, source, toc = []) { const prefix = path.posix.relative(path.posix.dirname(filename), '.') || '.'; const relative = to => path.posix.relative(path.posix.dirname(filename), to); const navLink = ([file, label]) => `${label}`; - const advanced = menu.slice(5); + const advanced = menu.slice(6); const expanded = advanced.some(([file]) => file === source); return ` ${escape(title)} · QueryBuilder4Delphi
QueryBuilder4DelphiGitHub ↗
-
-
${body}
+
+
${body}
${toc.length ? `` : ''}
`; } await mkdir(path.join(output, 'assets'), { recursive: true }); for (const source of documents) { - const markdown = await readFile(path.join(root, source), 'utf8'); + // Website-only pages replace README content marked with website:skip, such as links to this site. + const markdown = (await readFile(path.join(root, source), 'utf8')).replace(/[\s\S]*?\r?\n?/g, ''); const slugger = new GithubSlugger(); const toc = []; const marked = new Marked({ renderer: { @@ -74,6 +76,20 @@ for (const source of documents) { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, shell(title, body, source, toc)); } +// The landing page example comes from the README, whose generated SQL is checked +// against the compiler; the page only adds layout around it. +const readme = await readFile(path.join(root, 'README.md'), 'utf8'); +function readmeBlock(after, language) { + const start = readme.indexOf(after); + const code = start < 0 ? null : readme.slice(start).match(new RegExp('```' + language + '\\r?\\n([\\s\\S]*?)```'))?.[1]; + if (!code) throw new Error(`README.md must contain a ${language} block after ${after}`); + return hljs.highlight(code.replace(/\r\n/g, '\n').trimEnd(), { language }).value; +} +const landing = (await readFile(path.join(site, 'index.html'), 'utf8')) + .replaceAll('{{repo}}', repo).replaceAll('{{release}}', release) + .replace('{{example-delphi}}', readmeBlock('## Fluent search with optional filters', 'delphi')) + .replace('{{example-sql}}', readmeBlock('', 'sql')); +await writeFile(path.join(output, 'index.html'), shell('Fluent, parameterized SQL for Delphi', landing, 'index.html')); const converter = await readFile(path.join(site, 'converter.html'), 'utf8'); await writeFile(path.join(output, 'converter.html'), shell('SQL to Delphi', converter, 'converter.html')); await cp(path.join(site, 'style.css'), path.join(output, 'assets/style.css')); diff --git a/website/converter.html b/website/converter.html index facc920..75d86f6 100644 --- a/website/converter.html +++ b/website/converter.html @@ -1,12 +1,13 @@

THE QUERY WORKBENCH

SQL in. Delphi out.

Turn a SELECT query into fluent QueryBuilder4Delphi code. Everything runs in your browser; your SQL stays on your device.

-
-
01 SQL inputSELECT
02 Delphi output
+ORDER BY Title;

Ctrl+Enter (⌘Enter) to convert · Tab to indent · Escape, then Tab to leave the SQL editor.

-

Ready to convert.

-

What can I convert?

One SELECT statement with table and column aliases, DISTINCT, INNER/LEFT/RIGHT JOIN with one column comparison, CROSS JOIN, grouped AND/OR conditions, column comparisons, LIKE, IN, BETWEEN, IS NULL, GROUP BY, simple HAVING, ORDER BY and literal paging values. SQL Server TOP and OFFSET/FETCH are also supported.

CTEs, unions, subqueries, aggregate/function expressions, complex JOIN conditions, placeholders, quoted identifiers containing spaces or punctuation, and dialect-specific extensions are rejected. No partial code or raw SQL fallback is emitted. Zero row limits and MySQL string literals with backslash escapes are rejected because their meaning cannot be preserved reliably.

Ordinary decimals produce natural Delphi literals such as 19.99, without BCD wrappers or extra imports. Decimals are limited to 15 significant digits (ignoring insignificant zeros) within the normal Double range; high-precision values, subnormal values and scientific notation are rejected. Binary floating-point parameters do not guarantee exact SQL DECIMAL semantics. Exact parameter types depend on your schema: choose Currency, TBcd or another Delphi type manually when needed. Signed integer values retain exact Integer/Int64 validation.

The output is a complete BuildQuery: IQuery function. Compile it with your chosen TSqlDialect in Delphi; the converter does not execute SQL or run the Delphi compiler. PostgreSQL unquoted identifiers are folded to lowercase. SQL comments are not included in the output.

+

Ready to convert.

+
02 Delphi output
+

What can I convert?

One SELECT statement with table and column aliases, DISTINCT, INNER/LEFT/RIGHT JOIN with one column comparison, CROSS JOIN, AND/OR conditions with SQL precedence, NOT (…), column comparisons, LIKE, IN, BETWEEN, IS NULL, GROUP BY, HAVING, ORDER BY and literal paging values. SQL Server TOP and OFFSET/FETCH are also supported.

COUNT, SUM, AVG, MIN and MAX in the select list become SelectCount, SelectSum and so on; aggregates in HAVING and ORDER BY become HavingRaw and OrderByRaw with parameterized values. Subqueries work in IN, NOT IN, EXISTS, NOT EXISTS and comparisons, and are generated as nested TQuery.Create chains.

CTEs, unions, derived tables in FROM, other functions and expressions, COUNT(DISTINCT …), complex JOIN conditions, placeholders, quoted identifiers containing spaces or punctuation, and dialect-specific extensions are rejected. The message quotes the unsupported part and suggests the fluent or raw method to use instead; no partial code is emitted. Zero row limits and MySQL string literals with backslash escapes are rejected because their meaning cannot be preserved reliably.

Ordinary decimals produce natural Delphi literals such as 19.99, without BCD wrappers or extra imports. Decimals are limited to 15 significant digits (ignoring insignificant zeros) within the normal Double range; high-precision values, subnormal values and scientific notation are rejected. Binary floating-point parameters do not guarantee exact SQL DECIMAL semantics. Exact parameter types depend on your schema: choose Currency, TBcd or another Delphi type manually when needed. Signed integer values retain exact Integer/Int64 validation.

The output is a complete BuildQuery: IQuery function. Compile it with your chosen TSqlDialect in Delphi; the converter does not execute SQL or run the Delphi compiler. PostgreSQL unquoted identifiers are folded to lowercase. SQL comments are not included in the output.

diff --git a/website/converter.mjs b/website/converter.mjs index cb7cb93..48f2d00 100644 --- a/website/converter.mjs +++ b/website/converter.mjs @@ -6,12 +6,41 @@ const dialects = { TransactSQL: () => import('node-sql-parser/build/transactsql.js'), SQLite: () => import('node-sql-parser/build/sqlite.js'), }; -const unsupported = detail => { throw new Error(`${detail} is not supported in this version. No code was generated.`); }; +const dialectNames = { MySQL: 'MySQL', PostgreSQL: 'PostgreSQL', TransactSQL: 'SQL Server', SQLite: 'SQLite' }; +const hints = { + column: 'Add it to the generated code with SelectRaw.', + where: 'Add it to the generated code with WhereRaw (or HavingRaw in HAVING).', + literal: 'Use a literal example value; the generated code binds it as a parameter.', +}; +// The query being converted, kept only so errors can quote the offending SQL. +let source = null; +// Literal values were swapped for parser-safe markers; restore them for display. +function restore(text) { + return text.replace(/'QBD-LITERAL-(\d+)'/g, (marker, index) => source.literals.quoted[index] ?? marker) + .replace(/\b7\d{6}\b/g, slot => source.literals.numbers.get(slot) ?? slot); +} +function excerpt(start, end) { + const text = restore(source.text.slice(start, end)).replace(/\s+/g, ' ').trim(); + return text.length > 80 ? `${text.slice(0, 79)}…` : text; +} +function unsupported(detail, node, hint) { + const loc = node?.loc && source ? excerpt(node.loc.start.offset, node.loc.end.offset) : ''; + throw new Error(`The converter does not support ${detail}${loc ? `: “${loc}”` : ''}.${hint ? ` ${hint}` : ''} No code was generated.`); +} const meaningful = value => value != null && value !== false && value !== '' && (typeof value !== 'object' || Object.values(value).some(meaningful)); +const selectParts = { + with: ['common table expressions (WITH)', 'Use the With method in Delphi.'], + _next: ['UNION, INTERSECT or EXCEPT', 'Combine the converted queries with Union, Intersect or Except.'], + set_op: ['UNION, INTERSECT or EXCEPT', 'Combine the converted queries with Union, Intersect or Except.'], + into: ['SELECT … INTO'], locking_read: ['locking clauses such as FOR UPDATE'], + options: ['SELECT options such as SQL_CALC_FOUND_ROWS'], window: ['WINDOW clauses'], +}; function check(node, keys, context) { for (const [key, value] of Object.entries(node)) { - if (!keys.includes(key) && meaningful(value)) unsupported(`${context}: ${key}`); + if (keys.includes(key) || !meaningful(value)) continue; + if (context === 'SELECT' && selectParts[key]) unsupported(selectParts[key][0], null, selectParts[key][1]); + unsupported(`this form of ${context}`, node); } } export function delphiString(value) { @@ -20,67 +49,149 @@ export function delphiString(value) { /^[\x00-\x1f\x7f]$/.test(part) ? `#${part.charCodeAt(0)}` : `'${part.replaceAll("'", "''")}'` ).join('') || "''"; } -function identifier(value) { - if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_$]*$/.test(value)) unsupported('Identifiers containing spaces, punctuation or non-ASCII characters'); +function identifier(value, node) { + if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_$]*$/.test(value)) unsupported('identifiers containing spaces, punctuation or non-ASCII characters', node); return value; } function column(node, star = false) { - if (node?.type !== 'column_ref') unsupported('Expressions, functions and subqueries in place of columns'); - check(node, ['type', 'table', 'column', 'parentheses', 'loc'], 'Column'); + if (node?.type === 'aggr_func') unsupported('aggregates in this position', node, hints.column); + if (node?.type !== 'column_ref') unsupported('expressions, functions or subqueries in place of a column', node, hints.column); + check(node, ['type', 'table', 'column', 'parentheses', 'collate', 'loc'], 'column reference'); const name = typeof node.column === 'object' ? node.column.expr?.value : node.column; - return (node.table ? `${identifier(node.table)}.` : '') + (star && name === '*' ? '*' : identifier(name)); + return (node.table ? `${identifier(node.table, node)}.` : '') + (star && name === '*' ? '*' : identifier(name, node)); } function table(node) { + if (node.expr?.ast || node.expr?.type === 'select') unsupported('derived tables (subqueries in FROM)', node, 'Build the inner query separately and pass it to From.'); check(node, ['db', 'schema', 'table', 'as', 'join', 'on', 'loc'], 'FROM/JOIN'); - if (!node.table) unsupported('Derived tables'); - return [node.db, node.schema, node.table].filter(Boolean).map(identifier).join('.') + (node.as ? ` as ${identifier(node.as)}` : ''); + if (!node.table) unsupported('this table source', node); + return [node.db, node.schema, node.table].filter(Boolean).map(part => identifier(part, node)).join('.') + (node.as ? ` as ${identifier(node.as, node)}` : ''); } -function literal(node, literals) { - if (!node) unsupported('Missing values'); +function literal(node, literals, context) { + if (!node) unsupported('missing values', context); if (node.type === 'number' || node.type === 'unary_expr') { - return numericLiteral(numericText(node, literals)); + return numericLiteral(numericText(node, literals, context)); } - check(node, ['type', 'value', 'loc'], 'Value'); + if (node.type === 'null') unsupported('NULL as a comparison value or in a value list', context, 'Use IS NULL or IS NOT NULL.'); + if (node.type === 'param' || node.type === 'var' || (node.type === 'origin' && node.value === '?')) unsupported('placeholders', context, hints.literal); + check(node, ['type', 'value', 'loc'], 'value'); if (['single_quote_string', 'string'].includes(node.type)) { - if (!literals.strings.has(node.value)) unsupported('This string literal syntax'); + if (!literals.strings.has(node.value)) unsupported('this string literal syntax', context); return delphiString(literals.strings.get(node.value)); } if (['bool', 'boolean'].includes(node.type)) return node.value ? 'True' : 'False'; - unsupported('Parameters, NULL values in lists, or non-scalar values (use literal values for conversion)'); + unsupported('non-literal values', context, hints.literal); } const comparisons = ['=', '!=', '<>', '<', '>', '<=', '>=']; -function predicate(node, method = 'Where', indent = ' ', depth = 0, literals) { - if (depth > 30) unsupported('Conditions nested more than 30 levels'); - if (node?.type !== 'binary_expr') unsupported('This condition'); - check(node, ['type', 'operator', 'left', 'right', 'parentheses', 'loc'], 'Condition'); +const aggregates = { COUNT: 'Count', SUM: 'Sum', AVG: 'Avg', MIN: 'Min', MAX: 'Max' }; +// Returns the fluent method suffix, the column argument and an equivalent raw SQL expression. +function aggregate(node) { + check(node, ['type', 'name', 'args', 'over', 'loc'], 'aggregate'); + const name = String(node.name).toUpperCase(); + if (!aggregates[name]) unsupported(`the aggregate ${name}`, node, hints.column); + check(node.args, ['expr', 'distinct', 'orderby', 'separator', 'parentheses', 'loc'], 'aggregate'); + if (meaningful(node.args.distinct)) unsupported(`${name}(DISTINCT …)`, node, hints.column); + const star = node.args.expr?.type === 'star'; + if (star && name !== 'COUNT') unsupported(`${name}(*)`, node); + const target = star ? '*' : column(node.args.expr); + return { method: aggregates[name], column: target, raw: `${name}(${star ? '*' : target.split('.').map(part => `[${part}]`).join('.')})` }; +} +function functionName(node) { + const name = node?.name; + return String(typeof name === 'string' ? name : name?.name?.map(part => part.value).join('.') ?? '').toUpperCase(); +} +function subquery(node) { + if (node?.ast) return node.ast; + if (node?.type === 'select') return node; + if (node?.type === 'expr_list' && Array.isArray(node.value) && node.value.length === 1) return subquery(node.value[0]); + return null; +} +function existsQuery(node) { + if (node?.type !== 'function' || functionName(node) !== 'EXISTS') return null; + return subquery(node.args) || unsupported('this EXISTS condition', node); +} +const logical = node => node?.type === 'binary_expr' && ['AND', 'OR'].includes(node.operator.toUpperCase()) ? node.operator.toUpperCase() : null; +// Several parser grammars group AND/OR strictly left to right, so A OR B AND C +// arrives as (A OR B) AND C. Rebuild SQL precedence from the source order instead; +// explicitly parenthesized groups stay intact. The result is one flat list per +// operator, so only a change of operator needs a nested callback group. +function logicalTree(node) { + const sequence = []; + (function walk(part, outer) { + if (!logical(part) || (part.parentheses && !outer)) return sequence.push(part); + check(part, ['type', 'operator', 'left', 'right', 'parentheses', 'loc'], 'condition'); + walk(part.left, false); + sequence.push(logical(part)); + walk(part.right, false); + })(node, true); + if (sequence.length === 1) return null; + const alternatives = [[sequence[0]]]; + for (let i = 1; i < sequence.length; i += 2) { + if (sequence[i] === 'OR') alternatives.push([]); + alternatives.at(-1).push(sequence[i + 1]); + } + const and = parts => parts.length === 1 ? parts[0] : { op: 'AND', parts }; + return alternatives.length === 1 ? and(alternatives[0]) : { op: 'OR', parts: alternatives.map(and) }; +} +function conditions(node, method, indent, depth, literals) { + const tree = node.op ? node : logicalTree(node); + if (!tree) return [term(node, method, indent, depth, literals)]; + return tree.parts.map((part, i) => term(part, i && tree.op === 'OR' ? `Or${method}` : method, indent, depth, literals)); +} +function group(node, method, indent, depth, literals) { + if (depth > 30) unsupported('conditions nested more than 30 levels', node.op ? node.parts[0] : node); + const base = method.replace(/^Or/, '').replace(/Not$/, ''); + return `${indent}.${method}(\n${indent} function(Q: IQuery): IQuery\n${indent} begin\n${indent} Result := Q\n` + + conditions(node, base, indent + ' ', depth + 1, literals).join('\n') + `;\n${indent} end)`; +} +function term(node, method, indent, depth, literals) { + if (node.op || logical(node)) return group(node, method, indent, depth, literals); + const exists = existsQuery(node); + if (exists) return `${indent}.${method}Exists(${chain(exists, indent + ' ', literals, true)})`; + // Depending on the dialect, NOT (…) arrives as a unary operator or as a NOT() function. + const inner = node?.type === 'unary_expr' && ['NOT', 'NOT EXISTS'].includes(node.operator.toUpperCase()) ? node.expr : + node?.type === 'function' && functionName(node) === 'NOT' && node.args?.value?.length === 1 ? node.args.value[0] : null; + if (inner) { + const negated = node.operator?.toUpperCase() === 'NOT EXISTS' ? subquery(inner) : existsQuery(inner); + if (negated) return `${indent}.${method}NotExists(${chain(negated, indent + ' ', literals, true)})`; + return group(inner, `${method}Not`, indent, depth, literals); + } + return predicate(node, method, indent, literals); +} +function predicate(node, method, indent, literals) { + if (node?.type !== 'binary_expr') unsupported('this condition', node, hints.where); + check(node, ['type', 'operator', 'left', 'right', 'parentheses', 'loc'], 'condition'); const op = node.operator.toUpperCase(); - if (['AND', 'OR'].includes(op)) { - const base = method.replace(/^Or/, ''); - return `${indent}.${method}(\n${indent} function(Q: IQuery): IQuery\n${indent} begin\n${indent} Result := Q\n` + - predicate(node.left, base, indent + ' ', depth + 1, literals) + '\n' + - predicate(node.right, (op === 'OR' ? 'Or' : '') + base, indent + ' ', depth + 1, literals) + `;\n${indent} end)`; + if (node.left?.type === 'aggr_func') { + if (!comparisons.includes(op)) unsupported(`${op} with an aggregate`, node, hints.where); + return `${indent}.${method}Raw(${delphiString(`${aggregate(node.left).raw} ${op} ?`)}, [${literal(node.right, literals, node)}])`; } const col = delphiString(column(node.left)); - if (['IS', 'IS NOT'].includes(op) && node.right.type === 'null') return `${indent}.${method}${op === 'IS NOT' ? 'Not' : ''}Null(${col})`; + if (['IS', 'IS NOT'].includes(op)) { + if (node.right?.type !== 'null') unsupported(`${op} with a value other than NULL`, node, hints.where); + return `${indent}.${method}${op === 'IS NOT' ? 'Not' : ''}Null(${col})`; + } + const sub = subquery(node.right); + if (sub && ['IN', 'NOT IN'].includes(op)) return `${indent}.${method}${op === 'NOT IN' ? 'Not' : ''}In(${col}, ${chain(sub, indent + ' ', literals)})`; + if (sub && comparisons.includes(op)) return `${indent}.${method}(${col}, ${delphiString(op.toLowerCase())}, ${chain(sub, indent + ' ', literals)})`; if (['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'].includes(op)) { - if (node.right.type !== 'expr_list' || !Array.isArray(node.right.value)) unsupported('Subqueries in conditions'); - check(node.right, ['type', 'value', 'parentheses', 'loc'], 'Value list'); - const values = node.right.value.map(value => literal(value, literals)); + if (node.right?.type !== 'expr_list' || !Array.isArray(node.right.value)) unsupported(`this ${op} condition`, node, hints.where); + check(node.right, ['type', 'value', 'parentheses', 'loc'], 'value list'); + const values = node.right.value.map(value => literal(value, literals, node)); const between = op.includes('BETWEEN'); - if ((between && values.length !== 2) || !values.length) unsupported('This value list'); + if ((between && values.length !== 2) || !values.length) unsupported('this value list', node); return `${indent}.${method}${op.startsWith('NOT ') ? 'Not' : ''}${between ? 'Between' : 'In'}(${col}, ${between ? values.join(', ') : `[${values.join(', ')}]`})`; } - if (![...comparisons, 'LIKE', 'NOT LIKE'].includes(op)) unsupported(`Operator ${op}`); - if (node.right.type === 'column_ref') { - if (!comparisons.includes(op)) unsupported('Column comparisons with LIKE'); + if (![...comparisons, 'LIKE', 'NOT LIKE'].includes(op)) unsupported(`the ${op} operator`, node, hints.where); + if (node.right?.type === 'column_ref') { + if (!comparisons.includes(op)) unsupported('LIKE between two columns', node, hints.where); return `${indent}.${method}Columns(${col}, ${delphiString(op)}, ${delphiString(column(node.right))})`; } if (['LIKE', 'NOT LIKE'].includes(op)) { // Validate the scalar before choosing an idiomatic string helper. These // helpers add only their boundary wildcards and do not escape the value. - literal(node.right, literals); + literal(node.right, literals, node); const pattern = literals.strings.get(node.right.value); - if (typeof pattern !== 'string') unsupported('LIKE with a non-string pattern'); + if (typeof pattern !== 'string') unsupported('LIKE with a non-string pattern', node); const simple = pattern.match(/^(%?)([^%_\\[\]]+)(%?)$/); let suffix = 'Like'; let value = pattern; @@ -90,123 +201,166 @@ function predicate(node, method = 'Where', indent = ' ', depth = 0, literals) } return `${indent}.${method}${op === 'NOT LIKE' ? 'Not' : ''}${suffix}(${col}, ${delphiString(value)})`; } - return `${indent}.${method}(${col}, ${delphiString(op.toLowerCase())}, ${literal(node.right, literals)})`; + return `${indent}.${method}(${col}, ${delphiString(op.toLowerCase())}, ${literal(node.right, literals, node)})`; } -function numericText(node, literals) { +function numericText(node, literals, context) { if (node?.type === 'unary_expr' && ['+', '-'].includes(node.operator)) { - check(node, ['type', 'operator', 'expr', 'parentheses', 'loc'], 'Signed number'); - const text = numericText(node.expr, literals); + check(node, ['type', 'operator', 'expr', 'parentheses', 'loc'], 'signed number'); + const text = numericText(node.expr, literals, context); return node.operator === '+' ? text : text.startsWith('-') ? text.slice(1) : '-' + text; } - if (node?.type !== 'number') unsupported('Non-literal numeric values'); - check(node, ['type', 'value', 'loc'], 'Number'); + if (node?.type !== 'number') unsupported('non-literal numeric values', node?.loc ? node : context, hints.literal); + check(node, ['type', 'value', 'loc'], 'number'); // The parser only sees small unique integer slots, never the user's numbers. const text = literals.numbers.get(String(Math.abs(node.value))); - if (text == null) unsupported('Unrecognized numeric syntax'); + if (text == null) unsupported('this numeric syntax', context); return (node.value < 0 ? '-' : '') + text; } -function integer(node, max, literals) { - return pagingLiteral(numericText(node, literals), max); +function integer(node, max, literals, context) { + return pagingLiteral(numericText(node, literals, context), max); } -export async function convert(sql, dialect = 'MySQL') { - if (!dialects[dialect]) unsupported('This SQL dialect'); - if (!sql.trim()) throw new Error('Enter a SELECT query to convert.'); - if (sql.length > 50000) throw new Error('Please use a query shorter than 50,000 characters.'); - const mod = await dialects[dialect](); - const Parser = mod.Parser || mod.default?.Parser; - let ast; - // Preserve SQL literal values ourselves: the parser decodes backslash escapes - // even in dialects where backslashes are ordinary characters. - const literals = { strings: new Map(), numbers: new Map() }; - sql = sql.replace(/--[^\r\n]*|#[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]|'(?:''|[^'])*'|[A-Za-z_][A-Za-z0-9_$]*|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g, (token, offset) => { - if (dialect === 'MySQL' && token.startsWith('/*!')) unsupported('MySQL executable comments'); - if (/^(?:\d|\.\d)/.test(token)) { - const slot = String(7000000 + literals.numbers.size); - literals.numbers.set(slot, token); - return slot; - } - if (!token.startsWith("'")) return token; - if (offset > 0 && /[A-Za-z0-9_$]/.test(sql[offset - 1])) unsupported('Prefixed string literals'); - if (dialect === 'MySQL' && token.includes('\\')) unsupported('MySQL string literals with backslash escapes (SQL mode dependent)'); - const marker = `QBD-LITERAL-${literals.strings.size}`; - literals.strings.set(marker, token.slice(1, -1).replaceAll("''", "'")); - return `'${marker}'`; - }); - // PostgreSQL folds unquoted identifiers to lowercase. Preserve quoted tokens, - // strings and comments, while normalizing the unquoted input before parsing. - if (dialect === 'PostgreSQL') sql = sql.replace(/("(?:""|[^"])*"|'(?:''|[^'])*'|--[^\r\n]*|\/\*[\s\S]*?\*\/)|\b[A-Za-z_][A-Za-z0-9_$]*\b/g, - (token, quoted) => quoted ? token : token.toLowerCase()); - try { ast = new Parser().astify(sql, { database: dialect }); } - catch (error) { throw new Error(`Cannot parse this ${dialect} query: ${error.message}`); } - if (Array.isArray(ast)) { - if (ast.length !== 1) unsupported('Multiple statements'); - [ast] = ast; - } - if (ast.type !== 'select') unsupported('Statements other than SELECT'); - check(ast, ['type', 'columns', 'from', 'where', 'distinct', 'groupby', 'having', 'orderby', 'limit', 'top', 'loc', 'parentheses_symbol', '_parentheses'], 'SELECT'); - if (!Array.isArray(ast.from) || !ast.from.length) unsupported('SELECT without a table'); - const lines = [` Result := TQuery.Create(${delphiString(table(ast.from[0]))})`]; - if (ast.from[0].join || ast.from[0].on) unsupported('This FROM clause'); +// Builds a fluent chain for one SELECT. Subqueries reuse it with a deeper indent; +// inside EXISTS the library emits its own SELECT 1, so literal columns are dropped. +function chain(ast, indent, literals, exists = false) { + if (ast?.type !== 'select') unsupported('statements other than SELECT', ast, 'Build INSERT, UPDATE and DELETE statements with AsInsert, AsUpdate and AsDelete.'); + check(ast, ['type', 'columns', 'from', 'where', 'distinct', 'groupby', 'having', 'orderby', 'limit', 'top', 'loc', 'parentheses_symbol', '_parentheses', 'parentheses'], 'SELECT'); + if (!Array.isArray(ast.from) || !ast.from.length) unsupported('SELECT without a table', ast); + const lines = [`TQuery.Create(${delphiString(table(ast.from[0]))})`]; + if (ast.from[0].join || ast.from[0].on) unsupported('this FROM clause', ast.from[0]); if (meaningful(ast.distinct)) { - if (ast.distinct !== 'DISTINCT' && !(ast.distinct.type === 'DISTINCT' && !meaningful(ast.distinct.on))) unsupported('DISTINCT ON'); - lines.push(' .Distinct'); - } - if (ast.columns === '*') lines.push(" .Select(['*'])"); - else lines.push(` .Select([${ast.columns.map(item => { - check(item, ['expr', 'as', 'type', 'loc'], 'SELECT item'); - if (item.type && item.type !== 'expr') unsupported('This SELECT item'); - const name = item.expr?.type === 'star' ? '*' : column(item.expr, true); - return delphiString(name + (item.as ? ` as ${identifier(item.as)}` : '')); - }).join(', ')}])`); + if (ast.distinct !== 'DISTINCT' && !(ast.distinct.type === 'DISTINCT' && !meaningful(ast.distinct.on))) unsupported('DISTINCT ON', ast); + lines.push(`${indent}.Distinct`); + } + if (ast.columns === '*') lines.push(`${indent}.Select(['*'])`); + else { + const plain = []; + const flush = () => { if (plain.length) lines.push(`${indent}.Select([${plain.splice(0).join(', ')}])`); }; + for (const item of ast.columns) { + check(item, ['expr', 'as', 'type', 'loc'], 'SELECT item'); + if (item.type && item.type !== 'expr') unsupported('this SELECT item', item, hints.column); + const alias = item.as ? ` as ${identifier(item.as, item.expr)}` : ''; + if (exists && item.expr?.type === 'number' && !alias) continue; + if (item.expr?.type === 'aggr_func') { + flush(); + const { method, column: target } = aggregate(item.expr); + lines.push(`${indent}.Select${method}(${delphiString(target + alias)})`); + continue; + } + plain.push(delphiString((item.expr?.type === 'star' ? '*' : column(item.expr, true)) + alias)); + } + flush(); + } for (const join of ast.from.slice(1)) { const target = delphiString(table(join)); - if (join.join === 'CROSS JOIN' && !join.on) { lines.push(` .CrossJoin(${target})`); continue; } - const method = { 'INNER JOIN': 'Join', 'LEFT JOIN': 'LeftJoin', 'RIGHT JOIN': 'RightJoin' }[join.join]; + if (join.join === 'CROSS JOIN' && !join.on) { lines.push(`${indent}.CrossJoin(${target})`); continue; } + const method = { 'INNER JOIN': 'Join', 'JOIN': 'Join', 'LEFT JOIN': 'LeftJoin', 'RIGHT JOIN': 'RightJoin' }[join.join]; const on = join.on; - if (!method || on?.type !== 'binary_expr' || !comparisons.includes(on.operator)) unsupported('JOINs other than INNER/LEFT/RIGHT with a single column comparison, or CROSS JOIN'); + if (!join.join) unsupported('comma-separated tables in FROM', join, 'Write the join with INNER JOIN … ON.'); + if (!method || on?.type !== 'binary_expr' || !comparisons.includes(on.operator)) unsupported('JOINs other than INNER/LEFT/RIGHT JOIN on a single column comparison, or CROSS JOIN', join, 'Add the extra JOIN conditions with a Join callback in Delphi.'); check(on, ['type', 'operator', 'left', 'right', 'parentheses', 'loc'], 'JOIN condition'); - lines.push(` .${method}(${target}, ${delphiString(column(on.left))}, ${delphiString(column(on.right))}, ${delphiString(on.operator)})`); + lines.push(`${indent}.${method}(${target}, ${delphiString(column(on.left))}, ${delphiString(column(on.right))}, ${delphiString(on.operator)})`); } - if (ast.where) lines.push(predicate(ast.where, 'Where', ' ', 0, literals)); + if (ast.where) lines.push(...conditions(ast.where, 'Where', indent, 0, literals)); if (ast.groupby) { - const group = ast.groupby; - if (!Array.isArray(group)) check(group, ['columns', 'modifiers'], 'GROUP BY'); - if (meaningful(group.modifiers)) unsupported('GROUP BY modifiers'); - lines.push(` .GroupBy([${(Array.isArray(group) ? group : group.columns).map(c => delphiString(column(c))).join(', ')}])`); + const groupBy = ast.groupby; + if (!Array.isArray(groupBy)) check(groupBy, ['columns', 'modifiers'], 'GROUP BY'); + if (meaningful(groupBy.modifiers)) unsupported('GROUP BY modifiers such as WITH ROLLUP', ast); + lines.push(`${indent}.GroupBy([${(Array.isArray(groupBy) ? groupBy : groupBy.columns).map(c => delphiString(column(c))).join(', ')}])`); } - if (ast.having) lines.push(predicate(ast.having, 'Having', ' ', 0, literals)); + if (ast.having) lines.push(...conditions(ast.having, 'Having', indent, 0, literals)); for (const order of ast.orderby || []) { - check(order, ['expr', 'type', 'loc'], 'ORDER BY'); - if (order.type && !['ASC', 'DESC'].includes(order.type)) unsupported('This sort direction'); - lines.push(` .OrderBy${order.type === 'DESC' ? 'Desc' : ''}(${delphiString(column(order.expr))})`); + check(order, ['expr', 'type', 'loc', 'nulls'], 'ORDER BY'); + if (meaningful(order.nulls)) unsupported('NULLS FIRST/LAST', order.expr); + if (order.type && !['ASC', 'DESC'].includes(order.type)) unsupported('this sort direction', order.expr); + if (order.expr?.type === 'aggr_func') { + lines.push(`${indent}.OrderByRaw(${delphiString(aggregate(order.expr).raw + (order.type === 'DESC' ? ' DESC' : ''))})`); + continue; + } + if (order.expr?.type !== 'column_ref') unsupported('expressions in ORDER BY', order.expr, 'Add them to the generated code with OrderByRaw.'); + lines.push(`${indent}.OrderBy${order.type === 'DESC' ? 'Desc' : ''}(${delphiString(column(order.expr))})`); } if (ast.top) { check(ast.top, ['value', 'percent', 'with_ties'], 'TOP'); - if (ast.top.percent || ast.top.with_ties) unsupported('TOP PERCENT/WITH TIES'); - const count = integer({ type: 'number', value: ast.top.value }, 2147483647n, literals); - if (count.value === 0n) unsupported('TOP 0 (the library treats Limit(0) as unlimited)'); - lines.push(` .Limit(${count.code})`); + if (ast.top.percent || ast.top.with_ties) unsupported('TOP PERCENT or WITH TIES', ast); + const count = integer({ type: 'number', value: ast.top.value }, 2147483647n, literals, ast); + if (count.value === 0n) unsupported('TOP 0, because the library treats Limit(0) as unlimited', ast); + lines.push(`${indent}.Limit(${count.code})`); } if (ast.limit?.offset || ast.limit?.fetch) { - check(ast.limit, ['offset', 'fetch'], 'Paging'); - if (ast.top) unsupported('TOP combined with OFFSET/FETCH'); + check(ast.limit, ['offset', 'fetch', 'loc'], 'paging'); + if (ast.top) unsupported('TOP combined with OFFSET/FETCH', ast); if (ast.limit.fetch) { - const count = integer(ast.limit.fetch.value, 2147483647n, literals); - if (count.value === 0n) unsupported('FETCH 0'); - lines.push(` .Limit(${count.code})`); + const count = integer(ast.limit.fetch.value, 2147483647n, literals, ast); + if (count.value === 0n) unsupported('FETCH 0, because the library treats Limit(0) as unlimited', ast); + lines.push(`${indent}.Limit(${count.code})`); } - if (ast.limit.offset) lines.push(` .Offset(${integer(ast.limit.offset.value, 9223372036854775807n, literals).code})`); + if (ast.limit.offset) lines.push(`${indent}.Offset(${integer(ast.limit.offset.value, 9223372036854775807n, literals, ast).code})`); } else if (meaningful(ast.limit)) { - check(ast.limit, ['value', 'seperator'], 'Paging'); + check(ast.limit, ['value', 'seperator', 'loc'], 'paging'); const values = ast.limit.value; - if (!Array.isArray(values) || !values.length || values.length > 2 || !['', ',', 'offset'].includes(ast.limit.seperator || '')) unsupported('This paging syntax'); + if (!Array.isArray(values) || !values.length || values.length > 2 || !['', ',', 'offset'].includes(ast.limit.seperator || '')) unsupported('this paging syntax', ast); const offsetFirst = ast.limit.seperator === ','; const count = values[offsetFirst ? 1 : 0]; const offset = values.length === 2 ? values[offsetFirst ? 0 : 1] : null; - const limit = integer(count, 2147483647n, literals); - if (limit.value === 0n) unsupported('LIMIT 0 (the library treats Limit(0) as unlimited)'); - lines.push(` .Limit(${limit.code})`); - if (offset) lines.push(` .Offset(${integer(offset, 9223372036854775807n, literals).code})`); + const limit = integer(count, 2147483647n, literals, ast); + if (limit.value === 0n) unsupported('LIMIT 0, because the library treats Limit(0) as unlimited', ast); + lines.push(`${indent}.Limit(${limit.code})`); + if (offset) lines.push(`${indent}.Offset(${integer(offset, 9223372036854775807n, literals, ast).code})`); + } + return lines.join('\n'); +} +function parseError(error, text, dialect) { + const offset = error?.location?.start?.offset; + let near = ''; + if (typeof offset === 'number') { + // Extend to whole tokens so a literal marker is never cut in half. + const start = text.lastIndexOf(' ', Math.max(0, offset - 1)) + 1; + const end = text.slice(offset).search(/\s/); + near = excerpt(start, end < 0 ? text.length : Math.min(offset + end, start + 60)); + } + return new Error(`Cannot parse this ${dialectNames[dialect]} query${near ? ` near “${near}”` : ' (it ends unexpectedly)'}. Check the syntax and the selected input dialect.`); +} +export async function convert(sql, dialect = 'MySQL') { + if (!dialects[dialect]) throw new Error('Choose one of the listed input dialects.'); + if (!sql.trim()) throw new Error('Enter a SELECT query to convert.'); + if (sql.length > 50000) throw new Error('Please use a query shorter than 50,000 characters.'); + const mod = await dialects[dialect](); + const Parser = mod.Parser || mod.default?.Parser; + let ast; + // Preserve SQL literal values ourselves: the parser decodes backslash escapes + // even in dialects where backslashes are ordinary characters. + const literals = { strings: new Map(), numbers: new Map(), quoted: [] }; + source = { text: sql, literals }; + try { + sql = sql.replace(/--[^\r\n]*|#[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]|'(?:''|[^'])*'|[A-Za-z_][A-Za-z0-9_$]*|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g, (token, offset, text) => { + if (dialect === 'MySQL' && token.startsWith('/*!')) unsupported('MySQL executable comments'); + if (/^(?:\d|\.\d)/.test(token)) { + const slot = String(7000000 + literals.numbers.size); + literals.numbers.set(slot, token); + return slot; + } + if (!token.startsWith("'")) return token; + if (offset > 0 && /[A-Za-z0-9_$]/.test(text[offset - 1])) unsupported(`prefixed string literals such as ${text[offset - 1]}'…'`); + if (dialect === 'MySQL' && token.includes('\\')) unsupported('MySQL string literals with backslash escapes, because their meaning depends on the SQL mode'); + const marker = `QBD-LITERAL-${literals.strings.size}`; + literals.strings.set(marker, token.slice(1, -1).replaceAll("''", "'")); + literals.quoted.push(token); + return `'${marker}'`; + }); + // Excerpts use the rewritten text before case folding, which keeps the user's spelling. + source.text = sql; + // PostgreSQL folds unquoted identifiers to lowercase. Preserve quoted tokens, + // strings and comments, while normalizing the unquoted input before parsing. + if (dialect === 'PostgreSQL') sql = sql.replace(/("(?:""|[^"])*"|'(?:''|[^'])*'|--[^\r\n]*|\/\*[\s\S]*?\*\/)|\b[A-Za-z_][A-Za-z0-9_$]*\b/g, + (token, quoted) => quoted ? token : token.toLowerCase()); + try { ast = new Parser().astify(sql, { database: dialect, parseOptions: { includeLocations: true } }); } + catch (error) { throw parseError(error, source.text, dialect); } + if (Array.isArray(ast)) { + if (ast.length !== 1) unsupported('multiple statements', null, 'Convert one SELECT at a time.'); + [ast] = ast; + } + return `uses\n QueryBuilder4Delphi.Query.Core,\n QueryBuilder4Delphi.Query;\n\nfunction BuildQuery: IQuery;\nbegin\n Result := ${chain(ast, ' ', literals)};\nend;\n`; + } finally { + source = null; } - return `uses\n QueryBuilder4Delphi.Query.Core,\n QueryBuilder4Delphi.Query;\n\nfunction BuildQuery: IQuery;\nbegin\n${lines.join('\n')};\nend;\n`; } diff --git a/website/generate-smoke.mjs b/website/generate-smoke.mjs index bac2451..b4525bc 100644 --- a/website/generate-smoke.mjs +++ b/website/generate-smoke.mjs @@ -45,7 +45,7 @@ begin raise Exception.Create(Name + ': empty SQL'); if Result.Bindings.Count <> ExpectedBindings then raise Exception.Create(Name + ': wrong binding count'); - Writeln(Name + ': compiled SQL and checked bindings'); + Writeln(Name + ': ' + Result.Sql); end; procedure CheckInteger(const Value: TValue; const Expected: string; IsInt64: Boolean); diff --git a/website/index.html b/website/index.html new file mode 100644 index 0000000..d2278c5 --- /dev/null +++ b/website/index.html @@ -0,0 +1,30 @@ +
+

FLUENT SQL FOR DELPHI 12+

+

Write queries, not SQL strings.

+

QueryBuilder4Delphi builds parameterized SQL for six databases from one fluent Delphi API. Values become bindings, never concatenated text. A port of the .NET library SqlKata.

+ +

{{release}} adds object mapping, nullable DTOs and explicit NULL policies.

+
+
+

Example

+
Delphi · optional filters and paging
{{example-delphi}}
+
Generated SQL · SQL Server dialect
{{example-sql}}
+
+
+

Parameterized by default

Compile returns SQL with placeholders plus ordered bindings. A diagnostic preview with substituted values is a separate, explicit call.

+

Six dialects, one API

SQL Server, PostgreSQL, MySQL, SQLite, Oracle and Firebird. Quoting, placeholders and paging follow the selected compiler.

+

Objects in, objects out

Map rows to classes with ToList, First or Single, write DTOs back, and execute through FireDAC or your own provider.

+
+
+

Up and running in three steps

+
    +
  1. Add src to the Delphi search path. The core needs only the RTL; FireDAC is optional.
  2. +
  3. Use two units: QueryBuilder4Delphi.Query.Core and QueryBuilder4Delphi.Query.
  4. +
  5. Build, compile, execute. Pass the SQL and bindings to your data access layer, or call Execute with a provider.
  6. +
+

Read the full guide →

+
+
+

Already have SQL?

Paste a SELECT query and get fluent Delphi code. It runs entirely in your browser.

+Open the converter +
diff --git a/website/smoke-cases.mjs b/website/smoke-cases.mjs index e6cf8b5..0a2d019 100644 --- a/website/smoke-cases.mjs +++ b/website/smoke-cases.mjs @@ -11,5 +11,8 @@ export const smokeCases = [ { name: 'Paging', sql: dialect => dialect === 'TransactSQL' ? 'SELECT Id FROM Books ORDER BY Title DESC, Id OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY' : 'SELECT Id FROM Books ORDER BY Title DESC, Id LIMIT 20 OFFSET 40', bindings: 2 }, { name: 'IntegerBounds', sql: 'SELECT Id FROM Books WHERE Id IN (2147483647, -2147483648, 2147483648, -2147483649, 9007199254740993, 9223372036854775807, -9223372036854775808)', bindings: 7, integerValues: ['2147483647', '-2147483648', '2147483648', '-2147483649', '9007199254740993', '9223372036854775807', '-9223372036854775808'] }, { name: 'Decimals', sql: 'SELECT Id FROM Books WHERE Price IN (0.1, 19.99, 1.2300, .125, 1., -0.000000000000000001)', bindings: 6, decimalValues: ['0.1', '19.99', '1.2300', '0.125', '1.0', '-0.000000000000000001'] }, + { name: 'Aggregates', sql: 'SELECT AuthorId, COUNT(*) AS BookCount, SUM(Price) AS Total FROM Books GROUP BY AuthorId HAVING COUNT(*) > 2 OR SUM(Price) >= 99.5 ORDER BY COUNT(*) DESC', bindings: 2 }, + { name: 'Subqueries', sql: "SELECT Id FROM Books WHERE AuthorId IN (SELECT Id FROM Authors WHERE Country = 'AT') AND NOT EXISTS (SELECT 1 FROM Orders o WHERE o.BookId = Books.Id) AND Price > (SELECT AVG(Price) FROM Books WHERE Price > 0)", bindings: 2 }, + { name: 'Negation', sql: 'SELECT Id FROM Books WHERE NOT (Id = 1 OR Id = 2) AND Price > 10', bindings: 3 }, { name: 'Variants', sql: dialect => `SELECT b.Id FROM Books b INNER JOIN Authors a ON a.Id = b.AuthorId ${dialect === 'SQLite' ? 'LEFT JOIN Publishers p ON p.Id = b.PublisherId INNER JOIN Languages l ON l.Id = b.LanguageId' : 'RIGHT JOIN Publishers p ON p.Id = b.PublisherId CROSS JOIN Languages l'} WHERE b.Title NOT LIKE '%draft%' OR b.Title LIKE 'A_B%' GROUP BY b.Id HAVING b.Id NOT BETWEEN 1 AND 2 OR b.Id IS NOT NULL`, bindings: 4 }, ]; diff --git a/website/style.css b/website/style.css index 160e0d5..bdbcabe 100644 --- a/website/style.css +++ b/website/style.css @@ -339,7 +339,13 @@ summary:focus-visible { .editors { display: grid; grid-template-columns: 1fr 1fr; + align-items: start; gap: 18px; + margin-bottom: 34px; +} +/* The convert action sits between input and output in both layouts. */ +.input-column { + min-width: 0; } .editor-panel { border: 1px solid var(--line); @@ -374,7 +380,7 @@ summary:focus-visible { display: flex; align-items: center; gap: 20px; - margin: 20px 0 34px; + margin: 16px 0 0; } .convert-actions p { margin: 0; @@ -408,6 +414,143 @@ summary:focus-visible { color: var(--muted); font-size: 0.85rem; } +/* Landing page. Code blocks reuse the documentation styles. */ +.landing { + grid-column: 2/4; + padding-right: 40px; + max-width: 1280px; +} +.landing h1 { + font-size: clamp(2.5rem, 4.6vw, 4.6rem); + line-height: 1.05; + margin: 14px 0 22px; +} +.hero .lead { + font-size: 1.15rem; + max-width: 760px; +} +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin: 30px 0 18px; +} +.button { + display: inline-flex; + align-items: center; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--panel); + color: var(--text); + padding: 10px 18px; + font-size: 0.9rem; + text-decoration: none; + transition: + background-color 160ms ease, + border-color 160ms ease; +} +.button:hover { + color: var(--text); + border-color: var(--accent); +} +.button.primary, +.button.primary:hover { + color: var(--on-accent); + background: var(--accent); + border-color: var(--accent); + font-weight: 650; +} +.button.primary:hover { + background: var(--accent-hover); +} +.release { + font-size: 0.85rem; + color: var(--muted); +} +.showcase { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); + align-items: start; + gap: 18px; + margin: 36px 0 12px; +} +.showcase .code-block { + margin: 0; +} +.showcase pre { + font-size: 0.82rem; +} +.features { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 18px; + margin: 44px 0; +} +.features article { + border: 1px solid var(--line); + border-radius: 9px; + background: var(--panel); + padding: 22px 24px 8px; +} +.features h2 { + font-size: 1.05rem; + letter-spacing: 0; + margin: 0 0 10px; +} +.landing :is(.features, .install, .cta) p, +.install li { + color: var(--text-secondary); + font-size: 0.92rem; +} +.landing p code, +.install li code { + overflow-wrap: anywhere; +} +.install h2, +.cta h2 { + font-size: 1.45rem; + margin: 0 0 14px; +} +.install ol { + padding-left: 22px; + margin: 0 0 14px; +} +.install li { + margin: 0.5rem 0; +} +.install strong { + color: var(--text); +} +.cta { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + margin: 44px 0 0; + padding: 26px 28px; + border: 1px solid var(--line); + border-left: 3px solid var(--accent); + border-radius: 9px; + background: var(--panel); +} +.cta p { + margin: 0; +} +.cta .button { + white-space: nowrap; +} +.primary span, +.button span { + margin-left: 14px; +} +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} .skip { position: absolute; top: -60px; @@ -428,12 +571,17 @@ summary:focus-visible { .toc { display: none; } - .converter-page { + .converter-page, + .landing { grid-column: 2; } main { padding: 32px; } + .showcase, + .features { + grid-template-columns: minmax(0, 1fr); + } .sidebar { padding: 28px 15px; } @@ -477,9 +625,19 @@ summary:focus-visible { padding: 6px 10px; } main, - .converter-page { + .converter-page, + .landing { padding: 30px 20px 12px; } + .cta { + flex-direction: column; + align-items: start; + padding: 22px 20px; + } + .hero-actions .button { + flex: 1 1 auto; + justify-content: center; + } h1, .documentation h1 { font-size: 2rem; @@ -731,12 +889,14 @@ button, background: var(--surface-hover); } +/* Movement only: content is fully visible from the first frame, even where + animations are paused or throttled. */ main { - animation: page-arrive 260ms ease-out both; + animation: page-arrive 220ms ease-out; } .documentation :is(h1, h2, h3, h4):target { - animation: section-arrive 900ms ease-out; + animation: section-arrive 600ms ease-out; border-radius: 6px; } @@ -782,11 +942,9 @@ main { @keyframes page-arrive { from { - opacity: 0; transform: translateY(6px); } to { - opacity: 1; transform: translateY(0); } } diff --git a/website/test/browser/website.spec.mjs b/website/test/browser/website.spec.mjs index 36cfc7b..deb7f57 100644 --- a/website/test/browser/website.spec.mjs +++ b/website/test/browser/website.spec.mjs @@ -60,7 +60,9 @@ test('copy fallback selects the read-only output', async ({ page }) => { test('navigation has one active page and a keyboard-accessible Advanced group', async ({ page }) => { await page.goto('index.html'); const nav = page.getByRole('navigation', { name: 'Documentation', exact: true }); - await expect(nav.locator('[aria-current="page"]')).toHaveText('Overview'); + await expect(nav.locator('[aria-current="page"]')).toHaveText('Home'); + await nav.getByRole('link', { name: 'Getting started', exact: true }).click(); + await expect(nav.locator('[aria-current="page"]')).toHaveText('Getting started'); await expect(nav.locator('details')).not.toHaveAttribute('open'); const summary = nav.locator('summary'); await summary.focus(); @@ -120,6 +122,38 @@ for (const width of [1920, 1366, 768, 320, 375, 390]) { }); } +test('landing page leads to the guide and the converter at every width', async ({ page }) => { + for (const width of [1920, 1366, 768, 375, 320]) { + await page.setViewportSize({ width, height: 900 }); + await page.goto('index.html'); + await expect(page.getByRole('heading', { level: 1 })).toContainText('Write queries'); + await expect(page.locator('main')).toHaveCSS('opacity', '1'); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + const blocks = await page.locator('.showcase .code-block').all(); + const first = await blocks[0].boundingBox(), second = await blocks[1].boundingBox(); + if (width > 1150) expect(second.x).toBeGreaterThan(first.x + first.width); + else expect(second.y).toBeGreaterThan(first.y + first.height); + } + await page.getByRole('link', { name: 'Get started' }).click(); + await expect(page).toHaveURL(/guide\.html#installation$/); + await page.goto('index.html'); + await page.getByRole('main').getByRole('link', { name: 'Open the converter' }).click(); + await expect(page.getByRole('textbox', { name: 'Generated Delphi code' })).toContainText('BuildQuery'); +}); + +test('convert button sits between SQL input and Delphi output', async ({ page }) => { + for (const width of [1920, 768]) { + await page.setViewportSize({ width, height: 900 }); + await page.goto('converter.html'); + const input = await page.locator('.editor-panel').first().boundingBox(); + const button = await page.getByRole('button', { name: 'Convert to Delphi' }).boundingBox(); + const output = await page.locator('.editor-panel').nth(1).boundingBox(); + expect(button.y).toBeGreaterThan(input.y + input.height); + if (width > 1150) expect(button.x + button.width).toBeLessThan(output.x); + else expect(button.y + button.height).toBeLessThan(output.y); + } +}); + test('reduced motion and editor keyboard focus', async ({ page }) => { await page.emulateMedia({ reducedMotion: 'reduce' }); await page.goto('converter.html'); diff --git a/website/test/converter.test.mjs b/website/test/converter.test.mjs index fa65f99..67e229e 100644 --- a/website/test/converter.test.mjs +++ b/website/test/converter.test.mjs @@ -28,17 +28,62 @@ for (const dialect of ['MySQL', 'PostgreSQL', 'TransactSQL', 'SQLite']) { const code = await convert('SELECT b.Id FROM Books b LEFT JOIN Authors a ON a.Id = b.AuthorId', dialect); assert.ok(code.includes(dialect === 'PostgreSQL' ? ".LeftJoin('authors as a', 'a.id', 'b.authorid', '=')" : ".LeftJoin('Authors as a', 'a.Id', 'b.AuthorId', '=')")); }); - test(`${dialect}: reject unions, subqueries and aggregates`, async () => { - for (const query of ['SELECT Id FROM Books UNION SELECT Id FROM Authors', 'SELECT COUNT(*) FROM Books', 'SELECT Id FROM Books WHERE Id IN (SELECT Id FROM Authors)', 'SELECT * FROM (SELECT Id FROM Books) b']) { - await assert.rejects(convert(query, dialect), /not supported|Cannot parse/); + test(`${dialect}: aggregates become fluent selects and raw HAVING/ORDER BY`, async () => { + const code = await convert('SELECT AuthorId, COUNT(*) AS BookCount, MAX(Price) FROM Books GROUP BY AuthorId HAVING COUNT(*) > 2 ORDER BY COUNT(*) DESC', dialect); + const n = name => dialect === 'PostgreSQL' ? name.toLowerCase() : name; + assert.ok(code.includes(`.Select(['${n('AuthorId')}'])\n .SelectCount('* as ${n('BookCount')}')\n .SelectMax('${n('Price')}')`), code); + assert.ok(code.includes(".HavingRaw('COUNT(*) > ?', [2])"), code); + assert.ok(code.includes(".OrderByRaw('COUNT(*) DESC')"), code); + }); + test(`${dialect}: subqueries in IN, EXISTS and comparisons`, async () => { + const code = await convert("SELECT Id FROM Books WHERE AuthorId IN (SELECT Id FROM Authors WHERE Country = 'AT') AND NOT EXISTS (SELECT 1 FROM Orders) AND Price > (SELECT AVG(Price) FROM Books)", dialect); + const n = name => dialect === 'PostgreSQL' ? name.toLowerCase() : name; + assert.ok(code.includes(`.WhereIn('${n('AuthorId')}', TQuery.Create('${n('Authors')}')\n .Select(['${n('Id')}'])\n .Where('${n('Country')}', '=', 'AT'))`), code); + assert.ok(code.includes(`.WhereNotExists(TQuery.Create('${n('Orders')}'))`), code); + assert.ok(code.includes(`.Where('${n('Price')}', '>', TQuery.Create('${n('Books')}')\n .SelectAvg('${n('Price')}'))`), code); + }); + test(`${dialect}: NOT around a group becomes WhereNot`, async () => { + const code = await convert('SELECT Id FROM Books WHERE NOT (Id = 1 OR Id = 2)', dialect); + assert.match(code, /\.WhereNot\(\n\s+function\(Q: IQuery\): IQuery[\s\S]*\.Where\('id', '=', 1\)\n\s+\.OrWhere\('id', '=', 2\)/i); + }); + test(`${dialect}: reject unions, derived tables and DISTINCT aggregates`, async () => { + for (const query of ['SELECT Id FROM Books UNION SELECT Id FROM Authors', 'SELECT COUNT(DISTINCT AuthorId) FROM Books', 'SELECT * FROM (SELECT Id FROM Books) b']) { + await assert.rejects(convert(query, dialect), /does not support|Cannot parse/); } }); } -test('keeps mixed AND/OR precedence through nested callbacks', async () => { +test('flattens AND chains and nests only mixed precedence', async () => { const code = await convert('SELECT Id FROM Books WHERE (A = 1 OR B = 2) AND (C = 3 OR D = 4)'); - assert.equal((code.match(/function\(Q: IQuery\)/g) || []).length, 3); + assert.equal((code.match(/function\(Q: IQuery\)/g) || []).length, 2); assert.match(code, /\.Where\('A', '=', 1\)\n\s+\.OrWhere\('B', '=', 2\)/); assert.match(code, /\.Where\('C', '=', 3\)\n\s+\.OrWhere\('D', '=', 4\)/); + const flat = await convert("SELECT Id FROM Books WHERE Price BETWEEN 10 AND 20 AND Lang IN ('de', 'en') AND (Title LIKE '%x%' OR Deleted IS NULL)"); + assert.equal((flat.match(/function\(Q: IQuery\)/g) || []).length, 1); + assert.match(flat, /\n \.WhereBetween\('Price', 10, 20\)\n \.WhereIn\('Lang', \['de', 'en'\]\)\n \.Where\(\n/); + assert.match(await convert('SELECT Id FROM Books WHERE A = 1 OR B = 2 OR C = 3'), /\n \.Where\('A', '=', 1\)\n \.OrWhere\('B', '=', 2\)\n \.OrWhere\('C', '=', 3\);/); + const mixed = await convert('SELECT Id FROM Books WHERE A = 1 OR B = 2 AND C = 3'); + assert.match(mixed, /\n \.Where\('A', '=', 1\)\n \.OrWhere\(\n[\s\S]*\.Where\('B', '=', 2\)\n\s+\.Where\('C', '=', 3\);/); +}); +test('AND binds tighter than OR in every dialect, as in SQL', async () => { + // Parser grammars group AND/OR left to right; the converter must restore SQL precedence. + const callbacks = code => code.split('function(Q: IQuery)').length - 1; + for (const dialect of ['MySQL', 'PostgreSQL', 'TransactSQL', 'SQLite']) { + const code = await convert('SELECT Id FROM T WHERE A = 1 AND B = 2 OR C = 3 AND D = 4 OR E = 5', dialect); + assert.equal(callbacks(code), 2, `${dialect}\n${code}`); + assert.match(code, /\n \.Where\(\n[\s\S]*?\.Where\('a', '=', 1\)\n\s+\.Where\('b', '=', 2\);\n\s+end\)\n \.OrWhere\(\n[\s\S]*?\.Where\('c', '=', 3\)\n\s+\.Where\('d', '=', 4\);\n\s+end\)\n \.OrWhere\('e', '=', 5\);/i, dialect); + const grouped = await convert('SELECT Id FROM T WHERE (A = 1 OR B = 2) AND C = 3', dialect); + assert.match(grouped, /\n \.Where\(\n[\s\S]*?\.Where\('a', '=', 1\)\n\s+\.OrWhere\('b', '=', 2\);\n\s+end\)\n \.Where\('c', '=', 3\);/i, dialect); + } +}); +test('error messages name the SQL fragment and suggest an alternative', async () => { + await assert.rejects(convert('SELECT UPPER(Title) FROM Books'), { message: /does not support .*: “UPPER\(Title\)”\. Add it to the generated code with SelectRaw\./ }); + await assert.rejects(convert("SELECT Id FROM Books WHERE Title = 'a' AND Id = ?"), { message: /placeholders: “Id = \?”\. Use a literal example value/ }); + await assert.rejects(convert('SELECT Id FROM Books WHERE Price + 1 > 10.50'), { message: /“Price \+ 1”/ }); + await assert.rejects(convert('UPDATE Books SET Price = 1'), { message: /statements other than SELECT\. Build INSERT, UPDATE and DELETE statements with AsInsert, AsUpdate and AsDelete\./ }); + await assert.rejects(convert("SELECT Id FROM Books WHERE Title === 'x'", 'TransactSQL'), { message: /^Cannot parse this SQL Server query near “===”/ }); + for (const query of ['SELECT Id FROM Books WHERE Id IN (SELECT Id FROM Authors UNION SELECT 1)', 'SELECT Id INTO Other FROM Books', 'SELECT Id FROM Books FOR UPDATE']) { + await assert.rejects(convert(query), error => !/tableList|columnList|_next|locking_read|: into/.test(error.message), query); + } }); test('IN, BETWEEN, LIKE and column comparisons', async () => { const code = await convert("SELECT Id FROM Books WHERE Id NOT IN (1, 2) AND Price BETWEEN 10 AND 20 AND Title LIKE 'Delphi%' AND A >= B"); @@ -104,16 +149,19 @@ test('reject statements and clauses that would otherwise silently lose meaning', 'SELECT * FROM Books LIMIT 0', 'SELECT /*! DISTINCT */ Id FROM Books', 'SELECT Id FROM Books WHERE Id = 1e-324', String.raw`SELECT * FROM Books WHERE Title = 'a\nb'`, - ]) await assert.rejects(convert(query), /not supported|Cannot parse|Paging requires/, query); - await assert.rejects(convert('SELECT TOP 10 PERCENT Id FROM Books', 'TransactSQL'), /not supported/); - await assert.rejects(convert('SELECT TOP 0 Id FROM Books', 'TransactSQL'), /not supported/); - await assert.rejects(convert("SELECT * FROM Books WHERE Title = E'abc'", 'PostgreSQL'), /not supported/); - await assert.rejects(convert('SELECT DISTINCT ON (Id) Id FROM Books', 'PostgreSQL'), /not supported/); + ]) await assert.rejects(convert(query), /does not support|not supported|Cannot parse|Paging requires/, query); + await assert.rejects(convert('SELECT TOP 10 PERCENT Id FROM Books', 'TransactSQL'), /does not support/); + await assert.rejects(convert('SELECT TOP 0 Id FROM Books', 'TransactSQL'), /does not support/); + await assert.rejects(convert("SELECT * FROM Books WHERE Title = E'abc'", 'PostgreSQL'), /does not support/); + await assert.rejects(convert('SELECT DISTINCT ON (Id) Id FROM Books', 'PostgreSQL'), /does not support/); await assert.rejects(convert(''), /Enter a SELECT/); }); test('generated fluent calls exist in the Delphi interface', async () => { const api = await readFile(new URL('../../src/QueryBuilder4Delphi.Query.Core.pas', import.meta.url), 'utf8'); - const code = await convert("SELECT DISTINCT b.Id FROM Books b RIGHT JOIN Authors a ON b.AuthorId=a.Id WHERE b.Price NOT BETWEEN 1 AND 2 OR b.Title NOT LIKE 'A%' GROUP BY b.Id HAVING b.Id IN (1,2) ORDER BY b.Id DESC LIMIT 10 OFFSET 5"); + const code = [ + await convert("SELECT DISTINCT b.Id FROM Books b RIGHT JOIN Authors a ON b.AuthorId=a.Id WHERE b.Price NOT BETWEEN 1 AND 2 OR b.Title NOT LIKE 'A%' GROUP BY b.Id HAVING b.Id IN (1,2) ORDER BY b.Id DESC LIMIT 10 OFFSET 5"), + await convert('SELECT AuthorId, COUNT(*), SUM(Price), AVG(Price), MIN(Price), MAX(Price) FROM Books WHERE NOT (Id = 1) OR NOT EXISTS (SELECT 1 FROM X) OR EXISTS (SELECT 1 FROM Y) OR Id NOT IN (SELECT Id FROM Z) OR Price > (SELECT MAX(Price) FROM Z) GROUP BY AuthorId HAVING COUNT(*) > 1 OR NOT (AuthorId = 2) OR AuthorId IN (SELECT Id FROM A) ORDER BY SUM(Price)'), + ].join('\n'); for (const [, method] of code.matchAll(/\.(\w+)(?:\(|\n)/g)) { if (method === 'Create') continue; assert.match(api, new RegExp(`function ${method}\\b`, 'i'), method); diff --git a/website/test/site.test.mjs b/website/test/site.test.mjs index eed0878..44e1a2a 100644 --- a/website/test/site.test.mjs +++ b/website/test/site.test.mjs @@ -5,7 +5,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../dist'); test('built documentation links and anchors resolve under a project subpath', async () => { - const files = ['index.html', 'CHANGELOG.html', 'converter.html', ...(await readdir(path.join(root, 'docs'))).filter(f => f.endsWith('.html')).map(f => `docs/${f}`)]; + const files = ['index.html', 'guide.html', 'CHANGELOG.html', 'converter.html', ...(await readdir(path.join(root, 'docs'))).filter(f => f.endsWith('.html')).map(f => `docs/${f}`)]; for (const file of files) { const html = await readFile(path.join(root, file), 'utf8'); assert.match(html, /