ocp5/db.py

89 lines
2.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: freezed <freezed@users.noreply.github.com> 2018-07-26
Version: 0.1
Licence: `GNU GPL v3` GNU GPL v3: http://www.gnu.org/licenses/
Connect to DB
"""
import pymysql.cursors
from config import DB_CONFIG
2018-07-27 16:46:33 +00:00
DB_NOT_FOUND = True
2018-07-27 16:46:33 +00:00
# FUNCTION
def sql_create_db(filename=DB_CONFIG['file']):
2018-07-27 16:46:33 +00:00
"""
Get the SQL instruction to create the DB for file
:return: a list of each SQL query whithout the trailing ";"
:Tests:
>>> sql_create_db('wronq_file.sql')
File load error : wronq_file.sql
False
2018-07-27 16:46:33 +00:00
"""
from os import path
# Loading file
if path.isfile(filename) is False:
print("File load error : {}".format(filename))
return False
else:
with open(filename, "r") as sql_file:
# Split file in list
ret = sql_file.read().split(';')
# drop last empty entry
ret.pop()
return ret
# WORK
# Connect to the database
CONNECTION = pymysql.connect(host=DB_CONFIG['host'],
user=DB_CONFIG['user'],
password=DB_CONFIG['pass'],
charset=DB_CONFIG['char'],
cursorclass=pymysql.cursors.DictCursor)
try:
2018-07-27 16:46:33 +00:00
with CONNECTION.cursor() as cursor:
# Show DB
cursor.execute("SHOW DATABASES")
2018-07-27 16:46:33 +00:00
db_list = cursor.fetchall()
2018-07-27 16:46:33 +00:00
for idx, val in enumerate(db_list):
if DB_CONFIG['db'] in db_list[idx].values():
2018-07-27 16:46:33 +00:00
DB_NOT_FOUND = False
cursor.execute("USE {}".format(DB_CONFIG['db']))
2018-07-27 16:46:33 +00:00
print('DB exist : ready to use it.')
2018-07-27 16:46:33 +00:00
# No DB, create it
if DB_NOT_FOUND:
request_list = sql_create_db()
if request_list is not False:
for idx, sql_request in enumerate(request_list):
# print(sql_request + ';')
print("-- REQUEST #{} : --{}".format(idx, sql_request))
cursor.execute(sql_request + ';')
except pymysql.err.OperationalError as except_detail:
print("DB error: «{}»".format(except_detail))
finally:
2018-07-27 16:46:33 +00:00
CONNECTION.close()
if __name__ == "__main__":
""" Running doctests """
import doctest
doctest.testmod()