Bancos de dados2 minutos de leitura

Migrate Discord bot settings from SQLite to PostgreSQL

Copy per-server settings into an attached PostgreSQL database and verify the same Discord setting after a restart with a runnable Node.js example.

Prepare a backup and a test server

O Discord settings example uses Node.js 24 and stores one welcome message per server. It expects a SQLite guild_settings table with guild_id e welcome_message columns. Adapt the source query and destination schema for a different bot. Practice with a copy of the data first.

For a fresh test, run the example as a Discord Node.js bot. Set BOT_TOKEN e DISCORD_TEST_GUILD_ID for your test application and server. Run /welcome-setting message:Welcome aboard! to save a value, then invoke /welcome-setting to read it. The example stores it in guild-settings.sqlite. Stop writes and take a backup, including committed changes in SQLite’s write-ahead log.

Attach PostgreSQL to the bot deployment

Start a managed PostgreSQL deployment in the same account. In the bot’s Overview choose Connect a database. Select PostgreSQL and use the alias postgres. The example reads the BH_DB_POSTGRES_* variables from the runtime and verifies the database’s TLS certificate. Restart loads the attachment variables. See the attachment guide for the setup.

Import the saved settings once

Keep the bot stopped during the copy. Upload the example and the backed-up database. Set the deployment’s startup file to migrate.mjs. If the snapshot uses a different filename, set SQLITE_SETTINGS_FILE to its path. Start the deployment and check Console for the numbers of copied and already present rows. Once the import exits, reset the startup file to index.js before starting the bot again.

The import reads SQLite without changing it. PostgreSQL commits the copy in one transaction. A second run skips equal rows. If a destination value differs, the copy stops and rolls back. Keep the snapshot until the production bot has been verified.

Switch storage and verify a restart

  1. Definido SETTINGS_STORE=postgres in Variables and start the bot with index.js.
  2. Invoke /welcome-setting in the same server. Check that the imported value matches the old reply.
  3. Save a different test value. Restart the deployment and read the setting again. Seeing the new value after restart verifies a read and a write against the attached database.

In our Node.js 24 test against PostgreSQL 16 with client-certificate TLS, the example copied two rows. A second run skipped both. A fresh process read the changed message after the previous process exited, and a conflicting import left the destination unchanged.

If the test fails before anyone writes new data, you can stop the app and switch back to SETTINGS_STORE=sqlite with the original file. If people have written new settings in PostgreSQL, reconcile those changes before switching back.

See SQLite and PostgreSQL tradeoffs for bots ou o live Bothosting attachment demo.