Skip to content

mysql - feat: moving to async config changes - #2018

Merged
jaredwray merged 5 commits into
mainfrom
mysql---feat-moving-to-async-config-changes
Jul 18, 2026
Merged

mysql - feat: moving to async config changes#2018
jaredwray merged 5 commits into
mainfrom
mysql---feat-moving-to-async-config-changes

Conversation

@jaredwray

Copy link
Copy Markdown
Owner

Please check if the PR fulfills these requirements

  • Followed the Contributing and Code of Conduct guidelines.
  • Tests for the changes have been added (for bug fixes/features) with 100% code coverage.

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)
mysql - feat: moving to async config changes

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the KeyvMysql adapter to make configuration properties like uri, table, keyLength, and namespaceLength read-only after construction, introducing new methods (reconnect, useTable, and resizeKeyColumns) to safely handle runtime configuration changes. However, several helper methods used by these new features—such as initializeTable, enqueueConfigurationTransition, createPoolQuery, and assertConnected—are missing from the implementation, which will cause compilation and runtime errors.

I am having trouble creating individual review comments. Click here to see my feedback.

storage/mysql/src/index.ts (351-388)

critical

The methods enqueueConfigurationTransition, createPoolQuery, initializeTable, and assertConnected are called throughout the new configuration methods (reconnect, useTable, resizeKeyColumns) and the constructor, but they are not defined anywhere in the KeyvMysql class. This will cause compilation and runtime errors. Please define these helper methods within the class. Note that the implementation of initializeTable correctly inspects and migrates each column independently and preserves existing column widths as reported by SHOW COLUMNS to prevent redundant conversions.

	public resizeKeyColumns(options: KeyvMysqlKeyColumnOptions): Promise<void> {
		return this.enqueueConfigurationTransition(async () => {
			this.assertConnected();
			const keyLength = options.keyLength ?? this._keyLength;
			const namespaceLength = options.namespaceLength ?? this._namespaceLength;
			validateCompositeIndexLength(keyLength, namespaceLength);
			if (keyLength === this._keyLength && namespaceLength === this._namespaceLength) {
				return;
			}

			const query = await this._connected;
			const tableEsc = escapeIdentifier(this._table);
			const lengthRows = (await query(
				"SELECT MAX(CHAR_LENGTH(CONVERT(id USING utf8mb4))) AS keyLength, MAX(CHAR_LENGTH(CONVERT(namespace USING utf8mb4))) AS namespaceLength FROM " + tableEsc,
			)) as mysql.RowDataPacket[];
			const storedKeyLength = Number(lengthRows[0]?.keyLength ?? 0);
			const storedNamespaceLength = Number(lengthRows[0]?.namespaceLength ?? 0);
			if (storedKeyLength > keyLength) {
				throw new RangeError(
					"Cannot reduce keyLength to " + keyLength + "; the table contains a " + storedKeyLength + "-character key",
				);
			}

			if (storedNamespaceLength > namespaceLength) {
				throw new RangeError(
					"Cannot reduce namespaceLength to " + namespaceLength + "; the table contains a " + storedNamespaceLength + "-character namespace",
				);
			}

			const keyByteLength = keyLength * UTF8_MAX_BYTES_PER_CODE_POINT;
			const namespaceByteLength = namespaceLength * UTF8_MAX_BYTES_PER_CODE_POINT;
			await query(
				"ALTER TABLE " + tableEsc + " MODIFY COLUMN id VARBINARY(" + keyByteLength + ") NOT NULL, MODIFY COLUMN namespace VARBINARY(" + namespaceByteLength + ") NOT NULL DEFAULT ''",
			);
			this._keyLength = keyLength;
			this._namespaceLength = namespaceLength;
			});
	}

	private enqueueConfigurationTransition<T>(callback: () => Promise<T>): Promise<T> {
		const transition = this._configurationTransition.then(callback);
		this._configurationTransition = transition.then(() => {}).catch(() => {});
		return transition;
	}

	private createPoolQuery(pool: ConnectionPool): SqlQuery {
		return async (sql: string) => {
			const data = await pool.query(sql);
			return data[0];
		};
	}

	private assertConnected(): void {
		if (this._disconnected) {
			throw new Error("MySQL adapter is disconnected");
		}
	}

	private async initializeTable(
		query: SqlQuery,
		table: string,
		keyLength: number,
		namespaceLength: number,
	): Promise<void> {
		const tableEsc = escapeIdentifier(table);
		const indexNameValue = table + "_key_namespace_idx";
		const indexName = String.fromCharCode(96) + indexNameValue.replace(new RegExp(String.fromCharCode(96), "g"), String.fromCharCode(96) + String.fromCharCode(96)) + String.fromCharCode(96);
		const expiresIndexName = String.fromCharCode(96) + (table + "_expires_idx").replace(new RegExp(String.fromCharCode(96), "g"), String.fromCharCode(96) + String.fromCharCode(96)) + String.fromCharCode(96);
		const keyByteLength = keyLength * UTF8_MAX_BYTES_PER_CODE_POINT;
		const namespaceByteLength = namespaceLength * UTF8_MAX_BYTES_PER_CODE_POINT;
		const createTable = "CREATE TABLE IF NOT EXISTS " + tableEsc + "(id VARBINARY(" + keyByteLength + ") NOT NULL, value TEXT, namespace VARBINARY(" + namespaceByteLength + ") NOT NULL DEFAULT '', expires BIGINT UNSIGNED DEFAULT NULL, UNIQUE INDEX " + indexName + " (namespace, id), INDEX " + expiresIndexName + " (expires))";

		await query(createTable);

		const existingKeyColumns = (await query(
			"SHOW COLUMNS FROM " + tableEsc + " WHERE Field IN ('id', 'namespace')",
		)) as mysql.RowDataPacket[];
		const existingIdColumn = existingKeyColumns.find((column) => column.Field === "id");
		const existingNamespaceColumn = existingKeyColumns.find(
			(column) => column.Field === "namespace",
		);
		if (!existingIdColumn) {
			throw new Error("Table " + table + " does not have an id column");
		}

		const getColumnLength = (column: mysql.RowDataPacket): number => {
			const match = /\((\d+)\)/.exec(String(column.Type));
			if (!match) {
				throw new Error("Cannot determine the width of " + String(column.Field));
			}

			return Number(match[1]);
		};
		const getTargetByteLength = (column: mysql.RowDataPacket): number => {
			const columnLength = getColumnLength(column);
			return String(column.Type).toLowerCase().startsWith("varbinary(")
				? columnLength
				: columnLength * UTF8_MAX_BYTES_PER_CODE_POINT;
		};
		const existingTargetIndexByteLength =
			getTargetByteLength(existingIdColumn) +
			(existingNamespaceColumn
				? getTargetByteLength(existingNamespaceColumn)
				: namespaceByteLength);
		if (existingTargetIndexByteLength > MYSQL_MAX_COMPOSITE_INDEX_BYTES) {
			throw new RangeError(
				"Existing key columns require " + existingTargetIndexByteLength + " index bytes, exceeding MySQL's " + MYSQL_MAX_COMPOSITE_INDEX_BYTES + "-byte composite index limit",
			);
		}

		if (!existingNamespaceColumn) {
			try {
				await query(
					"ALTER TABLE " + tableEsc + " ADD COLUMN namespace VARBINARY(" + namespaceByteLength + ") NOT NULL DEFAULT ''",
				);
			} catch (error) {
				if ((error as { errno?: number }).errno !== 1060) {
					throw error;
				}
			}
		}

		const keyColumns = (await query(
			"SHOW COLUMNS FROM " + tableEsc + " WHERE Field IN ('id', 'namespace')",
		)) as mysql.RowDataPacket[];
		const idColumn = keyColumns.find((column) => column.Field === "id");
		const namespaceColumn = keyColumns.find((column) => column.Field === "namespace");
		if (!idColumn || !namespaceColumn) {
			throw new Error("Table " + table + " must have id and namespace columns");
		}
		const targetIndexByteLength =
			getTargetByteLength(idColumn) + getTargetByteLength(namespaceColumn);
		if (targetIndexByteLength > MYSQL_MAX_COMPOSITE_INDEX_BYTES) {
			throw new RangeError(
				"Existing key columns require " + targetIndexByteLength + " index bytes, exceeding MySQL's " + MYSQL_MAX_COMPOSITE_INDEX_BYTES + "-byte composite index limit",
			);
		}

		const idNeedsMigration = !String(idColumn.Type).toLowerCase().startsWith("varbinary(");
		const namespaceNeedsMigration = !String(namespaceColumn.Type)
			.toLowerCase()
			.startsWith("varbinary(");
		if (idNeedsMigration || namespaceNeedsMigration) {
			const modifyVarcharParts: string[] = [];
			const modifyVarbinaryParts: string[] = [];
			if (idNeedsMigration) {
				const idCharacterLength = getColumnLength(idColumn);
				modifyVarcharParts.push(
					"MODIFY COLUMN id VARCHAR(" + idCharacterLength + ") CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL",
				);
				modifyVarbinaryParts.push(
					"MODIFY COLUMN id VARBINARY(" + idCharacterLength * UTF8_MAX_BYTES_PER_CODE_POINT + ") NOT NULL",
				);
			}

			if (namespaceNeedsMigration) {
				const namespaceCharacterLength = getColumnLength(namespaceColumn);
				modifyVarcharParts.push(
					"MODIFY COLUMN namespace VARCHAR(" + namespaceCharacterLength + ") CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT ''",
				);
				modifyVarbinaryParts.push(
					"MODIFY COLUMN namespace VARBINARY(" + namespaceCharacterLength * UTF8_MAX_BYTES_PER_CODE_POINT + ") NOT NULL DEFAULT ''",
				);
			}

			await query("ALTER TABLE " + tableEsc + " " + modifyVarcharParts.join(", "));
			await query("ALTER TABLE " + tableEsc + " " + modifyVarbinaryParts.join(", "));
		}

		try {
			await query("ALTER TABLE " + tableEsc + " DROP PRIMARY KEY");
		} catch (error) {
			if ((error as { errno?: number }).errno !== 1091) {
				throw error;
			}
		}

		const indexRows = (await query(
			mysql.format("SHOW INDEX FROM " + tableEsc + " WHERE Key_name = ?", [indexNameValue]),
		)) as mysql.RowDataPacket[];
		const indexColumns = [...indexRows]
			.sort((a, b) => Number(a.Seq_in_index) - Number(b.Seq_in_index))
			.map((row) => String(row.Column_name));
		const hasNamespaceFirstUniqueIndex =
			indexColumns.length === 2 &&
			indexColumns[0] === "namespace" &&
			indexColumns[1] === "id" &&
			indexRows.every((row) => Number(row.Non_unique) === 0);

		if (!hasNamespaceFirstUniqueIndex) {
			if (indexRows.length > 0) {
				await query(
					"ALTER TABLE " + tableEsc + " DROP INDEX " + indexName + ", ADD UNIQUE INDEX " + indexName + " (namespace, id)",
				);
			} else {
				try {
					await query("CREATE UNIQUE INDEX " + indexName + " ON " + tableEsc + " (namespace, id)");
				} catch (error) {
					if ((error as { errno?: number }).errno !== 1061) {
						throw error;
					}
				}
			}
		}

		try {
			await query("ALTER TABLE " + tableEsc + " ADD COLUMN expires BIGINT UNSIGNED DEFAULT NULL");
		} catch (error) {
			if ((error as { errno?: number }).errno !== 1060) {
				throw error;
			}
		}

		try {
			await query("CREATE INDEX " + expiresIndexName + " ON " + tableEsc + " (expires)");
		} catch (error) {
			if ((error as { errno?: number }).errno !== 1061) {
				throw error;
			}
		}
	}
References
  1. When initializing database adapters or performing schema migrations, inspect and migrate each column independently. Retain and preserve the existing column widths rather than overwriting them with configured defaults.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 376956cb24

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread storage/mysql/src/index.ts
Comment thread storage/mysql/src/index.ts
Comment thread storage/mysql/src/index.ts Outdated
@codecov

codecov Bot commented Jul 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (97fa359) to head (9d66517).

Additional details and impacted files
@@            Coverage Diff             @@
##              main     #2018    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           55        55            
  Lines         4935      5067   +132     
  Branches       793       820    +27     
==========================================
+ Hits          4935      5067   +132     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jaredwray
jaredwray merged commit b775072 into main Jul 18, 2026
14 checks passed
@jaredwray
jaredwray deleted the mysql---feat-moving-to-async-config-changes branch July 18, 2026 20:51
This was referenced Aug 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant