Develop a Python script that will retrieve a small part (around 2% of the entries) of a big mariadb database. The subset must contain all the references, so it must be auto-contained, no missed references. The sql file is in the same folder, called "example.sql" and the script must return the database with ALL the tables but the corresponding small part of entries on a file called "reduced.sql". The database contains spanish characters.
Assistant
python
import sqlparse
import re
import sys
import os
import random
def main():
# File names
input_sql_file = 'example.sql'
output_sql_file = 'reduced.sql'
# Read the SQL file
with open(input_sql_file, 'r', encoding='utf-8') as f:
sql_content = f.read()
# Parse the SQL content
statements = sqlparse.split(sql_content)
# Dictionaries to hold table schemas and data
table_schemas = {}
table_foreign_keys = {}
table_data = {}
table_primary_keys = {}
# First pass: Parse CREATE TABLE statements to get table schemas and foreign keys
for statement in statements:
stmt = sqlparse.format(statement, strip_comments=True).strip()
if stmt.upper().startswith('CREATE TABLE'):
table_name, columns, primary_keys, foreign_keys = parse_create_table(stmt)
table_schemas[table_name] = columns
table_primary_keys[table_name] = primary_keys
table_foreign_keys[table_name] = foreign_keys
table_data[table_name] = []
# Second pass: Parse INSERT statements to get table data
for statement in statements:
stmt = sqlparse.format(statement, strip_comments=True).strip()
if stmt.upper().startswith('INSERT INTO'):
table_name, values_list = parse_insert(stmt)
if table_name in table_data:
table_data[table_name].extend(values_list)
else:
table_data[table_name] = values_list
# Start with root tables (tables without foreign keys referencing other tables)
root_tables = [table for table, fks in table_foreign_keys.items() if not fks]
included_records = {}
for table in table_schemas.keys():
included_records[table] = set()
# Randomly select 2% of records from root tables
for table in root_tables:
total_records = len(table_data[table])
num_samples = max(1, int(total_records * 0.02))
sampled_indices = random.sample(range(total_records), num_samples)
for idx in sampled_indices:
record = table_data[table][idx]
primary_key = get_primary_key_value(table_schemas[table], table_primary_keys[table], record)
included_records[table].add(primary_key)
# Expand to include referenced records to maintain referential integrity
changed = True
while changed:
changed = False
for table, records in included_records.items():
foreign_keys = table_foreign_keys[table]
if not foreign_keys:
continue
new_records = set()
for record in table_data[table]:
primary_key = get_primary_key_value(table_schemas[table], table_primary_keys[table], record)
if primary_key in records:
# Check foreign key fields
for fk in foreign_keys:
fk_column = fk['column']
ref_table = fk['ref_table']
ref_column = fk['ref_column']
ref_value = get_column_value(table_schemas[table], fk_column, record)
if ref_value is not None:
if ref_value not in included_records[ref_table]:
included_records[ref_table].add(ref_value)
changed = True
if changed:
break # Restart the process if changes occurred
# Write the reduced SQL file
with open(output_sql_file, 'w', encoding='utf-8') as f:
# Write CREATE TABLE statements
for statement in statements:
stmt = sqlparse.format(statement, strip_comments=True).strip()
if stmt.upper().startswith('CREATE TABLE'):
f.write(statement + '\n\n')
# Write INSERT statements for included records
for table in table_schemas.keys():
schema = table_schemas[table]
records_to_include = []
for record in table_data[table]:
primary_key = get_primary_key_value(schema, table_primary_keys[table], record)
if primary_key in included_records[table]:
records_to_include.append(record)
if records_to_include:
write_insert_statements(f, table, schema, records_to_include)
def parse_create_table(statement):
# Extract table name
match = re.search(r'CREATE TABLE `(.*?)`', statement, re.IGNORECASE)
if match:
table_name = match.group(1)
else:
raise ValueError("Could not parse table name in CREATE TABLE statement.")
columns = []
primary_keys = []
foreign_keys = []
# Extract column definitions
column_defs = re.findall(r'`(.*?)` (.*?)(,|\n)', statement)
for col_def in column_defs:
col_name = col_def[0]
col_type = col_def[1].split()[0]
columns.append({'name': col_name, 'type': col_type})
# Extract primary keys
pk_match = re.search(r'PRIMARY KEY \((.*?)\)', statement, re.IGNORECASE)
if pk_match:
pk_cols = re.findall(r'`(.*?)`', pk_match.group(1))
primary_keys.extend(pk_cols)
# Extract foreign keys
fk_matches = re.findall(r'FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)', statement, re.IGNORECASE)
for fk in fk_matches:
fk_column = fk[0]
ref_table = fk[1]
ref_column = fk[2]
foreign_keys.append({'column': fk_column, 'ref_table': ref_table, 'ref_column': ref_column})
return table_name, columns, primary_keys, foreign_keys
def parse_insert(statement):
# Extract table name
match = re.match(r'INSERT INTO `(.*?)`', statement, re.IGNORECASE)
if match:
table_name = match.group(1)
else:
raise ValueError("Could not parse table name in INSERT INTO statement.")
# Extract values
values_matches = re.findall(r'\((.*?)\)', statement)
values_list = []
for value_str in values_matches:
values = parse_values(value_str)
values_list.append(values)
return table_name, values_list
def parse_values(value_str):
# Split values considering that values may contain commas
values = []
current_value = ''
in_string = False
escape = False
for char in value_str:
if char == '\'' and not escape:
in_string = not in_string
current_value += char
elif char == '\\' and in_string:
escape = True
current_value += char
elif char == ',' and not in_string:
values.append(current_value.strip())
current_value = ''
else:
current_value += char
escape = False
values.append(current_value.strip())
return values
def get_primary_key_value(schema, primary_keys, record):
pk_values = []
for pk in primary_keys:
idx = get_column_index(schema, pk)
pk_values.append(record[idx])
return tuple(pk_values)
def get_column_index(schema, column_name):
for idx, column in enumerate(schema):
if column['name'] == column_name:
return idx
raise ValueError(f"Column {column_name} not found in schema.")
def get_column_value(schema, column_name, record):
idx = get_column_index(schema, column_name)
return record[idx]
def write_insert_statements(file_obj, table_name, schema, records):
file_obj.write(f'INSERT INTO `{table_name}` VALUES\n')
for idx, record in enumerate(records):
record_str = '(' + ', '.join(record) + ')'
if idx < len(records) - 1:
record_str += ',\n'
else:
record_str += ';\n\n'
file_obj.write(record_str)
if __name__ == '__main__':
main()
Explanation:
This Python script reads the example.sql file, parses the SQL statements, and selects approximately 2% of the entries from the root tables (tables without foreign key dependencies). It then includes any referenced records based on foreign key relationships to ensure the subset is self-contained and maintains referential integrity.
Key steps in the script:
Parse CREATE TABLE Statements:
It extracts table definitions, columns, primary keys, and foreign key relationships.
This is crucial for understanding how tables relate to each other.
Parse INSERT Statements:
It collects all the data inserted into each table.
The data is stored in a way that allows for easy access by table and record.
Sampling Records:
The script randomly selects 2% of the records from the root tables.
Root tables are those that do not have foreign key references to other tables.
Maintaining Referential Integrity:
For each selected record, the script checks for any foreign key references.
It includes the referenced records in the related tables.
This process is repeated until no new records need to be included.
Writing Reduced SQL File:
The script writes the CREATE TABLE statements to the new reduced.sql file.
It writes the INSERT statements only for the records included in the subset.
All Spanish characters are correctly handled by using UTF-8 encoding.
Note:
The script uses regular expressions to parse the SQL statements. It handles basic SQL syntax and may need adjustments for complex SQL files.
It uses the random module to sample approximately 2% of the records.
The script outputs the reduced SQL to reduced.sql in the same folder.
Handling Spanish Characters:
The script reads and writes files using encoding='utf-8', which properly handles Spanish characters and other Unicode text.
Dependencies:
The script uses the sqlparse module for parsing SQL statements. You may need to install it using pip install sqlparse.