<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Parth Joshi on Medium]]></title>
        <description><![CDATA[Stories by Parth Joshi on Medium]]></description>
        <link>https://medium.com/@parthjoshi90?source=rss-6e27044910ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gwuHculK2wS8esGZ.jpg</url>
            <title>Stories by Parth Joshi on Medium</title>
            <link>https://medium.com/@parthjoshi90?source=rss-6e27044910ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:31:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parthjoshi90/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The AST: Immutable, Composable Filter Expressions]]></title>
            <link>https://medium.com/@parthjoshi90/the-ast-immutable-composable-filter-expressions-4b1b61dacfcb?source=rss-6e27044910ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b1b61dacfcb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[specification-pattern]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <dc:creator><![CDATA[Parth Joshi]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 07:15:19 GMT</pubDate>
            <atom:updated>2026-04-18T07:15:19.248Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Escaping the Filter Maze (Part 2)</strong></p><p>For many developers, building dynamic database queries eventually turns into a <strong>filter maze</strong>. It usually starts with the procedural mess of building a dictionary: <strong>if status: filters[&#39;status&#39;] = status</strong>. As requirements evolve to include logical OR conditions, negated logic, or complex child relationships, the code descends into a fragile web of conditional string concatenations and deeply nested dictionary manipulation.</p><p>In this common anti-pattern, your business logic becomes inextricably tangled with database-specific implementation details.AxiomQuery provides this by implementing the Specification Pattern through an <strong>Abstract Syntax Tree (AST)</strong>. By treating query intent as pure, composable data, we shift away from the &quot;filter maze&quot; and toward a system where logic is a first-class citizen—predictable, testable, and entirely decoupled from the database driver.</p><p><strong>Takeaway 1: Your Predicates are Values, Not Commands</strong></p><p>The core architectural shift in AxiomQuery is the move from executing a query to constructing a “Value Object.” Instead of passing a command directly to the database, you define a leaf node called a Condition. This node, paired with the Op enum, ensures your logic is typed and validated in the application layer before it ever touches a database session.</p><p>This shift moves logic out of the driver and into pure Python, supporting 11 distinct operators categorized for clarity:</p><ul><li>Comparison: Equal (=),</li><li>Not Equal (!=),</li><li>Greater Than (&gt;),</li><li>Less Than (&lt;),</li><li>Greater Than or Equal (&gt;=), and Less Than or Equal (&lt;=).</li><li>Membership: In and Not In (where the value is a list).</li><li>Pattern Matching: Like and ILike (supporting % wildcards).</li><li>Null Checks: Is Null (evaluating to True or False).</li></ul><p>The AST is pure Python — it can be serialized, logged, tested, compared, and debugged without a database.</p><p><strong>Takeaway 2: The Power of Operator Overloading (&amp;, |, ~)</strong></p><p>Dictionary-based filtering fails because it lacks a readable syntax for complex logic. AxiomQuery solves this by utilizing Python’s native bitwise operators to create a <strong>Domain Specific Language (DSL)</strong>. This DSL maps the developer’s mental model directly to the AST structure, significantly improving the <strong>scannability</strong> of the code.</p><p>By overloading these operators, the library constructs And, Or, and Invert nodes through intuitive symbols:</p><ul><li><strong>&amp; maps to And:</strong> Joins multiple conditions where all must be satisfied.</li><li><strong>| maps to Or:</strong> Joins conditions where at least one must be satisfied.</li><li><strong>~ maps to Invert:</strong> Negates the underlying condition or logical group.</li></ul><p>This approach eliminates <strong>nested dictionary hell</strong>, providing a narrative flow to query definitions that matches how we reason about business rules.</p><p><strong>Takeaway 3: The “Identity Element” (The Secret to Optional Filters)</strong></p><p>Building optional filters typically requires repetitive <strong>if</strong> checks to see if a list is empty before appending logic. AxiomQuery treats Bool(True) as a logical identity element—the <strong>null object</strong> of the filter world.</p><p>In this system, None or an empty list [] automatically parses to Bool(True). This is architecturally significant because of the identity property: Bool(True) &amp; condition == condition. By starting a filter chain with this identity element, you can append optional filters without worrying about the current state of the chain. It provides a stable, default state for filters that simplifies logic and removes the need for guard clauses.</p><p><strong>Takeaway 4: Immutability and the “Frozen” Advantage</strong></p><p>AxiomQuery utilizes Frozen Dataclasses for its AST nodes. Making filters immutable and hashable is a major win for reliability. Because these nodes are <strong>frozen</strong>, Equality is determined by content rather than memory reference.</p><p>This enables memoization and deterministic testing. Because the AST nodes are hashable, they can serve as keys in a cache to store pre-compiled SQL statements. This significantly reduces computation overhead in high-traffic APIs, as identical logic trees can bypass the compilation phase entirely.</p><p>Safe for caching and predictable equality.</p><p><strong>Takeaway 5: Zero Dependencies at the Core</strong></p><p>A defining architectural choice is the absolute separation of concerns. The core AST components — defined in <strong>operators.py</strong> and <strong>ast.py</strong>—contain zero SQLAlchemy imports. The <strong>intent</strong> of the query is completely decoupled from the <strong>execution</strong> (handled later in <strong>compiler.py</strong>).</p><p>This separation ensures that your business specifications are not brittle. The AST acts as a pure representation of business intent, serving as a clean bridge between your transport layer (JSON) and your persistence layer (SQL).</p><p>The AST knows nothing about JSON, acts as a bridge for business intent, and knows nothing about the database.</p><p><strong>Conclusion: The Future of Composable Logic</strong></p><p>Embracing the Specification Pattern through an AST transforms logic into a portable asset. By moving away from strings and toward structured, immutable data, we gain the ability to manipulate, optimize, and transport our business rules across any boundary.</p><h3>🚀 Escape the Filter Maze: Try It Yourself</h3><p>Moving beyond brittle dictionaries is a paradigm shift, but you don’t have to build it from scratch. The complete source code for <strong>AxiomQuery</strong>, including the AST parser, SQLAlchemy compiler, and integration examples, is fully open-source.</p><p>🔗 <a href="https://github.com/Axiom-Dev-Labs/AxiomQuery"><strong>Explore the AxiomQuery Repository on GitHub</strong></a></p><p><strong>In the repo, you’ll find:</strong></p><ul><li>Out-of-the-box support for nested AND/OR logic.</li><li>Automated EXISTS subqueries for child relationship filtering.</li><li>Examples of integrating the JSON wire format with modern APIs.</li></ul><p><em>If this architecture helps you clean up your database logic or saves you from the maintenance tax, consider giving the repository a ⭐ to help other developers find it!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b1b61dacfcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Dictionary: Why Your Dynamic Filters Fail at Scale]]></title>
            <link>https://medium.com/@parthjoshi90/beyond-the-dictionary-why-your-dynamic-filters-fail-at-scale-5deaa71c94e9?source=rss-6e27044910ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5deaa71c94e9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[specification-pattern]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <dc:creator><![CDATA[Parth Joshi]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 16:35:46 GMT</pubDate>
            <atom:updated>2026-04-05T16:35:46.539Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Escaping the Filter Maze (Part 1)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-i_ibXJJsm_D_ROeUwJdDA.png" /></figure><p>It always starts with a single search bar. You’re building a list view, and the requirement is modest: “Let users filter by status.” You add an optional argument to your function, wrap a session.query in a quick if status:, and ship it.</p><p>But requirements never stay modest. Next comes date ranges. Then “exclude these categories.” Then “match any of these tags.” Before you realize it, your clean data layer has spiraled into a 300-line tangle of conditional logic and manual dictionary hacking.</p><p>This is the “filter maze.” It is a state where dynamic query building quietly becomes unmaintainable, turning what should be a simple data retrieval task into a fragile architectural burden. While the standard Python filters = {} approach feels like a quick win for an MVP, but it is a technical debt trap that eventually catches every growing project.</p><p><strong><em>The “If-Else” Sprawl and the Maintenance Tax</em></strong></p><p>The typical Python pattern for handling dynamic queries involves initializing an empty dictionary and conditionally appending keys based on optional function arguments.</p><pre>def get_orders(status=None, category=None, min_price=None):<br>    filters = {}<br>    if status:<br>        filters[&quot;status&quot;] = status<br>    if category:<br>        filters[&quot;category&quot;] = category<br>    # ... this continues until the function is unreadable<br>    return session.query(Order).filter_by(**filters).all()</pre><p>While this looks harmless, it imposes a brutal <strong><em>“maintenance tax.”</em></strong> This pattern erodes team velocity and eventually turns the codebase into a “no-go zone” for new developers. Every new requirement demands more boilerplate, more function parameters, and more unit tests for every possible permutation of if statements.</p><blockquote><em>“The filter maze: how dynamic query building quietly becomes unmaintainable.”</em></blockquote><p>Because this logic is imperative rather than declarative, it relies on “tribal knowledge.” Only the original author truly understands how the filters interact, making the system impossible to refactor with confidence.</p><p><strong>The Composition Wall (Why OR and NOT Logic Breaks the Dict)</strong></p><p>The primary technical failure of dictionary-based filters is that they are inherently flat AND structures. A dictionary can represent key1=A AND key2=B, but it fundamentally cannot represent nested logical trees.</p><p>As soon as a user asks for “Orders that are (Status: Pending OR Overdue) AND (Total &gt; 100),” the dictionary pattern hits a wall. Dictionaries are 1-level deep; real-world queries are recursive trees. To bridge this gap, developers usually descend into “logic hacks” — manually stringing together SQLAlchemy or_() or not_() clauses in brittle, ad-hoc blocks that violate the DRY (Don&#39;t Repeat Yourself) principle.</p><p>The problem intensifies with “child traversal.” If you need to filter parents based on a child relationship — for example, “Find all orders where a child OrderLine has a quantity &gt; 10” — a flat dictionary is useless. Most developers solve this by forcing manual joins, which risks creating massive Cartesian products and tanking database performance. A mature system should handle this via EXISTS subqueries automatically, but doing so manually for every optional filter is a recipe for exhaustion.</p><p><strong>The Divergence Dilemma (URL Params vs. ORM vs. SQL)</strong></p><p>When you rely on ad-hoc filtering, you suffer from a lack of a “canonical filter representation.” Your query logic ends up expressed in three divergent ways:</p><ol><li><strong>The Wire Format:</strong> URL parameters like ?status=active&amp;min_price=100.</li><li><strong>The App Logic:</strong> The intermediate Python filters dict and its associated if statements.</li><li><strong>The Database Execution:</strong> The final SQL generated by the ORM.</li></ol><p>These layers inevitably drift. A change in how the frontend sends a date format might require manual updates across the entire backend stack just to ensure the SQL remains valid. Without a single source of truth for what a “filter” is, the API behavior and the database execution will eventually disagree, leading to subtle, hard-to-track bugs.</p><p><strong>The Specification Solution (The Power of a Composable AST)</strong></p><p>The architectural antidote is the Specification pattern. Instead of building queries by manually assembling a dictionary, we shift to a composable, immutable AST (Abstract Syntax Tree). In this model, filters are treated as data, not just side-effecting code fragments.</p><p>By using an engine like AxiomQuery, you move logic from imperative code into a declarative structure. The “Canonical Representation” becomes a simple JSON domain that can be passed directly from the frontend to the backend:</p><p>[[&quot;status&quot;, &quot;=&quot;, &quot;CONFIRMED&quot;], [&quot;total&quot;, &quot;&gt;&quot;, 100]]</p><p>This JSON isn’t just a list of strings; it’s a wire format that the engine parses into a Python AST. Because the AST is a tree of value objects (Nodes), you can compose them using standard Python operators:</p><pre># Composing filters in Python<br>large_orders = Condition(&quot;total&quot;, &quot;&gt;&quot;, 100)<br>active_orders = Condition(&quot;status&quot;, &quot;=&quot;, &quot;CONFIRMED&quot;)<br>my_query = active_orders &amp; large_orders</pre><p>This approach allows a single representation to be parsed from JSON, composed in Python, and compiled safely into SQL WHERE clauses. By leveraging SQLAlchemy inspect() Internally, the system derives the schema directly from your models, handling complex logic and `EXISTS &#39;- based child traversal without you writing a single line of join logic.</p><p><strong>Conclusion: From Brittle Dicts to Scalable Systems</strong></p><p>Transitioning from brittle dictionaries to a specification-based system like <strong>AxiomQuery</strong> is the difference between a project that stalls under its own weight and one that scales. You gain a “Single Source of Truth” that works across the entire stack, supporting everything from complex nested logic to high-performance Async APIs.</p><p>If your filtering logic were treated as a first-class data structure instead of a side effect of your API, how much simpler would your architecture become? Moving beyond the dictionary isn’t just a refactor; it’s a commitment to building systems that are resilient to the inevitable complexity of real-world data.</p><h3>🚀 Escape the Filter Maze: Try It Yourself</h3><p>Moving beyond brittle dictionaries is a paradigm shift, but you don’t have to build it from scratch. The complete source code for <strong>AxiomQuery</strong>, including the AST parser, SQLAlchemy compiler, and integration examples, is fully open-source.</p><p>🔗 <a href="https://github.com/Axiom-Dev-Labs/AxiomQuery"><strong>Explore the AxiomQuery Repository on GitHub</strong></a></p><p><strong>In the repo, you’ll find:</strong></p><ul><li>Out-of-the-box support for nested AND/OR logic.</li><li>Automated EXISTS subqueries for child relationship filtering.</li><li>Examples of Usage.</li></ul><p><em>If this architecture helps you clean up your database logic or saves you from the maintenance tax, consider giving the repository a ⭐ to help other developers find it!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5deaa71c94e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>