datapy 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {datapy-0.2.0/datapy.egg-info → datapy-0.2.1}/PKG-INFO +11 -4
  2. {datapy-0.2.0 → datapy-0.2.1}/README.md +10 -3
  3. {datapy-0.2.0 → datapy-0.2.1}/datapy/__init__.py +18 -5
  4. {datapy-0.2.0 → datapy-0.2.1}/datapy/_datafile.py +131 -35
  5. {datapy-0.2.0 → datapy-0.2.1}/datapy/_reader.py +123 -22
  6. datapy-0.2.1/datapy/_statement.py +491 -0
  7. {datapy-0.2.0 → datapy-0.2.1}/datapy/cli.py +32 -4
  8. {datapy-0.2.0 → datapy-0.2.1/datapy.egg-info}/PKG-INFO +11 -4
  9. {datapy-0.2.0 → datapy-0.2.1}/datapy.egg-info/SOURCES.txt +3 -1
  10. {datapy-0.2.0 → datapy-0.2.1}/tests/test_cli.py +50 -0
  11. {datapy-0.2.0 → datapy-0.2.1}/tests/test_datafile.py +1 -1
  12. datapy-0.2.1/tests/test_query.py +237 -0
  13. datapy-0.2.1/tests/test_statement.py +85 -0
  14. {datapy-0.2.0 → datapy-0.2.1}/tests/test_stream.py +7 -5
  15. datapy-0.2.1/tests/test_values.py +207 -0
  16. datapy-0.2.0/datapy/_statement.py +0 -105
  17. datapy-0.2.0/tests/test_query.py +0 -128
  18. {datapy-0.2.0 → datapy-0.2.1}/LICENSE.txt +0 -0
  19. {datapy-0.2.0 → datapy-0.2.1}/MANIFEST.in +0 -0
  20. {datapy-0.2.0 → datapy-0.2.1}/datapy/__main__.py +0 -0
  21. {datapy-0.2.0 → datapy-0.2.1}/datapy/_errors.py +0 -0
  22. {datapy-0.2.0 → datapy-0.2.1}/datapy.egg-info/dependency_links.txt +0 -0
  23. {datapy-0.2.0 → datapy-0.2.1}/datapy.egg-info/entry_points.txt +0 -0
  24. {datapy-0.2.0 → datapy-0.2.1}/datapy.egg-info/requires.txt +0 -0
  25. {datapy-0.2.0 → datapy-0.2.1}/datapy.egg-info/top_level.txt +0 -0
  26. {datapy-0.2.0 → datapy-0.2.1}/pyproject.toml +0 -0
  27. {datapy-0.2.0 → datapy-0.2.1}/setup.cfg +0 -0
  28. {datapy-0.2.0 → datapy-0.2.1}/tests/test_ci.py +0 -0
  29. {datapy-0.2.0 → datapy-0.2.1}/tests/test_docs.py +0 -0
  30. {datapy-0.2.0 → datapy-0.2.1}/tests/test_entry_points.py +0 -0
  31. {datapy-0.2.0 → datapy-0.2.1}/tests/test_style.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datapy
3
- Version: 0.2.0
3
+ Version: 0.2.1
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
@@ -29,6 +29,10 @@ Dynamic: license-file
29
29
 
30
30
  An intuitive lightweight file based database and query tool.
31
31
 
