canvasapp/flex2.py

106 lines
3.4 KiB
Python

import pymysql
# Connect to the MySQL database using PyMySQL
conn = pymysql.connect(
host="192.168.1.6", # Your host (localhost, for example)
user="phowell", # Your MySQL username
password="rolley34",# Your MySQL password
database="db" # Your database name
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# Query to get the table structure
cursor.execute("""
SELECT
C.TABLE_NAME,
C.COLUMN_NAME,
C.COLUMN_TYPE,
C.IS_NULLABLE,
C.COLUMN_DEFAULT,
C.EXTRA,
KCU.REFERENCED_TABLE_NAME,
KCU.REFERENCED_COLUMN_NAME,
KCU.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.COLUMNS C
LEFT JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON C.TABLE_NAME = KCU.TABLE_NAME AND C.COLUMN_NAME = KCU.COLUMN_NAME
WHERE
C.TABLE_SCHEMA = 'db' -- Replace with your actual database name
AND C.TABLE_NAME LIKE 'conf_%'; -- Only tables starting with 'conf_'
""")
# Fetch all rows from the query result
columns_info = cursor.fetchall()
# Close the connection
cursor.close()
conn.close()
# Function to generate condensed output
def condense_structure(columns_info):
result = {}
for column in columns_info:
table = column['TABLE_NAME']
column_name = column['COLUMN_NAME']
column_type = column['COLUMN_TYPE']
is_nullable = column['IS_NULLABLE']
extra = column['EXTRA']
referenced_table = column['REFERENCED_TABLE_NAME']
referenced_column = column['REFERENCED_COLUMN_NAME']
constraint_name = column['CONSTRAINT_NAME']
# Condense data type (e.g., 'VARCHAR(255)' -> 'V(255)')
if column_type.startswith('varchar'):
column_type = 'V(' + column_type.split('(')[1].split(')')[0] + ')'
elif column_type.startswith('char'):
column_type = 'C(' + column_type.split('(')[1].split(')')[0] + ')'
elif column_type.startswith('int'):
column_type = 'I' # Int types are just abbreviated to 'I'
elif column_type.startswith('text'):
column_type = 'T' # Text types are abbreviated to 'T'
# Condense NULLABLE
if is_nullable == 'YES':
column_type += ' N' # Add N for nullable
else:
column_type += ' NN' # Add NN for not nullable
# Remove DEFAULT NULL if no default value is set
if column['COLUMN_DEFAULT'] is None:
column_default = ''
else:
column_default = f" D({column['COLUMN_DEFAULT']})" # Default value
# Add extra information, like auto-increment if available
if 'auto_increment' in extra:
column_type += " AI" # Add AI for auto-increment columns
# Handle foreign key references
if referenced_table:
column_type += f" FK({referenced_table}.{referenced_column})"
# Create shorthand for each column
shorthand = f"{column_name}: {column_type}{column_default}"
# Add to the result dict under the respective table
if table not in result:
result[table] = []
result[table].append(shorthand)
return result
# Condense the structure
condensed_structure = condense_structure(columns_info)
# Print out the condensed structure
for table, columns in condensed_structure.items():
print(f"Table: {table}")
for column in columns:
print(f" - {column}")
print("\n")