diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 873d354b7..fdb94bdd3 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -5489,7 +5489,11 @@ def analyze_column( total_rows = db[table].count def truncate(value): - if value_truncate is None or isinstance(value, (float, int)): + if ( + value_truncate is None + or value is None + or isinstance(value, (float, int)) + ): return value value = str(value) if len(value) > value_truncate: @@ -5509,7 +5513,23 @@ def truncate(value): ).fetchone()[0] most_common_results = None least_common_results = None - if num_distinct == 1: + + def sort_key(pair): + # Break ties on count using SQLite's ordering of types - null, + # then numbers, then text, then blobs - so that values of + # different types never need to be compared with each other + value, count = pair + if value is None: + return (count, 0) + if isinstance(value, (int, float)): + return (count, 1, value) + if isinstance(value, str): + return (count, 2, value) + return (count, 3, value) + + # count(distinct) does not count null, but group by gives it a group + num_groups = num_distinct + (1 if num_null else 0) + if num_distinct == 1 and num_null == 0: value = db.execute( f"select {column_quoted} from {table_quoted} limit 1" ).fetchone()[0] @@ -5529,9 +5549,9 @@ def truncate(value): f"limit {common_limit}" ).fetchall() ] - most_common_results.sort(key=lambda p: (p[1], p[0]), reverse=True) + most_common_results.sort(key=sort_key, reverse=True) if least_common: - if num_distinct <= common_limit: + if num_groups <= common_limit: # No need to run the query if it will just return the results in reverse order least_common_results = None else: @@ -5544,7 +5564,7 @@ def truncate(value): f"limit {common_limit}" ).fetchall() ] - least_common_results.sort(key=lambda p: (p[1], p[0])) + least_common_results.sort(key=sort_key) return ColumnDetails( self.name, column, diff --git a/tests/test_analyze_tables.py b/tests/test_analyze_tables.py index 9e4799cd9..d2deb9e21 100644 --- a/tests/test_analyze_tables.py +++ b/tests/test_analyze_tables.py @@ -317,3 +317,104 @@ def test_analyze_table_validate_columns(tmpdir, args, expected_error): assert result.exit_code == (1 if expected_error else 0) if expected_error: assert expected_error in result.output + + +@pytest.mark.parametrize("value_truncate", (None, 80)) +def test_analyze_column_nulls_plus_one_value(fresh_db, value_truncate): + # https://github.com/simonw/sqlite-utils/issues/887 + # count(distinct) ignores nulls, so this must not take the + # "single distinct value" shortcut + fresh_db.table("t").insert_all([{"c": None}, {"c": None}, {"c": "a"}, {"c": "a"}]) + details = fresh_db.table("t").analyze_column("c", value_truncate=value_truncate) + assert details.num_null == 2 + assert details.num_distinct == 1 + assert details.most_common == [("a", 2), (None, 2)] + assert details.least_common is None + + +def test_analyze_column_null_tied_with_string(fresh_db): + fresh_db.table("t").insert_all( + [{"c": None}, {"c": "a"}] + [{"c": c} for c in "bcdefg" for _ in range(2)] + ) + details = fresh_db.table("t").analyze_column("c", common_limit=5) + assert details.most_common == [ + ("f", 2), + ("e", 2), + ("d", 2), + ("c", 2), + ("b", 2), + ] + assert details.least_common == [ + (None, 1), + ("a", 1), + ("e", 2), + ("f", 2), + ("g", 2), + ] + + +def test_analyze_column_null_tied_in_most_common(fresh_db): + fresh_db.table("t").insert_all([{"c": None}, {"c": "a"}, {"c": "b"}, {"c": "b"}]) + details = fresh_db.table("t").analyze_column("c") + assert details.most_common == [("b", 2), ("a", 1), (None, 1)] + + +def test_analyze_column_mixed_types_tied(fresh_db): + # A column with no type affinity can hold integers, text and blobs + fresh_db.execute("create table t (c)") + fresh_db.execute( + "insert into t values (1), (1), ('a'), ('a'), (x'00'), (x'00'), (2), (null)" + ) + details = fresh_db.table("t").analyze_column("c", common_limit=3) + # Ties are ordered by SQLite's ordering of types: null, numbers, text, blobs + assert details.most_common == [(b"\x00", 2), ("a", 2), (1, 2)] + assert details.least_common == [(None, 1), (2, 1), (b"\x00", 2)] + + +def test_analyze_column_truncate_preserves_null(fresh_db): + fresh_db.table("t").insert_all( + [{"c": None}, {"c": None}, {"c": "None"}, {"c": "x"}] + ) + details = fresh_db.table("t").analyze_column("c", value_truncate=80) + assert details.most_common == [(None, 2), ("x", 1), ("None", 1)] + + +def test_analyze_column_least_common_counts_null_group(fresh_db): + # Two distinct values plus null is three groups, more than common_limit=2, + # so least_common is needed to show "b" + fresh_db.table("t").insert_all( + [{"c": None}, {"c": None}, {"c": None}, {"c": "a"}, {"c": "a"}, {"c": "b"}] + ) + details = fresh_db.table("t").analyze_column("c", common_limit=2) + assert details.most_common == [(None, 3), ("a", 2)] + assert details.least_common == [("b", 1), ("a", 2)] + + +def test_analyze_column_num_distinct_excludes_null(fresh_db): + # num_distinct follows SQL count(distinct), which does not count null + fresh_db.table("t").insert_all([{"c": None}, {"c": "a"}, {"c": "b"}]) + details = fresh_db.table("t").analyze_column("c") + assert details.num_null == 1 + assert details.num_distinct == 2 + assert details.most_common == [("b", 1), ("a", 1), (None, 1)] + + +def test_analyze_table_nulls_plus_one_value(tmpdir): + path = str(tmpdir / "nulls.db") + db = Database(path) + db.table("t").insert_all([{"c": None}, {"c": None}, {"c": "a"}, {"c": "a"}]) + result = CliRunner().invoke(cli.cli, ["analyze-tables", path, "--save"]) + assert result.exit_code == 0 + assert result.output == ( + "t.c: (1/1)\n\n" + " Total rows: 4\n" + " Null rows: 2\n" + " Blank rows: 0\n" + "\n" + " Distinct values: 1\n\n" + " Most common:\n" + " 2: a\n" + " 2: None\n\n" + ) + rows = list(Database(path).table("_analyze_tables_").rows) + assert rows[0]["most_common"] == '[["a", 2], [null, 2]]'