Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend Metasql query builder section on DATA page #25

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions content/en/DATA.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,27 @@ async ({ countryId }) => {
};
```

It uses Metarhia's [native SQL builder](https://github.com/metarhia/metasql) to access data from PostgreSQL database. Exactly that example demonstrates simple `select` usage, one of the builder's function among bunch of others available:
- `row` to query and receive data of a single row
- `scalar` to get result as a single scalar value
- `col` to get values from the one column in a form of array
- `dict` to get results of two columns from table as a dictionary object where first column values becomes keys, second column — its related values.
- `count` to get number of records in some table optionally restricted by where filter
- `insert`
- `update`
- `delete`
- `returning`
- `order`
- `desc` — counterpart of `order` for descending ordering
- `offset`
- `limit`
- `query` as approach to use pg driver directly for any parameterized SQL
- `sql` as alternative approach to build query using special SQL template syntax (more on that later).

In case you had started with [metarhia/Example](https://github.com/metarhia/Example) setup of the Metasql query builder is already done there. Otherwise it will be necessary to make few initial setup steps.

### Initial setup

We need Postgres server running and dependencies installed: `npm i pg metasql`.
To initialize connection to the database add following code to file `application/db/pg/start.js`:

Expand Down Expand Up @@ -181,15 +202,33 @@ INSERT INTO "City" ("name", "countryId") VALUES

## Metasql template sql

Metasql has alternative syntax to create query: `sql` template function. Despite it looks like normal template string with SQL value, there is conversion to a parameterized query under the hood to fulfill security requirements. That syntax especially useful for complex queries when traditional builder's functions chaining approach becomes too complicated. Let's look at example:

```js
const maxCount = 3;
const query = db.pg.sql`
SELECT * FROM "City"
WHERE "cityId" < ${5} AND "name" <> 'La Haye-en-Touraine'
WHERE "cityId" < ${5} AND "name" <> ${'excludedCity'}
ORDER BY name
LIMIT 3
LIMIT ${maxCount}
`;
```

The result in `query` variable is a prepared statement, where:
- number literal `5` converted into fixed query param
- value of the `maxCount` variable included as fixed query param
- `excludedCity` becomes a property name of an input argument, different value of which will become query parameter during every call to execute the statement.

To execute this SQL query the statement object has special method `rows` . For example:

```js
const data = await query.rows({ excludedCity: 'La Haye-en-Touraine' });
```

> Note that if you don't provide value for the `excludedCity` — the key will be used among params as a string literal.

Other few methods of prepared statement quite the same as with traditional builder syntax: `row`, `scalar`, `col`, `count`, `dict`. That way you can create queries of unlimited complexity using available SQL operators.

See more examples: https://github.com/metarhia/metasql/blob/master/test/sql.js

## Knex query builder
Expand Down