Skip to content

Commit

Permalink
Format with Black, remove unused imports, fix implicitly concatenated…
Browse files Browse the repository at this point in the history
… string
  • Loading branch information
hugovk committed Nov 24, 2024
1 parent 15f1593 commit 9c9fdc3
Show file tree
Hide file tree
Showing 11 changed files with 95 additions and 112 deletions.
102 changes: 59 additions & 43 deletions docs/tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,21 @@
}
],
"source": [
"db[\"creatures\"].insert_all([{\n",
" \"name\": \"Cleo\",\n",
" \"species\": \"dog\",\n",
" \"age\": 6\n",
"}, {\n",
" \"name\": \"Lila\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
"}, {\n",
" \"name\": \"Bants\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
"}])"
"db[\"creatures\"].insert_all(\n",
" [\n",
" {\"name\": \"Cleo\", \"species\": \"dog\", \"age\": 6},\n",
" {\n",
" \"name\": \"Lila\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
" },\n",
" {\n",
" \"name\": \"Bants\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
" },\n",
" ]\n",
")"
]
},
{
Expand Down Expand Up @@ -341,7 +343,9 @@
}
],
"source": [
"list(db.query(\"select * from creatures where species = :species\", {\"species\": \"chicken\"}))"
"list(\n",
" db.query(\"select * from creatures where species = :species\", {\"species\": \"chicken\"})\n",
")"
]
},
{
Expand Down Expand Up @@ -506,22 +510,24 @@
}
],
"source": [
"db[\"creatures\"].insert_all([{\n",
" \"id\": 1,\n",
" \"name\": \"Cleo\",\n",
" \"species\": \"dog\",\n",
" \"age\": 6\n",
"}, {\n",
" \"id\": 2,\n",
" \"name\": \"Lila\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
"}, {\n",
" \"id\": 3,\n",
" \"name\": \"Bants\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
"}], pk=\"id\")"
"db[\"creatures\"].insert_all(\n",
" [\n",
" {\"id\": 1, \"name\": \"Cleo\", \"species\": \"dog\", \"age\": 6},\n",
" {\n",
" \"id\": 2,\n",
" \"name\": \"Lila\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
" },\n",
" {\n",
" \"id\": 3,\n",
" \"name\": \"Bants\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
" },\n",
" ],\n",
" pk=\"id\",\n",
")"
]
},
{
Expand Down Expand Up @@ -575,17 +581,23 @@
}
],
"source": [
"table.insert_all([{\n",
" \"id\": 4,\n",
" \"name\": \"Azi\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
"}, {\n",
" \"id\": 5,\n",
" \"name\": \"Snowy\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.9,\n",
"}], pk=\"id\")"
"table.insert_all(\n",
" [\n",
" {\n",
" \"id\": 4,\n",
" \"name\": \"Azi\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.8,\n",
" },\n",
" {\n",
" \"id\": 5,\n",
" \"name\": \"Snowy\",\n",
" \"species\": \"chicken\",\n",
" \"age\": 0.9,\n",
" },\n",
" ],\n",
" pk=\"id\",\n",
")"
]
},
{
Expand Down Expand Up @@ -1006,7 +1018,9 @@
}
],
"source": [
"list(db.query(\"\"\"\n",
"list(\n",
" db.query(\n",
" \"\"\"\n",
" select\n",
" creatures.id,\n",
" creatures.name,\n",
Expand All @@ -1015,7 +1029,9 @@
" species.species\n",
" from creatures\n",
" join species on creatures.species_id = species.id\n",
"\"\"\"))"
"\"\"\"\n",
" )\n",
")"
]
},
{
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from setuptools import setup, find_packages
import io
import os

VERSION = "3.38"
Expand Down
4 changes: 1 addition & 3 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2137,9 +2137,7 @@ def search(
table_columns = table_obj.columns_dict
for c in column:
if c not in table_columns:
raise click.ClickException(
f"Table '{dbtable}' has no column '{c}"
)
raise click.ClickException(f"Table '{dbtable}' has no column '{c}")
sql = table_obj.search_sql(columns=column, order_by=order, limit=limit)
if show_sql:
click.echo(sql)
Expand Down
45 changes: 12 additions & 33 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,8 @@
cast,
Any,
Callable,
Dict,
Union,
Optional,
List,
Tuple,
)
from collections.abc import Generator, Iterable
import uuid
Expand Down Expand Up @@ -590,9 +587,7 @@ def quote_fts(self, query: str) -> str:
query += '"'
bits = _quote_fts_re.split(query)
bits = [b for b in bits if b and b != '""']
return " ".join(
f'"{bit}"' if not bit.startswith('"') else bit for bit in bits
)
return " ".join(f'"{bit}"' if not bit.startswith('"') else bit for bit in bits)

def quote_default_value(self, value: str) -> str:
if any(
Expand Down Expand Up @@ -680,9 +675,7 @@ def supports_strict(self) -> bool:
try:
table_name = f"t{secrets.token_hex(16)}"
with self.conn:
self.conn.execute(
f"create table {table_name} (name text) strict"
)
self.conn.execute(f"create table {table_name} (name text) strict")
self.conn.execute(f"drop table {table_name}")
return True
except Exception:
Expand Down Expand Up @@ -907,9 +900,7 @@ def sort_key(p):
if fk.other_column != "rowid" and not any(
c for c in self[fk.other_table].columns if c.name == fk.other_column
):
raise AlterError(
f"No such column: {fk.other_table}.{fk.other_column}"
)
raise AlterError(f"No such column: {fk.other_table}.{fk.other_column}")

column_defs = []
# ensure pk is a tuple
Expand Down Expand Up @@ -1592,9 +1583,7 @@ def indexes(self) -> list[Index]:
for row in self.db.execute_returning_dicts(sql):
index_name = row["name"]
index_name_quoted = (
f'"{index_name}"'
if not index_name.startswith('"')
else index_name
f'"{index_name}"' if not index_name.startswith('"') else index_name
)
column_sql = f"PRAGMA index_info({index_name_quoted})"
columns = []
Expand All @@ -1616,9 +1605,7 @@ def xindexes(self) -> list[XIndex]:
for row in self.db.execute_returning_dicts(sql):
index_name = row["name"]
index_name_quoted = (
f'"{index_name}"'
if not index_name.startswith('"')
else index_name
f'"{index_name}"' if not index_name.startswith('"') else index_name
)
column_sql = f"PRAGMA index_xinfo({index_name_quoted})"
index_columns = []
Expand Down Expand Up @@ -1971,15 +1958,11 @@ def transform_sql(
sqls.append(copy_sql)
# Drop (or keep) the old table
if keep_table:
sqls.append(
f"ALTER TABLE [{self.name}] RENAME TO [{keep_table}];"
)
sqls.append(f"ALTER TABLE [{self.name}] RENAME TO [{keep_table}];")
else:
sqls.append(f"DROP TABLE [{self.name}];")
# Rename the new one
sqls.append(
f"ALTER TABLE [{new_table_name}] RENAME TO [{self.name}];"
)
sqls.append(f"ALTER TABLE [{new_table_name}] RENAME TO [{self.name}];")
# Re-add existing indexes
for index in self.indexes:
if index.origin != "pk":
Expand Down Expand Up @@ -2152,9 +2135,7 @@ def create_index(
suffix = None
created_index_name = None
while True:
created_index_name = (
f"{index_name}_{suffix}" if suffix else index_name
)
created_index_name = f"{index_name}_{suffix}" if suffix else index_name
sql = (
textwrap.dedent(
"""
Expand Down Expand Up @@ -2510,9 +2491,7 @@ def populate_fts(self, columns: Iterable[str]) -> "Table":
"""
)
.strip()
.format(
table=self.name, columns=", ".join(f"[{c}]" for c in columns)
)
.format(table=self.name, columns=", ".join(f"[{c}]" for c in columns))
)
self.db.executescript(sql)
return self
Expand Down Expand Up @@ -3677,9 +3656,9 @@ def truncate(value):
most_common_results = None
least_common_results = None
if num_distinct == 1:
value = db.execute(
f"select [{column}] from [{table}] limit 1"
).fetchone()[0]
value = db.execute(f"select [{column}] from [{table}] limit 1").fetchone()[
0
]
most_common_results = [(truncate(value), total_rows)]
elif num_distinct != total_rows:
if most_common:
Expand Down
6 changes: 2 additions & 4 deletions sqlite_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import os
import sys
from . import recipes
from typing import Dict, cast, BinaryIO, Optional, Tuple, Type
from typing import cast, BinaryIO, Optional
from collections.abc import Iterable

import click
Expand Down Expand Up @@ -226,9 +226,7 @@ def _extra_key_strategy(
yield row
elif not extras_key:
extras = row.pop(None) # type: ignore
raise RowError(
f"Row {row} contained these extra values: {extras}"
)
raise RowError(f"Row {row} contained these extra values: {extras}")
else:
row[extras_key] = row.pop(None) # type: ignore
yield row
Expand Down
24 changes: 12 additions & 12 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,14 +845,14 @@ def test_query_json_binary(db_path):
"data": {
"$base64": True,
"encoded": (
"eJzt0c1xAyEMBeC7q1ABHleR3HxNAQrIjmb4M0gelx+RTY7p4N2WBYT0vmufUknH"
"8kq5lz5pqRFXsTOl3pYkE/NJnHXoStruJEVjc0mOCyTqq/ZMJnXEZW1Js2ZvRm5U+"
"DPKk9hRWqjyvTFx0YfzhT6MpGmN2lR1fzxjyfVMD9dFrS+bnkleMpMam/ZGXgrX1I"
"/K+5Au3S/9lNQRh0k4Gq/RUz8GiKfsQm+7JLsJ6fTo5JhVG00ZU76kZZkxePx49uI"
"jnpNoJyYlWUsoaSl/CcVATje/Kxu13RANnrHweaH3V5Jh4jvGyKCnxJLiXPKhmW3f"
"iCnG7Jql7RR3UvFo8jJ4z039dtOkTFmWzL1be9lt8A5II471m6vXy+l0BR/4wAc+8"
"IEPfOADH/jABz7wgQ984AMf+MAHPvCBD3zgAx/4wAc+8IEPfOADH/jABz7wgQ984A"
"Mf+MAHPvCBD3zgAx/4wAc+8IEPfOADH/jABz7wgQ984PuP7xubBoN9"
"eJzt0c1xAyEMBeC7q1ABHleR3HxNAQrIjmb4M0gelx+RTY7p4N2WBYT0vmufUknH"
"8kq5lz5pqRFXsTOl3pYkE/NJnHXoStruJEVjc0mOCyTqq/ZMJnXEZW1Js2ZvRm5U+"
"DPKk9hRWqjyvTFx0YfzhT6MpGmN2lR1fzxjyfVMD9dFrS+bnkleMpMam/ZGXgrX1I"
"/K+5Au3S/9lNQRh0k4Gq/RUz8GiKfsQm+7JLsJ6fTo5JhVG00ZU76kZZkxePx49uI"
"jnpNoJyYlWUsoaSl/CcVATje/Kxu13RANnrHweaH3V5Jh4jvGyKCnxJLiXPKhmW3f"
"iCnG7Jql7RR3UvFo8jJ4z039dtOkTFmWzL1be9lt8A5II471m6vXy+l0BR/4wAc+8"
"IEPfOADH/jABz7wgQ984AMf+MAHPvCBD3zgAx/4wAc+8IEPfOADH/jABz7wgQ984A"
"Mf+MAHPvCBD3zgAx/4wAc+8IEPfOADH/jABz7wgQ984PuP7xubBoN9"
),
},
}
Expand Down Expand Up @@ -1171,12 +1171,12 @@ def test_upsert_alter(db_path, tmpdir):
# Not null:
(
["name", "text", "--not-null", "name"],
("CREATE TABLE [t] (\n" " [name] TEXT NOT NULL\n" ")"),
("CREATE TABLE [t] (\n [name] TEXT NOT NULL\n)"),
),
# Default:
(
["age", "integer", "--default", "age", "3"],
("CREATE TABLE [t] (\n" " [age] INTEGER DEFAULT '3'\n" ")"),
("CREATE TABLE [t] (\n [age] INTEGER DEFAULT '3'\n)"),
),
# Compound primary key
(
Expand Down Expand Up @@ -2052,7 +2052,7 @@ def test_triggers(tmpdir, extra_args, expected):
),
(
["dogs"],
("CREATE TABLE [dogs] (\n" " [id] INTEGER,\n" " [name] TEXT\n" ")\n"),
("CREATE TABLE [dogs] (\n [id] INTEGER,\n [name] TEXT\n)\n"),
),
(
["chickens", "dogs"],
Expand Down Expand Up @@ -2328,7 +2328,7 @@ def test_rename_table(tmpdir):
)
assert result_error.exit_code == 1
assert result_error.output == (
'Error: Table "missing" could not be renamed. ' "no such table: missing\n"
'Error: Table "missing" could not be renamed. no such table: missing\n'
)
# And check --ignore works
result_error2 = CliRunner().invoke(
Expand Down
3 changes: 1 addition & 2 deletions tests/test_cli_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,7 @@ def test_insert_multiple_with_compound_primary_key(db_path, tmpdir):
def test_insert_not_null_default(db_path, tmpdir):
json_path = str(tmpdir / "dogs.json")
dogs = [
{"id": i, "name": f"Cleo {i}", "age": i + 3, "score": 10}
for i in range(1, 21)
{"id": i, "name": f"Cleo {i}", "age": i + 3, "score": 10} for i in range(1, 21)
]
with open(json_path, "w") as fp:
fp.write(json.dumps(dogs))
Expand Down
2 changes: 1 addition & 1 deletion tests/test_cli_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def test_memory_json_nl(tmpdir, use_stdin):
@pytest.mark.parametrize("use_stdin", (True, False))
def test_memory_csv_encoding(tmpdir, use_stdin):
latin1_csv = (
b"date,name,latitude,longitude\n" b"2020-03-04,S\xe3o Paulo,-23.561,-46.645\n"
b"date,name,latitude,longitude\n2020-03-04,S\xe3o Paulo,-23.561,-46.645\n"
)
input = None
if use_stdin:
Expand Down
Loading

0 comments on commit 9c9fdc3

Please sign in to comment.