Gajus Kuizinas on August 29, 2019

Is it ok to usesql.raw to create a fully dynamicORDER BY query?
letfield="createdAt"letdir="DESC"// generated like field.startsWith("+") ? "ASC" : "DESC"letorderToken=sql` ORDER BY${sql.identifier(field)}${sql.raw(dir)}'`letq=sql` SELECT * FROM "post"${orderToken} LIMIT 3`
You don't need to:sql tags can be nested.
letfield='createdAt';letdir=field.startsWith('+')?sql`ASC`:sql`DESC`;letorderToken=sql` ORDER BY${sql.identifier([field])}${dir}'`;letq=sql` SELECT * FROM "post"${orderToken} LIMIT 3`;
Thanks. What about optionalORDER BY? ForWHERE you started withTRUE so the absence of conditions results inWHERE (true) which is syntactically correct and has no performance implications. I can't find anything than can be used to order by default:
ORDER BY ??? default ???Another attempt with?: breaks the placeholder ordering in query:
SELECT ${makeProjection(pick)} FROM ${sql.identifier([table])}WHERE ${makeWhere(filter)}${sort ? sql`ORDER BY ${makeOrder(sort)}` : ``} -- doesn't workLIMIT ${makeLimit(limit)}OFFSET ${makeOffset(offset)}syntax error at or near "$1"
${sort ? sql`ORDER BY ${makeOrder(sort)}` : sql``}
Causes
InvalidInputError: Unexpected SQL input. Query cannot be empty.
sql`--`
I cannot recall the original reason for this constraint. Will likely remove this constraint. Trackgithub.com/gajus/slonik/issues/93.

Another question. WhyvalueList and other similar functions support only primitive values?
Is TypeScript a reason? The thing I like aboutpg driver is that, unlike MySQL, I canSELECT orINSERT a date, a boolean, an object, etc. value an it will do "the right thing" without an extra hassle.
Maybe it's not entirely safe or somehow "not a good practice" – I dunno.
For now, the API feels limiting for no obvious reason.

Value token can be any primitive that is shared between pg and JavaScript (string, integer, float, boolean, null).
If you have a requirement for automatic coalescing of other object types (such as Date), I suggest raising an issue. I cannot think of other types that would be relatively safe to cast, though.

JS Object withJSON.stringify?

Too many edges cases where an object could be passed accidentally inserting potentially sensitive data to the database.
There issql.json() for that, though.

Slonik's approach is very interesting. Although it's maybe not directly related to Slonik, but because we don't use an ORM:What would be the best way for transforming a SELECT query result of rows into an array of nested objects? For instance if we are joining multiple tables and have a master-detail-relationship. The web client usually expects some kind of nested JSON structure.

You can return JSON from PostgreSQL query.

Not at all. I think it is entirely unnecessary. Keep the queries simple. If you need to nest objects, either use frameworks that automate nesting (e.g. GraphQL), or write simple iteration routines to amend the data structures.

Seems thatsql.valueList does not exist anymore. Also the link above providedContinue reading sql.array vs sql.valueList. does not lead to the right section of the README in the repo.
Was this feature removed lately?

What's the difference betweentuple andvalueList? The only one I see is thattuple adds( and) parens around its values... The implementation and types are almost identical tovalueList, to the point I wonder why not to express one in terms of another or just ditchtuple as unnecessary. Most probably I miss something – that's just my first impression.

Eventuallysql.valueList,sql.rawList,sql.tupleList,sql.identifierList andsql.booleanExpression will be removed in favour of a single methodsql.expressionList.
github.com/gajus/slonik/issues/91
The original intention for separation was to force semantic resemblance and type strictness specific to the code fragment being generated. However, since then types have evolved for all of these helpers to allow a lot broader spectrum of allowed values.

sql.booleanExpression was removed in favour ofsql.join but the article has not been updated.
Seefeat: remove multiple methods in favor of sql.join
The doc link is nowgithub.com/gajus/slonik#slonik-que...

I am fetching issue where I have to generate dynamic ORDER BY clause for multiple columns.
Here is my sample query:
SELECT *FROM userWHERE gender = 'male' ORDER BY created_at ASC, updated_at DESCLIMIT 10 OFFSET 0;My Try:
const orderBy: string = 'ORDER BY created_at ASC, updated_at DESC';SELECT *FROM userWHERE gender = 'male' ${orderBy}LIMIT 10 OFFSET 0;Here, if I pass ORDER BY clause as ${orderBy}, then it take it as a value. It shows error.
The generated sql is like below:
{ sql: "\n SELECT *\nFROM user\nWHERE gender = 'male'\n $1\nLIMIT 10 OFFSET 0;\n", type: 'SLONIK_TOKEN_SQL', values: [ 'ORDER BY created_at ASC, updated_at DESC' ]}Please help me.

Hey Garjus - this is the first time I'm coming across your articles/project. Looks really interesting! I look foward to digging in :) I would love to hear your thoughts ongithub.com/craigmichaelmartin/pure... - apure ORM (no query builder dimension) which allows you to write regular native SQL and receive back properly nested/structured nestedpure (not db-aware stateful) business objects.

Where have all the sql builder functions go and how to replace them?
comparisonPredicate, valueList, etc.
I am trying to construct multiple WHERE statements dynamically, but I get all sorts of errors. The thing is, some of them might be undefined and thus ommited, but then sql builder yells that it's not a valid value

I think you should look into graphic QL

What about GraphQL?
For further actions, you may consider blocking this person and/orreporting abuse