samp.directory
← Scripts e bibliotecas

aujiz11/samp-db-migration

Version-controlled SQL migrations and automated database schema management for SA-MP/open.mp using MySQL.

Biblioteca★ 0atualizado há 6 diasSem licençaPawnsampctl
Abrir no GitHub

Este repositório não tem arquivo de licença. Ele é público para leitura, mas isso sozinho não dá permissão para reutilizar.

Instalar com o sampctl

sampctl package install aujiz11/samp-db-migration

Execute na pasta do seu projeto. O sampctl baixa o pacote e as dependências dele.

Testar no compilador Pawn →

Adiciona os arquivos de include dele, com as bibliotecas de que depende, ao compilador Pawn no seu navegador, prontos para incluir num script.

README.md

Database Migration for SA-MP/open.mp

Version-controlled SQL migrations and automated database schema management for SA-MP/open.mp using MySQL.

Keep database changes in numbered SQL files alongside your Pawn code. At startup, the library applies pending migrations in order and records completed versions in schema_migrations. Subsequent runs skip completed versions, allowing schema changes and initial data to be deployed with your gamemode.

Installation

  1. Download the latest release from GitHub Releases, or copy the complete contents of db_migration.inc into a local file with the same name.

  2. Place db_migration.inc in your include directory.

  3. Install and enable the MySQL plugin, then include a_mysql before this library:

    #include <open.mp> // For SA-MP, use <a_samp> instead.
    #include <a_mysql>
    #include <db_migration>
    
  4. Create scriptfiles/db-migrations/ in your server directory and add your SQL files there.

Usage

Create migration files

Use a four-digit version followed by an underscore, a description, and .sql:

scriptfiles/
└── db-migrations/
    ├── 0001_create_account.sql
    ├── 0002_create_inventory.sql
    ├── 0003_add_account.sql
    ├── 0004_add_inventory_items.sql
    └── 0005_add_account_email.sql

Versions must start at 0001 and remain consecutive. Each version must have exactly one file, duplicate versions and gaps cause initialization to fail. Descriptions may contain ASCII letters, digits, underscores, and hyphens.

For example, 0001_create_account.sql creates a table:

CREATE TABLE account (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Then 0002_add_account_email.sql extends it:

ALTER TABLE account
    ADD COLUMN email VARCHAR(128) NOT NULL DEFAULT '';

These two files form a separate minimal example. The examples directory contains the five-file account and inventory example shown in the directory tree above.

Run migrations at startup

Call DbMigration_Init after connecting to the database and before loading game data or submitting other queries:

#include <open.mp> // For SA-MP, use <a_samp> instead.
#include <a_mysql>
#include <db_migration>

new MySQL:g_Database = MYSQL_INVALID_HANDLE;

main() { }

public OnGameModeInit()
{
    // Create this database first and replace the connection settings.
    g_Database = mysql_connect("127.0.0.1", "samp", "password", "samp_database");
    if (g_Database == MYSQL_INVALID_HANDLE || mysql_errno(g_Database) != 0)
    {
        print("[Database] Connection failed.");
        SendRconCommand("exit");
        return 1;
    }

    new version;
    if (!DbMigration_Init(g_Database, version))
    {
        print("[Database] Migration failed. Check the server and MySQL logs.");
        SendRconCommand("exit");
        return 1;
    }

    printf("[Database] Schema is ready at version %d.", version);
    // Load game data and start normal database queries here.
    return 1;
}

public OnGameModeExit()
{
    if (g_Database != MYSQL_INVALID_HANDLE)
    {
        mysql_close(g_Database);
        g_Database = MYSQL_INVALID_HANDLE;
    }
    return 1;
}

Initialization is synchronous and blocks until it succeeds or fails. Use an idle connection with a selected database, autocommit enabled, and no active MySQL cache. Avoid calling it inside a query callback with an active cache.

Add new versions

After deploying versions 0001 through 0005, add 0006_*.sql for the next change. Deploy the full migration directory and restart the server. The library applies only version 6 to a database already at version 5, a new database runs all six migrations.

Keep previously applied files unchanged and available. The library tracks version numbers without storing file checksums, so editing an applied file does not update existing databases. Rollbacks and down migrations are not provided, use a new migration for subsequent changes.

API

stock bool:DbMigration_Init(MySQL:handle, &version = 0, const verifier[] = "")
ParameterDescription
handleAn open MySQL connection to the database being migrated.
versionOptional output parameter. On success, contains the latest applied version. On failure, it must not be treated as confirmation that the schema is ready.
verifierOptional name of a public function in the same AMX, used to validate the resulting schema.

Returns true when all available migrations have been applied and optional verification succeeds. Returns false on initialization, history, locking, SQL, verification, or lock-release failure.

Optional schema verification

Register a callback with this signature:

forward VerifyDatabase(MySQL:handle, version);

Implement it as public VerifyDatabase(MySQL:handle, version) and pass its name:

new version;
if (!DbMigration_Init(g_Database, version, "VerifyDatabase"))
{
    // Stop initialization and inspect the logs.
}

The callback receives the connection and the version being checked. Return a nonzero value to accept the schema, or 0 to fail verification. It runs after each pending migration, before that version is marked complete. If the database is already up to date, it runs once for the current version.

Make checks appropriate for each version: a column introduced in version 5 should only be required at version 5 or later. Delete any query caches created by the callback before returning.

Examples

See migration_example.pwn and the SQL migrations for a complete example that creates account and inventory tables, inserts an account and items, and adds an email column.

Copy the contents of examples/gamemodes/ and examples/scriptfiles/ into the matching server directories, update the connection settings, compile the gamemode, and enable it in your server configuration. Use a separate empty database for the first run. The expected final schema version is 5, with one sample account and two inventory item types totaling five items.

includemysqlopenmppawnsampsampctl

Esta página é montada com o que o GitHub publica sobre o repositório. O samp.directory não hospeda o código. Avisar de um problema com esta página

aujiz11/samp-db-migration: Biblioteca de SA-MP | samp.directory