Commit e1eb9c50 by arun.uday

v4

parent 5bd102c5
class MongoDBQuery:
@staticmethod
def insert(db, p_id, p_name, p_category, retail_price, discount_price, description, over_rating):
cur = db.insert_one({"product_id": p_id, "product_name": p_name, "product_category": p_category,
"retail_price": retail_price, "discount_price": discount_price,
"description": description, "overall_rating": over_rating})
return cur
@staticmethod
def update(db, condition_values, update_data):
update_d = db.update_many(condition_values, update_data)
return update_d
@staticmethod
def view(db, field_filter):
view_data = db.find(field_filter, {'_id': 0})
return view_data
@staticmethod
def delete(db, condition_values):
delete_data = db.delete_one(condition_values)
return delete_data
from scripts.config.postgres_connect_config import products
class QueriesPost:
@staticmethod
def create_table():
table = f"CREATE TABLE if not exists {products} " \
f"(Product_Id SERIAL PRIMARY KEY, Product_Name VARCHAR(255)," \
f"Product_Category VARCHAR(255)," \
f"Retail_Price INT," \
f"Discounted_Price INT," \
f"Description VARCHAR(255)," \
f"Overall_Rating INT)"
return table
@staticmethod
def insert_data():
insert_data = f"INSERT INTO {products} (Product_Name, Product_Category, Retail_Price, Discounted_Price," \
f"Description, Overall_Rating) VALUES (%s, %s, %s, %s, %s, %s)"
return insert_data
@staticmethod
def update_data(updates, conditions):
view_data = f"UPDATE {products} SET {updates} WHERE {conditions}"
return view_data
@staticmethod
def fetch_conditions(conditions):
fetch_data = f"SELECT * FROM {products} WHERE {conditions}"
return fetch_data
@staticmethod
def fetch_all():
fetch_data = f"SELECT * FROM {products}"
return fetch_data
@staticmethod
def delete_data(field_name, del_data):
del_val = f"DELETE FROM {products} WHERE {field_name} = {del_data}"
return del_val
# reading user inputs
from scripts.core.database.mongo.queries.mongodb_queires import MongoDBQuery
def read_inputs():
p_id = int(input("Enter the product id: "))
p_name = input("Enter the product name: ")
......@@ -14,10 +17,8 @@ def read_inputs():
# inserting data to mongo
def insert_data_db(db, p_id, p_name, p_category, retail_price, discount_price, description, over_rating):
try:
insert_res = db.insert_one({"Product Id": p_id, "Product Name": p_name, "Product category": p_category,
"Retail price": retail_price, "Discount Price": discount_price,
"Description": description,
"Overall rating": over_rating})
insert_res = MongoDBQuery().insert(db, p_id, p_name, p_category, retail_price, discount_price, description, over_rating)
return insert_res
except Exception as e:
print("Exception occurred :", e)
return insert_res
# deleting data
# getting user inputs
from scripts.core.database.mongo.queries.mongodb_queires import MongoDBQuery
def delete_db_input():
field_name = input("Enter the field condition: ")
del_data = int(input("Enter the data: "))
columns_ = ['product_id', 'product_name', 'product_category', 'retail_price',
'discount_price', 'description', 'overall_rating']
integer_val = [0, 3, 4, 6]
counter = 0
condition_values = {}
print("Conditions")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '' and (counter in integer_val):
condition_values.update({f'{columns_[counter]}': int(field_value)})
if field_value != '' and (counter not in integer_val):
condition_values.update({f'{columns_[counter]}': f'{field_value}'})
counter += 1
return field_name, del_data
return condition_values
# deleting the record
def db_delete(db, field_name, del_data):
filter_del = {field_name: del_data}
return db.delete_one(filter_del)
def db_delete(db, condition_values):
cur = MongoDBQuery().delete(db, condition_values)
return cur
from scripts.config.postgres_connect_config import products
from scripts.core.database.postgres.postgres_connect import cur
def post_columns():
# Execute a SELECT statement to get the column names of a table
cur.execute(f"SELECT * FROM {products} LIMIT 0")
# Get the column names
field_names = [desc[0] for desc in cur.description]
return field_names
# class for mongodb operations
from scripts.constants.file_constants import exception_msg
from scripts.core.engine.mongodb_connect import client
from scripts.core.database.mongo.mongodb_connect import client
from scripts.core.handlers.data_insert import insert_data_db, read_inputs
from scripts.core.handlers.delete_db_data import delete_db_input, db_delete
from scripts.core.handlers.update_mongo_db import db_update, input_update_db
from scripts.core.handlers.view_data_db import view_fields, view_cond, view_all
from scripts.core.handlers.view_data_db import view_fields, view_cond
class MongoDbStart:
......@@ -42,8 +42,8 @@ class MongoDbStart:
@staticmethod
def mongo_update(db):
try:
field_name, up_data, up_field_name, new_data = input_update_db()
update_check = db_update(db, field_name, up_data, up_field_name, new_data)
condition_values, update_values = input_update_db()
update_check = db_update(db, condition_values, update_values)
if update_check.matched_count > 0:
print("Data updated")
else:
......@@ -55,8 +55,8 @@ class MongoDbStart:
@staticmethod
def mongo_delete(db):
try:
field_name, del_data = delete_db_input()
del_check = db_delete(db, field_name, del_data)
condition_values = delete_db_input()
del_check = db_delete(db, condition_values)
if del_check.deleted_count > 0:
print("Data deleted")
else:
......@@ -68,16 +68,8 @@ class MongoDbStart:
@staticmethod
def mongo_view(db):
try:
field_filter, data_find = view_cond()
view_fields(db, field_filter, data_find)
except Exception as e:
print(f'{exception_msg}{e}')
@staticmethod
def mongo_view_all(db):
try:
view_all(db)
field_filter = view_cond()
view_fields(db, field_filter)
except Exception as e:
print(f'{exception_msg}{e}')
......
# deleting data
# getting user inputs
from scripts.config.postgres_connect_config import products
from scripts.core.database.postgres.queries.post_queries import QueriesPost
# user input
......@@ -13,4 +14,4 @@ def delete_db_post():
# deleting the record
def db_delete_post(cur, field_name, del_data):
return cur.execute(f"DELETE FROM {products} WHERE {field_name} = {del_data}")
return cur.execute(QueriesPost().delete_data(field_name, del_data))
# reading user inputs
from scripts.config.postgres_connect_config import products
from scripts.constants.file_constants import exception_msg
from scripts.core.database.postgres.queries.post_queries import QueriesPost
# user inputs
......@@ -20,8 +21,7 @@ def read_inputs_post():
def insert_data_post(cur, p_name, p_category, retail_price, discount_price, description, over_rating):
try:
val_data = [p_name, p_category, retail_price, discount_price, description, over_rating]
cur.execute(f"INSERT INTO {products} (Product_Name, Product_Category, Retail_Price, Discounted_Price, "
f"Description, Overall_Rating) VALUES (%s, %s, %s, %s, %s, %s)", val_data)
cur.execute(QueriesPost().insert_data(), val_data)
except Exception as e:
print(f'{exception_msg},{e}')
return False
......
# updating the db
from scripts.config.postgres_connect_config import products
from scripts.core.database.postgres.queries.post_queries import QueriesPost
from scripts.core.handlers.get_post_columns import post_columns
# user data
def input_update_post():
field_name = input("Enter the field condition: ")
up_data = int(input("Enter the data: "))
up_field_name = input("Enter the field to update: ")
new_data = input("Enter the new data: ")
columns_ = post_columns()
counter = 0
condition_values = {}
print("Conditions")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '':
condition_values.update({columns_[counter]: field_value})
counter += 1
return field_name, up_data, up_field_name, new_data
counter = 1
update_values = {}
print("New values")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '':
update_values.update({columns_[counter]: field_value})
counter += 1
return condition_values, update_values
# updating the database
def db_update_post(cur, field_name, up_data, up_field_name, new_data):
return cur.execute(f"UPDATE {products} SET {up_field_name} = '{new_data}' WHERE {field_name} = '{up_data}'")
def db_update_post(cur, condition_values, update_values):
conditions = [f"{field} = '{value}'" for field, value in condition_values.items()]
conditions = "and ".join(conditions)
updates = [f"{field} = '{value}'" for field, value in update_values.items()]
updates = ", ".join(updates)
if conditions and updates:
cur = cur.execute(QueriesPost().update_data())
else:
cur = None
return cur
......@@ -3,21 +3,56 @@
import pandas as pd
from scripts.config.postgres_connect_config import products
from scripts.core.database.postgres.queries.post_queries import QueriesPost
from scripts.core.handlers.get_post_columns import post_columns
# user input for fetch
def input_view_post():
columns_ = post_columns()
counter = 0
condition_values = {}
print("Conditions")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '':
condition_values.update({columns_[counter]: field_value})
counter += 1
return condition_values
# view the data
def view_fields_post(cur):
cur.execute(f"SELECT * FROM {products}")
cursor_data = cur.fetchall()
if cursor_data is not None:
print("Data collected....")
view_data = pd.DataFrame((view_data_record for view_data_record in cursor_data), columns=['Product Id',
'Product_Name',
'Product_Category',
'Retail_Price',
'Discounted_Price',
'Description',
'Overall_Rating'])
print(view_data)
def view_fields_post(cur, condition_values):
conditions = [f"{field} = '{value}'" for field, value in condition_values.items()]
conditions = " and ".join(conditions)
if conditions:
cur.execute(QueriesPost().fetch_conditions())
cursor_data = cur.fetchall()
if cursor_data:
print("Data collected....")
view_data = pd.DataFrame((view_data_record for view_data_record in cursor_data), columns=['Product Id',
'Product_Name',
'Product_Category',
'Retail_Price',
'Discounted_Price',
'Description',
'Overall_Rating'])
print(view_data)
else:
print("Data fetching failed")
else:
print("Data fetching failed")
cur.execute(QueriesPost().fetch_all())
cursor_data = cur.fetchall()
if cursor_data:
print("Data collected....")
view_data = pd.DataFrame((view_data_record for view_data_record in cursor_data), columns=['Product Id',
'Product_Name',
'Product_Category',
'Retail_Price',
'Discounted_Price',
'Description',
'Overall_Rating'])
print(view_data)
else:
print("Data fetching failed")
# class for postgresSql
from scripts.constants.file_constants import exception_msg
from scripts.core.engine.postgres_connect import cur, postgres_client
from scripts.core.database.postgres.postgres_connect import cur, postgres_client
from scripts.core.handlers.postgres_data_del import delete_db_post, db_delete_post
from scripts.core.handlers.postgres_data_insert import read_inputs_post, insert_data_post
from scripts.core.handlers.postgres_data_update import input_update_post, db_update_post
from scripts.core.handlers.postgres_data_view import view_fields_post
from scripts.core.handlers.postgres_data_view import view_fields_post, input_view_post
from scripts.core.handlers.postgres_table_create import create_table
......@@ -40,8 +40,8 @@ class PostgresStart:
@staticmethod
def post_update():
try:
field_name, up_data, up_field_name, new_data = input_update_post()
update_check = db_update_post(cur, field_name, up_data, up_field_name, new_data)
condition_values, update_values = input_update_post()
update_check = db_update_post(cur, condition_values, update_values)
if update_check is None:
print("Data updated")
else:
......@@ -64,7 +64,8 @@ class PostgresStart:
@staticmethod
def post_view():
try:
view_fields_post(cur)
condition_values = input_view_post()
view_fields_post(cur, condition_values)
except Exception as e:
print(f'{exception_msg}{e}')
......@@ -74,3 +75,4 @@ class PostgresStart:
# Close the cursor and connection
cur.close()
postgres_client.close()
# creating a table
from scripts.config.postgres_connect_config import products
from scripts.constants.file_constants import exception_msg
from scripts.core.database.postgres.queries.post_queries import QueriesPost
# create table if exist or not
def create_table(cur):
try:
cursor_db = cur
cursor_db.execute(f"SELECT * FROM information_schema.tables WHERE table_name = '{products}'")
if cursor_db.fetchone():
print("Table exist")
else:
# Create the table if it does not exist
cursor_db.execute(f"CREATE TABLE {products} "
f"(Product_Id SERIAL PRIMARY KEY, Product_Name VARCHAR(255),"
f"Product_Category VARCHAR(255),"
f"Retail_Price INT,"
f"Discounted_Price INT,"
f"Description VARCHAR(255),"
f"Overall_Rating INT)")
cursor_db.execute(QueriesPost().create_table())
except Exception as e:
print(f'{exception_msg},{e}')
return False
......
# updating the db
from scripts.core.database.mongo.queries.mongodb_queires import MongoDBQuery
# user data
def input_update_db():
field_name = input("Enter the field condition: ")
up_data = int(input("Enter the data: "))
up_field_name = input("Enter the field to update: ")
new_data = input("Enter the new data: ")
columns_ = ['product_id', 'product_name', 'product_category', 'retail_price',
'discount_price', 'description', 'overall_rating']
integer_val = [0, 3, 4, 6]
counter = 0
condition_values = {}
print("Conditions")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '' and (counter in integer_val):
condition_values.update({f'{columns_[counter]}': int(field_value)})
if field_value != '' and (counter not in integer_val):
condition_values.update({f'{columns_[counter]}': f'{field_value}'})
counter += 1
return field_name, up_data, up_field_name, new_data
counter = 1
update_values = {}
print("New values")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '' and (counter in integer_val):
update_values.update({f'{columns_[counter]}': int(field_value)})
if field_value != '' and (counter not in integer_val):
update_values.update({f'{columns_[counter]}': f'{field_value}'})
counter += 1
return condition_values, update_values
# updating the database
def db_update(db, field_name, up_data, up_field_name, new_data):
cond_data = {field_name: up_data}
update_data = {"$set": {up_field_name: new_data}}
return db.update_many(cond_data, update_data)
def db_update(db, condition_values, update_values):
update_data = {"$set": update_values}
cur = MongoDBQuery().update(db, condition_values, update_data)
return cur
......@@ -2,33 +2,35 @@
# display conditions
import pandas as pd
from scripts.core.database.mongo.queries.mongodb_queires import MongoDBQuery
# display conditions
def view_cond():
field_filter = input("Enter the field name: ")
data_find = int(input("Enter the data to find: "))
columns_ = ['product_id', 'product_name', 'product_category', 'retail_price',
'discount_price', 'description', 'overall_rating']
integer_val = [0, 3, 4, 6]
counter = 0
condition_values = {}
print("Conditions")
while counter < len(columns_):
field_value = input(f"Enter the {columns_[counter]} data: ")
if field_value != '' and (counter in integer_val):
condition_values.update({f'{columns_[counter]}': int(field_value)})
if field_value != '' and (counter not in integer_val):
condition_values.update({f'{columns_[counter]}': f'{field_value}'})
counter += 1
return field_filter, data_find
return condition_values
# view the data
def view_fields(db, field_filter, data_find):
filter_data = {field_filter: data_find}
view_data_cursor = db.find(filter_data, {'_id': 0})
view_cursor_count = db.count_documents(filter_data)
def view_fields(db, field_filter):
view_data_cursor = MongoDBQuery().view(db, field_filter)
view_cursor_count = db.count_documents(field_filter)
if view_cursor_count > 0:
print("Data collected....")
view_data = pd.json_normalize((view_data_record for view_data_record in view_data_cursor))
print(view_data)
else:
print("Data fetching failed")
def view_all(db):
view_data_cursor = db.find({}, {'_id': 0})
if len(list(view_data_cursor.clone())) > 0:
print("Data collected....")
view_data = pd.json_normalize((view_data_record for view_data_record in view_data_cursor))
print(view_data)
else:
print("Data fetching failed")
# access class functions
from scripts.services.mongo_db_operations import MongoDbStart
from scripts.services.postgres_db_operations import PostgresStart
from scripts.core.handlers.mongo_db_operations import MongoDbStart
from scripts.core.handlers.postgres_db_operations import PostgresStart
# mongo access
......@@ -9,7 +9,7 @@ def mongo_db_access_op():
db_created = db_class.mongo_create()
while True:
try:
user_query = input("Enter insert/ update/ delete/ view/view-all/ quit : ")
user_query = input("Enter insert/ update/ delete/ view/ quit : ")
if user_query == 'insert':
db_class.mongo_insert(db_created)
elif user_query == 'update':
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment