The state of string interpolation

Olivier FAURE couteaubleu at
Mon Dec 10 13:48:58 UTC 2018

On Thursday, 6 December 2018 at 16:19:12 UTC, Steven 
Schveighoffer wrote:
> With the concept of lowering to a tuple, I'd love to use such a 
> thing for database queries.
> For instance:
> db.exec("UPDATE Foo SET a = ?, b = ?, c = ?, d = ? WHERE id = 
> ?", aval, bval, cval, dval, id);
> vs.
> db.exec(i"UPDATE Foo SET a = $aval, b = $bval, c = $cval, d = 
> $dval WHERE id = $id");

I really like that, but I'd add a caveat: this syntax makes it 
harder for db.exec to know which arguments you give it are 
trusted compile-time inputs, and which arguments are unsafe 
runtime inputs.

I'd argue for a second syntax to be added as well, fi"formatted 
string". So:

db.exec(fi"UPDATE Foo SET a = $aval, b = $bval, c = $cval, WHERE 
id = $id");

would lower to:

db.exec("UPDATE Foo SET a = %s, b = %s, c = %s, WHERE id = %s", 
aval, bval, cval, id);

That way, db.exec would be able to interpret its first argument 
as trusted input and everything else as unsafe.

That syntax might be redundant if a builtin FromInterpolation 
struct is created. The thing is, there have been arguments 
against using a builtin struct, and a db.exec method built for 
interpolation would be incompatible with regular use, so this:

db.exec("UPDATE Foo SET a = ",aval,", b = ",bval,", c = ",cval,", 
WHERE id = ",id);

would not work, which would have to be documented, etc.

On the other hand, a fi"some string with $var" syntax could 
leverage any already existing db.exec method with a "C format" 
first parameter (including actual C functions?), without forcing 
the library implementation to differentiate between normal 
arguments and FromInterpolation arguments.

More information about the Digitalmars-d mailing list