Skip to content

Commit e8c5f0d

Browse files
committed
Correct the use of fetchone
1 parent 03fa42b commit e8c5f0d

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

coverage/sqldata.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def _read_db(self):
268268
"""Read the metadata from a database so that we are ready to use it."""
269269
with self._dbs[get_thread_id()] as db:
270270
try:
271-
schema_version, = db.execute("select version from coverage_schema").fetchone()
271+
schema_version, = db.execute_one("select version from coverage_schema")
272272
except Exception as exc:
273273
raise CoverageException(
274274
"Data file {!r} doesn't seem to be a coverage data file: {}".format(
@@ -374,7 +374,7 @@ def _context_id(self, context):
374374
assert context is not None
375375
self._start_using()
376376
with self._connect() as con:
377-
row = con.execute("select id from context where context = ?", (context,)).fetchone()
377+
row = con.execute_one("select id from context where context = ?", (context,))
378378
if row is not None:
379379
return row[0]
380380
else:
@@ -789,7 +789,7 @@ def file_tracer(self, filename):
789789
file_id = self._file_id(filename)
790790
if file_id is None:
791791
return None
792-
row = con.execute("select tracer from tracer where file_id = ?", (file_id,)).fetchone()
792+
row = con.execute_one("select tracer from tracer where file_id = ?", (file_id,))
793793
if row is not None:
794794
return row[0] or ""
795795
return "" # File was measured, but no tracer associated.
@@ -1062,6 +1062,23 @@ def execute(self, sql, parameters=()):
10621062
self.debug.write("EXCEPTION from execute: {}".format(msg))
10631063
raise CoverageException("Couldn't use data file {!r}: {}".format(self.filename, msg))
10641064

1065+
def execute_one(self, sql, parameters=()):
1066+
"""Execute a statement and return the one row that results.
1067+
1068+
This is like execute(sql, parameters).fetchone(), except it is
1069+
correct in reading the entire result set. This will raise an
1070+
exception if more than one row results.
1071+
1072+
Returns a row, or None if there were no rows.
1073+
"""
1074+
rows = list(self.execute(sql, parameters))
1075+
if len(rows) == 0:
1076+
return None
1077+
elif len(rows) == 1:
1078+
return rows[0]
1079+
else:
1080+
raise CoverageException("Sql {!r} shouldn't return {} rows".format(sql, len(rows)))
1081+
10651082
def executemany(self, sql, data):
10661083
"""Same as :meth:`python:sqlite3.Connection.executemany`."""
10671084
if self.debug:

0 commit comments

Comments
 (0)