Skip to content

Commit

Permalink
psf/black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Pihu1998 committed Apr 8, 2020
1 parent 7d59821 commit 1d0082d
Showing 1 changed file with 90 additions and 49 deletions.
139 changes: 90 additions & 49 deletions databaseconnect.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import logging
import logger_config
import chatbot

log = logging.getLogger(__name__)
log.info('Entered module: %s' % __name__)
log.info("Entered module: %s" % __name__)


@logger_config.logger
Expand All @@ -25,19 +26,19 @@ def connection_to_database():
)
if conn.is_connected():
# logging.debug("Connected")
logging.debug('MySQL connected')
logging.debug("MySQL connected")
break

except mysql.connector.Error as e:
tries += 1
print(e, "...Retrying")
logging.debug(e, "...Retrying")
sleep(20)
try:
if conn.is_connected():
# logging.debug("Connected")
logging.debug('MySQL connected')
logging.debug("MySQL connected")
return conn
except:
except Exception:
raise Exception("DATABASE NOT CONNECTED")


Expand All @@ -46,10 +47,21 @@ def connection_to_database():
def setup_database():
db = connection_to_database()
cur = db.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS chat_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, root_word VARCHAR(40), subject VARCHAR(40), verb VARCHAR(40), sentence VARCHAR(200))")
cur.execute("CREATE TABLE IF NOT EXISTS statement_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, root_word VARCHAR(40), subject VARCHAR(40), verb VARCHAR(40), sentence VARCHAR(200))")
cur.execute("CREATE TABLE IF NOT EXISTS question_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, root_word VARCHAR(40), subject VARCHAR(40), verb VARCHAR(40), sentence VARCHAR(200))")
cur.execute("CREATE TABLE IF NOT EXISTS directions_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, origin_location VARCHAR(100), destination_location VARCHAR(100))")

cur.execute(
"CREATE TABLE IF NOT EXISTS chat_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, root_word VARCHAR(40), subject VARCHAR(40), verb VARCHAR(40), sentence VARCHAR(200))" # noqa: E501
)
cur.execute(
"CREATE TABLE IF NOT EXISTS statement_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, root_word VARCHAR(40), subject VARCHAR(40), verb VARCHAR(40), sentence VARCHAR(200))" # noqa: E501
)
cur.execute(
"CREATE TABLE IF NOT EXISTS question_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, root_word VARCHAR(40), subject VARCHAR(40), verb VARCHAR(40), sentence VARCHAR(200))" # noqa: E501
)
cur.execute(
"CREATE TABLE IF NOT EXISTS directions_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, origin_location VARCHAR(100), destination_location VARCHAR(100))" # noqa: E501
)
return db



@logger_config.logger
Expand All @@ -59,9 +71,11 @@ def add_to_database(classification, subject, root, verb, H):
cur = db.cursor()
cur = db.cursor(prepared=True)
if classification == 'C':
cur.execute("INSERT INTO chat_table(root_word,verb,sentence) VALUES (%s, %s, %s)", (str(root), str(verb), H))
cur.execute(
"INSERT INTO chat_table(root_word,verb,sentence) VALUES (%s, %s, %s)", (str(root), str(verb), H,)
)
db.commit()
elif classification == 'Q':
elif classification == "Q":
cur.execute("SELECT sentence FROM question_table")
res = cur.fetchall()
exist = 0
Expand All @@ -71,7 +85,9 @@ def add_to_database(classification, subject, root, verb, H):
break
if exist == 0:
# do not add if question already exists
cur.execute("INSERT INTO question_table(subject,root_word,verb,sentence) VALUES (%s,%s,%s,%s)", (str(subject[0]), str(root),str(verb),H))
cur.execute(
"INSERT INTO question_table(subject,root_word,verb,sentence) VALUES (%s,%s,%s,%s)", (str(subject), str(root),str(verb),H,)
)
db.commit()
else:
cur.execute("SELECT sentence FROM statement_table")
Expand All @@ -81,23 +97,28 @@ def add_to_database(classification, subject, root, verb, H):
if r[-1] == H:
exist = 1
break

if exist == 0: # do not add if question already exists
cur.execute("INSERT INTO statement_table(subject,root_word,verb,sentence) VALUES (%s,%s,%s,%s)", (str(subject[0]), str(root), str(verb), H))
cur.execute(
"INSERT INTO statement_table(subject,root_word,verb,sentence) VALUES (%s,%s,%s,%s)", (str(subject), str(root), str(verb), H,)
)
db.commit()
return db


@logger_config.logger
# get a random chat response
def get_chat_response():
db = connection_to_database()
cur = db.cursor()
cur = db.cursor(buffered=True)
cur = db.cursor(prepared=True)
cur.execute("SELECT COUNT(*) FROM chat_table")
res = cur.fetchone()
total_chat_records = res[0]
import random
chat_id = random.randint(1, total_chat_records+1)
cur.execute("SELECT sentence FROM chat_table WHERE id = '{}'".format(chat_id))