32
+ [Documentation](https://coreydmccarty.dev/datapy/) ·
33
+ [PyPI](https://pypi.org/project/datapy/) ·
34
+ [Source](https://github.com/xanderyzwich/datapy)
35
+
32
36
  - Query csv files with SQL, without setting up a database
33
37
  - An approachable alternative to `grep` and `awk`: columns by name, flags
34
38
  you can guess
@@ -99,6 +103,7 @@ datapy -s COLUMNS FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
99
103
  | `-o`, `--order` | sort | `-o name`, `-o 'age desc'` |
100
104
  | `-g`, `--group` | one row per distinct value | `-s 'job, count(*)' -g job` |
101
105
  | `-l`, `--limit` | at most this many rows | `-l 10` |
106
+ | `-k`, `--skip-bad-rows` | leave out rows with the wrong number of fields | `-sak` |
102
107
 
103
108
  Each flag is followed by its value, and the flags can come in any order.
104
109
  Repeat `-w` to require several conditions.
@@ -151,7 +156,8 @@ with datapy.open("people.csv") as people:
151
156
  print(people.columns) # ['name', 'age', 'job']
152
157
 
153
158
  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
159
+ print(row["name"], row[1]) # by column name or position;
160
+ # values are strings, as in the file
155
161
 
156
162
  minors = people.query("select $1 from people where $2 < 18")
157
163
  print(len(minors))
@@ -177,9 +183,10 @@ Problems with a file or a statement raise `datapy.DatapyError`. The
177
183
 
178
184
  One `select` statement against one file. The statement is run by SQLite, so
179
185
  `where`, `order by`, `group by`, `limit` and SQLite's built-in functions all
180
- work. A column is treated as numeric when every value in it is a number, so
186
+ work. A column is compared as a number when every value in it is one, so
181
187
  `age > 40` compares numbers rather than text. That is decided from the first
182
- 1,000 rows; `-t zip` keeps a column as text.
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.
183
190
 
184
191
  See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
185
192
 
@@ -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 treated as numeric when every value in it is a number, so
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` keeps a column as text.
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.0"
17
+ __version__ = "0.2.1"
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(path, *, header: bool = True, delimiter: str = ",", text=()) -> DataFile:
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` and
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(path, header=header, delimiter=delimiter, text=text)
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,22 @@ 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
+ - `skipped`: with `skip_bad_rows`, how many rows have been left out so
72
+ far for having the wrong number of fields. Final once the last row has
73
+ been read.
66
74
  """
67
75
 
68
- def __init__(self, columns: list[str], rows, close, *, streamed: bool):
76
+ def __init__(self, columns: list[str], rows, close, source, *, streamed: bool):
69
77
  self.columns = columns
70
78
  self.streamed = streamed
79
+ self._source = source
71
80
  self._rows = rows
72
81
  self._close = close
73
82
 
83
+ @property
84
+ def skipped(self) -> int:
85
+ return self._source.skipped
86
+
74
87
  def __iter__(self) -> Stream:
75
88
  return self
76
89
 
@@ -96,25 +109,46 @@ class Stream:
96
109
 
97
110
 
98
111
  class _Table:
99
- """A SQLite table shaped like a data file, readable but not writable by queries."""
112
+ """A SQLite table shaped like a data file, readable but not writable by queries.
100
113
 
101
- def __init__(self, database: str, source: Source):
114
+ `layout` says how each numeric column is stored (see `rewrite`). One that
115
+ is both returned and compared is stored twice, so the value can be handed
116
+ back exactly as it is in the file.
117
+ """
118
+
119
+ def __init__(self, database: str, source: Source, layout: dict[str, str]):
102
120
  self.name = quote(source.path)
103
121
  self._locked = False
104
122
  self.functions = set()
105
123
  self.selects = 0
106
124
  self.conn = sqlite3.connect(database)
125
+ self.conn.create_collation(NUMBER_ORDER, compare_numbers)
107
126
  self.conn.execute("pragma journal_mode = off")
108
127
  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})"
128
+ # An empty field is null in every column. A number is converted by
129
+ # SQLite itself, and a numeric field of only spaces is empty too.
130
+ definitions, values, copies = [], [], []
131
+ 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:
134
+ # Too large for SQLite to hold as a number without rounding:
135
+ # kept as text and compared, exactly, by `compare_numbers`.
136
+ definitions.append(f"{quote(name)} TEXT COLLATE {NUMBER_ORDER}")
137
+ values.append("nullif(trim(?), '')")
138
+ elif stored == "text":
139
+ definitions.append(f"{quote(name)} TEXT")
140
+ values.append("nullif(?, '')")
141
+ else:
142
+ definitions.append(f"{quote(name)} {kind}")
143
+ values.append("nullif(trim(?), '')")
144
+ if stored == "both":
145
+ copies.append((index, name))
146
+ for index, name in copies:
147
+ definitions.append(f"{quote(text_column(name, source.columns))} TEXT")
148
+ values.append("nullif(?, '')")
149
+ self._copied = [index for index, _ in copies]
150
+ self.conn.execute(f"create table {self.name} ({', '.join(definitions)})")
151
+ self._insert = f"insert into {self.name} values ({', '.join(values)})"
118
152
  self.conn.commit()
119
153
  self.conn.row_factory = sqlite3.Row
120
154
  self.conn.set_authorizer(self._authorize)
@@ -136,6 +170,9 @@ class _Table:
136
170
  try:
137
171
  if replace:
138
172
  self.conn.execute(f"delete from {self.name}")
173
+ if self._copied:
174
+ copied = self._copied
175
+ rows = (row + [row[index] for index in copied] for row in rows)
139
176
  self.conn.executemany(self._insert, rows)
140
177
  self.conn.commit()
141
178
  finally:
@@ -155,7 +192,10 @@ class _Table:
155
192
 
156
193
  def _explain(error: Exception) -> str:
157
194
  message = str(error)
158
- if "not authorized" in message or "prohibited" in message:
195
+ if any(
196
+ phrase in message
197
+ for phrase in ("not authorized", "prohibited", "authorization denied")
198
+ ):
159
199
  return "only select statements are supported"
160
200
  if "one statement at a time" in message:
161
201
  return "only one statement can be run at a time"
@@ -188,37 +228,61 @@ class DataFile:
188
228
  names. When false the first line is data and columns are only available
189
229
  by position, as `$1`, `$2`...
190
230
  - `delimiter`: the single character that separates fields.
191
- - `text`: columns to keep as text even if their values look like numbers,
231
+ - `text`: columns to compare as text even if their values look like numbers,
192
232
  given by name or position: `text=["zip", "$4"]`.
233
+ - `skip_bad_rows`: a row must have exactly one field per column. By
234
+ default any other row raises `DatapyError`; when this is true such rows
235
+ are left out and counted in `skipped`.
193
236
 
194
- A column is treated as a number when every value in the first 1,000 rows
237
+ A column is compared as a number when every value in the first 1,000 rows
195
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.
196
240
 
197
241
  Attributes:
198
242
 
199
243
  - `path`: the path the file was opened with.
200
244
  - `columns`: the column names, in order.
245
+ - `skipped`: how many rows were left out by `skip_bad_rows`.
201
246
  - `closed`: true once the file has been closed.
202
247
  """
203
248
 
204
- def __init__(self, path, *, header: bool = True, delimiter: str = ",", text=()):
205
- source = Source(os.fspath(path), header=header, delimiter=delimiter, text=text)
249
+ def __init__(
250
+ self,
251
+ path,
252
+ *,
253
+ header: bool = True,
254
+ delimiter: str = ",",
255
+ text=(),
256
+ skip_bad_rows: bool = False,
257
+ ):
258
+ source = Source(
259
+ os.fspath(path),
260
+ header=header,
261
+ delimiter=delimiter,
262
+ text=text,
263
+ skip_bad_rows=skip_bad_rows,
264
+ )
206
265
  self._load(source)
207
266
 
208
267
  @classmethod
209
- def _from_source(cls, source: Source) -> DataFile:
268
+ def _from_source(cls, source: Source, layout: dict[str, str]) -> DataFile:
210
269
  data = cls.__new__(cls)
211
- data._load(source)
270
+ data._load(source, layout)
212
271
  return data
213
272
 
214
- def _load(self, source: Source) -> None:
273
+ def _load(self, source: Source, layout: dict[str, str] | None = None) -> None:
215
274
  self.path = source.path
216
275
  self.columns = source.columns
276
+ self._source = source
277
+ self._numeric = source.numeric
278
+ # The statements are not known yet, so every numeric column is kept
279
+ # both as a number and as it is in the file.
280
+ self._layout = layout or {name: "both" for name in self._numeric}
217
281
  self._table = None
218
282
  try:
219
283
  # An empty name is a private database in a temporary file: SQLite
220
284
  # keeps a small cache in memory and spills the rest to disk.
221
- self._table = _Table("", source)
285
+ self._table = _Table("", source, self._layout)
222
286
  self._table.fill(source.rows())
223
287
  except BaseException:
224
288
  self.close()
@@ -235,6 +299,10 @@ class DataFile:
235
299
  def __repr__(self) -> str:
236
300
  return f"DataFile({self.path!r})"
237
301
 
302
+ @property
303
+ def skipped(self) -> int:
304
+ return self._source.skipped
305
+
238
306
  @property
239
307
  def closed(self) -> bool:
240
308
  return self._table is None
@@ -277,11 +345,16 @@ class DataFile:
277
345
  raise DatapyError(
278
346
  f"the query names {name}, but the open file is {self.path}"
279
347
  )
280
- return self._run(rewrite(statement, self.path, self.columns))
348
+ rewritten = rewrite(
349
+ statement, self.path, self.columns, self._numeric, self._layout
350
+ )
351
+ return self._run(rewritten.sql)
281
352
 
282
353
  def _run(self, sql: str, close=None) -> Stream:
283
354
  cursor = self._table.execute(sql)
284
- return Stream(_names(cursor), _fetch(cursor), close, streamed=False)
355
+ return Stream(
356
+ _names(cursor), _fetch(cursor), close, self._source, streamed=False
357
+ )
285
358
 
286
359
  def _is_named(self, name: str) -> bool:
287
360
  file_name = os.path.basename(self.path)
@@ -324,7 +397,12 @@ def _batches(table: _Table, source: Source, sql: str, limit):
324
397
 
325
398
 
326
399
  def stream(
327
- statement: str, *, header: bool = True, delimiter: str = ",", text=()
400
+ statement: str,
401
+ *,
402
+ header: bool = True,
403
+ delimiter: str = ",",
404
+ text=(),
405
+ skip_bad_rows: bool = False,
328
406
  ) -> Stream:
329
407
  """Run one select statement and return a `Stream` of its rows.
330
408
 
@@ -335,7 +413,8 @@ def stream(
335
413
  row first (`order by`, `group by`, `count(*)`, a subquery...) is loaded
336
414
  into a temporary database on disk and then streamed from there.
337
415
 
338
- `header`, `delimiter` and `text` mean the same as for `datapy.open()`.
416
+ `header`, `delimiter`, `text` and `skip_bad_rows` mean the same as for
417
+ `datapy.open()`.
339
418
  """
340
419
  statement = clean(statement)
341
420
  files = find_files(statement)
@@ -343,15 +422,21 @@ def stream(
343
422
  raise DatapyError(
344
423
  "only one file can be queried at a time, found: " + ", ".join(sorted(files))
345
424
  )
346
- source = Source(files.pop(), header=header, delimiter=delimiter, text=text)
425
+ source = Source(
426
+ files.pop(),
427
+ header=header,
428
+ delimiter=delimiter,
429
+ text=text,
430
+ skip_bad_rows=skip_bad_rows,
431
+ )
347
432
  table = None
348
433
  try:
349
- sql = rewrite(statement, source.path, source.columns)
434
+ sql, layout = rewrite(statement, source.path, source.columns, source.numeric)
350
435
  split = split_row_wise(sql)
351
436
  if split is not None:
352
437
  # Compiling against the empty table reports syntax errors before
353
438
  # any data is read, and tells us what the statement uses.
354
- table = _Table(":memory:", source)
439
+ table = _Table(":memory:", source, layout)
355
440
  row_sql, limit = split
356
441
  cursor = table.execute(row_sql)
357
442
  cursor.fetchall()
@@ -362,10 +447,10 @@ def stream(
362
447
  source.close()
363
448
 
364
449
  rows = _batches(table, source, row_sql, limit)
365
- return Stream(_names(cursor), rows, close, streamed=True)
450
+ return Stream(_names(cursor), rows, close, source, streamed=True)
366
451
  table.close()
367
452
  table = None
368
- data = DataFile._from_source(source)
453
+ data = DataFile._from_source(source, layout)
369
454
  try:
370
455
  return data._run(sql, data.close)
371
456
  except BaseException:
@@ -379,14 +464,25 @@ def stream(
379
464
 
380
465
 
381
466
  def query(
382
- statement: str, *, header: bool = True, delimiter: str = ",", text=()
467
+ statement: str,
468
+ *,
469
+ header: bool = True,
470
+ delimiter: str = ",",
471
+ text=(),
472
+ skip_bad_rows: bool = False,
383
473
  ) -> Result:
384
474
  """Run one select statement against the file named in its `from` clause.
385
475
 
386
476
  A shortcut for opening the file, running a single query and closing it.
387
477
  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()`.
478
+ results. `header`, `delimiter`, `text` and `skip_bad_rows` mean the same
479
+ as for `datapy.open()`.
390
480
  """
391
- with stream(statement, header=header, delimiter=delimiter, text=text) as rows:
481
+ with stream(
482
+ statement,
483
+ header=header,
484
+ delimiter=delimiter,
485
+ text=text,
486
+ skip_bad_rows=skip_bad_rows,
487
+ ) as rows:
392
488
  return Result(rows.columns, list(rows))
@@ -2,7 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import codecs
5
6
  import csv
7
+ import io
6
8
  import itertools
7
9
  import re
8
10
  import sys
@@ -21,21 +23,86 @@ STDIN = "-"
21
23
  SAMPLE_ROWS = 1000
22
24
 
23
25
 
26
+ def _windows_1252(error: UnicodeError):
27
+ """Read bytes that are not UTF-8 as Windows-1252, the encoding Excel writes.
28
+
29
+ Used as a decoding error handler, so it costs nothing on a file that is
30
+ UTF-8 and only runs on the bytes that are not.
31
+ """
32
+ raw = error.object[error.start : error.end]
33
+ try:
34
+ return raw.decode("cp1252"), error.end
35
+ except UnicodeDecodeError:
36
+ return raw.decode("latin-1"), error.end # the five bytes cp1252 lacks
37
+
38
+
39
+ codecs.register_error("datapy-windows-1252", _windows_1252)
40
+
41
+
42
+ def decoded(binary) -> io.TextIOWrapper:
43
+ """Wrap a binary stream as text.
44
+
45
+ UTF-8, with or without a byte-order mark, is the expected encoding. Bytes
46
+ that are not valid UTF-8 are read as Windows-1252 rather than refused, and
47
+ a UTF-16 byte-order mark (Excel's "Unicode Text") switches to UTF-16.
48
+ """
49
+ mark = binary.peek(2)[:2]
50
+ encoding = "utf-16" if mark in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig"
51
+ return io.TextIOWrapper(
52
+ binary, encoding=encoding, errors="datapy-windows-1252", newline=""
53
+ )
54
+
55
+
56
+ #: The type of a column of whole numbers too large for SQLite's 64-bit
57
+ #: integer. It is stored as text and compared by `compare_numbers`.
58
+ BIG = "BIG"
59
+ #: The collation that compares such a column.
60
+ NUMBER_ORDER = "datapy_number"
61
+
62
+
24
63
  def column_type(values: list) -> str:
25
- """Pick a SQLite type for a column from a sample of its values.
64
+ """Pick a type for a column from a sample of its values.
26
65
 
27
66
  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.
67
+ as ``00123`` are compared as text.
29
68
  """
30
69
  present = [value.strip() for value in values if value and value.strip()]
31
70
  if present and all(_INTEGER.fullmatch(value) for value in present):
32
71
  if all(-_INT64_LIMIT <= int(value) < _INT64_LIMIT for value in present):
33
72
  return "INTEGER"
73
+ return BIG
34
74
  if present and all(_REAL.fullmatch(value) for value in present):
35
75
  return "REAL"
36
76
  return "TEXT"
37
77
 
38
78
 
79
+ def _number(text: str):
80
+ try:
81
+ return int(text)
82
+ except ValueError:
83
+ try:
84
+ return float(text)
85
+ except ValueError:
86
+ return None
87
+
88
+
89
+ def compare_numbers(left: str, right: str) -> int:
90
+ """Order two values as numbers, exactly, however many digits they have.
91
+
92
+ SQLite calls this for every comparison on a `BIG` column, which is slower
93
+ than its own comparison but does not round. A value that is not a number
94
+ sorts after every number, as it does in SQLite.
95
+ """
96
+ a, b = _number(left), _number(right)
97
+ if a is None or b is None:
98
+ if a is not None:
99
+ return -1
100
+ if b is not None:
101
+ return 1
102
+ a, b = left, right
103
+ return (a > b) - (a < b)
104
+
105
+
39
106
  class Source:
40
107
  """An open data file: its column names, column types and a stream of rows.
41
108
 
@@ -43,19 +110,35 @@ class Source:
43
110
  rest is read as `rows()` is consumed, which can happen once.
44
111
  """
45
112
 
46
- def __init__(self, path: str, *, header: bool, delimiter: str, text=()):
113
+ def __init__(
114
+ self,
115
+ path: str,
116
+ *,
117
+ header: bool,
118
+ delimiter: str,
119
+ text=(),
120
+ skip_bad_rows: bool = False,
121
+ ):
47
122
  if len(delimiter) != 1:
48
123
  raise DatapyError(
49
124
  f"delimiter must be a single character, got {delimiter!r}"
50
125
  )
51
126
  self.path = path
127
+ #: Rows left out so far because they had the wrong number of fields.
128
+ self.skipped = 0
129
+ self._skip_bad_rows = skip_bad_rows
52
130
  self.label = "standard input" if path == STDIN else path
53
131
  self._handle = None
132
+ self._owned = path != STDIN
54
133
  try:
55
- if path == STDIN:
56
- handle = sys.stdin
134
+ if self._owned:
135
+ handle = self._handle = decoded(open(path, "rb"))
136
+ elif hasattr(sys.stdin, "buffer"):
137
+ # Read the bytes ourselves, so that a pipe is decoded exactly
138
+ # as a file is, whatever the locale says.
139
+ handle = self._handle = decoded(sys.stdin.buffer)
57
140
  else:
58
- handle = self._handle = open(path, newline="", encoding="utf-8-sig")
141
+ handle = sys.stdin # replaced with a text stream by the caller
59
142
  except OSError as error:
60
143
  raise DatapyError(self._cannot("read", error)) from error
61
144
  self._reader = csv.reader(handle, delimiter=delimiter, skipinitialspace=True)
@@ -71,7 +154,7 @@ class Source:
71
154
  leading = []
72
155
  else:
73
156
  self.columns = [f"${i}" for i in range(1, len(first) + 1)]
74
- leading = [self._fit(first)]
157
+ leading = [first]
75
158
  self._check_names()
76
159
  self._rest = self._fitted()
77
160
  self._sample = leading + list(
@@ -90,15 +173,28 @@ class Source:
90
173
  self.close()
91
174
  raise
92
175
 
176
+ @property
177
+ def numeric(self) -> list[str]:
178
+ """The columns that are compared as numbers."""
179
+ return [
180
+ name
181
+ for name, kind in zip(self.columns, self.types)
182
+ if kind in ("INTEGER", "REAL")
183
+ ]
184
+
93
185
  def rows(self):
94
186
  """Every row in the file, each padded to the full width. Single use."""
95
187
  sample, self._sample = self._sample, []
96
188
  return itertools.chain(sample, self._rest)
97
189
 
98
190
  def close(self) -> None:
99
- if self._handle is not None:
100
- self._handle.close()
101
- self._handle = None
191
+ handle, self._handle = self._handle, None
192
+ if handle is None:
193
+ return
194
+ if self._owned:
195
+ handle.close()
196
+ else:
197
+ handle.detach() # leave standard input itself open
102
198
 
103
199
  def _cannot(self, verb: str, error: Exception) -> str:
104
200
  return (
@@ -119,20 +215,25 @@ class Source:
119
215
  if row:
120
216
  yield row
121
217
 
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
218
  def _fitted(self):
219
+ """Rows with one field per column.
220
+
221
+ Any other row means the file is damaged or a delimiter is not
222
+ quoted, and its values can no longer be matched to columns: it stops
223
+ the query, or is counted and left out when bad rows are skipped.
224
+ """
225
+ width = len(self.columns)
134
226
  for row in self._lines():
135
- yield self._fit(row)
227
+ if len(row) == width:
228
+ yield row
229
+ elif self._skip_bad_rows:
230
+ self.skipped += 1
231
+ else:
232
+ fields = "1 field" if len(row) == 1 else f"{len(row)} fields"
233
+ raise DatapyError(
234
+ f"{self.label}: line {self._reader.line_num} has {fields}, "
235
+ f"expected {width}"
236
+ )
136
237
 
137
238
  def _check_names(self) -> None:
138
239
  seen = set()