datapy 0.2.2__tar.gz → 0.3.0__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.
- {datapy-0.2.2/datapy.egg-info → datapy-0.3.0}/PKG-INFO +24 -3
- {datapy-0.2.2 → datapy-0.3.0}/README.md +23 -2
- {datapy-0.2.2 → datapy-0.3.0}/datapy/__init__.py +12 -5
- {datapy-0.2.2 → datapy-0.3.0}/datapy/_datafile.py +183 -42
- {datapy-0.2.2 → datapy-0.3.0}/datapy/_reader.py +57 -13
- datapy-0.3.0/datapy/_schema.py +216 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy/cli.py +81 -9
- {datapy-0.2.2 → datapy-0.3.0/datapy.egg-info}/PKG-INFO +24 -3
- {datapy-0.2.2 → datapy-0.3.0}/datapy.egg-info/SOURCES.txt +2 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_cli.py +104 -0
- datapy-0.3.0/tests/test_docs.py +74 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_entry_points.py +12 -1
- datapy-0.3.0/tests/test_schema.py +334 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_stream.py +5 -2
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_values.py +44 -1
- datapy-0.2.2/tests/test_docs.py +0 -42
- {datapy-0.2.2 → datapy-0.3.0}/LICENSE.txt +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/MANIFEST.in +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy/__main__.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy/_errors.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy/_statement.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy.egg-info/dependency_links.txt +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy.egg-info/entry_points.txt +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy.egg-info/requires.txt +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/datapy.egg-info/top_level.txt +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/pyproject.toml +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/setup.cfg +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_ci.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_datafile.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_query.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_statement.py +0 -0
- {datapy-0.2.2 → datapy-0.3.0}/tests/test_style.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datapy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: An intuitive lightweight file based database and query tool.
|
|
5
5
|
Author-email: Corey McCarty <corey@mccarty.dev>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -177,6 +177,26 @@ with datapy.stream("select name from people.csv where age > 40") as rows:
|
|
|
177
177
|
print(row["name"])
|
|
178
178
|
```
|
|
179
179
|
|
|
180
|
+
### Saving a file's schema
|
|
181
|
+
|
|
182
|
+
For a file you will come back to, or a file that arrives every month in the
|
|
183
|
+
same shape, save its columns and their types once, edit them if needed, and
|
|
184
|
+
reuse them instead of letting datapy guess from the first 1,000 rows:
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
datapy --schema-of orders-2026-11.csv orders.json
|
|
188
|
+
datapy -sa orders-2026-12.csv --schema orders.json -w 'amount > 990'
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
In Python a schema also gives typed values: `int` and `decimal.Decimal`
|
|
192
|
+
instead of strings.
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
with datapy.open("orders-2026-12.csv", schema="orders.json") as orders:
|
|
196
|
+
for row in orders.query("select id, amount from orders where amount > 990"):
|
|
197
|
+
print(row["id"] + 1, row["amount"]) # 1201 Decimal('1024.50')
|
|
198
|
+
```
|
|
199
|
+
|
|
180
200
|
Problems with a file or a statement raise `datapy.DatapyError`. The
|
|
181
201
|
[Python API reference](https://coreydmccarty.dev/datapy/python-api/) has the details.
|
|
182
202
|
|
|
@@ -186,8 +206,9 @@ One `select` statement against one file. The statement is run by SQLite, so
|
|
|
186
206
|
`where`, `order by`, `group by`, `limit` and SQLite's built-in functions all
|
|
187
207
|
work. A column is compared as a number when every value in it is one, so
|
|
188
208
|
`age > 40` compares numbers rather than text. That is decided from the first
|
|
189
|
-
1,000 rows; `-t zip` compares a column as
|
|
190
|
-
select comes back exactly as it is written in
|
|
209
|
+
1,000 rows, unless a schema says otherwise; `-t zip` compares a column as
|
|
210
|
+
text. Either way, a column you select comes back exactly as it is written in
|
|
211
|
+
the file.
|
|
191
212
|
|
|
192
213
|
See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
|
|
193
214
|
|
|
@@ -149,6 +149,26 @@ with datapy.stream("select name from people.csv where age > 40") as rows:
|
|
|
149
149
|
print(row["name"])
|
|
150
150
|
```
|
|
151
151
|
|
|
152
|
+
### Saving a file's schema
|
|
153
|
+
|
|
154
|
+
For a file you will come back to, or a file that arrives every month in the
|
|
155
|
+
same shape, save its columns and their types once, edit them if needed, and
|
|
156
|
+
reuse them instead of letting datapy guess from the first 1,000 rows:
|
|
157
|
+
|
|
158
|
+
```sh
|
|
159
|
+
datapy --schema-of orders-2026-11.csv orders.json
|
|
160
|
+
datapy -sa orders-2026-12.csv --schema orders.json -w 'amount > 990'
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
In Python a schema also gives typed values: `int` and `decimal.Decimal`
|
|
164
|
+
instead of strings.
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
with datapy.open("orders-2026-12.csv", schema="orders.json") as orders:
|
|
168
|
+
for row in orders.query("select id, amount from orders where amount > 990"):
|
|
169
|
+
print(row["id"] + 1, row["amount"]) # 1201 Decimal('1024.50')
|
|
170
|
+
```
|
|
171
|
+
|
|
152
172
|
Problems with a file or a statement raise `datapy.DatapyError`. The
|
|
153
173
|
[Python API reference](https://coreydmccarty.dev/datapy/python-api/) has the details.
|
|
154
174
|
|
|
@@ -158,8 +178,9 @@ One `select` statement against one file. The statement is run by SQLite, so
|
|
|
158
178
|
`where`, `order by`, `group by`, `limit` and SQLite's built-in functions all
|
|
159
179
|
work. A column is compared as a number when every value in it is one, so
|
|
160
180
|
`age > 40` compares numbers rather than text. That is decided from the first
|
|
161
|
-
1,000 rows; `-t zip` compares a column as
|
|
162
|
-
select comes back exactly as it is written in
|
|
181
|
+
1,000 rows, unless a schema says otherwise; `-t zip` compares a column as
|
|
182
|
+
text. Either way, a column you select comes back exactly as it is written in
|
|
183
|
+
the file.
|
|
163
184
|
|
|
164
185
|
See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
|
|
165
186
|
|
|
@@ -14,13 +14,14 @@ The command line entry point is `datapy.cli`, which uses only the names
|
|
|
14
14
|
exported here.
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
|
-
__version__ = "0.
|
|
17
|
+
__version__ = "0.3.0"
|
|
18
18
|
|
|
19
19
|
from datapy._datafile import DataFile, Result, Stream, query, stream
|
|
20
20
|
from datapy._errors import DatapyError
|
|
21
|
+
from datapy._schema import Schema, schema_of
|
|
21
22
|
|
|
22
23
|
# Tracebacks and reprs show the public name, not the internal module.
|
|
23
|
-
for _public in (DataFile, DatapyError, Result, Stream):
|
|
24
|
+
for _public in (DataFile, DatapyError, Result, Schema, Stream, schema_of):
|
|
24
25
|
_public.__module__ = __name__
|
|
25
26
|
del _public
|
|
26
27
|
|
|
@@ -28,15 +29,17 @@ del _public
|
|
|
28
29
|
def open(
|
|
29
30
|
path,
|
|
30
31
|
*,
|
|
31
|
-
header: bool =
|
|
32
|
-
delimiter: str =
|
|
32
|
+
header: bool | None = None,
|
|
33
|
+
delimiter: str | None = None,
|
|
33
34
|
text=(),
|
|
34
35
|
skip_bad_rows: bool = False,
|
|
36
|
+
schema=None,
|
|
37
|
+
typed: bool | None = None,
|
|
35
38
|
) -> DataFile:
|
|
36
39
|
"""Open a file for querying. Use it in a `with` block.
|
|
37
40
|
|
|
38
41
|
Returns a `DataFile`; see that class for what `header`, `delimiter`,
|
|
39
|
-
`text` and `
|
|
42
|
+
`text`, `skip_bad_rows`, `schema` and `typed` mean.
|
|
40
43
|
"""
|
|
41
44
|
return DataFile(
|
|
42
45
|
path,
|
|
@@ -44,6 +47,8 @@ def open(
|
|
|
44
47
|
delimiter=delimiter,
|
|
45
48
|
text=text,
|
|
46
49
|
skip_bad_rows=skip_bad_rows,
|
|
50
|
+
schema=schema,
|
|
51
|
+
typed=typed,
|
|
47
52
|
)
|
|
48
53
|
|
|
49
54
|
|
|
@@ -52,8 +57,10 @@ __all__ = [
|
|
|
52
57
|
"DataFile",
|
|
53
58
|
"DatapyError",
|
|
54
59
|
"Result",
|
|
60
|
+
"Schema",
|
|
55
61
|
"Stream",
|
|
56
62
|
"query",
|
|
63
|
+
"schema_of",
|
|
57
64
|
"stream",
|
|
58
65
|
"__version__",
|
|
59
66
|
]
|
|
@@ -2,13 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import decimal
|
|
5
6
|
import itertools
|
|
6
7
|
import os
|
|
7
8
|
import sqlite3
|
|
8
|
-
from dataclasses import dataclass
|
|
9
|
+
from dataclasses import dataclass, field
|
|
9
10
|
|
|
10
11
|
from datapy._errors import DatapyError
|
|
11
|
-
from datapy._reader import BIG, NUMBER_ORDER, Source, compare_numbers
|
|
12
|
+
from datapy._reader import BIG, NUMBER_ORDER, Source, compare_numbers, is_number
|
|
13
|
+
from datapy._schema import as_schema
|
|
12
14
|
from datapy._statement import (
|
|
13
15
|
ROW_FUNCTIONS,
|
|
14
16
|
clean,
|
|
@@ -23,6 +25,30 @@ from datapy._statement import (
|
|
|
23
25
|
BATCH_ROWS = 10_000
|
|
24
26
|
FIRST_BATCH_ROWS = 100
|
|
25
27
|
|
|
28
|
+
# Declared types that tell sqlite3 to hand a column back as a Python number.
|
|
29
|
+
# Each keeps TEXT affinity (it contains "TEXT" and not "INT"), so SQLite
|
|
30
|
+
# stores the value exactly as written, and only the conversion is typed.
|
|
31
|
+
_AS_INT = "DATAPY_TEXT_WHOLE"
|
|
32
|
+
_AS_DECIMAL = "DATAPY_TEXT_DECIMAL"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _to_int(value: bytes):
|
|
36
|
+
try:
|
|
37
|
+
return int(value)
|
|
38
|
+
except ValueError:
|
|
39
|
+
return None # not a number: empty, as when it is compared
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _to_decimal(value: bytes):
|
|
43
|
+
try:
|
|
44
|
+
return decimal.Decimal(value.decode())
|
|
45
|
+
except decimal.InvalidOperation:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
sqlite3.register_converter(_AS_INT, _to_int)
|
|
50
|
+
sqlite3.register_converter(_AS_DECIMAL, _to_decimal)
|
|
51
|
+
|
|
26
52
|
_READ_ONLY_ACTIONS = {
|
|
27
53
|
sqlite3.SQLITE_SELECT,
|
|
28
54
|
sqlite3.SQLITE_READ,
|
|
@@ -45,10 +71,13 @@ class Result:
|
|
|
45
71
|
|
|
46
72
|
- `columns`: the column names, in order.
|
|
47
73
|
- `rows`: the rows, as a list.
|
|
74
|
+
- `unfit`: values in a numeric column that are not numbers, counted by
|
|
75
|
+
column (see `Stream.unfit`).
|
|
48
76
|
"""
|
|
49
77
|
|
|
50
78
|
columns: list[str]
|
|
51
79
|
rows: list[sqlite3.Row]
|
|
80
|
+
unfit: dict[str, int] = field(default_factory=dict)
|
|
52
81
|
|
|
53
82
|
def __iter__(self):
|
|
54
83
|
return iter(self.rows)
|
|
@@ -74,12 +103,20 @@ class Stream:
|
|
|
74
103
|
- `skipped`: with `skip_bad_rows`, how many rows have been left out so
|
|
75
104
|
far for having the wrong number of fields. Final once the last row has
|
|
76
105
|
been read.
|
|
106
|
+
- `unfit`: values in a numeric column that are not numbers (an `N/A`
|
|
107
|
+
after the first 1,000 rows, say), counted by column. They are treated
|
|
108
|
+
as empty when comparing, sorting and calculating, but still returned as
|
|
109
|
+
written. Only columns the statement compares or calculates with are
|
|
110
|
+
checked. Final once the last row has been read.
|
|
77
111
|
"""
|
|
78
112
|
|
|
79
|
-
def __init__(
|
|
113
|
+
def __init__(
|
|
114
|
+
self, columns: list[str], rows, close, source, table, *, streamed: bool
|
|
115
|
+
):
|
|
80
116
|
self.columns = columns
|
|
81
117
|
self.streamed = streamed
|
|
82
118
|
self._source = source
|
|
119
|
+
self._table = table
|
|
83
120
|
self._rows = rows
|
|
84
121
|
self._close = close
|
|
85
122
|
|
|
@@ -91,6 +128,10 @@ class Stream:
|
|
|
91
128
|
def line_ending(self) -> str:
|
|
92
129
|
return self._source.line_ending
|
|
93
130
|
|
|
131
|
+
@property
|
|
132
|
+
def unfit(self) -> dict[str, int]:
|
|
133
|
+
return dict(self._table.unfit)
|
|
134
|
+
|
|
94
135
|
def __iter__(self) -> Stream:
|
|
95
136
|
return self
|
|
96
137
|
|
|
@@ -121,37 +162,62 @@ class _Table:
|
|
|
121
162
|
`layout` says how each numeric column is stored (see `rewrite`). One that
|
|
122
163
|
is both returned and compared is stored twice, so the value can be handed
|
|
123
164
|
back exactly as it is in the file.
|
|
165
|
+
|
|
166
|
+
In the number form of a column, a value that is not a number is made
|
|
167
|
+
empty, so it cannot match a comparison or sort among the numbers, and is
|
|
168
|
+
counted in `unfit`. The text form keeps it as written.
|
|
124
169
|
"""
|
|
125
170
|
|
|
126
|
-
def __init__(
|
|
171
|
+
def __init__(
|
|
172
|
+
self, database: str, source: Source, layout: dict[str, str], typed: bool
|
|
173
|
+
):
|
|
127
174
|
self.name = quote(source.path)
|
|
128
175
|
self._locked = False
|
|
129
176
|
self.functions = set()
|
|
130
177
|
self.selects = 0
|
|
131
|
-
|
|
178
|
+
# With `typed`, the text form of a numeric column is declared with a
|
|
179
|
+
# type that sqlite3 converts on the way out. Only a column selected on
|
|
180
|
+
# its own has a declared type, so worked-out values are untouched.
|
|
181
|
+
self.conn = sqlite3.connect(
|
|
182
|
+
database, detect_types=sqlite3.PARSE_DECLTYPES if typed else 0
|
|
183
|
+
)
|
|
132
184
|
self.conn.create_collation(NUMBER_ORDER, compare_numbers)
|
|
185
|
+
self.conn.create_function("datapy_is_number", 1, is_number, deterministic=True)
|
|
133
186
|
self.conn.execute("pragma journal_mode = off")
|
|
134
187
|
self.conn.execute("pragma synchronous = off")
|
|
135
188
|
# An empty field is null in every column. A number is converted by
|
|
136
189
|
# SQLite itself, and a numeric field of only spaces is empty too.
|
|
137
190
|
definitions, values, copies = [], [], []
|
|
191
|
+
#: SQL that empties the values of a number column that are not numbers.
|
|
192
|
+
self._not_numbers = {}
|
|
193
|
+
self.unfit = {}
|
|
194
|
+
as_written = {} # the declared type of each numeric column's text form
|
|
138
195
|
for index, (name, kind) in enumerate(zip(source.columns, source.types)):
|
|
139
|
-
stored =
|
|
140
|
-
|
|
196
|
+
stored = "text" if kind == "TEXT" else layout.get(name, "text")
|
|
197
|
+
column = quote(name)
|
|
198
|
+
if kind != "TEXT":
|
|
199
|
+
as_written[name] = (
|
|
200
|
+
"TEXT" if not typed else _AS_DECIMAL if kind == "REAL" else _AS_INT
|
|
201
|
+
)
|
|
202
|
+
if stored == "text":
|
|
203
|
+
definitions.append(f"{column} {as_written.get(name, 'TEXT')}")
|
|
204
|
+
values.append("nullif(?, '')")
|
|
205
|
+
elif kind == BIG:
|
|
141
206
|
# Too large for SQLite to hold as a number without rounding:
|
|
142
207
|
# kept as text and compared, exactly, by `compare_numbers`.
|
|
143
|
-
definitions.append(f"{
|
|
208
|
+
definitions.append(f"{column} TEXT COLLATE {NUMBER_ORDER}")
|
|
144
209
|
values.append("nullif(trim(?), '')")
|
|
145
|
-
|
|
146
|
-
definitions.append(f"{quote(name)} TEXT")
|
|
147
|
-
values.append("nullif(?, '')")
|
|
210
|
+
self._not_numbers[name] = f"not datapy_is_number({column})"
|
|
148
211
|
else:
|
|
149
|
-
|
|
212
|
+
# SQLite stores a value it cannot read as a number as text.
|
|
213
|
+
definitions.append(f"{column} {kind}")
|
|
150
214
|
values.append("nullif(trim(?), '')")
|
|
215
|
+
self._not_numbers[name] = f"typeof({column}) = 'text'"
|
|
151
216
|
if stored == "both":
|
|
152
217
|
copies.append((index, name))
|
|
153
218
|
for index, name in copies:
|
|
154
|
-
|
|
219
|
+
copy = quote(text_column(name, source.columns))
|
|
220
|
+
definitions.append(f"{copy} {as_written[name]}")
|
|
155
221
|
values.append("nullif(?, '')")
|
|
156
222
|
self._copied = [index for index, _ in copies]
|
|
157
223
|
self.conn.execute(f"create table {self.name} ({', '.join(definitions)})")
|
|
@@ -181,6 +247,12 @@ class _Table:
|
|
|
181
247
|
copied = self._copied
|
|
182
248
|
rows = (row + [row[index] for index in copied] for row in rows)
|
|
183
249
|
self.conn.executemany(self._insert, rows)
|
|
250
|
+
for name, condition in self._not_numbers.items():
|
|
251
|
+
emptied = self.conn.execute(
|
|
252
|
+
f"update {self.name} set {quote(name)} = null where {condition}"
|
|
253
|
+
).rowcount
|
|
254
|
+
if emptied:
|
|
255
|
+
self.unfit[name] = self.unfit.get(name, 0) + emptied
|
|
184
256
|
self.conn.commit()
|
|
185
257
|
finally:
|
|
186
258
|
self._locked = True
|
|
@@ -222,6 +294,29 @@ def _fetch(cursor: sqlite3.Cursor):
|
|
|
222
294
|
raise DatapyError(_explain(error)) from error
|
|
223
295
|
|
|
224
296
|
|
|
297
|
+
def _open_source(
|
|
298
|
+
path: str, *, header, delimiter, text, skip_bad_rows, schema
|
|
299
|
+
) -> Source:
|
|
300
|
+
"""Open a file, with options given here taking precedence over a schema's."""
|
|
301
|
+
schema = as_schema(schema)
|
|
302
|
+
if header is None:
|
|
303
|
+
header = schema.header if schema else True
|
|
304
|
+
if delimiter is None:
|
|
305
|
+
delimiter = schema.delimiter if schema else ","
|
|
306
|
+
return Source(
|
|
307
|
+
path,
|
|
308
|
+
header=header,
|
|
309
|
+
delimiter=delimiter,
|
|
310
|
+
text=text,
|
|
311
|
+
skip_bad_rows=skip_bad_rows,
|
|
312
|
+
declared=schema.columns if schema else None,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _typed(typed: bool | None, schema) -> bool:
|
|
317
|
+
return schema is not None if typed is None else typed
|
|
318
|
+
|
|
319
|
+
|
|
225
320
|
class DataFile:
|
|
226
321
|
"""A delimited text file opened for querying.
|
|
227
322
|
|
|
@@ -234,22 +329,37 @@ class DataFile:
|
|
|
234
329
|
- `header`: when true (the default) the first line holds the column
|
|
235
330
|
names. When false the first line is data and columns are only available
|
|
236
331
|
by position, as `$1`, `$2`...
|
|
237
|
-
- `delimiter`: the single character that separates fields
|
|
332
|
+
- `delimiter`: the single character that separates fields; `","` by
|
|
333
|
+
default.
|
|
238
334
|
- `text`: columns to compare as text even if their values look like numbers,
|
|
239
335
|
given by name or position: `text=["zip", "$4"]`.
|
|
240
336
|
- `skip_bad_rows`: a row must have exactly one field per column. By
|
|
241
337
|
default any other row raises `DatapyError`; when this is true such rows
|
|
242
338
|
are left out and counted in `skipped`.
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
339
|
+
- `schema`: a `Schema`, a dict shaped like one, or the file name of a
|
|
340
|
+
saved one. The file is read with its column types instead of guessing
|
|
341
|
+
them, and with its delimiter and header unless `delimiter` or `header`
|
|
342
|
+
is given. The file's columns must be the schema's, in any order.
|
|
343
|
+
- `typed`: return a numeric column selected on its own as a Python
|
|
344
|
+
number: `int` for whole numbers, `decimal.Decimal` for decimals, which
|
|
345
|
+
keeps the written form (`Decimal("10.50")`). A value that is not a
|
|
346
|
+
number comes back as `None`. On by default with a schema; without one,
|
|
347
|
+
the types are guessed from the first 1,000 rows. Values worked out by
|
|
348
|
+
the statement, such as `sum(amount)`, are as SQLite computes them.
|
|
349
|
+
|
|
350
|
+
Without a schema, a column is compared as a number when every value in
|
|
351
|
+
the first 1,000 rows is one. Use `text` for a column that only looks
|
|
352
|
+
numeric at the start. Either way, its values are returned as they are
|
|
353
|
+
written in the file.
|
|
247
354
|
|
|
248
355
|
Attributes:
|
|
249
356
|
|
|
250
357
|
- `path`: the path the file was opened with.
|
|
251
358
|
- `columns`: the column names, in order.
|
|
252
359
|
- `skipped`: how many rows were left out by `skip_bad_rows`.
|
|
360
|
+
- `unfit`: values in a numeric column that are not numbers, counted by
|
|
361
|
+
column. They are treated as empty when comparing, sorting and
|
|
362
|
+
calculating, but still returned as written.
|
|
253
363
|
- `closed`: true once the file has been closed.
|
|
254
364
|
"""
|
|
255
365
|
|
|
@@ -257,27 +367,34 @@ class DataFile:
|
|
|
257
367
|
self,
|
|
258
368
|
path,
|
|
259
369
|
*,
|
|
260
|
-
header: bool =
|
|
261
|
-
delimiter: str =
|
|
370
|
+
header: bool | None = None,
|
|
371
|
+
delimiter: str | None = None,
|
|
262
372
|
text=(),
|
|
263
373
|
skip_bad_rows: bool = False,
|
|
374
|
+
schema=None,
|
|
375
|
+
typed: bool | None = None,
|
|
264
376
|
):
|
|
265
|
-
source =
|
|
377
|
+
source = _open_source(
|
|
266
378
|
os.fspath(path),
|
|
267
379
|
header=header,
|
|
268
380
|
delimiter=delimiter,
|
|
269
381
|
text=text,
|
|
270
382
|
skip_bad_rows=skip_bad_rows,
|
|
383
|
+
schema=schema,
|
|
271
384
|
)
|
|
272
|
-
self._load(source)
|
|
385
|
+
self._load(source, typed=_typed(typed, schema))
|
|
273
386
|
|
|
274
387
|
@classmethod
|
|
275
|
-
def _from_source(
|
|
388
|
+
def _from_source(
|
|
389
|
+
cls, source: Source, layout: dict[str, str], typed: bool
|
|
390
|
+
) -> DataFile:
|
|
276
391
|
data = cls.__new__(cls)
|
|
277
|
-
data._load(source, layout)
|
|
392
|
+
data._load(source, layout, typed)
|
|
278
393
|
return data
|
|
279
394
|
|
|
280
|
-
def _load(
|
|
395
|
+
def _load(
|
|
396
|
+
self, source: Source, layout: dict[str, str] | None = None, typed=False
|
|
397
|
+
) -> None:
|
|
281
398
|
self.path = source.path
|
|
282
399
|
self.columns = source.columns
|
|
283
400
|
self._source = source
|
|
@@ -286,10 +403,12 @@ class DataFile:
|
|
|
286
403
|
# both as a number and as it is in the file.
|
|
287
404
|
self._layout = layout or {name: "both" for name in self._numeric}
|
|
288
405
|
self._table = None
|
|
406
|
+
self._unfit = {}
|
|
289
407
|
try:
|
|
290
408
|
# An empty name is a private database in a temporary file: SQLite
|
|
291
409
|
# keeps a small cache in memory and spills the rest to disk.
|
|
292
|
-
self._table = _Table("", source, self._layout)
|
|
410
|
+
self._table = _Table("", source, self._layout, typed)
|
|
411
|
+
self._unfit = self._table.unfit
|
|
293
412
|
self._table.fill(source.rows())
|
|
294
413
|
except BaseException:
|
|
295
414
|
self.close()
|
|
@@ -310,6 +429,10 @@ class DataFile:
|
|
|
310
429
|
def skipped(self) -> int:
|
|
311
430
|
return self._source.skipped
|
|
312
431
|
|
|
432
|
+
@property
|
|
433
|
+
def unfit(self) -> dict[str, int]:
|
|
434
|
+
return dict(self._unfit)
|
|
435
|
+
|
|
313
436
|
@property
|
|
314
437
|
def closed(self) -> bool:
|
|
315
438
|
return self._table is None
|
|
@@ -336,7 +459,7 @@ class DataFile:
|
|
|
336
459
|
use `stream()`.
|
|
337
460
|
"""
|
|
338
461
|
rows = self.stream(statement)
|
|
339
|
-
return Result(rows.columns, list(rows))
|
|
462
|
+
return Result(rows.columns, list(rows), rows.unfit)
|
|
340
463
|
|
|
341
464
|
def stream(self, statement: str) -> Stream:
|
|
342
465
|
"""Run a select statement and return a `Stream` of its rows.
|
|
@@ -360,7 +483,12 @@ class DataFile:
|
|
|
360
483
|
def _run(self, sql: str, close=None) -> Stream:
|
|
361
484
|
cursor = self._table.execute(sql)
|
|
362
485
|
return Stream(
|
|
363
|
-
_names(cursor),
|
|
486
|
+
_names(cursor),
|
|
487
|
+
_fetch(cursor),
|
|
488
|
+
close,
|
|
489
|
+
self._source,
|
|
490
|
+
self._table,
|
|
491
|
+
streamed=False,
|
|
364
492
|
)
|
|
365
493
|
|
|
366
494
|
def _is_named(self, name: str) -> bool:
|
|
@@ -406,10 +534,12 @@ def _batches(table: _Table, source: Source, sql: str, limit):
|
|
|
406
534
|
def stream(
|
|
407
535
|
statement: str,
|
|
408
536
|
*,
|
|
409
|
-
header: bool =
|
|
410
|
-
delimiter: str =
|
|
537
|
+
header: bool | None = None,
|
|
538
|
+
delimiter: str | None = None,
|
|
411
539
|
text=(),
|
|
412
540
|
skip_bad_rows: bool = False,
|
|
541
|
+
schema=None,
|
|
542
|
+
typed: bool | None = None,
|
|
413
543
|
) -> Stream:
|
|
414
544
|
"""Run one select statement and return a `Stream` of its rows.
|
|
415
545
|
|
|
@@ -420,8 +550,8 @@ def stream(
|
|
|
420
550
|
row first (`order by`, `group by`, `count(*)`, a subquery...) is loaded
|
|
421
551
|
into a temporary database on disk and then streamed from there.
|
|
422
552
|
|
|
423
|
-
`header`, `delimiter`, `text` and `
|
|
424
|
-
`datapy.open()`.
|
|
553
|
+
`header`, `delimiter`, `text`, `skip_bad_rows`, `schema` and `typed` mean
|
|
554
|
+
the same as for `datapy.open()`.
|
|
425
555
|
"""
|
|
426
556
|
statement = clean(statement)
|
|
427
557
|
files = find_files(statement)
|
|
@@ -429,21 +559,28 @@ def stream(
|
|
|
429
559
|
raise DatapyError(
|
|
430
560
|
"only one file can be queried at a time, found: " + ", ".join(sorted(files))
|
|
431
561
|
)
|
|
432
|
-
source =
|
|
562
|
+
source = _open_source(
|
|
433
563
|
files.pop(),
|
|
434
564
|
header=header,
|
|
435
565
|
delimiter=delimiter,
|
|
436
566
|
text=text,
|
|
437
567
|
skip_bad_rows=skip_bad_rows,
|
|
568
|
+
schema=schema,
|
|
438
569
|
)
|
|
439
570
|
table = None
|
|
571
|
+
typed = _typed(typed, schema)
|
|
440
572
|
try:
|
|
441
|
-
|
|
573
|
+
# Typed values are converted from the text form, so a typed statement
|
|
574
|
+
# keeps both forms of every numeric column.
|
|
575
|
+
both = {name: "both" for name in source.numeric} if typed else None
|
|
576
|
+
sql, layout = rewrite(
|
|
577
|
+
statement, source.path, source.columns, source.numeric, both
|
|
578
|
+
)
|
|
442
579
|
split = split_row_wise(sql)
|
|
443
580
|
if split is not None:
|
|
444
581
|
# Compiling against the empty table reports syntax errors before
|
|
445
582
|
# any data is read, and tells us what the statement uses.
|
|
446
|
-
table = _Table(":memory:", source, layout)
|
|
583
|
+
table = _Table(":memory:", source, layout, typed)
|
|
447
584
|
row_sql, limit = split
|
|
448
585
|
cursor = table.execute(row_sql)
|
|
449
586
|
cursor.fetchall()
|
|
@@ -454,10 +591,10 @@ def stream(
|
|
|
454
591
|
source.close()
|
|
455
592
|
|
|
456
593
|
rows = _batches(table, source, row_sql, limit)
|
|
457
|
-
return Stream(_names(cursor), rows, close, source, streamed=True)
|
|
594
|
+
return Stream(_names(cursor), rows, close, source, table, streamed=True)
|
|
458
595
|
table.close()
|
|
459
596
|
table = None
|
|
460
|
-
data = DataFile._from_source(source, layout)
|
|
597
|
+
data = DataFile._from_source(source, layout, typed)
|
|
461
598
|
try:
|
|
462
599
|
return data._run(sql, data.close)
|
|
463
600
|
except BaseException:
|
|
@@ -473,17 +610,19 @@ def stream(
|
|
|
473
610
|
def query(
|
|
474
611
|
statement: str,
|
|
475
612
|
*,
|
|
476
|
-
header: bool =
|
|
477
|
-
delimiter: str =
|
|
613
|
+
header: bool | None = None,
|
|
614
|
+
delimiter: str | None = None,
|
|
478
615
|
text=(),
|
|
479
616
|
skip_bad_rows: bool = False,
|
|
617
|
+
schema=None,
|
|
618
|
+
typed: bool | None = None,
|
|
480
619
|
) -> Result:
|
|
481
620
|
"""Run one select statement against the file named in its `from` clause.
|
|
482
621
|
|
|
483
622
|
A shortcut for opening the file, running a single query and closing it.
|
|
484
623
|
The whole result is held in memory; use `datapy.stream()` for large
|
|
485
|
-
results. `header`, `delimiter`, `text
|
|
486
|
-
as for `datapy.open()`.
|
|
624
|
+
results. `header`, `delimiter`, `text`, `skip_bad_rows`, `schema` and
|
|
625
|
+
`typed` mean the same as for `datapy.open()`.
|
|
487
626
|
"""
|
|
488
627
|
with stream(
|
|
489
628
|
statement,
|
|
@@ -491,5 +630,7 @@ def query(
|
|
|
491
630
|
delimiter=delimiter,
|
|
492
631
|
text=text,
|
|
493
632
|
skip_bad_rows=skip_bad_rows,
|
|
633
|
+
schema=schema,
|
|
634
|
+
typed=typed,
|
|
494
635
|
) as rows:
|
|
495
|
-
return Result(rows.columns, list(rows))
|
|
636
|
+
return Result(rows.columns, list(rows), rows.unfit)
|