datapy 0.2.0__tar.gz → 0.2.2__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.0/datapy.egg-info → datapy-0.2.2}/PKG-INFO +12 -4
- {datapy-0.2.0 → datapy-0.2.2}/README.md +10 -3
- {datapy-0.2.0 → datapy-0.2.2}/datapy/__init__.py +18 -5
- {datapy-0.2.0 → datapy-0.2.2}/datapy/_datafile.py +138 -35
- datapy-0.2.2/datapy/_reader.py +284 -0
- datapy-0.2.2/datapy/_statement.py +491 -0
- {datapy-0.2.0 → datapy-0.2.2}/datapy/cli.py +99 -9
- {datapy-0.2.0 → datapy-0.2.2/datapy.egg-info}/PKG-INFO +12 -4
- {datapy-0.2.0 → datapy-0.2.2}/datapy.egg-info/SOURCES.txt +3 -1
- {datapy-0.2.0 → datapy-0.2.2}/datapy.egg-info/requires.txt +1 -0
- {datapy-0.2.0 → datapy-0.2.2}/pyproject.toml +18 -1
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_ci.py +16 -0
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_cli.py +214 -0
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_datafile.py +1 -1
- datapy-0.2.2/tests/test_query.py +243 -0
- datapy-0.2.2/tests/test_statement.py +85 -0
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_stream.py +18 -5
- datapy-0.2.2/tests/test_values.py +207 -0
- datapy-0.2.0/datapy/_reader.py +0 -160
- datapy-0.2.0/datapy/_statement.py +0 -105
- datapy-0.2.0/tests/test_query.py +0 -128
- {datapy-0.2.0 → datapy-0.2.2}/LICENSE.txt +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/MANIFEST.in +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/datapy/__main__.py +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/datapy/_errors.py +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/datapy.egg-info/dependency_links.txt +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/datapy.egg-info/entry_points.txt +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/datapy.egg-info/top_level.txt +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/setup.cfg +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_docs.py +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_entry_points.py +0 -0
- {datapy-0.2.0 → datapy-0.2.2}/tests/test_style.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datapy
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
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
|
|
@@ -21,6 +21,7 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
License-File: LICENSE.txt
|
|
22
22
|
Provides-Extra: dev
|
|
23
23
|
Requires-Dist: pytest; extra == "dev"
|
|
24
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
24
25
|
Requires-Dist: build; extra == "dev"
|
|
25
26
|
Requires-Dist: black<27,>=26; extra == "dev"
|
|
26
27
|
Dynamic: license-file
|
|
@@ -29,6 +30,10 @@ Dynamic: license-file
|
|
|
29
30
|
|
|
30
31
|
An intuitive lightweight file based database and query tool.
|
|
31
32
|
|
|
33
|
+
[Documentation](https://coreydmccarty.dev/datapy/) ·
|
|
34
|
+
[PyPI](https://pypi.org/project/datapy/) ·
|
|
35
|
+
[Source](https://github.com/xanderyzwich/datapy)
|
|
36
|
+
|
|
32
37
|
- Query csv files with SQL, without setting up a database
|
|
33
38
|
- An approachable alternative to `grep` and `awk`: columns by name, flags
|
|
34
39
|
you can guess
|
|
@@ -99,6 +104,7 @@ datapy -s COLUMNS FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
|
|
|
99
104
|
| `-o`, `--order` | sort | `-o name`, `-o 'age desc'` |
|
|
100
105
|
| `-g`, `--group` | one row per distinct value | `-s 'job, count(*)' -g job` |
|
|
101
106
|
| `-l`, `--limit` | at most this many rows | `-l 10` |
|
|
107
|
+
| `-k`, `--skip-bad-rows` | leave out rows with the wrong number of fields | `-sak` |
|
|
102
108
|
|
|
103
109
|
Each flag is followed by its value, and the flags can come in any order.
|
|
104
110
|
Repeat `-w` to require several conditions.
|
|
@@ -151,7 +157,8 @@ with datapy.open("people.csv") as people:
|
|
|
151
157
|
print(people.columns) # ['name', 'age', 'job']
|
|
152
158
|
|
|
153
159
|
for row in people.query("select name, age from people.csv where age > 40"):
|
|
154
|
-
print(row["name"], row[1]) # by column name or position
|
|
160
|
+
print(row["name"], row[1]) # by column name or position;
|
|
161
|
+
# values are strings, as in the file
|
|
155
162
|
|
|
156
163
|
minors = people.query("select $1 from people where $2 < 18")
|
|
157
164
|
print(len(minors))
|
|
@@ -177,9 +184,10 @@ Problems with a file or a statement raise `datapy.DatapyError`. The
|
|
|
177
184
|
|
|
178
185
|
One `select` statement against one file. The statement is run by SQLite, so
|
|
179
186
|
`where`, `order by`, `group by`, `limit` and SQLite's built-in functions all
|
|
180
|
-
work. A column is
|
|
187
|
+
work. A column is compared as a number when every value in it is one, so
|
|
181
188
|
`age > 40` compares numbers rather than text. That is decided from the first
|
|
182
|
-
1,000 rows; `-t zip`
|
|
189
|
+
1,000 rows; `-t zip` compares a column as text. Either way, a column you
|
|
190
|
+
select comes back exactly as it is written in the file.
|
|
183
191
|
|
|
184
192
|
See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
|
|
185
193
|
|
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
An intuitive lightweight file based database and query tool.
|
|
4
4
|
|
|
5
|
+
[Documentation](https://coreydmccarty.dev/datapy/) ·
|
|
6
|
+
[PyPI](https://pypi.org/project/datapy/) ·
|
|
7
|
+
[Source](https://github.com/xanderyzwich/datapy)
|
|
8
|
+
|
|
5
9
|
- Query csv files with SQL, without setting up a database
|
|
6
10
|
- An approachable alternative to `grep` and `awk`: columns by name, flags
|
|
7
11
|
you can guess
|
|
@@ -72,6 +76,7 @@ datapy -s COLUMNS FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
|
|
|
72
76
|
| `-o`, `--order` | sort | `-o name`, `-o 'age desc'` |
|
|
73
77
|
| `-g`, `--group` | one row per distinct value | `-s 'job, count(*)' -g job` |
|
|
74
78
|
| `-l`, `--limit` | at most this many rows | `-l 10` |
|
|
79
|
+
| `-k`, `--skip-bad-rows` | leave out rows with the wrong number of fields | `-sak` |
|
|
75
80
|
|
|
76
81
|
Each flag is followed by its value, and the flags can come in any order.
|
|
77
82
|
Repeat `-w` to require several conditions.
|
|
@@ -124,7 +129,8 @@ with datapy.open("people.csv") as people:
|
|
|
124
129
|
print(people.columns) # ['name', 'age', 'job']
|
|
125
130
|
|
|
126
131
|
for row in people.query("select name, age from people.csv where age > 40"):
|
|
127
|
-
print(row["name"], row[1]) # by column name or position
|
|
132
|
+
print(row["name"], row[1]) # by column name or position;
|
|
133
|
+
# values are strings, as in the file
|
|
128
134
|
|
|
129
135
|
minors = people.query("select $1 from people where $2 < 18")
|
|
130
136
|
print(len(minors))
|
|
@@ -150,9 +156,10 @@ Problems with a file or a statement raise `datapy.DatapyError`. The
|
|
|
150
156
|
|
|
151
157
|
One `select` statement against one file. The statement is run by SQLite, so
|
|
152
158
|
`where`, `order by`, `group by`, `limit` and SQLite's built-in functions all
|
|
153
|
-
work. A column is
|
|
159
|
+
work. A column is compared as a number when every value in it is one, so
|
|
154
160
|
`age > 40` compares numbers rather than text. That is decided from the first
|
|
155
|
-
1,000 rows; `-t zip`
|
|
161
|
+
1,000 rows; `-t zip` compares a column as text. Either way, a column you
|
|
162
|
+
select comes back exactly as it is written in the file.
|
|
156
163
|
|
|
157
164
|
See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
|
|
158
165
|
|
|
@@ -14,7 +14,7 @@ The command line entry point is `datapy.cli`, which uses only the names
|
|
|
14
14
|
exported here.
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
|
-
__version__ = "0.2.
|
|
17
|
+
__version__ = "0.2.2"
|
|
18
18
|
|
|
19
19
|
from datapy._datafile import DataFile, Result, Stream, query, stream
|
|
20
20
|
from datapy._errors import DatapyError
|
|
@@ -25,13 +25,26 @@ for _public in (DataFile, DatapyError, Result, Stream):
|
|
|
25
25
|
del _public
|
|
26
26
|
|
|
27
27
|
|
|
28
|
-
def open(
|
|
28
|
+
def open(
|
|
29
|
+
path,
|
|
30
|
+
*,
|
|
31
|
+
header: bool = True,
|
|
32
|
+
delimiter: str = ",",
|
|
33
|
+
text=(),
|
|
34
|
+
skip_bad_rows: bool = False,
|
|
35
|
+
) -> DataFile:
|
|
29
36
|
"""Open a file for querying. Use it in a `with` block.
|
|
30
37
|
|
|
31
|
-
Returns a `DataFile`; see that class for what `header`, `delimiter
|
|
32
|
-
`text` mean.
|
|
38
|
+
Returns a `DataFile`; see that class for what `header`, `delimiter`,
|
|
39
|
+
`text` and `skip_bad_rows` mean.
|
|
33
40
|
"""
|
|
34
|
-
return DataFile(
|
|
41
|
+
return DataFile(
|
|
42
|
+
path,
|
|
43
|
+
header=header,
|
|
44
|
+
delimiter=delimiter,
|
|
45
|
+
text=text,
|
|
46
|
+
skip_bad_rows=skip_bad_rows,
|
|
47
|
+
)
|
|
35
48
|
|
|
36
49
|
|
|
37
50
|
# "open" is left out so that `from datapy import *` does not shadow the builtin.
|
|
@@ -8,7 +8,7 @@ import sqlite3
|
|
|
8
8
|
from dataclasses import dataclass
|
|
9
9
|
|
|
10
10
|
from datapy._errors import DatapyError
|
|
11
|
-
from datapy._reader import Source
|
|
11
|
+
from datapy._reader import BIG, NUMBER_ORDER, Source, compare_numbers
|
|
12
12
|
from datapy._statement import (
|
|
13
13
|
ROW_FUNCTIONS,
|
|
14
14
|
clean,
|
|
@@ -16,6 +16,7 @@ from datapy._statement import (
|
|
|
16
16
|
quote,
|
|
17
17
|
rewrite,
|
|
18
18
|
split_row_wise,
|
|
19
|
+
text_column,
|
|
19
20
|
)
|
|
20
21
|
|
|
21
22
|
#: Rows held in memory at once when a statement is run a batch at a time.
|
|
@@ -38,6 +39,10 @@ class Result:
|
|
|
38
39
|
row can be indexed by position (`row[0]`) or by column name
|
|
39
40
|
(`row["name"]`).
|
|
40
41
|
|
|
42
|
+
A column of the file comes back as a string, exactly as it is written
|
|
43
|
+
there, or `None` where the field is empty. A value that was worked out,
|
|
44
|
+
such as `age + 1` or `count(*)`, is a number.
|
|
45
|
+
|
|
41
46
|
- `columns`: the column names, in order.
|
|
42
47
|
- `rows`: the rows, as a list.
|
|
43
48
|
"""
|
|
@@ -63,14 +68,29 @@ class Stream:
|
|
|
63
68
|
- `streamed`: true when the file is being read as you iterate; false when
|
|
64
69
|
the statement needed the whole file to be loaded first (sorting,
|
|
65
70
|
grouping, counting and the like).
|
|
71
|
+
- `line_ending`: how lines end in the file, taken from its first line:
|
|
72
|
+
`"\\n"`, `"\\r\\n"` (Windows) or `"\\r"`. Write the rows out with
|
|
73
|
+
it to keep the file's own convention.
|
|
74
|
+
- `skipped`: with `skip_bad_rows`, how many rows have been left out so
|
|
75
|
+
far for having the wrong number of fields. Final once the last row has
|
|
76
|
+
been read.
|
|
66
77
|
"""
|
|
67
78
|
|
|
68
|
-
def __init__(self, columns: list[str], rows, close, *, streamed: bool):
|
|
79
|
+
def __init__(self, columns: list[str], rows, close, source, *, streamed: bool):
|
|
69
80
|
self.columns = columns
|
|
70
81
|
self.streamed = streamed
|
|
82
|
+
self._source = source
|
|
71
83
|
self._rows = rows
|
|
72
84
|
self._close = close
|
|
73
85
|
|
|
86
|
+
@property
|
|
87
|
+
def skipped(self) -> int:
|
|
88
|
+
return self._source.skipped
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def line_ending(self) -> str:
|
|
92
|
+
return self._source.line_ending
|
|
93
|
+
|
|
74
94
|
def __iter__(self) -> Stream:
|
|
75
95
|
return self
|
|
76
96
|
|
|
@@ -96,25 +116,46 @@ class Stream:
|
|
|
96
116
|
|
|
97
117
|
|
|
98
118
|
class _Table:
|
|
99
|
-
"""A SQLite table shaped like a data file, readable but not writable by queries.
|
|
119
|
+
"""A SQLite table shaped like a data file, readable but not writable by queries.
|
|
120
|
+
|
|
121
|
+
`layout` says how each numeric column is stored (see `rewrite`). One that
|
|
122
|
+
is both returned and compared is stored twice, so the value can be handed
|
|
123
|
+
back exactly as it is in the file.
|
|
124
|
+
"""
|
|
100
125
|
|
|
101
|
-
def __init__(self, database: str, source: Source):
|
|
126
|
+
def __init__(self, database: str, source: Source, layout: dict[str, str]):
|
|
102
127
|
self.name = quote(source.path)
|
|
103
128
|
self._locked = False
|
|
104
129
|
self.functions = set()
|
|
105
130
|
self.selects = 0
|
|
106
131
|
self.conn = sqlite3.connect(database)
|
|
132
|
+
self.conn.create_collation(NUMBER_ORDER, compare_numbers)
|
|
107
133
|
self.conn.execute("pragma journal_mode = off")
|
|
108
134
|
self.conn.execute("pragma synchronous = off")
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
135
|
+
# An empty field is null in every column. A number is converted by
|
|
136
|
+
# SQLite itself, and a numeric field of only spaces is empty too.
|
|
137
|
+
definitions, values, copies = [], [], []
|
|
138
|
+
for index, (name, kind) in enumerate(zip(source.columns, source.types)):
|
|
139
|
+
stored = layout.get(name, "text") if kind in ("INTEGER", "REAL") else "text"
|
|
140
|
+
if kind == BIG:
|
|
141
|
+
# Too large for SQLite to hold as a number without rounding:
|
|
142
|
+
# kept as text and compared, exactly, by `compare_numbers`.
|
|
143
|
+
definitions.append(f"{quote(name)} TEXT COLLATE {NUMBER_ORDER}")
|
|
144
|
+
values.append("nullif(trim(?), '')")
|
|
145
|
+
elif stored == "text":
|
|
146
|
+
definitions.append(f"{quote(name)} TEXT")
|
|
147
|
+
values.append("nullif(?, '')")
|
|
148
|
+
else:
|
|
149
|
+
definitions.append(f"{quote(name)} {kind}")
|
|
150
|
+
values.append("nullif(trim(?), '')")
|
|
151
|
+
if stored == "both":
|
|
152
|
+
copies.append((index, name))
|
|
153
|
+
for index, name in copies:
|
|
154
|
+
definitions.append(f"{quote(text_column(name, source.columns))} TEXT")
|
|
155
|
+
values.append("nullif(?, '')")
|
|
156
|
+
self._copied = [index for index, _ in copies]
|
|
157
|
+
self.conn.execute(f"create table {self.name} ({', '.join(definitions)})")
|
|
158
|
+
self._insert = f"insert into {self.name} values ({', '.join(values)})"
|
|
118
159
|
self.conn.commit()
|
|
119
160
|
self.conn.row_factory = sqlite3.Row
|
|
120
161
|
self.conn.set_authorizer(self._authorize)
|
|
@@ -136,6 +177,9 @@ class _Table:
|
|
|
136
177
|
try:
|
|
137
178
|
if replace:
|
|
138
179
|
self.conn.execute(f"delete from {self.name}")
|
|
180
|
+
if self._copied:
|
|
181
|
+
copied = self._copied
|
|
182
|
+
rows = (row + [row[index] for index in copied] for row in rows)
|
|
139
183
|
self.conn.executemany(self._insert, rows)
|
|
140
184
|
self.conn.commit()
|
|
141
185
|
finally:
|
|
@@ -155,7 +199,10 @@ class _Table:
|
|
|
155
199
|
|
|
156
200
|
def _explain(error: Exception) -> str:
|
|
157
201
|
message = str(error)
|
|
158
|
-
if
|
|
202
|
+
if any(
|
|
203
|
+
phrase in message
|
|
204
|
+
for phrase in ("not authorized", "prohibited", "authorization denied")
|
|
205
|
+
):
|
|
159
206
|
return "only select statements are supported"
|
|
160
207
|
if "one statement at a time" in message:
|
|
161
208
|
return "only one statement can be run at a time"
|
|
@@ -188,37 +235,61 @@ class DataFile:
|
|
|
188
235
|
names. When false the first line is data and columns are only available
|
|
189
236
|
by position, as `$1`, `$2`...
|
|
190
237
|
- `delimiter`: the single character that separates fields.
|
|
191
|
-
- `text`: columns to
|
|
238
|
+
- `text`: columns to compare as text even if their values look like numbers,
|
|
192
239
|
given by name or position: `text=["zip", "$4"]`.
|
|
240
|
+
- `skip_bad_rows`: a row must have exactly one field per column. By
|
|
241
|
+
default any other row raises `DatapyError`; when this is true such rows
|
|
242
|
+
are left out and counted in `skipped`.
|
|
193
243
|
|
|
194
|
-
A column is
|
|
244
|
+
A column is compared as a number when every value in the first 1,000 rows
|
|
195
245
|
is one. Use `text` for a column that only looks numeric at the start.
|
|
246
|
+
Either way, its values are returned as they are written in the file.
|
|
196
247
|
|
|
197
248
|
Attributes:
|
|
198
249
|
|
|
199
250
|
- `path`: the path the file was opened with.
|
|
200
251
|
- `columns`: the column names, in order.
|
|
252
|
+
- `skipped`: how many rows were left out by `skip_bad_rows`.
|
|
201
253
|
- `closed`: true once the file has been closed.
|
|
202
254
|
"""
|
|
203
255
|
|
|
204
|
-
def __init__(
|
|
205
|
-
|
|
256
|
+
def __init__(
|
|
257
|
+
self,
|
|
258
|
+
path,
|
|
259
|
+
*,
|
|
260
|
+
header: bool = True,
|
|
261
|
+
delimiter: str = ",",
|
|
262
|
+
text=(),
|
|
263
|
+
skip_bad_rows: bool = False,
|
|
264
|
+
):
|
|
265
|
+
source = Source(
|
|
266
|
+
os.fspath(path),
|
|
267
|
+
header=header,
|
|
268
|
+
delimiter=delimiter,
|
|
269
|
+
text=text,
|
|
270
|
+
skip_bad_rows=skip_bad_rows,
|
|
271
|
+
)
|
|
206
272
|
self._load(source)
|
|
207
273
|
|
|
208
274
|
@classmethod
|
|
209
|
-
def _from_source(cls, source: Source) -> DataFile:
|
|
275
|
+
def _from_source(cls, source: Source, layout: dict[str, str]) -> DataFile:
|
|
210
276
|
data = cls.__new__(cls)
|
|
211
|
-
data._load(source)
|
|
277
|
+
data._load(source, layout)
|
|
212
278
|
return data
|
|
213
279
|
|
|
214
|
-
def _load(self, source: Source) -> None:
|
|
280
|
+
def _load(self, source: Source, layout: dict[str, str] | None = None) -> None:
|
|
215
281
|
self.path = source.path
|
|
216
282
|
self.columns = source.columns
|
|
283
|
+
self._source = source
|
|
284
|
+
self._numeric = source.numeric
|
|
285
|
+
# The statements are not known yet, so every numeric column is kept
|
|
286
|
+
# both as a number and as it is in the file.
|
|
287
|
+
self._layout = layout or {name: "both" for name in self._numeric}
|
|
217
288
|
self._table = None
|
|
218
289
|
try:
|
|
219
290
|
# An empty name is a private database in a temporary file: SQLite
|
|
220
291
|
# keeps a small cache in memory and spills the rest to disk.
|
|
221
|
-
self._table = _Table("", source)
|
|
292
|
+
self._table = _Table("", source, self._layout)
|
|
222
293
|
self._table.fill(source.rows())
|
|
223
294
|
except BaseException:
|
|
224
295
|
self.close()
|
|
@@ -235,6 +306,10 @@ class DataFile:
|
|
|
235
306
|
def __repr__(self) -> str:
|
|
236
307
|
return f"DataFile({self.path!r})"
|
|
237
308
|
|
|
309
|
+
@property
|
|
310
|
+
def skipped(self) -> int:
|
|
311
|
+
return self._source.skipped
|
|
312
|
+
|
|
238
313
|
@property
|
|
239
314
|
def closed(self) -> bool:
|
|
240
315
|
return self._table is None
|
|
@@ -277,11 +352,16 @@ class DataFile:
|
|
|
277
352
|
raise DatapyError(
|
|
278
353
|
f"the query names {name}, but the open file is {self.path}"
|
|
279
354
|
)
|
|
280
|
-
|
|
355
|
+
rewritten = rewrite(
|
|
356
|
+
statement, self.path, self.columns, self._numeric, self._layout
|
|
357
|
+
)
|
|
358
|
+
return self._run(rewritten.sql)
|
|
281
359
|
|
|
282
360
|
def _run(self, sql: str, close=None) -> Stream:
|
|
283
361
|
cursor = self._table.execute(sql)
|
|
284
|
-
return Stream(
|
|
362
|
+
return Stream(
|
|
363
|
+
_names(cursor), _fetch(cursor), close, self._source, streamed=False
|
|
364
|
+
)
|
|
285
365
|
|
|
286
366
|
def _is_named(self, name: str) -> bool:
|
|
287
367
|
file_name = os.path.basename(self.path)
|
|
@@ -324,7 +404,12 @@ def _batches(table: _Table, source: Source, sql: str, limit):
|
|
|
324
404
|
|
|
325
405
|
|
|
326
406
|
def stream(
|
|
327
|
-
statement: str,
|
|
407
|
+
statement: str,
|
|
408
|
+
*,
|
|
409
|
+
header: bool = True,
|
|
410
|
+
delimiter: str = ",",
|
|
411
|
+
text=(),
|
|
412
|
+
skip_bad_rows: bool = False,
|
|
328
413
|
) -> Stream:
|
|
329
414
|
"""Run one select statement and return a `Stream` of its rows.
|
|
330
415
|
|
|
@@ -335,7 +420,8 @@ def stream(
|
|
|
335
420
|
row first (`order by`, `group by`, `count(*)`, a subquery...) is loaded
|
|
336
421
|
into a temporary database on disk and then streamed from there.
|
|
337
422
|
|
|
338
|
-
`header`, `delimiter` and `
|
|
423
|
+
`header`, `delimiter`, `text` and `skip_bad_rows` mean the same as for
|
|
424
|
+
`datapy.open()`.
|
|
339
425
|
"""
|
|
340
426
|
statement = clean(statement)
|
|
341
427
|
files = find_files(statement)
|
|
@@ -343,15 +429,21 @@ def stream(
|
|
|
343
429
|
raise DatapyError(
|
|
344
430
|
"only one file can be queried at a time, found: " + ", ".join(sorted(files))
|
|
345
431
|
)
|
|
346
|
-
source = Source(
|
|
432
|
+
source = Source(
|
|
433
|
+
files.pop(),
|
|
434
|
+
header=header,
|
|
435
|
+
delimiter=delimiter,
|
|
436
|
+
text=text,
|
|
437
|
+
skip_bad_rows=skip_bad_rows,
|
|
438
|
+
)
|
|
347
439
|
table = None
|
|
348
440
|
try:
|
|
349
|
-
sql = rewrite(statement, source.path, source.columns)
|
|
441
|
+
sql, layout = rewrite(statement, source.path, source.columns, source.numeric)
|
|
350
442
|
split = split_row_wise(sql)
|
|
351
443
|
if split is not None:
|
|
352
444
|
# Compiling against the empty table reports syntax errors before
|
|
353
445
|
# any data is read, and tells us what the statement uses.
|
|
354
|
-
table = _Table(":memory:", source)
|
|
446
|
+
table = _Table(":memory:", source, layout)
|
|
355
447
|
row_sql, limit = split
|
|
356
448
|
cursor = table.execute(row_sql)
|
|
357
449
|
cursor.fetchall()
|
|
@@ -362,10 +454,10 @@ def stream(
|
|
|
362
454
|
source.close()
|
|
363
455
|
|
|
364
456
|
rows = _batches(table, source, row_sql, limit)
|
|
365
|
-
return Stream(_names(cursor), rows, close, streamed=True)
|
|
457
|
+
return Stream(_names(cursor), rows, close, source, streamed=True)
|
|
366
458
|
table.close()
|
|
367
459
|
table = None
|
|
368
|
-
data = DataFile._from_source(source)
|
|
460
|
+
data = DataFile._from_source(source, layout)
|
|
369
461
|
try:
|
|
370
462
|
return data._run(sql, data.close)
|
|
371
463
|
except BaseException:
|
|
@@ -379,14 +471,25 @@ def stream(
|
|
|
379
471
|
|
|
380
472
|
|
|
381
473
|
def query(
|
|
382
|
-
statement: str,
|
|
474
|
+
statement: str,
|
|
475
|
+
*,
|
|
476
|
+
header: bool = True,
|
|
477
|
+
delimiter: str = ",",
|
|
478
|
+
text=(),
|
|
479
|
+
skip_bad_rows: bool = False,
|
|
383
480
|
) -> Result:
|
|
384
481
|
"""Run one select statement against the file named in its `from` clause.
|
|
385
482
|
|
|
386
483
|
A shortcut for opening the file, running a single query and closing it.
|
|
387
484
|
The whole result is held in memory; use `datapy.stream()` for large
|
|
388
|
-
results. `header`, `delimiter` and `
|
|
389
|
-
`datapy.open()`.
|
|
485
|
+
results. `header`, `delimiter`, `text` and `skip_bad_rows` mean the same
|
|
486
|
+
as for `datapy.open()`.
|
|
390
487
|
"""
|
|
391
|
-
with stream(
|
|
488
|
+
with stream(
|
|
489
|
+
statement,
|
|
490
|
+
header=header,
|
|
491
|
+
delimiter=delimiter,
|
|
492
|
+
text=text,
|
|
493
|
+
skip_bad_rows=skip_bad_rows,
|
|
494
|
+
) as rows:
|
|
392
495
|
return Result(rows.columns, list(rows))
|