Files
sqlpage--sqlpage/examples/official-site/sqlpage/migrations/72_set_variable.sql
Ophir LOJKINE e93056e6d8 Add sqlpage.set_variable(name, value) function and update docs (#1124)
* feat: Add sqlpage.set_variable function

Co-authored-by: contact <contact@ophir.dev>

* Refactor: Fix set_variable serialization and update tests

Co-authored-by: contact <contact@ophir.dev>

* fix tests: no json_extract on mssql

* Refactor: Update URLParameters handling in set_variable function

- Replaced serde_json::Map with a custom URLParameters struct for better management of URL parameters.
- Introduced methods for handling single and vector values in URLParameters.
- Updated tests to reflect changes in the set_variable function's behavior.

* cargo fmt

* clippy

* retsore set var test

* remove redundant test

* ensure set_variable only takes into account GET variables, not SET

* factor url parameter setting code

* v0.40

* sqlpage.set_variable links to "?" when no parameter is present

- Renamed URLParameters module for clarity and removed the deprecated url_parameter_deserializer.
- Updated the set_variable function to return parameters directly instead of appending to a URL.
- Adjusted related function calls to reflect changes in URL parameter management.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2025-11-24 12:55:32 +01:00

61 lines
1.7 KiB
SQL

INSERT INTO
sqlpage_functions (
"name",
"introduced_in_version",
"icon",
"description_md"
)
VALUES
(
'set_variable',
'0.40.0',
'variable',
'Returns a URL that is the same as the current page''s URL, but with a variable set to a new value.
This function is useful when you want to create a link that changes a parameter on the current page, while preserving other parameters.
It is equivalent to `sqlpage.link(sqlpage.path(), json_patch(sqlpage.variables(''get''), json_object(name, value)))`.
### Example
Let''s say you have a list of products, and you want to filter them by category. You can use `sqlpage.set_variable` to create links that change the category filter, without losing other potential filters (like a search query or a sort order).
```sql
select ''button'' as component, ''sm'' as size, ''center'' as justify;
select
category as title,
sqlpage.set_variable(''category'', category) as link,
case when $category = category then ''primary'' else ''secondary'' end as color
from categories;
```
### Parameters
- `name` (TEXT): The name of the variable to set.
- `value` (TEXT): The value to set the variable to. If `NULL` is passed, the variable is removed from the URL.
'
);
INSERT INTO
sqlpage_function_parameters (
"function",
"index",
"name",
"description_md",
"type"
)
VALUES
(
'set_variable',
1,
'name',
'The name of the variable to set.',
'TEXT'
),
(
'set_variable',
2,
'value',
'The value to set the variable to.',
'TEXT'
);