Reformat with black 26.1.0

This commit is contained in:
Claude 2026-01-21 15:23:44 +00:00
commit cb33bec699
No known key found for this signature in database
12 changed files with 48 additions and 114 deletions

View file

@ -42,7 +42,6 @@ from .utils import (
TypeTracker, TypeTracker,
) )
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@ -2919,8 +2918,7 @@ def _analyze(db, tables, columns, save, common_limit=10, no_most=False, no_least
) )
details = ( details = (
( (
textwrap.dedent( textwrap.dedent("""
"""
{table}.{column}: ({i}/{total}) {table}.{column}: ({i}/{total})
Total rows: {total_rows} Total rows: {total_rows}
@ -2928,8 +2926,7 @@ def _analyze(db, tables, columns, save, common_limit=10, no_most=False, no_least
Blank rows: {num_blank} Blank rows: {num_blank}
Distinct values: {num_distinct}{most_common_rendered}{least_common_rendered} Distinct values: {num_distinct}{most_common_rendered}{least_common_rendered}
""" """)
)
.strip() .strip()
.format( .format(
i=i + 1, i=i + 1,
@ -2976,8 +2973,7 @@ def uninstall(packages, yes):
def _generate_convert_help(): def _generate_convert_help():
help = textwrap.dedent( help = textwrap.dedent("""
"""
Convert columns using Python code you supply. For example: Convert columns using Python code you supply. For example:
\b \b
@ -2990,8 +2986,7 @@ def _generate_convert_help():
Use "-" for CODE to read Python code from standard input. Use "-" for CODE to read Python code from standard input.
The following common operations are available as recipe functions: The following common operations are available as recipe functions:
""" """).strip()
).strip()
recipe_names = [ recipe_names = [
n n
for n in dir(recipes) for n in dir(recipes)
@ -3005,15 +3000,13 @@ def _generate_convert_help():
name, str(inspect.signature(fn)), textwrap.dedent(fn.__doc__.rstrip()) name, str(inspect.signature(fn)), textwrap.dedent(fn.__doc__.rstrip())
) )
help += "\n\n" help += "\n\n"
help += textwrap.dedent( help += textwrap.dedent("""
"""
You can use these recipes like so: You can use these recipes like so:
\b \b
sqlite-utils convert my.db mytable mycolumn \\ sqlite-utils convert my.db mytable mycolumn \\
'r.jsonsplit(value, delimiter=":")' 'r.jsonsplit(value, delimiter=":")'
""" """).strip()
).strip()
return help return help

View file

@ -2348,12 +2348,10 @@ class Table(Queryable):
"{}_{}".format(index_name, suffix) if suffix else index_name "{}_{}".format(index_name, suffix) if suffix else index_name
) )
sql = ( sql = (
textwrap.dedent( textwrap.dedent("""
"""
CREATE {unique}INDEX {if_not_exists}{index_name} CREATE {unique}INDEX {if_not_exists}{index_name}
ON {table_name} ({columns}); ON {table_name} ({columns});
""" """)
)
.strip() .strip()
.format( .format(
index_name=quote_identifier(created_index_name), index_name=quote_identifier(created_index_name),
@ -2548,8 +2546,7 @@ class Table(Queryable):
See :ref:`python_api_cached_table_counts` for details. See :ref:`python_api_cached_table_counts` for details.
""" """
sql = ( sql = (
textwrap.dedent( textwrap.dedent("""
"""
{create_counts_table} {create_counts_table}
CREATE TRIGGER IF NOT EXISTS {trigger_insert} AFTER INSERT ON {table} CREATE TRIGGER IF NOT EXISTS {trigger_insert} AFTER INSERT ON {table}
BEGIN BEGIN
@ -2574,8 +2571,7 @@ class Table(Queryable):
); );
END; END;
INSERT OR REPLACE INTO _counts VALUES ({table_quoted}, (select count(*) from {table})); INSERT OR REPLACE INTO _counts VALUES ({table_quoted}, (select count(*) from {table}));
""" """)
)
.strip() .strip()
.format( .format(
create_counts_table=_COUNTS_TABLE_CREATE_SQL.format( create_counts_table=_COUNTS_TABLE_CREATE_SQL.format(
@ -2627,14 +2623,12 @@ class Table(Queryable):
:param replace: Should any existing FTS index for this table be replaced by the new one? :param replace: Should any existing FTS index for this table be replaced by the new one?
""" """
create_fts_sql = ( create_fts_sql = (
textwrap.dedent( textwrap.dedent("""
"""
CREATE VIRTUAL TABLE {table_fts} USING {fts_version} ( CREATE VIRTUAL TABLE {table_fts} USING {fts_version} (
{columns},{tokenize} {columns},{tokenize}
content={table} content={table}
) )
""" """)
)
.strip() .strip()
.format( .format(
table=quote_identifier(self.name), table=quote_identifier(self.name),
@ -2672,8 +2666,7 @@ class Table(Queryable):
table = quote_identifier(self.name) table = quote_identifier(self.name)
table_fts = quote_identifier(self.name + "_fts") table_fts = quote_identifier(self.name + "_fts")
triggers = ( triggers = (
textwrap.dedent( textwrap.dedent("""
"""
CREATE TRIGGER {table_ai} AFTER INSERT ON {table} BEGIN CREATE TRIGGER {table_ai} AFTER INSERT ON {table} BEGIN
INSERT INTO {table_fts} (rowid, {columns}) VALUES (new.rowid, {new_cols}); INSERT INTO {table_fts} (rowid, {columns}) VALUES (new.rowid, {new_cols});
END; END;
@ -2684,8 +2677,7 @@ class Table(Queryable):
INSERT INTO {table_fts} ({table_fts}, rowid, {columns}) VALUES('delete', old.rowid, {old_cols}); INSERT INTO {table_fts} ({table_fts}, rowid, {columns}) VALUES('delete', old.rowid, {old_cols});
INSERT INTO {table_fts} (rowid, {columns}) VALUES (new.rowid, {new_cols}); INSERT INTO {table_fts} (rowid, {columns}) VALUES (new.rowid, {new_cols});
END; END;
""" """)
)
.strip() .strip()
.format( .format(
table=table, table=table,
@ -2710,12 +2702,10 @@ class Table(Queryable):
""" """
columns_quoted = ", ".join(quote_identifier(c) for c in columns) columns_quoted = ", ".join(quote_identifier(c) for c in columns)
sql = ( sql = (
textwrap.dedent( textwrap.dedent("""
"""
INSERT INTO {table_fts} (rowid, {columns}) INSERT INTO {table_fts} (rowid, {columns})
SELECT rowid, {columns} FROM {table}; SELECT rowid, {columns} FROM {table};
""" """)
)
.strip() .strip()
.format( .format(
table=quote_identifier(self.name), table=quote_identifier(self.name),
@ -2732,17 +2722,11 @@ class Table(Queryable):
if fts_table: if fts_table:
self.db[fts_table].drop() self.db[fts_table].drop()
# Now delete the triggers that related to that table # Now delete the triggers that related to that table
sql = ( sql = textwrap.dedent("""
textwrap.dedent(
"""
SELECT name FROM sqlite_master SELECT name FROM sqlite_master
WHERE type = 'trigger' WHERE type = 'trigger'
AND (sql LIKE '% INSERT INTO [{}]%' OR sql LIKE '% INSERT INTO "{}"%') AND (sql LIKE '% INSERT INTO [{}]%' OR sql LIKE '% INSERT INTO "{}"%')
""" """).strip().format(fts_table, fts_table)
)
.strip()
.format(fts_table, fts_table)
)
trigger_names = [] trigger_names = []
for row in self.db.execute(sql).fetchall(): for row in self.db.execute(sql).fetchall():
trigger_names.append(row[0]) trigger_names.append(row[0])
@ -2768,8 +2752,7 @@ class Table(Queryable):
def detect_fts(self) -> Optional[str]: def detect_fts(self) -> Optional[str]:
"Detect if table has a corresponding FTS virtual table and return it" "Detect if table has a corresponding FTS virtual table and return it"
sql = textwrap.dedent( sql = textwrap.dedent("""
"""
SELECT name FROM sqlite_master SELECT name FROM sqlite_master
WHERE rootpage = 0 WHERE rootpage = 0
AND ( AND (
@ -2780,8 +2763,7 @@ class Table(Queryable):
AND sql LIKE '%VIRTUAL TABLE%USING FTS%' AND sql LIKE '%VIRTUAL TABLE%USING FTS%'
) )
) )
""" """).strip()
).strip()
args = { args = {
"like": '%VIRTUAL TABLE%USING FTS%content="{}"%'.format(self.name), "like": '%VIRTUAL TABLE%USING FTS%content="{}"%'.format(self.name),
"like2": '%VIRTUAL TABLE%USING FTS%content="{}"%'.format(self.name), "like2": '%VIRTUAL TABLE%USING FTS%content="{}"%'.format(self.name),
@ -2797,13 +2779,9 @@ class Table(Queryable):
"Run the ``optimize`` operation against the associated full-text search index table." "Run the ``optimize`` operation against the associated full-text search index table."
fts_table = self.detect_fts() fts_table = self.detect_fts()
if fts_table is not None: if fts_table is not None:
self.db.execute( self.db.execute("""
"""
INSERT INTO {table} ({table}) VALUES ("optimize"); INSERT INTO {table} ({table}) VALUES ("optimize");
""".strip().format( """.strip().format(table=quote_identifier(fts_table)))
table=quote_identifier(fts_table)
)
)
return self return self
def search_sql( def search_sql(
@ -2841,8 +2819,7 @@ class Table(Queryable):
) )
fts_table_quoted = quote_identifier(fts_table) fts_table_quoted = quote_identifier(fts_table)
virtual_table_using = self.db.table(fts_table).virtual_table_using virtual_table_using = self.db.table(fts_table).virtual_table_using
sql = textwrap.dedent( sql = textwrap.dedent("""
"""
with {original} as ( with {original} as (
select select
rowid, rowid,
@ -2859,8 +2836,7 @@ class Table(Queryable):
order by order by
{order_by} {order_by}
{limit_offset} {limit_offset}
""" """).strip()
).strip()
if virtual_table_using == "FTS5": if virtual_table_using == "FTS5":
rank_implementation = "{}.rank".format(fts_table_quoted) rank_implementation = "{}.rank".format(fts_table_quoted)
else: else:

View file

@ -42,14 +42,12 @@ def fresh_db():
@pytest.fixture @pytest.fixture
def existing_db(): def existing_db():
database = Database(memory=True) database = Database(memory=True)
database.executescript( database.executescript("""
"""
CREATE TABLE foo (text TEXT); CREATE TABLE foo (text TEXT);
INSERT INTO foo (text) values ("one"); INSERT INTO foo (text) values ("one");
INSERT INTO foo (text) values ("two"); INSERT INTO foo (text) values ("two");
INSERT INTO foo (text) values ("three"); INSERT INTO foo (text) values ("three");
""" """)
)
return database return database

View file

@ -143,10 +143,7 @@ def db_to_analyze_path(db_to_analyze, tmpdir):
def test_analyze_table(db_to_analyze_path): def test_analyze_table(db_to_analyze_path):
result = CliRunner().invoke(cli.cli, ["analyze-tables", db_to_analyze_path]) result = CliRunner().invoke(cli.cli, ["analyze-tables", db_to_analyze_path])
assert ( assert result.output.strip() == ("""
result.output.strip()
== (
"""
stuff.id: (1/3) stuff.id: (1/3)
Total rows: 8 Total rows: 8
@ -179,9 +176,7 @@ stuff.size: (3/3)
Most common: Most common:
5: 5 5: 5
3: 4""" 3: 4""").strip()
).strip()
)
def test_analyze_table_save(db_to_analyze_path): def test_analyze_table_save(db_to_analyze_path):

View file

@ -967,12 +967,9 @@ def test_query_json_with_json_cols(db_path):
result = CliRunner().invoke( result = CliRunner().invoke(
cli.cli, [db_path, "select id, name, friends from dogs"] cli.cli, [db_path, "select id, name, friends from dogs"]
) )
assert ( assert r"""
r"""
[{"id": 1, "name": "Cleo", "friends": "[{\"name\": \"Pancakes\"}, {\"name\": \"Bailey\"}]"}] [{"id": 1, "name": "Cleo", "friends": "[{\"name\": \"Pancakes\"}, {\"name\": \"Bailey\"}]"}]
""".strip() """.strip() == result.output.strip()
== result.output.strip()
)
# With --json-cols: # With --json-cols:
result = CliRunner().invoke( result = CliRunner().invoke(
cli.cli, [db_path, "select id, name, friends from dogs", "--json-cols"] cli.cli, [db_path, "select id, name, friends from dogs", "--json-cols"]
@ -2038,12 +2035,10 @@ def test_search_quote(tmpdir):
def test_indexes(tmpdir): def test_indexes(tmpdir):
db_path = str(tmpdir / "test.db") db_path = str(tmpdir / "test.db")
db = Database(db_path) db = Database(db_path)
db.conn.executescript( db.conn.executescript("""
"""
create table Gosh (c1 text, c2 text, c3 text); create table Gosh (c1 text, c2 text, c3 text);
create index Gosh_idx on Gosh(c2, c3 desc); create index Gosh_idx on Gosh(c2, c3 desc);
""" """)
)
result = CliRunner().invoke( result = CliRunner().invoke(
cli.cli, cli.cli,
["indexes", str(db_path)], ["indexes", str(db_path)],
@ -2134,16 +2129,12 @@ def test_triggers(tmpdir, extra_args, expected):
pk="id", pk="id",
) )
db["counter"].insert({"count": 1}) db["counter"].insert({"count": 1})
db.conn.execute( db.conn.execute(textwrap.dedent("""
textwrap.dedent(
"""
CREATE TRIGGER blah AFTER INSERT ON articles CREATE TRIGGER blah AFTER INSERT ON articles
BEGIN BEGIN
UPDATE counter SET count = count + 1; UPDATE counter SET count = count + 1;
END END
""" """))
)
)
args = ["triggers", db_path] args = ["triggers", db_path]
if extra_args: if extra_args:
args.extend(extra_args) args.extend(extra_args)

View file

@ -371,16 +371,14 @@ def test_convert_multi_complex_column_types(fresh_db_and_path):
], ],
pk="id", pk="id",
) )
code = textwrap.dedent( code = textwrap.dedent("""
"""
if value == 1: if value == 1:
return {"is_str": "", "is_float": 1.2, "is_int": None} return {"is_str": "", "is_float": 1.2, "is_int": None}
elif value == 2: elif value == 2:
return {"is_float": 1, "is_int": 12} return {"is_float": 1, "is_int": 12}
elif value == 3: elif value == 3:
return {"is_bytes": b"blah"} return {"is_bytes": b"blah"}
""" """)
)
result = CliRunner().invoke( result = CliRunner().invoke(
cli.cli, cli.cli,
[ [

View file

@ -20,7 +20,6 @@ import pathlib
import pytest import pytest
import uuid import uuid
try: try:
import pandas as pd # type: ignore import pandas as pd # type: ignore
except ImportError: except ImportError:

View file

@ -1,6 +1,5 @@
import pytest import pytest
EXAMPLES = [ EXAMPLES = [
("TEXT DEFAULT 'foo'", "'foo'", "'foo'"), ("TEXT DEFAULT 'foo'", "'foo'", "'foo'"),
("TEXT DEFAULT 'foo)'", "'foo)'", "'foo)'"), ("TEXT DEFAULT 'foo)'", "'foo)'", "'foo)'"),

View file

@ -5,14 +5,12 @@ import pytest
def test_duplicate(fresh_db): def test_duplicate(fresh_db):
# Create table using native Sqlite statement: # Create table using native Sqlite statement:
fresh_db.execute( fresh_db.execute("""CREATE TABLE "table1" (
"""CREATE TABLE "table1" (
"text_col" TEXT, "text_col" TEXT,
"real_col" REAL, "real_col" REAL,
"int_col" INTEGER, "int_col" INTEGER,
"bool_col" INTEGER, "bool_col" INTEGER,
"datetime_col" TEXT)""" "datetime_col" TEXT)""")
)
# Insert one row of mock data: # Insert one row of mock data:
dt = datetime.datetime.now() dt = datetime.datetime.now()
data = { data = {

View file

@ -126,9 +126,7 @@ def test_extract_rowid_table(fresh_db):
' "common_name_latin_name_id" INTEGER REFERENCES "common_name_latin_name"("id")\n' ' "common_name_latin_name_id" INTEGER REFERENCES "common_name_latin_name"("id")\n'
")" ")"
) )
assert ( assert fresh_db.execute("""
fresh_db.execute(
"""
select select
tree.name, tree.name,
common_name_latin_name.common_name, common_name_latin_name.common_name,
@ -136,10 +134,7 @@ def test_extract_rowid_table(fresh_db):
from tree from tree
join common_name_latin_name join common_name_latin_name
on tree.common_name_latin_name_id = common_name_latin_name.id on tree.common_name_latin_name_id = common_name_latin_name.id
""" """).fetchall() == [("Tree 1", "Palm", "Arecaceae")]
).fetchall()
== [("Tree 1", "Palm", "Arecaceae")]
)
def test_reuse_lookup_table(fresh_db): def test_reuse_lookup_table(fresh_db):

View file

@ -109,13 +109,11 @@ def test_table_repr(fresh_db):
def test_indexes(fresh_db): def test_indexes(fresh_db):
fresh_db.executescript( fresh_db.executescript("""
"""
create table Gosh (c1 text, c2 text, c3 text); create table Gosh (c1 text, c2 text, c3 text);
create index Gosh_c1 on Gosh(c1); create index Gosh_c1 on Gosh(c1);
create index Gosh_c2c3 on Gosh(c2, c3); create index Gosh_c2c3 on Gosh(c2, c3);
""" """)
)
assert [ assert [
Index( Index(
seq=0, seq=0,
@ -130,13 +128,11 @@ def test_indexes(fresh_db):
def test_xindexes(fresh_db): def test_xindexes(fresh_db):
fresh_db.executescript( fresh_db.executescript("""
"""
create table Gosh (c1 text, c2 text, c3 text); create table Gosh (c1 text, c2 text, c3 text);
create index Gosh_c1 on Gosh(c1); create index Gosh_c1 on Gosh(c1);
create index Gosh_c2c3 on Gosh(c2, c3 desc); create index Gosh_c2c3 on Gosh(c2, c3 desc);
""" """)
)
assert fresh_db["Gosh"].xindexes == [ assert fresh_db["Gosh"].xindexes == [
XIndex( XIndex(
name="Gosh_c2c3", name="Gosh_c2c3",

View file

@ -638,15 +638,13 @@ def test_transform_with_indexes_errors(fresh_db, transform_params):
def test_transform_with_unique_constraint_implicit_index(fresh_db): def test_transform_with_unique_constraint_implicit_index(fresh_db):
dogs = fresh_db["dogs"] dogs = fresh_db["dogs"]
# Create a table with a UNIQUE constraint on 'name', which creates an implicit index # Create a table with a UNIQUE constraint on 'name', which creates an implicit index
fresh_db.execute( fresh_db.execute("""
"""
CREATE TABLE dogs ( CREATE TABLE dogs (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
name TEXT UNIQUE, name TEXT UNIQUE,
age INTEGER age INTEGER
); );
""" """)
)
dogs.insert({"id": 1, "name": "Cleo", "age": 5}) dogs.insert({"id": 1, "name": "Cleo", "age": 5})
# Attempt to transform the table without modifying 'name' # Attempt to transform the table without modifying 'name'
@ -794,15 +792,13 @@ def test_transform_update_incoming_fks_self_referential(fresh_db):
fresh_db.execute("PRAGMA foreign_keys=ON") fresh_db.execute("PRAGMA foreign_keys=ON")
# Create employees table with self-referential FK (manager_id -> id) # Create employees table with self-referential FK (manager_id -> id)
fresh_db.execute( fresh_db.execute("""
"""
CREATE TABLE employees ( CREATE TABLE employees (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
name TEXT, name TEXT,
manager_id INTEGER REFERENCES employees(id) manager_id INTEGER REFERENCES employees(id)
) )
""" """)
)
fresh_db["employees"].insert_all( fresh_db["employees"].insert_all(
[ [
{"id": 1, "name": "CEO", "manager_id": None}, {"id": 1, "name": "CEO", "manager_id": None},