/
tomy.py
146 lines (111 loc) · 4.15 KB
/
tomy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import copy
import sqlite3
import pymysql
import argparse
import configparser
from tabulate import tabulate
from termcolor import colored, cprint
from prompt_toolkit.shortcuts import get_input
from prompt_toolkit.history import History
from prompt_toolkit.contrib.completers import WordCompleter
from pygments.lexers import SqlLexer
from pygments.style import Style
from pygments.token import Token
from pygments.styles.default import DefaultStyle
sql_completer = WordCompleter(['create', 'select', 'insert', 'drop',
'delete', 'from', 'where', 'table'], ignore_case=True)
class DocumentStyle(Style):
styles = {
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
}
styles.update(DefaultStyle.styles)
class TOMy:
def __init__(self, db):
"""Constructor"""
self.arguments()
self.database = db
self.connect()
def arguments(self):
"""
Parse arguments
"""
parser = argparse.ArgumentParser(description='Connect to a MySQL\
server')
parser.add_argument("-u", "--user", dest='user',
help="The MySQL user name to use when connecting\
to the server.")
parser.add_argument("-p", "--password", dest='password',
help="The password to use when connecting \
to the server.")
parser.add_argument("-hs", "--host", dest='host',
help="Connect to the MySQL server on the \
given host.")
parser.add_argument("-D", "--database", dest='database',
help="Database name.")
parser.add_argument("-P", "--port", dest='port',
help="The TCP/IP port number to use for \
the connection.")
parser.add_argument("-cnt", "--connection", dest='connection',
help="Select a conection saved in\
.connections file")
self.args = parser.parse_args()
if(self.args.connection is None):
self.default_args = copy.copy(self.args)
def connect(self):
self.connection = pymysql.connect(
host = self.args.host,
user = self.args.user,
passwd = self.args.password,
db = self.args.database,
cursorclass=pymysql.cursors.DictCursor
)
print(self.connection)
def None2NULL(self, none):
"""
I should learn how to use MySQLdb convertions
"""
if(none == None):
return 'NULL'
else:
return none
def is_number(self, s):
try:
float(s)
return True
except ValueError:
return False
def main(self):
self.database = db
history = History()
while True:
try:
text = get_input('> ', lexer=SqlLexer, completer=sql_completer, style=DocumentStyle, history=history)
except EOFError:
break # Control-D pressed.
with self.connection.cursor() as cursor:
messages = cursor.execute(text)
fetchall = cursor.fetchall()
result = []
description = cursor.description
headers = []
rowcount = cursor.rowcount
for i in description:
headers.append(i[0])
for record in fetchall:
result.append([self.None2NULL(record[d]) for d in headers])
print(tabulate(result, headers, tablefmt="grid"))
print(str(rowcount) + ' rows\n')
print('GoodBye!')
if __name__ == '__main__':
if len(sys.argv) < 2:
db = ':memory:'
else:
db = sys.argv[1]
tomy = TOMy(db)
tomy.main()