diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..c2e9b9c9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + groups: + all-dependencies: + patterns: + - "*" diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 00000000..a26d07c6 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,68 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/lint.yaml': + - 'actions/checkout@v7.0.1' + '.github/workflows/tests.yaml': + - 'actions/checkout@v7.0.1' + - 'actions/setup-python@v7.1.0' + - 'codecov/codecov-action@v7.1.1' + '.github/workflows/windows.yaml': + - 'actions/cache@v6.1.0' + - 'actions/checkout@v7.0.1' + - 'actions/download-artifact@v8.0.2' + - 'actions/setup-python@v7.1.0' + - 'actions/upload-artifact@v7.0.2' + - 'pypa/gh-action-pypi-publish@v1.14.3' +dependencies: + 'actions/cache@v6.1.0': + ref: 'v6.1.0' + commit: 'sha1-55cc8345863c7cc4c66a329aec7e433d2d1c52a9' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'actions/download-artifact@v8.0.2': + ref: 'v8.0.2' + commit: 'sha1-9000827ccba6bdab643e8b6fd33ac0654aef8333' + owner_id: 44036562 + repo_id: 192626254 + 'actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd': + ref: 'v8.0.0' + commit: 'sha1-ed597411d8f924073f98dfc5c65a23a2325f34cd' + owner_id: 44036562 + repo_id: 205262760 + 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405': + ref: 'v6.2.0' + commit: 'sha1-a309ff8b426b58ec0e2a45f0f869d46889d02405' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@v7.1.0': + ref: 'v7.1.0' + commit: 'sha1-6d4fd22b20465ccc0f7354476588e8df7c9ca0e0' + owner_id: 44036562 + repo_id: 192625525 + 'actions/upload-artifact@v7.0.2': + ref: 'v7.0.2' + commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9' + owner_id: 44036562 + repo_id: 192625955 + 'codecov/codecov-action@v7.1.1': + ref: 'v7.1.1' + commit: 'sha1-303a32d7a59b442fa8d48b6a1cc6825c09c847a5' + owner_id: 8226205 + repo_id: 200299178 + uses: + - 'actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd' + 'pypa/gh-action-pypi-publish@v1.14.3': + ref: 'v1.14.3' + commit: 'sha1-7245906fb61fa33a13554f9d5fb856fe61758086' + owner_id: 647025 + repo_id: 178055147 + uses: + - 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405' diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 95a95ac3..10a11f3c 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -8,8 +8,18 @@ on: jobs: lint: runs-on: ubuntu-latest + permissions: + contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Verify action lockfile + env: + GH_TOKEN: ${{ github.token }} + run: | + gh extension install github/gh-actions-lock --pin v0.4.0 + gh actions-lock --verify - run: pipx install ruff - run: ruff check src/ - run: ruff format src/ diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index cf784c78..1982e822 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -13,9 +13,9 @@ jobs: PIP_DISABLE_PIP_VERSION_CHECK: 1 strategy: matrix: - python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] + python-version: ["3.10", "3.12", "3.14", "3.14t", "3.15", "3.15t"] include: - - python-version: "3.12" + - python-version: "3.11" mariadb: 1 steps: - if: ${{ matrix.mariadb }} @@ -35,10 +35,10 @@ jobs: mysql --version mysql -uroot -proot -e "CREATE DATABASE mysqldb_test" - - uses: actions/checkout@v4 + - uses: actions/checkout@v7.0.1 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 + uses: actions/setup-python@v7.1.0 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -52,14 +52,19 @@ jobs: - name: Install test dependencies run: | pip install -r requirements.txt - + + - if: ${{ matrix.python-version == '3.12' || matrix.mariadb }} + name: Install SQLAlchemy + run: | + pip install "SQLAlchemy>=2,<3" + - name: Run tests env: TESTDB: actions.cnf run: | pytest --cov=MySQLdb tests - - uses: codecov/codecov-action@v5 + - uses: codecov/codecov-action@v7.1.1 django-test: name: "Run Django LTS test suite" @@ -68,7 +73,7 @@ jobs: env: PIP_NO_PYTHON_VERSION_WARNING: 1 PIP_DISABLE_PIP_VERSION_CHECK: 1 - DJANGO_VERSION: "4.2.16" + DJANGO_VERSION: "4.2.28" steps: - name: Start MySQL run: | @@ -78,10 +83,10 @@ jobs: mysql -uroot -proot -e "CREATE USER 'scott'@'%' IDENTIFIED BY 'tiger'; GRANT ALL ON *.* TO scott;" mysql -uroot -proot -e "CREATE DATABASE django_default; CREATE DATABASE django_other;" - - uses: actions/checkout@v4 + - uses: actions/checkout@v7.0.1 - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@v7.1.0 with: python-version: "3.12" cache: "pip" @@ -99,10 +104,11 @@ jobs: wget https://github.com/django/django/archive/${DJANGO_VERSION}.tar.gz tar xf ${DJANGO_VERSION}.tar.gz cp ci/test_mysql.py django-${DJANGO_VERSION}/tests/ + cp ci/test_mysql_executemany_multi.py django-${DJANGO_VERSION}/tests/ cd django-${DJANGO_VERSION} pip install . -r tests/requirements/py3.txt - name: Run Django test run: | cd django-${DJANGO_VERSION}/tests/ - PYTHONPATH=.. python3 ./runtests.py --settings=test_mysql + PYTHONPATH=.. python3 ./runtests.py --settings=test_mysql_executemany_multi diff --git a/.github/workflows/windows.yaml b/.github/workflows/windows.yaml index f8dbf87a..a92d4651 100644 --- a/.github/workflows/windows.yaml +++ b/.github/workflows/windows.yaml @@ -3,27 +3,42 @@ name: Build windows wheels on: push: branches: ["main", "ci"] + tags: ["v*"] pull_request: workflow_dispatch: +permissions: + contents: read + jobs: build: - runs-on: windows-latest + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + cmake_arch: x64 + cibw_arch: AMD64 + - os: windows-11-arm + cmake_arch: ARM64 + cibw_arch: ARM64 + runs-on: ${{ matrix.os }} env: - CONNECTOR_VERSION: "3.4.1" + CONNECTOR_VERSION: "3.4.9" steps: - name: Cache Connector id: cache-connector - uses: actions/cache@v4 + uses: actions/cache@v6.1.0 with: path: c:/mariadb-connector - key: mariadb-connector-c-${{ env.CONNECTOR_VERSION }}-win-2 + key: mariadb-connector-c-${{ env.CONNECTOR_VERSION }}-win-${{ matrix.cmake_arch }}-2 - name: Download and Unzip Connector if: steps.cache-connector.outputs.cache-hit != 'true' shell: bash + # zip URL should be updated by hand on each release. run: | - curl -LO "https://downloads.mariadb.com/Connectors/c/connector-c-${CONNECTOR_VERSION}/mariadb-connector-c-${CONNECTOR_VERSION}-src.zip" + curl -LO "https://dlm.mariadb.com/4751031/Connectors/c/connector-c-3.4.9/mariadb-connector-c-3.4.9-src.zip" unzip "mariadb-connector-c-${CONNECTOR_VERSION}-src.zip" -d c:/ mv "c:/mariadb-connector-c-${CONNECTOR_VERSION}-src" c:/mariadb-connector-src @@ -39,7 +54,7 @@ jobs: shell: cmd working-directory: c:/mariadb-connector-src/build run: | - cmake -A x64 .. -DCMAKE_BUILD_TYPE=Release -DCLIENT_PLUGIN_DIALOG=static -DCLIENT_PLUGIN_SHA256_PASSWORD=static -DCLIENT_PLUGIN_CACHING_SHA2_PASSWORD=static -DDEFAULT_SSL_VERIFY_SERVER_CERT=0 + cmake -A ${{ matrix.cmake_arch }} .. -DCMAKE_BUILD_TYPE=Release -DCLIENT_PLUGIN_DIALOG=static -DCLIENT_PLUGIN_SHA256_PASSWORD=static -DCLIENT_PLUGIN_CACHING_SHA2_PASSWORD=static -DDEFAULT_SSL_VERIFY_SERVER_CERT=0 - name: cmake build if: steps.cache-connector.outputs.cache-hit != 'true' @@ -56,7 +71,7 @@ jobs: cmake -DCMAKE_INSTALL_PREFIX=c:/mariadb-connector -DCMAKE_INSTALL_COMPONENT=Development -DCMAKE_BUILD_TYPE=Release -P cmake_install.cmake - name: Checkout mysqlclient - uses: actions/checkout@v4 + uses: actions/checkout@v7.0.1 with: path: mysqlclient @@ -73,25 +88,49 @@ jobs: EOF cat site.cfg - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7.1.0 - name: Install cibuildwheel run: python -m pip install cibuildwheel - name: Build wheels working-directory: mysqlclient env: - CIBW_PROJECT_REQUIRES_PYTHON: ">=3.9" - CIBW_ARCHS: "AMD64" + CIBW_PROJECT_REQUIRES_PYTHON: ">=3.10" + CIBW_ARCHS: ${{ matrix.cibw_arch }} CIBW_TEST_COMMAND: 'python -c "import MySQLdb; print(MySQLdb.version_info)" ' - run: "python -m cibuildwheel --prerelease-pythons --output-dir dist" + run: "python -m cibuildwheel --output-dir dist" - name: Build sdist + if: matrix.cibw_arch == 'AMD64' working-directory: mysqlclient run: | python -m pip install build python -m build -s -o dist - name: Upload Wheel - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7.0.2 with: - name: win-wheels + name: win-wheels-${{ matrix.cibw_arch }} path: mysqlclient/dist/*.* + if-no-files-found: error + + publish: + name: Publish to PyPI + needs: build + if: >- + github.event_name == 'push' && github.event.created && + startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Download distributions + uses: actions/download-artifact@v8.0.2 + with: + pattern: win-wheels-* + path: dist + merge-multiple: true + + - name: Publish distributions to PyPI + uses: pypa/gh-action-pypi-publish@v1.14.3 + with: + attestations: true diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 0b288620..75d7a389 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -1,9 +1,12 @@ version: 2 +sphinx: + configuration: doc/conf.py + build: os: ubuntu-22.04 tools: - python: "3.11" + python: "3.13" apt_packages: - default-libmysqlclient-dev diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..9208c096 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,68 @@ +## Checks before committing + +Run commands from the repository root. Format and lint the source before +committing: + +```sh +ruff format src/ +ruff check src/ +git diff --check +``` + +## Running the mysqlclient test suite + +The CI configuration is in [.github/workflows/tests.yaml](.github/workflows/tests.yaml). +The package is in `src/MySQLdb/` and the tests are in `tests/`. + +1. Install a C compiler, Python development headers, `pkg-config`, and MySQL or + MariaDB client development libraries, as described in [README.md](README.md). + A running MySQL or MariaDB server is also required for database tests. + +2. In a Python virtual environment, install the package and test dependencies: + + ```sh + python -m pip install -v . + python -m pip install -r requirements.txt + python -m pip install "SQLAlchemy>=2,<3" + ``` + + SQLAlchemy is needed to run `tests/test_sqlalchemy.py`; those tests are + skipped if it is not installed. + +3. Start the database server using the service manager available in your + environment. In containers without a service manager, run `mysqld` in a + separate, long-lived terminal with an initialized data directory and writable + socket and PID file locations. + + Create a dedicated test database using an administrator connection, for example: + + ```sh + mysql -uroot -p -e "CREATE DATABASE IF NOT EXISTS mysqldb_test" + ``` + + The test user needs to create, alter, and drop tables, run `SELECT`, + `INSERT`, `UPDATE`, and `DELETE`, and create, execute, and drop stored + procedures in that database. + `tests/actions.cnf` uses `127.0.0.1:3306`, user `root`, password `root`, and + database `mysqldb_test`. For different credentials, create a separate MySQL + option file with a `[MySQLdb-tests]` group, using `tests/actions.cnf` as a + template. + +4. Run the same pytest command as CI: + + ```sh + TESTDB=actions.cnf pytest --cov=MySQLdb tests + ``` + + `TESTDB` selects a filename under `tests/` or an absolute path to an option + file. Without it, `tests/default.cnf` is used. The tests create and drop + tables, so use the dedicated test database. + +CI also runs the Django test suite in a separate job. Refer to +`.github/workflows/tests.yaml` for its dependencies, database setup, and +`test_mysql_executemany_multi` settings. + +## Releases + +Follow [notes/release.md](notes/release.md) for version updates, release CI, +tagging, and publication. diff --git a/HISTORY.rst b/HISTORY.rst index 66470541..837f4141 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -1,3 +1,104 @@ +====================== + What's new in 2.3.2 +====================== + +Release: 2026-11-18 + +* Restore the use of the base type's literal conversion for subclasses of + ``str``, ``bytes``, and ``bytearray``. This fixes a regression in 2.3.1 where string-valued + ``enum.Enum`` members were serialized using their enum names instead of their + string values. (#814) + +* Avoid a spurious ``ProgrammingError`` when another thread drops the last + reference to a buffered result while the connection is in use. (#815) + +* Escape the contents of ``bytearray`` query parameters the same way as + ``bytes``. Previously, passing ``bytearray(b'ab')`` sent the Python string + representation to the server. This also applies to subclasses. (#817) + + +====================== + What's new in 2.3.1 +====================== + +Release: 2026-11-10 + +* **Security fix:** Escape Python ``set`` query parameters using the connection's + character set and SQL mode. This fixes SQL injection when + ``NO_BACKSLASH_ESCAPES`` is enabled and an attacker controls a set member. + ``frozenset`` parameters now use the same escaping. + See `GHSA-m9c3-99x3-77g6 `_. + +* Deprecate ``MySQLdb.converters.Set2Str``. + +* ``Connection.literal()`` now applies built-in handling only to exact built-in + types. Subclasses use the connection's converter mapping. + +* Fix crashes when looking up connection attributes with a non-string name or + a string containing lone surrogates. (#810) + + +====================== + What's new in 2.3.0 +====================== + +Release: 2026-09-07 + +* Concurrent use of the same Connection object from multiple threads now + raises ``ProgrammingError`` immediately instead of causing undefined + behavior. + Applications should use separate connections for concurrent operations. + (#781) + +* Add an optional ``executemany_fallback="multi"`` connection option. + When enabled, ``Cursor.executemany()`` can batch eligible INSERT, REPLACE, + UPDATE, and DELETE statements into multi-statement queries instead of + executing them one at a time. This can significantly improve performance of + operations such as SQLAlchemy bulk UPDATEs. The default remains "loop", + and the existing multi-row INSERT/REPLACE optimization is unchanged. (#798) + +* Add ``Cursor.warning_count`` to expose the warning count for the last + statement. (#780) + +* Make ``Cursor`` itself an iterator as specified by DB-API 2.0. + ``iter(cursor) is cursor`` and ``next(cursor)`` fetches the next row. (#785) + +* Quote stored procedure names and user variable names in ``Cursor.callproc()``, + allowing names containing reserved words or special characters. (#789) + +* Fix conversion of ``datetime.timedelta`` values to support microseconds and + negative values correctly. (#795) + +* Add Windows ARM64 wheels. (#796) + +* Test with Python 3.15 and free-threaded Python 3.15, and update the MariaDB + Connector/C used for Windows wheels to 3.4.9. (#797) + +* Add ``Connection.more_results()`` for checking whether additional results + remain after a multi-statement query. (#798) + +* Deprecate accessing exception classes such as ``ProgrammingError`` and + ``OperationalError`` as ``Cursor`` attributes. Access them from the + ``MySQLdb`` package instead. (#782) + +* Deprecate the ``reconnect`` parameter of ``Connection.ping()``. Calling + ``ping()`` without the parameter is unchanged. (#790) + + +====================== + What's new in 2.2.8 +====================== + +Release: 2026-02-10 + +* Add ``local_infile_dir`` option to restrict LOAD DATA LOCAL INFILE file path. (#755) +* windows wheel: Update mariadb-connector to 3.4.8 (#773) +* Add Python 3.14 and drop Python 3.8, 3.9 support. (#774) +* Experimental support for free threaded Python. Importing ``MySQLdb`` doesn't + enable the GIL anymore. This doesn't mean mysqlclient is thread safe. + You must not use same connection object from multiple threads concurrently. (#775) + + ====================== What's new in 2.2.7 ====================== diff --git a/README.md b/README.md index e679b533..9bc2fd43 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,17 @@ Or when you have question about MySQL/MariaDB: * [MySQL Support](https://dev.mysql.com/support/) * [Getting Help With MariaDB](https://mariadb.com/kb/en/getting-help-with-mariadb/) +## Free threading Python + +> [!NOTE] +> The support for Free threading Python is experimental. + +Since v2.2.8, free threading is supported when importing the extension module. Therefore, importing MySQLdb does not acquire GIL. + +However, this library does not support simultaneous operations on a single Connection object from multiple threads, regardless of free threading, and the behavior in such cases remains undefined. + +> [!WARNING] +> Do not use a single Connection object from multiple threads simultaneously. ## Install diff --git a/SECURITY.md b/SECURITY.md index 75f0c541..c4f4366a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,5 +1,10 @@ -## Security contact information +## Reporting a security vulnerability -To report a security vulnerability, please use the -[Tidelift security contact](https://tidelift.com/security). -Tidelift will coordinate the fix and disclosure. \ No newline at end of file +If you discover a security vulnerability in mysqlclient, please report it +privately using [GitHub's private vulnerability reporting](https://github.com/PyMySQL/mysqlclient/security/advisories/new). + +Please do not disclose vulnerability details in public issues, pull requests, +or discussions. + +The maintainers will use GitHub Security Advisories to investigate reports, +coordinate fixes, and manage disclosure. \ No newline at end of file diff --git a/ci/test_mysql_executemany_multi.py b/ci/test_mysql_executemany_multi.py new file mode 100644 index 00000000..4c585ce7 --- /dev/null +++ b/ci/test_mysql_executemany_multi.py @@ -0,0 +1,5 @@ +from test_mysql import * # noqa: F403 + + +for database in DATABASES.values(): # noqa: F405 + database.setdefault("OPTIONS", {})["executemany_fallback"] = "multi" diff --git a/doc/user_guide.rst b/doc/user_guide.rst index 8c76417b..82080521 100644 --- a/doc/user_guide.rst +++ b/doc/user_guide.rst @@ -72,6 +72,7 @@ MySQL C API function mapping ``mysql_get_server_info()`` ``conn.get_server_info()`` ``mysql_info()`` ``conn.info()`` ``mysql_insert_id()`` ``conn.insert_id()`` + ``mysql_more_results()`` ``conn.more_results()`` ``mysql_num_fields()`` ``result.num_fields()`` ``mysql_num_rows()`` ``result.num_rows()`` ``mysql_options()`` various options to ``_mysql.connect()`` @@ -321,6 +322,27 @@ connect(parameters...) overridden. Default: ``MySQLdb.cursors.Cursor``. *This must be a keyword parameter.* + executemany_fallback + Controls how ``Cursor.executemany()`` handles statements that + cannot use the multi-row INSERT/REPLACE optimization. ``"loop"`` + executes the statements one at a time and is the default. + ``"multi"`` may combine safe data manipulation statements into a + multi-statement query. If multi-statements are disabled or a query + is not eligible, execution silently falls back to ``"loop"``. + + This is a connection option so it can be passed through, for + example, SQLAlchemy's ``connect_args`` or Django's database + ``OPTIONS``:: + + create_engine( + "mysql+mysqldb://user:password@host/database", + connect_args={"executemany_fallback": "multi"}, + ) + + DATABASES["default"]["OPTIONS"]["executemany_fallback"] = "multi" + + See ``executemany()`` below for batching and transaction details. + use_unicode If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is @@ -396,6 +418,17 @@ connect(parameters...) server_public_key_path specifies path to a RSA public key used by caching sha2 password authentication. See https://dev.mysql.com/doc/refman/9.0/en/caching-sha2-pluggable-authentication.html + + local_infile + sets ``MYSQL_OPT_LOCAL_INFILE`` in ``mysql_options()`` enabling LOAD LOCAL INFILE from any path; zero disables; + + *This must be a keyword parameter.* + + local_infile_dir + sets ``MYSQL_OPT_LOAD_DATA_LOCAL_DIR`` in ``mysql_options()`` enabling LOAD LOCAL INFILE from any path; + if ``local_infile`` is set to ``True`` then this is ignored; + + *This must be a keyword parameter.* .. _mysql_ssl_set: http://dev.mysql.com/doc/refman/en/mysql-ssl-set.html @@ -551,6 +584,31 @@ close() close the cursor when you are done with it and before creating a new one. +executemany(operation, seq_of_params) + Executes an operation for every parameter set and returns the total + number of affected rows. Multi-row INSERT and REPLACE statements use + MySQLdb's existing single-statement ``VALUES`` rewrite whenever it + applies, independently of ``executemany_fallback``. + + With ``executemany_fallback="multi"``, statements that do not match that + rewrite may instead be sent in multi-statement batches. This applies only + to SQL templates which begin with INSERT, REPLACE, UPDATE, or DELETE + (ignoring leading whitespace), contain no semicolon, and contain no + ``RETURNING`` clause. Other statements, including statements beginning + with a comment or ``WITH``, use the normal loop. The loop is also used + silently when the connection does not have multi-statements enabled. + + Each batch is limited to 16000 encoded bytes, including separators, and + 200 statements. A single rendered statement exceeding the byte limit is + executed alone. On successful completion, ``rowcount`` and the return + value are the sum of the affected-row counts for all statements. + + Batching does not create an implicit transaction and is not atomic. If a + statement fails, statements before it may already have executed, while + statements after it do not execute. Applications needing all-or-nothing + behavior must manage a transaction explicitly; with autocommit enabled, + each statement may be committed independently. + info() Returns some information about the last query. Normally you don't need to check this. If there are any MySQL diff --git a/notes/release.md b/notes/release.md new file mode 100644 index 00000000..4081f3fb --- /dev/null +++ b/notes/release.md @@ -0,0 +1,105 @@ +# Release procedure + +The examples below release **2.3.1** after **2.3.0**. Replace the version +numbers and release date as needed. Run commands from the repository root. + +Ensure the PyPI Trusted Publisher for `mysqlclient` is configured with +repository `PyMySQL/mysqlclient`, workflow `windows.yaml`, and no required +environment name. + +## 1. Update the release notes + +Review the changes since the previous release: + +```sh +git log v2.3.0..HEAD --oneline +git diff v2.3.0..HEAD --stat +``` + +Add a `What's new in 2.3.1` section at the top of +[HISTORY.rst](../HISTORY.rst), with `Release: YYYY-MM-DD` set to the release +date. Document changes, fixes, and deprecations that affect users. + +## 2. Update the version and create a release PR + +Update both version fields in +[src/MySQLdb/release.py](../src/MySQLdb/release.py): + +```python +__version__ = "2.3.1" +version_info = (2, 3, 1, "final", 0) +``` + +Format the source and run the checks: + +```sh +ruff format src/ +ruff check src/ +git diff --check +``` + +Review the diff, commit it as `release v2.3.1`, and open a PR targeting +`main` in `PyMySQL/mysqlclient`. + +## 3. Verify CI for the release commit + +Once the PR checks pass, merge it into `main`. Verify that all of the +following workflows pass for the merged commit: + +- `Lint` +- `Test`, including MySQL, MariaDB, and Django tests +- `Build windows wheels` + +To run the tests locally, install the package and the dependencies in +`requirements.txt`, prepare the database, and run the command used by the +[test workflow](../.github/workflows/tests.yaml). Adjust `TESTDB` to use +the configuration for your database: + +```sh +TESTDB=actions.cnf pytest --cov=MySQLdb tests +``` + +Verify that the [Windows workflow](../.github/workflows/windows.yaml) +produces both `win-wheels-AMD64` and `win-wheels-ARM64` artifacts. The AMD64 +artifact also contains the source distribution (sdist). + +Record the release commit SHA. + +## 4. Create and push the release tag + +Replace `RELEASE_SHA` with the commit SHA verified in step 3. Fetch the +commit, create a lightweight tag, and push it: + +```sh +git fetch upstream main --tags +git tag v2.3.1 RELEASE_SHA +git push upstream refs/tags/v2.3.1 +``` + +Pushing the new `v*` tag starts a build of the tagged commit. Once both +Windows builds succeed, the `Publish to PyPI` job combines their artifacts +and publishes the wheels and sdist using Trusted Publishing. +Publishing is restricted to push events that create a new `v*` tag. + +## 5. Verify publication and create the GitHub Release + +Check the tag-triggered `Build windows wheels` workflow and confirm that +both builds and the `Publish to PyPI` job succeed. Then create the GitHub +Release: + +```sh +gh release create v2.3.1 -R PyMySQL/mysqlclient \ + --verify-tag --title v2.3.1 \ + --generate-notes --notes-start-tag v2.3.0 +``` + +## 6. Verify the published release + +Check that PyPI lists the sdist and wheels for both architectures. Install +`mysqlclient==2.3.1` in a fresh environment and verify the import and version: + +```sh +python -c 'import MySQLdb; print(MySQLdb.version_info)' +``` + +The expected output is `(2, 3, 1, 'final', 0)`. diff --git a/pyproject.toml b/pyproject.toml index d786f336..9deedef3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,16 +2,15 @@ name = "mysqlclient" description = "Python interface to MySQL" readme = "README.md" -requires-python = ">=3.8" +requires-python = ">=3.10" authors = [ {name = "Inada Naoki", email = "songofacandy@gmail.com"} ] -license = {text = "GNU General Public License v2 or later (GPLv2+)"} +license = "GPL-2.0-or-later" keywords = ["MySQL"] classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Other Environment", - "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows :: Windows NT/2000", "Operating System :: OS Independent", @@ -21,12 +20,11 @@ classifiers = [ "Programming Language :: C", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Topic :: Database", "Topic :: Database :: Database Engines/Servers", ] @@ -37,7 +35,7 @@ Project = "https://github.com/PyMySQL/mysqlclient" Documentation = "https://mysqlclient.readthedocs.io/" [build-system] -requires = ["setuptools>=61"] +requires = ["setuptools>=77"] build-backend = "setuptools.build_meta" [tool.setuptools] diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 00000000..2cfed8b2 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,13 @@ +[lint] +ignore = [ + "BLE001", + "DTZ001", + "EXE001", + "FLY002", + "N999", + "RUF012", + "S102", + "SIM115", + "TRY002", + "UP031", +] diff --git a/setup.py b/setup.py index 9a1d26b8..84451670 100644 --- a/setup.py +++ b/setup.py @@ -2,10 +2,9 @@ import os import subprocess import sys - -import setuptools from configparser import ConfigParser +import setuptools release_info = {} with open("src/MySQLdb/release.py", encoding="utf-8") as f: @@ -70,11 +69,11 @@ def get_config_posix(options=None): ("__version__", release_info["__version__"]), ] - ext_options = dict( - extra_compile_args=cflags, - extra_link_args=ldflags, - define_macros=define_macros, - ) + ext_options = { + "extra_compile_args": cflags, + "extra_link_args": ldflags, + "define_macros": define_macros, + } # newer versions of gcc require libstdc++ if doing a static build if static: ext_options["language"] = "c++" @@ -120,14 +119,14 @@ def get_config_win32(options): ("__version__", release_info["__version__"]), ] - ext_options = dict( - library_dirs=library_dirs, - libraries=libraries, - extra_link_args=extra_link_args, - include_dirs=include_dirs, - extra_objects=extra_objects, - define_macros=define_macros, - ) + ext_options = { + "library_dirs": library_dirs, + "libraries": libraries, + "extra_link_args": extra_link_args, + "include_dirs": include_dirs, + "extra_objects": extra_objects, + "define_macros": define_macros, + } return ext_options diff --git a/src/MySQLdb/__init__.py b/src/MySQLdb/__init__.py index 153bbdfe..ffe583fe 100644 --- a/src/MySQLdb/__init__.py +++ b/src/MySQLdb/__init__.py @@ -13,8 +13,8 @@ MySQLdb.converters module. """ -from .release import version_info from . import _mysql +from .release import version_info if version_info != _mysql.version_info: raise ImportError( @@ -24,32 +24,33 @@ ) -from ._mysql import ( - NotSupportedError, - OperationalError, - get_client_info, - ProgrammingError, - Error, - InterfaceError, - debug, - IntegrityError, - string_literal, - MySQLError, - DataError, - DatabaseError, - InternalError, - Warning, -) from MySQLdb.constants import FIELD_TYPE from MySQLdb.times import ( Date, - Time, - Timestamp, DateFromTicks, + Time, TimeFromTicks, + Timestamp, TimestampFromTicks, ) +from ._mysql import ( + DatabaseError, + DataError, + Error, + IntegrityError, + InterfaceError, + InternalError, + MySQLError, + NotSupportedError, + OperationalError, + ProgrammingError, + Warning, + debug, + get_client_info, + string_literal, +) + threadsafety = 1 apilevel = "2.0" paramstyle = "format" @@ -95,7 +96,7 @@ def __eq__(self, other): def test_DBAPISet_set_equality(): - assert STRING == STRING + assert STRING == STRING # noqa def test_DBAPISet_set_inequality(): @@ -125,33 +126,33 @@ def Connect(*args, **kwargs): __all__ = [ "BINARY", + "DATE", + "FIELD_TYPE", + "NUMBER", + "ROWID", + "STRING", + "TIME", + "TIMESTAMP", "Binary", "Connect", "Connection", - "DATE", - "Date", - "Time", - "Timestamp", - "DateFromTicks", - "TimeFromTicks", - "TimestampFromTicks", + "DBAPISet", "DataError", "DatabaseError", + "Date", + "DateFromTicks", "Error", - "FIELD_TYPE", "IntegrityError", "InterfaceError", "InternalError", "MySQLError", - "NUMBER", "NotSupportedError", - "DBAPISet", "OperationalError", "ProgrammingError", - "ROWID", - "STRING", - "TIME", - "TIMESTAMP", + "Time", + "TimeFromTicks", + "Timestamp", + "TimestampFromTicks", "Warning", "apilevel", "connect", diff --git a/src/MySQLdb/_mysql.c b/src/MySQLdb/_mysql.c index d6df4df8..7b54b575 100644 --- a/src/MySQLdb/_mysql.c +++ b/src/MySQLdb/_mysql.c @@ -48,6 +48,10 @@ PERFORMANCE OF THIS SOFTWARE. #define HAVE_MYSQL_SERVER_PUBLIC_KEY #endif +#if !defined(MARIADB_VERSION_ID) && MYSQL_VERSION_ID >= 80021 +#define HAVE_MYSQL_OPT_LOCAL_INFILE_DIR +#endif + #define PY_SSIZE_T_CLEAN 1 #include "Python.h" @@ -80,15 +84,10 @@ typedef struct { bool open; bool reconnect; PyObject *converter; + PyThread_type_lock lock; } _mysql_ConnectionObject; -#define check_connection(c) \ - if (!(c->open)) { \ - return _mysql_Exception(c); \ - }; - #define result_connection(r) ((_mysql_ConnectionObject *)r->conn) -#define check_result_connection(r) check_connection(result_connection(r)) extern PyTypeObject _mysql_ConnectionObject_Type; @@ -105,6 +104,67 @@ typedef struct { extern PyTypeObject _mysql_ResultObject_Type; +static int +_mysql_ConnectionObject_AllocateLock(_mysql_ConnectionObject *self) +{ + self->lock = PyThread_allocate_lock(); + if (self->lock == NULL) { + PyErr_NoMemory(); + return -1; + } + return 0; +} + +/* Try to acquire the connection lock without blocking. + * Returns 0 on success, -1 if the lock is already held by another thread + * (ProgrammingError is set). */ +static int +_mysql_ConnectionObject_Lock(_mysql_ConnectionObject *self) +{ + PyLockStatus status = PyThread_acquire_lock(self->lock, NOWAIT_LOCK); + if (status != PY_LOCK_ACQUIRED) { + PyErr_SetString(_mysql_ProgrammingError, + "This connection is already in use from another thread. " + "Do not use the same connection object from multiple threads simultaneously."); + return -1; + } + return 0; +} + +/* Blocking variant used only during deallocation where we must acquire the + * lock to call mysql_free_result() even if it means waiting. */ +static void +_mysql_ConnectionObject_LockWait(_mysql_ConnectionObject *self) +{ + Py_BEGIN_ALLOW_THREADS + PyThread_acquire_lock(self->lock, WAIT_LOCK); + Py_END_ALLOW_THREADS +} + +static void +_mysql_ConnectionObject_Unlock(_mysql_ConnectionObject *self) +{ + PyThread_release_lock(self->lock); +} + +#define BEGIN_CONNECTION_LOCK(c) _mysql_ConnectionObject_Lock(c) +#define END_CONNECTION_LOCK(c) _mysql_ConnectionObject_Unlock(c) + +#define BEGIN_RESULT_CONNECTION_LOCK(r) \ + _mysql_ConnectionObject_LockWait(result_connection(r)) +#define END_RESULT_CONNECTION_LOCK(r) \ + END_CONNECTION_LOCK(result_connection(r)) +#define BEGIN_CONNECTION_OPERATION(c, on_closed) \ + do { \ + if (_mysql_ConnectionObject_Lock(c) < 0) return NULL; \ + if (!(c)->open) { \ + END_CONNECTION_LOCK(c); \ + on_closed; \ + } \ + } while (0) +#define BEGIN_RESULT_OPERATION(r, on_closed) \ + BEGIN_CONNECTION_OPERATION(result_connection(r), on_closed) + PyObject * _mysql_Exception(_mysql_ConnectionObject *c) @@ -240,7 +300,7 @@ _get_encoding(MYSQL *mysql) return cs.csname; } -static char _mysql_ResultObject__doc__[] = +static const char _mysql_ResultObject__doc__[] = "result(connection, use=0, converter={}) -- Result set from a query.\n\ \n\ Creating instances of this class directly is an excellent way to\n\ @@ -267,9 +327,31 @@ _mysql_ResultObject_Initialize( &_mysql_ConnectionObject_Type, &conn, &use, &conv)) return -1; - self->conn = (PyObject *) conn; - Py_INCREF(conn); + /* A result keeps its original connection and buffering mode until deallocation. */ + bool already_initialized; +#ifdef Py_GIL_DISABLED + Py_BEGIN_CRITICAL_SECTION(self); +#endif + already_initialized = self->conn != NULL; + if (!already_initialized) { + self->conn = Py_NewRef(conn); + } +#ifdef Py_GIL_DISABLED + Py_END_CRITICAL_SECTION(); +#endif + if (already_initialized) { + PyErr_SetString(_mysql_ProgrammingError, "Result is already initialized"); + return -1; + } self->use = use; + if (BEGIN_CONNECTION_LOCK(conn) < 0) { + return -1; + } + if (!conn->open) { + END_CONNECTION_LOCK(conn); + _mysql_Exception(conn); + return -1; + } Py_BEGIN_ALLOW_THREADS ; if (use) result = mysql_use_result(&(conn->connection)); @@ -280,6 +362,7 @@ _mysql_ResultObject_Initialize( Py_END_ALLOW_THREADS ; self->encoding = _get_encoding(&(conn->connection)); + END_CONNECTION_LOCK(conn); //fprintf(stderr, "encoding=%s\n", self->encoding); if (!result) { if (mysql_errno(&(conn->connection))) { @@ -436,7 +519,7 @@ _mysql_ConnectionObject_Initialize( "client_flag", "ssl", "ssl_mode", "local_infile", "read_timeout", "write_timeout", "charset", - "auth_plugin", "server_public_key_path", + "auth_plugin", "server_public_key_path", "local_infile_dir", NULL } ; int connect_timeout = 0; int read_timeout = 0; @@ -448,14 +531,16 @@ _mysql_ConnectionObject_Initialize( *read_default_group=NULL, *charset=NULL, *auth_plugin=NULL, - *server_public_key_path=NULL; + *server_public_key_path=NULL, + *local_infile_dir=NULL; self->converter = NULL; self->open = false; self->reconnect = false; + self->lock = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "|ssssisOiiisssiOsiiisss:connect", + "|ssssisOiiisssiOsiiissss:connect", kwlist, &host, &user, &passwd, &db, &port, &unix_socket, &conv, @@ -469,16 +554,28 @@ _mysql_ConnectionObject_Initialize( &write_timeout, &charset, &auth_plugin, - &server_public_key_path + &server_public_key_path, + &local_infile_dir )) return -1; + if (_mysql_ConnectionObject_AllocateLock(self)) { + return -1; + } + #ifndef HAVE_MYSQL_SERVER_PUBLIC_KEY if (server_public_key_path) { PyErr_SetString(_mysql_NotSupportedError, "server_public_key_path is not supported"); return -1; } #endif + +#ifndef HAVE_MYSQL_OPT_LOCAL_INFILE_DIR + if (local_infile_dir) { + PyErr_SetString(_mysql_NotSupportedError, "local_infile_dir is not supported"); + return -1; + } +#endif // For compatibility with PyPy, we need to keep strong reference // to unicode objects until we use UTF8. #define _stringsuck(d,t,s) {t=PyMapping_GetItemString(s,#d);\ @@ -599,6 +696,12 @@ _mysql_ConnectionObject_Initialize( } #endif +#ifdef HAVE_MYSQL_OPT_LOCAL_INFILE_DIR + if (local_infile_dir) { + mysql_options(&(self->connection), MYSQL_OPT_LOAD_DATA_LOCAL_DIR, local_infile_dir); + } +#endif + Py_BEGIN_ALLOW_THREADS conn = mysql_real_connect(&(self->connection), host, user, passwd, db, port, unix_socket, client_flag); @@ -628,7 +731,7 @@ _mysql_ConnectionObject_Initialize( return 0; } -static char _mysql_connect__doc__[] = +static const char _mysql_connect__doc__[] = "Returns a MYSQL connection object. Exclusive use of\n\ keyword parameters strongly recommended. Consult the\n\ MySQL C API documentation for more details.\n\ @@ -717,7 +820,7 @@ static int _mysql_ConnectionObject_clear( return 0; } -static char _mysql_ConnectionObject_close__doc__[] = +static const char _mysql_ConnectionObject_close__doc__[] = "Close the connection. No further activity possible."; static PyObject * @@ -725,16 +828,17 @@ _mysql_ConnectionObject_close( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS mysql_close(&(self->connection)); Py_END_ALLOW_THREADS self->open = false; _mysql_ConnectionObject_clear(self); + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_affected_rows__doc__ [] = +static const char _mysql_ConnectionObject_affected_rows__doc__ [] = "Return number of rows affected by the last query.\n\ Non-standard. Use Cursor.rowcount.\n\ "; @@ -745,14 +849,15 @@ _mysql_ConnectionObject_affected_rows( PyObject *noargs) { my_ulonglong ret; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); ret = mysql_affected_rows(&(self->connection)); + END_CONNECTION_LOCK(self); if (ret == (my_ulonglong)-1) return PyLong_FromLong(-1); return PyLong_FromUnsignedLongLong(ret); } -static char _mysql_debug__doc__[] = +static const char _mysql_debug__doc__[] = "Does a DBUG_PUSH with the given string.\n\ mysql_debug() uses the Fred Fish debug library.\n\ To use this function, you must compile the client library to\n\ @@ -769,7 +874,7 @@ _mysql_debug( Py_RETURN_NONE; } -static char _mysql_ConnectionObject_dump_debug_info__doc__[] = +static const char _mysql_ConnectionObject_dump_debug_info__doc__[] = "Instructs the server to write some debug information to the\n\ log. The connected user must have the process privilege for\n\ this to work. Non-standard.\n\ @@ -781,15 +886,20 @@ _mysql_ConnectionObject_dump_debug_info( PyObject *noargs) { int err; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_dump_debug_info(&(self->connection)); Py_END_ALLOW_THREADS - if (err) return _mysql_Exception(self); + if (err) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_autocommit__doc__[] = +static const char _mysql_ConnectionObject_autocommit__doc__[] = "Set the autocommit mode. True values enable; False value disable.\n\ "; static PyObject * @@ -799,15 +909,20 @@ _mysql_ConnectionObject_autocommit( { int flag, err; if (!PyArg_ParseTuple(args, "i", &flag)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_autocommit(&(self->connection), flag); Py_END_ALLOW_THREADS - if (err) return _mysql_Exception(self); + if (err) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_get_autocommit__doc__[] = +static const char _mysql_ConnectionObject_get_autocommit__doc__[] = "Get the autocommit mode. True when enable; False when disable.\n"; static PyObject * @@ -815,14 +930,16 @@ _mysql_ConnectionObject_get_autocommit( _mysql_ConnectionObject *self, PyObject *args) { - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); if (self->connection.server_status & SERVER_STATUS_AUTOCOMMIT) { + END_CONNECTION_LOCK(self); Py_RETURN_TRUE; } + END_CONNECTION_LOCK(self); Py_RETURN_FALSE; } -static char _mysql_ConnectionObject_commit__doc__[] = +static const char _mysql_ConnectionObject_commit__doc__[] = "Commits the current transaction\n\ "; static PyObject * @@ -831,15 +948,20 @@ _mysql_ConnectionObject_commit( PyObject *noargs) { int err; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_commit(&(self->connection)); Py_END_ALLOW_THREADS - if (err) return _mysql_Exception(self); + if (err) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_rollback__doc__[] = +static const char _mysql_ConnectionObject_rollback__doc__[] = "Rolls back the current transaction\n\ "; static PyObject * @@ -848,15 +970,20 @@ _mysql_ConnectionObject_rollback( PyObject *noargs) { int err; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_rollback(&(self->connection)); Py_END_ALLOW_THREADS - if (err) return _mysql_Exception(self); + if (err) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_next_result__doc__[] = +static const char _mysql_ConnectionObject_next_result__doc__[] = "If more query results exist, next_result() reads the next query\n\ results and returns the status back to application.\n\ \n\ @@ -869,22 +996,49 @@ Returns 0 if there are more results; -1 if there are no more results\n\ \n\ Non-standard.\n\ "; + +static const char _mysql_ConnectionObject_more_results__doc__[] = +"Returns True if one or more results follow the current result of a\n\ +multi-statement query. This check does not advance to the next result.\n\ +\n\ +Non-standard.\n\ +"; + +static PyObject * +_mysql_ConnectionObject_more_results( + _mysql_ConnectionObject *self, + PyObject *noargs) +{ + int ret; + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + ret = mysql_more_results(&(self->connection)); + END_CONNECTION_LOCK(self); + if (ret) + Py_RETURN_TRUE; + Py_RETURN_FALSE; +} + static PyObject * _mysql_ConnectionObject_next_result( _mysql_ConnectionObject *self, PyObject *noargs) { int err; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_next_result(&(self->connection)); Py_END_ALLOW_THREADS - if (err > 0) return _mysql_Exception(self); + if (err > 0) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); return PyLong_FromLong(err); } -static char _mysql_ConnectionObject_set_server_option__doc__[] = +static const char _mysql_ConnectionObject_set_server_option__doc__[] = "set_server_option(option) -- Enables or disables an option\n\ for the connection.\n\ \n\ @@ -898,15 +1052,20 @@ _mysql_ConnectionObject_set_server_option( int err, flags=0; if (!PyArg_ParseTuple(args, "i", &flags)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_set_server_option(&(self->connection), flags); Py_END_ALLOW_THREADS - if (err) return _mysql_Exception(self); + if (err) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); return PyLong_FromLong(err); } -static char _mysql_ConnectionObject_sqlstate__doc__[] = +static const char _mysql_ConnectionObject_sqlstate__doc__[] = "Returns a string containing the SQLSTATE error code\n\ for the last error. The error code consists of five characters.\n\ '00000' means \"no error.\" The values are specified by ANSI SQL\n\ @@ -923,11 +1082,14 @@ _mysql_ConnectionObject_sqlstate( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyUnicode_FromString(mysql_sqlstate(&(self->connection))); + PyObject *ret; + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + ret = PyUnicode_FromString(mysql_sqlstate(&(self->connection))); + END_CONNECTION_LOCK(self); + return ret; } -static char _mysql_ConnectionObject_warning_count__doc__[] = +static const char _mysql_ConnectionObject_warning_count__doc__[] = "Returns the number of warnings generated during execution\n\ of the previous SQL statement.\n\ \n\ @@ -938,11 +1100,14 @@ _mysql_ConnectionObject_warning_count( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyLong_FromLong(mysql_warning_count(&(self->connection))); + unsigned int count; + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + count = mysql_warning_count(&(self->connection)); + END_CONNECTION_LOCK(self); + return PyLong_FromLong(count); } -static char _mysql_ConnectionObject_errno__doc__[] = +static const char _mysql_ConnectionObject_errno__doc__[] = "Returns the error code for the most recently invoked API function\n\ that can succeed or fail. A return value of zero means that no error\n\ occurred.\n\ @@ -953,11 +1118,14 @@ _mysql_ConnectionObject_errno( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyLong_FromLong((long)mysql_errno(&(self->connection))); + unsigned int err; + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + err = mysql_errno(&(self->connection)); + END_CONNECTION_LOCK(self); + return PyLong_FromLong((long)err); } -static char _mysql_ConnectionObject_error__doc__[] = +static const char _mysql_ConnectionObject_error__doc__[] = "Returns the error message for the most recently invoked API function\n\ that can succeed or fail. An empty string ("") is returned if no error\n\ occurred.\n\ @@ -968,11 +1136,14 @@ _mysql_ConnectionObject_error( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyUnicode_FromString(mysql_error(&(self->connection))); + PyObject *ret; + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + ret = PyUnicode_FromString(mysql_error(&(self->connection))); + END_CONNECTION_LOCK(self); + return ret; } -static char _mysql_escape_string__doc__[] = +static const char _mysql_escape_string__doc__[] = "escape_string(s) -- quote any SQL-interpreted characters in string s.\n\ \n\ Use connection.escape_string(s), if you use it at all.\n\ @@ -989,6 +1160,7 @@ _mysql_escape_string( char *in, *out; unsigned long len; Py_ssize_t size; + int use_connection = 0; if (!PyArg_ParseTuple(args, "s#:escape_string", &in, &size)) return NULL; str = PyBytes_FromStringAndSize((char *) NULL, size*2+1); if (!str) return PyErr_NoMemory(); @@ -996,7 +1168,14 @@ _mysql_escape_string( if (self && PyModule_Check((PyObject*)self)) self = NULL; - if (self && self->open) { + if (self) { + if (BEGIN_CONNECTION_LOCK(self) < 0) { + Py_DECREF(str); + return NULL; + } + use_connection = self->open; + } + if (use_connection) { #if MYSQL_VERSION_ID >= 50707 && !defined(MARIADB_BASE_VERSION) && !defined(MARIADB_VERSION_ID) len = mysql_real_escape_string_quote(&(self->connection), out, in, size, '\''); #else @@ -1005,16 +1184,18 @@ _mysql_escape_string( } else { len = mysql_escape_string(out, in, size); } + if (self) { + END_CONNECTION_LOCK(self); + } if (_PyBytes_Resize(&str, len) < 0) return NULL; return (str); } -static char _mysql_string_literal__doc__[] = +static const char _mysql_string_literal__doc__[] = "string_literal(obj) -- converts object obj into a SQL string literal.\n\ This means, any special SQL characters are escaped, and it is enclosed\n\ -within single quotes. In other words, it performs:\n\ -\n\ -\"'%s'\" % escape_string(str(obj))\n\ +within single quotes. For bytes and bytearray, the byte contents are\n\ +escaped directly. Other objects are converted to strings first.\n\ \n\ Use connection.string_literal(obj), if you use it at all.\n\ _mysql.string_literal(obj) cannot handle character sets."; @@ -1025,19 +1206,35 @@ _mysql_string_literal( PyObject *o) { PyObject *s; // input string or bytes. need to decref. + int use_connection = 0; + PyObject *str = NULL; if (self && PyModule_Check((PyObject*)self)) self = NULL; + if (self) { + if (BEGIN_CONNECTION_LOCK(self) < 0) return NULL; + use_connection = self->open; + } if (PyBytes_Check(o)) { s = o; Py_INCREF(s); } + else if (PyByteArray_Check(o)) { +#ifdef Py_GIL_DISABLED + Py_BEGIN_CRITICAL_SECTION(o); +#endif + s = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(o), PyByteArray_GET_SIZE(o)); +#ifdef Py_GIL_DISABLED + Py_END_CRITICAL_SECTION(); +#endif + if (!s) goto error; + } else { PyObject *t = PyObject_Str(o); - if (!t) return NULL; + if (!t) goto error; - const char *encoding = (self && self->open) ? + const char *encoding = use_connection ? _get_encoding(&self->connection) : utf8; if (encoding == utf8) { s = t; @@ -1045,7 +1242,7 @@ _mysql_string_literal( else { s = PyUnicode_AsEncodedString(t, encoding, "strict"); Py_DECREF(t); - if (!s) return NULL; + if (!s) goto error; } } @@ -1054,6 +1251,10 @@ _mysql_string_literal( Py_ssize_t size; if (PyUnicode_Check(s)) { in = PyUnicode_AsUTF8AndSize(s, &size); + if (!in) { + Py_DECREF(s); + goto error; + } } else { assert(PyBytes_Check(s)); in = PyBytes_AsString(s); @@ -1061,16 +1262,17 @@ _mysql_string_literal( } // Prepare output buffer (str, out) - PyObject *str = PyBytes_FromStringAndSize((char *) NULL, size*2+3); + str = PyBytes_FromStringAndSize((char *) NULL, size*2+3); if (!str) { Py_DECREF(s); - return PyErr_NoMemory(); + PyErr_NoMemory(); + goto error; } char *out = PyBytes_AS_STRING(str); // escape unsigned long len; - if (self && self->open) { + if (use_connection) { #if MYSQL_VERSION_ID >= 50707 && !defined(MARIADB_BASE_VERSION) && !defined(MARIADB_VERSION_ID) len = mysql_real_escape_string_quote(&(self->connection), out+1, in, size, '\''); #else @@ -1081,12 +1283,20 @@ _mysql_string_literal( } Py_DECREF(s); + if (self) { + END_CONNECTION_LOCK(self); + } *out = *(out+len+1) = '\''; if (_PyBytes_Resize(&str, len+2) < 0) { Py_DECREF(str); return NULL; } return str; +error: + if (self) { + END_CONNECTION_LOCK(self); + } + return NULL; } static PyObject * @@ -1113,7 +1323,7 @@ _escape_item( return quoted; } -static char _mysql_escape__doc__[] = +static const char _mysql_escape__doc__[] = "escape(obj, dict) -- escape any special characters in object obj\n\ using mapping dict to provide quoting functions for each type.\n\ Returns a SQL literal string."; @@ -1123,6 +1333,7 @@ _mysql_escape( PyObject *args) { PyObject *o=NULL, *d=NULL; + PyObject *converter = NULL; if (!PyArg_ParseTuple(args, "O|O:escape", &o, &d)) return NULL; if (d) { @@ -1133,17 +1344,25 @@ _mysql_escape( } return _escape_item(self, o, d); } else { - if (!self) { + if (!self || PyModule_Check(self)) { PyErr_SetString(PyExc_TypeError, "argument 2 must be a mapping"); return NULL; } - return _escape_item(self, o, - ((_mysql_ConnectionObject *) self)->converter); + if (BEGIN_CONNECTION_LOCK((_mysql_ConnectionObject *)self) < 0) return NULL; + converter = ((_mysql_ConnectionObject *) self)->converter; + Py_XINCREF(converter); + END_CONNECTION_LOCK((_mysql_ConnectionObject *)self); + if (!converter) { + return _mysql_Exception((_mysql_ConnectionObject *)self); + } + PyObject *ret = _escape_item(self, o, converter); + Py_DECREF(converter); + return ret; } } -static char _mysql_ResultObject_describe__doc__[] = +static const char _mysql_ResultObject_describe__doc__[] = "Returns the sequence of 7-tuples required by the DB-API for\n\ the Cursor.description attribute.\n\ "; @@ -1157,7 +1376,7 @@ _mysql_ResultObject_describe( MYSQL_FIELD *fields; unsigned int i, n; - check_result_connection(self); + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); n = mysql_num_fields(self->result); fields = mysql_fetch_fields(self->result); @@ -1185,13 +1404,15 @@ _mysql_ResultObject_describe( if (!t) goto error; PyTuple_SET_ITEM(d, i, t); } + END_RESULT_CONNECTION_LOCK(self); return d; error: + END_RESULT_CONNECTION_LOCK(self); Py_XDECREF(d); return NULL; } -static char _mysql_ResultObject_field_flags__doc__[] = +static const char _mysql_ResultObject_field_flags__doc__[] = "Returns a tuple of field flags, one for each column in the result.\n\ " ; @@ -1203,7 +1424,7 @@ _mysql_ResultObject_field_flags( PyObject *d; MYSQL_FIELD *fields; unsigned int i, n; - check_result_connection(self); + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); n = mysql_num_fields(self->result); fields = mysql_fetch_fields(self->result); if (!(d = PyTuple_New(n))) return NULL; @@ -1212,8 +1433,10 @@ _mysql_ResultObject_field_flags( if (!(f = PyLong_FromLong((long)fields[i].flags))) goto error; PyTuple_SET_ITEM(d, i, f); } + END_RESULT_CONNECTION_LOCK(self); return d; error: + END_RESULT_CONNECTION_LOCK(self); Py_XDECREF(d); return NULL; } @@ -1498,7 +1721,7 @@ _mysql__fetch_row( return -1; } -static char _mysql_ResultObject_fetch_row__doc__[] = +static const char _mysql_ResultObject_fetch_row__doc__[] = "fetch_row([maxrows, how]) -- Fetches up to maxrows as a tuple.\n\ The rows are formatted according to how:\n\ \n\ @@ -1520,8 +1743,9 @@ _mysql_ResultObject_fetch_row( if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:fetch_row", kwlist, &maxrows, &how)) return NULL; - check_result_connection(self); + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); if (how >= (int)(sizeof(row_converters) / sizeof(row_converters[0]))) { + END_RESULT_CONNECTION_LOCK(self); PyErr_SetString(PyExc_ValueError, "how out of range"); return NULL; } @@ -1542,8 +1766,10 @@ _mysql_ResultObject_fetch_row( */ PyObject *t = PyList_AsTuple(r); Py_DECREF(r); + END_RESULT_CONNECTION_LOCK(self); return t; error: + END_RESULT_CONNECTION_LOCK(self); Py_XDECREF(r); return NULL; } @@ -1556,7 +1782,7 @@ _mysql_ResultObject_discard( _mysql_ResultObject *self, PyObject *noargs) { - check_result_connection(self); + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); MYSQL_ROW row; Py_BEGIN_ALLOW_THREADS @@ -1566,12 +1792,15 @@ _mysql_ResultObject_discard( Py_END_ALLOW_THREADS _mysql_ConnectionObject *conn = (_mysql_ConnectionObject *)self->conn; if (mysql_errno(&conn->connection)) { - return _mysql_Exception(conn); + PyObject *ret = _mysql_Exception(conn); + END_RESULT_CONNECTION_LOCK(self); + return ret; } + END_RESULT_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_change_user__doc__[] = +static const char _mysql_ConnectionObject_change_user__doc__[] = "Changes the user and causes the database specified by db to\n\ become the default (current) database on the connection\n\ specified by mysql. In subsequent queries, this database is\n\ @@ -1601,15 +1830,20 @@ _mysql_ConnectionObject_change_user( if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ss:change_user", kwlist, &user, &pwd, &db)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS r = mysql_change_user(&(self->connection), user, pwd, db); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_character_set_name__doc__[] = +static const char _mysql_ConnectionObject_character_set_name__doc__[] = "Returns the default character set for the current connection.\n\ Non-standard.\n\ "; @@ -1620,12 +1854,16 @@ _mysql_ConnectionObject_character_set_name( PyObject *noargs) { const char *s; - check_connection(self); + PyObject *ret; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); s = mysql_character_set_name(&(self->connection)); - return PyUnicode_FromString(s); + ret = PyUnicode_FromString(s); + END_CONNECTION_LOCK(self); + return ret; } -static char _mysql_ConnectionObject_set_character_set__doc__[] = +static const char _mysql_ConnectionObject_set_character_set__doc__[] = "Sets the default character set for the current connection.\n\ Non-standard.\n\ "; @@ -1637,17 +1875,23 @@ _mysql_ConnectionObject_set_character_set( { const char *s; int err; + if (!PyArg_ParseTuple(args, "s", &s)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS err = mysql_set_character_set(&(self->connection), s); Py_END_ALLOW_THREADS - if (err) return _mysql_Exception(self); + if (err) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } #if MYSQL_VERSION_ID >= 50010 -static char _mysql_ConnectionObject_get_character_set_info__doc__[] = +static const char _mysql_ConnectionObject_get_character_set_info__doc__[] = "Returns a dict with information about the current character set:\n\ \n\ collation\n\ @@ -1676,9 +1920,13 @@ _mysql_ConnectionObject_get_character_set_info( PyObject *result; MY_CHARSET_INFO cs; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); mysql_get_character_set_info(&(self->connection), &cs); - if (!(result = PyDict_New())) return NULL; + if (!(result = PyDict_New())) { + END_CONNECTION_LOCK(self); + return NULL; + } if (cs.csname) PyDict_SetItemString(result, "name", PyUnicode_FromString(cs.csname)); if (cs.name) @@ -1689,11 +1937,12 @@ _mysql_ConnectionObject_get_character_set_info( PyDict_SetItemString(result, "dir", PyUnicode_FromString(cs.dir)); PyDict_SetItemString(result, "mbminlen", PyLong_FromLong(cs.mbminlen)); PyDict_SetItemString(result, "mbmaxlen", PyLong_FromLong(cs.mbmaxlen)); + END_CONNECTION_LOCK(self); return result; } #endif -static char _mysql_ConnectionObject_get_native_connection__doc__[] = +static const char _mysql_ConnectionObject_get_native_connection__doc__[] = "Return the internal MYSQL* wrapped in a PyCapsule object.\n\ NOTE: this is a private API introduced ONLY for XTA integration,\n\ don't use it for different use cases.\n\ @@ -1708,14 +1957,16 @@ _mysql_ConnectionObject_get_native_connection( PyObject *noargs) { PyObject *result; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); result = PyCapsule_New(&(self->connection), "_mysql.connection.native_connection", NULL); + END_CONNECTION_LOCK(self); return result; } -static char _mysql_get_client_info__doc__[] = +static const char _mysql_get_client_info__doc__[] = "get_client_info() -- Returns a string that represents\n\ the client library version."; static PyObject * @@ -1726,7 +1977,7 @@ _mysql_get_client_info( return PyUnicode_FromString(mysql_get_client_info()); } -static char _mysql_ConnectionObject_get_host_info__doc__[] = +static const char _mysql_ConnectionObject_get_host_info__doc__[] = "Returns a string that represents the MySQL client library\n\ version. Non-standard.\n\ "; @@ -1736,11 +1987,15 @@ _mysql_ConnectionObject_get_host_info( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyUnicode_FromString(mysql_get_host_info(&(self->connection))); + PyObject *ret; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + ret = PyUnicode_FromString(mysql_get_host_info(&(self->connection))); + END_CONNECTION_LOCK(self); + return ret; } -static char _mysql_ConnectionObject_get_proto_info__doc__[] = +static const char _mysql_ConnectionObject_get_proto_info__doc__[] = "Returns an unsigned integer representing the protocol version\n\ used by the current connection. Non-standard.\n\ "; @@ -1750,11 +2005,15 @@ _mysql_ConnectionObject_get_proto_info( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyLong_FromLong((long)mysql_get_proto_info(&(self->connection))); + unsigned int proto; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + proto = mysql_get_proto_info(&(self->connection)); + END_CONNECTION_LOCK(self); + return PyLong_FromLong((long)proto); } -static char _mysql_ConnectionObject_get_server_info__doc__[] = +static const char _mysql_ConnectionObject_get_server_info__doc__[] = "Returns a string that represents the server version number.\n\ Non-standard.\n\ "; @@ -1764,11 +2023,15 @@ _mysql_ConnectionObject_get_server_info( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyUnicode_FromString(mysql_get_server_info(&(self->connection))); + PyObject *ret; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + ret = PyUnicode_FromString(mysql_get_server_info(&(self->connection))); + END_CONNECTION_LOCK(self); + return ret; } -static char _mysql_ConnectionObject_info__doc__[] = +static const char _mysql_ConnectionObject_info__doc__[] = "Retrieves a string providing information about the most\n\ recently executed query. Non-standard. Use messages or\n\ Cursor.messages.\n\ @@ -1780,13 +2043,20 @@ _mysql_ConnectionObject_info( PyObject *noargs) { const char *s; - check_connection(self); + PyObject *ret; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); s = mysql_info(&(self->connection)); - if (s) return PyUnicode_FromString(s); + if (s) { + ret = PyUnicode_FromString(s); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_insert_id__doc__[] = +static const char _mysql_ConnectionObject_insert_id__doc__[] = "Returns the ID generated for an AUTO_INCREMENT column by the previous\n\ query. Use this function after you have performed an INSERT query into a\n\ table that contains an AUTO_INCREMENT field.\n\ @@ -1813,12 +2083,14 @@ _mysql_ConnectionObject_insert_id( PyObject *noargs) { my_ulonglong r; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); r = mysql_insert_id(&(self->connection)); + END_CONNECTION_LOCK(self); return PyLong_FromUnsignedLongLong(r); } -static char _mysql_ConnectionObject_kill__doc__[] = +static const char _mysql_ConnectionObject_kill__doc__[] = "Asks the server to kill the thread specified by pid.\n\ Non-standard. Deprecated."; @@ -1830,17 +2102,23 @@ _mysql_ConnectionObject_kill( unsigned long pid; int r; char query[50]; + if (!PyArg_ParseTuple(args, "k:kill", &pid)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); snprintf(query, 50, "KILL %lu", pid); Py_BEGIN_ALLOW_THREADS r = mysql_query(&(self->connection), query); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_field_count__doc__[] = +static const char _mysql_ConnectionObject_field_count__doc__[] = "Returns the number of columns for the most recent query on the\n\ connection. Non-standard. Will probably give you bogus results\n\ on most cursor classes. Use Cursor.rowcount.\n\ @@ -1851,11 +2129,15 @@ _mysql_ConnectionObject_field_count( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyLong_FromLong((long)mysql_field_count(&(self->connection))); + unsigned int count; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + count = mysql_field_count(&(self->connection)); + END_CONNECTION_LOCK(self); + return PyLong_FromLong((long)count); } -static char _mysql_ConnectionObject_fileno__doc__[] = +static const char _mysql_ConnectionObject_fileno__doc__[] = "Return file descriptor of the underlying libmysqlclient connection.\n\ This provides raw access to the underlying network connection.\n\ "; @@ -1865,11 +2147,15 @@ _mysql_ConnectionObject_fileno( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); - return PyLong_FromLong(self->connection.net.fd); + int fd; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); + fd = self->connection.net.fd; + END_CONNECTION_LOCK(self); + return PyLong_FromLong(fd); } -static char _mysql_ResultObject_num_fields__doc__[] = +static const char _mysql_ResultObject_num_fields__doc__[] = "Returns the number of fields (column) in the result." ; static PyObject * @@ -1877,11 +2163,15 @@ _mysql_ResultObject_num_fields( _mysql_ResultObject *self, PyObject *noargs) { - check_result_connection(self); - return PyLong_FromLong((long)mysql_num_fields(self->result)); + unsigned int fields; + + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); + fields = mysql_num_fields(self->result); + END_RESULT_CONNECTION_LOCK(self); + return PyLong_FromLong((long)fields); } -static char _mysql_ResultObject_num_rows__doc__[] = +static const char _mysql_ResultObject_num_rows__doc__[] = "Returns the number of rows in the result set. Note that if\n\ use=1, this will not return a valid value until the entire result\n\ set has been read.\n\ @@ -1892,18 +2182,22 @@ _mysql_ResultObject_num_rows( _mysql_ResultObject *self, PyObject *noargs) { - check_result_connection(self); - return PyLong_FromUnsignedLongLong(mysql_num_rows(self->result)); + my_ulonglong rows; + + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); + rows = mysql_num_rows(self->result); + END_RESULT_CONNECTION_LOCK(self); + return PyLong_FromUnsignedLongLong(rows); } -static char _mysql_ConnectionObject_ping__doc__[] = +static const char _mysql_ConnectionObject_ping__doc__[] = "Checks whether or not the connection to the server is working.\n\ \n\ This function can be used by clients that remain idle for a\n\ long while, to check whether or not the server has closed the\n\ connection.\n\ \n\ -New in 1.2.2: Accepts an optional reconnect parameter. If True,\n\ +DEPRECATED: Accepts an optional `reconnect` parameter. If True,\n\ then the client will attempt reconnection. Note that this setting\n\ is persistent. By default, this is on in MySQL<5.0.3, and off\n\ thereafter.\n\ @@ -1920,15 +2214,22 @@ _mysql_ConnectionObject_ping( _mysql_ConnectionObject *self, PyObject *args) { - int reconnect = 0; + int reconnect = -1; + if (!PyArg_ParseTuple(args, "|p", &reconnect)) return NULL; - check_connection(self); + if (reconnect != -1) { + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "The reconnect parameter of ping() is deprecated.", + 1) < 0) { + return NULL; + } + } else { + reconnect = 0; + } + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); if (reconnect != (self->reconnect == true)) { // libmysqlclient show warning to stderr when MYSQL_OPT_RECONNECT is used. // so we avoid using it as possible for now. - // TODO: Warn when reconnect is true. - // MySQL 8.0.33 show warning to stderr already. - // We will emit Pytohn warning in future. my_bool recon = (my_bool)reconnect; mysql_options(&self->connection, MYSQL_OPT_RECONNECT, &recon); self->reconnect = (bool)reconnect; @@ -1937,11 +2238,16 @@ _mysql_ConnectionObject_ping( Py_BEGIN_ALLOW_THREADS r = mysql_ping(&(self->connection)); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_query__doc__[] = +static const char _mysql_ConnectionObject_query__doc__[] = "Execute a query. store_result() or use_result() will get the\n\ result set, if any. Non-standard. Use cursor() to create a cursor,\n\ then cursor.execute().\n\ @@ -1955,18 +2261,24 @@ _mysql_ConnectionObject_query( char *query; Py_ssize_t len; int r; + if (!PyArg_ParseTuple(args, "s#:query", &query, &len)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS r = mysql_real_query(&(self->connection), query, len); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_send_query__doc__[] = +static const char _mysql_ConnectionObject_send_query__doc__[] = "Send a query. Same to query() except not wait response.\n\n\ Use read_query_result() before calling store_result() or use_result()\n"; @@ -1979,18 +2291,24 @@ _mysql_ConnectionObject_send_query( Py_ssize_t len; int r; MYSQL *mysql = &(self->connection); + if (!PyArg_ParseTuple(args, "s#:query", &query, &len)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS r = mysql_send_query(mysql, query, len); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_read_query_result__doc__[] = +static const char _mysql_ConnectionObject_read_query_result__doc__[] = "Read result of query sent by send_query().\n"; static PyObject * @@ -2000,16 +2318,22 @@ _mysql_ConnectionObject_read_query_result( { int r; MYSQL *mysql = &(self->connection); - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS r = (int)mysql_read_query_result(mysql); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_select_db__doc__[] = +static const char _mysql_ConnectionObject_select_db__doc__[] = "Causes the database specified by db to become the default\n\ (current) database on the connection specified by mysql. In subsequent\n\ queries, this database is the default for table references that do not\n\ @@ -2028,16 +2352,22 @@ _mysql_ConnectionObject_select_db( { char *db; int r; + if (!PyArg_ParseTuple(args, "s:select_db", &db)) return NULL; - check_connection(self); + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS r = mysql_select_db(&(self->connection), db); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_shutdown__doc__[] = +static const char _mysql_ConnectionObject_shutdown__doc__[] = "Asks the database server to shut down. The connected user must\n\ have shutdown privileges. Non-standard. Deprecated.\n\ "; @@ -2048,15 +2378,21 @@ _mysql_ConnectionObject_shutdown( PyObject *noargs) { int r; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS r = mysql_query(&(self->connection), "SHUTDOWN"); Py_END_ALLOW_THREADS - if (r) return _mysql_Exception(self); + if (r) { + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } -static char _mysql_ConnectionObject_stat__doc__[] = +static const char _mysql_ConnectionObject_stat__doc__[] = "Returns a character string containing information similar to\n\ that provided by the mysqladmin status command. This includes\n\ uptime in seconds and the number of running threads,\n\ @@ -2069,15 +2405,23 @@ _mysql_ConnectionObject_stat( PyObject *noargs) { const char *s; - check_connection(self); + PyObject *ret; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); Py_BEGIN_ALLOW_THREADS s = mysql_stat(&(self->connection)); Py_END_ALLOW_THREADS - if (!s) return _mysql_Exception(self); - return PyUnicode_FromString(s); + if (!s) { + ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; + } + ret = PyUnicode_FromString(s); + END_CONNECTION_LOCK(self); + return ret; } -static char _mysql_ConnectionObject_store_result__doc__[] = +static const char _mysql_ConnectionObject_store_result__doc__[] = "Returns a result object acquired by mysql_store_result\n\ (results stored in the client). If no results are available,\n\ None is returned. Non-standard.\n\ @@ -2091,8 +2435,10 @@ _mysql_ConnectionObject_store_result( PyObject *arglist=NULL, *kwarglist=NULL, *result=NULL; _mysql_ResultObject *r=NULL; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); arglist = Py_BuildValue("(OiO)", self, 0, self->converter); + END_CONNECTION_LOCK(self); if (!arglist) goto error; kwarglist = PyDict_New(); if (!kwarglist) goto error; @@ -2114,7 +2460,7 @@ _mysql_ConnectionObject_store_result( return result; } -static char _mysql_ConnectionObject_thread_id__doc__[] = +static const char _mysql_ConnectionObject_thread_id__doc__[] = "Returns the thread ID of the current connection. This value\n\ can be used as an argument to kill() to kill the thread.\n\ \n\ @@ -2131,12 +2477,14 @@ _mysql_ConnectionObject_thread_id( PyObject *noargs) { unsigned long pid; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); pid = mysql_thread_id(&(self->connection)); + END_CONNECTION_LOCK(self); return PyLong_FromLong((long)pid); } -static char _mysql_ConnectionObject_use_result__doc__[] = +static const char _mysql_ConnectionObject_use_result__doc__[] = "Returns a result object acquired by mysql_use_result\n\ (results stored in the server). If no results are available,\n\ None is returned. Non-standard.\n\ @@ -2150,8 +2498,10 @@ _mysql_ConnectionObject_use_result( PyObject *arglist=NULL, *kwarglist=NULL, *result=NULL; _mysql_ResultObject *r=NULL; - check_connection(self); + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); arglist = Py_BuildValue("(OiO)", self, 1, self->converter); + END_CONNECTION_LOCK(self); if (!arglist) return NULL; kwarglist = PyDict_New(); if (!kwarglist) goto error; @@ -2182,31 +2532,31 @@ _mysql_ConnectionObject_discard_result( _mysql_ConnectionObject *self, PyObject *noargs) { - check_connection(self); + MYSQL_RES *res; + MYSQL_ROW row; + int err = 0; + + BEGIN_CONNECTION_OPERATION(self, return _mysql_Exception(self)); MYSQL *conn = &(self->connection); Py_BEGIN_ALLOW_THREADS; - MYSQL_RES *res = mysql_use_result(conn); - if (res == NULL) { - Py_BLOCK_THREADS; - if (mysql_errno(conn) != 0) { - // fprintf(stderr, "mysql_use_result failed: %s\n", mysql_error(conn)); - return _mysql_Exception(self); + res = mysql_use_result(conn); + if (res != NULL) { + while (NULL != (row = mysql_fetch_row(res))) { + // do nothing. } - Py_RETURN_NONE; + mysql_free_result(res); } - - MYSQL_ROW row; - while (NULL != (row = mysql_fetch_row(res))) { - // do nothing. - } - mysql_free_result(res); Py_END_ALLOW_THREADS; - if (mysql_errno(conn)) { + err = mysql_errno(conn); + if (err) { // fprintf(stderr, "mysql_free_result failed: %s\n", mysql_error(conn)); - return _mysql_Exception(self); + PyObject *ret = _mysql_Exception(self); + END_CONNECTION_LOCK(self); + return ret; } + END_CONNECTION_LOCK(self); Py_RETURN_NONE; } @@ -2220,6 +2570,10 @@ _mysql_ConnectionObject_dealloc( self->open = false; } Py_CLEAR(self->converter); + if (self->lock != NULL) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } MyFree(self); } @@ -2236,7 +2590,7 @@ _mysql_ConnectionObject_repr( return PyUnicode_FromString(buf); } -static char _mysql_ResultObject_data_seek__doc__[] = +static const char _mysql_ResultObject_data_seek__doc__[] = "data_seek(n) -- seek to row n of result set"; static PyObject * _mysql_ResultObject_data_seek( @@ -2244,9 +2598,11 @@ _mysql_ResultObject_data_seek( PyObject *args) { unsigned int row; + if (!PyArg_ParseTuple(args, "i:data_seek", &row)) return NULL; - check_result_connection(self); + BEGIN_RESULT_OPERATION(self, return _mysql_Exception(result_connection(self))); mysql_data_seek(self->result, row); + END_RESULT_CONNECTION_LOCK(self); Py_RETURN_NONE; } @@ -2255,7 +2611,15 @@ _mysql_ResultObject_dealloc( _mysql_ResultObject *self) { PyObject_GC_UnTrack((PyObject *)self); + /* Only an unbuffered result may need to read remaining rows from the connection. */ + bool lock_connection = self->use && self->result != NULL && self->conn != NULL; + if (lock_connection) { + BEGIN_RESULT_CONNECTION_LOCK(self); + } mysql_free_result(self->result); + if (lock_connection) { + END_RESULT_CONNECTION_LOCK(self); + } _mysql_ResultObject_clear(self); MyFree(self); } @@ -2300,6 +2664,12 @@ static PyMethodDef _mysql_ConnectionObject_methods[] = { METH_NOARGS, _mysql_ConnectionObject_rollback__doc__ }, + { + "more_results", + (PyCFunction)_mysql_ConnectionObject_more_results, + METH_NOARGS, + _mysql_ConnectionObject_more_results__doc__ + }, { "next_result", (PyCFunction)_mysql_ConnectionObject_next_result, @@ -2622,9 +2992,8 @@ _mysql_ConnectionObject_getattro( _mysql_ConnectionObject *self, PyObject *name) { - const char *cname; - cname = PyUnicode_AsUTF8(name); - if (strcmp(cname, "closed") == 0) + if (PyUnicode_Check(name) && + PyUnicode_CompareWithASCIIString(name, "closed") == 0) return PyLong_FromLong((long)!(self->open)); return PyObject_GenericGetAttr((PyObject *)self, name); @@ -2852,7 +3221,7 @@ _mysql_NewException( #define QUOTE(X) _QUOTE(X) #define _QUOTE(X) #X -static char _mysql___doc__[] = +static const char _mysql___doc__[] = "an adaptation of the MySQL C API (mostly)\n\ \n\ You probably are better off using MySQLdb instead of using this\n\ @@ -2892,7 +3261,9 @@ PyInit__mysql(void) module = PyModule_Create(&_mysqlmodule); if (!module) return module; /* this really should never happen */ - +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED); +#endif if (!(dict = PyModule_GetDict(module))) goto error; if (PyDict_SetItemString(dict, "version_info", PyRun_String(QUOTE(version_info), Py_eval_input, diff --git a/src/MySQLdb/connections.py b/src/MySQLdb/connections.py index 5bcfc937..ee25b810 100644 --- a/src/MySQLdb/connections.py +++ b/src/MySQLdb/connections.py @@ -4,20 +4,21 @@ want to make your own subclasses. In most cases, you will probably override Connection.default_cursor with a non-standard Cursor class. """ + import re -from . import cursors, _mysql +from . import _mysql, cursors from ._exceptions import ( - Warning, - Error, - InterfaceError, - DataError, DatabaseError, - OperationalError, + DataError, + Error, IntegrityError, + InterfaceError, InternalError, NotSupportedError, + OperationalError, ProgrammingError, + Warning, ) # Mapping from MySQL charset name to Python codec name @@ -52,6 +53,7 @@ class Connection(_mysql.connection): """MySQL Database Connection Object""" default_cursor = cursors.Cursor + executemany_fallback = "loop" def __init__(self, *args, **kwargs): """ @@ -122,6 +124,13 @@ class object, used to create cursors (keyword only) If True, enable multi statements for clients >= 4.1. Defaults to True. + :param str executemany_fallback: + Controls how ``Cursor.executemany()`` executes statements which + cannot use the multi-row INSERT/REPLACE optimization. ``"loop"`` + executes each statement separately (the default), while + ``"multi"`` batches safe data manipulation statements into a + multi-statement query when multi statements are enabled. + :param str ssl_mode: specify the security settings for connection to the server; see the MySQL documentation for more details @@ -142,7 +151,13 @@ class object, used to create cursors (keyword only) See https://dev.mysql.com/doc/refman/9.0/en/caching-sha2-pluggable-authentication.html :param bool local_infile: - enables LOAD LOCAL INFILE; zero disables + sets ``MYSQL_OPT_LOCAL_INFILE`` in ``mysql_options()`` enabling LOAD LOCAL INFILE from any path; zero disables; + + :param str local_infile_dir: + sets ``MYSQL_OPT_LOAD_DATA_LOCAL_DIR`` in ``mysql_options()`` enabling LOAD LOCAL INFILE from any path; + if ``local_infile`` is set to ``True`` then this is ignored; + + supported for mysql version >= 8.0.21 :param bool autocommit: If False (default), autocommit is disabled. @@ -157,7 +172,7 @@ class object, used to create cursors (keyword only) documentation for the MySQL C API for some hints on what they do. """ from MySQLdb.constants import CLIENT, FIELD_TYPE - from MySQLdb.converters import conversions, _bytes_or_str + from MySQLdb.converters import _bytes_or_str, conversions kwargs2 = kwargs.copy() @@ -166,11 +181,7 @@ class object, used to create cursors (keyword only) if "passwd" in kwargs2: kwargs2["password"] = kwargs2.pop("passwd") - if "conv" in kwargs: - conv = kwargs["conv"] - else: - conv = conversions - + conv = kwargs.get("conv", conversions) conv2 = {} for k, v in conv.items(): if isinstance(k, int) and isinstance(v, list): @@ -185,6 +196,11 @@ class object, used to create cursors (keyword only) use_unicode = kwargs2.pop("use_unicode", True) sql_mode = kwargs2.pop("sql_mode", "") self._binary_prefix = kwargs2.pop("binary_prefix", False) + executemany_fallback = kwargs2.pop( + "executemany_fallback", self.executemany_fallback + ) + if executemany_fallback not in ("loop", "multi"): + raise ValueError("executemany_fallback must be either 'loop' or 'multi'") client_flag = kwargs.get("client_flag", 0) client_flag |= CLIENT.MULTI_RESULTS @@ -200,11 +216,8 @@ class object, used to create cursors (keyword only) super().__init__(*args, **kwargs2) self.cursorclass = cursorclass - self.encoders = { - k: v - for k, v in conv.items() - if type(k) is not int # noqa: E721 - } + self.executemany_fallback = executemany_fallback + self.encoders = {k: v for k, v in conv.items() if type(k) is not int} self._server_version = tuple( [numeric_part(n) for n in self.get_server_info().split(".")[:2]] ) @@ -233,13 +246,20 @@ class object, used to create cursors (keyword only) self.converter[FIELD_TYPE.JSON] = str self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS - if self._transactional: - if autocommit is not None: - self.autocommit(autocommit) + if self._transactional and autocommit is not None: + self.autocommit(autocommit) self.messages = [] - def _set_attributes(self, host=None, user=None, password=None, database="", port=3306, - unix_socket=None, **kwargs): + def _set_attributes( + self, + host=None, + user=None, + password=None, + database="", + port=3306, + unix_socket=None, + **kwargs, + ): """set some attributes for otel""" if unix_socket and not host: host = "localhost" @@ -289,6 +309,12 @@ def _bytes_literal(self, bs): def _tuple_literal(self, t): return b"(%s)" % (b",".join(map(self.literal, t))) + def _set_literal(self, s): + for c in s: + if not isinstance(c, str): + raise TypeError("set elements must be strings") + return self.string_literal(",".join(s)) + def literal(self, o): """If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are @@ -297,14 +323,15 @@ def literal(self, o): Non-standard. For internal use; do not use this in your applications. """ + t = type(o) if isinstance(o, str): s = self.string_literal(o.encode(self.encoding)) - elif isinstance(o, bytearray): - s = self._bytes_literal(o) - elif isinstance(o, bytes): + elif isinstance(o, (bytes, bytearray)): s = self._bytes_literal(o) - elif isinstance(o, (tuple, list)): + elif t is tuple or t is list: s = self._tuple_literal(o) + elif t is set or t is frozenset: + s = self._set_literal(o) else: s = self.escape(o, self.encoders) if isinstance(s, str): diff --git a/src/MySQLdb/constants/ER.py b/src/MySQLdb/constants/ER.py index 8c5ece24..4480a3d3 100644 --- a/src/MySQLdb/constants/ER.py +++ b/src/MySQLdb/constants/ER.py @@ -18,8 +18,7 @@ m = re.match(r"^\s*#define\s+((ER|WARN)_[A-Z0-9_]+)\s+(\d+)\s*", line) if m: name = m.group(1) - if name.startswith("ER_"): - name = name[3:] + name = name.removeprefix("ER_") value = int(m.group(3)) if name == "ERROR_LAST": if error_last is None or error_last < value: diff --git a/src/MySQLdb/constants/__init__.py b/src/MySQLdb/constants/__init__.py index 0372265b..fefb2f12 100644 --- a/src/MySQLdb/constants/__init__.py +++ b/src/MySQLdb/constants/__init__.py @@ -1 +1 @@ -__all__ = ["CR", "FIELD_TYPE", "CLIENT", "ER", "FLAG"] +__all__ = ["CLIENT", "CR", "ER", "FIELD_TYPE", "FLAG"] diff --git a/src/MySQLdb/converters.py b/src/MySQLdb/converters.py index d6fdc01c..29328f44 100644 --- a/src/MySQLdb/converters.py +++ b/src/MySQLdb/converters.py @@ -30,23 +30,23 @@ (with the copy() method), modify the copies, and then pass them to MySQL.connect(). """ + +import array from decimal import Decimal +from MySQLdb._exceptions import ProgrammingError from MySQLdb._mysql import string_literal from MySQLdb.constants import FIELD_TYPE, FLAG from MySQLdb.times import ( Date, - DateTimeType, + Date_or_None, DateTime2literal, - DateTimeDeltaType, - DateTimeDelta2literal, DateTime_or_None, + DateTimeDelta2literal, + DateTimeDeltaType, + DateTimeType, TimeDelta_or_None, - Date_or_None, ) -from MySQLdb._exceptions import ProgrammingError - -import array NoneType = type(None) @@ -62,6 +62,9 @@ def Bool2Str(s, d): def Set2Str(s, d): # Only support ascii string. Not tested. + import warnings + + warnings.warn("Set2Str is deprecated", DeprecationWarning, stacklevel=2) return string_literal(",".join(s)) @@ -112,7 +115,6 @@ def array2Str(o, d): Date: Thing2Literal, DateTimeType: DateTime2literal, DateTimeDeltaType: DateTimeDelta2literal, - set: Set2Str, Decimal: Decimal2Literal, FIELD_TYPE.TINY: int, FIELD_TYPE.SHORT: int, diff --git a/src/MySQLdb/cursors.py b/src/MySQLdb/cursors.py index 70fbeea4..cf8fe4e5 100644 --- a/src/MySQLdb/cursors.py +++ b/src/MySQLdb/cursors.py @@ -3,10 +3,13 @@ This module implements Cursors of various types for MySQLdb. By default, MySQLdb uses the Cursor class. """ + import re -from ._exceptions import ProgrammingError +from ._exceptions import InternalError, MySQLError, ProgrammingError +from .constants import CLIENT, CR +_EXECUTEMANY_MULTI_SEPARATOR = b"\n;\n" #: Regular expression for ``Cursor.executemany```. #: executemany only supports simple bulk insert. @@ -22,6 +25,45 @@ re.IGNORECASE | re.DOTALL, ) +_RE_INSERT_VALUES_BYTES = re.compile( + RE_INSERT_VALUES.pattern.encode("ascii"), re.IGNORECASE | re.DOTALL +) +_RE_EXECUTEMANY_DML = re.compile( + r"\s*(?:INSERT|REPLACE|UPDATE|DELETE)\b", re.IGNORECASE +) +_RE_EXECUTEMANY_DML_BYTES = re.compile( + _RE_EXECUTEMANY_DML.pattern.encode("ascii"), re.IGNORECASE +) +_RE_RETURNING = re.compile(r"\bRETURNING\b", re.IGNORECASE) +_RE_RETURNING_BYTES = re.compile( + _RE_RETURNING.pattern.encode("ascii"), re.IGNORECASE +) + + +def _match_insert_values(query): + if isinstance(query, (bytes, bytearray)): + return _RE_INSERT_VALUES_BYTES.match(query) + return RE_INSERT_VALUES.match(query) + + +def _is_executemany_dml(query): + """Return whether query is safe for client-side multi-statement batching.""" + if isinstance(query, (bytes, bytearray)): + return ( + b";" not in query + and _RE_EXECUTEMANY_DML_BYTES.match(query) is not None + and _RE_RETURNING_BYTES.search(query) is None + ) + return ( + ";" not in query + and _RE_EXECUTEMANY_DML.match(query) is not None + and _RE_RETURNING.search(query) is None + ) + + +def _backquote_escape(s): + return s.replace(b"`", b"``") + class BaseCursor: """A base for Cursor classes. Useful attributes: @@ -46,24 +88,21 @@ class BaseCursor: #: Default value of max_allowed_packet is 1048576. max_stmt_length = 64 * 1024 - from ._exceptions import ( - MySQLError, - Warning, - Error, - InterfaceError, - DatabaseError, - DataError, - OperationalError, - IntegrityError, - InternalError, - ProgrammingError, - NotSupportedError, - ) + #: Maximum encoded size and statement count for multi-statement + #: ``executemany`` fallback batches. The size includes separators and is + #: measured after argument conversion. Subclasses may override them. + max_multi_stmt_length = 16_000 + max_multi_stmt_count = 200 + + #: Override with ``"loop"`` or ``"multi"`` on a cursor subclass or + #: instance. ``None`` inherits the policy from the connection. + executemany_fallback = None connection = None def __init__(self, connection): self.connection = connection + self.warning_count = 0 self.description = None self.description_flags = None self.rowcount = 0 @@ -140,6 +179,7 @@ def _do_get_result(self, db): self.description = result.describe() self.description_flags = result.field_flags() + self.warning_count = db.warning_count() self.rowcount = db.affected_rows() self.rownumber = 0 self.lastrowid = db.insert_id() @@ -225,19 +265,21 @@ def executemany(self, query, args): :param args: Sequence of sequences or mappings. It is used as parameter. :return: Number of rows affected, if any. - This method improves performance on multiple-row INSERT and - REPLACE. Otherwise it is equivalent to looping over args with - execute(). + This method improves performance on multiple-row INSERT and REPLACE. + When ``executemany_fallback`` is ``"multi"``, it also batches safe DML + statements if the connection has multi statements enabled. Otherwise, + it is equivalent to looping over args with execute(). """ if not args: return - m = RE_INSERT_VALUES.match(query) + m = _match_insert_values(query) if m: q_prefix = m.group(1) % () q_values = m.group(2).rstrip() q_postfix = m.group(3) or "" - assert q_values[0] == "(" and q_values[-1] == ")" + assert q_values[:1] in ("(", b"(") + assert q_values[-1:] in (")", b")") return self._do_execute_many( q_prefix, q_values, @@ -247,9 +289,129 @@ def executemany(self, query, args): self._get_db().encoding, ) - self.rowcount = sum(self.execute(query, arg) for arg in args) + fallback = self.executemany_fallback + db = self._get_db() + if fallback is None: + fallback = getattr(db, "executemany_fallback", "loop") + if fallback not in ("loop", "multi"): + raise ValueError("executemany_fallback must be either 'loop' or 'multi'") + + if ( + fallback == "multi" + and db.client_flag & CLIENT.MULTI_STATEMENTS + and _is_executemany_dml(query) + ): + return self._do_execute_many_multi(query, args) + + rows = None + for arg in args: + result = self.execute(query, arg) + rows = result if rows is None else rows + result + if rows is None: + return + self.rowcount = rows return self.rowcount + def _do_execute_many_multi(self, query, args): + rows = 0 + statement_count = 0 + sql = bytearray() + + for arg in args: + statement = self._mogrify(query, arg) + if statement_count and ( + statement_count >= self.max_multi_stmt_count + or len(sql) + len(_EXECUTEMANY_MULTI_SEPARATOR) + len(statement) + > self.max_multi_stmt_length + ): + rows += self._execute_multi_statement_batch( + bytes(sql), statement_count + ) + sql.clear() + statement_count = 0 + if statement_count: + sql += _EXECUTEMANY_MULTI_SEPARATOR + sql += statement + statement_count += 1 + if not statement_count: + return + rows += self._execute_multi_statement_batch(bytes(sql), statement_count) + self.rowcount = rows + return rows + + def _execute_multi_statement_batch(self, query, statement_count): + """Execute and fully consume one generated multi-statement query.""" + if statement_count == 1: + return self.execute(query) + + db = self._get_db() + query_started = False + try: + query_started = True + self.execute(query) + if self.description is not None: + self._raise_multi_statement_result_mismatch(db) + rows = self.rowcount + for _ in range(statement_count - 1): + if not db.more_results(): + self._raise_multi_statement_result_mismatch(db) + if db.next_result() != 0: + self._raise_multi_statement_result_mismatch(db) + self._do_get_result(db) + if self.description is not None: + self._raise_multi_statement_result_mismatch(db) + self._post_get_result() + rows += self.rowcount + if db.more_results(): + self._raise_multi_statement_result_mismatch(db) + return rows + except BaseException as exc: + # A server-side SQL error from next_result() terminates the rest of + # the multi-statement query and leaves the protocol synchronized. + # Interruptions and client/protocol failures can leave unread + # results, so discard the connection instead of risking reuse. + self.description = None + self.description_flags = None + self.warning_count = 0 + self.rowcount = None + self.lastrowid = None + self._result = None + self._rows = None + self.rownumber = None + if query_started and self._multi_statement_error_needs_close(exc): + self._close_connection(db) + raise + + def _raise_multi_statement_result_mismatch(self, db): + if self._result is not None: + try: + self._result.discard() + except BaseException: # noqa: S110 + pass + self._result = None + self._close_connection(db) + raise InternalError("multi-statement executemany result count mismatch") + + @staticmethod + def _close_connection(db): + try: + db.close() + except BaseException: # noqa: S110 + pass + + def _multi_statement_error_needs_close(self, exc): + if not isinstance(exc, MySQLError): + return True + if not exc.args or not isinstance(exc.args[0], int): + return True + errno = exc.args[0] + return ( + CR.MIN_ERROR <= errno <= CR.MAX_ERROR + or errno == 1153 # ER_NET_PACKET_TOO_LARGE + or errno == 1927 # ER_CONNECTION_KILLED (MariaDB) + or errno == 4031 # ER_CLIENT_INTERACTION_TIMEOUT + ) + def _do_execute_many( self, prefix, values, postfix, args, max_stmt_length, encoding ): @@ -261,7 +423,11 @@ def _do_execute_many( postfix = postfix.encode(encoding) sql = bytearray(prefix) args = iter(args) - v = self._mogrify(values, next(args)) + try: + first_arg = next(args) + except StopIteration: + return + v = self._mogrify(values, first_arg) sql += v rows = 0 for arg in args: @@ -291,10 +457,10 @@ def callproc(self, procname, args=()): variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. - The server variables are named @_procname_n, where procname + The server variables are named @`_procname_n`, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure - have been fetched, you can issue a SELECT @_procname_0, ... + have been fetched, you can issue a SELECT @`_procname_0`, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure @@ -307,17 +473,18 @@ def callproc(self, procname, args=()): db = self._get_db() if isinstance(procname, str): procname = procname.encode(db.encoding) + procname_escaped = _backquote_escape(procname) if args: - fmt = b"@_" + procname + b"_%d=%s" + fmt = b"@`_" + procname_escaped + b"_%d`=%s" q = b"SET %s" % b",".join( fmt % (index, db.literal(arg)) for index, arg in enumerate(args) ) self._query(q) self.nextset() - q = b"CALL %s(%s)" % ( - procname, - b",".join([b"@_%s_%d" % (procname, i) for i in range(len(args))]), + q = b"CALL `%s`(%s)" % ( + procname_escaped, + b",".join([b"@`_%s_%d`" % (procname_escaped, i) for i in range(len(args))]), ) self._query(q) return args @@ -325,6 +492,7 @@ def callproc(self, procname, args=()): def _query(self, q): db = self._get_db() self._result = None + self.warning_count = 0 self.rowcount = None self.lastrowid = None db.query(q) @@ -339,18 +507,41 @@ def _fetch_row(self, size=1): return self._result.fetch_row(size, self._fetch_type) def __iter__(self): - return iter(self.fetchone, None) + return self - Warning = Warning - Error = Error - InterfaceError = InterfaceError - DatabaseError = DatabaseError - DataError = DataError - OperationalError = OperationalError - IntegrityError = IntegrityError - InternalError = InternalError - ProgrammingError = ProgrammingError - NotSupportedError = NotSupportedError + def __next__(self): + row = self.fetchone() + if row is None: + raise StopIteration + return row + + def __getattr__(self, name): + # DB-API 2.0 optional extension says these errors can be accessed + # via Connection object. But MySQLdb had defined them on Cursor object. + import warnings + + from . import _exceptions as err + + if name in ( + "Warning", + "Error", + "InterfaceError", + "DatabaseError", + "DataError", + "OperationalError", + "IntegrityError", + "InternalError", + "ProgrammingError", + "NotSupportedError", + ): + # Deprecated since v2.3. Will be removed in 2027. + warnings.warn( + "errors should be accessed from `MySQLdb` package", + DeprecationWarning, + stacklevel=2, + ) + return getattr(err, name) + raise AttributeError(name) class CursorStoreResultMixIn: @@ -413,14 +604,8 @@ def scroll(self, value, mode="relative"): raise IndexError("out of range") self.rownumber = r - def __iter__(self): - self._check_executed() - result = self.rownumber and self._rows[self.rownumber :] or self._rows - return iter(result) - class CursorUseResultMixIn: - """This is a MixIn class which causes the result set to be stored in the server and sent row-by-row to client side, i.e. it uses mysql_use_result(). You MUST retrieve the entire result set and @@ -435,6 +620,7 @@ def fetchone(self): self._check_executed() r = self._fetch_row(1) if not r: + self.warning_count = self._get_db().warning_count() return None self.rownumber = self.rownumber + 1 return r[0] @@ -443,7 +629,10 @@ def fetchmany(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() - r = self._fetch_row(size or self.arraysize) + size = size or self.arraysize + r = self._fetch_row(size) + if len(r) < size: + self.warning_count = self._get_db().warning_count() self.rownumber = self.rownumber + len(r) return r @@ -451,20 +640,10 @@ def fetchall(self): """Fetches all available rows from the cursor.""" self._check_executed() r = self._fetch_row(0) + self.warning_count = self._get_db().warning_count() self.rownumber = self.rownumber + len(r) return r - def __iter__(self): - return self - - def next(self): - row = self.fetchone() - if row is None: - raise StopIteration - return row - - __next__ = next - class CursorTupleRowsMixIn: """This is a MixIn class that causes all rows to be returned as tuples, diff --git a/src/MySQLdb/release.py b/src/MySQLdb/release.py index 234d9958..e0ccb338 100644 --- a/src/MySQLdb/release.py +++ b/src/MySQLdb/release.py @@ -1,3 +1,3 @@ __author__ = "Inada Naoki " -__version__ = "2.2.7" -version_info = (2, 2, 7, "final", 0) +__version__ = "2.3.2" +version_info = (2, 3, 2, "final", 0) diff --git a/src/MySQLdb/times.py b/src/MySQLdb/times.py index 915d827b..a920cb30 100644 --- a/src/MySQLdb/times.py +++ b/src/MySQLdb/times.py @@ -4,8 +4,10 @@ Use Python datetime module to handle date and time columns. """ -from time import localtime + from datetime import date, datetime, time, timedelta +from time import localtime + from MySQLdb._mysql import string_literal Date = date @@ -36,10 +38,20 @@ def TimestampFromTicks(ticks): def format_TIMEDELTA(v): - seconds = int(v.seconds) % 60 - minutes = int(v.seconds // 60) % 60 - hours = int(v.seconds // 3600) % 24 - return "%d %d:%d:%d" % (v.days, hours, minutes, seconds) + # Negative timedeltas store the sign in days and keep seconds positive. + # Format the absolute value so the sign is not applied twice by MySQL. + sign = "" + if v.days < 0: + sign = "-" + v = abs(v) + + micros = v.microseconds + minutes, seconds = divmod(v.seconds, 60) + hours, minutes = divmod(minutes, 60) + + if micros: + return f"{sign}{v.days} {hours}:{minutes}:{seconds}.{micros:06d}" + return f"{sign}{v.days} {hours}:{minutes}:{seconds}" def format_TIMESTAMP(d): diff --git a/tests/capabilities.py b/tests/capabilities.py index 1e695e9e..eb218ff7 100644 --- a/tests/capabilities.py +++ b/tests/capabilities.py @@ -1,19 +1,21 @@ #!/usr/bin/env python -O -""" Script to test database capabilities and the DB-API interface - for functionality and memory leaks. +"""Script to test database capabilities and the DB-API interface +for functionality and memory leaks. - Adapted from a script by M-A Lemburg. +Adapted from a script by M-A Lemburg. """ -from time import time + import unittest +from time import time + from configdb import connection_factory class DatabaseTest(unittest.TestCase): db_module = None connect_args = () - connect_kwargs = dict() + connect_kwargs = {} create_table_extra = "" rows = 10 debug = False @@ -161,7 +163,7 @@ def generator(row, col): pass else: self.fail( - "Over-long column did not generate warnings/exception with single insert" # noqa: E501 + "Over-long column did not generate warnings/exception with single insert" ) self.connection.rollback() @@ -176,7 +178,7 @@ def generator(row, col): pass else: self.fail( - "Over-long columns did not generate warnings/exception with execute()" # noqa: E501 + "Over-long columns did not generate warnings/exception with execute()" ) self.connection.rollback() @@ -191,7 +193,7 @@ def generator(row, col): pass else: self.fail( - "Over-long columns did not generate warnings/exception with executemany()" # noqa: E501 + "Over-long columns did not generate warnings/exception with executemany()" ) self.connection.rollback() diff --git a/tests/configdb.py b/tests/configdb.py index c2949039..75814ec9 100644 --- a/tests/configdb.py +++ b/tests/configdb.py @@ -5,10 +5,10 @@ tests_path = path.dirname(__file__) conf_file = environ.get("TESTDB", "default.cnf") conf_path = path.join(tests_path, conf_file) -connect_kwargs = dict( - read_default_file=conf_path, - read_default_group="MySQLdb-tests", -) +connect_kwargs = { + "read_default_file": conf_path, + "read_default_group": "MySQLdb-tests", +} def connection_kwargs(kwargs): diff --git a/tests/dbapi20.py b/tests/dbapi20.py index be0f6292..da13dd25 100644 --- a/tests/dbapi20.py +++ b/tests/dbapi20.py @@ -1,22 +1,22 @@ #!/usr/bin/env python -""" Python DB API 2.0 driver compliance unit test suite. +"""Python DB API 2.0 driver compliance unit test suite. - This software is Public Domain and may be used without restrictions. + This software is Public Domain and may be used without restrictions. - "Now we have booze and barflies entering the discussion, plus rumours of - DBAs on drugs... and I won't tell you what flashes through my mind each - time I read the subject line with 'Anal Compliance' in it. All around - this is turning out to be a thoroughly unwholesome unit test." +"Now we have booze and barflies entering the discussion, plus rumours of + DBAs on drugs... and I won't tell you what flashes through my mind each + time I read the subject line with 'Anal Compliance' in it. All around + this is turning out to be a thoroughly unwholesome unit test." - -- Ian Bicking + -- Ian Bicking """ __rcs_id__ = "$Id$" __version__ = "$Revision$"[11:-2] __author__ = "Stuart Bishop " -import unittest import time +import unittest # $Log$ # Revision 1.1.2.1 2006/02/25 03:44:32 adustman @@ -113,7 +113,6 @@ def setUp(self): """self.drivers should override this method to perform required setup if any is necessary, such as creating the database. """ - pass def tearDown(self): """self.drivers should override this method to perform required cleanup @@ -300,7 +299,7 @@ def test_rowcount(self): self.assertEqual( cur.rowcount, -1, - "cursor.rowcount should be -1 after executing no-result " "statements", + "cursor.rowcount should be -1 after executing no-result statements", ) cur.execute( "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix) @@ -410,12 +409,12 @@ def _paraminsert(self, cur): self.assertEqual( beers[0], "Cooper's", - "cursor.fetchall retrieved incorrect data, or data inserted " "incorrectly", + "cursor.fetchall retrieved incorrect data, or data inserted incorrectly", ) self.assertEqual( beers[1], "Victoria Bitter", - "cursor.fetchall retrieved incorrect data, or data inserted " "incorrectly", + "cursor.fetchall retrieved incorrect data, or data inserted incorrectly", ) def test_executemany(self): @@ -483,7 +482,7 @@ def test_fetchone(self): self.assertEqual( cur.fetchone(), None, - "cursor.fetchone should return None if a query retrieves " "no rows", + "cursor.fetchone should return None if a query retrieves no rows", ) self.assertTrue(cur.rowcount in (-1, 0)) @@ -591,7 +590,7 @@ def test_fetchmany(self): rows.sort() # Make sure we get the right data back out - for i in range(0, 6): + for i in range(6): self.assertEqual( rows[i], self.samples[i], @@ -648,7 +647,7 @@ def test_fetchall(self): ) rows = [r[0] for r in rows] rows.sort() - for i in range(0, len(self.samples)): + for i in range(len(self.samples)): self.assertEqual( rows[i], self.samples[i], "cursor.fetchall retrieved incorrect rows" ) @@ -701,7 +700,7 @@ def test_mixedfetch(self): rows.append(rows4[0]) rows.extend([rows56[0][0], rows56[1][0]]) rows.sort() - for i in range(0, len(self.samples)): + for i in range(len(self.samples)): self.assertEqual( rows[i], self.samples[i], "incorrect data retrieved or inserted" ) diff --git a/tests/test_MySQLdb_capabilities.py b/tests/test_MySQLdb_capabilities.py index dbff27c2..5693faa5 100644 --- a/tests/test_MySQLdb_capabilities.py +++ b/tests/test_MySQLdb_capabilities.py @@ -1,12 +1,13 @@ #!/usr/bin/env python -import capabilities -from datetime import timedelta -from contextlib import closing import unittest -import MySQLdb -from configdb import connection_factory import warnings +from contextlib import closing +from datetime import timedelta +import capabilities +from configdb import connection_factory + +import MySQLdb warnings.filterwarnings("ignore") @@ -14,9 +15,10 @@ class test_MySQLdb(capabilities.DatabaseTest): db_module = MySQLdb connect_args = () - connect_kwargs = dict( - use_unicode=True, sql_mode="ANSI,STRICT_TRANS_TABLES,TRADITIONAL" - ) + connect_kwargs = { + "use_unicode": True, + "sql_mode": "ANSI,STRICT_TRANS_TABLES,TRADITIONAL", + } create_table_extra = "ENGINE=INNODB CHARACTER SET UTF8" leak_test = False @@ -45,7 +47,7 @@ def test_stored_procedures(self): self.create_table(("pos INT", "tree CHAR(20)")) c.executemany( "INSERT INTO %s (pos,tree) VALUES (%%s,%%s)" % self.table, - list(enumerate("ash birch cedar Lärche pine".split())), + list(enumerate(["ash", "birch", "cedar", "Lärche", "pine"])), ) db.commit() @@ -185,15 +187,17 @@ def test_binary_prefix(self): if binary_prefix is not None: kwargs["binary_prefix"] = binary_prefix - with closing(connection_factory(**kwargs)) as conn: - with closing(conn.cursor()) as c: - c.execute("SELECT CHARSET(%s)", (MySQLdb.Binary(b"raw bytes"),)) - self.assertEqual( - c.fetchall()[0][0], "binary" if binary_prefix else "utf8mb4" - ) - # normal strings should not get prefix - c.execute("SELECT CHARSET(%s)", ("str",)) - self.assertEqual(c.fetchall()[0][0], "utf8mb4") + with ( + closing(connection_factory(**kwargs)) as conn, + closing(conn.cursor()) as c, + ): + c.execute("SELECT CHARSET(%s)", (MySQLdb.Binary(b"raw bytes"),)) + self.assertEqual( + c.fetchall()[0][0], "binary" if binary_prefix else "utf8mb4" + ) + # normal strings should not get prefix + c.execute("SELECT CHARSET(%s)", ("str",)) + self.assertEqual(c.fetchall()[0][0], "utf8mb4") if __name__ == "__main__": diff --git a/tests/test_MySQLdb_dbapi20.py b/tests/test_MySQLdb_dbapi20.py index a0dd92a1..3d297446 100644 --- a/tests/test_MySQLdb_dbapi20.py +++ b/tests/test_MySQLdb_dbapi20.py @@ -1,10 +1,12 @@ #!/usr/bin/env python -import dbapi20 import unittest -import MySQLdb -from configdb import connection_kwargs import warnings +import dbapi20 +from configdb import connection_kwargs + +import MySQLdb + warnings.simplefilter("ignore") @@ -12,7 +14,7 @@ class test_MySQLdb(dbapi20.DatabaseAPI20Test): driver = MySQLdb connect_args = () connect_kw_args = connection_kwargs( - dict(sql_mode="ANSI,STRICT_TRANS_TABLES,TRADITIONAL") + {"sql_mode": "ANSI,STRICT_TRANS_TABLES,TRADITIONAL"} ) def test_setoutputsize(self): @@ -53,7 +55,7 @@ def test_fetchall(self): ) rows = [r[0] for r in rows] rows.sort() - for i in range(0, len(self.samples)): + for i in range(len(self.samples)): self.assertEqual( rows[i], self.samples[i], "cursor.fetchall retrieved incorrect rows" ) @@ -98,7 +100,7 @@ def test_fetchone(self): self.assertEqual( cur.fetchone(), None, - "cursor.fetchone should return None if a query retrieves " "no rows", + "cursor.fetchone should return None if a query retrieves no rows", ) self.assertTrue(cur.rowcount in (-1, 0)) @@ -172,9 +174,7 @@ def help_nextset_setUp(self, cur): select count(*) from %(tp)sbooze; select name from %(tp)sbooze; end - """ % dict( - tp=self.table_prefix - ) + """ % {"tp": self.table_prefix} cur.execute(sql) def help_nextset_tearDown(self, cur): diff --git a/tests/test_MySQLdb_nonstandard.py b/tests/test_MySQLdb_nonstandard.py index 5e841791..2e3f0a0a 100644 --- a/tests/test_MySQLdb_nonstandard.py +++ b/tests/test_MySQLdb_nonstandard.py @@ -1,10 +1,11 @@ import unittest +import warnings + +from configdb import connection_factory -from MySQLdb import _mysql import MySQLdb +from MySQLdb import _mysql from MySQLdb.constants import FIELD_TYPE -from configdb import connection_factory -import warnings warnings.simplefilter("ignore") diff --git a/tests/test_MySQLdb_times.py b/tests/test_MySQLdb_times.py index 2081b1ac..8b3509ed 100644 --- a/tests/test_MySQLdb_times.py +++ b/tests/test_MySQLdb_times.py @@ -1,12 +1,11 @@ -from datetime import time, date, datetime, timedelta -from time import gmtime import unittest -from unittest import mock import warnings +from datetime import date, datetime, time, timedelta +from time import gmtime +from unittest import mock from MySQLdb import times - warnings.simplefilter("ignore") @@ -121,6 +120,7 @@ def test_datetime_to_literal(self): def test_datetimedelta_to_literal(self): d = datetime(2015, 12, 13, 1, 2, 3) - datetime(2015, 12, 13, 1, 2, 2) assert times.DateTimeDelta2literal(d, "") == b"'0 0:0:1'" + assert times.DateTimeDelta2literal(-timedelta(minutes=30), "") == b"'-0 0:30:0'" class TestFormat(unittest.TestCase): @@ -132,7 +132,13 @@ def test_format_timedelta(self): assert times.format_TIMEDELTA(d) == "0 2:2:2" d = datetime(2015, 1, 1, 10, 11, 12) - datetime(2015, 1, 1, 11, 12, 13) - assert times.format_TIMEDELTA(d) == "-1 22:58:59" + assert times.format_TIMEDELTA(d) == "-0 1:1:1" + + assert times.format_TIMEDELTA(-timedelta(minutes=30)) == "-0 0:30:0" + assert times.format_TIMEDELTA(-timedelta(days=1, hours=2)) == "-1 2:0:0" + d = timedelta(seconds=83579, microseconds=51000) + assert times.format_TIMEDELTA(d) == "0 23:12:59.051000" + assert times.format_TIMEDELTA(-d) == "-0 23:12:59.051000" def test_format_timestamp(self): assert times.format_TIMESTAMP(datetime(2015, 2, 3)) == "2015-02-03 00:00:00" diff --git a/tests/test__mysql.py b/tests/test__mysql.py index dd024b72..bbb4f3c9 100644 --- a/tests/test__mysql.py +++ b/tests/test__mysql.py @@ -1,7 +1,47 @@ import pytest + from MySQLdb import _mysql +from MySQLdb.connections import Connection + + +@pytest.mark.parametrize("data", [b"", b"a'\x00\\\xffb"]) +def test_string_literal_bytearray(data): + class Subclass(bytearray): + def __str__(self): + raise AssertionError("string_literal should use the byte contents") + + expected = _mysql.string_literal(data) + assert _mysql.string_literal(bytearray(data)) == expected + assert _mysql.string_literal(Subclass(data)) == expected def test_result_type(): with pytest.raises(TypeError): _mysql.result(b"xyz") + + +@pytest.mark.parametrize("connection_type", [_mysql.connection, Connection]) +@pytest.mark.parametrize("name", [5, None, b"closed", [], {}]) +def test_connection_getattribute_non_string(connection_type, name): + conn = connection_type.__new__(connection_type) + with pytest.raises(TypeError): + conn.__getattribute__(name) + + +@pytest.mark.parametrize("connection_type", [_mysql.connection, Connection]) +@pytest.mark.parametrize("name", ["missing", "closed\x00suffix", "\ud800"]) +def test_connection_getattribute_missing(connection_type, name): + conn = connection_type.__new__(connection_type) + with pytest.raises(AttributeError): + conn.__getattribute__(name) + + +@pytest.mark.parametrize("connection_type", [_mysql.connection, Connection]) +def test_connection_getattribute(connection_type): + class AttributeName(str): + pass + + conn = connection_type.__new__(connection_type) + assert conn.closed == 1 + assert conn.__getattribute__(AttributeName("closed")) == 1 + assert conn.__class__ is connection_type diff --git a/tests/test_connection.py b/tests/test_connection.py index 960de572..6efacdd9 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -1,26 +1,251 @@ +import enum +import threading +import time +from concurrent.futures import ThreadPoolExecutor + import pytest +from configdb import connection_factory, connection_kwargs from MySQLdb._exceptions import ProgrammingError +from MySQLdb.connections import Connection +from MySQLdb.constants import CLIENT, FIELD_TYPE + + +@pytest.fixture +def conn(): + connection = connection_factory() + try: + yield connection + finally: + connection.close() + + +@pytest.mark.parametrize("sql_mode", ["", "NO_BACKSLASH_ESCAPES"]) +def test_literal_str_enum(conn, sql_mode): + class Foo(str, enum.Enum): + BAR = "BAR" + BAZ = "BAZ" + + conn.set_sql_mode(sql_mode) + assert conn.literal(Foo.BAR) == b"'BAR'" + assert conn.literal((Foo.BAR, Foo.BAZ)) == b"('BAR','BAZ')" + cursor = conn.cursor() + cursor.execute("SELECT %s", (Foo.BAR,)) + assert cursor.fetchone() == ("BAR",) + + +@pytest.mark.parametrize("value", ["BAR", b"BAR"]) +@pytest.mark.parametrize("binary_prefix", [False, True]) +def test_literal_string_subclass(value, binary_prefix): + class Subclass(type(value)): + pass + + with connection_factory(binary_prefix=binary_prefix) as conn: + assert conn.literal(Subclass(value)) == conn.literal(value) + + +@pytest.mark.parametrize("binary_prefix", [False, True]) +def test_literal_bytearray_subclass(binary_prefix): + class Subclass(bytearray): + pass + + data = b"A'\x00\\B" + value = Subclass(data) + with connection_factory(binary_prefix=binary_prefix) as conn: + assert conn.literal(value) == conn.literal(data) + cursor = conn.cursor() + cursor.execute("SELECT %s", (value,)) + expected = data if binary_prefix else data.decode(conn.encoding) + assert cursor.fetchone() == (expected,) + -from configdb import connection_factory +@pytest.mark.parametrize("container_type", [tuple, list, set, frozenset]) +def test_literal_container_subclass_converter(conn, container_type): + class Subclass(container_type): + pass + + conn.encoders[Subclass] = lambda value, mapping: b"'custom'" + cursor = conn.cursor() + cursor.execute("SELECT %s", (Subclass(["BAR"]),)) + assert cursor.fetchone() == ("custom",) + + +@pytest.mark.parametrize("set_type", [set, frozenset]) +@pytest.mark.parametrize("sql_mode", ["", "NO_BACKSLASH_ESCAPES"]) +@pytest.mark.parametrize("charset", ["utf8mb4", "latin1"]) +def test_literal_set_escaping(set_type, sql_mode, charset): + value = "é' OR 1=1 -- \\" + with connection_factory(charset=charset, sql_mode=sql_mode) as conn: + cursor = conn.cursor() + cursor.execute("SELECT %s", (set_type([value]),)) + assert cursor.fetchone() == (value,) + with pytest.raises(TypeError, match="set elements must be strings"): + conn.literal(set_type([1])) -def test_multi_statements_default_true(): - conn = connection_factory() +def test_multi_statements_default_true(conn): cursor = conn.cursor() cursor.execute("select 17; select 2") + assert conn.more_results() is True rows = cursor.fetchall() assert rows == ((17,),) + assert cursor.nextset() == 1 + assert conn.more_results() is False def test_multi_statements_false(): conn = connection_factory(multi_statements=False) - cursor = conn.cursor() + try: + cursor = conn.cursor() + assert not conn.client_flag & CLIENT.MULTI_STATEMENTS - with pytest.raises(ProgrammingError): - cursor.execute("select 17; select 2") + with pytest.raises(ProgrammingError): + cursor.execute("select 17; select 2") - cursor.execute("select 17") - rows = cursor.fetchall() - assert rows == ((17,),) + cursor.execute("select 17") + rows = cursor.fetchall() + assert rows == ((17,),) + finally: + conn.close() + + +def test_executemany_fallback_option(): + with connection_factory() as conn: + assert conn.executemany_fallback == "loop" + + with connection_factory(executemany_fallback="multi") as conn: + assert conn.executemany_fallback == "multi" + + with pytest.raises(ValueError, match="executemany_fallback"): + connection_factory(executemany_fallback="invalid") + + +def test_executemany_fallback_connection_subclass_default(): + class MultiConnection(Connection): + executemany_fallback = "multi" + + with MultiConnection(**connection_kwargs({})) as conn: + assert conn.executemany_fallback == "multi" + + with MultiConnection(**connection_kwargs({"executemany_fallback": "loop"})) as conn: + assert conn.executemany_fallback == "loop" + + +def test_ping_false_warns(conn): + with pytest.warns(DeprecationWarning, match="reconnect parameter"): + conn.ping(False) + + +def test_connection_concurrent_use_raises(conn): + """While a slow query holds the connection lock, any other access from + a second thread must raise ProgrammingError immediately (not block).""" + thread_error = None + done = threading.Event() + + def run_slow_query(): + nonlocal thread_error + try: + conn.query("SELECT SLEEP(0.5)") + result = conn.store_result() + result.fetch_row() + except Exception as exc: # pragma: no cover + thread_error = exc + finally: + done.set() + + thread = threading.Thread(target=run_slow_query) + thread.start() + + # Give the background thread time to acquire the lock and enter SLEEP. + time.sleep(0.1) + + start = time.monotonic() + with pytest.raises(ProgrammingError, match="already in use"): + conn.thread_id() + # Should fail immediately, not wait for the SLEEP to finish. + assert time.monotonic() - start < 0.1 + + done.wait() + thread.join() + assert thread_error is None + + +@pytest.mark.parametrize("use", [False, True]) +def test_result_rejects_reinitialization(conn, use): + conn.query("SELECT 1 UNION ALL SELECT 2 ORDER BY 1") + result = conn.use_result() if use else conn.store_result() + with pytest.raises(ProgrammingError, match="already initialized"): + result.__init__(conn, not use) + + assert result.fetch_row() == ((1,),) + del result # Leave the second row for cleanup. + conn.query("SELECT 3") + assert conn.store_result().fetch_row() == ((3,),) + + +def test_stored_result_dealloc_while_connection_locked(conn): + stored = [] + + def store_result(): + conn.query("SELECT 1") + stored.append(conn.store_result()) + + with ThreadPoolExecutor(max_workers=1) as executor: + # On free-threaded CPython, drop the last reference on its owning thread. + executor.submit(store_result).result() + + def convert(value): + # fetch_row holds the connection lock while calling this converter. + executor.submit(stored.clear).result(timeout=5) + return int(value) + + conn.converter[FIELD_TYPE.NEWDECIMAL] = convert + conn.query("SELECT CAST(2 AS DECIMAL(1,0))") + assert conn.use_result().fetch_row() == ((2,),) + assert not stored + + +def test_result_concurrent_use_raises(conn): + """While fetch_row holds the connection lock streaming a slow result, + any other access from a second thread must raise ProgrammingError immediately.""" + conn.query( + "SELECT 1 FROM information_schema.tables a " + "CROSS JOIN information_schema.tables b LIMIT 20000" + ) + result = conn.use_result() + + thread_error = None + done = threading.Event() + started = threading.Event() + + def fetch_all_rows(): + nonlocal thread_error + try: + started.set() + rows = result.fetch_row(maxrows=0) + assert rows + except Exception as exc: # pragma: no cover + thread_error = exc + finally: + done.set() + + thread = threading.Thread(target=fetch_all_rows) + thread.start() + + assert started.wait(timeout=1.0) + + deadline = time.monotonic() + 1.0 + while time.monotonic() < deadline: + try: + conn.thread_id() + except ProgrammingError as exc: + assert "already in use" in str(exc) + break + time.sleep(0.01) + else: # pragma: no cover + pytest.fail("expected ProgrammingError while result.fetch_row() is running") + + done.wait() + thread.join() + assert thread_error is None diff --git a/tests/test_cursor.py b/tests/test_cursor.py index 1d2c3655..3a9b2af5 100644 --- a/tests/test_cursor.py +++ b/tests/test_cursor.py @@ -1,7 +1,13 @@ +from textwrap import dedent +from types import SimpleNamespace + import pytest -import MySQLdb.cursors from configdb import connection_factory +import MySQLdb.cursors +from MySQLdb._exceptions import IntegrityError, InternalError, OperationalError +from MySQLdb.constants import CLIENT, ER +from MySQLdb.converters import conversions _conns = [] _tables = [] @@ -56,9 +62,9 @@ def test_executemany(): "INSERT INTO TEST (ID, NAME) VALUES (%(id_name)s, %(name)s) ON duplicate update" ) assert m is not None, "error parse %(id_name)s" - assert ( - m.group(3) == " ON duplicate update" - ), "group 3 not ON duplicate update, bug in RE_INSERT_VALUES?" + assert m.group(3) == " ON duplicate update", ( + "group 3 not ON duplicate update, bug in RE_INSERT_VALUES?" + ) # https://github.com/PyMySQL/mysqlclient-python/issues/178 m = MySQLdb.cursors.RE_INSERT_VALUES.match( @@ -74,16 +80,24 @@ def test_executemany(): # list args data = [(i,) for i in range(10)] cursor.executemany("insert into test (data) values (%s)", data) - assert cursor._executed.endswith( - b",(7),(8),(9)" - ), "execute many with %s not in one query" + assert cursor._executed.endswith(b",(7),(8),(9)"), ( + "execute many with %s not in one query" + ) + + # bytes and bytearray queries use the same INSERT/REPLACE fast path. + cursor.executemany(b"insert into test (data) values (%s)", [(10,), (11,)]) + assert cursor._executed.endswith(b"(10),(11)") + cursor.executemany( + bytearray(b"insert into test (data) values (%s)"), [(12,), (13,)] + ) + assert cursor._executed.endswith(b"(12),(13)") # dict args data_dict = [{"data": i} for i in range(10)] cursor.executemany("insert into test (data) values (%(data)s)", data_dict) - assert cursor._executed.endswith( - b",(7),(8),(9)" - ), "execute many with %(data)s not in one query" + assert cursor._executed.endswith(b",(7),(8),(9)"), ( + "execute many with %(data)s not in one query" + ) # %% in column set cursor.execute( @@ -96,13 +110,470 @@ def test_executemany(): q = "INSERT INTO percent_test (`A%%`, `B%%`) VALUES (%s, %s)" assert MySQLdb.cursors.RE_INSERT_VALUES.match(q) is not None cursor.executemany(q, [(3, 4), (5, 6)]) - assert cursor._executed.endswith( - b"(3, 4),(5, 6)" - ), "executemany with %% not in one query" + assert cursor._executed.endswith(b"(3, 4),(5, 6)"), ( + "executemany with %% not in one query" + ) finally: cursor.execute("DROP TABLE IF EXISTS percent_test") +@pytest.mark.parametrize( + "Cursor", [MySQLdb.cursors.Cursor, MySQLdb.cursors.SSCursor] +) +def test_executemany_multi_update(Cursor): + conn = connect(executemany_fallback="multi") + cursor = conn.cursor(Cursor) + cursor.execute( + "CREATE TABLE executemany_multi_update " + "(id int primary key, data varchar(100))" + ) + _tables.append("executemany_multi_update") + cursor.executemany( + "INSERT INTO executemany_multi_update (id, data) VALUES (%s, %s)", + [(1, 0), (2, 0), (3, 0)], + ) + assert MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR not in cursor._executed + assert b"),(" in cursor._executed + + rows = cursor.executemany( + "UPDATE executemany_multi_update " + "SET data=%(data)s WHERE id=%(id)s", + [ + {"id": 1, "data": "ten;still-a-value"}, + {"id": 2, "data": "twenty"}, + {"id": 3, "data": "thirty"}, + ], + ) + + assert rows == 3 + assert cursor.rowcount == 3 + assert cursor.description is None + assert cursor._executed.count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) == 2 + assert conn.affected_rows() == 1 + assert conn.warning_count() == 0 + assert conn.more_results() is False + + cursor.execute("SELECT id, data FROM executemany_multi_update ORDER BY id") + assert cursor.fetchall() == ( + (1, "ten;still-a-value"), + (2, "twenty"), + (3, "thirty"), + ) + + +def test_executemany_multi_delete(): + conn = connect(executemany_fallback="multi") + cursor = conn.cursor() + cursor.execute( + "CREATE TABLE executemany_multi_delete (id int primary key, data int)" + ) + _tables.append("executemany_multi_delete") + cursor.executemany( + "INSERT INTO executemany_multi_delete (id, data) VALUES (%s, %s)", + [(1, 10), (2, 20), (3, 30)], + ) + + assert ( + cursor.executemany( + "DELETE FROM executemany_multi_delete WHERE id=%s", [(1,), (3,)] + ) + == 2 + ) + assert cursor.rowcount == 2 + assert cursor._executed.count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) == 1 + assert conn.affected_rows() == 1 + cursor.execute("SELECT id FROM executemany_multi_delete") + assert cursor.fetchall() == ((2,),) + + +def test_executemany_multi_keeps_last_statement_metadata(): + conn = connect(executemany_fallback="multi") + cursor = conn.cursor() + cursor.execute( + "CREATE TABLE executemany_multi_metadata " + "(id int primary key auto_increment, data varchar(1))" + ) + _tables.append("executemany_multi_metadata") + + assert ( + cursor.executemany( + "INSERT IGNORE INTO executemany_multi_metadata SET data=%s", + [("a",), ("b",), ("too long",)], + ) + == 3 + ) + assert cursor.rowcount == 3 + assert cursor.lastrowid == 3 + assert conn.insert_id() == 3 + assert conn.affected_rows() == 1 + assert conn.warning_count() > 0 + assert conn.more_results() is False + + +def test_executemany_multi_policy_and_capability(): + conn = connect() + cursor = conn.cursor() + cursor.execute( + "CREATE TABLE executemany_multi_policy (id int primary key, data int)" + ) + _tables.append("executemany_multi_policy") + cursor.executemany( + "INSERT INTO executemany_multi_policy (id, data) VALUES (%s, %s)", + [(1, 0), (2, 0)], + ) + + query = "UPDATE executemany_multi_policy SET data=%s WHERE id=%s" + cursor.executemany(query, [(10, 1), (20, 2)]) + assert MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR not in cursor._executed + + class MultiCursor(MySQLdb.cursors.Cursor): + executemany_fallback = "multi" + + subclass_cursor = conn.cursor(MultiCursor) + subclass_cursor.executemany(query, [(11, 1), (21, 2)]) + assert ( + subclass_cursor._executed.count( + MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR + ) + == 1 + ) + + cursor.executemany_fallback = "multi" + cursor.executemany(query, [(12, 1), (22, 2)]) + assert cursor._executed.count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) == 1 + assert cursor.executemany( + query + " -- trailing comment", [(13, 1), (23, 2)] + ) == 2 + assert cursor._executed.count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) == 1 + + cursor.executemany_fallback = "loop" + cursor.executemany(query, [(14, 1), (24, 2)]) + assert MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR not in cursor._executed + + with pytest.raises(ValueError, match="executemany_fallback"): + cursor.executemany_fallback = "invalid" + cursor.executemany(query, [(15, 1), (25, 2)]) + + conn.commit() + no_multi_conn = connect( + executemany_fallback="multi", multi_statements=False + ) + no_multi_cursor = no_multi_conn.cursor() + no_multi_cursor.executemany(query, [(16, 1), (26, 2)]) + assert ( + MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR + not in no_multi_cursor._executed + ) + no_multi_conn.rollback() + + +@pytest.mark.parametrize( + ("query", "expected"), + [ + ("UPDATE t SET value=%s", True), + (b"DELETE FROM t WHERE id=%s", True), + (bytearray(b"UPDATE t SET value=%s"), True), + ("INSERT INTO t SET value=%s", True), + ("REPLACE INTO t SET value=%s", True), + ("WITH values_ AS (SELECT 1) UPDATE t SET value=%s", False), + ("UPDATE t SET value=%s;", False), + ("UPDATE t SET value=%s RETURNING id", False), + ("SELECT %s", False), + ("/* comment */ UPDATE t SET value=%s", False), + ], +) +def test_is_executemany_dml(query, expected): + assert MySQLdb.cursors._is_executemany_dml(query) is expected + + +def test_executemany_multi_batch_limits_and_single_arg(): + class RecordingCursor(MySQLdb.cursors.Cursor): + max_multi_stmt_length = 1_000_000 + max_multi_stmt_count = 2 + + def __init__(self, connection): + super().__init__(connection) + self.execute_calls = [] + + def execute(self, query, args=None): + self.execute_calls.append((query, args)) + return super().execute(query, args) + + conn = connect(executemany_fallback="multi") + cursor = conn.cursor(RecordingCursor) + cursor.execute( + "CREATE TABLE executemany_multi_limits " + "(id int primary key, data text)" + ) + _tables.append("executemany_multi_limits") + cursor.executemany( + "INSERT INTO executemany_multi_limits (id, data) VALUES (%s, %s)", + [(i, 0) for i in range(1, 7)], + ) + + query = "UPDATE executemany_multi_limits SET data=%s WHERE id=%s" + cursor.execute_calls.clear() + assert cursor.executemany(query, [(i * 10, i) for i in range(1, 6)]) == 5 + assert len(cursor.execute_calls) == 3 + assert [ + bytes(q).count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) + for q, args in cursor.execute_calls + ] == [1, 1, 0] + assert all(args is None for query, args in cursor.execute_calls) + assert cursor.rowcount == 5 + assert conn.affected_rows() == 1 + + first_arg = ("a", 1) + second_base_arg = ("", 2) + first_statement = cursor._mogrify(query, first_arg) + second_base_statement = cursor._mogrify(query, second_base_arg) + filler_length = ( + 16_000 + - len(first_statement) + - len(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) + - len(second_base_statement) + ) + boundary_args = [first_arg, ("x" * filler_length, 2), ("c", 3)] + cursor.max_multi_stmt_count = 200 + cursor.max_multi_stmt_length = 16_000 + cursor.execute_calls.clear() + assert cursor.executemany(query, boundary_args) == 3 + assert len(cursor.execute_calls) == 2 + assert len(cursor.execute_calls[0][0]) == 16_000 + + cursor.max_multi_stmt_length = 1_000_000 + cursor.max_multi_stmt_count = 200 + cursor.execute_calls.clear() + assert ( + cursor.executemany( + "DELETE FROM executemany_multi_limits WHERE id=%s", + [(1000 + i,) for i in range(201)], + ) + == 0 + ) + assert len(cursor.execute_calls) == 2 + assert [ + bytes(q).count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) + for q, args in cursor.execute_calls + ] == [199, 0] + + cursor.execute_calls.clear() + arg = (60, 6) + assert cursor.executemany(query, [arg]) == 1 + assert cursor.execute_calls == [(cursor._mogrify(query, arg), None)] + + assert MySQLdb.cursors.BaseCursor.max_multi_stmt_length == 16_000 + assert MySQLdb.cursors.BaseCursor.max_multi_stmt_count == 200 + + +def test_executemany_multi_streams_arguments(): + class RecordingCursor(MySQLdb.cursors.Cursor): + max_multi_stmt_count = 2 + + def _mogrify(self, query, args): + return (query % args).encode() + + def execute(self, query, args=None): + calls.append(query) + self.rowcount = 1 + return 1 + + def _execute_multi_statement_batch(self, query, statement_count): + if statement_count == 1: + return super()._execute_multi_statement_batch(query, statement_count) + calls.append(query) + return statement_count + + calls = [] + cursor = RecordingCursor( + SimpleNamespace( + executemany_fallback="multi", client_flag=CLIENT.MULTI_STATEMENTS + ) + ) + + def params(): + yield (1,) + yield (2,) + yield (3,) + assert len(calls) == 1 + yield (4,) + yield (5,) + + query = "UPDATE t SET value=%s" + assert cursor.executemany(query, params()) == 5 + assert len(calls) == 3 + assert calls[-1] == b"UPDATE t SET value=5" + assert cursor.rowcount == 5 + assert cursor.executemany(query, iter(())) is None + assert len(calls) == 3 + assert cursor.rowcount == 5 + + calls.clear() + cursor.max_multi_stmt_length = 1 + assert cursor.executemany(query, iter([(6,), (7,)])) == 2 + assert calls == [b"UPDATE t SET value=6", b"UPDATE t SET value=7"] + + +def test_executemany_multi_oversized_statement_runs_alone(): + class TinyBatchCursor(MySQLdb.cursors.Cursor): + max_multi_stmt_length = 1 + + def __init__(self, connection): + super().__init__(connection) + self.execute_calls = [] + + def execute(self, query, args=None): + self.execute_calls.append((query, args)) + return super().execute(query, args) + + conn = connect(executemany_fallback="multi") + cursor = conn.cursor(TinyBatchCursor) + cursor.execute( + "CREATE TABLE executemany_multi_oversized (id int primary key, data int)" + ) + _tables.append("executemany_multi_oversized") + cursor.execute_calls.clear() + + query = "UPDATE executemany_multi_oversized SET data=%s WHERE id=%s" + cursor.executemany(query, [(10, 1), (20, 2)]) + assert len(cursor.execute_calls) == 2 + assert all( + MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR not in bytes(q) + for q, args in cursor.execute_calls + ) + + +@pytest.mark.parametrize("fallback", ["loop", "multi"]) +def test_executemany_multi_generator_and_empty_generator(fallback): + conn = connect(executemany_fallback=fallback) + cursor = conn.cursor() + cursor.execute( + "CREATE TABLE executemany_multi_generator (id int primary key, data int)" + ) + _tables.append("executemany_multi_generator") + insert = "INSERT INTO executemany_multi_generator (id, data) VALUES (%s, %s)" + assert cursor.executemany(insert, ((i, 0) for i in range(1, 4))) == 3 + assert cursor.executemany(insert, iter(())) is None + assert cursor.rowcount == 3 + + query = "UPDATE executemany_multi_generator SET data=%s WHERE id=%s" + params = ((i * 10, i) for i in range(1, 4)) + assert cursor.executemany(query, params) == 3 + if fallback == "multi": + assert cursor._executed.count(MySQLdb.cursors._EXECUTEMANY_MULTI_SEPARATOR) == 2 + assert cursor.executemany(query, iter(())) is None + assert cursor.rowcount == 3 + + cursor.execute("SELECT id, data FROM executemany_multi_generator ORDER BY id") + assert cursor.fetchall() == ((1, 10), (2, 20), (3, 30)) + + +@pytest.mark.parametrize( + ("args", "expected_ids"), + [ + ([(99, 10), (1, 10), (2, 20)], (99,)), + ([(1, 10), (99, 10), (2, 20)], (1, 99)), + ([(1, 10), (2, 20), (99, 10)], (1, 2, 99)), + ], +) +def test_executemany_multi_sql_error(args, expected_ids): + conn = connect(executemany_fallback="multi") + cursor = conn.cursor() + cursor.execute( + "CREATE TABLE executemany_multi_error (id int primary key, data int)" + ) + _tables.append("executemany_multi_error") + cursor.execute("INSERT INTO executemany_multi_error VALUES (99, 0)") + + with pytest.raises(IntegrityError): + cursor.executemany( + "INSERT INTO executemany_multi_error SET id=%s, data=%s", args + ) + + assert cursor.rowcount is None + assert conn.open + assert conn.more_results() is False + cursor.execute("SELECT id FROM executemany_multi_error ORDER BY id") + assert tuple(row[0] for row in cursor.fetchall()) == expected_ids + + +@pytest.mark.parametrize( + "Cursor", [MySQLdb.cursors.Cursor, MySQLdb.cursors.SSCursor] +) +def test_executemany_multi_rejects_unexpected_result_count(Cursor): + class RawSQL: + pass + + def raw_sql_literal(value, conv): + return b"1; SELECT 1" + + cleanup_conn = connect() + cleanup_cursor = cleanup_conn.cursor() + cleanup_cursor.execute( + "CREATE TABLE executemany_multi_result_count (id int primary key, data int)" + ) + _tables.append("executemany_multi_result_count") + cleanup_cursor.execute( + "INSERT INTO executemany_multi_result_count VALUES (1, 0)" + ) + cleanup_conn.commit() + + custom_conversions = conversions.copy() + custom_conversions[RawSQL] = raw_sql_literal + conn = connect(executemany_fallback="multi", conv=custom_conversions) + cursor = conn.cursor(Cursor) + + with pytest.raises(InternalError, match="multi-statement executemany"): + cursor.executemany( + "UPDATE executemany_multi_result_count SET data=%s", + [(RawSQL(),), (RawSQL(),)], + ) + + assert not conn.open + _conns.remove(conn) + + +@pytest.mark.parametrize( + "failure", [KeyboardInterrupt(), OperationalError(2013, "server lost")] +) +def test_executemany_multi_drain_failure_closes_connection(failure): + class FailingCursor(MySQLdb.cursors.Cursor): + armed = False + result_number = 0 + + def _do_get_result(self, db): + super()._do_get_result(db) + if self.armed: + self.result_number += 1 + if self.result_number == 2: + raise failure + + cleanup_conn = connect() + cleanup_cursor = cleanup_conn.cursor() + cleanup_cursor.execute( + "CREATE TABLE executemany_multi_drain_failure " + "(id int primary key, data int)" + ) + _tables.append("executemany_multi_drain_failure") + cleanup_cursor.execute( + "INSERT INTO executemany_multi_drain_failure VALUES (1, 0), (2, 0)" + ) + cleanup_conn.commit() + + conn = connect(executemany_fallback="multi") + cursor = conn.cursor(FailingCursor) + cursor.armed = True + with pytest.raises(type(failure)) as exc_info: + cursor.executemany( + "UPDATE executemany_multi_drain_failure SET data=%s WHERE id=%s", + [(10, 1), (20, 2)], + ) + + assert exc_info.value is failure + assert not conn.open + _conns.remove(conn) + + def test_pyparam(): conn = connect() cursor = conn.cursor() @@ -243,3 +714,88 @@ def test_binary_prefix(): "INSERT INTO test_binary_prefix (id, json) VALUES (%(id)s, %(json)s)", ({"id": 1, "json": "{}"}, {"id": 2, "json": "{}"}), ) + + +def test_warning_count(): + conn = connect() + cursor = conn.cursor() + + cursor.execute("DROP TABLE IF EXISTS `no_exists_table`") + assert cursor.warning_count == 1 + + cursor.execute("SHOW WARNINGS") + warning = cursor.fetchone() + assert warning[1] == ER.BAD_TABLE_ERROR + assert "no_exists_table" in warning[2] + + cursor.execute("SELECT 1") + assert cursor.warning_count == 0 + + +def test_sscursor_warning_count(): + conn = connect() + cursor = conn.cursor(MySQLdb.cursors.SSCursor) + + cursor.execute("DROP TABLE IF EXISTS `no_exists_table`") + assert cursor.warning_count == 1 + + cursor.execute("SHOW WARNINGS") + warning = cursor.fetchone() + assert warning[1] == ER.BAD_TABLE_ERROR + assert "no_exists_table" in warning[2] + assert cursor.fetchone() is None + + cursor.execute("SELECT 1") + assert cursor.fetchone() == (1,) + assert cursor.fetchone() is None + assert cursor.warning_count == 0 + + cursor.execute("SELECT CAST('abc' AS SIGNED)") + rows = cursor.fetchmany(2) + assert len(rows) == 1 + assert cursor.warning_count == 1 + + +@pytest.mark.parametrize("Cursor", [MySQLdb.cursors.Cursor, MySQLdb.cursors.SSCursor]) +def test_cursor_is_iterator(Cursor): + conn = connect() + cursor = conn.cursor(Cursor) + + cursor.execute("DROP TABLE IF EXISTS test_cursor_is_iterator") + cursor.execute( + "CREATE TABLE test_cursor_is_iterator (id INT PRIMARY KEY, name VARCHAR(20))" + ) + _tables.append("test_cursor_is_iterator") + cursor.executemany( + "INSERT INTO test_cursor_is_iterator (id, name) VALUES (%s, %s)", + [(1, "a"), (2, "b"), (3, "c")], + ) + + cursor.execute("SELECT name FROM test_cursor_is_iterator ORDER BY id") + assert iter(cursor) is cursor + assert next(cursor) == ("a",) + assert next(cursor) == ("b",) + assert next(cursor) == ("c",) + with pytest.raises(StopIteration): + next(cursor) + + +def test_callproc_escaping(): + conn = connect() + cur = conn.cursor() + + cur.execute("DROP PROCEDURE IF EXISTS `foo.bar`") + try: + cur.execute( + dedent("""\ + create procedure `foo.bar` (arg1 int) + begin + select arg1*2; + end + """) + ) + + cur.callproc("foo.bar", args=(123,)) + assert cur.fetchone()[0] == 246 + finally: + cur.execute("DROP PROCEDURE IF EXISTS `foo.bar`") diff --git a/tests/test_errors.py b/tests/test_errors.py index fae28e81..a6c12997 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -1,7 +1,7 @@ import pytest -import MySQLdb.cursors from configdb import connection_factory +import MySQLdb.cursors _conns = [] _tables = [] diff --git a/tests/test_sqlalchemy.py b/tests/test_sqlalchemy.py new file mode 100644 index 00000000..fb99a174 --- /dev/null +++ b/tests/test_sqlalchemy.py @@ -0,0 +1,151 @@ +from contextlib import contextmanager + +import pytest + + +pytest.importorskip("sqlalchemy", minversion="2.0") + +from sqlalchemy import ( + Integer, + bindparam, + create_engine, + delete, + event, + insert, + select, + update, +) +from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column +from sqlalchemy.pool import NullPool + +from MySQLdb.constants import CLIENT +from configdb import connection_kwargs + + +class Base(DeclarativeBase): + pass + + +class BulkRow(Base): + __tablename__ = "test_sqlalchemy_executemany" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + value: Mapped[int] = mapped_column(Integer, nullable=False) + + +@pytest.fixture(scope="module") +def engine(): + engine = create_engine( + "mysql+mysqldb://", + connect_args=connection_kwargs({"executemany_fallback": "multi"}), + poolclass=NullPool, + ) + Base.metadata.drop_all(engine) + Base.metadata.create_all(engine) + yield engine + Base.metadata.drop_all(engine) + engine.dispose() + + +def reset_rows(engine): + with engine.begin() as connection: + connection.execute(delete(BulkRow)) + connection.execute( + insert(BulkRow), + [ + {"id": 1, "value": 10}, + {"id": 2, "value": 20}, + {"id": 3, "value": 30}, + ], + ) + + +@contextmanager +def capture_executemany(engine): + calls = [] + + def after_cursor_execute( + connection, cursor, statement, parameters, context, executemany + ): + calls.append( + { + "statement": statement, + "executemany": executemany, + "rowcount": cursor.rowcount, + "executed": cursor._executed, + } + ) + + event.listen(engine, "after_cursor_execute", after_cursor_execute) + try: + yield calls + finally: + event.remove(engine, "after_cursor_execute", after_cursor_execute) + + +def assert_executemany_call(calls, operation, rowcount): + calls = [ + call + for call in calls + if call["statement"].lstrip().upper().startswith(operation) + ] + assert len(calls) == 1 + assert calls[0]["executemany"] is True + assert calls[0]["rowcount"] == rowcount + # The ORM passed one statement template to DB-API executemany(), while + # mysqlclient sent the rendered statements in one multi-statement query. + assert b";" in calls[0]["executed"] + + +def test_connect_args_enable_multi_fallback_and_found_rows(engine): + with engine.connect() as connection: + driver_connection = connection.connection.driver_connection + assert driver_connection.executemany_fallback == "multi" + assert driver_connection.client_flag & CLIENT.FOUND_ROWS + + +def test_bulk_update_mappings_uses_executemany(engine): + reset_rows(engine) + + with capture_executemany(engine) as calls, Session(engine) as session: + session.bulk_update_mappings( + BulkRow, + [ + {"id": 1, "value": 10}, # no-op; FOUND_ROWS still counts it + {"id": 2, "value": 21}, + ], + ) + session.commit() + + assert_executemany_call(calls, "UPDATE ", 2) + + +def test_orm_bulk_update_by_primary_key_uses_executemany(engine): + reset_rows(engine) + + with capture_executemany(engine) as calls, Session(engine) as session: + session.execute( + update(BulkRow), + [ + {"id": 1, "value": 11}, + {"id": 2, "value": 22}, + ], + ) + session.commit() + + assert_executemany_call(calls, "UPDATE ", 2) + + +def test_core_executemany_delete_rowcount(engine): + reset_rows(engine) + + with capture_executemany(engine) as calls, engine.begin() as connection: + result = connection.execute( + delete(BulkRow).where(BulkRow.id == bindparam("target_id")), + [{"target_id": 1}, {"target_id": 99}, {"target_id": 3}], + ) + assert result.rowcount == 2 + + assert_executemany_call(calls, "DELETE ", 2) + with engine.connect() as connection: + assert connection.scalars(select(BulkRow.id)).all() == [2] diff --git a/tests/travis.cnf b/tests/travis.cnf deleted file mode 100644 index 5fd6f847..00000000 --- a/tests/travis.cnf +++ /dev/null @@ -1,10 +0,0 @@ -# To create your own custom version of this file, read -# http://dev.mysql.com/doc/refman/5.1/en/option-files.html -# and set TESTDB in your environment to the name of the file - -[MySQLdb-tests] -host = 127.0.0.1 -port = 3306 -user = root -database = mysqldb_test -default-character-set = utf8mb4