Skip to content

Commit d5fc8a6

Browse files
committed
Remove apsw alias from utils
1 parent b264e48 commit d5fc8a6

File tree

7 files changed

+28
-30
lines changed

7 files changed

+28
-30
lines changed

apswutils/db.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
# This file is from sqlite-utils and copyright and license is the same as that project
22
__all__ = ['Database', 'Queryable', 'Table', 'View']
33

4-
from .utils import ( chunks, hash_record, sqlite3, OperationalError, suggest_column_types, types_for_column_types, column_affinity, find_spatialite,)
4+
from .utils import ( chunks, hash_record, OperationalError, suggest_column_types, types_for_column_types, column_affinity, find_spatialite,)
55
import binascii
66
from collections import namedtuple
77
from collections.abc import Mapping
88
import contextlib, datetime, decimal, inspect, itertools, json, os, pathlib, re, secrets, textwrap
99
from typing import ( cast, Any, Callable, Dict, Generator, Iterable, Union, Optional, List, Tuple,Iterator)
1010
from functools import cache
1111
import uuid
12+
import apsw
1213
import apsw.ext
1314
import apsw.bestpractice
1415

@@ -219,7 +220,7 @@ class Database:
219220
dB = Database(memory=True)
220221
221222
:param filename_or_conn: String path to a file, or a ``pathlib.Path`` object, or a
222-
``sqlite3`` connection
223+
``apsw`` connection
223224
:param memory: set to ``True`` to create an in-memory database
224225
:param memory_name: creates a named in-memory database that can be shared across multiple connections
225226
:param recreate: set to ``True`` to delete and recreate a file database (**dangerous**)
@@ -237,7 +238,7 @@ class Database:
237238

238239
def __init__(
239240
self,
240-
filename_or_conn: Optional[Union[str, pathlib.Path, sqlite3.Connection]] = None,
241+
filename_or_conn: Optional[Union[str, pathlib.Path, apsw.Connection]] = None,
241242
memory: bool = False,
242243
memory_name: Optional[str] = None,
243244
recreate: bool = False,
@@ -253,21 +254,21 @@ def __init__(
253254
uri = "file:{}?mode=memory&cache=shared".format(memory_name)
254255
# The flags being set allow apswutils to maintain the same behavior here
255256
# as sqlite-minutils
256-
self.conn = sqlite3.Connection(
257+
self.conn = apsw.Connection(
257258
uri, flags=apsw.SQLITE_OPEN_URI|apsw.SQLITE_OPEN_READWRITE
258259
)
259260
elif memory or filename_or_conn == ":memory:":
260-
self.conn = sqlite3.Connection(":memory:")
261+
self.conn = apsw.Connection(":memory:")
261262
elif isinstance(filename_or_conn, (str, pathlib.Path)):
262263
if recreate and os.path.exists(filename_or_conn):
263264
try:
264265
os.remove(filename_or_conn)
265266
except OSError:
266267
# Avoid mypy and __repr__ errors, see:
267268
# https://github.com/simonw/sqlite-utils/issues/503
268-
self.conn = sqlite3.Connection(":memory:")
269+
self.conn = apsw.Connection(":memory:")
269270
raise
270-
self.conn = sqlite3.Connection(str(filename_or_conn))
271+
self.conn = apsw.Connection(str(filename_or_conn))
271272
else:
272273
assert not recreate, "recreate cannot be used with connections, only paths"
273274
self.conn = filename_or_conn
@@ -368,7 +369,7 @@ def register(fn):
368369
fn_name, fn, arity, **dict(kwargs, deterministic=True)
369370
)
370371
registered = True
371-
except sqlite3.Error: # Remember, sqlite3 here is actually apsw
372+
except apsw.Error:
372373
# TODO Find the precise error, sqlite-minutils used sqlite3.NotSupportedError
373374
# but as this isn't defined in APSW we fall back to apsw.Error
374375
pass
@@ -422,9 +423,9 @@ def query(
422423

423424
def execute(
424425
self, sql: str, parameters: Optional[Union[Iterable, dict]] = None
425-
) -> sqlite3.Cursor:
426+
) -> apsw.Cursor:
426427
"""
427-
Execute SQL query and return a ``sqlite3.Cursor``.
428+
Execute SQL query and return a ``apsw.Cursor``.
428429
429430
:param sql: SQL query to execute
430431
:param parameters: Parameters to use in that query - an iterable for ``where id = ?``
@@ -435,9 +436,9 @@ def execute(
435436
if parameters: return self.conn.execute(sql, parameters)
436437
else: return self.conn.execute(sql)
437438

438-
def executescript(self, sql: str) -> sqlite3.Cursor:
439+
def executescript(self, sql: str) -> apsw.Cursor:
439440
"""
440-
Execute multiple SQL statements separated by ; and return the ``sqlite3.Cursor``.
441+
Execute multiple SQL statements separated by ; and return the ``apsw.Cursor``.
441442
442443
:param sql: SQL to execute
443444
"""
@@ -1353,7 +1354,7 @@ def schema(self) -> str:
13531354

13541355
class Table(Queryable):
13551356
"""
1356-
A Table class instance represents a sqlite3 table that may or may not exist
1357+
A Table class instance represents a table that may or may not exist
13571358
in the database. The Table class instance may or may not represent some of
13581359
the rows of the database table. After some mutations (INSERT/UPDATE/UPSERT)
13591360
the changed records the Table class instance can be iterated over, returning

apswutils/utils.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,11 @@
1111
import sys
1212
import json
1313
from typing import Dict, cast, BinaryIO, Iterable, Optional, Tuple, Type
14+
import apsw
1415

15-
# TODO: Change use of apsw as a shim for sqlite3 more explicit
16-
# In order to keep this PR minimal, we use sqlite3 as a shim for APSW
17-
import apsw as sqlite3
1816
# TODO: Replace use of OperationalError with more explicit apsw errors
1917
# In order to keep this PR minimal, we use OperationalError as a shim for apsw.Error
20-
OperationalError = sqlite3.Error
18+
OperationalError = apsw.Error
2119

2220
SPATIALITE_PATHS = (
2321
"/usr/lib/x86_64-linux-gnu/mod_spatialite.so",

tests/conftest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from apswutils import Database
2-
from apswutils.utils import sqlite3
2+
import apsw
33
import pytest
44

55
CREATE_TABLES = """
@@ -36,6 +36,6 @@ def existing_db():
3636
@pytest.fixture
3737
def db_path(tmpdir):
3838
path = str(tmpdir / "test.db")
39-
db = sqlite3.connect(path)
39+
db = Database(path)
4040
db.executescript(CREATE_TABLES)
4141
return path

tests/test_create.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
Table,
1010
View,
1111
)
12-
from apswutils.utils import hash_record, sqlite3
12+
from apswutils.utils import hash_record
1313
import collections
1414
import datetime
1515
import decimal
@@ -717,7 +717,7 @@ def test_columns_not_in_first_record_should_not_cause_batch_to_be_too_large(fres
717717
fresh_db["too_many_columns"].insert_all(
718718
records, alter=True, batch_size=batch_size
719719
)
720-
except sqlite3.OperationalError:
720+
except OperationalError:
721721
raise
722722

723723

@@ -1312,7 +1312,7 @@ def test_rename_table(fresh_db):
13121312
assert ["renamed"] == fresh_db.table_names()
13131313
assert [{"foo": "bar"}] == list(fresh_db["renamed"].rows)
13141314
# Should error if table does not exist:
1315-
with pytest.raises(sqlite3.SQLError):
1315+
with pytest.raises(apsw.SQLError):
13161316
fresh_db.rename_table("does_not_exist", "renamed")
13171317

13181318

tests/test_recreate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
import apsw
12
from apswutils import Database
2-
import sqlite3
33
import pathlib
44
import pytest
55

@@ -13,7 +13,7 @@ def test_recreate_ignored_for_in_memory():
1313

1414

1515
def test_recreate_not_allowed_for_connection():
16-
conn = sqlite3.connect(":memory:")
16+
conn = apsw.Connection(":memory:")
1717
with pytest.raises(AssertionError):
1818
Database(conn, recreate=True)
1919

tests/test_register_function.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import pytest
33
import sys
44
from unittest.mock import MagicMock, call
5-
from apswutils.utils import sqlite3
5+
import apsw
66

77

88
def test_register_function(fresh_db):
@@ -60,9 +60,9 @@ def side_effect(*args, **kwargs):
6060
nonlocal first
6161
if first:
6262
first = False
63-
raise sqlite3.Error()
63+
raise apsw.Error()
6464

65-
# But if sqlite3.NotSupportedError is raised, it tries again
65+
# But if apsw.NotSupportedError is raised, it tries again
6666
fresh_db.conn.create_scalar_function.reset_mock()
6767
fresh_db.conn.create_scalar_function.side_effect = side_effect
6868

tests/test_transform.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from apswutils.db import ForeignKey
22
from apswutils.utils import OperationalError
3-
from sqlite3 import IntegrityError
43
import pytest
54
import apsw
65
from collections.abc import Mapping
@@ -391,14 +390,14 @@ def test_transform_verify_foreign_keys(fresh_db):
391390
fresh_db["books"].insert(
392391
{"id": 1, "title": "Book", "author_id": 3}, pk="id", foreign_keys={"author_id"}
393392
)
394-
# Renaming the id column on authors should break everything with an IntegrityError
393+
# Renaming the id column on authors should break everything with an SQLError
395394
# The old error didn't match the Sqlite docs.
396395
# We use a transaction to constrain and rollback the error.
397396
fresh_db.begin()
398397
try:
399398
fresh_db["authors"].transform(rename={"id": "id2"})
400399
fresh_db.commit()
401-
except apsw.ConstraintError:
400+
except apsw.SQLError:
402401
fresh_db.rollback()
403402

404403
# This should have rolled us back

0 commit comments

Comments
 (0)