"""Start and remove a disposable local MySQL server, then run the DB-API lesson."""
import argparse
import importlib.util
import json
import os
import secrets
import socket
import subprocess
import tempfile
import time
from contextlib import closing, contextmanager
from decimal import Decimal
from pathlib import Path
import pymysql
from pymysql.constants import SERVER_STATUS
SCHEMA = "mbsky_legacy_lab"
TABLE = "shift_samples"
ACCOUNT = "mbsky_legacy_worker"
STOP_ACCOUNT = "mbsky_legacy_shutdown"
STATUS = SERVER_STATUS.SERVER_STATUS_IN_TRANS
PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, CREATE ROUTINE, EXECUTE"
MAKE_TABLE = """CREATE TABLE shift_samples (
id INT PRIMARY KEY,
label VARCHAR(48) NOT NULL,
hours INT NOT NULL,
team CHAR(1) NOT NULL,
fee DECIMAL(7,2) NOT NULL
) ENGINE=InnoDB"""
INSERT = "INSERT INTO shift_samples (id,label,hours,team,fee) VALUES (%s,%s,%s,%s,%s)"
IDS = "SELECT id FROM shift_samples ORDER BY id"
def socket_port():
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
return reservation.getsockname()[1]
@contextmanager
def new_database(server, scratch):
server = server.resolve(strict=True)
if server.name.lower() != "mysqld.exe" or server.parent.name.lower() != "bin":
raise ValueError("Select the bin/mysqld.exe of a local MySQL 8.4 distribution.")
data = scratch / "data"
init_sql = scratch / "bootstrap.sql"
secret = secrets.token_hex(24)
admin_secret = secrets.token_hex(24)
shutdown_secret = secrets.token_hex(24)
init_sql.write_text(
f"ALTER USER 'root'@'localhost' IDENTIFIED BY '{admin_secret}';\n"
f"CREATE DATABASE {SCHEMA} CHARACTER SET utf8mb4;\n"
f"CREATE USER '{ACCOUNT}'@'127.0.0.1' IDENTIFIED BY '{secret}' REQUIRE SSL;\n"
f"GRANT {PRIVILEGES} ON {SCHEMA}.* TO '{ACCOUNT}'@'127.0.0.1';\n"
f"CREATE USER '{STOP_ACCOUNT}'@'127.0.0.1' IDENTIFIED BY '{shutdown_secret}' REQUIRE SSL;\n"
f"GRANT SHUTDOWN ON *.* TO '{STOP_ACCOUNT}'@'127.0.0.1';\n",
encoding="ascii",
)
env = {key: value for key, value in os.environ.items()
if key.upper() in {"SYSTEMROOT", "WINDIR", "TEMP", "TMP"}}
env.update(TEMP=str(scratch), TMP=str(scratch))
common = [str(server), "--no-defaults", "--basedir=" + str(server.parent.parent),
"--datadir=" + str(data)]
with (scratch / "init-output.log").open("wb") as init_output:
result = subprocess.run(
[*common, "--initialize-insecure", "--log-error=" + str(scratch / "init.log")],
cwd=scratch, env=env, stdout=init_output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW, timeout=90,
)
if result.returncode:
raise RuntimeError(f"Disposable MySQL initialization exited with code {result.returncode}.")
port = socket_port()
with (scratch / "server-output.log").open("wb") as output:
process = subprocess.Popen(
[*common, "--no-monitor", "--port=" + str(port), "--bind-address=127.0.0.1", "--mysqlx=OFF",
"--skip-log-bin", "--log-error=" + str(scratch / "server.log"),
"--init-file=" + str(init_sql)],
cwd=scratch, env=env, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW,
)
attested = False
cleanup = {"graceful_shutdown": False}
try:
config = dict(host="127.0.0.1", port=port, user=ACCOUNT, password=secret,
database=SCHEMA, charset="utf8mb4", autocommit=False,
ssl_ca=str(data / "ca.pem"), ssl_verify_cert=True,
connect_timeout=2, read_timeout=4, write_timeout=4)
for _ in range(90):
if process.poll() is not None:
raise RuntimeError(f"Disposable MySQL stopped with code {process.returncode}.")
try:
if not (data / "ca.pem").is_file():
time.sleep(.2)
continue
with closing(pymysql.connect(**config)) as db, db.cursor() as cursor:
cursor.execute("SELECT @@datadir")
location, = cursor.fetchone()
if Path(location).resolve() != data.resolve():
raise RuntimeError("Server identity differs from the owned data directory.")
attested = True
break
except (OSError, pymysql.OperationalError) as exc:
if isinstance(exc, pymysql.OperationalError) and exc.args[0] in (1044, 1045):
raise RuntimeError("Disposable account could not authenticate.") from None
time.sleep(.2)
else:
raise RuntimeError("Disposable MySQL did not become available.")
init_sql.unlink()
yield config, cleanup
finally:
if attested and process.poll() is None:
try:
shutdown_config = config | {"user": STOP_ACCOUNT, "password": shutdown_secret,
"database": None, "autocommit": True}
with closing(pymysql.connect(**shutdown_config)) as control, control.cursor() as cursor:
cursor.execute("SELECT @@datadir")
location, = cursor.fetchone()
if Path(location).resolve() != data.resolve():
raise RuntimeError("Shutdown target differs from the owned directory.")
cursor.execute("SHUTDOWN")
cleanup["graceful_shutdown"] = process.wait(timeout=12) == 0
except (pymysql.Error, OSError, subprocess.TimeoutExpired):
pass
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=12)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
def expected_error(action, kind, code):
try:
action()
except kind as error:
assert type(error) is kind and error.args[0] == code, (type(error).__name__, error.args[0])
return [type(error).__name__, error.args[0]]
raise AssertionError(f"Expected {kind.__name__}")
def run_lab(config):
observations = {}
with closing(pymysql.connect(**config)) as db, closing(
pymysql.connect(**(config | {"autocommit": True}))) as observer:
with db.cursor() as cur, db.cursor() as second, observer.cursor() as other:
def query(sql, args=None, *, handle=cur):
handle.execute(sql, args)
return handle.fetchall()
no_cursor_transaction = not (db.server_status & STATUS)
cur.execute("SELECT VERSION(), DATABASE()")
version, database = cur.fetchone()
cipher, = query("SHOW SESSION STATUS LIKE 'Ssl_cipher'")
observations["connection"] = [version, database, not db.get_autocommit(),
observer.get_autocommit(), bool(cipher[1])]
observations["initial_transaction"] = no_cursor_transaction
query("SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'")
before = query("SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s",
(SCHEMA, TABLE))
cur.execute(MAKE_TABLE)
engine, = query("SELECT ENGINE FROM information_schema.tables WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s",
(SCHEMA, TABLE))
observations["ddl"] = [before, engine[0]]
inserted = cur.execute(
"INSERT INTO shift_samples (id,label,hours,team,fee) VALUES (1,'Harbor',8,'A',125.60)")
observed_before_commit = query(IDS, handle=other)
second.execute(INSERT, (2, "O'Quay", 6, "A", Decimal("101.25")))
same_connection = query(IDS)
db.commit()
after_commit = query(IDS, handle=other)
observations["insert"] = [inserted, observed_before_commit, same_connection, after_commit]
named = {"id":3, "label":"北站🚢", "hours":4, "team":"B", "fee":Decimal("98.50")}
cur.execute("INSERT INTO shift_samples VALUES (%(id)s,%(label)s,%(hours)s,%(team)s,%(fee)s)", named)
db.commit()
malicious_looking = "Harbor' OR 1=1 -- "
observations["bound_values"] = [
query("SELECT label FROM shift_samples WHERE id=%s", (3,))[0][0],
query("SELECT id FROM shift_samples WHERE label=%s", (malicious_looking,)),
query(IDS),
]
cur.execute("SELECT label,fee FROM shift_samples WHERE fee>%s ORDER BY id", (Decimal("100.00"),))
first = cur.fetchone()
remaining = cur.fetchall()
observations["query"] = [[first[0], str(first[1]), type(first[1]).__name__],
[[label,str(fee)] for label,fee in remaining],
cur.fetchone(), cur.fetchall(), cur.rowcount]
db.commit()
changed = cur.execute("UPDATE shift_samples SET hours=hours+1 WHERE team=%s", ("A",))
db.commit()
observations["update"] = [changed, query("SELECT id,hours FROM shift_samples ORDER BY id", handle=other)]
removed = cur.execute("DELETE FROM shift_samples WHERE hours>%s", (8,))
own = query(IDS)
db.rollback()
restored = query(IDS, handle=other)
removed_again = cur.execute("DELETE FROM shift_samples WHERE hours>%s", (8,))
db.commit()
observations["delete"] = [removed, own, restored, removed_again, query(IDS, handle=other)]
cur.execute(INSERT, (4,"Temporary",3,"B",Decimal("25.00")))
integrity = expected_error(
lambda: second.execute(INSERT, (2,"Duplicate",9,"B",Decimal("25.00"))),
pymysql.IntegrityError, 1062)
db.rollback()
observations["rollback"] = [integrity, query(IDS, handle=other)]
query("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ", handle=other)
observer.begin()
snapshot = query(IDS, handle=other)
cur.execute(INSERT, (5,"Snapshot",2,"B",Decimal("15.00")))
db.commit()
pinned = query(IDS, handle=other)
observer.commit()
observations["isolation"] = [snapshot, pinned, query(IDS, handle=other)]
cur.execute(INSERT, (6,"Before DDL",2,"B",Decimal("16.00")))
before_ddl = query(IDS, handle=other)
cur.execute("CREATE TABLE ddl_boundary (id INT PRIMARY KEY) ENGINE=InnoDB")
db.rollback()
observations["ddl_commit"] = [before_ddl, query(IDS, handle=other),
query("SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s",
(SCHEMA,"ddl_boundary"), handle=other)]
cur.execute("DROP TABLE ddl_boundary")
cur.execute("""CREATE PROCEDURE lab_double(IN units INT)
READS SQL DATA SELECT units*2 AS total""")
cur.callproc("lab_double", (7,))
procedure_value = cur.fetchone()
extra_result_sets = 0
while cur.nextset():
cur.fetchall()
extra_result_sets += 1
observations["stored_procedure"] = [procedure_value, extra_result_sets]
ignored = cur.execute("INSERT IGNORE INTO shift_samples VALUES (2,'Duplicate',4,'B',1.00)")
warning, = query("SHOW WARNINGS")
observations["exceptions"] = {
"Warning":[issubclass(pymysql.Warning, Exception), ignored, warning[0], warning[1]],
"Error":[issubclass(pymysql.Error, Exception), not issubclass(pymysql.Warning, pymysql.Error),
isinstance(pymysql.IntegrityError(1062, "sample"), pymysql.Error)],
"DatabaseError":[issubclass(pymysql.DatabaseError,pymysql.Error),
isinstance(pymysql.IntegrityError(1062,"sample"),pymysql.DatabaseError)],
"IntegrityError":integrity,
"DataError":expected_error(
lambda: cur.execute(INSERT,(7,"Overflow",3,"B",Decimal("100000.00"))),
pymysql.DataError,1264),
"ProgrammingError":expected_error(lambda: cur.execute("SELEC 1"),pymysql.ProgrammingError,1064),
"NotSupportedError":expected_error(
lambda: cur.execute("CREATE TABLE no_engine_probe (id INT) ENGINE=mbsky_missing_engine"),
pymysql.NotSupportedError,1286),
"InternalError":[issubclass(pymysql.InternalError,pymysql.DatabaseError),
type(pymysql.InternalError(0,"synthetic")).__name__],
}
db.rollback()
observations["exceptions"]["InterfaceError"] = expected_error(
lambda: db.query("SELECT 1"),pymysql.InterfaceError,0)
observations["exceptions"]["OperationalError"] = expected_error(
lambda: pymysql.connect(**(config | {"password":"deliberately-wrong-own-lab-password"})),
pymysql.OperationalError,1045)
observations["driver"] = [pymysql.apilevel,pymysql.paramstyle,importlib.util.find_spec("MySQLdb") is not None]
return observations
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--mysqld", type=Path, required=True, help="Path to local MySQL 8.4 bin/mysqld.exe")
parser.add_argument("--scratch-parent", type=Path, help="Optional parent for the disposable data directory")
options = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="mbsky-legacy-mysql-", dir=options.scratch_parent) as directory:
with new_database(options.mysqld, Path(directory).resolve()) as (config, cleanup):
report = run_lab(config)
report["graceful_shutdown"] = cleanup["graceful_shutdown"]
report["disposable_directory_removed"] = not Path(directory).exists()
print(json.dumps(report, ensure_ascii=True))
if __name__ == "__main__":
main()
本例需在 Windows CPython 3.12、PyMySQL 1.2.3、MySQL 8.4 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12、PyMySQL 1.2.3、MySQL 8.4
入口文件:projects/python-legacy-lab/legacy-mysql-lab/run_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
run_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12、PyMySQL 1.2.3、MySQL 8.4。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a453.zip