←back to thread

620 points tambourine_man | 2 comments | | HN request time: 0s | source
Show context
serbuvlad ◴[] No.43750075[source]
All things considered, this is pretty cool. Basically, this replaces

    db.execute("QUERY WHERE name = ?", (name,))
with

    db.execute(t"QUERY WHERE name = {name}")
Does the benefit from this syntactic sugar outweigh the added complexity of a new language feature? I think it does in this case for two reasons:

1. Allowing library developers to do whatever they want with {} expansions is a good thing, and will probably spawn some good uses.

2. Generalizing template syntax across a language, so that all libraries solve this problem in the same way, is probably a good thing.

replies(12): >>43750226 #>>43750250 #>>43750260 #>>43750279 #>>43750513 #>>43750750 #>>43752117 #>>43752173 #>>43752293 #>>43754738 #>>43756560 #>>43763190 #
Tenoke ◴[] No.43750250[source]
I don't see what it adds over f-string in that example?
replies(6): >>43750258 #>>43750261 #>>43750262 #>>43750265 #>>43750295 #>>43750581 #
ds_ ◴[] No.43750261[source]
The execute function can recognize it as a t-string and prevent SQL injection if the name is coming from user input. f-strings immediately evaluate to a string, whereas t-strings evaluate to a template object which requires further processing to turn it into a string.
replies(1): >>43750286 #
Tenoke ◴[] No.43750286[source]
Then the useful part is the extra execute function you have to write (it's not just a substitute like in the comment) and an extra function can confirm the safety of a value going into a f-string just as well.

I get the general case, but even then it seems like an implicit anti-pattern over doing db.execute(f"QUERY WHERE name = {safe(name)}")

replies(5): >>43750324 #>>43750380 #>>43750409 #>>43754093 #>>43756889 #
1. NewEntryHN ◴[] No.43750380[source]
Some SQL engines support accepting parameters separately so that values get bound to the query once the abstract syntax tree is already built, which is way safer than string escapes shenanigans.
replies(1): >>43751841 #
2. ljm ◴[] No.43751841[source]
I’d always prefer to use a prepared statement if I can, but sadly that’s also less feasible in the fancy new serverless execution environments where the DB adapter often can’t support them.

For me it just makes it easier to identify as safe, because it might not be obvious at a glance that an interpolated template string is properly sanitised.