Use yield as expression for a quick in-database filter

Viewed 53

I'm studying about coroutines and I came across an explanation, about how yield as an expression, locks the function waiting to receive a value. Thinking about it, I ended up having an idea, which is the following: let's suppose that I wanted to make a filter in a querie (for example, using pandas). For this, I would make the query in the database before receiving the filter value, that is, the query would already be ready, just needing the filter. Think of the list as the result of the query:

def create_corroutine(func):
  def wrapper(*args, **kwargs):
    coro = func(*args, **kwargs)
    next(coro)
    return coro
  return wrapper

@create_corroutine
def corroutine():
    query = ['Giannis', 'Lebron', 'Ja Morant']

    while True:
      person_search = yield
      
      person_search = [person for person in query if person == person_search]
      
      print(person_search)


c = corroutine()
c.send('Lebron')

Is this a valid thought?

1 Answers

Yes, you are quite astute.

This is called the volcano pattern in database query systems

The query can be a complete boolean expression as well expressed as an S-tree

You can then merge these with other operators such as limit or group by

Related