Skip to content

Instantly share code, notes, and snippets.

@mostafa6765
Created August 13, 2024 09:51
Show Gist options
  • Save mostafa6765/28556ce66ec6ea491054964bde8f551b to your computer and use it in GitHub Desktop.
Save mostafa6765/28556ce66ec6ea491054964bde8f551b to your computer and use it in GitHub Desktop.
import re
def get_run_sql_metadata(sql_conditions_data):
sql_conditions = []
the_vars = {}
for condition in sql_conditions_data:
key_name = condition['key_name']
value = condition['value']
static_value = condition['static_value']
# Split the static_value by ';' and update the_vars dictionary
key_value_pairs = [pair.split('=') for pair in static_value.strip(';').split(';')]
for key, val in key_value_pairs:
the_vars[key] = val.strip("'")
# Add the key and value to sql_conditions
sql_conditions.append({key_name: value})
return sql_conditions, the_vars
def extract_variables(text):
pattern = r'\{(\w+)\}' # Regular expression pattern to find all occurrences of {word}
matches = re.findall(pattern, text) # Find all matches
return list(matches) # Convert matches to a list
def format_condition(conditions, the_vars):
formatted_conditions = {}
for condition in conditions:
key = condition.get("key_name", "")
value_template = condition.get("value", "")
is_all_var_exist = True
# Check if variables need to be extracted and added to the_vars
variables = extract_variables(value_template)
the_vars_keys = the_vars.keys()
for var in variables:
if var not in the_vars_keys:
is_all_var_exist = False
break
if is_all_var_exist:
# Format value with the provided variables
formatted_value = value_template.format(**the_vars)
formatted_conditions[key] = formatted_value
else:
formatted_conditions[key] = " "
return formatted_conditions
def get_the_actual_sql(request, the_sql_content, the_sql_condition):
sql_conditions, the_vars = get_run_sql_metadata(the_sql_condition)
sql_conditions = format_condition(sql_conditions, the_vars)
# Replace customsql placeholders in SQL contents with values from sql_conditions
if the_sql_content and sql_conditions:
for key, value in sql_conditions.items():
placeholder = f"--customsql{{{key}}}"
the_sql_content = re.sub(placeholder, value, the_sql_content)
return {
'sql_contents': the_sql_content
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment