|
1 | | -export const parseQuery = (query: string) => { |
2 | | - const [command, ...rest] = query.split(" "); |
| 1 | +// select * from users where id = 1; |
3 | 2 |
|
4 | | - if (command !== "SELECT") { |
5 | | - throw new Error("Only SELECT queries are supported"); |
| 3 | +import { ParsedSqlType } from "types/sql"; |
| 4 | + |
| 5 | +export const parseQuery = (query: string): ParsedSqlType => { |
| 6 | + const parsedQuery: ParsedSqlType = { |
| 7 | + command: "select", |
| 8 | + table: "", |
| 9 | + columns: [], |
| 10 | + filters: null, |
| 11 | + }; |
| 12 | + |
| 13 | + const [command, ...rest] = query.toLocaleLowerCase().split(" "); |
| 14 | + |
| 15 | + if (command !== "select") { |
| 16 | + throw new Error("Only select queries are supported"); |
6 | 17 | } |
| 18 | + parsedQuery.command = command; |
7 | 19 |
|
8 | | - const fromIndex = rest.findIndex((word) => word === "FROM"); |
| 20 | + const fromIndex = rest.indexOf("from"); |
9 | 21 | if (fromIndex === -1) { |
10 | 22 | throw new Error("Invalid query, missing FROM keyword"); |
11 | 23 | } |
| 24 | + parsedQuery.table = rest[fromIndex + 1]; |
| 25 | + parsedQuery.columns = rest.slice(0, fromIndex); |
12 | 26 |
|
13 | | - const columns = rest.slice(0, fromIndex); |
14 | | - const table = rest[fromIndex + 1]; |
| 27 | + const whereIndex = rest.indexOf("where"); |
| 28 | + if (whereIndex !== -1) { |
| 29 | + parsedQuery.filters = [ |
| 30 | + { |
| 31 | + column: rest[whereIndex + 1], |
| 32 | + // FIXME: you know what to do here! |
| 33 | + operator: rest[whereIndex + 2] as "=", |
| 34 | + value: rest[whereIndex + 3], |
| 35 | + }, |
| 36 | + ]; |
| 37 | + // throw new Error("Invalid query, WHERE clause is not supported"); |
| 38 | + } |
15 | 39 |
|
16 | | - return { command, table, columns }; |
| 40 | + return parsedQuery; |
17 | 41 | }; |
0 commit comments