Skip to content

Commit 0c1165e

Browse files
committed
Centralize DBCursor. Remove ignore-errors.
1 parent 3630c12 commit 0c1165e

7 files changed

Lines changed: 25 additions & 48 deletions

File tree

litecli/packages/special/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# ruff: noqa
2-
# mypy: ignore-errors
32

43
from __future__ import annotations
54

litecli/packages/special/dbcommands.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,17 @@
88
import sys
99
import platform
1010
import shlex
11-
from typing import Any, List, Optional, Tuple, Protocol, Sequence
11+
from typing import Any, List, Optional, Tuple
1212

1313

1414
from litecli import __version__
1515
from litecli.packages.special import iocommands
1616
from .main import special_command, RAW_QUERY, PARSED_QUERY
17+
from .types import DBCursor
1718

1819
log = logging.getLogger(__name__)
1920

2021

21-
class DBCursor(Protocol):
22-
description: Optional[Sequence[Sequence[Any]]]
23-
24-
def execute(self, sql: str, params: Any = ...) -> Any: ...
25-
26-
def fetchall(self) -> List[Tuple[Any, ...]]: ...
27-
28-
def fetchone(self) -> Optional[Tuple[Any, ...]]: ...
29-
30-
3122
@special_command(
3223
".tables",
3324
"\\dt",

litecli/packages/special/favoritequeries.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# -*- coding: utf-8 -*-
2-
# mypy: ignore-errors
32
from __future__ import annotations
43

54
from typing import Any, List, Optional

litecli/packages/special/iocommands.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# mypy: ignore-errors
2-
31
from __future__ import annotations
42

53
import locale
@@ -10,7 +8,7 @@
108
import subprocess
119
from io import open
1210
from time import sleep
13-
from typing import Any, Dict, Generator, List, Optional, Tuple, TextIO
11+
from typing import Any, Generator, List, Optional, Tuple, TextIO
1412

1513
import click
1614
import sqlparse
@@ -115,8 +113,9 @@ def editor_command(command: str) -> bool:
115113
@export
116114
def get_filename(sql: str) -> Optional[str]:
117115
if sql.strip().startswith("\\e"):
118-
command, _, filename = sql.partition(" ")
116+
_cmd, _sep, filename = sql.partition(" ")
119117
return filename.strip() or None
118+
return None
120119

121120

122121
@export
@@ -188,7 +187,7 @@ def execute_favorite_query(cur: Any, arg: str, verbose: bool = False, **_: Any)
188187
yield result
189188

190189
"""Parse out favorite name and optional substitution parameters"""
191-
name, _, arg_str = arg.partition(" ")
190+
name, _sep, arg_str = arg.partition(" ")
192191
args = shlex.split(arg_str)
193192

194193
query = favoritequeries.get(name)
@@ -269,7 +268,7 @@ def save_favorite_query(arg: str, **_: Any) -> List[Tuple]:
269268
if not arg:
270269
return [(None, None, None, usage)]
271270

272-
name, _, query = arg.partition(" ")
271+
name, _sep, query = arg.partition(" ")
273272

274273
# If either name or query is missing then print the usage and complain.
275274
if (not name) or (not query):
@@ -310,19 +309,21 @@ def execute_system_command(arg: str, **_: Any) -> List[Tuple]:
310309
args = arg.split(" ")
311310
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
312311
output, error = process.communicate()
313-
response = output if not error else error
312+
raw = output if not error else error
314313

315314
# Python 3 returns bytes. This needs to be decoded to a string.
316-
if isinstance(response, bytes):
315+
if isinstance(raw, bytes):
317316
encoding = locale.getpreferredencoding(False)
318-
response = response.decode(encoding)
317+
response = raw.decode(encoding)
318+
else:
319+
response = raw
319320

320321
return [(None, None, None, response)]
321322
except OSError as e:
322323
return [(None, None, None, "OSError: %s" % e.strerror)]
323324

324325

325-
def parseargfile(arg: str) -> Dict[str, str]:
326+
def parseargfile(arg: str) -> Tuple[str, str]:
326327
if arg.startswith("-o "):
327328
mode = "w"
328329
filename = arg[3:]
@@ -333,7 +334,7 @@ def parseargfile(arg: str) -> Dict[str, str]:
333334
if not filename:
334335
raise TypeError("You must provide a filename.")
335336

336-
return {"file": os.path.expanduser(filename), "mode": mode}
337+
return (os.path.expanduser(filename), mode)
337338

338339

339340
@special_command(
@@ -346,7 +347,8 @@ def set_tee(arg: str, **_: Any) -> List[Tuple]:
346347
global tee_file
347348

348349
try:
349-
tee_file = open(**parseargfile(arg))
350+
file, mode = parseargfile(arg)
351+
tee_file = open(file, mode)
350352
except (IOError, OSError) as e:
351353
raise OSError("Cannot write to file '{}': {}".format(e.filename, e.strerror))
352354

@@ -409,7 +411,8 @@ def unset_once_if_written() -> None:
409411
global once_file, written_to_once_file
410412
if once_file and written_to_once_file:
411413
once_file.close()
412-
once_file = written_to_once_file = None
414+
once_file = None
415+
written_to_once_file = False
413416

414417

415418
@special_command(
@@ -453,7 +456,7 @@ def write_pipe_once(output: str) -> None:
453456
def unset_pipe_once_if_written() -> None:
454457
"""Unset the pipe_once cmd, if it has been written to."""
455458
global pipe_once_process, written_to_pipe_once_process
456-
if written_to_pipe_once_process:
459+
if written_to_pipe_once_process and pipe_once_process:
457460
(stdout_data, stderr_data) = pipe_once_process.communicate()
458461
if len(stdout_data) > 0:
459462
print(stdout_data.rstrip("\n"))

litecli/packages/special/llm.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@
1616
import sys
1717
from runpy import run_module
1818
from time import time
19-
from typing import Any, Dict, List, Optional, Tuple, Protocol, Sequence
19+
from typing import Any, Dict, List, Optional, Tuple
2020

2121
import click
2222
import llm
2323
from llm.cli import cli
2424

2525
from . import export
2626
from .main import Verbosity, parse_special_command
27+
from .types import DBCursor
2728

2829
log = logging.getLogger(__name__)
2930

@@ -218,17 +219,6 @@ def ensure_litecli_template(replace: bool = False) -> None:
218219
return
219220

220221

221-
@export
222-
class DBCursor(Protocol):
223-
description: Optional[Sequence[Sequence[Any]]]
224-
225-
def execute(self, sql: str, params: Any = ...) -> Any: ...
226-
227-
def fetchall(self) -> List[Tuple[Any, ...]]: ...
228-
229-
def fetchone(self) -> Optional[Tuple[Any, ...]]: ...
230-
231-
232222
@export
233223
def handle_llm(text: str, cur: DBCursor) -> Tuple[str, Optional[str], float]:
234224
"""This function handles the special command `\\llm`.

litecli/packages/special/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# mypy: ignore-errors
2-
31
from __future__ import annotations
42
import logging
53
from collections import namedtuple
@@ -141,6 +139,8 @@ def execute(cur: Any, sql: str) -> List[Tuple]:
141139
elif special_cmd.arg_type == RAW_QUERY:
142140
return special_cmd.handler(cur=cur, query=sql)
143141

142+
raise CommandNotFound(f"Command type not found: {command}")
143+
144144

145145
@special_command("help", "\\?", "Show this help.", arg_type=NO_QUERY, aliases=("\\?", "?"))
146146
def show_help() -> List[Tuple]: # All the parameters are ignored.

litecli/packages/special/utils.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# mypy: ignore-errors
2-
31
from __future__ import annotations
42

53
from typing import List, Tuple, Optional
@@ -130,8 +128,5 @@ def check_if_sqlitedotcommand(command: str) -> bool:
130128
".width",
131129
]
132130

133-
if isinstance(command, str):
134-
command = command.split(" ", 1)[0].lower()
135-
return command in sqlite3dotcommands
136-
else:
137-
return False
131+
command = command.split(" ", 1)[0].lower()
132+
return command in sqlite3dotcommands

0 commit comments

Comments
 (0)