Skip to content

Fixing startupcommands and successful perpetually set as True #160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 12, 2023
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
## TBD

### Features

* Adding support for startup commands being set in liteclirc and executed on startup. Limited to commands already implemented in litecli. ([[#56](https://github.com/dbcli/litecli/issues/56)])

### Bug Fixes

* Fix [[#146](https://github.com/dbcli/litecli/issues/146)], making sure `.once`
can be used more than once in a session.
* Fixed setting `successful = True` only when query is executed without exceptions so
failing queries get `successful = False` in `query_history`.
* Changed `master` to `main` in CONTRIBUTING.md to reflect GitHubs new default branch
naming.

## 1.9.0 - 2022-06-06

Expand Down Expand Up @@ -115,3 +123,4 @@
[Shawn Chapla]: https://github.com/shwnchpl
[Zhaolong Zhu]: https://github.com/zzl0
[Zhiming Wang]: https://github.com/zmwangx
[Bjørnar Smestad]: https://brendesmestad.no
8 changes: 7 additions & 1 deletion litecli/liteclirc
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ output.header = "#00ff5f bold"
output.odd-row = ""
output.even-row = ""


# Favorite queries.
[favorite_queries]

# Startup commands
# litecli commands or sqlite commands to be executed on startup.
# some of them will require you to have a database attached.
# they will be executed in the same order as they appear in the list.
[startup_commands]
#commands = ".tables", "pragma foreign_keys = ON;"
30 changes: 30 additions & 0 deletions litecli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ def __init__(
fg="red",
)
self.logfile = False
# Load startup commands.
try:
self.startup_commands = c["startup_commands"]
except KeyError: # Redundant given the load_config() function that merges in the standard config, but put here to avoid fail if user do not have updated config file.
self.startup_commands = None

self.completion_refresher = CompletionRefresher()

Expand Down Expand Up @@ -589,6 +594,31 @@ def one_iteration(text=None):
editing_mode=editing_mode,
search_ignore_case=True,
)
def startup_commands():
if self.startup_commands:
if "commands" in self.startup_commands:
for command in self.startup_commands['commands']:
try:
res = sqlexecute.run(command)
except Exception as e:
click.echo(command)
self.echo(str(e), err=True, fg="red")
else:
click.echo(command)
for title, cur, headers, status in res:
if title == 'dot command not implemented':
self.echo("The SQLite dot command '" + command.split(' ', 1)[0]+"' is not yet implemented.", fg="yellow")
else:
output = self.format_output(title, cur, headers)
for line in output:
self.echo(line)
else:
self.echo("Could not read commands. The startup commands needs to be formatted as: \n commands = 'command1', 'command2', ...", fg="yellow")

try:
startup_commands()
except Exception as e:
self.echo("Could not execute all startup commands: \n"+str(e), fg="yellow")

try:
while True:
Expand Down
16 changes: 16 additions & 0 deletions litecli/packages/special/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,19 @@ def format_uptime(uptime_in_seconds):

uptime = " ".join(uptime_values)
return uptime


def check_if_sqlitedotcommand(command):
"""Does a check if the command supplied is in the list of SQLite dot commands.

:param command: A command (str) supplied from the user
:returns: True/False
"""

sqlite3dotcommands = ['.archive','.auth','.backup','.bail','.binary','.cd','.changes','.check','.clone','.connection','.databases','.dbconfig','.dbinfo','.dump','.echo','.eqp','.excel','.exit','.expert','.explain','.filectrl','.fullschema','.headers','.help','.import','.imposter','.indexes','.limit','.lint','.load','.log','.mode','.nonce','.nullvalue','.once','.open','.output','.parameter','.print','.progress','.prompt','.quit','.read','.recover','.restore','.save','.scanstats','.schema','.selftest','.separator','.session','.sha3sum','.shell','.show','.stats','.system','.tables','.testcase','.testctrl','.timeout','.timer','.trace','.vfsinfo','.vfslist','.vfsname','.width']

if isinstance(command, str):
command = command.split(' ', 1)[0].lower()
return (command in sqlite3dotcommands)
else:
return False
13 changes: 8 additions & 5 deletions litecli/sqlexecute.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@
import uuid
from contextlib import closing
from sqlite3 import OperationalError
from litecli.packages.special.utils import check_if_sqlitedotcommand

import sqlparse
import os.path

from .packages import special

_logger = logging.getLogger(__name__)

# FIELD_TYPES = decoders.copy()
# FIELD_TYPES.update({
# FIELD_TYPE.NULL: type(None)
# })


class SQLExecute(object):

databases_query = """
Expand Down Expand Up @@ -79,6 +78,7 @@ def connect(self, database=None):
# retrieve connection id
self.reset_connection_id()


def run(self, statement):
"""Execute the sql in the database and return the results. The results
are a list of tuples. Each tuple has 4 values
Expand Down Expand Up @@ -129,9 +129,12 @@ def run(self, statement):
for result in special.execute(cur, sql):
yield result
except special.CommandNotFound: # Regular SQL
_logger.debug("Regular sql statement. sql: %r", sql)
cur.execute(sql)
yield self.get_result(cur)
if check_if_sqlitedotcommand(sql):
yield ('dot command not implemented', None, None, None)
else:
_logger.debug("Regular sql statement. sql: %r", sql)
cur.execute(sql)
yield self.get_result(cur)

def get_result(self, cursor):
"""Get the current result's data from the cursor."""
Expand Down
7 changes: 7 additions & 0 deletions tests/liteclirc
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,10 @@ Token.Toolbar.Arg.Text = nobold
[favorite_queries]
q_param = select * from test where name=?
sh_param = select * from test where id=$1

# Startup commands
# litecli commands or sqlite commands to be executed on startup.
# some of them will require you to have a database attached.
# they will be executed in the same order as they appear in the list.
[startup_commands]
commands = "create table startupcommands(a text)", "insert into startupcommands values('abc')"
13 changes: 13 additions & 0 deletions tests/test_dbspecial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from litecli.packages.completion_engine import suggest_type
from test_completion_engine import sorted_dicts
from litecli.packages.special.utils import format_uptime
from litecli.packages.special.utils import check_if_sqlitedotcommand


def test_import_first_argument():
Expand Down Expand Up @@ -74,3 +75,15 @@ def test_indexes():
{"type": "schema"},
]
)


def test_check_if_sqlitedotcommand():
test_cases = [
[".tables", True],
[".BiNarY", True],
["binary", False],
[234, False],
[".changes test! test", True],
["NotDotcommand", False]]
for command, expected_result in test_cases:
assert check_if_sqlitedotcommand(command) == expected_result
7 changes: 7 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,10 @@ def test_import_command(executor):
"""
assert result.exit_code == 0
assert expected in "".join(result.output)


def test_startup_commands(executor):
m = LiteCli(liteclirc=default_config_file)
assert m.startup_commands['commands'] == ['create table startupcommands(a text)', "insert into startupcommands values('abc')"]

# implement tests on executions of the startupcommands