datapy 0.2.0__py3-none-any.whl
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/__init__.py +46 -0
- datapy/__main__.py +3 -0
- datapy/_datafile.py +392 -0
- datapy/_errors.py +9 -0
- datapy/_reader.py +160 -0
- datapy/_statement.py +105 -0
- datapy/cli.py +297 -0
- datapy-0.2.0.dist-info/METADATA +198 -0
- datapy-0.2.0.dist-info/RECORD +13 -0
- datapy-0.2.0.dist-info/WHEEL +5 -0
- datapy-0.2.0.dist-info/entry_points.txt +2 -0
- datapy-0.2.0.dist-info/licenses/LICENSE.txt +201 -0
- datapy-0.2.0.dist-info/top_level.txt +1 -0
datapy/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Query delimited text files with SQL.
|
|
3
|
+
|
|
4
|
+
This package is the entry point for Python code. Everything a script needs is
|
|
5
|
+
importable from here; modules whose names start with an underscore are
|
|
6
|
+
internal and may change without notice.
|
|
7
|
+
|
|
8
|
+
import datapy
|
|
9
|
+
|
|
10
|
+
with datapy.open("people.csv") as people:
|
|
11
|
+
people.query("select name from people.csv where age > 40")
|
|
12
|
+
|
|
13
|
+
The command line entry point is `datapy.cli`, which uses only the names
|
|
14
|
+
exported here.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__version__ = "0.2.0"
|
|
18
|
+
|
|
19
|
+
from datapy._datafile import DataFile, Result, Stream, query, stream
|
|
20
|
+
from datapy._errors import DatapyError
|
|
21
|
+
|
|
22
|
+
# Tracebacks and reprs show the public name, not the internal module.
|
|
23
|
+
for _public in (DataFile, DatapyError, Result, Stream):
|
|
24
|
+
_public.__module__ = __name__
|
|
25
|
+
del _public
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def open(path, *, header: bool = True, delimiter: str = ",", text=()) -> DataFile:
|
|
29
|
+
"""Open a file for querying. Use it in a `with` block.
|
|
30
|
+
|
|
31
|
+
Returns a `DataFile`; see that class for what `header`, `delimiter` and
|
|
32
|
+
`text` mean.
|
|
33
|
+
"""
|
|
34
|
+
return DataFile(path, header=header, delimiter=delimiter, text=text)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# "open" is left out so that `from datapy import *` does not shadow the builtin.
|
|
38
|
+
__all__ = [
|
|
39
|
+
"DataFile",
|
|
40
|
+
"DatapyError",
|
|
41
|
+
"Result",
|
|
42
|
+
"Stream",
|
|
43
|
+
"query",
|
|
44
|
+
"stream",
|
|
45
|
+
"__version__",
|
|
46
|
+
]
|
datapy/__main__.py
ADDED
datapy/_datafile.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Run statements against a file, a batch at a time or from a temporary database."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import os
|
|
7
|
+
import sqlite3
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
from datapy._errors import DatapyError
|
|
11
|
+
from datapy._reader import Source
|
|
12
|
+
from datapy._statement import (
|
|
13
|
+
ROW_FUNCTIONS,
|
|
14
|
+
clean,
|
|
15
|
+
find_files,
|
|
16
|
+
quote,
|
|
17
|
+
rewrite,
|
|
18
|
+
split_row_wise,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
#: Rows held in memory at once when a statement is run a batch at a time.
|
|
22
|
+
BATCH_ROWS = 10_000
|
|
23
|
+
FIRST_BATCH_ROWS = 100
|
|
24
|
+
|
|
25
|
+
_READ_ONLY_ACTIONS = {
|
|
26
|
+
sqlite3.SQLITE_SELECT,
|
|
27
|
+
sqlite3.SQLITE_READ,
|
|
28
|
+
sqlite3.SQLITE_FUNCTION,
|
|
29
|
+
getattr(sqlite3, "SQLITE_RECURSIVE", 33),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Result:
|
|
35
|
+
"""The rows returned by a query, all held in memory.
|
|
36
|
+
|
|
37
|
+
Iterate over it to get the rows, or use `len()` for the row count. Each
|
|
38
|
+
row can be indexed by position (`row[0]`) or by column name
|
|
39
|
+
(`row["name"]`).
|
|
40
|
+
|
|
41
|
+
- `columns`: the column names, in order.
|
|
42
|
+
- `rows`: the rows, as a list.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
columns: list[str]
|
|
46
|
+
rows: list[sqlite3.Row]
|
|
47
|
+
|
|
48
|
+
def __iter__(self):
|
|
49
|
+
return iter(self.rows)
|
|
50
|
+
|
|
51
|
+
def __len__(self):
|
|
52
|
+
return len(self.rows)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Stream:
|
|
56
|
+
"""The rows of a query, produced one at a time as you iterate.
|
|
57
|
+
|
|
58
|
+
Unlike a `Result` it can be iterated only once and has no length, but it
|
|
59
|
+
never holds more than a batch of rows in memory. Use it in a `with` block,
|
|
60
|
+
or call `close()`, if you stop before the last row.
|
|
61
|
+
|
|
62
|
+
- `columns`: the column names, in order.
|
|
63
|
+
- `streamed`: true when the file is being read as you iterate; false when
|
|
64
|
+
the statement needed the whole file to be loaded first (sorting,
|
|
65
|
+
grouping, counting and the like).
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, columns: list[str], rows, close, *, streamed: bool):
|
|
69
|
+
self.columns = columns
|
|
70
|
+
self.streamed = streamed
|
|
71
|
+
self._rows = rows
|
|
72
|
+
self._close = close
|
|
73
|
+
|
|
74
|
+
def __iter__(self) -> Stream:
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def __next__(self) -> sqlite3.Row:
|
|
78
|
+
try:
|
|
79
|
+
return next(self._rows)
|
|
80
|
+
except BaseException:
|
|
81
|
+
self.close()
|
|
82
|
+
raise
|
|
83
|
+
|
|
84
|
+
def __enter__(self) -> Stream:
|
|
85
|
+
return self
|
|
86
|
+
|
|
87
|
+
def __exit__(self, *_) -> None:
|
|
88
|
+
self.close()
|
|
89
|
+
|
|
90
|
+
def close(self) -> None:
|
|
91
|
+
"""Stop reading and release the file. Closing twice is harmless."""
|
|
92
|
+
close, self._close = self._close, None
|
|
93
|
+
self._rows = iter(())
|
|
94
|
+
if close is not None:
|
|
95
|
+
close()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _Table:
|
|
99
|
+
"""A SQLite table shaped like a data file, readable but not writable by queries."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, database: str, source: Source):
|
|
102
|
+
self.name = quote(source.path)
|
|
103
|
+
self._locked = False
|
|
104
|
+
self.functions = set()
|
|
105
|
+
self.selects = 0
|
|
106
|
+
self.conn = sqlite3.connect(database)
|
|
107
|
+
self.conn.execute("pragma journal_mode = off")
|
|
108
|
+
self.conn.execute("pragma synchronous = off")
|
|
109
|
+
definitions = ", ".join(
|
|
110
|
+
f"{quote(name)} {kind}" for name, kind in zip(source.columns, source.types)
|
|
111
|
+
)
|
|
112
|
+
self.conn.execute(f"create table {self.name} ({definitions})")
|
|
113
|
+
# Numeric columns: SQLite converts the text itself; blank becomes null.
|
|
114
|
+
values = ", ".join(
|
|
115
|
+
"?" if kind == "TEXT" else "nullif(trim(?), '')" for kind in source.types
|
|
116
|
+
)
|
|
117
|
+
self._insert = f"insert into {self.name} values ({values})"
|
|
118
|
+
self.conn.commit()
|
|
119
|
+
self.conn.row_factory = sqlite3.Row
|
|
120
|
+
self.conn.set_authorizer(self._authorize)
|
|
121
|
+
self._locked = True
|
|
122
|
+
|
|
123
|
+
def _authorize(self, action, _first, second, *_):
|
|
124
|
+
if not self._locked:
|
|
125
|
+
return sqlite3.SQLITE_OK
|
|
126
|
+
if action == sqlite3.SQLITE_SELECT:
|
|
127
|
+
self.selects += 1
|
|
128
|
+
elif action == sqlite3.SQLITE_FUNCTION:
|
|
129
|
+
self.functions.add((second or "").lower())
|
|
130
|
+
return (
|
|
131
|
+
sqlite3.SQLITE_OK if action in _READ_ONLY_ACTIONS else sqlite3.SQLITE_DENY
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def fill(self, rows, *, replace: bool = False) -> None:
|
|
135
|
+
self._locked = False
|
|
136
|
+
try:
|
|
137
|
+
if replace:
|
|
138
|
+
self.conn.execute(f"delete from {self.name}")
|
|
139
|
+
self.conn.executemany(self._insert, rows)
|
|
140
|
+
self.conn.commit()
|
|
141
|
+
finally:
|
|
142
|
+
self._locked = True
|
|
143
|
+
|
|
144
|
+
def execute(self, sql: str) -> sqlite3.Cursor:
|
|
145
|
+
self.functions.clear()
|
|
146
|
+
self.selects = 0
|
|
147
|
+
try:
|
|
148
|
+
return self.conn.execute(sql)
|
|
149
|
+
except (sqlite3.Error, sqlite3.Warning) as error:
|
|
150
|
+
raise DatapyError(_explain(error)) from error
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
self.conn.close()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _explain(error: Exception) -> str:
|
|
157
|
+
message = str(error)
|
|
158
|
+
if "not authorized" in message or "prohibited" in message:
|
|
159
|
+
return "only select statements are supported"
|
|
160
|
+
if "one statement at a time" in message:
|
|
161
|
+
return "only one statement can be run at a time"
|
|
162
|
+
if message.startswith("no such table"):
|
|
163
|
+
return f"only one file can be queried at a time ({message})"
|
|
164
|
+
return message
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _names(cursor: sqlite3.Cursor) -> list[str]:
|
|
168
|
+
return [d[0] for d in cursor.description or ()]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _fetch(cursor: sqlite3.Cursor):
|
|
172
|
+
try:
|
|
173
|
+
yield from cursor
|
|
174
|
+
except (sqlite3.Error, sqlite3.Warning) as error:
|
|
175
|
+
raise DatapyError(_explain(error)) from error
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class DataFile:
|
|
179
|
+
"""A delimited text file opened for querying.
|
|
180
|
+
|
|
181
|
+
Usually created with `datapy.open()` in a `with` block. The file is read
|
|
182
|
+
once when opened, into a temporary database on disk rather than into
|
|
183
|
+
memory, so any number of queries can then be run against it, including
|
|
184
|
+
ones that sort, group or count. The file itself is never modified.
|
|
185
|
+
|
|
186
|
+
- `path`: the file to open, or `"-"` to read standard input.
|
|
187
|
+
- `header`: when true (the default) the first line holds the column
|
|
188
|
+
names. When false the first line is data and columns are only available
|
|
189
|
+
by position, as `$1`, `$2`...
|
|
190
|
+
- `delimiter`: the single character that separates fields.
|
|
191
|
+
- `text`: columns to keep as text even if their values look like numbers,
|
|
192
|
+
given by name or position: `text=["zip", "$4"]`.
|
|
193
|
+
|
|
194
|
+
A column is treated as a number when every value in the first 1,000 rows
|
|
195
|
+
is one. Use `text` for a column that only looks numeric at the start.
|
|
196
|
+
|
|
197
|
+
Attributes:
|
|
198
|
+
|
|
199
|
+
- `path`: the path the file was opened with.
|
|
200
|
+
- `columns`: the column names, in order.
|
|
201
|
+
- `closed`: true once the file has been closed.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
def __init__(self, path, *, header: bool = True, delimiter: str = ",", text=()):
|
|
205
|
+
source = Source(os.fspath(path), header=header, delimiter=delimiter, text=text)
|
|
206
|
+
self._load(source)
|
|
207
|
+
|
|
208
|
+
@classmethod
|
|
209
|
+
def _from_source(cls, source: Source) -> DataFile:
|
|
210
|
+
data = cls.__new__(cls)
|
|
211
|
+
data._load(source)
|
|
212
|
+
return data
|
|
213
|
+
|
|
214
|
+
def _load(self, source: Source) -> None:
|
|
215
|
+
self.path = source.path
|
|
216
|
+
self.columns = source.columns
|
|
217
|
+
self._table = None
|
|
218
|
+
try:
|
|
219
|
+
# An empty name is a private database in a temporary file: SQLite
|
|
220
|
+
# keeps a small cache in memory and spills the rest to disk.
|
|
221
|
+
self._table = _Table("", source)
|
|
222
|
+
self._table.fill(source.rows())
|
|
223
|
+
except BaseException:
|
|
224
|
+
self.close()
|
|
225
|
+
raise
|
|
226
|
+
finally:
|
|
227
|
+
source.close()
|
|
228
|
+
|
|
229
|
+
def __enter__(self) -> DataFile:
|
|
230
|
+
return self
|
|
231
|
+
|
|
232
|
+
def __exit__(self, *_) -> None:
|
|
233
|
+
self.close()
|
|
234
|
+
|
|
235
|
+
def __repr__(self) -> str:
|
|
236
|
+
return f"DataFile({self.path!r})"
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def closed(self) -> bool:
|
|
240
|
+
return self._table is None
|
|
241
|
+
|
|
242
|
+
def close(self) -> None:
|
|
243
|
+
"""Release the loaded data.
|
|
244
|
+
|
|
245
|
+
Called automatically at the end of a `with` block. Closing twice is
|
|
246
|
+
harmless; querying a closed file raises `DatapyError`.
|
|
247
|
+
"""
|
|
248
|
+
if self._table is not None:
|
|
249
|
+
self._table.close()
|
|
250
|
+
self._table = None
|
|
251
|
+
|
|
252
|
+
def query(self, statement: str) -> Result:
|
|
253
|
+
"""Run a select statement against this file and return a `Result`.
|
|
254
|
+
|
|
255
|
+
Columns can be referenced by header name or by position (`$1` is the
|
|
256
|
+
first column). The `from` clause may name the file by the path it was
|
|
257
|
+
opened with, by its file name (`people.csv`) or by its name without
|
|
258
|
+
the extension (`people`).
|
|
259
|
+
|
|
260
|
+
The whole result is held in memory. For a result too large for that,
|
|
261
|
+
use `stream()`.
|
|
262
|
+
"""
|
|
263
|
+
rows = self.stream(statement)
|
|
264
|
+
return Result(rows.columns, list(rows))
|
|
265
|
+
|
|
266
|
+
def stream(self, statement: str) -> Stream:
|
|
267
|
+
"""Run a select statement and return a `Stream` of its rows.
|
|
268
|
+
|
|
269
|
+
Takes the same statements as `query()`, but hands the rows over one
|
|
270
|
+
at a time instead of collecting them.
|
|
271
|
+
"""
|
|
272
|
+
if self.closed:
|
|
273
|
+
raise DatapyError(f"{self.path} is closed")
|
|
274
|
+
statement = clean(statement)
|
|
275
|
+
for name in find_files(statement):
|
|
276
|
+
if not self._is_named(name):
|
|
277
|
+
raise DatapyError(
|
|
278
|
+
f"the query names {name}, but the open file is {self.path}"
|
|
279
|
+
)
|
|
280
|
+
return self._run(rewrite(statement, self.path, self.columns))
|
|
281
|
+
|
|
282
|
+
def _run(self, sql: str, close=None) -> Stream:
|
|
283
|
+
cursor = self._table.execute(sql)
|
|
284
|
+
return Stream(_names(cursor), _fetch(cursor), close, streamed=False)
|
|
285
|
+
|
|
286
|
+
def _is_named(self, name: str) -> bool:
|
|
287
|
+
file_name = os.path.basename(self.path)
|
|
288
|
+
return name in (
|
|
289
|
+
self.path,
|
|
290
|
+
file_name,
|
|
291
|
+
os.path.splitext(file_name)[0],
|
|
292
|
+
) or os.path.abspath(name) == os.path.abspath(self.path)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _batches(table: _Table, source: Source, sql: str, limit):
|
|
296
|
+
"""Run a row-by-row statement over the file one batch of rows at a time.
|
|
297
|
+
|
|
298
|
+
Batches start small, so the first rows come out quickly and a small
|
|
299
|
+
`limit` reads very little, then grow to `BATCH_ROWS`.
|
|
300
|
+
"""
|
|
301
|
+
rows = source.rows()
|
|
302
|
+
remaining = limit
|
|
303
|
+
size = min(FIRST_BATCH_ROWS, BATCH_ROWS)
|
|
304
|
+
while remaining is None or remaining > 0:
|
|
305
|
+
batch, failure = [], None
|
|
306
|
+
try:
|
|
307
|
+
for row in itertools.islice(rows, size):
|
|
308
|
+
batch.append(row)
|
|
309
|
+
except DatapyError as error:
|
|
310
|
+
failure = error # report it only after the rows before it
|
|
311
|
+
if batch:
|
|
312
|
+
table.fill(batch, replace=True)
|
|
313
|
+
for row in _fetch(table.execute(sql)):
|
|
314
|
+
yield row
|
|
315
|
+
if remaining is not None:
|
|
316
|
+
remaining -= 1
|
|
317
|
+
if remaining == 0:
|
|
318
|
+
return
|
|
319
|
+
if failure is not None:
|
|
320
|
+
raise failure
|
|
321
|
+
if len(batch) < size:
|
|
322
|
+
return
|
|
323
|
+
size = min(size * 10, BATCH_ROWS)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def stream(
|
|
327
|
+
statement: str, *, header: bool = True, delimiter: str = ",", text=()
|
|
328
|
+
) -> Stream:
|
|
329
|
+
"""Run one select statement and return a `Stream` of its rows.
|
|
330
|
+
|
|
331
|
+
The file named in the `from` clause is read as you iterate, so a statement
|
|
332
|
+
that only picks columns and filters rows (`select`, `where`, `limit`)
|
|
333
|
+
runs in a small, fixed amount of memory however large the file is, and
|
|
334
|
+
stops reading as soon as you stop iterating. A statement that needs every
|
|
335
|
+
row first (`order by`, `group by`, `count(*)`, a subquery...) is loaded
|
|
336
|
+
into a temporary database on disk and then streamed from there.
|
|
337
|
+
|
|
338
|
+
`header`, `delimiter` and `text` mean the same as for `datapy.open()`.
|
|
339
|
+
"""
|
|
340
|
+
statement = clean(statement)
|
|
341
|
+
files = find_files(statement)
|
|
342
|
+
if len(files) > 1:
|
|
343
|
+
raise DatapyError(
|
|
344
|
+
"only one file can be queried at a time, found: " + ", ".join(sorted(files))
|
|
345
|
+
)
|
|
346
|
+
source = Source(files.pop(), header=header, delimiter=delimiter, text=text)
|
|
347
|
+
table = None
|
|
348
|
+
try:
|
|
349
|
+
sql = rewrite(statement, source.path, source.columns)
|
|
350
|
+
split = split_row_wise(sql)
|
|
351
|
+
if split is not None:
|
|
352
|
+
# Compiling against the empty table reports syntax errors before
|
|
353
|
+
# any data is read, and tells us what the statement uses.
|
|
354
|
+
table = _Table(":memory:", source)
|
|
355
|
+
row_sql, limit = split
|
|
356
|
+
cursor = table.execute(row_sql)
|
|
357
|
+
cursor.fetchall()
|
|
358
|
+
if table.selects == 1 and table.functions <= ROW_FUNCTIONS:
|
|
359
|
+
|
|
360
|
+
def close(table=table):
|
|
361
|
+
table.close()
|
|
362
|
+
source.close()
|
|
363
|
+
|
|
364
|
+
rows = _batches(table, source, row_sql, limit)
|
|
365
|
+
return Stream(_names(cursor), rows, close, streamed=True)
|
|
366
|
+
table.close()
|
|
367
|
+
table = None
|
|
368
|
+
data = DataFile._from_source(source)
|
|
369
|
+
try:
|
|
370
|
+
return data._run(sql, data.close)
|
|
371
|
+
except BaseException:
|
|
372
|
+
data.close()
|
|
373
|
+
raise
|
|
374
|
+
except BaseException:
|
|
375
|
+
if table is not None:
|
|
376
|
+
table.close()
|
|
377
|
+
source.close()
|
|
378
|
+
raise
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def query(
|
|
382
|
+
statement: str, *, header: bool = True, delimiter: str = ",", text=()
|
|
383
|
+
) -> Result:
|
|
384
|
+
"""Run one select statement against the file named in its `from` clause.
|
|
385
|
+
|
|
386
|
+
A shortcut for opening the file, running a single query and closing it.
|
|
387
|
+
The whole result is held in memory; use `datapy.stream()` for large
|
|
388
|
+
results. `header`, `delimiter` and `text` mean the same as for
|
|
389
|
+
`datapy.open()`.
|
|
390
|
+
"""
|
|
391
|
+
with stream(statement, header=header, delimiter=delimiter, text=text) as rows:
|
|
392
|
+
return Result(rows.columns, list(rows))
|
datapy/_errors.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""The one exception type datapy raises."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class DatapyError(Exception):
|
|
5
|
+
"""Raised for any problem with a statement or the file it queries.
|
|
6
|
+
|
|
7
|
+
Catch this one type to handle a missing or malformed file, an invalid
|
|
8
|
+
statement, or a statement that is not a `select`.
|
|
9
|
+
"""
|
datapy/_reader.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Read a delimited text file lazily and work out the type of each column."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import itertools
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from datapy._errors import DatapyError
|
|
11
|
+
|
|
12
|
+
_INTEGER = re.compile(r"[+-]?(?:0|[1-9]\d*)")
|
|
13
|
+
_REAL = re.compile(r"[+-]?(?:(?:0|[1-9]\d*)(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?")
|
|
14
|
+
_INT64_LIMIT = 2**63
|
|
15
|
+
|
|
16
|
+
#: The file name that means "read standard input", as in most Unix tools.
|
|
17
|
+
STDIN = "-"
|
|
18
|
+
|
|
19
|
+
#: Column types are decided from this many rows at the start of the file, so
|
|
20
|
+
#: that the rest of it never has to be held in memory.
|
|
21
|
+
SAMPLE_ROWS = 1000
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def column_type(values: list) -> str:
|
|
25
|
+
"""Pick a SQLite type for a column from a sample of its values.
|
|
26
|
+
|
|
27
|
+
A column is numeric only if every non-empty sampled value is; values such
|
|
28
|
+
as ``00123`` keep their leading zeros by making the column text.
|
|
29
|
+
"""
|
|
30
|
+
present = [value.strip() for value in values if value and value.strip()]
|
|
31
|
+
if present and all(_INTEGER.fullmatch(value) for value in present):
|
|
32
|
+
if all(-_INT64_LIMIT <= int(value) < _INT64_LIMIT for value in present):
|
|
33
|
+
return "INTEGER"
|
|
34
|
+
if present and all(_REAL.fullmatch(value) for value in present):
|
|
35
|
+
return "REAL"
|
|
36
|
+
return "TEXT"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Source:
|
|
40
|
+
"""An open data file: its column names, column types and a stream of rows.
|
|
41
|
+
|
|
42
|
+
Only the header and the first `SAMPLE_ROWS` rows are read up front. The
|
|
43
|
+
rest is read as `rows()` is consumed, which can happen once.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, path: str, *, header: bool, delimiter: str, text=()):
|
|
47
|
+
if len(delimiter) != 1:
|
|
48
|
+
raise DatapyError(
|
|
49
|
+
f"delimiter must be a single character, got {delimiter!r}"
|
|
50
|
+
)
|
|
51
|
+
self.path = path
|
|
52
|
+
self.label = "standard input" if path == STDIN else path
|
|
53
|
+
self._handle = None
|
|
54
|
+
try:
|
|
55
|
+
if path == STDIN:
|
|
56
|
+
handle = sys.stdin
|
|
57
|
+
else:
|
|
58
|
+
handle = self._handle = open(path, newline="", encoding="utf-8-sig")
|
|
59
|
+
except OSError as error:
|
|
60
|
+
raise DatapyError(self._cannot("read", error)) from error
|
|
61
|
+
self._reader = csv.reader(handle, delimiter=delimiter, skipinitialspace=True)
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
first = next(self._lines(), None)
|
|
65
|
+
if first is None:
|
|
66
|
+
raise DatapyError(f"{self.label} is empty")
|
|
67
|
+
if header:
|
|
68
|
+
self.columns = [
|
|
69
|
+
name.strip() or f"${i}" for i, name in enumerate(first, start=1)
|
|
70
|
+
]
|
|
71
|
+
leading = []
|
|
72
|
+
else:
|
|
73
|
+
self.columns = [f"${i}" for i in range(1, len(first) + 1)]
|
|
74
|
+
leading = [self._fit(first)]
|
|
75
|
+
self._check_names()
|
|
76
|
+
self._rest = self._fitted()
|
|
77
|
+
self._sample = leading + list(
|
|
78
|
+
itertools.islice(self._rest, SAMPLE_ROWS - len(leading))
|
|
79
|
+
)
|
|
80
|
+
forced = self._positions(text)
|
|
81
|
+
self.types = [
|
|
82
|
+
(
|
|
83
|
+
"TEXT"
|
|
84
|
+
if i in forced
|
|
85
|
+
else column_type([row[i] for row in self._sample])
|
|
86
|
+
)
|
|
87
|
+
for i in range(len(self.columns))
|
|
88
|
+
]
|
|
89
|
+
except BaseException:
|
|
90
|
+
self.close()
|
|
91
|
+
raise
|
|
92
|
+
|
|
93
|
+
def rows(self):
|
|
94
|
+
"""Every row in the file, each padded to the full width. Single use."""
|
|
95
|
+
sample, self._sample = self._sample, []
|
|
96
|
+
return itertools.chain(sample, self._rest)
|
|
97
|
+
|
|
98
|
+
def close(self) -> None:
|
|
99
|
+
if self._handle is not None:
|
|
100
|
+
self._handle.close()
|
|
101
|
+
self._handle = None
|
|
102
|
+
|
|
103
|
+
def _cannot(self, verb: str, error: Exception) -> str:
|
|
104
|
+
return (
|
|
105
|
+
f"cannot {verb} {self.label}: {getattr(error, 'strerror', None) or error}"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def _lines(self):
|
|
109
|
+
"""Non-blank lines, with read and parse failures turned into DatapyError."""
|
|
110
|
+
while True:
|
|
111
|
+
try:
|
|
112
|
+
row = next(self._reader)
|
|
113
|
+
except StopIteration:
|
|
114
|
+
return
|
|
115
|
+
except OSError as error:
|
|
116
|
+
raise DatapyError(self._cannot("read", error)) from error
|
|
117
|
+
except (csv.Error, UnicodeDecodeError) as error:
|
|
118
|
+
raise DatapyError(self._cannot("parse", error)) from error
|
|
119
|
+
if row:
|
|
120
|
+
yield row
|
|
121
|
+
|
|
122
|
+
def _fit(self, row: list) -> list:
|
|
123
|
+
width = len(self.columns)
|
|
124
|
+
if len(row) > width:
|
|
125
|
+
raise DatapyError(
|
|
126
|
+
f"{self.label}: line {self._reader.line_num} has {len(row)} fields, "
|
|
127
|
+
f"expected {width}"
|
|
128
|
+
)
|
|
129
|
+
if len(row) < width:
|
|
130
|
+
row.extend([None] * (width - len(row)))
|
|
131
|
+
return row
|
|
132
|
+
|
|
133
|
+
def _fitted(self):
|
|
134
|
+
for row in self._lines():
|
|
135
|
+
yield self._fit(row)
|
|
136
|
+
|
|
137
|
+
def _check_names(self) -> None:
|
|
138
|
+
seen = set()
|
|
139
|
+
for name in self.columns:
|
|
140
|
+
if name.lower() in seen:
|
|
141
|
+
raise DatapyError(
|
|
142
|
+
f"{self.label} has more than one column named {name!r}"
|
|
143
|
+
)
|
|
144
|
+
seen.add(name.lower())
|
|
145
|
+
|
|
146
|
+
def _positions(self, names) -> set[int]:
|
|
147
|
+
"""Resolve column names or $N references to column positions."""
|
|
148
|
+
if isinstance(names, str):
|
|
149
|
+
names = [names]
|
|
150
|
+
lowered = [name.lower() for name in self.columns]
|
|
151
|
+
positions = set()
|
|
152
|
+
for name in names:
|
|
153
|
+
name = name.strip()
|
|
154
|
+
if re.fullmatch(r"\$\d+", name) and 1 <= int(name[1:]) <= len(lowered):
|
|
155
|
+
positions.add(int(name[1:]) - 1)
|
|
156
|
+
elif name.lower() in lowered:
|
|
157
|
+
positions.add(lowered.index(name.lower()))
|
|
158
|
+
else:
|
|
159
|
+
raise DatapyError(f"{self.label} has no column {name!r}")
|
|
160
|
+
return positions
|