Skip to content

Commit 83d0ad5

Browse files
committed
added filter in our sql parsergit add . weelll, sort of.. 😬
1 parent 505dd7c commit 83d0ad5

File tree

3 files changed

+45
-8
lines changed

3 files changed

+45
-8
lines changed

‎src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ export const SqlToNoSql = (query: string) => {
1414
};
1515

1616
console.log(SqlToNoSql("SELECT * FROM users"));
17+
console.log(SqlToNoSql("select * from users where id = 1"));

‎src/types/sql.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
interface filterType {
2+
column: string;
3+
operator: "=";
4+
value: string | number;
5+
}
6+
7+
export interface ParsedSqlType {
8+
command: "select";
9+
table: string;
10+
columns: string[];
11+
filters: filterType[] | null;
12+
}

‎src/utils/parser.ts‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,41 @@
1-
export const parseQuery = (query: string) => {
2-
const [command, ...rest] = query.split(" ");
1+
// select * from users where id = 1;
32

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");
617
}
18+
parsedQuery.command = command;
719

8-
const fromIndex = rest.findIndex((word) => word === "FROM");
20+
const fromIndex = rest.indexOf("from");
921
if (fromIndex === -1) {
1022
throw new Error("Invalid query, missing FROM keyword");
1123
}
24+
parsedQuery.table = rest[fromIndex + 1];
25+
parsedQuery.columns = rest.slice(0, fromIndex);
1226

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+
}
1539

16-
return { command, table, columns };
40+
return parsedQuery;
1741
};

0 commit comments

Comments
 (0)