datasette-scan 0.1__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.
- datasette_scan-0.1/LICENSE +201 -0
- datasette_scan-0.1/PKG-INFO +120 -0
- datasette_scan-0.1/README.md +102 -0
- datasette_scan-0.1/datasette_scan/__init__.py +187 -0
- datasette_scan-0.1/datasette_scan.egg-info/PKG-INFO +120 -0
- datasette_scan-0.1/datasette_scan.egg-info/SOURCES.txt +11 -0
- datasette_scan-0.1/datasette_scan.egg-info/dependency_links.txt +1 -0
- datasette_scan-0.1/datasette_scan.egg-info/entry_points.txt +2 -0
- datasette_scan-0.1/datasette_scan.egg-info/requires.txt +2 -0
- datasette_scan-0.1/datasette_scan.egg-info/top_level.txt +1 -0
- datasette_scan-0.1/pyproject.toml +40 -0
- datasette_scan-0.1/setup.cfg +4 -0
- datasette_scan-0.1/tests/test_scan.py +312 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datasette-scan
|
|
3
|
+
Version: 0.1
|
|
4
|
+
Summary: Datasette plugin for scanning for SQLite files
|
|
5
|
+
Author: Simon Willison
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/simonw/datasette-scan
|
|
8
|
+
Project-URL: Changelog, https://github.com/simonw/datasette-scan/releases
|
|
9
|
+
Project-URL: Issues, https://github.com/simonw/datasette-scan/issues
|
|
10
|
+
Project-URL: CI, https://github.com/simonw/datasette-scan/actions
|
|
11
|
+
Classifier: Framework :: Datasette
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: datasette
|
|
16
|
+
Requires-Dist: sqlite-scanner>=0.1.1
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# datasette-scan
|
|
20
|
+
|
|
21
|
+
[](https://pypi.org/project/datasette-scan/)
|
|
22
|
+
[](https://github.com/simonw/datasette-scan/releases)
|
|
23
|
+
[](https://github.com/simonw/datasette-scan/actions/workflows/test.yml)
|
|
24
|
+
[](https://github.com/simonw/datasette-scan/blob/main/LICENSE)
|
|
25
|
+
|
|
26
|
+
Datasette plugin that scans directories for SQLite database files and serves them.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
Install this plugin in the same environment as Datasette.
|
|
31
|
+
```bash
|
|
32
|
+
datasette install datasette-scan
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
Scan the current directory for SQLite files and serve them:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
datasette scan
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Scan a specific directory:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
datasette scan /path/to/directory
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Scan multiple directories and include explicit database files:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
datasette scan /data/projects /data/archives extra.db
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Specify a port (or any other `datasette serve` option):
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
datasette scan -p 8001
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
All options accepted by `datasette serve` are also accepted by `datasette scan` -- these are introspected at runtime, so new options added to future versions of Datasette will be picked up automatically.
|
|
62
|
+
|
|
63
|
+
### How it works
|
|
64
|
+
|
|
65
|
+
- Positional arguments that are **directories** are scanned recursively for SQLite files using the [sqlite-scanner](https://pypi.org/project/sqlite-scanner/) binary, which identifies SQLite files by their magic bytes rather than file extension.
|
|
66
|
+
- Positional arguments that are **files** are passed through directly as database files.
|
|
67
|
+
- If no positional arguments are given, the current directory (`.`) is scanned.
|
|
68
|
+
- Discovered files are then served as if you had run `datasette serve file1.db file2.db ...`.
|
|
69
|
+
|
|
70
|
+
### Continuous scanning
|
|
71
|
+
|
|
72
|
+
Use `--scan-interval` to periodically re-scan directories for new SQLite files while the server is running. New databases will be added automatically.
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
datasette scan /data --scan-interval 5
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
This re-scans every 5 seconds. Any new SQLite files that appear in the scanned directories will be added to the running Datasette instance without a restart.
|
|
79
|
+
|
|
80
|
+
### Corrupted and locked files
|
|
81
|
+
|
|
82
|
+
Since `datasette scan` discovers files automatically, it takes precautions against problematic databases:
|
|
83
|
+
|
|
84
|
+
- **Corrupted files are skipped.** Each discovered file is validated by running `SELECT * FROM sqlite_master` before it is served. Files that fail this check are skipped with a warning to stderr.
|
|
85
|
+
- **Locked files are handled safely.** Databases locked by another process are opened in read-only mode instead of causing the server to fail. (The `--nolock` option from `datasette serve` is always enabled and not exposed as a separate flag.)
|
|
86
|
+
|
|
87
|
+
These protections apply to files discovered by scanning directories. Explicit file arguments are passed through to `datasette serve` without validation.
|
|
88
|
+
|
|
89
|
+
### Examples
|
|
90
|
+
|
|
91
|
+
Scan the current directory and open in a browser:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
datasette scan -o
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Scan with CORS enabled on a custom port:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
datasette scan /data --cors -p 9000
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Use `--get` to test without starting a server:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
datasette scan /data --get /.json
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Development
|
|
110
|
+
|
|
111
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
112
|
+
```bash
|
|
113
|
+
cd datasette-scan
|
|
114
|
+
# Confirm the plugin is visible
|
|
115
|
+
uv run datasette plugins
|
|
116
|
+
```
|
|
117
|
+
To run the tests:
|
|
118
|
+
```bash
|
|
119
|
+
uv run pytest
|
|
120
|
+
```
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# datasette-scan
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/datasette-scan/)
|
|
4
|
+
[](https://github.com/simonw/datasette-scan/releases)
|
|
5
|
+
[](https://github.com/simonw/datasette-scan/actions/workflows/test.yml)
|
|
6
|
+
[](https://github.com/simonw/datasette-scan/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
Datasette plugin that scans directories for SQLite database files and serves them.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Install this plugin in the same environment as Datasette.
|
|
13
|
+
```bash
|
|
14
|
+
datasette install datasette-scan
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
Scan the current directory for SQLite files and serve them:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
datasette scan
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Scan a specific directory:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
datasette scan /path/to/directory
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Scan multiple directories and include explicit database files:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
datasette scan /data/projects /data/archives extra.db
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Specify a port (or any other `datasette serve` option):
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
datasette scan -p 8001
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
All options accepted by `datasette serve` are also accepted by `datasette scan` -- these are introspected at runtime, so new options added to future versions of Datasette will be picked up automatically.
|
|
44
|
+
|
|
45
|
+
### How it works
|
|
46
|
+
|
|
47
|
+
- Positional arguments that are **directories** are scanned recursively for SQLite files using the [sqlite-scanner](https://pypi.org/project/sqlite-scanner/) binary, which identifies SQLite files by their magic bytes rather than file extension.
|
|
48
|
+
- Positional arguments that are **files** are passed through directly as database files.
|
|
49
|
+
- If no positional arguments are given, the current directory (`.`) is scanned.
|
|
50
|
+
- Discovered files are then served as if you had run `datasette serve file1.db file2.db ...`.
|
|
51
|
+
|
|
52
|
+
### Continuous scanning
|
|
53
|
+
|
|
54
|
+
Use `--scan-interval` to periodically re-scan directories for new SQLite files while the server is running. New databases will be added automatically.
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
datasette scan /data --scan-interval 5
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
This re-scans every 5 seconds. Any new SQLite files that appear in the scanned directories will be added to the running Datasette instance without a restart.
|
|
61
|
+
|
|
62
|
+
### Corrupted and locked files
|
|
63
|
+
|
|
64
|
+
Since `datasette scan` discovers files automatically, it takes precautions against problematic databases:
|
|
65
|
+
|
|
66
|
+
- **Corrupted files are skipped.** Each discovered file is validated by running `SELECT * FROM sqlite_master` before it is served. Files that fail this check are skipped with a warning to stderr.
|
|
67
|
+
- **Locked files are handled safely.** Databases locked by another process are opened in read-only mode instead of causing the server to fail. (The `--nolock` option from `datasette serve` is always enabled and not exposed as a separate flag.)
|
|
68
|
+
|
|
69
|
+
These protections apply to files discovered by scanning directories. Explicit file arguments are passed through to `datasette serve` without validation.
|
|
70
|
+
|
|
71
|
+
### Examples
|
|
72
|
+
|
|
73
|
+
Scan the current directory and open in a browser:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
datasette scan -o
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Scan with CORS enabled on a custom port:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
datasette scan /data --cors -p 9000
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Use `--get` to test without starting a server:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
datasette scan /data --get /.json
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Development
|
|
92
|
+
|
|
93
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
94
|
+
```bash
|
|
95
|
+
cd datasette-scan
|
|
96
|
+
# Confirm the plugin is visible
|
|
97
|
+
uv run datasette plugins
|
|
98
|
+
```
|
|
99
|
+
To run the tests:
|
|
100
|
+
```bash
|
|
101
|
+
uv run pytest
|
|
102
|
+
```
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
from datasette import hookimpl
|
|
2
|
+
from datasette.database import Database
|
|
3
|
+
import click
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sqlite3
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import sqlite_scanner
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def validate_databases(paths):
|
|
16
|
+
"""Check each path is a readable SQLite database.
|
|
17
|
+
|
|
18
|
+
Returns (valid, skipped) where skipped is a list of (path, reason) tuples.
|
|
19
|
+
"""
|
|
20
|
+
valid = []
|
|
21
|
+
skipped = []
|
|
22
|
+
for path in paths:
|
|
23
|
+
try:
|
|
24
|
+
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
|
|
25
|
+
try:
|
|
26
|
+
conn.execute("SELECT * FROM sqlite_master")
|
|
27
|
+
valid.append(path)
|
|
28
|
+
finally:
|
|
29
|
+
conn.close()
|
|
30
|
+
except Exception as e:
|
|
31
|
+
skipped.append((path, str(e)))
|
|
32
|
+
return valid, skipped
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def scan_directories(directories):
|
|
36
|
+
"""Scan directories for SQLite files using the sqlite-scanner binary.
|
|
37
|
+
|
|
38
|
+
Returns a list of absolute paths to discovered SQLite files.
|
|
39
|
+
"""
|
|
40
|
+
binary = sqlite_scanner.get_binary_path()
|
|
41
|
+
if not os.path.exists(binary):
|
|
42
|
+
raise click.ClickException(
|
|
43
|
+
f"sqlite-scanner binary not found at {binary}"
|
|
44
|
+
)
|
|
45
|
+
result = subprocess.run(
|
|
46
|
+
[binary, "--jsonl"] + list(directories),
|
|
47
|
+
capture_output=True,
|
|
48
|
+
text=True,
|
|
49
|
+
)
|
|
50
|
+
if result.returncode != 0:
|
|
51
|
+
raise click.ClickException(
|
|
52
|
+
f"sqlite-scanner failed: {result.stderr.strip()}"
|
|
53
|
+
)
|
|
54
|
+
paths = []
|
|
55
|
+
for line in result.stdout.strip().splitlines():
|
|
56
|
+
if line:
|
|
57
|
+
entry = json.loads(line)
|
|
58
|
+
paths.append(entry["path"])
|
|
59
|
+
return paths
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def rescan_and_add_databases(ds, directories, known_paths):
|
|
63
|
+
"""Re-scan directories and add any newly discovered databases to Datasette.
|
|
64
|
+
|
|
65
|
+
Returns the updated set of known paths.
|
|
66
|
+
"""
|
|
67
|
+
found = scan_directories(directories)
|
|
68
|
+
known_paths = set(known_paths)
|
|
69
|
+
for path in found:
|
|
70
|
+
if path not in known_paths:
|
|
71
|
+
db = Database(ds, path=path, is_mutable=True)
|
|
72
|
+
ds.add_database(db)
|
|
73
|
+
known_paths.add(path)
|
|
74
|
+
return known_paths
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _background_scanner(ds, directories, known_paths, interval):
|
|
78
|
+
"""Background thread that periodically re-scans for new databases."""
|
|
79
|
+
while True:
|
|
80
|
+
time.sleep(interval)
|
|
81
|
+
try:
|
|
82
|
+
known_paths = rescan_and_add_databases(ds, directories, known_paths)
|
|
83
|
+
except Exception as e:
|
|
84
|
+
click.echo(f"Scan error: {e}", err=True)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@hookimpl
|
|
88
|
+
def register_commands(cli):
|
|
89
|
+
serve_cmd = cli.commands.get("serve")
|
|
90
|
+
|
|
91
|
+
@cli.command()
|
|
92
|
+
@click.argument("paths", type=click.Path(), nargs=-1)
|
|
93
|
+
@click.option(
|
|
94
|
+
"--scan-interval",
|
|
95
|
+
type=float,
|
|
96
|
+
default=None,
|
|
97
|
+
help="Re-scan directories for new databases every N seconds",
|
|
98
|
+
)
|
|
99
|
+
def scan(paths, scan_interval, **kwargs):
|
|
100
|
+
"""Scan directories for SQLite files and serve them with Datasette"""
|
|
101
|
+
if not paths:
|
|
102
|
+
paths = (".",)
|
|
103
|
+
|
|
104
|
+
# Separate files from directories
|
|
105
|
+
db_files = []
|
|
106
|
+
directories = []
|
|
107
|
+
for p in paths:
|
|
108
|
+
if os.path.isdir(p):
|
|
109
|
+
directories.append(p)
|
|
110
|
+
else:
|
|
111
|
+
db_files.append(p)
|
|
112
|
+
|
|
113
|
+
# Scan directories for SQLite files
|
|
114
|
+
scanned_files = []
|
|
115
|
+
if directories:
|
|
116
|
+
scanned_files = scan_directories(directories)
|
|
117
|
+
|
|
118
|
+
# Validate scanned files, skip corrupted ones
|
|
119
|
+
if scanned_files:
|
|
120
|
+
valid, skipped = validate_databases(scanned_files)
|
|
121
|
+
for path, reason in skipped:
|
|
122
|
+
click.echo(
|
|
123
|
+
f"Skipping {path}: {reason}", err=True
|
|
124
|
+
)
|
|
125
|
+
db_files.extend(valid)
|
|
126
|
+
|
|
127
|
+
# Always use nolock for safety with discovered files
|
|
128
|
+
kwargs["nolock"] = True
|
|
129
|
+
|
|
130
|
+
if scan_interval is not None and directories:
|
|
131
|
+
# Continuous scanning mode: build and run the server ourselves
|
|
132
|
+
# so we can add databases to the running instance
|
|
133
|
+
known_paths = set(db_files)
|
|
134
|
+
ds = serve_cmd.callback(
|
|
135
|
+
files=tuple(db_files), return_instance=True, **kwargs
|
|
136
|
+
)
|
|
137
|
+
# Start background scanner thread
|
|
138
|
+
scanner_thread = threading.Thread(
|
|
139
|
+
target=_background_scanner,
|
|
140
|
+
args=(ds, directories, known_paths, scan_interval),
|
|
141
|
+
daemon=True,
|
|
142
|
+
)
|
|
143
|
+
scanner_thread.start()
|
|
144
|
+
|
|
145
|
+
# Handle --get: do the request and exit
|
|
146
|
+
get = kwargs.get("get")
|
|
147
|
+
if get:
|
|
148
|
+
from datasette.utils.testing import TestClient
|
|
149
|
+
|
|
150
|
+
client = TestClient(ds)
|
|
151
|
+
response = client.get(get)
|
|
152
|
+
click.echo(response.text)
|
|
153
|
+
sys.exit(0 if response.status == 200 else 1)
|
|
154
|
+
|
|
155
|
+
# Start the server
|
|
156
|
+
import uvicorn
|
|
157
|
+
|
|
158
|
+
host = kwargs.get("host", "127.0.0.1")
|
|
159
|
+
port = kwargs.get("port", 8001)
|
|
160
|
+
uvicorn_kwargs = dict(
|
|
161
|
+
host=host,
|
|
162
|
+
port=port,
|
|
163
|
+
log_level="info",
|
|
164
|
+
lifespan="on",
|
|
165
|
+
workers=1,
|
|
166
|
+
)
|
|
167
|
+
uds = kwargs.get("uds")
|
|
168
|
+
if uds:
|
|
169
|
+
uvicorn_kwargs["uds"] = uds
|
|
170
|
+
ssl_keyfile = kwargs.get("ssl_keyfile")
|
|
171
|
+
if ssl_keyfile:
|
|
172
|
+
uvicorn_kwargs["ssl_keyfile"] = ssl_keyfile
|
|
173
|
+
ssl_certfile = kwargs.get("ssl_certfile")
|
|
174
|
+
if ssl_certfile:
|
|
175
|
+
uvicorn_kwargs["ssl_certfile"] = ssl_certfile
|
|
176
|
+
uvicorn.run(ds.app(), **uvicorn_kwargs)
|
|
177
|
+
else:
|
|
178
|
+
# Simple mode: delegate to serve
|
|
179
|
+
ctx = click.get_current_context()
|
|
180
|
+
ctx.invoke(serve_cmd, files=tuple(db_files), **kwargs)
|
|
181
|
+
|
|
182
|
+
# Copy all options from serve to scan (but not arguments),
|
|
183
|
+
# excluding --nolock which is always enabled for scan
|
|
184
|
+
if serve_cmd:
|
|
185
|
+
for param in serve_cmd.params:
|
|
186
|
+
if isinstance(param, click.Option) and param.name != "nolock":
|
|
187
|
+
scan.params.append(param)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datasette-scan
|
|
3
|
+
Version: 0.1
|
|
4
|
+
Summary: Datasette plugin for scanning for SQLite files
|
|
5
|
+
Author: Simon Willison
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/simonw/datasette-scan
|
|
8
|
+
Project-URL: Changelog, https://github.com/simonw/datasette-scan/releases
|
|
9
|
+
Project-URL: Issues, https://github.com/simonw/datasette-scan/issues
|
|
10
|
+
Project-URL: CI, https://github.com/simonw/datasette-scan/actions
|
|
11
|
+
Classifier: Framework :: Datasette
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: datasette
|
|
16
|
+
Requires-Dist: sqlite-scanner>=0.1.1
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# datasette-scan
|
|
20
|
+
|
|
21
|
+
[](https://pypi.org/project/datasette-scan/)
|
|
22
|
+
[](https://github.com/simonw/datasette-scan/releases)
|
|
23
|
+
[](https://github.com/simonw/datasette-scan/actions/workflows/test.yml)
|
|
24
|
+
[](https://github.com/simonw/datasette-scan/blob/main/LICENSE)
|
|
25
|
+
|
|
26
|
+
Datasette plugin that scans directories for SQLite database files and serves them.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
Install this plugin in the same environment as Datasette.
|
|
31
|
+
```bash
|
|
32
|
+
datasette install datasette-scan
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
Scan the current directory for SQLite files and serve them:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
datasette scan
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Scan a specific directory:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
datasette scan /path/to/directory
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Scan multiple directories and include explicit database files:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
datasette scan /data/projects /data/archives extra.db
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Specify a port (or any other `datasette serve` option):
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
datasette scan -p 8001
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
All options accepted by `datasette serve` are also accepted by `datasette scan` -- these are introspected at runtime, so new options added to future versions of Datasette will be picked up automatically.
|
|
62
|
+
|
|
63
|
+
### How it works
|
|
64
|
+
|
|
65
|
+
- Positional arguments that are **directories** are scanned recursively for SQLite files using the [sqlite-scanner](https://pypi.org/project/sqlite-scanner/) binary, which identifies SQLite files by their magic bytes rather than file extension.
|
|
66
|
+
- Positional arguments that are **files** are passed through directly as database files.
|
|
67
|
+
- If no positional arguments are given, the current directory (`.`) is scanned.
|
|
68
|
+
- Discovered files are then served as if you had run `datasette serve file1.db file2.db ...`.
|
|
69
|
+
|
|
70
|
+
### Continuous scanning
|
|
71
|
+
|
|
72
|
+
Use `--scan-interval` to periodically re-scan directories for new SQLite files while the server is running. New databases will be added automatically.
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
datasette scan /data --scan-interval 5
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
This re-scans every 5 seconds. Any new SQLite files that appear in the scanned directories will be added to the running Datasette instance without a restart.
|
|
79
|
+
|
|
80
|
+
### Corrupted and locked files
|
|
81
|
+
|
|
82
|
+
Since `datasette scan` discovers files automatically, it takes precautions against problematic databases:
|
|
83
|
+
|
|
84
|
+
- **Corrupted files are skipped.** Each discovered file is validated by running `SELECT * FROM sqlite_master` before it is served. Files that fail this check are skipped with a warning to stderr.
|
|
85
|
+
- **Locked files are handled safely.** Databases locked by another process are opened in read-only mode instead of causing the server to fail. (The `--nolock` option from `datasette serve` is always enabled and not exposed as a separate flag.)
|
|
86
|
+
|
|
87
|
+
These protections apply to files discovered by scanning directories. Explicit file arguments are passed through to `datasette serve` without validation.
|
|
88
|
+
|
|
89
|
+
### Examples
|
|
90
|
+
|
|
91
|
+
Scan the current directory and open in a browser:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
datasette scan -o
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Scan with CORS enabled on a custom port:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
datasette scan /data --cors -p 9000
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Use `--get` to test without starting a server:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
datasette scan /data --get /.json
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Development
|
|
110
|
+
|
|
111
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
112
|
+
```bash
|
|
113
|
+
cd datasette-scan
|
|
114
|
+
# Confirm the plugin is visible
|
|
115
|
+
uv run datasette plugins
|
|
116
|
+
```
|
|
117
|
+
To run the tests:
|
|
118
|
+
```bash
|
|
119
|
+
uv run pytest
|
|
120
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
datasette_scan/__init__.py
|
|
5
|
+
datasette_scan.egg-info/PKG-INFO
|
|
6
|
+
datasette_scan.egg-info/SOURCES.txt
|
|
7
|
+
datasette_scan.egg-info/dependency_links.txt
|
|
8
|
+
datasette_scan.egg-info/entry_points.txt
|
|
9
|
+
datasette_scan.egg-info/requires.txt
|
|
10
|
+
datasette_scan.egg-info/top_level.txt
|
|
11
|
+
tests/test_scan.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
datasette_scan
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "datasette-scan"
|
|
3
|
+
version = "0.1"
|
|
4
|
+
description = "Datasette plugin for scanning for SQLite files"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{name = "Simon Willison"}]
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
classifiers=[
|
|
9
|
+
"Framework :: Datasette"
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"datasette",
|
|
14
|
+
"sqlite-scanner>=0.1.1"
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[dependency-groups]
|
|
18
|
+
dev = [
|
|
19
|
+
"pytest",
|
|
20
|
+
"pytest-asyncio"
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["setuptools"]
|
|
25
|
+
build-backend = "setuptools.build_meta"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/simonw/datasette-scan"
|
|
30
|
+
Changelog = "https://github.com/simonw/datasette-scan/releases"
|
|
31
|
+
Issues = "https://github.com/simonw/datasette-scan/issues"
|
|
32
|
+
CI = "https://github.com/simonw/datasette-scan/actions"
|
|
33
|
+
|
|
34
|
+
[project.entry-points.datasette]
|
|
35
|
+
scan = "datasette_scan"
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
asyncio_mode = "strict"
|
|
39
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
40
|
+
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import click
|
|
2
|
+
from click.testing import CliRunner
|
|
3
|
+
from datasette.app import Datasette
|
|
4
|
+
from datasette.cli import cli
|
|
5
|
+
from datasette_scan import scan_directories, rescan_and_add_databases, validate_databases
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import pytest
|
|
9
|
+
import sqlite3
|
|
10
|
+
import tempfile
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from unittest.mock import patch
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture
|
|
16
|
+
def tmp_with_dbs(tmp_path):
|
|
17
|
+
"""Create a temp directory with some SQLite databases."""
|
|
18
|
+
db1 = tmp_path / "one.db"
|
|
19
|
+
db2 = tmp_path / "subdir" / "two.db"
|
|
20
|
+
db2.parent.mkdir()
|
|
21
|
+
for db_path in (db1, db2):
|
|
22
|
+
conn = sqlite3.connect(str(db_path))
|
|
23
|
+
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
24
|
+
conn.close()
|
|
25
|
+
# Non-SQLite file
|
|
26
|
+
(tmp_path / "not_a_db.txt").write_text("hello")
|
|
27
|
+
return tmp_path
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@pytest.mark.asyncio
|
|
31
|
+
async def test_plugin_is_installed():
|
|
32
|
+
datasette = Datasette(memory=True)
|
|
33
|
+
response = await datasette.client.get("/-/plugins.json")
|
|
34
|
+
assert response.status_code == 200
|
|
35
|
+
installed_plugins = {p["name"] for p in response.json()}
|
|
36
|
+
assert "datasette-scan" in installed_plugins
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_scan_command_exists():
|
|
40
|
+
runner = CliRunner()
|
|
41
|
+
result = runner.invoke(cli, ["scan", "--help"])
|
|
42
|
+
assert result.exit_code == 0
|
|
43
|
+
assert "Usage: cli scan" in result.output
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_scan_has_serve_options():
|
|
47
|
+
"""scan should have all of serve's options (except nolock, always enabled)."""
|
|
48
|
+
serve_cmd = cli.commands["serve"]
|
|
49
|
+
scan_cmd = cli.commands["scan"]
|
|
50
|
+
serve_option_names = {
|
|
51
|
+
p.name for p in serve_cmd.params if isinstance(p, click.Option)
|
|
52
|
+
}
|
|
53
|
+
scan_option_names = {
|
|
54
|
+
p.name for p in scan_cmd.params if isinstance(p, click.Option)
|
|
55
|
+
}
|
|
56
|
+
# All serve options except nolock should be present on scan
|
|
57
|
+
# nolock is always enabled for scan and not exposed as an option
|
|
58
|
+
missing = serve_option_names - scan_option_names - {"nolock"}
|
|
59
|
+
assert not missing, f"scan is missing these serve options: {missing}"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_scan_has_scan_interval_option():
|
|
63
|
+
"""scan should have the --scan-interval option that serve doesn't."""
|
|
64
|
+
scan_cmd = cli.commands["scan"]
|
|
65
|
+
scan_option_names = {
|
|
66
|
+
p.name for p in scan_cmd.params if isinstance(p, click.Option)
|
|
67
|
+
}
|
|
68
|
+
assert "scan_interval" in scan_option_names
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_scan_directories_finds_sqlite_files(tmp_with_dbs):
|
|
72
|
+
"""scan_directories should find SQLite files using the sqlite-scanner binary."""
|
|
73
|
+
found = scan_directories([str(tmp_with_dbs)])
|
|
74
|
+
found_names = {Path(f).name for f in found}
|
|
75
|
+
assert "one.db" in found_names
|
|
76
|
+
assert "two.db" in found_names
|
|
77
|
+
assert "not_a_db.txt" not in found_names
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_scan_default_scans_current_directory(tmp_with_dbs):
|
|
81
|
+
"""With no args, scan should scan the current directory."""
|
|
82
|
+
runner = CliRunner()
|
|
83
|
+
result = runner.invoke(
|
|
84
|
+
cli, ["scan", "--get", "/.json"], catch_exceptions=False
|
|
85
|
+
)
|
|
86
|
+
# We just need it to not error - with no SQLite in cwd it may serve
|
|
87
|
+
# empty but should not crash
|
|
88
|
+
assert result.exit_code == 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_scan_serves_discovered_files(tmp_with_dbs):
|
|
92
|
+
"""scan should discover files and serve them via Datasette."""
|
|
93
|
+
runner = CliRunner()
|
|
94
|
+
result = runner.invoke(
|
|
95
|
+
cli,
|
|
96
|
+
["scan", str(tmp_with_dbs), "--get", "/.json"],
|
|
97
|
+
catch_exceptions=False,
|
|
98
|
+
)
|
|
99
|
+
assert result.exit_code == 0
|
|
100
|
+
data = json.loads(result.output)
|
|
101
|
+
db_names = set(data.keys())
|
|
102
|
+
assert "one" in db_names
|
|
103
|
+
assert "two" in db_names
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_scan_explicit_file_args(tmp_with_dbs):
|
|
107
|
+
"""Explicit file arguments should be passed through directly."""
|
|
108
|
+
db_path = str(tmp_with_dbs / "one.db")
|
|
109
|
+
runner = CliRunner()
|
|
110
|
+
result = runner.invoke(
|
|
111
|
+
cli,
|
|
112
|
+
["scan", db_path, "--get", "/.json"],
|
|
113
|
+
catch_exceptions=False,
|
|
114
|
+
)
|
|
115
|
+
assert result.exit_code == 0
|
|
116
|
+
data = json.loads(result.output)
|
|
117
|
+
assert "one" in data
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_scan_mixed_files_and_dirs(tmp_with_dbs):
|
|
121
|
+
"""Mix of explicit files and directories should work."""
|
|
122
|
+
# Create an extra database outside the scanned dir
|
|
123
|
+
extra_db = tmp_with_dbs / "extra" / "standalone.db"
|
|
124
|
+
extra_db.parent.mkdir()
|
|
125
|
+
conn = sqlite3.connect(str(extra_db))
|
|
126
|
+
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
127
|
+
conn.close()
|
|
128
|
+
|
|
129
|
+
runner = CliRunner()
|
|
130
|
+
result = runner.invoke(
|
|
131
|
+
cli,
|
|
132
|
+
[
|
|
133
|
+
"scan",
|
|
134
|
+
str(tmp_with_dbs / "subdir"), # directory - will find two.db
|
|
135
|
+
str(extra_db), # explicit file
|
|
136
|
+
"--get",
|
|
137
|
+
"/.json",
|
|
138
|
+
],
|
|
139
|
+
catch_exceptions=False,
|
|
140
|
+
)
|
|
141
|
+
assert result.exit_code == 0
|
|
142
|
+
data = json.loads(result.output)
|
|
143
|
+
db_names = set(data.keys())
|
|
144
|
+
assert "two" in db_names
|
|
145
|
+
assert "standalone" in db_names
|
|
146
|
+
# one.db should NOT be found since we only scanned subdir
|
|
147
|
+
assert "one" not in db_names
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_scan_error_when_binary_missing():
|
|
151
|
+
"""Should raise a clear error if sqlite-scanner binary isn't found."""
|
|
152
|
+
with patch("datasette_scan.sqlite_scanner.get_binary_path") as mock_path:
|
|
153
|
+
mock_path.return_value = "/nonexistent/sqlite-scanner"
|
|
154
|
+
runner = CliRunner()
|
|
155
|
+
result = runner.invoke(cli, ["scan", "--get", "/.json"])
|
|
156
|
+
assert result.exit_code != 0
|
|
157
|
+
assert "sqlite-scanner" in result.output.lower() or "Error" in result.output
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def test_scan_passes_port_option(tmp_with_dbs):
|
|
161
|
+
"""Serve options like --port should be passed through."""
|
|
162
|
+
runner = CliRunner()
|
|
163
|
+
# Using --get bypasses actual server start, but port is still accepted
|
|
164
|
+
result = runner.invoke(
|
|
165
|
+
cli,
|
|
166
|
+
["scan", str(tmp_with_dbs), "-p", "9999", "--get", "/.json"],
|
|
167
|
+
catch_exceptions=False,
|
|
168
|
+
)
|
|
169
|
+
assert result.exit_code == 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@pytest.mark.asyncio
|
|
173
|
+
async def test_rescan_adds_new_databases(tmp_with_dbs):
|
|
174
|
+
"""rescan_and_add_databases should add newly discovered files to Datasette."""
|
|
175
|
+
# Start with one.db already known
|
|
176
|
+
db1 = str(tmp_with_dbs / "one.db")
|
|
177
|
+
ds = Datasette([db1])
|
|
178
|
+
known = {db1}
|
|
179
|
+
initial_db_count = len(ds.databases)
|
|
180
|
+
|
|
181
|
+
# Rescan should find two.db and add it
|
|
182
|
+
known = rescan_and_add_databases(ds, [str(tmp_with_dbs)], known)
|
|
183
|
+
assert len(ds.databases) > initial_db_count
|
|
184
|
+
db_names = set(ds.databases.keys())
|
|
185
|
+
assert "two" in db_names
|
|
186
|
+
|
|
187
|
+
# The new file should now be in known
|
|
188
|
+
two_path = str(tmp_with_dbs / "subdir" / "two.db")
|
|
189
|
+
assert two_path in known
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@pytest.mark.asyncio
|
|
193
|
+
async def test_rescan_does_not_duplicate(tmp_with_dbs):
|
|
194
|
+
"""rescan_and_add_databases should not re-add already known files."""
|
|
195
|
+
ds = Datasette([])
|
|
196
|
+
known = set()
|
|
197
|
+
|
|
198
|
+
# First scan adds files
|
|
199
|
+
known = rescan_and_add_databases(ds, [str(tmp_with_dbs)], known)
|
|
200
|
+
count_after_first = len(ds.databases)
|
|
201
|
+
|
|
202
|
+
# Second scan should not add duplicates
|
|
203
|
+
known = rescan_and_add_databases(ds, [str(tmp_with_dbs)], known)
|
|
204
|
+
assert len(ds.databases) == count_after_first
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def test_validate_databases_accepts_good_files(tmp_with_dbs):
|
|
208
|
+
"""validate_databases should accept valid SQLite files."""
|
|
209
|
+
paths = [
|
|
210
|
+
str(tmp_with_dbs / "one.db"),
|
|
211
|
+
str(tmp_with_dbs / "subdir" / "two.db"),
|
|
212
|
+
]
|
|
213
|
+
valid, skipped = validate_databases(paths)
|
|
214
|
+
assert valid == paths
|
|
215
|
+
assert skipped == []
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def test_validate_databases_skips_corrupted(tmp_path):
|
|
219
|
+
"""validate_databases should skip corrupted SQLite files."""
|
|
220
|
+
good = tmp_path / "good.db"
|
|
221
|
+
conn = sqlite3.connect(str(good))
|
|
222
|
+
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
223
|
+
conn.close()
|
|
224
|
+
|
|
225
|
+
corrupted = tmp_path / "corrupted.db"
|
|
226
|
+
data = bytearray(good.read_bytes())
|
|
227
|
+
for i in range(100, 200):
|
|
228
|
+
data[i] = 0xFF
|
|
229
|
+
corrupted.write_bytes(data)
|
|
230
|
+
|
|
231
|
+
valid, skipped = validate_databases([str(good), str(corrupted)])
|
|
232
|
+
assert valid == [str(good)]
|
|
233
|
+
assert len(skipped) == 1
|
|
234
|
+
assert skipped[0][0] == str(corrupted)
|
|
235
|
+
assert "malformed" in skipped[0][1].lower() or "error" in skipped[0][1].lower()
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def test_validate_databases_skips_truncated(tmp_path):
|
|
239
|
+
"""validate_databases should skip truncated SQLite files."""
|
|
240
|
+
truncated = tmp_path / "truncated.db"
|
|
241
|
+
truncated.write_bytes(b"SQLite format 3\x00" + b"\x00" * 84)
|
|
242
|
+
|
|
243
|
+
valid, skipped = validate_databases([str(truncated)])
|
|
244
|
+
assert valid == []
|
|
245
|
+
assert len(skipped) == 1
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def test_scan_skips_corrupted_and_serves_good(tmp_path):
|
|
249
|
+
"""scan should skip corrupted files and serve only valid ones."""
|
|
250
|
+
good = tmp_path / "good.db"
|
|
251
|
+
conn = sqlite3.connect(str(good))
|
|
252
|
+
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
253
|
+
conn.close()
|
|
254
|
+
|
|
255
|
+
corrupted = tmp_path / "corrupted.db"
|
|
256
|
+
data = bytearray(good.read_bytes())
|
|
257
|
+
for i in range(100, 200):
|
|
258
|
+
data[i] = 0xFF
|
|
259
|
+
corrupted.write_bytes(data)
|
|
260
|
+
|
|
261
|
+
runner = CliRunner()
|
|
262
|
+
result = runner.invoke(
|
|
263
|
+
cli,
|
|
264
|
+
["scan", str(tmp_path), "--get", "/.json"],
|
|
265
|
+
catch_exceptions=False,
|
|
266
|
+
)
|
|
267
|
+
assert result.exit_code == 0
|
|
268
|
+
# Output may contain warning lines before the JSON; extract JSON part
|
|
269
|
+
lines = result.output.strip().splitlines()
|
|
270
|
+
json_lines = [l for l in lines if not l.startswith("Skipping ")]
|
|
271
|
+
data = json.loads("\n".join(json_lines))
|
|
272
|
+
assert "good" in data
|
|
273
|
+
assert "corrupted" not in data
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def test_scan_warns_about_skipped_files(tmp_path):
|
|
277
|
+
"""scan should print warnings about skipped files."""
|
|
278
|
+
good = tmp_path / "good.db"
|
|
279
|
+
conn = sqlite3.connect(str(good))
|
|
280
|
+
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
281
|
+
conn.close()
|
|
282
|
+
|
|
283
|
+
corrupted = tmp_path / "corrupted.db"
|
|
284
|
+
data = bytearray(good.read_bytes())
|
|
285
|
+
for i in range(100, 200):
|
|
286
|
+
data[i] = 0xFF
|
|
287
|
+
corrupted.write_bytes(data)
|
|
288
|
+
|
|
289
|
+
runner = CliRunner()
|
|
290
|
+
result = runner.invoke(
|
|
291
|
+
cli,
|
|
292
|
+
["scan", str(tmp_path), "--get", "/.json"],
|
|
293
|
+
)
|
|
294
|
+
assert result.exit_code == 0
|
|
295
|
+
assert "corrupted.db" in result.output
|
|
296
|
+
assert "Skipping" in result.output
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def test_scan_defaults_nolock(tmp_with_dbs):
|
|
300
|
+
"""scan should pass --nolock by default to handle locked databases."""
|
|
301
|
+
# We can verify this by checking that the nolock kwarg is True
|
|
302
|
+
# when delegated to serve. We'll test indirectly: scan a directory
|
|
303
|
+
# and confirm it works (nolock doesn't break anything for unlocked files).
|
|
304
|
+
runner = CliRunner()
|
|
305
|
+
result = runner.invoke(
|
|
306
|
+
cli,
|
|
307
|
+
["scan", str(tmp_with_dbs), "--get", "/.json"],
|
|
308
|
+
catch_exceptions=False,
|
|
309
|
+
)
|
|
310
|
+
assert result.exit_code == 0
|
|
311
|
+
data = json.loads(result.output)
|
|
312
|
+
assert "one" in data
|