sqlanswer 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PyChallenge
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlanswer
3
+ Version: 0.1.0
4
+ Summary: Print SQL results as clean tables and check if two queries return the same rows. Handy for SQL practice.
5
+ Author: SQLCrab
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://sqlcrab.com
8
+ Project-URL: SQL exercises, https://sqlcrab.com
9
+ Keywords: sql,sqlite,table,compare,practice,learning,education
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: SQL
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Topic :: Database
15
+ Classifier: Topic :: Education
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # sqlanswer
22
+
23
+ Print SQL query results as clean tables, and check whether two queries return the same rows.
24
+
25
+ Handy when you're practicing SQL from Python: run your query, see the result clearly, then check it against a reference answer. No dependencies. Works with `sqlite3` out of the box and with any DB-API connection (psycopg, mysql-connector, duckdb and others).
26
+
27
+ ```bash
28
+ pip install sqlanswer
29
+ ```
30
+
31
+ ## Show a query as a table
32
+
33
+ ```python
34
+ import sqlite3
35
+ from sqlanswer import show
36
+
37
+ conn = sqlite3.connect("shop.db")
38
+ show(conn, "SELECT name, price, category FROM products")
39
+ ```
40
+
41
+ ```
42
+ +-------+-------+-----------+
43
+ | name | price | category |
44
+ +-------+-------+-----------+
45
+ | Pen | 1.5 | office |
46
+ | Desk | 120 | furniture |
47
+ | Chair | 75.25 | furniture |
48
+ | Lamp | 30 | NULL |
49
+ +-------+-------+-----------+
50
+ 4 rows
51
+ ```
52
+
53
+ Numbers are right-aligned, `NULL` is shown as `NULL`, long text is cut off, and large results show the first 50 rows (`limit=None` shows everything). You can also pass a file path instead of a connection: `show("shop.db", "SELECT ...")`.
54
+
55
+ ## Check your answer against another query
56
+
57
+ ```python
58
+ from sqlanswer import compare
59
+
60
+ compare(
61
+ conn,
62
+ "SELECT name FROM products WHERE price > 10", # your query
63
+ "SELECT name FROM products WHERE price > 50", # expected answer
64
+ )
65
+ ```
66
+
67
+ ```
68
+ DIFFERENT: Rows differ: 0 missing, 1 extra
69
+ Extra rows (returned but not expected):
70
+ +------+
71
+ | name |
72
+ +------+
73
+ | Lamp |
74
+ +------+
75
+ ```
76
+
77
+ By default `compare` works the way most SQL exercises are graded:
78
+
79
+ - **Row order doesn't matter.** Use `ordered=True` when the task asks for a specific `ORDER BY`.
80
+ - **Duplicate rows do matter.** Forgetting `DISTINCT` counts as wrong.
81
+ - **Column names don't matter.** Use `check_column_names=True` when aliases are part of the task.
82
+ - **Floats are rounded** to 6 digits, so `0.1 + 0.2` matches `0.3`.
83
+
84
+ `compare` returns a result that is truthy when the queries match, with `.missing`, `.extra` and `.reason` for details.
85
+
86
+ ## From the command line
87
+
88
+ ```bash
89
+ python -m sqlanswer shop.db "SELECT * FROM products"
90
+ python -m sqlanswer shop.db "SELECT name FROM products WHERE price > 10" \
91
+ --expected "SELECT name FROM products WHERE price > 50"
92
+ ```
93
+
94
+ The compare command exits with code 1 when the results differ, so you can use it in scripts.
95
+
96
+ ## Want SQL exercises to practice on?
97
+
98
+ [SQLCrab](https://sqlcrab.com) has SQL challenges you can solve right in your browser.
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,82 @@
1
+ # sqlanswer
2
+
3
+ Print SQL query results as clean tables, and check whether two queries return the same rows.
4
+
5
+ Handy when you're practicing SQL from Python: run your query, see the result clearly, then check it against a reference answer. No dependencies. Works with `sqlite3` out of the box and with any DB-API connection (psycopg, mysql-connector, duckdb and others).
6
+
7
+ ```bash
8
+ pip install sqlanswer
9
+ ```
10
+
11
+ ## Show a query as a table
12
+
13
+ ```python
14
+ import sqlite3
15
+ from sqlanswer import show
16
+
17
+ conn = sqlite3.connect("shop.db")
18
+ show(conn, "SELECT name, price, category FROM products")
19
+ ```
20
+
21
+ ```
22
+ +-------+-------+-----------+
23
+ | name | price | category |
24
+ +-------+-------+-----------+
25
+ | Pen | 1.5 | office |
26
+ | Desk | 120 | furniture |
27
+ | Chair | 75.25 | furniture |
28
+ | Lamp | 30 | NULL |
29
+ +-------+-------+-----------+
30
+ 4 rows
31
+ ```
32
+
33
+ Numbers are right-aligned, `NULL` is shown as `NULL`, long text is cut off, and large results show the first 50 rows (`limit=None` shows everything). You can also pass a file path instead of a connection: `show("shop.db", "SELECT ...")`.
34
+
35
+ ## Check your answer against another query
36
+
37
+ ```python
38
+ from sqlanswer import compare
39
+
40
+ compare(
41
+ conn,
42
+ "SELECT name FROM products WHERE price > 10", # your query
43
+ "SELECT name FROM products WHERE price > 50", # expected answer
44
+ )
45
+ ```
46
+
47
+ ```
48
+ DIFFERENT: Rows differ: 0 missing, 1 extra
49
+ Extra rows (returned but not expected):
50
+ +------+
51
+ | name |
52
+ +------+
53
+ | Lamp |
54
+ +------+
55
+ ```
56
+
57
+ By default `compare` works the way most SQL exercises are graded:
58
+
59
+ - **Row order doesn't matter.** Use `ordered=True` when the task asks for a specific `ORDER BY`.
60
+ - **Duplicate rows do matter.** Forgetting `DISTINCT` counts as wrong.
61
+ - **Column names don't matter.** Use `check_column_names=True` when aliases are part of the task.
62
+ - **Floats are rounded** to 6 digits, so `0.1 + 0.2` matches `0.3`.
63
+
64
+ `compare` returns a result that is truthy when the queries match, with `.missing`, `.extra` and `.reason` for details.
65
+
66
+ ## From the command line
67
+
68
+ ```bash
69
+ python -m sqlanswer shop.db "SELECT * FROM products"
70
+ python -m sqlanswer shop.db "SELECT name FROM products WHERE price > 10" \
71
+ --expected "SELECT name FROM products WHERE price > 50"
72
+ ```
73
+
74
+ The compare command exits with code 1 when the results differ, so you can use it in scripts.
75
+
76
+ ## Want SQL exercises to practice on?
77
+
78
+ [SQLCrab](https://sqlcrab.com) has SQL challenges you can solve right in your browser.
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sqlanswer"
7
+ version = "0.1.0"
8
+ description = "Print SQL results as clean tables and check if two queries return the same rows. Handy for SQL practice."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ authors = [{ name = "SQLCrab" }]
13
+ keywords = ["sql", "sqlite", "table", "compare", "practice", "learning", "education"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: SQL",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Education",
19
+ "Topic :: Database",
20
+ "Topic :: Education",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://sqlcrab.com"
26
+ "SQL exercises" = "https://sqlcrab.com"
27
+
28
+ [project.scripts]
29
+ sqlanswer = "sqlanswer.__main__:main"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,245 @@
1
+ """sqlanswer: print SQL results as clean tables and check if two queries return the same rows.
2
+
3
+ import sqlite3
4
+ from sqlanswer import show, compare
5
+
6
+ conn = sqlite3.connect("shop.db")
7
+ show(conn, "SELECT name, price FROM products LIMIT 5")
8
+
9
+ compare(conn,
10
+ "SELECT name FROM products WHERE price > 10", # your answer
11
+ "SELECT name FROM products WHERE NOT price <= 10") # reference
12
+
13
+ Works with sqlite3 out of the box and with any DB-API 2.0 connection
14
+ (psycopg, mysql-connector, duckdb, ...).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import sqlite3
20
+ import sys
21
+ from collections import Counter
22
+ from dataclasses import dataclass, field
23
+ from typing import Any, Iterable, Sequence
24
+
25
+ __all__ = ["show", "format_table", "compare", "run", "Comparison"]
26
+ __version__ = "0.1.0"
27
+
28
+
29
+ # ---------------------------------------------------------------- running
30
+
31
+ def _connect(db: Any) -> Any:
32
+ if isinstance(db, (str, bytes)) or hasattr(db, "__fspath__"):
33
+ return sqlite3.connect(db)
34
+ return db
35
+
36
+
37
+ def run(db: Any, sql: str, params: Sequence | dict | None = None) -> tuple[list[str], list[tuple]]:
38
+ """Run a query and return (column_names, rows).
39
+
40
+ ``db`` can be a DB-API connection or a path to a SQLite file.
41
+ """
42
+ conn = _connect(db)
43
+ cur = conn.cursor()
44
+ try:
45
+ if params is None:
46
+ cur.execute(sql)
47
+ else:
48
+ cur.execute(sql, params)
49
+ if cur.description is None:
50
+ return [], []
51
+ headers = [d[0] for d in cur.description]
52
+ rows = [tuple(r) for r in cur.fetchall()]
53
+ return headers, rows
54
+ finally:
55
+ try:
56
+ cur.close()
57
+ except Exception:
58
+ pass
59
+
60
+
61
+ # ---------------------------------------------------------------- tables
62
+
63
+ def _cell(value: Any, max_width: int) -> str:
64
+ if value is None:
65
+ text = "NULL"
66
+ elif isinstance(value, float):
67
+ text = f"{value:.10g}"
68
+ elif isinstance(value, (bytes, bytearray, memoryview)):
69
+ text = f"<{len(bytes(value))} bytes>"
70
+ else:
71
+ text = str(value)
72
+ text = text.replace("\n", "\\n").replace("\t", " ")
73
+ if max_width and len(text) > max_width:
74
+ text = text[: max_width - 3] + "..."
75
+ return text
76
+
77
+
78
+ def _is_number(value: Any) -> bool:
79
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
80
+
81
+
82
+ def format_table(
83
+ headers: Sequence[str],
84
+ rows: Iterable[Sequence[Any]],
85
+ *,
86
+ max_width: int = 40,
87
+ ) -> str:
88
+ """Format rows as a plain-text table. Numbers are right-aligned."""
89
+ rows = [tuple(r) for r in rows]
90
+ headers = [str(h) for h in headers] or [f"col{i + 1}" for i in range(len(rows[0]) if rows else 0)]
91
+ cells = [[_cell(v, max_width) for v in row] for row in rows]
92
+ ncols = len(headers)
93
+ widths = [len(h) for h in headers]
94
+ for row in cells:
95
+ for i, c in enumerate(row[:ncols]):
96
+ widths[i] = max(widths[i], len(c))
97
+
98
+ numeric = [
99
+ bool(rows) and all(_is_number(r[i]) or r[i] is None for r in rows)
100
+ for i in range(ncols)
101
+ ]
102
+
103
+ def line(values: Sequence[str], align_numbers: bool) -> str:
104
+ parts = []
105
+ for i, v in enumerate(values):
106
+ if align_numbers and numeric[i]:
107
+ parts.append(v.rjust(widths[i]))
108
+ else:
109
+ parts.append(v.ljust(widths[i]))
110
+ return "| " + " | ".join(parts) + " |"
111
+
112
+ sep = "+-" + "-+-".join("-" * w for w in widths) + "-+"
113
+ out = [sep, line(headers, False), sep]
114
+ out += [line(r, True) for r in cells]
115
+ out.append(sep)
116
+ return "\n".join(out)
117
+
118
+
119
+ def show(
120
+ db: Any,
121
+ sql: str,
122
+ params: Sequence | dict | None = None,
123
+ *,
124
+ limit: int | None = 50,
125
+ max_width: int = 40,
126
+ stream: Any = None,
127
+ ) -> None:
128
+ """Run a query and print the result as a table.
129
+
130
+ Shows at most ``limit`` rows (None for all) and says how many were hidden.
131
+ """
132
+ out = stream if stream is not None else sys.stdout
133
+ headers, rows = run(db, sql, params)
134
+ if not headers:
135
+ print("(query returned no result set)", file=out)
136
+ return
137
+ shown = rows if limit is None else rows[:limit]
138
+ print(format_table(headers, shown, max_width=max_width), file=out)
139
+ total = len(rows)
140
+ word = "row" if total == 1 else "rows"
141
+ if len(shown) < total:
142
+ print(f"{len(shown)} of {total} {word} shown", file=out)
143
+ else:
144
+ print(f"{total} {word}", file=out)
145
+
146
+
147
+ # ---------------------------------------------------------------- comparing
148
+
149
+ @dataclass
150
+ class Comparison:
151
+ """Result of ``compare``. Truthy when both queries return the same rows."""
152
+
153
+ same: bool
154
+ reason: str
155
+ headers: list[str] = field(default_factory=list)
156
+ missing: list[tuple] = field(default_factory=list) # in expected, not in actual
157
+ extra: list[tuple] = field(default_factory=list) # in actual, not in expected
158
+
159
+ def __bool__(self) -> bool:
160
+ return self.same
161
+
162
+
163
+ def _norm(value: Any, float_digits: int) -> Any:
164
+ if isinstance(value, float):
165
+ rounded = round(value, float_digits)
166
+ return int(rounded) if rounded.is_integer() else rounded
167
+ return value
168
+
169
+
170
+ def _sort_key(row: tuple) -> tuple:
171
+ # Sort mixed types and NULLs without errors.
172
+ return tuple((v is None, type(v).__name__, v if v is not None else 0) for v in row)
173
+
174
+
175
+ def compare(
176
+ db: Any,
177
+ actual_sql: str,
178
+ expected_sql: str,
179
+ *,
180
+ ordered: bool = False,
181
+ check_column_names: bool = False,
182
+ float_digits: int = 6,
183
+ verbose: bool = True,
184
+ show_limit: int = 10,
185
+ stream: Any = None,
186
+ ) -> Comparison:
187
+ """Check whether ``actual_sql`` returns the same rows as ``expected_sql``.
188
+
189
+ By default row order does not matter (like most SQL exercises), duplicate
190
+ rows do matter, and column names are ignored. Set ``ordered=True`` when the
191
+ exercise asks for ORDER BY, and ``check_column_names=True`` when aliases matter.
192
+ """
193
+ out = stream if stream is not None else sys.stdout
194
+ conn = _connect(db)
195
+ a_headers, a_rows = run(conn, actual_sql)
196
+ e_headers, e_rows = run(conn, expected_sql)
197
+
198
+ a_rows = [tuple(_norm(v, float_digits) for v in r) for r in a_rows]
199
+ e_rows = [tuple(_norm(v, float_digits) for v in r) for r in e_rows]
200
+
201
+ result: Comparison
202
+ if len(a_headers) != len(e_headers):
203
+ result = Comparison(
204
+ False,
205
+ f"Different number of columns: got {len(a_headers)} {a_headers}, "
206
+ f"expected {len(e_headers)} {e_headers}",
207
+ headers=e_headers,
208
+ )
209
+ elif check_column_names and [h.lower() for h in a_headers] != [h.lower() for h in e_headers]:
210
+ result = Comparison(
211
+ False, f"Different column names: got {a_headers}, expected {e_headers}",
212
+ headers=e_headers,
213
+ )
214
+ else:
215
+ a_count, e_count = Counter(a_rows), Counter(e_rows)
216
+ missing = sorted((e_count - a_count).elements(), key=_sort_key)
217
+ extra = sorted((a_count - e_count).elements(), key=_sort_key)
218
+ if missing or extra:
219
+ result = Comparison(
220
+ False,
221
+ f"Rows differ: {len(missing)} missing, {len(extra)} extra",
222
+ headers=e_headers, missing=missing, extra=extra,
223
+ )
224
+ elif ordered and a_rows != e_rows:
225
+ first = next(i for i, (x, y) in enumerate(zip(a_rows, e_rows)) if x != y)
226
+ result = Comparison(
227
+ False,
228
+ f"Same rows but in a different order (first difference at row {first + 1})",
229
+ headers=e_headers,
230
+ )
231
+ else:
232
+ n = len(e_rows)
233
+ result = Comparison(True, f"Same result ({n} row{'s' if n != 1 else ''})", headers=e_headers)
234
+
235
+ if verbose:
236
+ label = "MATCH" if result.same else "DIFFERENT"
237
+ print(f"{label}: {result.reason}", file=out)
238
+ for title, rows in (("Missing rows (expected but not returned):", result.missing),
239
+ ("Extra rows (returned but not expected):", result.extra)):
240
+ if rows:
241
+ print(title, file=out)
242
+ print(format_table(result.headers, rows[:show_limit]), file=out)
243
+ if len(rows) > show_limit:
244
+ print(f"... and {len(rows) - show_limit} more", file=out)
245
+ return result
@@ -0,0 +1,33 @@
1
+ """Command line use:
2
+
3
+ python -m sqlanswer shop.db "SELECT * FROM products"
4
+ python -m sqlanswer shop.db "SELECT ..." --expected "SELECT ..."
5
+ """
6
+
7
+ import argparse
8
+ import sys
9
+
10
+ from . import compare, show
11
+
12
+
13
+ def main(argv=None) -> int:
14
+ p = argparse.ArgumentParser(
15
+ prog="sqlanswer",
16
+ description="Show a SQLite query as a table, or compare it with an expected query.",
17
+ )
18
+ p.add_argument("database", help="path to a SQLite database file")
19
+ p.add_argument("query", help="SQL query to run")
20
+ p.add_argument("--expected", help="reference query to compare against")
21
+ p.add_argument("--ordered", action="store_true", help="row order must match too")
22
+ p.add_argument("--limit", type=int, default=50, help="max rows to show (default 50, 0 = all)")
23
+ args = p.parse_args(argv)
24
+
25
+ if args.expected:
26
+ ok = compare(args.database, args.query, args.expected, ordered=args.ordered)
27
+ return 0 if ok else 1
28
+ show(args.database, args.query, limit=args.limit or None)
29
+ return 0
30
+
31
+
32
+ if __name__ == "__main__":
33
+ sys.exit(main())
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlanswer
3
+ Version: 0.1.0
4
+ Summary: Print SQL results as clean tables and check if two queries return the same rows. Handy for SQL practice.
5
+ Author: SQLCrab
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://sqlcrab.com
8
+ Project-URL: SQL exercises, https://sqlcrab.com
9
+ Keywords: sql,sqlite,table,compare,practice,learning,education
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: SQL
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Topic :: Database
15
+ Classifier: Topic :: Education
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # sqlanswer
22
+
23
+ Print SQL query results as clean tables, and check whether two queries return the same rows.
24
+
25
+ Handy when you're practicing SQL from Python: run your query, see the result clearly, then check it against a reference answer. No dependencies. Works with `sqlite3` out of the box and with any DB-API connection (psycopg, mysql-connector, duckdb and others).
26
+
27
+ ```bash
28
+ pip install sqlanswer
29
+ ```
30
+
31
+ ## Show a query as a table
32
+
33
+ ```python
34
+ import sqlite3
35
+ from sqlanswer import show
36
+
37
+ conn = sqlite3.connect("shop.db")
38
+ show(conn, "SELECT name, price, category FROM products")
39
+ ```
40
+
41
+ ```
42
+ +-------+-------+-----------+
43
+ | name | price | category |
44
+ +-------+-------+-----------+
45
+ | Pen | 1.5 | office |
46
+ | Desk | 120 | furniture |
47
+ | Chair | 75.25 | furniture |
48
+ | Lamp | 30 | NULL |
49
+ +-------+-------+-----------+
50
+ 4 rows
51
+ ```
52
+
53
+ Numbers are right-aligned, `NULL` is shown as `NULL`, long text is cut off, and large results show the first 50 rows (`limit=None` shows everything). You can also pass a file path instead of a connection: `show("shop.db", "SELECT ...")`.
54
+
55
+ ## Check your answer against another query
56
+
57
+ ```python
58
+ from sqlanswer import compare
59
+
60
+ compare(
61
+ conn,
62
+ "SELECT name FROM products WHERE price > 10", # your query
63
+ "SELECT name FROM products WHERE price > 50", # expected answer
64
+ )
65
+ ```
66
+
67
+ ```
68
+ DIFFERENT: Rows differ: 0 missing, 1 extra
69
+ Extra rows (returned but not expected):
70
+ +------+
71
+ | name |
72
+ +------+
73
+ | Lamp |
74
+ +------+
75
+ ```
76
+
77
+ By default `compare` works the way most SQL exercises are graded:
78
+
79
+ - **Row order doesn't matter.** Use `ordered=True` when the task asks for a specific `ORDER BY`.
80
+ - **Duplicate rows do matter.** Forgetting `DISTINCT` counts as wrong.
81
+ - **Column names don't matter.** Use `check_column_names=True` when aliases are part of the task.
82
+ - **Floats are rounded** to 6 digits, so `0.1 + 0.2` matches `0.3`.
83
+
84
+ `compare` returns a result that is truthy when the queries match, with `.missing`, `.extra` and `.reason` for details.
85
+
86
+ ## From the command line
87
+
88
+ ```bash
89
+ python -m sqlanswer shop.db "SELECT * FROM products"
90
+ python -m sqlanswer shop.db "SELECT name FROM products WHERE price > 10" \
91
+ --expected "SELECT name FROM products WHERE price > 50"
92
+ ```
93
+
94
+ The compare command exits with code 1 when the results differ, so you can use it in scripts.
95
+
96
+ ## Want SQL exercises to practice on?
97
+
98
+ [SQLCrab](https://sqlcrab.com) has SQL challenges you can solve right in your browser.
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/sqlanswer/__init__.py
5
+ src/sqlanswer/__main__.py
6
+ src/sqlanswer.egg-info/PKG-INFO
7
+ src/sqlanswer.egg-info/SOURCES.txt
8
+ src/sqlanswer.egg-info/dependency_links.txt
9
+ src/sqlanswer.egg-info/entry_points.txt
10
+ src/sqlanswer.egg-info/top_level.txt
11
+ tests/test_sqlanswer.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sqlanswer = sqlanswer.__main__:main
@@ -0,0 +1 @@
1
+ sqlanswer
@@ -0,0 +1,159 @@
1
+ import io
2
+ import sqlite3
3
+ import unittest
4
+
5
+ from sqlanswer import compare, format_table, run, show
6
+ from sqlanswer.__main__ import main
7
+
8
+
9
+ def make_db():
10
+ conn = sqlite3.connect(":memory:")
11
+ conn.executescript(
12
+ """
13
+ CREATE TABLE products (id INTEGER, name TEXT, price REAL, category TEXT);
14
+ INSERT INTO products VALUES
15
+ (1, 'Pen', 1.5, 'office'),
16
+ (2, 'Desk', 120.0, 'furniture'),
17
+ (3, 'Chair', 75.25, 'furniture'),
18
+ (4, 'Lamp', 30.0, NULL);
19
+ """
20
+ )
21
+ return conn
22
+
23
+
24
+ class ShowTests(unittest.TestCase):
25
+ def setUp(self):
26
+ self.conn = make_db()
27
+
28
+ def test_table_output(self):
29
+ buf = io.StringIO()
30
+ show(self.conn, "SELECT name, price FROM products ORDER BY id", stream=buf)
31
+ out = buf.getvalue()
32
+ self.assertIn("| name | price |", out)
33
+ self.assertIn("| Pen | 1.5 |", out)
34
+ self.assertIn("4 rows", out)
35
+
36
+ def test_null_and_limit(self):
37
+ buf = io.StringIO()
38
+ show(self.conn, "SELECT name, category FROM products ORDER BY id", limit=2, stream=buf)
39
+ out = buf.getvalue()
40
+ self.assertIn("2 of 4 rows shown", out)
41
+ buf = io.StringIO()
42
+ show(self.conn, "SELECT category FROM products WHERE id = 4", stream=buf)
43
+ self.assertIn("NULL", buf.getvalue())
44
+ self.assertIn("1 row\n", buf.getvalue())
45
+
46
+ def test_params(self):
47
+ headers, rows = run(self.conn, "SELECT name FROM products WHERE price > ?", (50,))
48
+ self.assertEqual(headers, ["name"])
49
+ self.assertEqual(sorted(rows), [("Chair",), ("Desk",)])
50
+
51
+ def test_truncation(self):
52
+ t = format_table(["x"], [("a" * 100,)], max_width=10)
53
+ self.assertIn("aaaaaaa...", t)
54
+
55
+ def test_no_result_set(self):
56
+ buf = io.StringIO()
57
+ show(self.conn, "CREATE TABLE t (a INTEGER)", stream=buf)
58
+ self.assertIn("no result set", buf.getvalue())
59
+
60
+
61
+ class CompareTests(unittest.TestCase):
62
+ def setUp(self):
63
+ self.conn = make_db()
64
+
65
+ def cmp(self, a, b, **kw):
66
+ buf = io.StringIO()
67
+ return compare(self.conn, a, b, stream=buf, **kw), buf.getvalue()
68
+
69
+ def test_equivalent_queries_match(self):
70
+ r, out = self.cmp(
71
+ "SELECT name FROM products WHERE price > 50",
72
+ "SELECT name FROM products WHERE NOT price <= 50",
73
+ )
74
+ self.assertTrue(r)
75
+ self.assertIn("MATCH", out)
76
+
77
+ def test_order_ignored_by_default(self):
78
+ r, _ = self.cmp(
79
+ "SELECT name FROM products ORDER BY name",
80
+ "SELECT name FROM products ORDER BY id",
81
+ )
82
+ self.assertTrue(r)
83
+
84
+ def test_order_checked_when_asked(self):
85
+ r, out = self.cmp(
86
+ "SELECT name FROM products ORDER BY name",
87
+ "SELECT name FROM products ORDER BY id",
88
+ ordered=True,
89
+ )
90
+ self.assertFalse(r)
91
+ self.assertIn("different order", out)
92
+
93
+ def test_missing_and_extra(self):
94
+ r, out = self.cmp(
95
+ "SELECT name FROM products WHERE price > 10",
96
+ "SELECT name FROM products WHERE price > 50",
97
+ )
98
+ self.assertFalse(r)
99
+ self.assertEqual(r.extra, [("Lamp",)])
100
+ self.assertEqual(r.missing, [])
101
+ self.assertIn("Extra rows", out)
102
+
103
+ def test_column_count(self):
104
+ r, out = self.cmp("SELECT name, price FROM products", "SELECT name FROM products")
105
+ self.assertFalse(r)
106
+ self.assertIn("number of columns", out)
107
+
108
+ def test_duplicates_matter(self):
109
+ r, _ = self.cmp(
110
+ "SELECT category FROM products",
111
+ "SELECT DISTINCT category FROM products",
112
+ )
113
+ self.assertFalse(r)
114
+
115
+ def test_float_rounding(self):
116
+ r, _ = self.cmp("SELECT 0.1 + 0.2", "SELECT 0.3")
117
+ self.assertTrue(r)
118
+
119
+ def test_column_names(self):
120
+ r, _ = self.cmp("SELECT name AS n FROM products", "SELECT name FROM products")
121
+ self.assertTrue(r)
122
+ r, _ = self.cmp(
123
+ "SELECT name AS n FROM products", "SELECT name FROM products",
124
+ check_column_names=True,
125
+ )
126
+ self.assertFalse(r)
127
+
128
+ def test_nulls_sort_safely(self):
129
+ r, _ = self.cmp(
130
+ "SELECT category FROM products WHERE id > 1",
131
+ "SELECT category FROM products",
132
+ )
133
+ self.assertFalse(r)
134
+ self.assertEqual(r.missing, [("office",)])
135
+
136
+
137
+ class CliTests(unittest.TestCase):
138
+ def test_cli_with_file(self):
139
+ import os
140
+ import tempfile
141
+
142
+ with tempfile.TemporaryDirectory() as d:
143
+ path = os.path.join(d, "t.db")
144
+ c = sqlite3.connect(path)
145
+ c.executescript("CREATE TABLE t (a INTEGER); INSERT INTO t VALUES (1), (2);")
146
+ c.commit()
147
+ c.close()
148
+ import contextlib
149
+
150
+ buf = io.StringIO()
151
+ with contextlib.redirect_stdout(buf):
152
+ self.assertEqual(main([path, "SELECT a FROM t"]), 0)
153
+ self.assertEqual(main([path, "SELECT a FROM t", "--expected", "SELECT a FROM t"]), 0)
154
+ self.assertEqual(main([path, "SELECT a FROM t", "--expected", "SELECT 1"]), 1)
155
+ self.assertIn("2 rows", buf.getvalue())
156
+
157
+
158
+ if __name__ == "__main__":
159
+ unittest.main()