<?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 Rakshit Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Rakshit Choudhary on Medium]]></description>
        <link>https://medium.com/@Darth_Knight?source=rss-3f5b86579ac7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*iMIQRWGGaLWpsG91I1OESQ.jpeg</url>
            <title>Stories by Rakshit Choudhary on Medium</title>
            <link>https://medium.com/@Darth_Knight?source=rss-3f5b86579ac7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:43:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Darth_Knight/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[Dynamic Models In SQL]]></title>
            <link>https://medium.com/@Darth_Knight/dynamic-models-in-sql-798b3f10458d?source=rss-3f5b86579ac7------2</link>
            <guid isPermaLink="false">https://medium.com/p/798b3f10458d</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rakshit Choudhary]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 03:45:53 GMT</pubDate>
            <atom:updated>2020-12-23T13:13:02.928Z</atom:updated>
            <content:encoded><![CDATA[<p>We at Grofers started using segment as our solution for enabling us to create different user segments for running analytics. It exports the segments created on the dashboard to our self hosted database to which our internal services can query from. This integration was adding new columns to our table every time a new segment was created on the dashboard. Now in order to query these columns we had to update the model in our codebase every time a new column was added. This turned out to be quite cumbersome for us to manage.</p><p>We could have gone with an integration with a NoSQL database like MongoDB but segment currently doesn’t support it.</p><p>The solution we ended up going up was for creating dynamic models in SQL using SQLAlchemy’s Inspector class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w24h-sYXh2ka9a8px4vPuA.png" /></figure><h3>Introduction</h3><p>This is a quick tutorial on how to create dynamic models in SqlAlchemy by getting the latest table metadata from the database.</p><h4><strong>Model :</strong></h4><p>A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you&#39;re storing. Generally, each model maps to a single database table.</p><p><strong>The basics:</strong></p><ul><li>Each model is a Python class.</li><li>Each attribute of the model represents a database field.</li><li>With all of this, Flask gives you an automatically-generated database-access API; see<a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/"> Making queries</a>.</li></ul><pre><strong>class</strong> <strong>User</strong>(db.model):<br>    __tablename__ = &quot;users&quot;<br>    <br>    id = db.Column(db.BigInteger, primary_key=True)<br>    name = db.Column(db.Text, index=True)<br>    email = db.Column(db.Text, index=True)<br>    segment_A = db.Column(db.Boolean, index=True)<br>    segment_B = db.Column(db.Boolean, index=True)</pre><p><strong>But the problem arises when the columns in your table change very frequently.</strong></p><p>In such a scenario you need to update your model every time you are adding a new column to your table. Which is very tedious if you are dealing with production code.</p><h4>Enter the SQLAlchemy Inspector<strong> :</strong></h4><p>So we can overcome this by dynamically fetching the metadata about the database and then creating the model on the fly.</p><p>SQLAlchemy provides <a href="https://docs.sqlalchemy.org/en/13/core/reflection.html#fine-grained-reflection-with-inspector"><strong>Inspector</strong></a> which is a low-level interface that provides a backend-agnostic system of loading lists of schema, table, column, and constraint descriptions from a given database are also available.</p><p>A <a href="https://docs.sqlalchemy.org/en/13/core/reflection.html#sqlalchemy.engine.reflection.Inspector">Inspector</a> an object is usually created via the <a href="https://docs.sqlalchemy.org/en/13/core/inspection.html#sqlalchemy.inspection.inspect">inspect()</a> function:</p><pre>from sqlalchemy import inspect, create_engine<br>engine = create_engine(&#39;SQLALCHEMY_DATABASE_URI&#39;)<br>insp = inspect(engine)</pre><p>Inspector returns the following things from the database</p><ul><li>Schema</li><li>Tables</li><li>Columns and constraints.</li></ul><p>Inspector object has different methods that we can use to extract out information that we need about the DB like schema name, foreign keys, indexes etc . You can read more about these <a href="https://docs.sqlalchemy.org/en/13/core/reflection.html#sqlalchemy.engine.reflection.Inspector.default_schema_name"><strong>here</strong></a>. In this blog, we will be using the <strong>get_columns</strong> method of the inspector object which gives us information about columns.</p><pre><strong>def refresh_user_model()</strong>:<br>    # getting the schema and extracting the required column names<br>    inspector = Inspector.from_engine(engine)<br>    db_columns = inspector.get_columns(&#39;users&#39;,schema=DB_SCHEMA)<br>    new_user_model_columns = []<br>    for column in db_columns:<br>        new_user_model_columns.append(tuple([column[&#39;name&#39;],<br>                                             column[&#39;type&#39;]]))</pre><p>get_columns return column information as a list of dicts with these keys:</p><ul><li><strong>name</strong> - the column’s name</li><li><strong>type</strong> - the type of this column; an instance of <a href="https://docs.sqlalchemy.org/en/13/core/type_api.html#sqlalchemy.types.TypeEngine">TypeEngine</a></li><li><strong>nullable</strong> - boolean flag if the column is NULL or NOT NULL</li><li><strong>default</strong> - the column’s server default value - this is returned as a string SQL expression.</li><li><strong>attrs</strong> - dict containing optional column attributes</li></ul><h4><strong>Primary Key Requirement in Models</strong></h4><p>One important point to note is that while defining a model in SQLAlchemy we need to assign a primary key to every model. Because in order to map to a particular table, SQLAlchemy ORM needs at least <strong>one column denoted as a primary key column.</strong></p><p>So creating a new model we need to manually make a key as a primary key. Here I am mapping ‘<strong>id’ </strong>as a primary key because most of the tables have a unique identifier ‘<strong>id’</strong> present in them.</p><p>Now in order to map a new model with an existing model, we can use <a href="https://docs.sqlalchemy.org/en/13/orm/mapping_styles.html#classical-mappings"><strong>mapper</strong></a><strong>() function</strong>. A mapper appends the new table model with another model.</p><p>Because I have manually added id as a primary key I need to remove it from my new_user_model_columns in order to<strong> avoid mapping the same column twice</strong>.</p><p>Finally, before mapping a table again we need to clear the previous mapping as I am calling this method repeatedly at regular intervals. For that, we are using <strong>clear_mappers()</strong> which clears all the previous mappings.</p><pre># remaking the entire model<br>new_user_model_columns.remove(&#39;id&#39;,&#39;BigInteger&#39;)<br>metadata = MetaData(bind=engine, schema=DB_SCHEMA)<br>new_user_model = Table(&#39;users&#39;, metadata,<br>                     Column(&#39;id&#39;, BigInteger, primary_key=True),<br>                     *(Column(col, type) for col, type in <br>                                        new_user_model_columns))<br>clear_mappers()<br>mapper(User, new_user_model)</pre><p><strong>Periodic refreshing the model :</strong></p><p>For this, we can use threading where a method will keep on calling the <strong>refresh_user_model() </strong>method at regular intervals.</p><pre>def start_user_model_sync():<br>  threading.Timer(MODEL_REFRESH_TIME, start_user_model_sync).start()<br>  refresh_user_model() </pre><p>It takes around <strong>.03-.04 seconds</strong> to refresh the model.</p><p>Thanks for reading! If you have any questions or comments, please leave a response below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=798b3f10458d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>