Last active
March 6, 2020 01:20
-
-
Save tnibert/87e92da69bab71710190e7e320e19a41 to your computer and use it in GitHub Desktop.
SQL implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This contains various implementations of SQL functions in python | |
The two functions are not built for the same context | |
""" | |
def hash_join(table1, index1, table2, index2): | |
""" | |
Perform a sql like join operation on two dicts, on the specified indexes | |
""" | |
from collections import defaultdict | |
h = defaultdict(list) | |
# hash phase | |
for s in table1: | |
h[s[index1]].append(s) | |
# join phase | |
return [(s + r) for r in table2 for s in h[r[index2]]] | |
def select(self, *args, where=lambda e: True): | |
""" | |
Perform an SQL select supporting where clause | |
Designed to be used in a class with a json member | |
:param args: columns to query | |
:param where: a lambda with one argument returning a boolean, functions as where clause | |
each entry in the json will be compared with the where clause | |
:return: | |
""" | |
returned_data = [] | |
if len(args) == 0: | |
args = self.json["content"][0].keys() | |
# filter out by the where clause | |
filtered = filter(where, self.json["content"]) | |
for entry in filtered: | |
filtered_entry = {} | |
for arg in args: | |
filtered_entry[arg] = entry[arg] | |
returned_data.append(filtered_entry) | |
return returned_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment