[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77XY0PVDTM2M78VSS0EZAXR":3,"skill-same:01M77XY0PVDTM2M78VSS0EZAXR":49},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":33,"updatedAt":34,"install":35,"resources":48},"01M77XY0PVDTM2M78VSS0EZAXR","mysql-patterns",null,"MySQL and MariaDB schema, query, indexing, transaction, replication, and connection-pool patterns for production backends.","503496348-ops\u002Fmischief-production","503496348-ops","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F266905914?v=4","01M77X5J7XQWWZGT8998HDGXQM","AtomCollide","01M77X5J8V78Y3NXMY6BBC75X9",2,"MIT","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fecc-mysql-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: mysql-patterns\ndescription: MySQL and MariaDB schema, query, indexing, transaction, replication, and connection-pool patterns for production backends.\nmetadata:\n  origin: HCP\n---\n\n# MySQL Patterns\n\nUse this skill when working on MySQL or MariaDB schema design, migrations,\nslow-query investigation, queue-style transactions, connection pools, or\nproduction database configuration. Prefer exact version checks before applying a\nfeature-specific pattern because MySQL and MariaDB have diverged in several SQL\ndetails.\n\n## Activation\n\n- Designing MySQL or MariaDB tables, indexes, and constraints\n- Reviewing migrations before they run on large production tables\n- Debugging slow queries, lock waits, deadlocks, or connection exhaustion\n- Adding keyset pagination, upserts, full-text search, JSON columns, or queues\n- Configuring application connection pools, read replicas, TLS, or slow logs\n\n## Version Check\n\nStart by identifying the engine and version:\n\n```sql\nSELECT VERSION();\nSHOW VARIABLES LIKE 'version_comment';\n```\n\nKeep MySQL and MariaDB guidance separate when syntax differs:\n\n- MySQL documents row aliases as the replacement for `VALUES(col)` in\n  `ON DUPLICATE KEY UPDATE`; `VALUES(col)` is deprecated there.\n- MariaDB documents `VALUES(col)` as the supported way to reference inserted\n  values in `ON DUPLICATE KEY UPDATE`; use it for cross-engine compatibility.\n- `SKIP LOCKED` is appropriate for queue-like work only. It skips locked rows\n  and can return an inconsistent view, so do not use it for general accounting\n  or integrity-sensitive reads.\n\n## Schema Defaults\n\n```sql\nCREATE TABLE orders (\n    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n    account_id BIGINT UNSIGNED NOT NULL,\n    status VARCHAR(32) NOT NULL,\n    total DECIMAL(15, 2) NOT NULL,\n    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n    deleted_at DATETIME NULL,\n    PRIMARY KEY (id),\n    KEY idx_orders_account_status_created (account_id, status, created_at),\n    KEY idx_orders_active (account_id, deleted_at)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n```\n\nDefault choices:\n\n| Use Case | Prefer | Avoid |\n| --- | --- | --- |\n| Surrogate primary keys | `BIGINT UNSIGNED AUTO_INCREMENT` | `INT` for tables that can grow beyond 2B rows |\n| UUID lookup keys | `BINARY(16)` with conversion helpers | `VARCHAR(36)` primary keys on hot tables |\n| Money and exact quantities | `DECIMAL(p, s)` | `FLOAT` or `DOUBLE` |\n| User-facing text | `utf8mb4` tables and indexes | MySQL `utf8` \u002F `utf8mb3` defaults |\n| Application timestamps | `DATETIME` with UTC managed by the app | Assuming `DATETIME` stores time zone metadata |\n| Soft deletes | `deleted_at DATETIME NULL` plus scoped indexes | Filtering soft-deleted rows without an index |\n| Extensible status values | lookup table or constrained `VARCHAR` | `ENUM` when values change often |\n\n## Indexing\n\nComposite index order usually follows equality predicates first, then range or\nsort columns:\n\n```sql\nCREATE INDEX idx_orders_account_status_created\n    ON orders (account_id, status, created_at);\n\nSELECT id, total\nFROM orders\nWHERE account_id = ?\n  AND status = 'pending'\n  AND created_at >= ?\nORDER BY created_at DESC\nLIMIT 50;\n```\n\nUse `EXPLAIN` before adding or changing an index:\n\n```sql\nEXPLAIN\nSELECT id, total\nFROM orders\nWHERE account_id = 123 AND status = 'pending'\nORDER BY created_at DESC\nLIMIT 50;\n```\n\nSignals to investigate:\n\n| Field | Risk Signal |\n| --- | --- |\n| `type` | `ALL` on a large table |\n| `key` | `NULL` when a selective predicate exists |\n| `rows` | Very high row estimate for an interactive path |\n| `Extra` | `Using temporary`, `Using filesort`, or broad `Using where` |\n\nAvoid adding indexes blindly. Each index increases write cost, migration time,\nbackup size, and buffer-pool pressure.\n\n## Query Patterns\n\n### Upsert\n\nCross-engine-compatible form:\n\n```sql\nINSERT INTO user_settings (user_id, setting_key, setting_value)\nVALUES (?, ?, ?)\nON DUPLICATE KEY UPDATE\n    setting_value = VALUES(setting_value),\n    updated_at = CURRENT_TIMESTAMP;\n```\n\nMySQL row-alias form:\n\n```sql\nINSERT INTO user_settings (user_id, setting_key, setting_value)\nVALUES (?, ?, ?) AS new\nON DUPLICATE KEY UPDATE\n    setting_value = new.setting_value,\n    updated_at = CURRENT_TIMESTAMP;\n```\n\nUse the row-alias form only after confirming the target is MySQL. Use\n`VALUES(col)` for MariaDB or mixed MySQL\u002FMariaDB fleets.\n\n### Keyset Pagination\n\n```sql\nSELECT id, name, created_at\nFROM products\nWHERE (created_at, id) \u003C (?, ?)\nORDER BY created_at DESC, id DESC\nLIMIT 50;\n```\n\nBack it with an index that matches the cursor:\n\n```sql\nCREATE INDEX idx_products_created_id ON products (created_at, id);\n```\n\nDo not use deep `OFFSET` pagination on large tables; it makes the server scan\nand discard rows before returning the page.\n\n### JSON Fields\n\nUse JSON columns for extension data, not for fields that need heavy relational\nfiltering or constraints.\n\n```sql\nCREATE TABLE events (\n    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n    payload JSON NOT NULL,\n    event_type VARCHAR(64)\n        GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(payload, '$.type'))) STORED,\n    KEY idx_events_type (event_type)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n```\n\nFor frequently queried JSON paths, expose a generated column and index that\ncolumn. Keep foreign keys, ownership, tenancy, and lifecycle fields relational.\n\n### Full-Text Search\n\n```sql\nALTER TABLE articles ADD FULLTEXT KEY ft_articles_title_body (title, body);\n\nSELECT id, title, MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE) AS score\nFROM articles\nWHERE MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE)\nORDER BY score DESC\nLIMIT 20;\n```\n\nUse external search when you need typo tolerance, complex ranking, cross-table\nfacets, or language-specific analysis beyond built-in full-text behavior.\n\n## Transactions\n\nKeep transactions short and lock rows in a consistent order:\n\n```sql\nSTART TRANSACTION;\n\nSELECT id, balance\nFROM accounts\nWHERE id IN (?, ?)\nORDER BY id\nFOR UPDATE;\n\nUPDATE accounts SET balance = balance - ? WHERE id = ?;\nUPDATE accounts SET balance = balance + ? WHERE id = ?;\n\nCOMMIT;\n```\n\nDeadlock and lock-wait checklist:\n\n- Lock rows in a deterministic order across code paths.\n- Do external API calls before opening the transaction, not inside it.\n- Add indexes for predicates used in `UPDATE`, `DELETE`, and locking reads.\n- On deadlock, roll back and retry the whole transaction with a bounded retry\n  budget.\n- Capture `SHOW ENGINE INNODB STATUS\\G` soon after a deadlock; it is overwritten\n  by later events.\n\nQueue-style worker claim:\n\n```sql\nSTART TRANSACTION;\n\nSELECT id\nFROM jobs\nWHERE status = 'pending'\nORDER BY created_at\nLIMIT 1\nFOR UPDATE SKIP LOCKED;\n\nUPDATE jobs\nSET status = 'processing', started_at = CURRENT_TIMESTAMP\nWHERE id = ?;\n\nCOMMIT;\n```\n\nUse `SKIP LOCKED` only for queue-like workloads where skipping a locked row is\nacceptable. It is not a replacement for normal transactional consistency.\n\n## Connection Pools\n\nSQLAlchemy example:\n\n```python\nfrom sqlalchemy import create_engine\n\nengine = create_engine(\n    \"mysql+mysqlconnector:\u002F\u002Fapp:secret@db.internal\u002Fapp\",\n    pool_size=10,\n    max_overflow=5,\n    pool_timeout=30,\n    pool_recycle=240,\n    pool_pre_ping=True,\n    connect_args={\"connect_timeout\": 5},\n)\n```\n\nNode.js `mysql2` example:\n\n```javascript\nimport mysql from 'mysql2\u002Fpromise';\n\nconst pool = mysql.createPool({\n  host: process.env.DB_HOST,\n  user: process.env.DB_USER,\n  password: process.env.DB_PASSWORD,\n  database: process.env.DB_NAME,\n  waitForConnections: true,\n  connectionLimit: 10,\n  queueLimit: 0,\n  enableKeepAlive: true,\n  keepAliveInitialDelay: 30000,\n});\n\nconst [rows] = await pool.execute(\n  'SELECT id, total FROM orders WHERE account_id = ? LIMIT 50',\n  [accountId],\n);\n```\n\nKeep application pool recycling below the server `wait_timeout`. If the server\nuses `wait_timeout = 300`, a `pool_recycle` around 240 seconds is coherent;\n`pool_pre_ping` still helps recover from network and failover events.\n\n## Diagnostics\n\nUseful first-pass commands:\n\n```sql\nSHOW FULL PROCESSLIST;\nSHOW ENGINE INNODB STATUS\\G;\nSHOW VARIABLES LIKE 'slow_query_log';\nSHOW VARIABLES LIKE 'long_query_time';\n```\n\nEnable the slow log in a controlled environment:\n\n```sql\nSET GLOBAL slow_query_log = 'ON';\nSET GLOBAL long_query_time = 1;\nSET GLOBAL log_queries_not_using_indexes = 'ON';\n```\n\nUse `EXPLAIN ANALYZE` only when it is safe to execute the query. It runs the\nstatement and can be expensive on production-sized data.\n\n## Replication\n\nRead replicas can lag. Do not route read-your-own-write paths, checkout flows,\npermission checks, or idempotency-key reads to a replica immediately after a\nwrite.\n\n```sql\n-- MySQL legacy terminology, still common in existing fleets\nSHOW SLAVE STATUS\\G;\n\n-- Newer terminology where supported\nSHOW REPLICA STATUS\\G;\n```\n\nCheck the engine\u002Fversion before standardizing on one command. Monitor replica\nSQL thread health, IO thread health, and lag, not just whether the TCP\nconnection is alive.\n\n## Security\n\n```sql\nCREATE USER 'app'@'%' IDENTIFIED BY 'use-a-secret-manager';\nGRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'%';\n\nALTER USER 'app'@'%' REQUIRE SSL;\n\nSELECT user, host\nFROM mysql.user\nWHERE user = '';\n\nDROP USER IF EXISTS ''@'localhost';\nDROP USER IF EXISTS ''@'%';\n```\n\nSecurity review points:\n\n- Do not grant `ALL PRIVILEGES` or `*.*` to application users.\n- Require TLS for application users when traffic crosses hosts or networks.\n- Store credentials in the platform secret manager, not in examples, scripts, or\n  repository files.\n- Separate migration\u002Fadmin users from runtime application users.\n- Audit public network exposure and bind addresses before tuning performance.\n\n## Configuration\n\nExample starting point for a dedicated database host:\n\n```ini\n[mysqld]\ninnodb_buffer_pool_size = 4G\ninnodb_flush_log_at_trx_commit = 1\nsync_binlog = 1\n\nmax_connections = 300\nthread_cache_size = 50\n\nwait_timeout = 300\ninteractive_timeout = 300\ninnodb_lock_wait_timeout = 10\n\nslow_query_log = ON\nlong_query_time = 1\nlog_queries_not_using_indexes = ON\n\nlog_bin = mysql-bin\nbinlog_format = ROW\nbinlog_expire_logs_seconds = 604800\n```\n\nTreat configuration values as a prompt for review, not a universal preset. Size\nmemory, connections, log retention, and durability settings from workload,\nhardware, backup policy, and recovery objectives.\n\n## Anti-Patterns\n\n| Anti-Pattern | Risk | Better Pattern |\n| --- | --- | --- |\n| `SELECT *` in hot paths | Over-fetching and brittle clients | Select explicit columns |\n| Deep `OFFSET` pagination | Linear scans and slow pages | Keyset pagination |\n| No index on foreign-key joins | Slow joins and lock-heavy deletes | Index FK columns intentionally |\n| Long transactions | Lock waits and large undo history | Commit small units of work |\n| Direct DML against `mysql.user` | Grant-table corruption risk | Use `CREATE USER`, `ALTER USER`, `DROP USER` |\n| Application user with admin grants | High blast radius | Least-privilege runtime user |\n| Pool recycle above `wait_timeout` | Stale pooled connections | Recycle below timeout and pre-ping |\n| Replica reads after writes | Stale user-facing state | Pin read-after-write flows to primary |\n\n## Output Expectations\n\nWhen this skill is used for review, return:\n\n1. Engine\u002Fversion assumptions.\n2. Highest-risk correctness, lock, security, and migration issues.\n3. Exact SQL or code changes for the safe path.\n4. Validation plan: `EXPLAIN`, migration dry run, lock\u002Fdeadlock check, and\n   rollback criteria.\n5. Any MySQL\u002FMariaDB syntax differences that affect the recommendation.\n\n## Related\n\n- Skill: `postgres-patterns` - PostgreSQL-specific schema and query patterns\n- Skill: `database-migrations` - migration planning and rollout safety\n- Skill: `backend-patterns` - API and service-layer patterns\n- Skill: `security-review` - secret handling, auth, and least privilege\n- Agent: `database-reviewer` - broader database review workflow\n","# MySQL Patterns\n\nUse this skill when working on MySQL or MariaDB schema design, migrations,\nslow-query investigation, queue-style transactions, connection pools, or\nproduction database configuration. Prefer exact version checks before applying a\nfeature-specific pattern because MySQL and MariaDB have diverged in several SQL\ndetails.\n\n## Activation\n\n- Designing MySQL or MariaDB tables, indexes, and constraints\n- Reviewing migrations before they run on large production tables\n- Debugging slow queries, lock waits, deadlocks, or connection exhaustion\n- Adding keyset pagination, upserts, full-text search, JSON columns, or queues\n- Configuring application connection pools, read replicas, TLS, or slow logs\n\n## Version Check\n\nStart by identifying the engine and version:\n\n```sql\nSELECT VERSION();\nSHOW VARIABLES LIKE 'version_comment';\n```\n\nKeep MySQL and MariaDB guidance separate when syntax differs:\n\n- MySQL documents row aliases as the replacement for `VALUES(col)` in\n  `ON DUPLICATE KEY UPDATE`; `VALUES(col)` is deprecated there.\n- MariaDB documents `VALUES(col)` as the supported way to reference inserted\n  values in `ON DUPLICATE KEY UPDATE`; use it for cross-engine compatibility.\n- `SKIP LOCKED` is appropriate for queue-like work only. It skips locked rows\n  and can return an inconsistent view, so do not use it for general accounting\n  or integrity-sensitive reads.\n\n## Schema Defaults\n\n```sql\nCREATE TABLE orders (\n    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n    account_id BIGINT UNSIGNED NOT NULL,\n    status VARCHAR(32) NOT NULL,\n    total DECIMAL(15, 2) NOT NULL,\n    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n    deleted_at DATETIME NULL,\n    PRIMARY KEY (id),\n    KEY idx_orders_account_status_created (account_id, status, created_at),\n    KEY idx_orders_active (account_id, deleted_at)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n```\n\nDefault choices:\n\n| Use Case | Prefer | Avoid |\n| --- | --- | --- |\n| Surrogate primary keys | `BIGINT UNSIGNED AUTO_INCREMENT` | `INT` for tables that can grow beyond 2B rows |\n| UUID lookup keys | `BINARY(16)` with conversion helpers | `VARCHAR(36)` primary keys on hot tables |\n| Money and exact quantities | `DECIMAL(p, s)` | `FLOAT` or `DOUBLE` |\n| User-facing text | `utf8mb4` tables and indexes | MySQL `utf8` \u002F `utf8mb3` defaults |\n| Application timestamps | `DATETIME` with UTC managed by the app | Assuming `DATETIME` stores time zone metadata |\n| Soft deletes | `deleted_at DATETIME NULL` plus scoped indexes | Filtering soft-deleted rows without an index |\n| Extensible status values | lookup table or constrained `VARCHAR` | `ENUM` when values change often |\n\n## Indexing\n\nComposite index order usually follows equality predicates first, then range or\nsort columns:\n\n```sql\nCREATE INDEX idx_orders_account_status_created\n    ON orders (account_id, status, created_at);\n\nSELECT id, total\nFROM orders\nWHERE account_id = ?\n  AND status = 'pending'\n  AND created_at >= ?\nORDER BY created_at DESC\nLIMIT 50;\n```\n\nUse `EXPLAIN` before adding or changing an index:\n\n```sql\nEXPLAIN\nSELECT id, total\nFROM orders\nWHERE account_id = 123 AND status = 'pending'\nORDER BY created_at DESC\nLIMIT 50;\n```\n\nSignals to investigate:\n\n| Field | Risk Signal |\n| --- | --- |\n| `type` | `ALL` on a large table |\n| `key` | `NULL` when a selective predicate exists |\n| `rows` | Very high row estimate for an interactive path |\n| `Extra` | `Using temporary`, `Using filesort`, or broad `Using where` |\n\nAvoid adding indexes blindly. Each index increases write cost, migration time,\nbackup size, and buffer-pool pressure.\n\n## Query Patterns\n\n### Upsert\n\nCross-engine-compatible form:\n\n```sql\nINSERT INTO user_settings (user_id, setting_key, setting_value)\nVALUES (?, ?, ?)\nON DUPLICATE KEY UPDATE\n    setting_value = VALUES(setting_value),\n    updated_at = CURRENT_TIMESTAMP;\n```\n\nMySQL row-alias form:\n\n```sql\nINSERT INTO user_settings (user_id, setting_key, setting_value)\nVALUES (?, ?, ?) AS new\nON DUPLICATE KEY UPDATE\n    setting_value = new.setting_value,\n    updated_at = CURRENT_TIMESTAMP;\n```\n\nUse the row-alias form only after confirming the target is MySQL. Use\n`VALUES(col)` for MariaDB or mixed MySQL\u002FMariaDB fleets.\n\n### Keyset Pagination\n\n```sql\nSELECT id, name, created_at\nFROM products\nWHERE (created_at, id) \u003C (?, ?)\nORDER BY created_at DESC, id DESC\nLIMIT 50;\n```\n\nBack it with an index that matches the cursor:\n\n```sql\nCREATE INDEX idx_products_created_id ON products (created_at, id);\n```\n\nDo not use deep `OFFSET` pagination on large tables; it makes the server scan\nand discard rows before returning the page.\n\n### JSON Fields\n\nUse JSON columns for extension data, not for fields that need heavy relational\nfiltering or constraints.\n\n```sql\nCREATE TABLE events (\n    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n    payload JSON NOT NULL,\n    event_type VARCHAR(64)\n        GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(payload, '$.type'))) STORED,\n    KEY idx_events_type (event_type)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n```\n\nFor frequently queried JSON paths, expose a generated column and index that\ncolumn. Keep foreign keys, ownership, tenancy, and lifecycle fields relational.\n\n### Full-Text Search\n\n```sql\nALTER TABLE articles ADD FULLTEXT KEY ft_articles_title_body (title, body);\n\nSELECT id, title, MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE) AS score\nFROM articles\nWHERE MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE)\nORDER BY score DESC\nLIMIT 20;\n```\n\nUse external search when you need typo tolerance, complex ranking, cross-table\nfacets, or language-specific analysis beyond built-in full-text behavior.\n\n## Transactions\n\nKeep transactions short and lock rows in a consistent order:\n\n```sql\nSTART TRANSACTION;\n\nSELECT id, balance\nFROM accounts\nWHERE id IN (?, ?)\nORDER BY id\nFOR UPDATE;\n\nUPDATE accounts SET balance = balance - ? WHERE id = ?;\nUPDATE accounts SET balance = balance + ? WHERE id = ?;\n\nCOMMIT;\n```\n\nDeadlock and lock-wait checklist:\n\n- Lock rows in a deterministic order across code paths.\n- Do external API calls before opening the transaction, not inside it.\n- Add indexes for predicates used in `UPDATE`, `DELETE`, and locking reads.\n- On deadlock, roll back and retry the whole transaction with a bounded retry\n  budget.\n- Capture `SHOW ENGINE INNODB STATUS\\G` soon after a deadlock; it is overwritten\n  by later events.\n\nQueue-style worker claim:\n\n```sql\nSTART TRANSACTION;\n\nSELECT id\nFROM jobs\nWHERE status = 'pending'\nORDER BY created_at\nLIMIT 1\nFOR UPDATE SKIP LOCKED;\n\nUPDATE jobs\nSET status = 'processing', started_at = CURRENT_TIMESTAMP\nWHERE id = ?;\n\nCOMMIT;\n```\n\nUse `SKIP LOCKED` only for queue-like workloads where skipping a locked row is\nacceptable. It is not a replacement for normal transactional consistency.\n\n## Connection Pools\n\nSQLAlchemy example:\n\n```python\nfrom sqlalchemy import create_engine\n\nengine = create_engine(\n    \"mysql+mysqlconnector:\u002F\u002Fapp:secret@db.internal\u002Fapp\",\n    pool_size=10,\n    max_overflow=5,\n    pool_timeout=30,\n    pool_recycle=240,\n    pool_pre_ping=True,\n    connect_args={\"connect_timeout\": 5},\n)\n```\n\nNode.js `mysql2` example:\n\n```javascript\nimport mysql from 'mysql2\u002Fpromise';\n\nconst pool = mysql.createPool({\n  host: process.env.DB_HOST,\n  user: process.env.DB_USER,\n  password: process.env.DB_PASSWORD,\n  database: process.env.DB_NAME,\n  waitForConnections: true,\n  connectionLimit: 10,\n  queueLimit: 0,\n  enableKeepAlive: true,\n  keepAliveInitialDelay: 30000,\n});\n\nconst [rows] = await pool.execute(\n  'SELECT id, total FROM orders WHERE account_id = ? LIMIT 50',\n  [accountId],\n);\n```\n\nKeep application pool recycling below the server `wait_timeout`. If the server\nuses `wait_timeout = 300`, a `pool_recycle` around 240 seconds is coherent;\n`pool_pre_ping` still helps recover from network and failover events.\n\n## Diagnostics\n\nUseful first-pass commands:\n\n```sql\nSHOW FULL PROCESSLIST;\nSHOW ENGINE INNODB STATUS\\G;\nSHOW VARIABLES LIKE 'slow_query_log';\nSHOW VARIABLES LIKE 'long_query_time';\n```\n\nEnable the slow log in a controlled environment:\n\n```sql\nSET GLOBAL slow_query_log = 'ON';\nSET GLOBAL long_query_time = 1;\nSET GLOBAL log_queries_not_using_indexes = 'ON';\n```\n\nUse `EXPLAIN ANALYZE` only when it is safe to execute the query. It runs the\nstatement and can be expensive on production-sized data.\n\n## Replication\n\nRead replicas can lag. Do not route read-your-own-write paths, checkout flows,\npermission checks, or idempotency-key reads to a replica immediately after a\nwrite.\n\n```sql\n-- MySQL legacy terminology, still common in existing fleets\nSHOW SLAVE STATUS\\G;\n\n-- Newer terminology where supported\nSHOW REPLICA STATUS\\G;\n```\n\nCheck the engine\u002Fversion before standardizing on one command. Monitor replica\nSQL thread health, IO thread health, and lag, not just whether the TCP\nconnection is alive.\n\n## Security\n\n```sql\nCREATE USER 'app'@'%' IDENTIFIED BY 'use-a-secret-manager';\nGRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'%';\n\nALTER USER 'app'@'%' REQUIRE SSL;\n\nSELECT user, host\nFROM mysql.user\nWHERE user = '';\n\nDROP USER IF EXISTS ''@'localhost';\nDROP USER IF EXISTS ''@'%';\n```\n\nSecurity review points:\n\n- Do not grant `ALL PRIVILEGES` or `*.*` to application users.\n- Require TLS for application users when traffic crosses hosts or networks.\n- Store credentials in the platform secret manager, not in examples, scripts, or\n  repository files.\n- Separate migration\u002Fadmin users from runtime application users.\n- Audit public network exposure and bind addresses before tuning performance.\n\n## Configuration\n\nExample starting point for a dedicated database host:\n\n```ini\n[mysqld]\ninnodb_buffer_pool_size = 4G\ninnodb_flush_log_at_trx_commit = 1\nsync_binlog = 1\n\nmax_connections = 300\nthread_cache_size = 50\n\nwait_timeout = 300\ninteractive_timeout = 300\ninnodb_lock_wait_timeout = 10\n\nslow_query_log = ON\nlong_query_time = 1\nlog_queries_not_using_indexes = ON\n\nlog_bin = mysql-bin\nbinlog_format = ROW\nbinlog_expire_logs_seconds = 604800\n```\n\nTreat configuration values as a prompt for review, not a universal preset. Size\nmemory, connections, log retention, and durability settings from workload,\nhardware, backup policy, and recovery objectives.\n\n## Anti-Patterns\n\n| Anti-Pattern | Risk | Better Pattern |\n| --- | --- | --- |\n| `SELECT *` in hot paths | Over-fetching and brittle clients | Select explicit columns |\n| Deep `OFFSET` pagination | Linear scans and slow pages | Keyset pagination |\n| No index on foreign-key joins | Slow joins and lock-heavy deletes | Index FK columns intentionally |\n| Long transactions | Lock waits and large undo history | Commit small units of work |\n| Direct DML against `mysql.user` | Grant-table corruption risk | Use `CREATE USER`, `ALTER USER`, `DROP USER` |\n| Application user with admin grants | High blast radius | Least-privilege runtime user |\n| Pool recycle above `wait_timeout` | Stale pooled connections | Recycle below timeout and pre-ping |\n| Replica reads after writes | Stale user-facing state | Pin read-after-write flows to primary |\n\n## Output Expectations\n\nWhen this skill is used for review, return:\n\n1. Engine\u002Fversion assumptions.\n2. Highest-risk correctness, lock, security, and migration issues.\n3. Exact SQL or code changes for the safe path.\n4. Validation plan: `EXPLAIN`, migration dry run, lock\u002Fdeadlock check, and\n   rollback criteria.\n5. Any MySQL\u002FMariaDB syntax differences that affect the recommendation.\n\n## Related\n\n- Skill: `postgres-patterns` - PostgreSQL-specific schema and query patterns\n- Skill: `database-migrations` - migration planning and rollout safety\n- Skill: `backend-patterns` - API and service-layer patterns\n- Skill: `security-review` - secret handling, auth, and least privilege\n- Agent: `database-reviewer` - broader database review workflow\n",{"name":5,"metadata":24,"description":7},{"origin":25},"HCP","main","c9103dbad48ef3005f163584d0f2abd4591217f6","skills\u002Fecc-mysql-patterns",1,"https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production","https:\u002F\u002Fgithub.com\u002F503496348-ops","https:\u002F\u002F503496348-ops.github.io\u002Fatomcollide-product-matrix\u002F#tree","元素碰撞-AtomCollide-AI 智能体实验室 测试人专属成长社群 正式招募\r\n我们的目标很纯粹：连接每一位测试工程师\u002FAI使用探索与爱好者，让你在这里既能扎实打磨技术硬实力，也能打通职业晋升的新通路，这是一个专注于AI领域的开源组","2026-07-30 00:35:42",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add 503496348-ops\u002Fmischief-production --skill mysql-patterns",{"tool":41,"command":42},"bunx","bunx skills add 503496348-ops\u002Fmischief-production --skill mysql-patterns",{"tool":44,"command":45},"pnpm","pnpm dlx skills add 503496348-ops\u002Fmischief-production --skill mysql-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fecc-mysql-patterns\u002FSKILL.md",true,[],[50,57,64,71,78,85],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M77YG7NPZHE751W9QGK3H9ED","writing-skills","Use when creating new skills, editing existing skills, or verifying skills work before deployment","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fsp-writing-skills\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M77YG4HPYH0GJP974DZ6KCPQ","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fsp-writing-plans\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M77YFZW1FZ1GVC5C89NPE5M8","verification-before-completion","Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fsp-verification-before-completion\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M77YFVPWANT5VE5GWBTKHPA2","using-智械工程","Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fsp-using-superpowers\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M77YFQJAW5PX3QYSBCD3B24S","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fsp-using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M77YFMSTB70VX8W2QHNJWYB0","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002F503496348-ops\u002Fmischief-production\u002Fblob\u002Fmain\u002Fskills\u002Fsp-test-driven-development\u002FSKILL.md",[],[]]