这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions mycli/clitoolbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ def get_toolbar_tokens() -> list[tuple[str, str]]:
delimiter = special.get_current_delimiter()
result.append((
"class:bottom-toolbar",
" ({} [{}] will end the line) ".format("Semi-colon" if delimiter == ";" else "Delimiter", delimiter),
f' ({"Semi-colon" if delimiter == ";" else "Delimiter"} [{delimiter}] will end the line) ',
))

if mycli.multi_line:
result.append(("class:bottom-toolbar.on", "[F3] Multiline: ON "))
else:
result.append(("class:bottom-toolbar.off", "[F3] Multiline: OFF "))
if mycli.prompt_app.editing_mode == EditingMode.VI:
result.append(("class:bottom-toolbar.on", "Vi-mode ({})".format(_get_vi_mode())))
result.append(("class:bottom-toolbar.on", f"Vi-mode ({_get_vi_mode()})"))

if mycli.toolbar_error_message:
result.append(("class:bottom-toolbar", " " + mycli.toolbar_error_message))
Expand Down
2 changes: 1 addition & 1 deletion mycli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def str_to_bool(s: str | bool) -> bool:
elif s.lower() in false_values:
return False
else:
raise ValueError("not a recognized boolean value: {0}".format(s))
raise ValueError(f'not a recognized boolean value: {s}')


def strip_matching_quotes(s: str) -> str:
Expand Down
2 changes: 1 addition & 1 deletion mycli/magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def mycli_line_magic(line: str):
conn._mycli = mycli

# For convenience, print the connection alias
print("Connected: {}".format(conn.name))
print(f'Connected: {conn.name}')

