brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: mariadb --init-command runs a statement every time you connect

Mariadb
~/tips/tip-mariadb-client-init-command

mariadb --init-command="SET SESSION sql_mode='STRICT_ALL_TABLES'" mydb

Runs one SQL statement automatically after the client connects, and again after a reconnect.

Some session settings I want every time I connect, and typing them by hand gets old fast. The MariaDB client can send them for me.

mariadb --init-command="SET SESSION sql_mode='STRICT_ALL_TABLES'" mydb

The client connects, runs that statement, and only then gives you the prompt. The docs add that the command is automatically executed again when the client reconnects, which matters because a dropped connection would otherwise lose your session settings without telling you.

It also works for one-off scripts together with -e, which runs a statement and quits:

mariadb --init-command="SET SESSION time_zone='+00:00'" \
  -e "SELECT NOW()" mydb

To make it permanent, put it in an option file as init-command=... in the client section. Since the docs state it is re-executed on reconnect, a statement with side effects, such as an INSERT, is a bad idea there. Keep it to SET statements.

Caveat: it belongs to the client you start. Applications and other tools connect with their own settings and do not pick it up, so it will not fix a session setting for your website. For that, use the server-side or application-side connection settings instead. On MySQL, the client has the same --init-command option.

Further reading: MariaDB command-line client options

More Mariadb tips ALTER TABLE t ADD COLUMN z INT INVISIBLE; CREATE SEQUENCE s START WITH 100 INCREMENT BY 10; CREATE OR REPLACE TABLE scratch ( mariadb-admin -u root -p extended-status --relative --sleep=10 \ ALTER USER 'app'@'localhost' ACCOUNT LOCK; All Mariadb tips (15) All topics

Link