asInt method
Extract the value as unquoted text and cast it to an integer.
This method performs a two-step conversion:
- The value is extracted as its unquoted text representation (e.g.
->>). - The resulting text is cast to an integer using standard SQL casting rules.
In SQL this is conceptually similar to:
CAST(JSON_VALUE(this, '$') AS BIGINT)
Extraction Behavior:
- JSON Number
42becomes text"42". - JSON Number
3.14becomes text"3.14". - JSON String
"123"becomes text"123". - JSON String
"hello"becomes text"hello". - JSON Boolean
truebecomes text"true"(or"1"on SQLite).. - JSON Object/Array becomes the JSON string representation (e.g.
'{"a":1}'). - JSON Null
nullbecomes SQLNULL.
Casting Behavior:
- PostgreSQL: Throws a runtime exception if the text is not a valid integer.
- SQLite: Parses the integer prefix of the string (e.g.
"12abc"becomes12). Returns0if no valid prefix exists.
Warning
This is unsafe and may cause runtime errors.
If the JSON data does not match your expectations, the cast may cause
runtime failures or silently return unexpected values (like 0).
Implementation
Expr<int?> asInt() =>
CastExpression._(ExpressionJsonExtract._(this), ColumnType.integer);