try:
mycli.run_cli()
Expand Down
2 changes: 1 addition & 1 deletion mycli/packages/prompt_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def convert(self, value: bool | str, param: click.Parameter | None, ctx: click.C
return True
if value in ("no", "n"):
return False
self.fail("%s is not a valid boolean" % value, param, ctx)
self.fail(f'{value} is not a valid boolean', param, ctx)

def __repr__(self):
return "BOOL"
Expand Down
26 changes: 13 additions & 13 deletions mycli/packages/special/dbcommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def list_tables(
verbose: bool = False,
) -> list[tuple]:
if arg:
query = "SHOW FIELDS FROM {0}".format(arg)
query = f'SHOW FIELDS FROM {arg}'
else:
query = "SHOW TABLES"
logger.debug(query)
Expand All @@ -36,7 +36,7 @@ def list_tables(
return [(None, None, None, "")]

if verbose and arg:
query = "SHOW CREATE TABLE {0}".format(arg)
query = f'SHOW CREATE TABLE {arg}'
logger.debug(query)
cur.execute(query)
if one := cur.fetchone():
Expand Down Expand Up @@ -93,8 +93,8 @@ def status(cur: Cursor, **_) -> list[tuple]:
implementation = platform.python_implementation()
version = platform.python_version()
client_info = []
client_info.append("mycli {0},".format(__version__))
client_info.append("running on {0} {1}".format(implementation, version))
client_info.append(f'mycli {__version__}')
client_info.append(f'running on {implementation} {version}')
title.append(" ".join(client_info) + "\n")

# Build the output that will be displayed as a table.
Expand All @@ -121,13 +121,13 @@ def status(cur: Cursor, **_) -> list[tuple]:
pager = "stdout"
output.append(("Current pager:", pager))

output.append(("Server version:", "{0} {1}".format(variables["version"], variables["version_comment"])))
output.append(("Server version:", f'{variables["version"]} {variables["version_comment"]}'))
output.append(("Protocol version:", variables["protocol_version"]))

if "unix" in cur.connection.host_info.lower():
host_info = cur.connection.host_info
else:
host_info = "{0} via TCP/IP".format(cur.connection.host)
host_info = f'{cur.connection.host} via TCP/IP'

output.append(("Connection:", host_info))

Expand All @@ -154,17 +154,17 @@ def status(cur: Cursor, **_) -> list[tuple]:
if "Threads_connected" in status:
# Print the current server statistics.
stats = []
stats.append("Connections: {0}".format(status["Threads_connected"]))
stats.append(f'Connections: {status["Threads_connected"]}')
if "Queries" in status:
stats.append("Queries: {0}".format(status["Queries"]))
stats.append("Slow queries: {0}".format(status["Slow_queries"]))
stats.append("Opens: {0}".format(status["Opened_tables"]))
stats.append(f'Queries: {status["Queries"]}')
stats.append(f'Slow queries: {status["Slow_queries"]}')
stats.append(f'Opens: {status["Opened_tables"]}')
if "Flush_commands" in status:
stats.append("Flush tables: {0}".format(status["Flush_commands"]))
stats.append("Open tables: {0}".format(status["Open_tables"]))
stats.append(f'Flush tables: {status["Flush_commands"]}')
stats.append(f'Open tables: {status["Open_tables"]}')
if "Queries" in status:
queries_per_second = int(status["Queries"]) / int(status["Uptime"])
stats.append("Queries per second avg: {:.3f}".format(queries_per_second))
stats.append(f'Queries per second avg: {queries_per_second:.3f}')
stats_str = " ".join(stats)
footer.append("\n" + stats_str)

Expand Down
2 changes: 1 addition & 1 deletion mycli/packages/special/delimitercommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def set(self, arg: str, **_) -> list[tuple[None, None, None, str]]:
return [(None, None, None, 'Invalid delimiter "delimiter"')]

self._delimiter = delimiter
return [(None, None, None, "Changed delimiter to {}".format(delimiter))]
return [(None, None, None, f'Changed delimiter to {delimiter}')]

@property
def current(self) -> str:
Expand Down
6 changes: 3 additions & 3 deletions mycli/packages/special/favoritequeries.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class FavoriteQueries:

# Delete a favorite query.
> \\fd simple
simple: Deleted
simple: Deleted.
"""

# Class-level variable, for convenience to use as a singleton.
Expand Down Expand Up @@ -60,6 +60,6 @@ def delete(self, name: str) -> str:
try:
del self.config[self.section_name][name]
except KeyError:
return "%s: Not Found." % name
return f'{name}: Not Found.'
self.config.write()
return "%s: Deleted" % name
return f'{name}: Deleted.'
24 changes: 12 additions & 12 deletions mycli/packages/special/iocommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ def is_pager_enabled() -> bool:
def set_pager(arg: str, **_) -> list[tuple]:
if arg:
os.environ["PAGER"] = arg
msg = "PAGER set to %s." % arg
msg = f"PAGER set to {arg}."
set_pager_enabled(True)
else:
if "PAGER" in os.environ:
msg = "PAGER set to %s." % os.environ["PAGER"]
msg = f"PAGER set to {os.environ['PAGER']}."
else:
# This uses click's default per echo_via_pager.
msg = "Pager enabled."
Expand Down Expand Up @@ -176,7 +176,7 @@ def open_external_editor(filename: str | None = None, sql: str | None = None) ->

# Populate the editor buffer with the partial sql (if available) and a
# placeholder comment.
query = click.edit("{sql}\n\n{marker}".format(sql=sql, marker=MARKER), extension=".sql") or ''
query = click.edit(f"{sql}\n\n{MARKER}", extension=".sql") or ''

if query:
query = query.split(MARKER, 1)[0].rstrip("\n")
Expand Down Expand Up @@ -219,7 +219,7 @@ def copy_query_to_clipboard(sql: str | None = None) -> str | None:
message = None

try:
pyperclip.copy("{sql}".format(sql=sql))
pyperclip.copy(f"{sql}")
except RuntimeError as e:
message = f"Error clipping query: {e}."

Expand Down Expand Up @@ -251,7 +251,7 @@ def execute_favorite_query(cur: Cursor, arg: str, **_) -> Generator[tuple, None,

query = favoritequeries.get(name)
if query is None:
message = "No favorite query: %s" % (name)
message = f"No favorite query: {name}"
yield (None, None, None, message)
else:
query, arg_error = subst_favorite_query_args(query, args)
Expand All @@ -260,7 +260,7 @@ def execute_favorite_query(cur: Cursor, arg: str, **_) -> Generator[tuple, None,
else:
for sql in sqlparse.split(query):
sql = sql.rstrip(";")
title = "> %s" % (sql)
title = f"> {sql}"
cur.execute(sql)
if cur.description:
headers = [x[0] for x in cur.description]
Expand Down Expand Up @@ -356,7 +356,7 @@ def execute_system_command(arg: str, **_) -> list[tuple]:

return [(None, None, None, response_str)]
except OSError as e:
return [(None, None, None, "OSError: %s" % e.strerror)]
return [(None, None, None, f"OSError: {e.strerror}")]


def parseargfile(arg: str) -> tuple[str, str]:
Expand All @@ -380,7 +380,7 @@ def set_tee(arg: str, **_) -> list[tuple]:
try:
tee_file = open(*parseargfile(arg))
except (IOError, OSError) as e:
raise OSError("Cannot write to file '{}': {}".format(e.filename, e.strerror))
raise OSError(f"Cannot write to file '{e.filename}': {e.strerror}")

return [(None, None, None, "")]

Expand Down Expand Up @@ -413,7 +413,7 @@ def set_once(arg: str, **_) -> list[tuple]:
try:
once_file = open(*parseargfile(arg))
except (IOError, OSError) as e:
raise OSError("Cannot write to file '{}': {}".format(e.filename, e.strerror))
raise OSError(f"Cannot write to file '{e.filename}': {e.strerror}")
written_to_once_file = False

return [(None, None, None, "")]
Expand Down Expand Up @@ -456,7 +456,7 @@ def _run_post_redirect_hook(post_redirect_command: str, filename: str) -> None:
stderr=subprocess.DEVNULL,
)
except Exception as e:
raise OSError("Redirect post hook failed: {}".format(e))
raise OSError(f"Redirect post hook failed: {e}")


@special_command("\\pipe_once", "\\| command", "Send next result to a subprocess.", aliases=["\\|"])
Expand Down Expand Up @@ -547,15 +547,15 @@ def watch_query(arg: str, **kwargs) -> Generator[tuple, None, None]:
if left_arg == "-c":
clear_screen = True
continue
statement = "{0!s} {1!s}".format(left_arg, arg)
statement = f"{left_arg} {arg}"
destructive_prompt = confirm_destructive_query(statement)
if destructive_prompt is False:
click.secho("Wise choice!")
return
elif destructive_prompt is True:
click.secho("Your call!")
cur = kwargs["cur"]
sql_list = [(sql.rstrip(";"), "> {0!s}".format(sql)) for sql in sqlparse.split(statement)]
sql_list = [(sql.rstrip(";"), f"> {sql}") for sql in sqlparse.split(statement)]
old_pager_enabled = is_pager_enabled()
while True:
if clear_screen:
Expand Down
6 changes: 3 additions & 3 deletions mycli/packages/special/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def execute(cur: Cursor, sql: str) -> list[tuple]:
except KeyError:
special_cmd = COMMANDS[command.lower()]
if special_cmd.case_sensitive:
raise CommandNotFound("Command not found: %s" % command)
raise CommandNotFound(f'Command not found: {command}')

# "help <SQL KEYWORD> is a special case. We want built-in help, not
# mycli help here.
Expand Down Expand Up @@ -160,14 +160,14 @@ def show_keyword_help(cur: Cursor, arg: str) -> list[tuple]:
:return: list
"""
keyword = arg.strip('"').strip("'")
query = "help '{0}'".format(keyword)
query = f"help '{keyword}'"
logger.debug(query)
cur.execute(query)
if cur.description and cur.rowcount > 0:
headers = [x[0] for x in cur.description]
return [(None, cur, headers, "")]
else:
return [(None, None, None, "No help found for {0}.".format(keyword))]
return [(None, None, None, f'No help found for {keyword}.')]


@special_command("exit", "\\q", "Exit.", arg_type=ArgType.NO_QUERY, aliases=["\\q"])
Expand Down
2 changes: 1 addition & 1 deletion mycli/packages/special/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def format_uptime(uptime_in_seconds: str) -> str:
if value == 1 and unit.endswith("s"):
# Remove the "s" if the unit is singular.
unit = unit[:-1]
uptime_values.append("{0} {1}".format(value, unit))
uptime_values.append(f'{value} {unit}')

uptime = " ".join(uptime_values)
return uptime
12 changes: 6 additions & 6 deletions mycli/packages/tabular_output/sql_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@ def adapter(data: list[str], headers: list[str], table_format: Union[str, None]
if len(tables) > 0:
table = tables[0]
if table[0]:
table_name = "{}.{}".format(*table[:2])
table_name = f'{table[0]}.{table[1]}'
else:
table_name = table[1]
else:
table_name = "`DUAL`"
if table_format == "sql-insert":
h = "`, `".join(headers)
yield "INSERT INTO {} (`{}`) VALUES".format(table_name, h)
yield f'INSERT INTO {table_name} (`{h}`) VALUES'
prefix = " "
for d in data:
values = ", ".join(escape_for_sql_statement(v) for i, v in enumerate(d))
yield "{}({})".format(prefix, values)
yield f'{prefix}({values})'
if prefix == " ":
prefix = ", "
yield ";"
Expand All @@ -51,15 +51,15 @@ def adapter(data: list[str], headers: list[str], table_format: Union[str, None]
if len(s) > 2:
keys = int(s[-1])
for d in data:
yield "UPDATE {} SET".format(table_name)
yield f'UPDATE {table_name} SET'
prefix = " "
for i, v in enumerate(d[keys:], keys):
yield "{}`{}` = {}".format(prefix, headers[i], escape_for_sql_statement(v))
yield f'{prefix}`{headers[i]}` = {escape_for_sql_statement(v)}'
if prefix == " ":
prefix = ", "
f = "`{}` = {}"
where = (f.format(headers[i], escape_for_sql_statement(d[i])) for i in range(keys))
yield "WHERE {};".format(" AND ".join(where))
yield f'WHERE {" AND ".join(where)};'


def register_new_formatter(tof: TabularOutputFormatter):
Expand Down
4 changes: 2 additions & 2 deletions mycli/sqlcompleter.py
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,7 @@ def __init__(

def escape_name(self, name: str) -> str:
if name and ((not self.name_pattern.match(name)) or (name.upper() in self.reserved_words) or (name.upper() in self.functions)):
name = "`%s`" % name
name = f'`{name}`'

return name

Expand Down Expand Up @@ -1079,7 +1079,7 @@ def find_matches(

if fuzzy:
regex = ".*?".join(map(re.escape, text))
pat = re.compile("(%s)" % regex)
pat = re.compile(f'({regex})')
for item in collection:
r = pat.search(item.lower())
if r:
Expand Down
6 changes: 3 additions & 3 deletions test/test_sqlexecute.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def test_favorite_query(executor):
assert_result_equal(results, title="> select * from test where a like 'a%'", headers=["a"], rows=[("abc",)], auto_status=False)

results = run(executor, "\\fd test-a")
assert_result_equal(results, status="test-a: Deleted")
assert_result_equal(results, status="test-a: Deleted.")


@dbtest
Expand All @@ -152,7 +152,7 @@ def test_favorite_query_multiple_statement(executor):
assert expected == results

results = run(executor, "\\fd test-ad")
assert_result_equal(results, status="test-ad: Deleted")
assert_result_equal(results, status="test-ad: Deleted.")


@dbtest
Expand All @@ -172,7 +172,7 @@ def test_favorite_query_expanded_output(executor):
set_expanded_output(False)

results = run(executor, "\\fd test-ae")
assert_result_equal(results, status="test-ae: Deleted")
assert_result_equal(results, status="test-ae: Deleted.")


@dbtest
Expand Down