Skip to content

Commit e38fa29

Browse files
committed
docs: add example how to use insecureRawSQL
1 parent ef8ae38 commit e38fa29

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

adminforth/documentation/docs/tutorial/03-Customization/03-virtualColumns.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,42 @@ columns: [
140140
```
141141
This way, when admin selects, for example, "Luxury" option for "Apartment Type" filter, it will be replace with a more complex "or" filter.
142142
143+
### Custom SQL queries with `insecureRawSQL`
144+
145+
Rarely the sec of Filters supported by AdminForth is not enough for your needs.
146+
In this case you can use `insecureRawSQL` to write your own part of where clause.
147+
148+
However the vital concern that the SQL passed to DB as is, so if you substitute any user inputs it will not be escaped and can lead to SQL injection. To miticate the issue we recommend using `sqlstring` package which will escape the inputs for you.
149+
150+
```bash
151+
npm i sqlstring
152+
```
153+
154+
Then you can use it like this:
155+
156+
```ts title='./resources/apartments.ts'
157+
import sqlstring from 'sqlstring';
158+
...
159+
160+
beforeDatasourceRequest: async ({ query }: { query: any }) => {
161+
query.filters = query.filters.map((filter: any) => {
162+
// replace apartment_type filter with complex one
163+
if (filter.field === 'some_json_b_field') {
164+
return {
165+
// check if some_json_b_field->'$.some_field' is equal to filter.value
166+
insecureRawSQL: `some_json_b_field->'$.some_field' = ${sqlstring.escape(filter.value)}`,
167+
}
168+
}
169+
170+
return filter;
171+
});
172+
return { ok: true, error: "" };
173+
}
174+
```
175+
176+
This example will allow to search for some nested field in JSONB column, however you can use any SQL query here.
177+
178+
143179
144180
## Virtual columns for editing.
145181

0 commit comments

Comments
 (0)