Skip to content

Commit 8ed0247

Browse files
authored
Update text
1 parent c986b86 commit 8ed0247

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

lib/ecto/query/api.ex

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -399,28 +399,33 @@ defmodule Ecto.Query.API do
399399
400400
fragment("lower(?)", p.title) == type(^title, :string)
401401
402-
## Identifiers (literals)
402+
## Identifiers and Constants
403403
404-
Sometimes you need to interpolate a literal value into a fragment,
405-
instead of a parameter. For example, you may need to pass a table
406-
name or a collation, such as:
404+
Sometimes you need to interpolate an identifier or a constant value into a fragment,
405+
instead of a query parameter. The latter can happen if your database does not allow
406+
parameterizing certain clauses. For example:
407407
408408
collation = "es_ES"
409409
fragment("? COLLATE ?", ^name, ^collation)
410410
411-
The example above won't work because `collation` will be passed
412-
as a parameter, while it has to be a literal part of the query.
411+
limit = "10"
412+
"posts" |> select([p], p.title) |> limit(fragment("?", ^limit))
413413
414-
You can address this by telling Ecto that variable is a literal:
414+
The first example above won't work because `collation` needs to be quoted as an identifier.
415+
The second example won't work on databases that do not allow passing query parameters
416+
as part of `limit`.
417+
418+
You can address this by telling Ecto to treat these values differently than a query parameter:
415419
416420
fragment("? COLLATE ?", ^name, identifier(^collation))
421+
"posts" |> select([p], p.title) |> limit(fragment("?", ^constant(limit))
417422
418-
Ecto will then escape it and make it part of the query.
423+
Ecto will make these values directly part of the query, handling quoting and escaping where necessary.
419424
420-
> #### Literals and query caching {: .warning}
425+
> #### Query caching {: .warning}
421426
>
422-
> Because literals are made part of the query, each interpolated
423-
> literal will generate a separate query, with its own cache.
427+
> Because identifiers and constants are made part of the query, each different
428+
> value will generate a separate query, with its own cache.
424429
425430
## Splicing
426431

0 commit comments

Comments
 (0)