datapy 0.2.1__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.
Files changed (33) hide show
  1. {datapy-0.2.1/datapy.egg-info → datapy-0.3.0}/PKG-INFO +25 -3
  2. {datapy-0.2.1 → datapy-0.3.0}/README.md +23 -2
  3. {datapy-0.2.1 → datapy-0.3.0}/datapy/__init__.py +12 -5
  4. {datapy-0.2.1 → datapy-0.3.0}/datapy/_datafile.py +190 -42
  5. {datapy-0.2.1 → datapy-0.3.0}/datapy/_reader.py +87 -20
  6. datapy-0.3.0/datapy/_schema.py +216 -0
  7. {datapy-0.2.1 → datapy-0.3.0}/datapy/cli.py +150 -16
  8. {datapy-0.2.1 → datapy-0.3.0/datapy.egg-info}/PKG-INFO +25 -3
  9. {datapy-0.2.1 → datapy-0.3.0}/datapy.egg-info/SOURCES.txt +2 -0
  10. {datapy-0.2.1 → datapy-0.3.0}/datapy.egg-info/requires.txt +1 -0
  11. {datapy-0.2.1 → datapy-0.3.0}/pyproject.toml +18 -1
  12. {datapy-0.2.1 → datapy-0.3.0}/tests/test_ci.py +16 -0
  13. datapy-0.3.0/tests/test_cli.py +549 -0
  14. datapy-0.3.0/tests/test_docs.py +74 -0
  15. {datapy-0.2.1 → datapy-0.3.0}/tests/test_entry_points.py +12 -1
  16. {datapy-0.2.1 → datapy-0.3.0}/tests/test_query.py +6 -0
  17. datapy-0.3.0/tests/test_schema.py +334 -0
  18. {datapy-0.2.1 → datapy-0.3.0}/tests/test_stream.py +16 -2
  19. {datapy-0.2.1 → datapy-0.3.0}/tests/test_values.py +44 -1
  20. datapy-0.2.1/tests/test_cli.py +0 -281
  21. datapy-0.2.1/tests/test_docs.py +0 -42
  22. {datapy-0.2.1 → datapy-0.3.0}/LICENSE.txt +0 -0
  23. {datapy-0.2.1 → datapy-0.3.0}/MANIFEST.in +0 -0
  24. {datapy-0.2.1 → datapy-0.3.0}/datapy/__main__.py +0 -0
  25. {datapy-0.2.1 → datapy-0.3.0}/datapy/_errors.py +0 -0
  26. {datapy-0.2.1 → datapy-0.3.0}/datapy/_statement.py +0 -0
  27. {datapy-0.2.1 → datapy-0.3.0}/datapy.egg-info/dependency_links.txt +0 -0
  28. {datapy-0.2.1 → datapy-0.3.0}/datapy.egg-info/entry_points.txt +0 -0
  29. {datapy-0.2.1 → datapy-0.3.0}/datapy.egg-info/top_level.txt +0 -0
  30. {datapy-0.2.1 → datapy-0.3.0}/setup.cfg +0 -0
  31. {datapy-0.2.1 → datapy-0.3.0}/tests/test_datafile.py +0 -0
  32. {datapy-0.2.1 → datapy-0.3.0}/tests/test_statement.py +0 -0
  33. {datapy-0.2.1 → 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.2.1
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
@@ -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
@@ -176,6 +177,26 @@ with datapy.stream("select name from people.csv where age > 40") as rows:
176
177
  print(row["name"])
177
178
  ```
178
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
+
179
200
  Problems with a file or a statement raise `datapy.DatapyError`. The
180
201
  [Python API reference](https://coreydmccarty.dev/datapy/python-api/) has the details.
181
202
 
@@ -185,8 +206,9 @@ One `select` statement against one file. The statement is run by SQLite, so
185
206
  `where`, `order by`, `group by`, `limit` and SQLite's built-in functions all
186
207
  work. A column is compared as a number when every value in it is one, so
187
208
  `age > 40` compares numbers rather than text. That is decided from the first
188
- 1,000 rows; `-t zip` compares a column as text. Either way, a column you
189
- select comes back exactly as it is written in the file.
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.
190
212
 
191
213
  See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
192
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 text. Either way, a column you
162
- select comes back exactly as it is written in the file.
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.2.1"
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 = True,
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 `skip_bad_rows` mean.
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)
@@ -68,15 +97,26 @@ class Stream:
68
97
  - `streamed`: true when the file is being read as you iterate; false when
69
98
  the statement needed the whole file to be loaded first (sorting,
70
99
  grouping, counting and the like).
100
+ - `line_ending`: how lines end in the file, taken from its first line:
101
+ `"\\n"`, `"\\r\\n"` (Windows) or `"\\r"`. Write the rows out with
102
+ it to keep the file's own convention.
71
103
  - `skipped`: with `skip_bad_rows`, how many rows have been left out so
72
104
  far for having the wrong number of fields. Final once the last row has
73
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.
74
111
  """
75
112
 
76
- def __init__(self, columns: list[str], rows, close, source, *, streamed: bool):
113
+ def __init__(
114
+ self, columns: list[str], rows, close, source, table, *, streamed: bool
115
+ ):
77
116
  self.columns = columns
78
117
  self.streamed = streamed
79
118
  self._source = source
119
+ self._table = table
80
120
  self._rows = rows
81
121
  self._close = close
82
122
 
@@ -84,6 +124,14 @@ class Stream:
84
124
  def skipped(self) -> int:
85
125
  return self._source.skipped
86
126
 
127
+ @property
128
+ def line_ending(self) -> str:
129
+ return self._source.line_ending
130
+
131
+ @property
132
+ def unfit(self) -> dict[str, int]:
133
+ return dict(self._table.unfit)
134
+
87
135
  def __iter__(self) -> Stream:
88
136
  return self
89
137
 
@@ -114,37 +162,62 @@ class _Table:
114
162
  `layout` says how each numeric column is stored (see `rewrite`). One that
115
163
  is both returned and compared is stored twice, so the value can be handed
116
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.
117
169
  """
118
170
 
119
- def __init__(self, database: str, source: Source, layout: dict[str, str]):
171
+ def __init__(
172
+ self, database: str, source: Source, layout: dict[str, str], typed: bool
173
+ ):
120
174
  self.name = quote(source.path)
121
175
  self._locked = False
122
176
  self.functions = set()
123
177
  self.selects = 0
124
- self.conn = sqlite3.connect(database)
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
+ )
125
184
  self.conn.create_collation(NUMBER_ORDER, compare_numbers)
185
+ self.conn.create_function("datapy_is_number", 1, is_number, deterministic=True)
126
186
  self.conn.execute("pragma journal_mode = off")
127
187
  self.conn.execute("pragma synchronous = off")
128
188
  # An empty field is null in every column. A number is converted by
129
189
  # SQLite itself, and a numeric field of only spaces is empty too.
130
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
131
195
  for index, (name, kind) in enumerate(zip(source.columns, source.types)):
132
- stored = layout.get(name, "text") if kind in ("INTEGER", "REAL") else "text"
133
- if kind == BIG:
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:
134
206
  # Too large for SQLite to hold as a number without rounding:
135
207
  # kept as text and compared, exactly, by `compare_numbers`.
136
- definitions.append(f"{quote(name)} TEXT COLLATE {NUMBER_ORDER}")
208
+ definitions.append(f"{column} TEXT COLLATE {NUMBER_ORDER}")
137
209
  values.append("nullif(trim(?), '')")
138
- elif stored == "text":
139
- definitions.append(f"{quote(name)} TEXT")
140
- values.append("nullif(?, '')")
210
+ self._not_numbers[name] = f"not datapy_is_number({column})"
141
211
  else:
142
- definitions.append(f"{quote(name)} {kind}")
212
+ # SQLite stores a value it cannot read as a number as text.
213
+ definitions.append(f"{column} {kind}")
143
214
  values.append("nullif(trim(?), '')")
215
+ self._not_numbers[name] = f"typeof({column}) = 'text'"
144
216
  if stored == "both":
145
217
  copies.append((index, name))
146
218
  for index, name in copies:
147
- definitions.append(f"{quote(text_column(name, source.columns))} TEXT")
219
+ copy = quote(text_column(name, source.columns))
220
+ definitions.append(f"{copy} {as_written[name]}")
148
221
  values.append("nullif(?, '')")
149
222
  self._copied = [index for index, _ in copies]
150
223
  self.conn.execute(f"create table {self.name} ({', '.join(definitions)})")
@@ -174,6 +247,12 @@ class _Table:
174
247
  copied = self._copied
175
248
  rows = (row + [row[index] for index in copied] for row in rows)
176
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
177
256
  self.conn.commit()
178
257
  finally:
179
258
  self._locked = True
@@ -215,6 +294,29 @@ def _fetch(cursor: sqlite3.Cursor):
215
294
  raise DatapyError(_explain(error)) from error
216
295
 
217
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
+
218
320
  class DataFile:
219
321
  """A delimited text file opened for querying.
220
322
 
@@ -227,22 +329,37 @@ class DataFile:
227
329
  - `header`: when true (the default) the first line holds the column
228
330
  names. When false the first line is data and columns are only available
229
331
  by position, as `$1`, `$2`...
230
- - `delimiter`: the single character that separates fields.
332
+ - `delimiter`: the single character that separates fields; `","` by
333
+ default.
231
334
  - `text`: columns to compare as text even if their values look like numbers,
232
335
  given by name or position: `text=["zip", "$4"]`.
233
336
  - `skip_bad_rows`: a row must have exactly one field per column. By
234
337
  default any other row raises `DatapyError`; when this is true such rows
235
338
  are left out and counted in `skipped`.
236
-
237
- A column is compared as a number when every value in the first 1,000 rows
238
- is one. Use `text` for a column that only looks numeric at the start.
239
- Either way, its values are returned as they are written in the file.
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.
240
354
 
241
355
  Attributes:
242
356
 
243
357
  - `path`: the path the file was opened with.
244
358
  - `columns`: the column names, in order.
245
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.
246
363
  - `closed`: true once the file has been closed.
247
364
  """
248
365
 
@@ -250,27 +367,34 @@ class DataFile:
250
367
  self,
251
368
  path,
252
369
  *,
253
- header: bool = True,
254
- delimiter: str = ",",
370
+ header: bool | None = None,
371
+ delimiter: str | None = None,
255
372
  text=(),
256
373
  skip_bad_rows: bool = False,
374
+ schema=None,
375
+ typed: bool | None = None,
257
376
  ):
258
- source = Source(
377
+ source = _open_source(
259
378
  os.fspath(path),
260
379
  header=header,
261
380
  delimiter=delimiter,
262
381
  text=text,
263
382
  skip_bad_rows=skip_bad_rows,
383
+ schema=schema,
264
384
  )
265
- self._load(source)
385
+ self._load(source, typed=_typed(typed, schema))
266
386
 
267
387
  @classmethod
268
- def _from_source(cls, source: Source, layout: dict[str, str]) -> DataFile:
388
+ def _from_source(
389
+ cls, source: Source, layout: dict[str, str], typed: bool
390
+ ) -> DataFile:
269
391
  data = cls.__new__(cls)
270
- data._load(source, layout)
392
+ data._load(source, layout, typed)
271
393
  return data
272
394
 
273
- def _load(self, source: Source, layout: dict[str, str] | None = None) -> None:
395
+ def _load(
396
+ self, source: Source, layout: dict[str, str] | None = None, typed=False
397
+ ) -> None:
274
398
  self.path = source.path
275
399
  self.columns = source.columns
276
400
  self._source = source
@@ -279,10 +403,12 @@ class DataFile:
279
403
  # both as a number and as it is in the file.
280
404
  self._layout = layout or {name: "both" for name in self._numeric}
281
405
  self._table = None
406
+ self._unfit = {}
282
407
  try:
283
408
  # An empty name is a private database in a temporary file: SQLite
284
409
  # keeps a small cache in memory and spills the rest to disk.
285
- self._table = _Table("", source, self._layout)
410
+ self._table = _Table("", source, self._layout, typed)
411
+ self._unfit = self._table.unfit
286
412
  self._table.fill(source.rows())
287
413
  except BaseException:
288
414
  self.close()
@@ -303,6 +429,10 @@ class DataFile:
303
429
  def skipped(self) -> int:
304
430
  return self._source.skipped
305
431
 
432
+ @property
433
+ def unfit(self) -> dict[str, int]:
434
+ return dict(self._unfit)
435
+
306
436
  @property
307
437
  def closed(self) -> bool:
308
438
  return self._table is None
@@ -329,7 +459,7 @@ class DataFile:
329
459
  use `stream()`.
330
460
  """
331
461
  rows = self.stream(statement)
332
- return Result(rows.columns, list(rows))
462
+ return Result(rows.columns, list(rows), rows.unfit)
333
463
 
334
464
  def stream(self, statement: str) -> Stream:
335
465
  """Run a select statement and return a `Stream` of its rows.
@@ -353,7 +483,12 @@ class DataFile:
353
483
  def _run(self, sql: str, close=None) -> Stream:
354
484
  cursor = self._table.execute(sql)
355
485
  return Stream(
356
- _names(cursor), _fetch(cursor), close, self._source, streamed=False
486
+ _names(cursor),
487
+ _fetch(cursor),
488
+ close,
489
+ self._source,
490
+ self._table,
491
+ streamed=False,
357
492
  )
358
493
 
359
494
  def _is_named(self, name: str) -> bool:
@@ -399,10 +534,12 @@ def _batches(table: _Table, source: Source, sql: str, limit):
399
534
  def stream(
400
535
  statement: str,
401
536
  *,
402
- header: bool = True,
403
- delimiter: str = ",",
537
+ header: bool | None = None,
538
+ delimiter: str | None = None,
404
539
  text=(),
405
540
  skip_bad_rows: bool = False,
541
+ schema=None,
542
+ typed: bool | None = None,
406
543
  ) -> Stream:
407
544
  """Run one select statement and return a `Stream` of its rows.
408
545
 
@@ -413,8 +550,8 @@ def stream(
413
550
  row first (`order by`, `group by`, `count(*)`, a subquery...) is loaded
414
551
  into a temporary database on disk and then streamed from there.
415
552
 
416
- `header`, `delimiter`, `text` and `skip_bad_rows` mean the same as for
417
- `datapy.open()`.
553
+ `header`, `delimiter`, `text`, `skip_bad_rows`, `schema` and `typed` mean
554
+ the same as for `datapy.open()`.
418
555
  """
419
556
  statement = clean(statement)
420
557
  files = find_files(statement)
@@ -422,21 +559,28 @@ def stream(
422
559
  raise DatapyError(
423
560
  "only one file can be queried at a time, found: " + ", ".join(sorted(files))
424
561
  )
425
- source = Source(
562
+ source = _open_source(
426
563
  files.pop(),
427
564
  header=header,
428
565
  delimiter=delimiter,
429
566
  text=text,
430
567
  skip_bad_rows=skip_bad_rows,
568
+ schema=schema,
431
569
  )
432
570
  table = None
571
+ typed = _typed(typed, schema)
433
572
  try:
434
- sql, layout = rewrite(statement, source.path, source.columns, source.numeric)
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
+ )
435
579
  split = split_row_wise(sql)
436
580
  if split is not None:
437
581
  # Compiling against the empty table reports syntax errors before
438
582
  # any data is read, and tells us what the statement uses.
439
- table = _Table(":memory:", source, layout)
583
+ table = _Table(":memory:", source, layout, typed)
440
584
  row_sql, limit = split
441
585
  cursor = table.execute(row_sql)
442
586
  cursor.fetchall()
@@ -447,10 +591,10 @@ def stream(
447
591
  source.close()
448
592
 
449
593
  rows = _batches(table, source, row_sql, limit)
450
- return Stream(_names(cursor), rows, close, source, streamed=True)
594
+ return Stream(_names(cursor), rows, close, source, table, streamed=True)
451
595
  table.close()
452
596
  table = None
453
- data = DataFile._from_source(source, layout)
597
+ data = DataFile._from_source(source, layout, typed)
454
598
  try:
455
599
  return data._run(sql, data.close)
456
600
  except BaseException:
@@ -466,17 +610,19 @@ def stream(
466
610
  def query(
467
611
  statement: str,
468
612
  *,
469
- header: bool = True,
470
- delimiter: str = ",",
613
+ header: bool | None = None,
614
+ delimiter: str | None = None,
471
615
  text=(),
472
616
  skip_bad_rows: bool = False,
617
+ schema=None,
618
+ typed: bool | None = None,
473
619
  ) -> Result:
474
620
  """Run one select statement against the file named in its `from` clause.
475
621
 
476
622
  A shortcut for opening the file, running a single query and closing it.
477
623
  The whole result is held in memory; use `datapy.stream()` for large
478
- results. `header`, `delimiter`, `text` and `skip_bad_rows` mean the same
479
- as for `datapy.open()`.
624
+ results. `header`, `delimiter`, `text`, `skip_bad_rows`, `schema` and
625
+ `typed` mean the same as for `datapy.open()`.
480
626
  """
481
627
  with stream(
482
628
  statement,
@@ -484,5 +630,7 @@ def query(
484
630
  delimiter=delimiter,
485
631
  text=text,
486
632
  skip_bad_rows=skip_bad_rows,
633
+ schema=schema,
634
+ typed=typed,
487
635
  ) as rows:
488
- return Result(rows.columns, list(rows))
636
+ return Result(rows.columns, list(rows), rows.unfit)