Skip to content

Instantly share code, notes, and snippets.

@gargomoma
Created January 10, 2023 15:44
Show Gist options
  • Save gargomoma/9a3fd0ad0d08aa7463189a73e5462dfe to your computer and use it in GitHub Desktop.
Save gargomoma/9a3fd0ad0d08aa7463189a73e5462dfe to your computer and use it in GitHub Desktop.
python code for people that hates to do huge SQL queries
##
##Coming from your friendly neighborhood Spider-Man!
##
def chunkArray(ArrObj, length):
'''Splits a list on a list of lists given a lenght'''
return list(ArrObj[0+i:length+i] for i in range(0, len(ArrObj), length))
def where_in_builder(list_of_elements, var_to_filter,split_by=1_000,is_str=True,return_as_str=True):
'''Builds a IN(...) clause from a list, user can select either a single string or a list of IN(...) for each chunk'''
quotation = "'" if is_str else ""
in_list = [ '{0} in({1})'.format( var_to_filter , ' ,'.join( [f"{quotation}{x}{quotation}" for x in chunk_list ] ) ) for chunk_list in chunkArray(list_of_elements, split_by ) ]
return '\n OR '.join( in_list ) if return_as_str else in_list
def where_or_builder(list_of_elements, var_to_filter,split_by=1_000,is_str=True,return_as_str=True):
'''Builds a OR varname clause from a list, user can select either a single string or a list of OR varname for each chunk'''
quotation = "'" if is_str else ""
or_list = [ '\n OR '.join( [f"{var_to_filter} = {quotation}{x}{quotation}" for x in chunk_list ] ) for chunk_list in chunkArray(list_of_elements, split_by ) ]
return ' OR '.join( or_list ) if return_as_str else in_list
def where_in_builder_split(list_of_elements, var_to_filter,split_by=1_000,is_str=True,return_as_str=True):
where_in = where_in_builder(list_of_elements, var_to_filter,split_by,is_str,return_as_str)
return where_in.split("OR")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment