Stable content identity: Content ID, slug, revision and DB ID

A Python and PyMySQL experiment with two MySQL 8.4 schemas: one stable content key, different local numbers, and rejection of stale and competing edits.

A permanent seal, a replaceable label and layers of paper suggest content identity, naming and revisions.
A permanent seal, a replaceable label and layers of paper suggest content identity, naming and revisions.

A piece of content can change its title, acquire a translation and move to another database. We still need to answer a basic question: is it the same article or a different one? If the answer depends on a row number or the current spelling of an address, ordinary editing starts to resemble the creation of new content.

In “Article: how an author's journal becomes a product”, I separated the manuscript, preview and public article. Now we will examine identity: what should survive a move, what may change during an edit, and which number belongs only to a particular database. We will check this with an independent Python, PyMySQL and MySQL 8.4/InnoDB example.

Four questions instead of one number

Our teaching model introduces four separate values:

Value Which question does it answer? What happens during an edit?
content_id Which piece of content is this within the agreed catalogue? It remains the same
slug Which readable name is used for addressing? It may change by a separate decision
revision Which revision of the record are we processing? It explicitly increases when an update is accepted
db_id Which row represents the content in this database? It is not transferred as a shared identity

This is the example's contract, not a universal schema for every CMS. In particular, Content ID means a stable content key here. It does not mean a byte address derived from a cryptographic hash, and it does not require a particular UUID format. The synthetic string content-demo-a is sufficient for the experiment.

The number in an editorial plan has a separate purpose as well: it organizes the work. The name of a file directory helps locate the files. Neither should automatically become the primary key of a working database. Even if all the numbers happen to match at the beginning, that coincidence does not establish a relationship between their meanings.

In MySQL, a BIGINT UNSIGNED AUTO_INCREMENT column assigns the local db_id. The InnoDB documentation describes its behaviour; it does not promise gapless numbering. We will deliberately add an extra record to the second independent schema so that the same content receives different local numbers. That difference should be an ordinary condition, not a transfer error.

What the key actually guarantees

A nonempty content_id is passed to both catalogues as an identity that has already been chosen. The example does not calculate it from the title, slug or list position. A real process must separately define who issues keys, the namespace in which they are unique, and how collisions between independent sources are handled.

Matching titles do not justify merging content automatically. Two articles can approach the same topic from different angles, while one article can receive a completely different title after editing. The decision to edit existing content or create new content must be explicit. Accidentally issuing a new key for a routine correction will not restore translation relationships and previous references merely because the text is similar. Reusing an old key for another article will not make technical uniqueness detect the change in semantic identity.

The InnoDB table combines NOT NULL, a unique index and CHECK constraints for a nonempty key and a positive revision. MySQL 8.4 CREATE TABLE describes these constraints. The content_id uses VARCHAR with utf8mb4_0900_bin: case, accents and trailing spaces are significant. Keys are limited to 255 Unicode characters; longer keys are rejected before a transaction begins rather than truncated by the server. Slugs and titles use LONGTEXT. Uniqueness applies within a catalogue; our code must still pass the agreed key between independent schemas.

Uniqueness does not imply immutability either. An operator allowed to execute arbitrary SQL could rewrite the field if other controls permitted it. In this experiment, the update operation never changes the key: it locates the content by that key and works only with the slug, title and revision. The guarantee therefore combines a data constraint with an explicitly chosen contract for operations.

Two temporary catalogues

You need Python 3.12 or newer, PyMySQL[rsa]==1.2.4 and MySQL 8.4. Run every command from the Demo root, with the guarded disposable MySQL lab from the earlier example already configured. The shared tools/mysql_fixture.py reuses that lab's existing schema ownership mechanism; PHP is also needed for that helper mechanism, but the catalogue itself is implemented in Python. Create a private virtual environment and install the dependencies:

python3 --version
python3 -m venv .venv-pymysql
.venv-pymysql/bin/python -m pip install -r tools/requirements-mysql.txt

The complete implementation is in tools/content-identity-lab/identity_lab.py:

from __future__ import annotations

import argparse
from contextlib import contextmanager
import json
from pathlib import Path
import sys
from typing import Iterator

from pymysql.connections import Connection
from pymysql.constants.SERVER_STATUS import SERVER_STATUS_IN_TRANS

# Use the repository's existing schema owner and native connection fixture.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from mysql_fixture import MysqlFixture


CONTENT_ID = "content-demo-a"
MAX_CONTENT_ID_LENGTH = 255
SCHEMA = """
CREATE TABLE IF NOT EXISTS material (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    content_id VARCHAR(255) CHARACTER SET utf8mb4
        COLLATE utf8mb4_0900_bin NOT NULL,
    slug LONGTEXT NOT NULL,
    revision BIGINT NOT NULL,
    title LONGTEXT NOT NULL,
    UNIQUE KEY material_content_id (content_id),
    CONSTRAINT material_content_id_nonempty CHECK (CHAR_LENGTH(content_id) > 0),
    CONSTRAINT material_revision_positive CHECK (revision >= 1)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin
"""


class RevisionConflict(Exception):
    pass


class Catalog:
    def __init__(self, connection: Connection):
        """Use a native runtime DictCursor connection; execute no DDL.

        As in the original context-manager API, exiting closes this connection.
        Operations own their transactions and reject an ambient transaction.
        """
        self.connection = connection

    @staticmethod
    def initialize(migrator: Connection) -> None:
        """Initialize through the fixture's separate migrator before DML."""
        if migrator.server_status & SERVER_STATUS_IN_TRANS:
            raise RuntimeError("Cannot initialize inside an active transaction.")
        with migrator.cursor() as cursor:
            cursor.execute(SCHEMA)

    def __enter__(self) -> Catalog:
        return self

    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.connection.close()

    @staticmethod
    def _validate_content_id(content_id: str) -> None:
        # Empty and NULL inserts still reach the native database constraints.
        # The finite indexed VARCHAR bound is checked before any transaction or
        # mutation, independently of server truncation/error settings.
        if content_id is not None:
            if not isinstance(content_id, str):
                raise TypeError("content_id must be a string or None.")
            if len(content_id) > MAX_CONTENT_ID_LENGTH:
                raise ValueError(
                    f"content_id must contain at most {MAX_CONTENT_ID_LENGTH} characters."
                )

    @contextmanager
    def _transaction(self) -> Iterator[None]:
        if self.connection.server_status & SERVER_STATUS_IN_TRANS:
            raise RuntimeError("Catalog operations require no active transaction.")
        self.connection.begin()
        try:
            yield
            self.connection.commit()
        except BaseException:
            # Only a transaction begun above belongs to this operation. Native
            # duplicate, lock-timeout and deadlock errors are not translated or
            # retried. In particular, a lock timeout needs a full rollback.
            self.connection.rollback()
            raise

    def _read(self, content_id: str) -> dict:
        with self.connection.cursor() as cursor:
            cursor.execute(
                """SELECT id AS db_id, content_id, slug, revision, title
                   FROM material WHERE content_id = %s""",
                (content_id,),
            )
            row = cursor.fetchone()
        if row is None:
            raise KeyError(content_id)
        return dict(row)

    def read(self, content_id: str) -> dict:
        self._validate_content_id(content_id)
        with self._transaction():
            return self._read(content_id)

    def create(self, content_id: str, slug: str, title: str) -> dict:
        self._validate_content_id(content_id)
        with self._transaction():
            with self.connection.cursor() as cursor:
                cursor.execute(
                    """INSERT INTO material (content_id, slug, revision, title)
                       VALUES (%s, %s, 1, %s)""",
                    (content_id, slug, title),
                )
            return self._read(content_id)

    def revise(
        self, content_id: str, expected_revision: int, slug: str, title: str
    ) -> dict:
        self._validate_content_id(content_id)
        with self._transaction():
            with self.connection.cursor() as cursor:
                # InnoDB UPDATE is a locking current read, not a prior snapshot
                # check. After waiting for a writer it rechecks the revision.
                changed = cursor.execute(
                    """UPDATE material
                       SET slug = %s, title = %s, revision = revision + 1
                       WHERE content_id = %s AND revision = %s""",
                    (slug, title, content_id, expected_revision),
                )
                if changed != 1:
                    raise RevisionConflict("Unknown content ID or stale revision.")
            # Read while still owning the write lock, so the returned revision
            # is this operation's result rather than a later writer's result.
            return self._read(content_id)


def run_demo(stale: bool = False) -> dict:
    # Two separately owned schemas give independent AUTO_INCREMENT namespaces.
    # Fixture lifetimes enclose every connection and all business transactions.
    with MysqlFixture("identity_demo_a") as first_fixture, MysqlFixture(
        "identity_demo_b"
    ) as second_fixture:
        for fixture in (first_fixture, second_fixture):
            with fixture.migrator() as migrator:
                Catalog.initialize(migrator)
        with Catalog(first_fixture.runtime()) as first, Catalog(
            second_fixture.runtime()
        ) as second:
            second.create("content-demo-b", "another-note", "Another note")
            before = {
                "first": first.create(CONTENT_ID, "backup-basics", "Backup basics"),
                "second": second.create(CONTENT_ID, "backup-basics", "Backup basics"),
            }
            after = {
                "first": first.revise(CONTENT_ID, 1, "backup-and-restore", "Backup and restore"),
                "second": second.revise(CONTENT_ID, 1, "backup-and-restore", "Backup and restore"),
            }
            if stale:
                first.revise(CONTENT_ID, 1, "outdated-slug", "Outdated edit")
            return {"before": before, "after": after}


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Compare content identity in two fixture-owned MySQL schemas."
    )
    parser.add_argument("--stale", action="store_true", help="Attempt an edit based on an old revision.")
    args = parser.parse_args()
    try:
        result = run_demo(stale=args.stale)
    except RevisionConflict as error:
        print(f"revision conflict: {error}", file=sys.stderr)
        return 2
    print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

PyMySQL passes values separately from SQL through %s parameters; its connection API is described in the PyMySQL documentation. Each catalogue operation begins its own transaction and ends it with commit or rollback. A mutation reads its result before commit while it still holds the lock. If the connection already has an active transaction, the catalogue refuses the operation without committing or rolling back someone else's work. A duplicate key remains native error 1062 rather than a silent replacement; other errors also propagate after rollback of the owned transaction.

MysqlFixture creates two independent MySQL schemas and removes them after their connections close. Before business operations, an explicit Catalog.initialize(migrator) call executes DDL through a separate migrator connection; runtime connections have DML privileges only. This is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database: MySQL DDL can cause an implicit commit, so it is kept outside the business transaction.

One piece of content, different local numbers

Run the demonstration from the Demo root through the guarded MySQL lab:

PYTHONPATH=tools PYTHONDONTWRITEBYTECODE=1 bash fixtures/mysql_labs/run.sh .venv-pymysql/bin/python tools/content-identity-lab/identity_lab.py

The program returns JSON with two snapshots: before and after. The first shows the initial record, and the second shows the explicit update. The observed run has the following mapping:

Catalogue and point in time db_id content_id slug revision
First, before the edit 1 content-demo-a backup-basics 1
Second, before the edit 2 content-demo-a backup-basics 1
First, after the edit 1 content-demo-a backup-and-restore 2
Second, after the edit 2 content-demo-a backup-and-restore 2

An unrelated teaching record was created in the second catalogue first. The target content therefore has a different local number. We do not align the counters or force both databases to issue the same number. Mapping uses the stable key, while the local number remains a property of a particular stored record.

There is no automatic synchronization between the schemas. The code explicitly invokes creation and editing in each catalogue. Remove the second update call and the second copy will remain on the old revision. Shared identity lets us locate the corresponding content; it neither delivers changes itself nor decides which copy should win.

A revision belongs to an explicit change

The revise() method receives the key and expected revision. A single UPDATE changes the slug and title and increments the revision only when both values match. This is an InnoDB locking current read: after waiting for another writer, it checks the condition again rather than relying on an earlier snapshot. Zero changed rows means RevisionConflict. The UPDATE documentation describes the syntax.

This counter is not a date, publication number or indication of the author's approval. Reading a record, making a preview or copying a file does not increase it. Our contract increments it for every accepted update call, even when the new values happen to equal the old ones. Detecting empty changes and retaining the complete revision history are not implemented here.

The table stores only the current record. A larger revision does not mean that the previous text can be recovered: the old values have been replaced. A complete history would require separate revision storage and a rule preventing those revisions from being silently rewritten. That is a different requirement from checking the expected revision during an update. This experiment keeps it separate so that a simple numeric counter is not mistaken for an archive, a backup system or an author acceptance mechanism.

Try submitting an edit based on a revision that is already out of date:

PYTHONPATH=tools PYTHONDONTWRITEBYTECODE=1 bash fixtures/mysql_labs/run.sh .venv-pymysql/bin/python tools/content-identity-lab/identity_lab.py --stale

In this mode, the program first performs its ordinary update and then refers to the initial revision again. The process exits with code 2, reports a conflict on stderr and prints no successful JSON on stdout. The ordinary run exits with code 0. This is the contract chosen for our command.

The same exception covers an unknown key and a mismatched revision. A real product interface might need different explanations, but both cases reject the same dangerous assumption: silently creating or overwriting other content is not acceptable. The test below checks that a rejected edit leaves the current record unchanged.

Check the meaning, not only the printed JSON

The complete test suite is in tools/content-identity-lab/test_identity_lab.py:

from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
from threading import Barrier
import unittest

import pymysql
from pymysql.constants.SERVER_STATUS import SERVER_STATUS_IN_TRANS

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from mysql_fixture import MysqlFixture

from identity_lab import CONTENT_ID, MAX_CONTENT_ID_LENGTH, Catalog, RevisionConflict


