RandomDBGenerator/pythonProject/sqlgenerator/SQLGenerator.py

50 lines
1.8 KiB
Python
Raw Normal View History

import datetime
import random
import time
from sqlgenerator.ColumnValue import ValueType, ColumnValue
from sqlparse.SQLColumn import SQLColumn, SQLColumnType
from sqlparse.SQLTable import SQLTable
from lorem_text import lorem
min_bigint = 0
max_bigint = 9223372036854775807
min_int = -2147483648
max_int = 2147483647
min_date = datetime.date(2023, 1, 1)
max_date = datetime.date(2024, 12, 31)
def generate_random_insert(sql_table: SQLTable):
columnValues = []
for column in sql_table.columns:
columnValues.append(generate_random_column(column))
sql_insert_command = "INSERT INTO " + sql_table.table_name + " VALUES (${i});"
for columnValue in columnValues:
if columnValue.valueType == ValueType.INT:
sql_insert_command = sql_insert_command.replace("${i}", str(columnValue.value) + ", ${i}")
else:
sql_insert_command = sql_insert_command.replace("${i}", "'" + columnValue.value + "', ${i}")
sql_insert_command = sql_insert_command.replace(", ${i}", "")
return sql_insert_command
def generate_random_column(sql_column: SQLColumn):
if sql_column.columnType == SQLColumnType.BIGINT:
return ColumnValue(random.randint(min_bigint, max_bigint), ValueType.INT)
elif sql_column.columnType == SQLColumnType.INT:
return ColumnValue(random.randint(min_int, max_int), ValueType.INT)
elif sql_column.columnType == SQLColumnType.VARCHAR:
text_legnth = random.randint(1, 255)
lorem_text = lorem.sentence()
return ColumnValue(lorem_text[:text_legnth], ValueType.STRING)
elif sql_column.columnType == SQLColumnType.DATE:
delta = max_date - min_date
random_days = random.randrange(delta.days + 1)
random_date = min_date + datetime.timedelta(days=random_days)
return ColumnValue(str(random_date), ValueType.STRING)