title: Storing logic inside database
body: <p>This is NOT about stored procedures (or at least i don't think it is).</p>
  
  <p>Lets say i have a database. A database has some cities in it and events that take place in those cities. Some people are going to use this site and they want to get notified about certain events, when they enter the site. <br />
  The rules for specifying what events they want to be notified about are supposed to be general.</p>
  
  <p>For example, i would want user to be able to say "I want to be notified about all events, that will take place on sunday, in city that was founded between year 1200 and 1400, in the country which name starts with the letter "F" or which is in South America", which would be translate in pseudo-logic-code of:</p>
  
  <pre><code>  (
    event.date.day == Sunday 
    and 
    event.city.founded_date.year.between(1200, 1400)
    ) 
  AND 
    (
    event.city.country.starts_with("F")
    or
    event.city.country.continent == "South Africa"
    )
  </code></pre>
  
  <p>The rules like "continent is", "day is", "foundation date is between" et cetera are to be predefined, user will choose it, but i want to be able to add new rules in future.</p>
  
  <p>What is the best way to store such logic? The only solution i can come up with is a "NotificationGatherer" model. It would contain id of a user, and a string with json.
  I would create a json binary tree, for this particular case, the capitalized "AND" would be a root with two children - the inner and and inner or.
  The first children would have two simple conditions, which would reflect the actual conditions as abive.</p>
  
  <p>Then i would have a method that's called on user's request, which would either:<br /></p>
  
  <ol>
  <li><p>Evaluate the value (true/false) of this conditions set for all upcoming events</p>
  
  <p>or</p></li>
  <li><p>Form a queryset with filters, which would fetch all the upcoming events that satisfy given conditions (much more difficult and much more efficient).</p></li>
  </ol>
  
  <p>Now, is this even a good approach, or should i try something else?
  It seems rather complex (I already see how painful it would be to test it), and i can imagine that a lot of people could have needed something like this in the past, yet i can't find any suggestions, because any searching for "logic in database" automatically points me to articles/questions about stored procedures.</p>
  
  <p>If that makes any difference, I'm using django and mysql.</p>