NAME

Web::Session::MariaDBJSON - Add index and search methods to Apache::Session::MySQL for MariaDB, using a JSON field

SYNOPSIS

Create table. Example for Lemonldap::NG with generated columns and indexes:

CREATE TABLE sessions (
    id varchar(64) not null primary key,
    a_session json,
    _whatToTrace varchar(255) COLLATE utf8mb4_bin
        AS (JSON_VALUE(a_session, '$._whatToTrace')) VIRTUAL,
    _session_kind varchar(32) COLLATE utf8mb4_bin
        AS (JSON_VALUE(a_session, '$._session_kind')) VIRTUAL,
    _utime bigint unsigned
        AS (cast(JSON_VALUE(a_session, '$._utime') as unsigned)) VIRTUAL,
    _lastSeen bigint unsigned
        AS (cast(JSON_VALUE(a_session, '$._lastSeen') as unsigned)) VIRTUAL,
    _oidcRtUpdate bigint unsigned
        AS (cast(JSON_VALUE(a_session, '$._oidcRtUpdate') as unsigned))
        VIRTUAL,
    ipAddr varchar(64) COLLATE utf8mb4_bin
        AS (JSON_VALUE(a_session, '$.ipAddr')) VIRTUAL,
    KEY _whatToTrace (_whatToTrace),
    KEY _session_kind (_session_kind),
    KEY _utime (_utime),
    KEY _lastSeen (_lastSeen),
    KEY _oidcRtUpdate (_oidcRtUpdate),
    KEY ipAddr (ipAddr)
) ENGINE=InnoDB;

In MariaDB, json is an alias for longtext COLLATE utf8mb4_bin CHECK (json_valid(a_session)).

Use it with Perl:

use Web::Session::MariaDBJSON;

my $args = {
     DataSource => 'dbi:MariaDB:database=sessions', # or dbi:mysql:...
     UserName   => $db_user,
     Password   => $db_pass,

     # Fields that have a generated column
     Index      => '_whatToTrace _session_kind _utime _lastSeen'
                 . ' _oidcRtUpdate ipAddr',
};

The DSN selects the driver: dbi:MariaDB:... requires DBD::MariaDB and dbi:mysql:... requires DBD::mysql, otherwise DBI dies with install_driver(...) failed. DBD::MariaDB always exchanges UTF-8 (utf8mb4). With DBD::mysql, this module connects with mysql_enable_utf8mb4, which selects utf8mb4 for the connection (characters outside the BMP, such as emoji, are supported). When you give your own Handle to the store, it is used as is: connect it with mysql_enable_utf8mb4 (or SET NAMES utf8mb4).

Use it like Web::Session::MySQLJSON. Web::Session::MariaDB is an alias of this module.

Generated columns

Any field can be searched, but only the fields listed in Index can use an index. Each of them must have a generated column (VIRTUAL or PERSISTENT) with an index. Rules:

  • The column name must be exactly the field name: this module queries the column itself because MariaDB doesn't reliably use the index of a generated column when a query contains its expression (10.11 never does, 11.8 never does for LIKE).

  • Columns must be generated from a_session: this module writes only id and a_session.

  • A column listed in Index that exists but is not generated from a_session - for example one left over from a migration from the former column-based Web::Session::MySQL, which wrote real columns - stays NULL. This module checks Index once per database handle, warns about such fields (and about missing columns) and reads them from the JSON document like fields that are not listed in Index: results are the same, only slower.

  • VIRTUAL columns are computed when read and use no space in the table (their index does). PERSISTENT columns are stored: they use more space but are not recomputed.

  • Text columns must use the utf8mb4_bin collation, as in the example above: otherwise indexed fields follow the table collation (by default, case-insensitive, and also accent-insensitive with MariaDB 11) whereas other fields are compared exactly.

  • _utime, _lastSeen, _oidcRtUpdate (and other indexed fields used by deleteIfLowerThan(), searchLt() or searchGt()) must be integer columns: these methods compare the column directly (they cast other fields to unsigned).

  • With strict SQL mode, a value that doesn't fit into its column (too long string, non-integer _utime, _lastSeen or _oidcRtUpdate) makes the session storage fail: size varchar columns generously; Lemonldap::NG always writes integer _utime, _lastSeen and _oidcRtUpdate.

_lastSeen is needed when Lemonldap::NG "timeoutActivity" is used: sessions purge then deletes sessions whose _utime or _lastSeen is too old, and an OR with a non indexed side forces a full table scan (with both columns, MariaDB uses an index_merge).

_oidcRtUpdate is useful when OpenID Connect relying parties have a refresh token activity timeout: sessions purge then calls searchLt() on _oidcRtUpdate.

Fields that are not listed in Index are read with JSON_VALUE(a_session, '$.field'). JSON_VALUE returns NULL for missing fields, JSON null, arrays and objects: such values can't be searched and get_key_from_all_sessions() returns undef for them when called with field names.

Searches are exact (case- and accent-sensitive) for all fields, as long as generated text columns use the utf8mb4_bin collation (see above). Field names and searched values are strings: a non flagged string containing bytes 0x80 or more is first tried as UTF-8 and read as Latin-1 if it is not valid UTF-8, so both encodings find non-ASCII values.

To add a generated column to an existing table:

ALTER TABLE sessions
    ADD COLUMN ipAddr varchar(64) COLLATE utf8mb4_bin
        AS (JSON_VALUE(a_session, '$.ipAddr')) VIRTUAL,
    ADD KEY ipAddr (ipAddr);

DESCRIPTION

Web::Session provides some class methods to manipulate all sessions and add the capability to index some fields to make research faster.

Web::Session::MariaDBJSON implements it for MariaDB databases, storing sessions in JSON and using generated columns for indexed fields. It works with DBD::MariaDB (dbi:MariaDB:...) and DBD::mysql (dbi:mysql:...). It has been tested with MariaDB 10.11 and 11.8.

For MySQL, use Web::Session::MySQLJSON.

searchLt() and searchGt()

# Sessions whose _utime is lower than $time
my $hash = Web::Session::MariaDBJSON->searchLt( $args,
    '_utime', $time, 'uid' );

searchLt() and searchGt() take the same arguments and return the same data as searchOn(): sessions whose field is lower (or greater) than the given value, which is excluded. The value must be a number (12, -12 or 12.5): otherwise nothing is returned and an error is printed on STDERR. Spaces around the value are ignored.

Fields are compared in SQL as deleteIfLowerThan() does: fields listed in Index on their (integer) generated column, which index is used (only if the Index check accepted this column, see above), other fields with cast(JSON_VALUE(a_session, '$.field') as unsigned). Values are compared as unsigned integers: a non-numeric value is 0.

Sessions without the field are never returned. This differs from the Perl fallback of Lemonldap::NG, where a missing field is compared as 0: searchLt() would then return nearly all sessions. Lemonldap::NG doesn't need them: its sessions purge ignores sessions without _oidcRtUpdate. A field stored as JSON null is skipped too (JSON_VALUE returns NULL).

For fields not listed in Index, a negative value becomes a huge number because of the unsigned cast (-5 is found by searchGt( $args, $field, 50 )). Lemonldap::NG timestamps are positive integers.

SEE ALSO

Apache::Session, Web::Session::MySQLJSON, http://lemonldap-ng.org

COPYRIGHT AND LICENSE

2009-2026 by Xavier Guimard
2013-2025 by Clément Oudot
2019-2025 by Maxime Besson
2013-2025 by Worteks
2023-2026 by Linagora

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.1 or, at your option, any later version of Perl 5 you may have available.