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/_statement.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Find the file a statement names and rewrite the statement for SQLite."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from datapy._errors import DatapyError
|
|
8
|
+
|
|
9
|
+
# One pass over a statement: string literals and quoted identifiers are matched
|
|
10
|
+
# so that nothing inside them is mistaken for a from clause or a $N column.
|
|
11
|
+
_TOKENS = re.compile(
|
|
12
|
+
r"""
|
|
13
|
+
(?P<from>\bfrom\s+)(?P<file>'[^']*'|"[^"]*"|[^\s;,()]+)
|
|
14
|
+
| (?P<quoted>'(?:[^']|'')*'|"(?:[^"]|"")*")
|
|
15
|
+
| \$(?P<position>\d+)
|
|
16
|
+
""",
|
|
17
|
+
re.IGNORECASE | re.VERBOSE,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def clean(statement: str) -> str:
|
|
22
|
+
statement = statement.strip().rstrip(";").strip()
|
|
23
|
+
if not statement:
|
|
24
|
+
raise DatapyError("no query given")
|
|
25
|
+
return statement
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def quote(identifier: str) -> str:
|
|
29
|
+
return '"' + identifier.replace('"', '""') + '"'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _unquote(token: str) -> str:
|
|
33
|
+
if len(token) >= 2 and token[0] == token[-1] and token[0] in "'\"":
|
|
34
|
+
return token[1:-1]
|
|
35
|
+
return token
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def find_files(statement: str) -> set[str]:
|
|
39
|
+
"""Return every file named in a from clause of the statement."""
|
|
40
|
+
files = {
|
|
41
|
+
_unquote(m.group("file"))
|
|
42
|
+
for m in _TOKENS.finditer(statement)
|
|
43
|
+
if m.group("file")
|
|
44
|
+
}
|
|
45
|
+
if not files:
|
|
46
|
+
raise DatapyError("no file found: expected 'from <file>' in the query")
|
|
47
|
+
return files
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def rewrite(statement: str, table: str, columns: list[str]) -> str:
|
|
51
|
+
"""Point every from clause at the loaded table and turn $N into column names."""
|
|
52
|
+
|
|
53
|
+
def replace(match: re.Match) -> str:
|
|
54
|
+
if match.group("file"):
|
|
55
|
+
return match.group("from") + quote(table)
|
|
56
|
+
if match.group("position"):
|
|
57
|
+
position = int(match.group("position"))
|
|
58
|
+
if not 1 <= position <= len(columns):
|
|
59
|
+
raise DatapyError(
|
|
60
|
+
f"${position} is out of range: {table} has {len(columns)} column(s)"
|
|
61
|
+
)
|
|
62
|
+
return quote(columns[position - 1])
|
|
63
|
+
return match.group(0)
|
|
64
|
+
|
|
65
|
+
return _TOKENS.sub(replace, statement)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
_QUOTED = re.compile(r"""'(?:[^']|'')*'|"(?:[^"]|"")*\"""")
|
|
69
|
+
_TRAILING_LIMIT = re.compile(r"\s+limit\s+(\d+)\s*$", re.IGNORECASE)
|
|
70
|
+
|
|
71
|
+
# Any of these means a row's output can depend on other rows, so the whole
|
|
72
|
+
# file has to be available. Unquoted column names that happen to match are
|
|
73
|
+
# caught too, which only costs speed, never correctness.
|
|
74
|
+
_NEEDS_EVERY_ROW = re.compile(
|
|
75
|
+
r"""\b(distinct|order|group|having|limit|offset|union|intersect|except|over
|
|
76
|
+
|window|join|natural|cross|with|values|rowid|oid|_rowid_)\b|--|/\*""",
|
|
77
|
+
re.IGNORECASE | re.VERBOSE,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
#: Functions whose result depends only on the row they are given. A function
|
|
81
|
+
#: that is not listed here is assumed to need every row.
|
|
82
|
+
ROW_FUNCTIONS = frozenset(
|
|
83
|
+
"""abs ceil ceiling char coalesce concat concat_ws date datetime exp floor
|
|
84
|
+
format glob hex ifnull iif instr julianday length like ln log log10 log2
|
|
85
|
+
lower ltrim mod nullif octet_length pow power printf quote replace round
|
|
86
|
+
rtrim sign sqrt strftime substr substring time timediff trim trunc typeof
|
|
87
|
+
unhex unicode unixepoch upper""".split()
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def split_row_wise(sql: str):
|
|
92
|
+
"""Split a trailing `limit N` off a statement that looks row-by-row.
|
|
93
|
+
|
|
94
|
+
Returns `(sql_without_limit, limit)` when nothing in the text of the
|
|
95
|
+
statement needs more than one row at a time, or `None` when it must be run
|
|
96
|
+
against the whole file. The caller still has to check which functions and
|
|
97
|
+
subqueries the statement uses.
|
|
98
|
+
"""
|
|
99
|
+
limit = None
|
|
100
|
+
match = _TRAILING_LIMIT.search(sql)
|
|
101
|
+
if match:
|
|
102
|
+
sql, limit = sql[: match.start()], int(match.group(1))
|
|
103
|
+
if _NEEDS_EVERY_ROW.search(_QUOTED.sub('""', sql)):
|
|
104
|
+
return None
|
|
105
|
+
return sql, limit
|
datapy/cli.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command line entry point: query a data file without setting up a database.
|
|
3
|
+
|
|
4
|
+
datapy -sa people.csv -w 'age > 40' -o name
|
|
5
|
+
datapy -s name,job people.csv -w 'age > 40'
|
|
6
|
+
datapy 'select name, $3 from people.csv where age > 40'
|
|
7
|
+
|
|
8
|
+
Flags follow the `tar` pattern: one operation flag (`-s` to select) plus
|
|
9
|
+
modifier flags that can be combined with it (`-sa` to select all columns).
|
|
10
|
+
Each part of the query is its own flag followed by its value, in any order.
|
|
11
|
+
This module uses only the public `datapy` API.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import csv
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
from datapy import DatapyError, __version__, stream
|
|
23
|
+
|
|
24
|
+
USAGE = """\
|
|
25
|
+
%(prog)s -sa FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
|
|
26
|
+
%(prog)s -s COLUMNS FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
|
|
27
|
+
%(prog)s -sa FILE -q 'CLAUSES'
|
|
28
|
+
%(prog)s 'STATEMENT'"""
|
|
29
|
+
|
|
30
|
+
EPILOG = """\
|
|
31
|
+
arguments:
|
|
32
|
+
FILE the data file to query. Leave it out, or use -, to read
|
|
33
|
+
standard input
|
|
34
|
+
COLUMNS with -s, the columns to select, as one argument:
|
|
35
|
+
name,job or 'name, $3'
|
|
36
|
+
STATEMENT without -s, a whole select statement in one set of quotes
|
|
37
|
+
|
|
38
|
+
examples:
|
|
39
|
+
datapy -sa people.csv
|
|
40
|
+
datapy -sa people.csv -w 'age > 40' -o name
|
|
41
|
+
datapy -sa people.csv -o 'age desc' -l 10
|
|
42
|
+
datapy -s 'job, count(*)' people.csv -g job
|
|
43
|
+
datapy -sa people.csv -q 'where age > 40 order by name'
|
|
44
|
+
datapy 'select name, job from people.csv where age > 40'
|
|
45
|
+
cat people.csv | datapy -sa -w '$2 > 40' | head
|
|
46
|
+
|
|
47
|
+
Rows are read and written as they go, so a query that only picks columns and
|
|
48
|
+
filters rows (-s, -w, -l) uses a small, fixed amount of memory on a file of
|
|
49
|
+
any size. Sorting, grouping and counting need every row first: those load
|
|
50
|
+
the file into a temporary database on disk, not into memory.
|
|
51
|
+
|
|
52
|
+
A column is treated as a number when every value in its first 1,000 rows is
|
|
53
|
+
one. Use -t to keep a column as text.
|
|
54
|
+
|
|
55
|
+
Put each value in single quotes. Without them the shell treats > and < as
|
|
56
|
+
redirects and expands * and $1. Use double quotes when the value contains
|
|
57
|
+
text in single quotes:
|
|
58
|
+
datapy -sa people.csv -w "name = 'Ann'"
|
|
59
|
+
|
|
60
|
+
exit status: 0 on success, 1 if the query or file is invalid, 2 on a usage error.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
#: Output is flushed this often so that downstream commands see rows promptly.
|
|
64
|
+
FLUSH_ROWS = 1000
|
|
65
|
+
|
|
66
|
+
_CLAUSES = re.compile(r"\s*(where|order\s+by|group\s+by|having|limit)\s+\S", re.I)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
70
|
+
parser = argparse.ArgumentParser(
|
|
71
|
+
prog="datapy",
|
|
72
|
+
usage=USAGE,
|
|
73
|
+
description="Query a delimited data file with SQL.",
|
|
74
|
+
epilog=EPILOG,
|
|
75
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
76
|
+
add_help=False,
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument("query", metavar="ARG", nargs="*", help=argparse.SUPPRESS)
|
|
79
|
+
|
|
80
|
+
operations = parser.add_argument_group("operations")
|
|
81
|
+
operations.add_argument(
|
|
82
|
+
"-s",
|
|
83
|
+
"--select",
|
|
84
|
+
action="store_true",
|
|
85
|
+
help="select COLUMNS from FILE",
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
clauses = parser.add_argument_group(
|
|
89
|
+
"clauses", "With -s. Each takes one value, and they can be in any order."
|
|
90
|
+
)
|
|
91
|
+
clauses.add_argument(
|
|
92
|
+
"-w",
|
|
93
|
+
"--where",
|
|
94
|
+
metavar="CONDITION",
|
|
95
|
+
action="append",
|
|
96
|
+
default=[],
|
|
97
|
+
help="only rows matching CONDITION, e.g. -w 'age > 40'. "
|
|
98
|
+
"Repeat it to require every condition",
|
|
99
|
+
)
|
|
100
|
+
clauses.add_argument(
|
|
101
|
+
"-g",
|
|
102
|
+
"--group",
|
|
103
|
+
metavar="COLUMNS",
|
|
104
|
+
action="append",
|
|
105
|
+
default=[],
|
|
106
|
+
help="one row per distinct value of COLUMNS, for use with count(*), "
|
|
107
|
+
"sum() and the like",
|
|
108
|
+
)
|
|
109
|
+
clauses.add_argument(
|
|
110
|
+
"-o",
|
|
111
|
+
"--order",
|
|
112
|
+
metavar="COLUMNS",
|
|
113
|
+
action="append",
|
|
114
|
+
default=[],
|
|
115
|
+
help="sort by COLUMNS, e.g. -o name or -o 'age desc'",
|
|
116
|
+
)
|
|
117
|
+
clauses.add_argument(
|
|
118
|
+
"-l",
|
|
119
|
+
"--limit",
|
|
120
|
+
metavar="COUNT",
|
|
121
|
+
type=int,
|
|
122
|
+
help="return at most COUNT rows",
|
|
123
|
+
)
|
|
124
|
+
clauses.add_argument(
|
|
125
|
+
"-q",
|
|
126
|
+
"--query",
|
|
127
|
+
dest="clauses",
|
|
128
|
+
metavar="CLAUSES",
|
|
129
|
+
help="everything from 'where' to the end as one SQL string, "
|
|
130
|
+
"instead of -w, -g, -o and -l",
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
modifiers = parser.add_argument_group("modifiers")
|
|
134
|
+
modifiers.add_argument(
|
|
135
|
+
"-a",
|
|
136
|
+
"--all",
|
|
137
|
+
action="store_true",
|
|
138
|
+
help="with -s, select all columns, so COLUMNS is left out",
|
|
139
|
+
)
|
|
140
|
+
modifiers.add_argument(
|
|
141
|
+
"-f",
|
|
142
|
+
"--file",
|
|
143
|
+
action="store_true",
|
|
144
|
+
help="query a data file directly (the default, and the only mode so far)",
|
|
145
|
+
)
|
|
146
|
+
modifiers.add_argument(
|
|
147
|
+
"-d",
|
|
148
|
+
"--delimiter",
|
|
149
|
+
metavar="CHAR",
|
|
150
|
+
default=",",
|
|
151
|
+
help="field delimiter for input and output, e.g. ';' or '\\t' (default ',')",
|
|
152
|
+
)
|
|
153
|
+
modifiers.add_argument(
|
|
154
|
+
"-t",
|
|
155
|
+
"--text",
|
|
156
|
+
metavar="COLUMNS",
|
|
157
|
+
action="append",
|
|
158
|
+
default=[],
|
|
159
|
+
help="keep these columns as text even if they look like numbers, "
|
|
160
|
+
"e.g. -t zip or -t 'zip, $4'",
|
|
161
|
+
)
|
|
162
|
+
modifiers.add_argument(
|
|
163
|
+
"-H",
|
|
164
|
+
"--no-header",
|
|
165
|
+
action="store_true",
|
|
166
|
+
help="the first line is data; refer to columns as $1, $2...",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
other = parser.add_argument_group("other")
|
|
170
|
+
other.add_argument(
|
|
171
|
+
"-h", "--help", action="help", help="show this help message and exit"
|
|
172
|
+
)
|
|
173
|
+
other.add_argument(
|
|
174
|
+
"-V",
|
|
175
|
+
"--version",
|
|
176
|
+
action="version",
|
|
177
|
+
version=f"%(prog)s {__version__}",
|
|
178
|
+
help="show the version and exit",
|
|
179
|
+
)
|
|
180
|
+
return parser
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _without_keyword(value: str, keyword: str) -> str:
|
|
184
|
+
"""Accept `-w 'where age > 40'` as well as `-w 'age > 40'`."""
|
|
185
|
+
return re.sub(rf"^\s*{keyword}\s+", "", value, flags=re.I).strip()
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def build_clauses(parser: argparse.ArgumentParser, args: argparse.Namespace) -> str:
|
|
189
|
+
"""Assemble the clause flags in SQL order, whatever order they were given in."""
|
|
190
|
+
flags_used = args.where or args.group or args.order or args.limit is not None
|
|
191
|
+
if args.clauses is not None:
|
|
192
|
+
if flags_used:
|
|
193
|
+
parser.error("-q/--query replaces -w, -g, -o and -l: use one or the other")
|
|
194
|
+
if not _CLAUSES.match(args.clauses):
|
|
195
|
+
parser.error(
|
|
196
|
+
"-q/--query must start with where, order by, group by, having "
|
|
197
|
+
f"or limit, got {args.clauses!r}"
|
|
198
|
+
)
|
|
199
|
+
return args.clauses.strip()
|
|
200
|
+
|
|
201
|
+
where = [_without_keyword(value, "where") for value in args.where]
|
|
202
|
+
group = [_without_keyword(value, r"group\s+by") for value in args.group]
|
|
203
|
+
order = [_without_keyword(value, r"order\s+by") for value in args.order]
|
|
204
|
+
for flag, values in (("-w", where), ("-g", group), ("-o", order)):
|
|
205
|
+
if any(not value for value in values):
|
|
206
|
+
parser.error(f"{flag} needs a value")
|
|
207
|
+
if args.limit is not None and args.limit < 0:
|
|
208
|
+
parser.error("-l/--limit cannot be negative")
|
|
209
|
+
|
|
210
|
+
parts = []
|
|
211
|
+
if where:
|
|
212
|
+
parts.append("where " + " and ".join(f"({value})" for value in where))
|
|
213
|
+
if group:
|
|
214
|
+
parts.append("group by " + ", ".join(group))
|
|
215
|
+
if order:
|
|
216
|
+
parts.append("order by " + ", ".join(order))
|
|
217
|
+
if args.limit is not None:
|
|
218
|
+
parts.append(f"limit {args.limit}")
|
|
219
|
+
return " ".join(parts)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def build_statement(parser: argparse.ArgumentParser, args: argparse.Namespace) -> str:
|
|
223
|
+
"""Turn the flags and arguments into one statement."""
|
|
224
|
+
words = args.query
|
|
225
|
+
if args.all and not args.select:
|
|
226
|
+
parser.error("-a/--all needs -s/--select (use -sa)")
|
|
227
|
+
clauses = build_clauses(parser, args)
|
|
228
|
+
|
|
229
|
+
if not args.select:
|
|
230
|
+
if clauses:
|
|
231
|
+
parser.error("-w, -g, -o, -l and -q need -s/--select")
|
|
232
|
+
if len(words) != 1:
|
|
233
|
+
parser.error(
|
|
234
|
+
"a statement must be one argument: put it in quotes, " "or use -s / -sa"
|
|
235
|
+
)
|
|
236
|
+
return words[0]
|
|
237
|
+
|
|
238
|
+
names = ["FILE"] if args.all else ["COLUMNS", "FILE"]
|
|
239
|
+
form = "-sa FILE" if args.all else "-s COLUMNS FILE"
|
|
240
|
+
if len(words) == len(names) - 1 and not sys.stdin.isatty():
|
|
241
|
+
words = words + ["-"] # FILE left out and input is piped in
|
|
242
|
+
if len(words) < len(names):
|
|
243
|
+
parser.error(f"missing {names[len(words)]}: expected {form}")
|
|
244
|
+
if len(words) > len(names):
|
|
245
|
+
parser.error(
|
|
246
|
+
f"unexpected argument {words[len(names)]!r}: expected {form}, then "
|
|
247
|
+
"-w, -g, -o, -l or -q for the rest of the query"
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
columns = "*" if args.all else words[0].strip()
|
|
251
|
+
file = words[-1]
|
|
252
|
+
if not columns:
|
|
253
|
+
parser.error("COLUMNS is empty")
|
|
254
|
+
if '"' in file:
|
|
255
|
+
parser.error('FILE cannot contain a double quote (")')
|
|
256
|
+
return f'select {columns} from "{file}" {clauses}'.rstrip()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def main(argv: list[str] | None = None) -> int:
|
|
260
|
+
"""Run the command line and return its exit status."""
|
|
261
|
+
parser = build_parser()
|
|
262
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
263
|
+
if not argv:
|
|
264
|
+
parser.print_help(sys.stderr)
|
|
265
|
+
return 2
|
|
266
|
+
# Everything after "--" is an argument, even if it starts with a dash.
|
|
267
|
+
literal = []
|
|
268
|
+
if "--" in argv:
|
|
269
|
+
split = argv.index("--")
|
|
270
|
+
argv, literal = argv[:split], argv[split + 1 :]
|
|
271
|
+
args = parser.parse_intermixed_args(argv)
|
|
272
|
+
args.query += literal
|
|
273
|
+
|
|
274
|
+
statement = build_statement(parser, args)
|
|
275
|
+
delimiter = "\t" if args.delimiter == "\\t" else args.delimiter
|
|
276
|
+
text = [name for value in args.text for name in value.split(",") if name.strip()]
|
|
277
|
+
writer = csv.writer(sys.stdout, delimiter=delimiter, lineterminator="\n")
|
|
278
|
+
try:
|
|
279
|
+
with stream(
|
|
280
|
+
statement, header=not args.no_header, delimiter=delimiter, text=text
|
|
281
|
+
) as rows:
|
|
282
|
+
if not args.no_header:
|
|
283
|
+
writer.writerow(rows.columns)
|
|
284
|
+
for count, row in enumerate(rows, start=1):
|
|
285
|
+
writer.writerow(row)
|
|
286
|
+
if count % FLUSH_ROWS == 0:
|
|
287
|
+
sys.stdout.flush()
|
|
288
|
+
sys.stdout.flush()
|
|
289
|
+
except DatapyError as error:
|
|
290
|
+
sys.stdout.flush()
|
|
291
|
+
print(f"datapy: error: {error}", file=sys.stderr)
|
|
292
|
+
return 1
|
|
293
|
+
except BrokenPipeError:
|
|
294
|
+
# The reader went away (e.g. `datapy ... | head`): stop reading the
|
|
295
|
+
# file and exit quietly.
|
|
296
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
297
|
+
return 0
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datapy
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: An intuitive lightweight file based database and query tool.
|
|
5
|
+
Author-email: Corey McCarty <corey@mccarty.dev>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/xanderyzwich/datapy
|
|
8
|
+
Project-URL: Documentation, https://coreydmccarty.dev/datapy/
|
|
9
|
+
Project-URL: Changelog, https://coreydmccarty.dev/datapy/changelog/
|
|
10
|
+
Project-URL: Issues, https://github.com/xanderyzwich/datapy/issues
|
|
11
|
+
Keywords: file,database,query,csv,sql
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Topic :: Database
|
|
15
|
+
Classifier: Environment :: Console
|
|
16
|
+
Classifier: Natural Language :: English
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE.txt
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest; extra == "dev"
|
|
24
|
+
Requires-Dist: build; extra == "dev"
|
|
25
|
+
Requires-Dist: black<27,>=26; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# Datapy
|
|
29
|
+
|
|
30
|
+
An intuitive lightweight file based database and query tool.
|
|
31
|
+
|
|
32
|
+
- Query csv files with SQL, without setting up a database
|
|
33
|
+
- An approachable alternative to `grep` and `awk`: columns by name, flags
|
|
34
|
+
you can guess
|
|
35
|
+
- Works in a pipeline and on files larger than memory
|
|
36
|
+
- No dependencies outside the Python standard library
|
|
37
|
+
- Read-only: your data files are never modified
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
Datapy needs Python 3.10 or newer.
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
pip install datapy
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
Given `people.csv`:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
name,age,job
|
|
53
|
+
Ann,49,engineer
|
|
54
|
+
Bob,7,student
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Select every column with `-sa` and the file name:
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
$ datapy -sa people.csv
|
|
61
|
+
name,age,job
|
|
62
|
+
Ann,49,engineer
|
|
63
|
+
Bob,7,student
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Narrow it down and sort it with `-w` (where) and `-o` (order):
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
$ datapy -sa people.csv -w 'age > 40' -o name
|
|
70
|
+
name,age,job
|
|
71
|
+
Ann,49,engineer
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Choose columns with `-s`, by header name or by position (`$1` is the first
|
|
75
|
+
column):
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
$ datapy -s name,job people.csv -w 'age > 40'
|
|
79
|
+
name,job
|
|
80
|
+
Ann,engineer
|
|
81
|
+
|
|
82
|
+
$ datapy -s '$1' people.csv -w '$2 < 18'
|
|
83
|
+
name
|
|
84
|
+
Bob
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Building a query from flags
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
datapy -sa FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
|
|
91
|
+
datapy -s COLUMNS FILE [-w CONDITION] [-g COLUMNS] [-o COLUMNS] [-l COUNT]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
| Flag | Meaning | Example |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `-s`, `--select` | choose columns | `-s name,job` |
|
|
97
|
+
| `-a`, `--all` | with `-s`, all columns | `-sa` |
|
|
98
|
+
| `-w`, `--where` | only rows matching a condition | `-w 'age > 40'` |
|
|
99
|
+
| `-o`, `--order` | sort | `-o name`, `-o 'age desc'` |
|
|
100
|
+
| `-g`, `--group` | one row per distinct value | `-s 'job, count(*)' -g job` |
|
|
101
|
+
| `-l`, `--limit` | at most this many rows | `-l 10` |
|
|
102
|
+
|
|
103
|
+
Each flag is followed by its value, and the flags can come in any order.
|
|
104
|
+
Repeat `-w` to require several conditions.
|
|
105
|
+
|
|
106
|
+
Put each value in single quotes. Without them the shell treats `>` and `<` as
|
|
107
|
+
redirects and expands `*` and `$1` before datapy sees them. Use double quotes
|
|
108
|
+
when the value contains text in single quotes:
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
datapy -sa people.csv -w "name = 'Ann'"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Pipes and large files
|
|
115
|
+
|
|
116
|
+
Leave the file out to read standard input. Results are written as csv, so
|
|
117
|
+
datapy fits anywhere in a pipeline:
|
|
118
|
+
|
|
119
|
+
```sh
|
|
120
|
+
cat people.csv | datapy -sa -w 'age > 40' | head
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Rows are read and written as they go. Picking columns and filtering rows
|
|
124
|
+
takes a small, fixed amount of memory on a file of any size; sorting,
|
|
125
|
+
grouping and counting use temporary disk space instead of memory. See
|
|
126
|
+
[large files, pipes and memory](https://coreydmccarty.dev/datapy/performance/) for details and
|
|
127
|
+
measurements.
|
|
128
|
+
|
|
129
|
+
### If you know SQL
|
|
130
|
+
|
|
131
|
+
`-q` takes everything from `where` to the end as one string, in place of
|
|
132
|
+
`-w`, `-g`, `-o` and `-l`. Or pass a whole statement as a single argument:
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
datapy -sa people.csv -q 'where age > 40 order by name limit 5'
|
|
136
|
+
datapy 'select name, job from people.csv where age > 40'
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`datapy --help` lists every flag, as does the
|
|
140
|
+
[command line reference](https://coreydmccarty.dev/datapy/cli/).
|
|
141
|
+
|
|
142
|
+
### From Python
|
|
143
|
+
|
|
144
|
+
Open a file in a `with` block and query it as often as you like. The file is
|
|
145
|
+
read once, when it is opened:
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
import datapy
|
|
149
|
+
|
|
150
|
+
with datapy.open("people.csv") as people:
|
|
151
|
+
print(people.columns) # ['name', 'age', 'job']
|
|
152
|
+
|
|
153
|
+
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
|
|
155
|
+
|
|
156
|
+
minors = people.query("select $1 from people where $2 < 18")
|
|
157
|
+
print(len(minors))
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Statements are the same ones the command line accepts. Inside the block the
|
|
161
|
+
`from` clause can name the file by its path, its file name (`people.csv`) or
|
|
162
|
+
just its name without the extension (`people`).
|
|
163
|
+
|
|
164
|
+
For a result too large to hold in memory, `datapy.stream()` hands the rows
|
|
165
|
+
over one at a time:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
with datapy.stream("select name from people.csv where age > 40") as rows:
|
|
169
|
+
for row in rows:
|
|
170
|
+
print(row["name"])
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Problems with a file or a statement raise `datapy.DatapyError`. The
|
|
174
|
+
[Python API reference](https://coreydmccarty.dev/datapy/python-api/) has the details.
|
|
175
|
+
|
|
176
|
+
## What a query can do
|
|
177
|
+
|
|
178
|
+
One `select` statement against one file. The statement is run by SQLite, so
|
|
179
|
+
`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
|
|
181
|
+
`age > 40` compares numbers rather than text. That is decided from the first
|
|
182
|
+
1,000 rows; `-t zip` keeps a column as text.
|
|
183
|
+
|
|
184
|
+
See [what a query can do](https://coreydmccarty.dev/datapy/sql-support/) for the full rules and limits.
|
|
185
|
+
|
|
186
|
+
## Development
|
|
187
|
+
|
|
188
|
+
See [CONTRIBUTING.md](https://coreydmccarty.dev/datapy/contributing/) for setup, the code layout and the
|
|
189
|
+
checks that run before a release. Changes are listed in
|
|
190
|
+
[CHANGELOG.md](https://coreydmccarty.dev/datapy/changelog/).
|
|
191
|
+
|
|
192
|
+
Want to contribute? Great!
|
|
193
|
+
|
|
194
|
+
This project was originated as a way to bring a community together for Hacktoberfest. I'm glad to have community involvement and help others to understand databases on a more basic level.
|
|
195
|
+
|
|
196
|
+
## License
|
|
197
|
+
|
|
198
|
+
Apache 2.0
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
datapy/__init__.py,sha256=ELIOwzBzjNlPrlhiFRXkwtSie4jvfHVxluSH-GNqe8E,1286
|
|
2
|
+
datapy/__main__.py,sha256=Om5ATszwLGhtqdPjCjkVF6v2KlFaFS9dhIo076n_v0Q,54
|
|
3
|
+
datapy/_datafile.py,sha256=9z4lO8Q8dqsvPWeJN_sanqIdtpwrY8vzFa2IhqdYbuY,13347
|
|
4
|
+
datapy/_errors.py,sha256=pExcn4EMg2rny7rl1JzV5koUsHtF1b-5EeqRBTn_Go0,284
|
|
5
|
+
datapy/_reader.py,sha256=kfhXkEKPWLj0tEAt0a2g2MtI0SvwX8QItYZg4vKurso,5712
|
|
6
|
+
datapy/_statement.py,sha256=aVP6SY4-dSGpRZNwbmuOfbDJGjCMOtiWdBxHWFYYHBU,3679
|
|
7
|
+
datapy/cli.py,sha256=U1XRMVkmoIqyZO5sR-zeINzO7OzTfeLuROZaPIyvlj8,10298
|
|
8
|
+
datapy-0.2.0.dist-info/licenses/LICENSE.txt,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
|
|
9
|
+
datapy-0.2.0.dist-info/METADATA,sha256=A-TAUQAASpyytkgDexfe5UhcjacdN1eJj8e_41OlrDw,6053
|
|
10
|
+
datapy-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
datapy-0.2.0.dist-info/entry_points.txt,sha256=Y7jXCEea50cAaC3ZFQgVbY7_v2fsHlQtfwnF4CgVt3I,43
|
|
12
|
+
datapy-0.2.0.dist-info/top_level.txt,sha256=XHnWDOptQyzP_OfcwkrhH8JsMG-DJMrg-nLtjljMs_8,7
|
|
13
|
+
datapy-0.2.0.dist-info/RECORD,,
|