Skip to content

get_path_segment() and is_path_matching() sqlpage functions#1266

Open
olivierauverlot wants to merge 2 commits intosqlpage:mainfrom
olivierauverlot:get_path_segment
Open

get_path_segment() and is_path_matching() sqlpage functions#1266
olivierauverlot wants to merge 2 commits intosqlpage:mainfrom
olivierauverlot:get_path_segment

Conversation

@olivierauverlot
Copy link
Copy Markdown
Contributor

Two new useful functions for building RESTful APIs. They avoid using SQL queries to extract an element from a URL and to check whether a URL matches a pattern. The endpoint code is more readable and more performant. The method is the same regardless of the database.

Copy link
Copy Markdown
Collaborator

@lovasoa lovasoa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Do you have an example of how you would use these functions?

Maybe a regex matching function would be more generally useful, for both matching and extracting components?

@olivierauverlot
Copy link
Copy Markdown
Contributor Author

olivierauverlot commented Apr 4, 2026

A fake example of how to use these functions. The following code is placed in the /api/v1/users/404.sql file. It allows to manage 3 endpoints.

-- Returns user information (lookup based on UID)
-- GET /api/v1/users/42
SELECT 
    'json' AS component, 
    JSON_OBJECT(
        'name', name,
        'surname', surname
    ) AS contents
FROM users
WHERE   sqlppage.is_path_matching(sqlpage.path(),'/api/v1/users/%') 
   AND  id = sqlpage.get_path_segment(sqlpage.path(),4);

-- Returns all accounts of a user (lookup based on UID)
-- GET /api/v1/users/42/accounts
SELECT
    'json' AS component,
    JSON_OBJECT(
        'uid', sqlpage.get_path_segment(sqlpage.path(),4),
        'logins', (
            SELECT JSON_GROUP_ARRAY(
                JSON_OBJECT(
                    'group', group,
                    'homedir', homedir
                )
            ) FROM accounts
            WHERE accounts.uid = sqlpage.get_path_segment(sqlpage.path(),4)
        )
    ) AS contents
WHERE sqlpage.is_path_matching(sqlpage.path(),'/api/v1/users/%/accounts');

-- Returns detailed account information (lookup based on UID and login)
-- GET /api/v1/users/42/accounts/jdoe
SELECT
    'json' AS component,
    JSON_OBJECT(
        'uid', uid,
        'group', group
        'homedir', homedir
    ) AS contents
FROM
    accounts
WHERE  sqlppage.is_path_matching(sqlpage.path(),'/api/v1/users/%/accounts/%') 
  AND  accounts.uid = sqlpage.get_path_segment(sqlpage.path(),4)
  AND  accounts.login = sqlpage.get_path_segment(sqlpage.path(),6);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants