sanka-connector-sqlite 0.1.0a10__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sanka_connector_sqlite-0.1.0a10/.gitignore +12 -0
- sanka_connector_sqlite-0.1.0a10/LICENSE +202 -0
- sanka_connector_sqlite-0.1.0a10/PKG-INFO +30 -0
- sanka_connector_sqlite-0.1.0a10/README.md +17 -0
- sanka_connector_sqlite-0.1.0a10/pyproject.toml +24 -0
- sanka_connector_sqlite-0.1.0a10/src/sanka_connector_sqlite/__init__.py +424 -0
- sanka_connector_sqlite-0.1.0a10/src/sanka_connector_sqlite/py.typed +0 -0
- sanka_connector_sqlite-0.1.0a10/tests/test_sqlite.py +95 -0
- sanka_connector_sqlite-0.1.0a10/tests/test_sqlite_source.py +174 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sanka-connector-sqlite
|
|
3
|
+
Version: 0.1.0a10
|
|
4
|
+
Summary: SQLite connector for the Sanka migration runtime
|
|
5
|
+
Project-URL: Repository, https://github.com/sankaHQ/sanka-connectors
|
|
6
|
+
Project-URL: Issues, https://github.com/sankaHQ/sanka-connectors/issues
|
|
7
|
+
Author: Sanka, Inc.
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Requires-Dist: sanka-connector-sdk==0.1.0a10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# SQLite connector
|
|
15
|
+
|
|
16
|
+
SQLite as either side of a Sanka run.
|
|
17
|
+
|
|
18
|
+
As a **source**, every user table becomes a migratable object: fields and
|
|
19
|
+
types come from `PRAGMA table_info`, the identity is the table's
|
|
20
|
+
single-column primary key (or `rowid`, exposed as an extra field), and reads
|
|
21
|
+
use keyset pagination (`WHERE <pk> > ? ORDER BY <pk>`) for deterministic,
|
|
22
|
+
resumable cursors. Exact record counts are reported; `WITHOUT ROWID` tables
|
|
23
|
+
with composite primary keys are inventoried with a warning and no identity.
|
|
24
|
+
|
|
25
|
+
As a **destination**, records are written into one table per target object
|
|
26
|
+
(created on first write, columns added as new fields appear), with
|
|
27
|
+
identity-based upserts honoring the run's conflict policy and JSON-encoded
|
|
28
|
+
complex values. Inventory reads back table row counts for verification.
|
|
29
|
+
|
|
30
|
+
Apache-2.0; depends only on the `sanka-connector-sdk` interface (stdlib `sqlite3`).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# SQLite connector
|
|
2
|
+
|
|
3
|
+
SQLite as either side of a Sanka run.
|
|
4
|
+
|
|
5
|
+
As a **source**, every user table becomes a migratable object: fields and
|
|
6
|
+
types come from `PRAGMA table_info`, the identity is the table's
|
|
7
|
+
single-column primary key (or `rowid`, exposed as an extra field), and reads
|
|
8
|
+
use keyset pagination (`WHERE <pk> > ? ORDER BY <pk>`) for deterministic,
|
|
9
|
+
resumable cursors. Exact record counts are reported; `WITHOUT ROWID` tables
|
|
10
|
+
with composite primary keys are inventoried with a warning and no identity.
|
|
11
|
+
|
|
12
|
+
As a **destination**, records are written into one table per target object
|
|
13
|
+
(created on first write, columns added as new fields appear), with
|
|
14
|
+
identity-based upserts honoring the run's conflict policy and JSON-encoded
|
|
15
|
+
complex values. Inventory reads back table row counts for verification.
|
|
16
|
+
|
|
17
|
+
Apache-2.0; depends only on the `sanka-connector-sdk` interface (stdlib `sqlite3`).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sanka-connector-sqlite"
|
|
3
|
+
version = "0.1.0a10"
|
|
4
|
+
description = "SQLite connector for the Sanka migration runtime"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "Sanka, Inc." }]
|
|
10
|
+
dependencies = ["sanka-connector-sdk==0.1.0a10"]
|
|
11
|
+
|
|
12
|
+
[project.entry-points."sanka.connectors"]
|
|
13
|
+
sqlite = "sanka_connector_sqlite:CONNECTOR"
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/sankaHQ/sanka-connectors"
|
|
17
|
+
Issues = "https://github.com/sankaHQ/sanka-connectors/issues"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling>=1.27"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/sanka_connector_sqlite"]
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""SQLite source and destination connector.
|
|
3
|
+
|
|
4
|
+
As a source, every user table is a migratable object: fields come from
|
|
5
|
+
``PRAGMA table_info``, the identity is the table's single-column primary key
|
|
6
|
+
(else ``rowid``, exposed as an extra field), and reads use keyset pagination
|
|
7
|
+
(``WHERE <pk> > ? ORDER BY <pk>``) so cursors are deterministic and resumable.
|
|
8
|
+
|
|
9
|
+
As a destination, tables are created lazily from the records written to them
|
|
10
|
+
(TEXT-affinity columns; complex values JSON-encoded), and widened with
|
|
11
|
+
``ALTER TABLE`` when new fields appear. Writes honor the identity fields and
|
|
12
|
+
conflict policy from :class:`sanka_connector.WriteOptions`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import sqlite3
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from sanka_connector import (
|
|
24
|
+
ConfigurationError,
|
|
25
|
+
ConnectorRegistration,
|
|
26
|
+
Credentials,
|
|
27
|
+
DataError,
|
|
28
|
+
FieldSchema,
|
|
29
|
+
Inventory,
|
|
30
|
+
ObjectSchema,
|
|
31
|
+
RecordPage,
|
|
32
|
+
RelationshipWrite,
|
|
33
|
+
RelationshipWriteResult,
|
|
34
|
+
SourceFilter,
|
|
35
|
+
SourceObject,
|
|
36
|
+
UnsupportedFeatureError,
|
|
37
|
+
WriteOptions,
|
|
38
|
+
WriteResult,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
_IDENTIFIER = re.compile(r"[^a-z0-9_]+")
|
|
42
|
+
_ROWID = "rowid"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _identifier(value: str, *, kind: str) -> str:
|
|
46
|
+
normalized = _IDENTIFIER.sub("_", value.strip().lower()).strip("_")
|
|
47
|
+
if not normalized:
|
|
48
|
+
raise DataError(f"cannot derive a SQLite {kind} name from {value!r}")
|
|
49
|
+
if normalized[0].isdigit():
|
|
50
|
+
normalized = f"t_{normalized}"
|
|
51
|
+
return normalized
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _quote(name: str) -> str:
|
|
55
|
+
escaped = name.replace('"', '""')
|
|
56
|
+
return f'"{escaped}"'
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _database_path(credentials: Credentials, *, role: str) -> str:
|
|
60
|
+
raw = credentials.settings.get("connection") or credentials.settings.get("path")
|
|
61
|
+
if not raw:
|
|
62
|
+
raise ConfigurationError(f"sqlite {role} needs a database path (connection)")
|
|
63
|
+
path_text = str(raw)
|
|
64
|
+
for prefix in ("sqlite:///", "sqlite://"):
|
|
65
|
+
if path_text.startswith(prefix):
|
|
66
|
+
path_text = path_text[len(prefix) :]
|
|
67
|
+
break
|
|
68
|
+
if not path_text:
|
|
69
|
+
raise ConfigurationError(f"sqlite {role} path is empty")
|
|
70
|
+
return str(Path(path_text).expanduser())
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _column_type(declared: str) -> str:
|
|
74
|
+
upper = declared.upper()
|
|
75
|
+
if "BOOL" in upper:
|
|
76
|
+
return "boolean"
|
|
77
|
+
if "INT" in upper or any(marker in upper for marker in ("REAL", "FLOA", "DOUB")):
|
|
78
|
+
return "number"
|
|
79
|
+
return "string"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _SqliteConnectionCache:
|
|
83
|
+
"""Per-instance connection cache shared by the source and destination roles."""
|
|
84
|
+
|
|
85
|
+
def __init__(self) -> None:
|
|
86
|
+
self._connections: dict[str, sqlite3.Connection] = {}
|
|
87
|
+
|
|
88
|
+
def _cached_connection(self, key: str) -> sqlite3.Connection:
|
|
89
|
+
connection = self._connections.get(key)
|
|
90
|
+
if connection is None:
|
|
91
|
+
connection = sqlite3.connect(key)
|
|
92
|
+
self._connections[key] = connection
|
|
93
|
+
return connection
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SqliteSource(_SqliteConnectionCache):
|
|
97
|
+
provider = "sqlite"
|
|
98
|
+
binding_kind = "database"
|
|
99
|
+
|
|
100
|
+
async def discover_objects(self, credentials: Credentials) -> list[SourceObject]:
|
|
101
|
+
connection = self._connect(credentials)
|
|
102
|
+
return [
|
|
103
|
+
SourceObject(key=table, label=table, canonical_type=table, default_selected=True)
|
|
104
|
+
for table in self._tables(connection)
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
async def inventory(
|
|
108
|
+
self,
|
|
109
|
+
credentials: Credentials,
|
|
110
|
+
*,
|
|
111
|
+
object_types: list[str] | None = None,
|
|
112
|
+
) -> Inventory:
|
|
113
|
+
connection = self._connect(credentials)
|
|
114
|
+
tables = self._tables(connection)
|
|
115
|
+
if object_types is not None:
|
|
116
|
+
requested = set(object_types)
|
|
117
|
+
tables = [table for table in tables if table in requested]
|
|
118
|
+
|
|
119
|
+
objects: list[ObjectSchema] = []
|
|
120
|
+
warnings: list[str] = []
|
|
121
|
+
for table in tables:
|
|
122
|
+
columns = self._columns(connection, table)
|
|
123
|
+
fields = [
|
|
124
|
+
FieldSchema(
|
|
125
|
+
key=str(column[1]),
|
|
126
|
+
label=str(column[1]),
|
|
127
|
+
data_type=_column_type(str(column[2])),
|
|
128
|
+
)
|
|
129
|
+
for column in columns
|
|
130
|
+
]
|
|
131
|
+
identity = self._identity_column(connection, table, columns)
|
|
132
|
+
identity_fields: list[str] = []
|
|
133
|
+
if identity == _ROWID:
|
|
134
|
+
fields.append(FieldSchema(key=_ROWID, label=_ROWID, data_type="number"))
|
|
135
|
+
identity_fields = [_ROWID]
|
|
136
|
+
elif identity is not None:
|
|
137
|
+
identity_fields = [identity]
|
|
138
|
+
else:
|
|
139
|
+
warnings.append(
|
|
140
|
+
f"table {table!r} has neither a single-column primary key nor a rowid;"
|
|
141
|
+
" no identity field is available"
|
|
142
|
+
)
|
|
143
|
+
count = connection.execute(f"SELECT COUNT(*) FROM {_quote(table)}").fetchone()[0]
|
|
144
|
+
objects.append(
|
|
145
|
+
ObjectSchema(
|
|
146
|
+
key=table,
|
|
147
|
+
label=table,
|
|
148
|
+
canonical_type=table,
|
|
149
|
+
record_count=int(count),
|
|
150
|
+
fields=fields,
|
|
151
|
+
identity_fields=identity_fields,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
return Inventory(
|
|
155
|
+
provider=self.provider,
|
|
156
|
+
connection_id=credentials.connection_id,
|
|
157
|
+
objects=objects,
|
|
158
|
+
warnings=warnings,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
async def read_records(
|
|
162
|
+
self,
|
|
163
|
+
credentials: Credentials,
|
|
164
|
+
*,
|
|
165
|
+
object_type: str,
|
|
166
|
+
field_keys: list[str],
|
|
167
|
+
limit: int,
|
|
168
|
+
cursor: str | None = None,
|
|
169
|
+
source_filter: SourceFilter | None = None,
|
|
170
|
+
) -> RecordPage:
|
|
171
|
+
connection = self._connect(credentials)
|
|
172
|
+
self._require_table(connection, object_type)
|
|
173
|
+
columns = self._columns(connection, object_type)
|
|
174
|
+
declared = {str(column[1]) for column in columns}
|
|
175
|
+
key_column = self._identity_column(connection, object_type, columns)
|
|
176
|
+
if key_column is None:
|
|
177
|
+
raise UnsupportedFeatureError(
|
|
178
|
+
f"table {object_type!r} has neither a single-column primary key nor a rowid;"
|
|
179
|
+
" keyset pagination is unavailable",
|
|
180
|
+
remediation="add a single-column primary key to the table",
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
select_columns = [key for key in field_keys if key in declared or key == key_column]
|
|
184
|
+
if key_column not in select_columns:
|
|
185
|
+
select_columns.append(key_column)
|
|
186
|
+
rendered = ", ".join(
|
|
187
|
+
f"{_ROWID} AS {_ROWID}" if name == _ROWID and name not in declared else _quote(name)
|
|
188
|
+
for name in select_columns
|
|
189
|
+
)
|
|
190
|
+
key_reference = (
|
|
191
|
+
_ROWID if key_column == _ROWID and key_column not in declared else _quote(key_column)
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
page_size = max(1, limit)
|
|
195
|
+
sql = f"SELECT {rendered} FROM {_quote(object_type)}"
|
|
196
|
+
parameters: list[Any] = []
|
|
197
|
+
if cursor is not None:
|
|
198
|
+
sql += f" WHERE {key_reference} > ?"
|
|
199
|
+
parameters.append(cursor)
|
|
200
|
+
sql += f" ORDER BY {key_reference} LIMIT ?"
|
|
201
|
+
parameters.append(page_size + 1)
|
|
202
|
+
|
|
203
|
+
rows = connection.execute(sql, parameters).fetchall()
|
|
204
|
+
has_more = len(rows) > page_size
|
|
205
|
+
records: list[dict[str, Any]] = []
|
|
206
|
+
last_key: Any = None
|
|
207
|
+
for row in rows[:page_size]:
|
|
208
|
+
values = dict(zip(select_columns, row, strict=True))
|
|
209
|
+
last_key = values[key_column]
|
|
210
|
+
if last_key is None:
|
|
211
|
+
raise DataError(
|
|
212
|
+
f"table {object_type!r} has a NULL value in identity column "
|
|
213
|
+
f"{key_column!r}; keyset pagination requires non-NULL keys"
|
|
214
|
+
)
|
|
215
|
+
records.append({key: values.get(key) for key in field_keys})
|
|
216
|
+
return RecordPage(
|
|
217
|
+
object_key=object_type,
|
|
218
|
+
records=records,
|
|
219
|
+
next_cursor=str(last_key) if has_more else None,
|
|
220
|
+
has_more=has_more,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
async def count_records(
|
|
224
|
+
self,
|
|
225
|
+
credentials: Credentials,
|
|
226
|
+
*,
|
|
227
|
+
object_type: str,
|
|
228
|
+
source_filter: SourceFilter | None = None,
|
|
229
|
+
) -> int:
|
|
230
|
+
connection = self._connect(credentials)
|
|
231
|
+
self._require_table(connection, object_type)
|
|
232
|
+
row = connection.execute(f"SELECT COUNT(*) FROM {_quote(object_type)}").fetchone()
|
|
233
|
+
return int(row[0])
|
|
234
|
+
|
|
235
|
+
# -- internals ----------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
def _connect(self, credentials: Credentials) -> sqlite3.Connection:
|
|
238
|
+
key = _database_path(credentials, role="source")
|
|
239
|
+
if key not in self._connections and not Path(key).is_file():
|
|
240
|
+
raise ConfigurationError(f"sqlite source database not found: {key}")
|
|
241
|
+
return self._cached_connection(key)
|
|
242
|
+
|
|
243
|
+
def _tables(self, connection: sqlite3.Connection) -> list[str]:
|
|
244
|
+
rows = connection.execute(
|
|
245
|
+
"SELECT name FROM sqlite_master"
|
|
246
|
+
" WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
247
|
+
).fetchall()
|
|
248
|
+
return [str(row[0]) for row in rows]
|
|
249
|
+
|
|
250
|
+
def _require_table(self, connection: sqlite3.Connection, object_type: str) -> None:
|
|
251
|
+
if object_type not in self._tables(connection):
|
|
252
|
+
raise DataError(f"sqlite source has no table {object_type!r}")
|
|
253
|
+
|
|
254
|
+
def _columns(self, connection: sqlite3.Connection, table: str) -> list[Any]:
|
|
255
|
+
return connection.execute(f"PRAGMA table_info({_quote(table)})").fetchall()
|
|
256
|
+
|
|
257
|
+
def _identity_column(
|
|
258
|
+
self, connection: sqlite3.Connection, table: str, columns: list[Any]
|
|
259
|
+
) -> str | None:
|
|
260
|
+
primary_key = [str(column[1]) for column in columns if int(column[5]) > 0]
|
|
261
|
+
if len(primary_key) == 1:
|
|
262
|
+
return primary_key[0]
|
|
263
|
+
if self._has_rowid(connection, table):
|
|
264
|
+
return _ROWID
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
def _has_rowid(self, connection: sqlite3.Connection, table: str) -> bool:
|
|
268
|
+
try:
|
|
269
|
+
connection.execute(f"SELECT {_ROWID} FROM {_quote(table)} LIMIT 1")
|
|
270
|
+
except sqlite3.OperationalError:
|
|
271
|
+
return False
|
|
272
|
+
return True
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class SqliteDestination(_SqliteConnectionCache):
|
|
276
|
+
provider = "sqlite"
|
|
277
|
+
binding_kind = "database"
|
|
278
|
+
|
|
279
|
+
def automatic_target_object(self, canonical_type: str) -> str | None:
|
|
280
|
+
return _identifier(canonical_type, kind="table")
|
|
281
|
+
|
|
282
|
+
async def inventory(
|
|
283
|
+
self,
|
|
284
|
+
credentials: Credentials,
|
|
285
|
+
*,
|
|
286
|
+
canonical_types: set[str],
|
|
287
|
+
) -> Inventory:
|
|
288
|
+
# Inventory is a read: a database that does not exist yet is simply
|
|
289
|
+
# empty — never create the file from an inspection/planning path.
|
|
290
|
+
if not Path(_database_path(credentials, role="destination")).exists():
|
|
291
|
+
return Inventory(provider=self.provider, connection_id=credentials.connection_id)
|
|
292
|
+
connection = self._connect(credentials)
|
|
293
|
+
objects: list[ObjectSchema] = []
|
|
294
|
+
for canonical_type in sorted(canonical_types):
|
|
295
|
+
table = _identifier(canonical_type, kind="table")
|
|
296
|
+
if not self._table_exists(connection, table):
|
|
297
|
+
continue
|
|
298
|
+
count = connection.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()[0]
|
|
299
|
+
columns = connection.execute(f'PRAGMA table_info("{table}")').fetchall()
|
|
300
|
+
objects.append(
|
|
301
|
+
ObjectSchema(
|
|
302
|
+
key=table,
|
|
303
|
+
label=table,
|
|
304
|
+
canonical_type=canonical_type,
|
|
305
|
+
record_count=int(count),
|
|
306
|
+
fields=[
|
|
307
|
+
FieldSchema(key=str(column[1]), label=str(column[1])) for column in columns
|
|
308
|
+
],
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
return Inventory(
|
|
312
|
+
provider=self.provider, connection_id=credentials.connection_id, objects=objects
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
async def write_record(
|
|
316
|
+
self,
|
|
317
|
+
credentials: Credentials,
|
|
318
|
+
*,
|
|
319
|
+
object_type: str,
|
|
320
|
+
properties: dict[str, Any],
|
|
321
|
+
options: WriteOptions,
|
|
322
|
+
) -> WriteResult:
|
|
323
|
+
if not properties:
|
|
324
|
+
return WriteResult(status="skipped", message="empty record")
|
|
325
|
+
connection = self._connect(credentials)
|
|
326
|
+
table = _identifier(object_type, kind="table")
|
|
327
|
+
columns = {
|
|
328
|
+
_identifier(key, kind="column"): _to_sql(value) for key, value in properties.items()
|
|
329
|
+
}
|
|
330
|
+
self._ensure_table(connection, table, columns.keys())
|
|
331
|
+
|
|
332
|
+
identity_columns = [
|
|
333
|
+
_identifier(field, kind="column") for field in (options.identity_fields or [])
|
|
334
|
+
]
|
|
335
|
+
existing_rowid = self._find_existing(connection, table, identity_columns, columns)
|
|
336
|
+
|
|
337
|
+
if existing_rowid is not None and options.conflict_policy == "skip_existing":
|
|
338
|
+
return WriteResult(status="skipped", destination_record_id=str(existing_rowid))
|
|
339
|
+
if existing_rowid is not None and options.conflict_policy == "update_existing":
|
|
340
|
+
assignments = ", ".join(f'"{name}" = ?' for name in columns)
|
|
341
|
+
connection.execute(
|
|
342
|
+
f'UPDATE "{table}" SET {assignments} WHERE rowid = ?',
|
|
343
|
+
(*columns.values(), existing_rowid),
|
|
344
|
+
)
|
|
345
|
+
connection.commit()
|
|
346
|
+
return WriteResult(status="updated", destination_record_id=str(existing_rowid))
|
|
347
|
+
|
|
348
|
+
names = ", ".join(f'"{name}"' for name in columns)
|
|
349
|
+
placeholders = ", ".join("?" for _ in columns)
|
|
350
|
+
inserted = connection.execute(
|
|
351
|
+
f'INSERT INTO "{table}" ({names}) VALUES ({placeholders})',
|
|
352
|
+
tuple(columns.values()),
|
|
353
|
+
)
|
|
354
|
+
connection.commit()
|
|
355
|
+
return WriteResult(status="created", destination_record_id=str(inserted.lastrowid))
|
|
356
|
+
|
|
357
|
+
async def write_relationship(
|
|
358
|
+
self,
|
|
359
|
+
credentials: Credentials,
|
|
360
|
+
*,
|
|
361
|
+
relationship: RelationshipWrite,
|
|
362
|
+
) -> RelationshipWriteResult:
|
|
363
|
+
return RelationshipWriteResult(
|
|
364
|
+
status="skipped", message="sqlite destination does not model relationships yet"
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
# -- internals ----------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
def _connect(self, credentials: Credentials) -> sqlite3.Connection:
|
|
370
|
+
key = _database_path(credentials, role="destination")
|
|
371
|
+
if key not in self._connections:
|
|
372
|
+
Path(key).parent.mkdir(parents=True, exist_ok=True)
|
|
373
|
+
return self._cached_connection(key)
|
|
374
|
+
|
|
375
|
+
def _table_exists(self, connection: sqlite3.Connection, table: str) -> bool:
|
|
376
|
+
row = connection.execute(
|
|
377
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", (table,)
|
|
378
|
+
).fetchone()
|
|
379
|
+
return row is not None
|
|
380
|
+
|
|
381
|
+
def _ensure_table(self, connection: sqlite3.Connection, table: str, columns: Any) -> None:
|
|
382
|
+
column_list = list(columns)
|
|
383
|
+
if not self._table_exists(connection, table):
|
|
384
|
+
rendered = ", ".join(f'"{name}"' for name in column_list)
|
|
385
|
+
connection.execute(f'CREATE TABLE "{table}" ({rendered})')
|
|
386
|
+
connection.commit()
|
|
387
|
+
return
|
|
388
|
+
existing = {
|
|
389
|
+
str(row[1]) for row in connection.execute(f'PRAGMA table_info("{table}")').fetchall()
|
|
390
|
+
}
|
|
391
|
+
for name in column_list:
|
|
392
|
+
if name not in existing:
|
|
393
|
+
connection.execute(f'ALTER TABLE "{table}" ADD COLUMN "{name}"')
|
|
394
|
+
connection.commit()
|
|
395
|
+
|
|
396
|
+
def _find_existing(
|
|
397
|
+
self,
|
|
398
|
+
connection: sqlite3.Connection,
|
|
399
|
+
table: str,
|
|
400
|
+
identity_columns: list[str],
|
|
401
|
+
columns: dict[str, Any],
|
|
402
|
+
) -> int | None:
|
|
403
|
+
usable = [name for name in identity_columns if name in columns]
|
|
404
|
+
if not usable:
|
|
405
|
+
return None
|
|
406
|
+
predicate = " AND ".join(f'"{name}" = ?' for name in usable)
|
|
407
|
+
row = connection.execute(
|
|
408
|
+
f'SELECT rowid FROM "{table}" WHERE {predicate} LIMIT 1',
|
|
409
|
+
tuple(columns[name] for name in usable),
|
|
410
|
+
).fetchone()
|
|
411
|
+
return None if row is None else int(row[0])
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _to_sql(value: Any) -> Any:
|
|
415
|
+
if isinstance(value, bool):
|
|
416
|
+
return int(value)
|
|
417
|
+
if value is None or isinstance(value, int | float | str):
|
|
418
|
+
return value
|
|
419
|
+
return json.dumps(value, ensure_ascii=False)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
CONNECTOR = ConnectorRegistration(
|
|
423
|
+
name="sqlite", source=SqliteSource(), destination=SqliteDestination()
|
|
424
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sqlite3
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from sanka_connector import Credentials, WriteOptions
|
|
8
|
+
from sanka_connector_sqlite import CONNECTOR, SqliteDestination
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _credentials(path: Path) -> Credentials:
|
|
12
|
+
return Credentials(provider="sqlite", settings={"connection": str(path)})
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
OPTIONS = WriteOptions(conflict_policy="update_existing", identity_fields=["path"])
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def test_create_update_skip_and_schema_evolution(tmp_path: Path) -> None:
|
|
19
|
+
db = tmp_path / "out.db"
|
|
20
|
+
destination = SqliteDestination()
|
|
21
|
+
credentials = _credentials(db)
|
|
22
|
+
|
|
23
|
+
created = await destination.write_record(
|
|
24
|
+
credentials,
|
|
25
|
+
object_type="documents",
|
|
26
|
+
properties={"path": "a.md", "title": "A", "published": True, "tags": ["x", "y"]},
|
|
27
|
+
options=OPTIONS,
|
|
28
|
+
)
|
|
29
|
+
assert created.status == "created"
|
|
30
|
+
|
|
31
|
+
updated = await destination.write_record(
|
|
32
|
+
credentials,
|
|
33
|
+
object_type="documents",
|
|
34
|
+
properties={"path": "a.md", "title": "A2", "views": 10},
|
|
35
|
+
options=OPTIONS,
|
|
36
|
+
)
|
|
37
|
+
assert updated.status == "updated"
|
|
38
|
+
assert updated.destination_record_id == created.destination_record_id
|
|
39
|
+
|
|
40
|
+
skipped = await destination.write_record(
|
|
41
|
+
credentials,
|
|
42
|
+
object_type="documents",
|
|
43
|
+
properties={"path": "a.md", "title": "ignored"},
|
|
44
|
+
options=WriteOptions(conflict_policy="skip_existing", identity_fields=["path"]),
|
|
45
|
+
)
|
|
46
|
+
assert skipped.status == "skipped"
|
|
47
|
+
|
|
48
|
+
rows = (
|
|
49
|
+
sqlite3.connect(db)
|
|
50
|
+
.execute("SELECT path, title, published, tags, views FROM documents")
|
|
51
|
+
.fetchall()
|
|
52
|
+
)
|
|
53
|
+
assert rows == [("a.md", "A2", 1, '["x", "y"]', 10)]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def test_inventory_readback_and_target_suggestion(tmp_path: Path) -> None:
|
|
57
|
+
db = tmp_path / "out.db"
|
|
58
|
+
destination = SqliteDestination()
|
|
59
|
+
credentials = _credentials(db)
|
|
60
|
+
for index in range(3):
|
|
61
|
+
await destination.write_record(
|
|
62
|
+
credentials,
|
|
63
|
+
object_type="documents",
|
|
64
|
+
properties={"path": f"{index}.md"},
|
|
65
|
+
options=OPTIONS,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
inventory = await destination.inventory(credentials, canonical_types={"documents", "absent"})
|
|
69
|
+
assert len(inventory.objects) == 1
|
|
70
|
+
assert inventory.objects[0].record_count == 3
|
|
71
|
+
assert destination.automatic_target_object("My Docs!") == "my_docs"
|
|
72
|
+
assert CONNECTOR.name == "sqlite"
|
|
73
|
+
assert CONNECTOR.destination is not None and CONNECTOR.source is not None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def test_inventory_on_missing_database_is_empty_and_creates_nothing(
|
|
77
|
+
tmp_path: Path,
|
|
78
|
+
) -> None:
|
|
79
|
+
db = tmp_path / "never-created.db"
|
|
80
|
+
inventory = await SqliteDestination().inventory(_credentials(db), canonical_types={"documents"})
|
|
81
|
+
assert inventory.objects == []
|
|
82
|
+
assert not db.exists() # planning/inspection must leave no artifacts
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def test_sqlite_url_prefix_is_accepted(tmp_path: Path) -> None:
|
|
86
|
+
db = tmp_path / "url.db"
|
|
87
|
+
destination = SqliteDestination()
|
|
88
|
+
result = await destination.write_record(
|
|
89
|
+
Credentials(provider="sqlite", settings={"connection": f"sqlite:///{db}"}),
|
|
90
|
+
object_type="items",
|
|
91
|
+
properties={"path": "x", "n": 1},
|
|
92
|
+
options=OPTIONS,
|
|
93
|
+
)
|
|
94
|
+
assert result.status == "created"
|
|
95
|
+
assert sqlite3.connect(db).execute("SELECT COUNT(*) FROM items").fetchone()[0] == 1
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sqlite3
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from sanka_connector import (
|
|
10
|
+
ConfigurationError,
|
|
11
|
+
Credentials,
|
|
12
|
+
SupportsRecordCounts,
|
|
13
|
+
UnsupportedFeatureError,
|
|
14
|
+
)
|
|
15
|
+
from sanka_connector_sqlite import CONNECTOR, SqliteSource
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _credentials(path: Path) -> Credentials:
|
|
19
|
+
return Credentials(provider="sqlite", settings={"connection": str(path)})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _seed(path: Path) -> None:
|
|
23
|
+
connection = sqlite3.connect(path)
|
|
24
|
+
connection.executescript(
|
|
25
|
+
"""
|
|
26
|
+
CREATE TABLE items (
|
|
27
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
28
|
+
name TEXT NOT NULL,
|
|
29
|
+
price REAL,
|
|
30
|
+
in_stock BOOLEAN,
|
|
31
|
+
notes
|
|
32
|
+
);
|
|
33
|
+
CREATE TABLE logs (message TEXT);
|
|
34
|
+
CREATE TABLE pairs (a TEXT, b TEXT, PRIMARY KEY (a, b)) WITHOUT ROWID;
|
|
35
|
+
"""
|
|
36
|
+
)
|
|
37
|
+
connection.executemany(
|
|
38
|
+
"INSERT INTO items (id, name, price, in_stock, notes) VALUES (?, ?, ?, ?, ?)",
|
|
39
|
+
[(index, f"item-{index}", 1.5 * index, index % 2, None) for index in range(1, 6)],
|
|
40
|
+
)
|
|
41
|
+
connection.executemany("INSERT INTO logs (message) VALUES (?)", [("m1",), ("m2",), ("m3",)])
|
|
42
|
+
connection.execute("INSERT INTO pairs (a, b) VALUES ('x', 'y')")
|
|
43
|
+
connection.commit()
|
|
44
|
+
connection.close()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def test_discover_objects_lists_user_tables_only(tmp_path: Path) -> None:
|
|
48
|
+
db = tmp_path / "in.db"
|
|
49
|
+
_seed(db)
|
|
50
|
+
objects = await SqliteSource().discover_objects(_credentials(db))
|
|
51
|
+
# AUTOINCREMENT creates sqlite_sequence, which must be skipped as an internal.
|
|
52
|
+
assert [o.key for o in objects] == ["items", "logs", "pairs"]
|
|
53
|
+
assert all(o.default_selected and o.canonical_type == o.key for o in objects)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def test_inventory_primary_key_table(tmp_path: Path) -> None:
|
|
57
|
+
db = tmp_path / "in.db"
|
|
58
|
+
_seed(db)
|
|
59
|
+
inventory = await SqliteSource().inventory(_credentials(db), object_types=["items"])
|
|
60
|
+
assert len(inventory.objects) == 1
|
|
61
|
+
items = inventory.objects[0]
|
|
62
|
+
assert items.record_count == 5
|
|
63
|
+
assert items.identity_fields == ["id"]
|
|
64
|
+
assert {f.key: f.data_type for f in items.fields} == {
|
|
65
|
+
"id": "number",
|
|
66
|
+
"name": "string",
|
|
67
|
+
"price": "number",
|
|
68
|
+
"in_stock": "boolean",
|
|
69
|
+
"notes": "string",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def test_inventory_rowid_and_without_rowid_paths(tmp_path: Path) -> None:
|
|
74
|
+
db = tmp_path / "in.db"
|
|
75
|
+
_seed(db)
|
|
76
|
+
inventory = await SqliteSource().inventory(_credentials(db))
|
|
77
|
+
by_key = {o.key: o for o in inventory.objects}
|
|
78
|
+
|
|
79
|
+
logs = by_key["logs"]
|
|
80
|
+
assert logs.identity_fields == ["rowid"]
|
|
81
|
+
assert [f.key for f in logs.fields] == ["message", "rowid"]
|
|
82
|
+
assert logs.fields[-1].data_type == "number"
|
|
83
|
+
|
|
84
|
+
pairs = by_key["pairs"]
|
|
85
|
+
assert pairs.identity_fields == []
|
|
86
|
+
assert any("pairs" in w for w in inventory.warnings)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
async def test_read_records_keyset_paginates_across_pages(tmp_path: Path) -> None:
|
|
90
|
+
db = tmp_path / "in.db"
|
|
91
|
+
_seed(db)
|
|
92
|
+
source = SqliteSource()
|
|
93
|
+
credentials = _credentials(db)
|
|
94
|
+
|
|
95
|
+
first = await source.read_records(
|
|
96
|
+
credentials, object_type="items", field_keys=["id", "name"], limit=2
|
|
97
|
+
)
|
|
98
|
+
assert [r["id"] for r in first.records] == [1, 2]
|
|
99
|
+
assert first.has_more and first.next_cursor == "2"
|
|
100
|
+
|
|
101
|
+
second = await source.read_records(
|
|
102
|
+
credentials, object_type="items", field_keys=["id", "name"], limit=2, cursor="2"
|
|
103
|
+
)
|
|
104
|
+
assert [r["id"] for r in second.records] == [3, 4]
|
|
105
|
+
assert second.has_more and second.next_cursor == "4"
|
|
106
|
+
|
|
107
|
+
third = await source.read_records(
|
|
108
|
+
credentials, object_type="items", field_keys=["id", "name"], limit=2, cursor="4"
|
|
109
|
+
)
|
|
110
|
+
assert [r["id"] for r in third.records] == [5]
|
|
111
|
+
assert third.records[0]["name"] == "item-5"
|
|
112
|
+
assert not third.has_more and third.next_cursor is None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
async def test_read_records_rowid_path_and_missing_fields(tmp_path: Path) -> None:
|
|
116
|
+
db = tmp_path / "in.db"
|
|
117
|
+
_seed(db)
|
|
118
|
+
source = SqliteSource()
|
|
119
|
+
credentials = _credentials(db)
|
|
120
|
+
|
|
121
|
+
first = await source.read_records(
|
|
122
|
+
credentials, object_type="logs", field_keys=["message", "rowid", "absent"], limit=2
|
|
123
|
+
)
|
|
124
|
+
assert first.records == [
|
|
125
|
+
{"message": "m1", "rowid": 1, "absent": None},
|
|
126
|
+
{"message": "m2", "rowid": 2, "absent": None},
|
|
127
|
+
]
|
|
128
|
+
assert first.has_more and first.next_cursor == "2"
|
|
129
|
+
|
|
130
|
+
rest = await source.read_records(
|
|
131
|
+
credentials,
|
|
132
|
+
object_type="logs",
|
|
133
|
+
field_keys=["message", "rowid", "absent"],
|
|
134
|
+
limit=2,
|
|
135
|
+
cursor=first.next_cursor,
|
|
136
|
+
)
|
|
137
|
+
assert rest.records == [{"message": "m3", "rowid": 3, "absent": None}]
|
|
138
|
+
assert not rest.has_more and rest.next_cursor is None
|
|
139
|
+
|
|
140
|
+
# The cursor advances even when the identity is not among the requested fields.
|
|
141
|
+
unrequested = await source.read_records(
|
|
142
|
+
credentials, object_type="logs", field_keys=["message"], limit=1
|
|
143
|
+
)
|
|
144
|
+
assert unrequested.records == [{"message": "m1"}]
|
|
145
|
+
assert unrequested.has_more and unrequested.next_cursor == "1"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def test_without_rowid_composite_key_reads_are_unsupported(tmp_path: Path) -> None:
|
|
149
|
+
db = tmp_path / "in.db"
|
|
150
|
+
_seed(db)
|
|
151
|
+
with pytest.raises(UnsupportedFeatureError):
|
|
152
|
+
await SqliteSource().read_records(
|
|
153
|
+
_credentials(db), object_type="pairs", field_keys=["a", "b"], limit=10
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
async def test_count_capability_and_registration_has_both_roles(tmp_path: Path) -> None:
|
|
158
|
+
db = tmp_path / "in.db"
|
|
159
|
+
_seed(db)
|
|
160
|
+
source = SqliteSource()
|
|
161
|
+
assert await source.count_records(_credentials(db), object_type="items") == 5
|
|
162
|
+
assert await source.count_records(_credentials(db), object_type="logs") == 3
|
|
163
|
+
assert isinstance(source, SupportsRecordCounts)
|
|
164
|
+
assert CONNECTOR.name == "sqlite"
|
|
165
|
+
assert CONNECTOR.source is not None
|
|
166
|
+
assert CONNECTOR.destination is not None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
async def test_missing_database_is_configuration_error(tmp_path: Path) -> None:
|
|
170
|
+
missing = tmp_path / "absent.db"
|
|
171
|
+
with pytest.raises(ConfigurationError):
|
|
172
|
+
await SqliteSource().discover_objects(_credentials(missing))
|
|
173
|
+
# Reading must never create an empty database file as a side effect.
|
|
174
|
+
assert not missing.exists()
|