Interpolated strings and SQL
Nickolay Bukreyev
buknik95 at ya.ru
Wed Jan 10 15:07:42 UTC 2024
On Monday, 8 January 2024 at 03:05:17 UTC, Walter Bright wrote:
> On 1/7/2024 6:30 PM, Walter Bright wrote:
>> On 1/7/2024 3:50 PM, Timon Gehr wrote:
>>> This cannot work:
>>>
>>> ```
>>> int x=readln.strip.split.to!int;
>>> db.execi(xxx!i"INSERT INTO sample VALUES ($(id), $(2*x))");
>>> ```
>>
>> True, you got me there. It's the 2\*x that is not turnable
>> into an alias. I'm going to think about this a bit.
>
> I wonder if what we're missing are functions that operate on
> tuples and return tuples. We almost have them in the form of:
>
> ```
> template tuple(A ...) { alias tuple = A; }
> ```
>
> but the compiler wants A to only consist of symbols, types and
> expressions that can be computed at compile time. This is so
> the name mangling will work. But what if we don't bother doing
> name mangling for this kind of template?
Yes! It would be brilliant if `alias` could refer to any
Expression, not just symbols. If that was the case, we could just
pass InterpolationHeader/Footer/etc. to template parameters (as
opposed to runtime parameters, where they go now).
```d
// Desired syntax:
db.execi!i"INSERT INTO sample VALUES ($(id), $(2*x))";
// Desugars to:
db.execi!(
InterpolationHeader(),
InterpolatedLiteral!"INSERT INTO sample VALUES ("(),
InterpolatedExpression!"id"(),
id,
InterpolatedLiteral!", "(),
InterpolatedExpression!"2*x"(),
2*x, // Currently illegal (`2*x` is not aliasable).
InterpolatedLiteral!")"(),
InterpolationFooter(),
);
// `execi!(...)` would expand to:
db.execImpl("INSERT INTO sample VALUES (?1, ?2)", id, 2*x);
```
With this approach, they are processed entirely via compile-time
sequence manipulations. Zero-sized structs are never passed as
arguments. Inlining is not necessary to get rid of them.
An example with `writeln` (or just about any function alike):
```d
writeln(interpolate!i"prefix $(baz + 4) suffix");
// Desugars to:
writeln(interpolate!(
InterpolationHeader(),
InterpolatedLiteral!"prefix "(),
InterpolatedExpression!"baz + 4"(),
baz + 4,
InterpolatedLiteral!" suffix"(),
InterpolationFooter(),
));
// `interpolate!(...)` would expand to:
writeln("prefix ", baz + 4, " suffix");
```
More information about the Digitalmars-d
mailing list