class IdentityTest(unittest.TestCase):
    def setUp(self):
        self.first_fixture = MysqlFixture("identity_test_a")
        self.addCleanup(self.first_fixture.close)
        self.second_fixture = MysqlFixture("identity_test_b")
        self.addCleanup(self.second_fixture.close)
        for fixture in (self.first_fixture, self.second_fixture):
            with fixture.migrator() as migrator:
                Catalog.initialize(migrator)

    def testDifferentLocalIdsStillIdentifyTheSameContent(self):
        with Catalog(self.first_fixture.runtime()) as first, Catalog(
            self.second_fixture.runtime()
        ) as second:
            second.create("content-demo-b", "another-note", "Another note")
            left = first.create(CONTENT_ID, "backup-basics", "Backup basics")
            right = second.create(CONTENT_ID, "backup-basics", "Backup basics")
            self.assertNotEqual(left["db_id"], right["db_id"])
            self.assertEqual(left["content_id"], right["content_id"])

    def testSlugAndTitleCanChangeWithoutChangingIdentity(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            before = catalog.create(CONTENT_ID, "backup-basics", "Backup basics")
            after = catalog.revise(CONTENT_ID, 1, "backup-and-restore", "Backup and restore")
            self.assertEqual(before["db_id"], after["db_id"])
            self.assertEqual(before["content_id"], after["content_id"])
            self.assertEqual(2, after["revision"])
            self.assertEqual("backup-and-restore", after["slug"])
            self.assertEqual("Backup and restore", after["title"])

    def testDuplicateContentIdDoesNotReplaceTheExistingRow(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            before = catalog.create(CONTENT_ID, "backup-basics", "Backup basics")
            with self.assertRaises(pymysql.IntegrityError) as caught:
                catalog.create(CONTENT_ID, "different-slug", "Different note")
            self.assertEqual(1062, caught.exception.args[0])
            self.assertFalse(catalog.connection.server_status & SERVER_STATUS_IN_TRANS)
            self.assertEqual(before, catalog.read(CONTENT_ID))

    def testStaleRevisionCannotOverwriteTheCurrentRecord(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            catalog.create(CONTENT_ID, "backup-basics", "Backup basics")
            current = catalog.revise(CONTENT_ID, 1, "backup-and-restore", "Backup and restore")
            with self.assertRaises(RevisionConflict):
                catalog.revise(CONTENT_ID, 1, "outdated-slug", "Outdated edit")
            self.assertEqual(current, catalog.read(CONTENT_ID))

    def testUnknownIdentityCannotCreateARevision(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            with self.assertRaises(RevisionConflict):
                catalog.revise("unknown-content", 1, "new-slug", "New title")
            with self.assertRaises(KeyError):
                catalog.read("unknown-content")

    def testASeparateConnectionReadsTheCommittedRevision(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            catalog.create(CONTENT_ID, "backup-basics", "Backup basics")
            current = catalog.revise(CONTENT_ID, 1, "backup-and-restore", "Backup and restore")
        # This is a new TCP connection to the same owned schema: evidence of
        # committed persistence, not a filesystem or crash-durability test.
        with Catalog(self.first_fixture.runtime()) as reopened:
            self.assertEqual(current, reopened.read(CONTENT_ID))

    def testSqlLikeTitleIsStoredAsData(self):
        title = "A title'); DROP TABLE material; --"
        with Catalog(self.first_fixture.runtime()) as catalog:
            catalog.create(CONTENT_ID, "literal-title", title)
            self.assertEqual(title, catalog.read(CONTENT_ID)["title"])

    def testEmptyAndNullContentIdsAreRejected(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            for value, error_code in (("", 3819), (None, 1048)):
                with self.subTest(value=value):
                    # MySQL CHECK violations (3819) are native OperationalError;
                    # NULL violations (1048) are native IntegrityError.
                    expected_error = (
                        pymysql.OperationalError if value == "" else pymysql.IntegrityError
                    )
                    with self.assertRaises(expected_error) as caught:
                        catalog.create(value, "backup-basics", "Backup basics")
                    self.assertEqual(error_code, caught.exception.args[0])
                    self.assertFalse(
                        catalog.connection.server_status & SERVER_STATUS_IN_TRANS
                    )
                    with self.assertRaises(KeyError):
                        catalog.read(value)

    def testContentIdBoundIsCheckedBeforeMutation(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            boundary = "界" * MAX_CONTENT_ID_LENGTH
            before = catalog.create(boundary, "boundary", "Boundary")
            oversized = boundary + "界"
            with self.assertRaises(ValueError):
                catalog.create(oversized, "truncated", "Must not replace")
            with self.assertRaises(ValueError):
                catalog.revise(oversized, 1, "truncated", "Must not revise")
            with self.assertRaises(ValueError):
                catalog.read(oversized)
            self.assertEqual(before, catalog.read(boundary))
            self.assertFalse(catalog.connection.server_status & SERVER_STATUS_IN_TRANS)
            with catalog.connection.cursor() as cursor:
                cursor.execute("SELECT COUNT(*) AS total FROM material")
                self.assertEqual(1, cursor.fetchone()["total"])

    def testContentIdentityIsCaseAndTrailingSpaceSensitive(self):
        identities = ("Content-A", "content-a", "content-a ", "café", "cafe")
        with Catalog(self.first_fixture.runtime()) as catalog:
            rows = [catalog.create(value, "slug", "Title") for value in identities]
            self.assertEqual(len(identities), len({row["db_id"] for row in rows}))
            for value, row in zip(identities, rows):
                self.assertEqual(row, catalog.read(value))

    def testAmbientTransactionIsNotCommittedOrRolledBack(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            catalog.connection.begin()
            try:
                with catalog.connection.cursor() as cursor:
                    cursor.execute(
                        """INSERT INTO material (content_id, slug, revision, title)
                           VALUES (%s, %s, 1, %s)""",
                        (CONTENT_ID, "pending", "Uncommitted"),
                    )
                operations = (
                    lambda: catalog.read(CONTENT_ID),
                    lambda: catalog.create("another", "slug", "Title"),
                    lambda: catalog.revise(CONTENT_ID, 1, "changed", "Changed"),
                    lambda: Catalog.initialize(catalog.connection),
                )
                for operation in operations:
                    with self.assertRaises(RuntimeError):
                        operation()
                    self.assertTrue(
                        catalog.connection.server_status & SERVER_STATUS_IN_TRANS
                    )
                with catalog.connection.cursor() as cursor:
                    cursor.execute(
                        "SELECT title FROM material WHERE content_id = %s", (CONTENT_ID,)
                    )
                    self.assertEqual("Uncommitted", cursor.fetchone()["title"])
                with Catalog(self.first_fixture.runtime()) as observer:
                    with self.assertRaises(KeyError):
                        observer.read(CONTENT_ID)
            finally:
                # The test, not Catalog, owns this transaction.
                catalog.connection.rollback()
            with self.assertRaises(KeyError):
                catalog.read(CONTENT_ID)

    def testConcurrentRevisionsHaveOneWinner(self):
        with Catalog(self.first_fixture.runtime()) as catalog:
            catalog.create(CONTENT_ID, "original", "Original")
        connections = [self.first_fixture.runtime(), self.first_fixture.runtime()]
        barrier = Barrier(2)

        def revise(connection, label):
            with Catalog(connection) as catalog:
                barrier.wait(timeout=30)
                try:
                    return catalog.revise(CONTENT_ID, 1, label, label)
                except RevisionConflict:
                    return None

        # Connections are independent; the parent fixture remains alive until
        # both workers exit. Unexpected native errors propagate via result().
        with ThreadPoolExecutor(max_workers=2) as executor:
            futures = [
                executor.submit(revise, connection, label)
                for connection, label in zip(connections, ("left", "right"))
            ]
            results = [future.result() for future in futures]
        winners = [row for row in results if row is not None]
        self.assertEqual(1, len(winners))
        self.assertEqual(2, winners[0]["revision"])
        with Catalog(self.first_fixture.runtime()) as observer:
            self.assertEqual(winners[0], observer.read(CONTENT_ID))


if __name__ == "__main__":
    unittest.main()

The command uses the standard unittest framework:

PYTHONPATH=tools PYTHONDONTWRITEBYTECODE=1 bash fixtures/mysql_labs/run.sh .venv-pymysql/bin/python -m unittest discover -s tools/content-identity-lab -v

The 12-test suite passed against MySQL 8.4. It covers different local numbers, changing a slug without changing identity, a native duplicate-key error, a stale edit, unknown content, reading a committed revision through another connection, a literal SQL-like title, and empty and NULL keys. It additionally checks the Unicode key length bound before mutation, case-sensitive and trailing-space-sensitive identity, preservation of an ambient transaction, and exactly one winner when two concurrent edits target the same revision. These are specific properties of the example, not an overall application security guarantee.

A separate native connection reads a committed record from the same schema, not a Python dictionary left in memory. The concurrency test uses two independent connections: one edit succeeds and the other receives a conflict. This is a narrow optimistic-revision scenario, not a measurement of load, network retries or reconciliation between independent sources. The checks do not establish persistence after an operating-system or disk failure either.

Add languages without losing the content

For a multilingual blog, first define what shared identity means. One possible contract gives the content a common key and identifies each language version by the pair content_id and locale. Ukrainian, Russian and English pages can then have different titles and slugs while representing the same piece of content.

That does not establish semantic equivalence. If the original moves to a new revision, the existence of an English row with the same key does not confirm an updated translation. A separate source_revision can record which source revision the translation represents. The translation's own correction history may have another counter.

Our MySQL example stores only one language form of the content and does not implement those tables. It provides a basis for designing them: do not infer language relationships from incidental DB IDs or identical addresses. Author acceptance also remains a separate action. A higher revision means that a record changed under the contract, not that publication is authorized.

A slug may change; an old link needs a decision

An immutable key does not remove responsibility for public addresses. Readers may still have old links after a slug changes. W3C's discussion of stable URIs explains the practical value of lasting addresses. A real website must decide how the old address continues to lead to the same content.

The lab has no router, redirects or slug uniqueness checks within a language and section. We change a field in synthetic databases, not a URL on the working website. During a future import, the stable key should locate the target content, the revision should check the basis of an edit, and the local DB ID should connect internal records. Repeated imports, deletion and address migration need additional rules.

For example, a related record in the destination database must refer to that database's local content row. First locate the mapping by the stable key, obtain the local number, and only then create the internal relationship. Copying a number from the first database without that mapping can point to entirely different content in the second. Our unrelated record makes precisely this risk visible: the required article already has another number there. The example does not include a finished importer handling those relationships.

Separating these values prevents a title correction from creating a new entity because of a misleading identifier. A translation can be linked to its content and its particular source, while two databases can retain different local numbers without losing the mapping. Establish that boundary before the catalogue accumulates articles, translations and a history of changes.

File tools/mysql_fixture.py:

"""Native Python connections to schemas owned exclusively by PHP MysqlLab.

Use inside fixtures/mysql_labs/run.sh. Initialize schema explicitly through
migrator(); pass runtime() connections to application code. Keep the fixture in
the parent during worker restarts. Send runtime_settings() only through private
pipes or a private child environment; never print settings.
"""

from __future__ import annotations

import json
from pathlib import Path
import re
import subprocess
from typing import Any

import pymysql
from pymysql.connections import Connection
from pymysql.cursors import DictCursor


_INIT_COMMAND = "SET NAMES utf8mb4 COLLATE utf8mb4_0900_bin"
_OWNER = Path(__file__).resolve().parent / "mysql-labs" / "fixture-owner.php"
_WIRE_KEYS = {"host", "port", "database", "user", "password"}


class MysqlFixture:
    """Own a PHP fixture process, not SQL schema/account lifecycle logic."""

    def __init__(self, purpose: str):
        if not isinstance(purpose, str) or re.fullmatch(r"[a-z][a-z0-9_]{0,19}", purpose) is None:
            raise ValueError("Use a lowercase fixture purpose of 1–20 safe characters.")
        self._owner: subprocess.Popen | None = None
        self._connections: list[Connection] = []
        self._settings: dict[str, dict[str, Any]] = {}
        self._closed = False
        self._close_failed = False
        try:
            self._owner = subprocess.Popen(
                ["php", str(_OWNER), purpose],
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
                shell=False,
            )
            assert self._owner.stdout is not None
            line = self._owner.stdout.readline(16385)
            try:
                if not line.endswith(b"\n") or len(line) > 16384:
                    raise ValueError
                payload = json.loads(line.decode("utf-8"))
                self._settings = self._validate(payload, purpose)
            except (ValueError, TypeError, KeyError, UnicodeError):
                raise RuntimeError("PHP fixture owner returned invalid connection metadata.") from None
            if self._owner.poll() is not None:
                raise RuntimeError("PHP fixture owner exited before ownership handoff.")
        except BaseException:
            self.close()
            raise

    @staticmethod
    def _validate(payload: Any, purpose: str) -> dict[str, dict[str, Any]]:
        if not isinstance(payload, dict) or set(payload) != {"runtime", "migrator"}:
            raise ValueError
        result = {}
        for role, prefix in (("runtime", "adlr_"), ("migrator", "adlm_")):
            settings = payload[role]
            if not isinstance(settings, dict) or set(settings) != _WIRE_KEYS:
                raise ValueError
            if settings["host"] != "127.0.0.1":
                raise ValueError
            if type(settings["port"]) is not int or not 1024 <= settings["port"] <= 65535:
                raise ValueError
            if not isinstance(settings["database"], str) or re.fullmatch(
                r"article_demo_lab_" + re.escape(purpose) + r"_[0-9a-f]{16}",
                settings["database"],
            ) is None:
                raise ValueError
            if not isinstance(settings["user"], str) or re.fullmatch(
                prefix + r"[0-9a-f]{16}", settings["user"]
            ) is None:
                raise ValueError
            if not isinstance(settings["password"], str) or re.fullmatch(
                r"[0-9a-f]{64}", settings["password"]
            ) is None:
                raise ValueError
            result[role] = dict(
                settings,
                charset="utf8mb4",
                autocommit=True,
                init_command=_INIT_COMMAND,
            )
        if any(result["runtime"][key] != result["migrator"][key]
               for key in ("host", "port", "database")):
            raise ValueError
        return result

    def _require_open(self) -> None:
        if self._closed:
            raise RuntimeError("MySQL fixture is closed.")

    def runtime_settings(self) -> dict[str, Any]:
        """Return a private, JSON-safe copy of native PyMySQL keyword settings."""
        self._require_open()
        return dict(self._settings["runtime"])

    def migrator_settings(self) -> dict[str, Any]:
        """Return private migrator settings, never root credentials."""
        self._require_open()
        return dict(self._settings["migrator"])

    def _connect(self, role: str) -> Connection:
        self._require_open()
        connection = pymysql.connect(**self._settings[role], cursorclass=DictCursor)
        self._connections.append(connection)
        return connection

    def runtime(self) -> Connection:
        return self._connect("runtime")

    def migrator(self) -> Connection:
        return self._connect("migrator")

    def close(self) -> None:
        """Close Python connections before signalling EOF to the PHP owner."""
        if self._closed:
            if self._close_failed:
                raise RuntimeError("MySQL fixture cleanup failed.")
            return
        self._closed = True
        failed = False
        for connection in self._connections:
            try:
                if connection.open:
                    connection.close()
            except Exception:
                failed = True
        self._connections.clear()
        self._settings.clear()
        owner = self._owner
        if owner is not None:
            # Closing stdout also prevents a malformed owner response from
            # blocking its producer while we wait for cleanup after EOF.
            if owner.stdout is not None:
                try:
                    owner.stdout.close()
                except OSError:
                    failed = True
            if owner.stdin is not None:
                try:
                    owner.stdin.close()
                except BrokenPipeError:
                    pass
                except OSError:
                    failed = True
            if owner.wait() != 0:
                failed = True
        self._close_failed = failed
        if failed:
            raise RuntimeError("MySQL fixture cleanup failed.")

    def __enter__(self) -> MysqlFixture:
        self._require_open()
        return self

    def __exit__(self, exc_type, exc_value, traceback) -> None:
        self.close()

File tools/mysql-labs/fixture-owner.php:

<?php

declare(strict_types=1);

use App\Infrastructure\MysqlLab;

// Private pipe protocol only. Never include exception messages or credentials
// in diagnostics. MysqlLab remains the sole schema and account owner.
$lab = null;
$status = 0;

try {
    require dirname(__DIR__, 2).'/vendor/autoload.php';

    if ($argc !== 2 || preg_match('/\A[a-z][a-z0-9_]{0,19}\z/D', $argv[1]) !== 1) {
        throw new InvalidArgumentException('Invalid fixture purpose.');
    }
    $lab = MysqlLab::create($argv[1]);

    // MysqlLab has already validated the selected host, port, and server UUID.
    $host = getenv('DEMO_MYSQL_LAB_HOST');
    $port = getenv('DEMO_MYSQL_LAB_PORT');
    if ($host !== '127.0.0.1' || !is_string($port)
        || preg_match('/\A[1-9][0-9]{3,4}\z/D', $port) !== 1
        || (int) $port < 1024 || (int) $port > 65535) {
        throw new RuntimeException('Invalid fixture endpoint.');
    }

    $pdo = $lab->runtime();
    $database = $pdo->query('SELECT DATABASE()')->fetchColumn();
    $pdo = null;
    if (!is_string($database) || $database === '') {
        throw new RuntimeException('Missing fixture database.');
    }

    $common = ['host' => $host, 'port' => (int) $port, 'database' => $database];
    $line = json_encode([
        'runtime' => $common + [
            'user' => $lab->runtimeUser(),
            'password' => $lab->runtimePassword(),
        ],
        'migrator' => $common + [
            'user' => $lab->migratorUser(),
            'password' => $lab->migratorPassword(),
        ],
    ], JSON_THROW_ON_ERROR)."\n";
    if (fwrite(STDOUT, $line) !== strlen($line) || !fflush(STDOUT)) {
        throw new RuntimeException('Fixture handoff failed.');
    }
    unset($line, $common);

    // EOF is the normal Python close protocol; an explicit close is also valid.
    while (($command = fgets(STDIN)) !== false) {
        if (trim($command) === 'close') {
            break;
        }
    }
} catch (Throwable) {
    fwrite(STDERR, "MySQL fixture owner failed.\n");
    $status = 1;
} finally {
    if ($lab !== null) {
        try {
            $lab->close();
        } catch (Throwable) {
            fwrite(STDERR, "MySQL fixture owner cleanup failed.\n");
            $status = 1;
        }
    }
}

exit($status);

File tools/requirements-mysql.txt:

PyMySQL[rsa]==1.2.4
python3 -m venv .venv-mysql
.venv-mysql/bin/pip install -r tools/requirements-mysql.txt
PYTHONPATH=tools bash fixtures/mysql_labs/run.sh .venv-mysql/bin/python -B -m unittest discover -s tools/content-identity-lab -v
  1. Editorial Three languages, one article: how to spot an outdated translation
  2. Symfony Core Reimporting content: where updates are allowed and where to stop
  3. Symfony Core Editing a published article: how to avoid losing another edit
  4. Symfony Core The product owns the route: changing URLs without rewriting the capability

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article