[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -1,17 +1,20 @@
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""SQLite abstraction for coverage.py"""
from __future__ import annotations
import contextlib
import re
import sqlite3
from typing import Any
from typing import cast
from typing import Iterable
from typing import Iterator
from typing import Tuple
from typing import cast, Any, Iterable, Iterator, Tuple
from coverage.debug import auto_repr, clipped_repr, exc_one_line
from coverage.debug import auto_repr
from coverage.debug import clipped_repr
from coverage.debug import exc_one_line
from coverage.exceptions import DataError
from coverage.types import TDebugCtl
@ -28,6 +31,7 @@ class SqliteDb:
etc(a, b)
"""
def __init__(self, filename: str, debug: TDebugCtl) -> None:
self.debug = debug
self.filename = filename
@ -46,40 +50,40 @@ class SqliteDb:
# effectively causing a nested context. However, given the idempotent
# nature of the tracer operations, sharing a connection among threads
# is not a problem.
if self.debug.should("sql"):
self.debug.write(f"Connecting to {self.filename!r}")
if self.debug.should('sql'):
self.debug.write(f'Connecting to {self.filename!r}')
try:
self.con = sqlite3.connect(self.filename, check_same_thread=False)
except sqlite3.Error as exc:
raise DataError(f"Couldn't use data file {self.filename!r}: {exc}") from exc
if self.debug.should("sql"):
self.debug.write(f"Connected to {self.filename!r} as {self.con!r}")
if self.debug.should('sql'):
self.debug.write(f'Connected to {self.filename!r} as {self.con!r}')
self.con.create_function("REGEXP", 2, lambda txt, pat: re.search(txt, pat) is not None)
self.con.create_function('REGEXP', 2, lambda txt, pat: re.search(txt, pat) is not None)
# Turning off journal_mode can speed up writing. It can't always be
# disabled, so we have to be prepared for *-journal files elsewhere.
# In Python 3.12+, we can change the config to allow journal_mode=off.
if hasattr(sqlite3, "SQLITE_DBCONFIG_DEFENSIVE"):
if hasattr(sqlite3, 'SQLITE_DBCONFIG_DEFENSIVE'):
# Turn off defensive mode, so that journal_mode=off can succeed.
self.con.setconfig( # type: ignore[attr-defined, unused-ignore]
sqlite3.SQLITE_DBCONFIG_DEFENSIVE, False,
)
# This pragma makes writing faster. It disables rollbacks, but we never need them.
self.execute_void("pragma journal_mode=off")
self.execute_void('pragma journal_mode=off')
# This pragma makes writing faster. It can fail in unusual situations
# (https://github.com/nedbat/coveragepy/issues/1646), so use fail_ok=True
# to keep things going.
self.execute_void("pragma synchronous=off", fail_ok=True)
self.execute_void('pragma synchronous=off', fail_ok=True)
def close(self) -> None:
"""If needed, close the connection."""
if self.con is not None and self.filename != ":memory:":
if self.debug.should("sql"):
self.debug.write(f"Closing {self.con!r} on {self.filename!r}")
if self.con is not None and self.filename != ':memory:':
if self.debug.should('sql'):
self.debug.write(f'Closing {self.con!r} on {self.filename!r}')
self.con.close()
self.con = None
@ -99,15 +103,15 @@ class SqliteDb:
self.con.__exit__(exc_type, exc_value, traceback)
self.close()
except Exception as exc:
if self.debug.should("sql"):
self.debug.write(f"EXCEPTION from __exit__: {exc_one_line(exc)}")
if self.debug.should('sql'):
self.debug.write(f'EXCEPTION from __exit__: {exc_one_line(exc)}')
raise DataError(f"Couldn't end data file {self.filename!r}: {exc}") from exc
def _execute(self, sql: str, parameters: Iterable[Any]) -> sqlite3.Cursor:
"""Same as :meth:`python:sqlite3.Connection.execute`."""
if self.debug.should("sql"):
tail = f" with {parameters!r}" if parameters else ""
self.debug.write(f"Executing {sql!r}{tail}")
if self.debug.should('sql'):
tail = f' with {parameters!r}' if parameters else ''
self.debug.write(f'Executing {sql!r}{tail}')
try:
assert self.con is not None
try:
@ -119,21 +123,21 @@ class SqliteDb:
return self.con.execute(sql, parameters) # type: ignore[arg-type]
except sqlite3.Error as exc:
msg = str(exc)
if self.filename != ":memory:":
if self.filename != ':memory:':
try:
# `execute` is the first thing we do with the database, so try
# hard to provide useful hints if something goes wrong now.
with open(self.filename, "rb") as bad_file:
cov4_sig = b"!coverage.py: This is a private format"
with open(self.filename, 'rb') as bad_file:
cov4_sig = b'!coverage.py: This is a private format'
if bad_file.read(len(cov4_sig)) == cov4_sig:
msg = (
"Looks like a coverage 4.x data file. " +
"Are you mixing versions of coverage?"
'Looks like a coverage 4.x data file. ' +
'Are you mixing versions of coverage?'
)
except Exception:
pass
if self.debug.should("sql"):
self.debug.write(f"EXCEPTION from execute: {exc_one_line(exc)}")
if self.debug.should('sql'):
self.debug.write(f'EXCEPTION from execute: {exc_one_line(exc)}')
raise DataError(f"Couldn't use data file {self.filename!r}: {msg}") from exc
@contextlib.contextmanager
@ -170,8 +174,8 @@ class SqliteDb:
with self.execute(sql, parameters) as cur:
assert cur.lastrowid is not None
rowid: int = cur.lastrowid
if self.debug.should("sqldata"):
self.debug.write(f"Row id result: {rowid!r}")
if self.debug.should('sqldata'):
self.debug.write(f'Row id result: {rowid!r}')
return rowid
def execute_one(self, sql: str, parameters: Iterable[Any] = ()) -> tuple[Any, ...] | None:
@ -194,12 +198,12 @@ class SqliteDb:
def _executemany(self, sql: str, data: list[Any]) -> sqlite3.Cursor:
"""Same as :meth:`python:sqlite3.Connection.executemany`."""
if self.debug.should("sql"):
final = ":" if self.debug.should("sqldata") else ""
self.debug.write(f"Executing many {sql!r} with {len(data)} rows{final}")
if self.debug.should("sqldata"):
if self.debug.should('sql'):
final = ':' if self.debug.should('sqldata') else ''
self.debug.write(f'Executing many {sql!r} with {len(data)} rows{final}')
if self.debug.should('sqldata'):
for i, row in enumerate(data):
self.debug.write(f"{i:4d}: {row!r}")
self.debug.write(f'{i:4d}: {row!r}')
assert self.con is not None
try:
return self.con.executemany(sql, data)
@ -217,14 +221,16 @@ class SqliteDb:
def executescript(self, script: str) -> None:
"""Same as :meth:`python:sqlite3.Connection.executescript`."""
if self.debug.should("sql"):
self.debug.write("Executing script with {} chars: {}".format(
len(script), clipped_repr(script, 100),
))
if self.debug.should('sql'):
self.debug.write(
'Executing script with {} chars: {}'.format(
len(script), clipped_repr(script, 100),
),
)
assert self.con is not None
self.con.executescript(script).close()
def dump(self) -> str:
"""Return a multi-line string, the SQL dump of the database."""
assert self.con is not None
return "\n".join(self.con.iterdump())
return '\n'.join(self.con.iterdump())