![Namecheap Takes Down Polyfill.io Service Following Supply Chain Attack](https://cdn.sanity.io/images/cgdhsj6q/production/6af25114feaaac7179b18127c83327568ff592d1-1024x1024.webp?w=800&fit=max&auto=format)
Security News
Namecheap Takes Down Polyfill.io Service Following Supply Chain Attack
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
pg-sql2
Advanced tools
Readme
Create highly dynamic SQL in a powerful and flexible manner without opening yourself to SQL injection attacks.
A key aim of this library is to be very fast, if you think you can improve performance further please open a PR!
To help us develop this software sustainably, we ask all individuals and businesses that use it to help support its ongoing maintenance and development via sponsorship.
And please give some love to our featured sponsors 🤩:
![]() The Guild * | ![]() Dovetail * | ![]() Netflix * | ![]() Stellate * |
Steelhead * |
* Sponsors the entire Graphile suite
const { default: sql } = require("pg-sql2");
// or import sql from 'pg-sql2';
const tableName = "user";
const fields = ["name", "age", "height"];
// sql.join is used to join fragments with a common separator, NOT to join tables!
const sqlFields = sql.join(
// sql.identifier safely escapes arguments and joins them with dots
fields.map((fieldName) => sql.identifier(tableName, fieldName)),
", ",
);
// sql.value will store the value and instead add a placeholder to the SQL
// statement, to ensure that no SQL injection can occur.
const sqlConditions = sql`created_at > NOW() - interval '3 years' and age > ${sql.value(
22,
)}`;
// This could be a full query, but we're going to embed it in another query safely
const innerQuery = sql`select ${sqlFields} from ${sql.identifier(
tableName,
)} where ${sqlConditions}`;
// Symbols are automatically assigned unique identifiers
const sqlAlias = sql.identifier(Symbol());
const query = sql`
with ${sqlAlias} as (${innerQuery})
select
(select json_agg(row_to_json(${sqlAlias})) from ${sqlAlias}) as all_data,
(select max(age) from ${sqlAlias}) as max_age
`;
// sql.compile compiles the query into an SQL statement and a list of values
const { text, values } = sql.compile(query);
console.log(text);
/* ->
with __local_0__ as (select "user"."name", "user"."age", "user"."height" from "user" where created_at > NOW() - interval '3 years' and age > $1)
select
(select json_agg(row_to_json(__local_0__)) from __local_0__) as all_data,
(select max(age) from __local_0__) as max_age
*/
console.log(values); // [ 22 ]
// Then to run the query using `pg` module, do something like:
// const { rows } = await pg.query(text, values);
sql`...`
Builds part of (or the whole of) an SQL query, safely interpreting the embedded
expressions. If a non sql
expression is passed in, e.g.:
sql`select ${1}`;
then an error will be thrown. This prevents SQL injection, as all values must go through an allowed API.
sql.identifier(ident, ...)
Represents a safely escaped SQL identifier; if multiple arguments are passed
then each will be escaped and then they will be joined with dots (e.g.
"schema"."table"."column"
).
sql.value(val)
Represents an SQL value, will be replaced with a placeholder and the value collected up at compile time.
sql.literal(val)
As sql.value
, but in the case of very simple values may write them directly to
the SQL statement rather than using a placeholder. Should only be used with data
that is not sensitive and is trusted (not user-provided data), e.g. for the key
arguments to json_build_object(key, val, key, val, ...)
which you have
produced.
sql.join(arrayOfFragments, delimiter)
Joins an array of sql
values using the delimiter (which is treated as a raw
SQL string); e.g.
const arrayOfSqlFields = ["a", "b", "c", "d"].map((n) => sql.identifier(n));
sql`select ${sql.join(arrayOfSqlFields, ", ")}`; // -> select "a", "b", "c", "d"
const arrayOfSqlConditions = [sql`a = 1`, sql`b = 2`, sql`c = 3`];
sql`where (${sql.join(arrayOfSqlConditions, ") and (")})`; // -> where (a = 1) and (b = 2) and (c = 3)
const fragments = [
{ alias: "name", sqlFragment: sql.identifier("user", "name") },
{ alias: "age", sqlFragment: sql.identifier("user", "age") },
];
sql`
json_build_object(
${sql.join(
fragments.map(
({ sqlFragment, alias }) => sql`${sql.literal(alias)}, ${sqlFragment}`,
),
",\n",
)}
)`;
const arrayOfSqlInnerJoins = [
sql`inner join bar on (bar.foo_id = foo.id)`,
sql`inner join baz on (baz.bar_id = bar.id)`,
];
sql`select * from foo ${sql.join(arrayOfSqlInnerJoins, " ")}`;
// select * from foo inner join bar on (bar.foo_id = foo.id) inner join baz on (baz.bar_id = bar.id)
sql.compile(query)
Compiles the query into an SQL statement and a list of values, ready to be executed
const query = sql`...`;
const { text, values } = sql.compile(query);
// const { rows } = await pg.query(text, values);
sql.compile(query, options)
An advanced form of sql.compile
that can be used to provide the placeholders
when you're using sql.placeholder
.
This is a replacement for
@calebmer's pg-sql
, combining the
additional work that was done to it
in postgraphql
and offering the following enhancements:
sql.literal
which is similar to sql.value
but when used with simple
values can write the valid direct to the SQL statement. USE WITH CAUTION.
The purpose for this is if you are using trusted values (e.g. for the keys
to
json_build_object(...)
)
then debugging your SQL becomes a lot easier because fewer placeholders are
used.FAQs
Generate safe Postgres-compliant SQL with tagged template literals
The npm package pg-sql2 receives a total of 24,161 weekly downloads. As such, pg-sql2 popularity was classified as popular.
We found that pg-sql2 demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.
Security News
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.