chat_id = random.randint(1, total_chat_records)
cur.execute("SELECT sentence FROM chat_table WHERE id = %s",(str(chat_id),))
res = cur.fetchone()
B = res[0]
return B
Expand All @@ -106,7 +127,7 @@ def get_chat_response():
@logger_config.logger
def get_question_response(subject, root, verb):
db = connection_to_database()
cur = db.cursor(buffered=True)
cur = db.cursor(prepared=True)
if str(subject) == '[]':
cur.execute("SELECT verb FROM statement_table")
res = cur.fetchall()
Expand All @@ -116,13 +137,15 @@ def get_question_response(subject, root, verb):
found = 1
break
if found == 1:
cur.execute("SELECT sentence FROM statement_table WHERE verb= '{}'".format(verb))
cur.execute(
"SELECT sentence FROM statement_table WHERE verb= %s",(str(verb),)
)
res = cur.fetchone()
B = res[0]
return B, 0
return B, chatbot.LearnResponse.MESSAGE.name
else:
B = "Sorry I don't know the response to this. Please train me."
return B, 1
return B, chatbot.LearnResponse.TRAIN_ME.name
else:
cur.execute("SELECT subject FROM statement_table")
res = cur.fetchall()
Expand All @@ -132,34 +155,45 @@ def get_question_response(subject, root, verb):
found = 1
break
if found == 1:
cur.execute("SELECT verb FROM statement_table WHERE subject= '{}'".format(subject[0]))
cur.execute(
"SELECT verb FROM statement_table WHERE subject= %s", (str(subject[0]),)
)
res = cur.fetchone()
checkVerb = res[0] # checkVerb is a string while verb is a list. checkVerb ['verb']
checkVerb = res[0]
# checkVerb is a string while verb is a list. checkVerb ['verb']
if checkVerb == '[]':
cur.execute("SELECT sentence FROM statement_table WHERE subject= '{}'".format(subject[0]))
cur.execute(
"SELECT sentence FROM statement_table WHERE subject= %s", (str(subject[0]),)
)
res = cur.fetchone()
B = res[0]
return B, 0
return B, chatbot.LearnResponse.MESSAGE.name
else:
if checkVerb[2:-2] == verb[0]:
cur.execute("SELECT sentence FROM statement_table WHERE subject= '{}'".format(subject[0]))
cur.execute(
"SELECT sentence FROM statement_table WHERE subject= %s", (str(subject[0]),)
)
res = cur.fetchone()
B = res[0]
return B, 0
return B, chatbot.LearnResponse.MESSAGE.name
else:
B = "Sorry I don't know the response to this. Please train me."
return B, 1
return B, chatbot.LearnResponse.TRAIN_ME.name

else:
B = "Sorry I don't know the response to this. Please train me."
return B, 1
return B, chatbot.LearnResponse.TRAIN_ME.name


@logger_config.logger
def add_learnt_statement_to_database(subject, root, verb):
db = connection_to_database()
cur = db.cursor()
cur.execute("INSERT INTO statement_table(subject,root_word,verb) VALUES (%s,%s,%s)", (str(subject), str(root), str(verb)))
cur.execute(
"INSERT INTO statement_table(subject,root_word,verb) VALUES (%s,%s,%s)", (str(subject), str(root), str(verb),)
)
db.commit()
return db


@logger_config.logger
Expand All @@ -169,11 +203,11 @@ def learn_question_response(H):
cur.execute("SELECT id FROM statement_table ORDER BY id DESC")
res = cur.fetchone()
last_id = res[0]
#cur.execute("UPDATE statement_table SET sentence={H} WHERE id={last_id}")
cur.execute("UPDATE statement_table SET sentence = '{}' WHERE id = '{}'".format(H, last_id))
cur.execute("UPDATE statement_table SET sentence = %s WHERE id = %s",(H, str(last_id),))
db.commit()
B = "Thank you! I have learnt this."
return B, 0
return B, chatbot.LearnResponse.MESSAGE.name


@logger_config.logger
def clear_table(table_name):
Expand All @@ -182,40 +216,47 @@ def clear_table(table_name):

if table_name in ("question_table", "statement_table"):
tables_to_be_cleaned = ("question_table", "statement_table")
cur.execute("The following tables will be cleaned:\n")
logging.debug("The following tables will be cleaned:\n")
for table in tables_to_be_cleaned:
describe_table(cur, table)

if input("Enter 'Y' to confirm cleaning of BOTH tables: ") in ("Y", "y"):
if input("Enter 'Y' to confirm cleaning of BOTH tables: ") in ("Y", "y",):
for table in tables_to_be_cleaned:
cur.execute("DELETE FROM {table}")
cur.execute("DELETE FROM %s",(table,))
db.commit()
cur.execute("Tables cleaned successfully")
logging.debug("Tables cleaned successfully")
else:
cur.execute("Table cleaning skipped.")
logging.debug("Table cleaning skipped.")

else:
cur.execute("The following table will be cleaned:\n")
logging.debug("The following table will be cleaned:\n")
describe_table(cur, table_name)

if input("Enter 'Y' to confirm: ") in ("Y", "y"):
cur.execute("Table cleaned successfully")
cur.execute("DELETE FROM {table_name}")
logging.debug("Table cleaned successfully")
cur.execute("DELETE FROM %s",(table_name,))
db.commit()
else:
cur.execute("Table cleaning skipped.")
logging.debug("Table cleaning skipped.")

return db



@logger_config.logger
def describe_table(cur, table_name):
cur.execute("DESC {table_name}")
cur.execute("DESC %s",(table_name,))
res = cur.fetchall()
column_names = [col[0] for col in res]

cur.execute("SELECT COUNT(*) FROM {table_name}")
cur.execute("SELECT COUNT(*) FROM %s",(table_name,))
res = cur.fetchall()
records_no = res[0][0]

cur.execute("Table Name:", table_name)
cur.execute("Columns:", column_names)
cur.execute("Number of existing records:", records_no)
cur.execute()
logging.debug("Table Name:", table_name)
logging.debug("Columns:", column_names)
logging.debug("Number of existing records:", records_no)
logging.debug()

return records_no

0 comments on commit 1d0082d

Please sign in to comment.