<?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 Shrinivas Deshmukh on Medium]]></title>
        <description><![CDATA[Stories by Shrinivas Deshmukh on Medium]]></description>
        <link>https://medium.com/@shrinivdeshmukh?source=rss-62bb2f9dfa3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*plc-_1ERxvyCJfdYHZEXZQ.jpeg</url>
            <title>Stories by Shrinivas Deshmukh on Medium</title>
            <link>https://medium.com/@shrinivdeshmukh?source=rss-62bb2f9dfa3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:14:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shrinivdeshmukh/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[Alchemy modelgen: Database Migrations made Easier (Part 2)]]></title>
            <link>https://shrinivdeshmukh.medium.com/alchemy-modelgen-database-migrations-made-easier-part-2-18b9ac41b102?source=rss-62bb2f9dfa3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b9ac41b102</guid>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[time-travel]]></category>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[schema-versioning]]></category>
            <dc:creator><![CDATA[Shrinivas Deshmukh]]></dc:creator>
            <pubDate>Mon, 31 May 2021 15:35:37 GMT</pubDate>
            <atom:updated>2021-06-01T15:48:17.687Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part 2 of the alchemy-modelgen series. <a href="https://shrinivdeshmukh.medium.com/alchemy-modelgen-database-migrations-made-easier-151f0d44ad2"><strong>Click here</strong></a> to read part 1 of this series. In this post, we’ll use a YAML file to perform operations on a database. We’ll look at how to define schema in YAML files, create tables from YAML, change the schema, and switch between schema versions.</p><p>Throughout this post, we’ll be using the sqlite database.</p><h3>Table of Contents</h3><ul><li><a href="#eb47">About YAML format</a></li><li><a href="#a3a8">Initialize alchemy-modelgen</a></li><li><a href="#7c40">Write the YAML file</a></li><li><a href="#c2a9">Create tables for the first time in the sqlite database</a></li><li><a href="#b6cf">Alter the tables</a></li><li><a href="#b368">Time Travel</a></li><li><a href="#b610">Conclusion</a></li></ul><h3>About YAML format</h3><p>Why use a YAML file? To answer the question, let’s look at what is a YAML file.</p><p>Yet Another Markup Language (YAML) is an acronym for Yet Another Markup Language. It’s a simple, human-readable file format that’s commonly used for writing configurations, documentation, and, in this case, table schemas. Scalar data types like strings, integers, and floats, as well as associative arrays like maps, dictionaries, and hashes, are natively encoded in YAML.</p><p>YAML files have a simple syntax that is simple to read and write. The colon : denotes key-value pairs, while the hyphen - denotes arrays or lists. For example, in the snippet below, the key is address, and the value is Mumbai, India.</p><pre>address: Mumbai, India</pre><p>This syntax can be extended for complex key value pairs. For example, in the snippet below, we have address as the parent key, city, and country as the child keys and their corresponsing values as values</p><pre>address:<br>	city: Mumbai<br>	country: India</pre><p>As we can see, YAML files are simple to read, write, and maintain. There is no complicated syntax, they can be passed from one person to another without losing readability, and they are simple to store and maintain (they’re just text files!).</p><p>Now that we’ve learned what YAML files are and why they’re so simple to read and write, let’s take a look at how alchemy-modelgen uses them to make database maintenance easier.</p><p>The command modelgen can be used to interact with the tool. This is the cli that comes with the tool. We’ll start by initializing alchemy-modelgen, then move on to more advanced database operations.</p><h3>Initialize alchemy-modelgen</h3><p>A folder structure is created as a result of the initialize action. This folder is necessary for alchemy-modelgen to keep track of our database.</p><pre>modelgen init -d myproject</pre><pre>cd myproject</pre><p>This results in the following structure:</p><pre>myproject<br>├── alembic_migrate<br>│   └── __init__.py<br>│   └── env.py<br>│   └── script.py.mako<br>│   └── versions<br>│ 	└── __init__.py<br>│   └── README<br>├── templates<br>│   └── example.yaml<br>└── alembic.ini</pre><p>The schemas defined in the YAML file are translated to a format that alchemy-modelgen can understand using sqlalchemy, a python ORM tool. The translated files can be found in the myproject/models/ folder.</p><h3>Write the YAML file</h3><p>Take, for example, a food delivery app. The app stores user information such as name, address, and phone number, as well as order details such as which restaurant the user ordered from, the order amount, and the date of the order. This will be our use case for the rest of the article.</p><p>We start with 2 tables, user and order in a yaml file templates/foodelivery.yaml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7733f607f51e610c05d85947b24533/href">https://medium.com/media/af7733f607f51e610c05d85947b24533/href</a></iframe><p>Let’s look at the YAML snippet above and see what each field means.</p><p>We’ll start with the table parent tag. The alchemy-modelgen keyword table points to the beginning of the YAML schema file.</p><p>For the parent key tables, we have two child keys: user and order. Table names are created using these keys. These names will be used to create the tables. The user who is writing this YAML can specify these keys. These aren’t keywords for alchemy-modelgen.</p><p>The tables’ structure is defined by the sub keys of the two child keys. columns is the first sub key. columns is an alchemy-modelgen keyword that should be used in its original form. We define an array of columns in the columns sections, with their keys being name, type, primary key, and so on. The following keys are supported in the columns sections:</p><ul><li><strong>name:</strong> name of the column (string, ex: firstname, address, contact)</li><li><strong>type:</strong> datatype of the column (string, ex: integer, float, boolean, date)</li><li><strong>primary_key:</strong> whether the column is primary key or not (true or false are the supported only values, default is false)</li><li><strong>length:</strong> length of the column (integer, ex: 10, 2, 300, etc)</li><li><strong>unique:</strong> whether the values in the column should be unique or not (true or false are the supported only values, default is false)</li><li><strong>nullable:</strong> whether the column is allowed to be empty or not (true or false are the supported only values, default is false)</li><li><strong>foreign_key:</strong> whether to reference a primary key of some other table or not. Format is table_name.primary_key_column_name. In the example above, the table order is referencing user_id from the table user</li></ul><p>These sub keys in the column section are alchemy-modelgen keywords.</p><h3>Create tables for the first time in the sqlite database</h3><p>Let’s look at how to convert the YAML file into a format that alchemy-modelgen can understand, create our base (very first) version of schema, and create tables in the database now that we have the YAML file ready.</p><p>The YAML-to-alchemy-modelgen translation process is the first step. We do this by using the createmodel subcommand. -s or —source and -p or —path are the two parameters for createmodel.</p><p>The -s or —source option informs modelgen about the schema’s source, whether it’s a yaml file or an existing database. In this post, we’ll be looking at YAML. In the next installment of this series, we’ll look at the latter. Either yaml or database should be the value of -s. Our source is yaml in this case.</p><p>-p or —path tells modelgen where to find the YAML file. Using the -p parameter, we pass the filepath of the YAML file defined above. Our filepath is templates/foodelivery.yaml in this case.</p><pre>modelgen createmodel -s yaml -p templates/foodelivery.yaml -a</pre><p>If we look in the models folder, we should see a file called foodedelivery.py. This is the translated file that we are looking for. It’s worth noting that this file’s name is similar to that of the YAML file.</p><p>We’ll now create the table schema’s foundation, or the first version. For this version, our tool use the translated file created in the previous step. We use a subcommand called migrate for this. The following parameters are supported by migrate:</p><ul><li><strong>revision:</strong> revision creates a local version of the schema. It is similar to git commit</li><li><strong>current:</strong> show current active version</li><li><strong>history:</strong> list all the schema versions</li><li><strong>upgrade:</strong> upgrade the database according to the current version, similar to git push</li></ul><p>There are a few other subcommands, but we only need these in this section. In the following sections, we’ll look at the other commands.</p><p>Now let’s get started on our first version:</p><pre>modelgen migrate revision --autogenerate -m &#39;initial migration&#39; -p sqlite:///foodelivery.db</pre><p>What’s going on here is that our tool is looking for modified files in the models folder. For creating corresponding version files, any modified files (in this case models/foodelivery.py) are used. The alembic_migrate/versions folder is where these version files are stored. If we search the folder, we can see a file called cb88ceb46594 initial <a href="http://migration.py/">migration.py</a>. Take note of the file’s name. It contains our message which was passed by the -m parameter, as well as the unique identifier string cb88ceb46594 .</p><p>In the above command, we’ve passed --autogenerate, -m and -p parameters. Let’s look at what these parameters mean:</p><ul><li>--autogenerate: automatically create the version file and tag the file with a version id</li><li>-m or --message: message string to be used with the version. It is similar to git commit -m. It tells briefly what this version is about.</li><li>-p or --path: points to the database path. This path needs to be in sqlalchemy supported format which is<br> database+connector://username:password@host:port/database. Database connections supported by modelgen are:<br>1. <strong>mysql:</strong> mysql+mysqlconnector://&lt;username&gt;:&lt;password&gt;@&lt;host:&lt;port&gt;/&lt;database&gt; <br>2. <strong>postgresql:</strong> postgresql+psycopg2://&lt;username&gt;:&lt;password&gt;@&lt;host:&lt;port&gt;/&lt;database&gt; <br>3. <strong>redshift:</strong> redshift+psycopg2://&lt;username&gt;:&lt;password&gt;@&lt;host:&lt;port&gt;/&lt;database&gt; <br>4. <strong>snowflake:</strong> snowflake://&lt;username&gt;:&lt;password&gt;@&lt;account&gt; <br>5. <strong>sqlite:</strong> sqlite:///&lt;filepath&gt;.db</li></ul><p>More info about the sqlalchemy url format can be found here <a href="https://github.com/snowflakedb/snowflake-sqlalchemy">here</a>. Support for more databases will be added soon!</p><p>So far, we’ve translated our YAML file and created our first version file. To create tables in the database, our tool uses the version files created in the previous step. So, let’s get started on the database tables!</p><p>We again use the subcommand migrate to do this. Here, we pass the parameters upgrade head to the migrate subcommand:</p><pre>modelgen migrate upgrade head -p sqlite:///foodelivery.db</pre><p>Behind the scenes, our tools are looking for the latest version file in alembic_migrate/versions. This is the file that will be used to create the database tables.</p><p>The parameter upgrade means to <em>upgrade the database to the most recent version as specified in the yaml file</em>, while the parameter head <em>indicates the most recent version id</em>.</p><p><strong>NOTE: In the above commands, we’ve used<br> </strong><strong>-p sqlite:///foodelivery.db.<br> The alternate way to do this is by defining an environment variable </strong><strong>DATABASE_URI. This variable can be set to the database url like<br> </strong><strong>export DATABASE_URI=sqlite:///foodelivery.db.<br> In that case, the above commands can be like<br> </strong><strong>modelgen migrate revision --autogenerate -m &#39;initial migration&#39; or </strong><strong>modelgen migrate upgrade head</strong></p><p>This command will create a sqlite file in the directory called foodelivery.db.</p><p>Start a sqlite database interactive shell to verify the database’s tables:</p><pre>sqlite3 foodelivery.db 		   # start sqlite3 shell<br>sqlite&gt; pragma table_info(&#39;user&#39;);</pre><p><strong>OUTPUT</strong></p><pre>0|user_id|INTEGER|1||1</pre><pre>1|firstname|VARCHAR|0||0</pre><pre>2|lastname|VARCHAR|0||0</pre><pre>3|dob|DATE|0||0</pre><pre>4|contact|NUMERIC|1||0</pre><pre>5|address|VARCHAR(200)|0||0</pre><p>In the same terminal, let’s look at the order table</p><pre>sqlite&gt; pragma table_info(&#39;order&#39;);</pre><p><strong>OUTPUT</strong></p><pre>0|order_id|INTEGER|1||1</pre><pre>1|hotel_name|VARCHAR(100)|0||0</pre><pre>2|order_date|DATE|0||0</pre><pre>3|amount|FLOAT|0||0</pre><pre>4|user_id|INTEGER|0||0</pre><p>Both the tables are created in the foodelivery.db sqlite database.</p><p>To exit from the sqlite shell press ctrl+c three times.</p><p>This completed our one entire end to end flow. To summarise the flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*woXZIa_ALLhSDCMBxZWQRQ.png" /><figcaption>create table for the first time using YAML schema file</figcaption></figure><h3>Alter the tables</h3><p>Adding or deleting columns, changing the data type of a column, and adding or removing constraints are all examples of table changes.</p><p>Let’s take a closer look at this in the context of our use case. Let’s say as the owner of the food delivery app we want to add a new table to record the restaurant’s details. Also, we realized that during the development of the app the current length of our address column, which is 200 characters, is insufficient, and that some addresses exceed 200 characters, so we need to increase the length of the address column from 200 to 300 characters. What is the best way to accomplish this? What role can alchemy-modelgen play in this?</p><p>Let’s try to answer that. We begin by editing our yaml file which is at templates/foodelivery.yaml:</p><p>Let’s take a look at how to alter the tables. We’ll increase the length of the user table’s address column from 200 to 300 characters and add a new column to the order table called amount. We’ll also double-check that the changes are reflected in the tables.</p><p><strong>Edit the </strong><strong>templates/foodelivery.yaml:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13ddfdd2deafa21f0a7bd50ee96c3a18/href">https://medium.com/media/13ddfdd2deafa21f0a7bd50ee96c3a18/href</a></iframe><p>We added a new table called restaurant in our foodelivery.yaml file. It has columns restaurant_id, restaurant_name, address and minimum_order_amount. We also changed the column length of the address column of table user from 200 to 300.</p><p>Let’s look at how to reflect these changes in the database.</p><p>We start by translating the YAML schema into alchemy-modelgen format. The commands are essentially the same:</p><pre>modelgen createmodel -s yaml -p templates/foodelivery.yaml -a</pre><p>This command will modify the already written foodelivery.py file in the models folder. These changes are made as per the changes made in the YAML file.</p><p>The next step, as before, is to create a version file for this change in the schema. We run the command to create the version file:</p><pre>modelgen migrate revision --autogenerate -m &#39;new table restaurant added, length of address column of user table changed from 200 to 300&#39; -p sqlite:///foodelivery.db</pre><p>The command is same as before, with a slight difference. The value of -m is different from the command we ran earlier. We basically document the changes in this version of the schema using -m.</p><p>The final step is to make these changes in the database tables. To do so, we run the upgrade command:</p><pre>modelgen migrate upgrade head -p sqlite:///foodelivery.db</pre><p>Your changes should be in the database now!</p><p>So what’s happening here? Let’s understand what’s happening.</p><ul><li>The translate command createmodel reads the YAML file. It scans the YAML file for any changes. It then modifies our file models/foodelivery.py with the changes captured from the YAML.</li><li>The next command, the migrate revision scans the file models/foodelivery.py for any changes. Since the translate step modified the file, the migrate revision picks up the changed models/foodelivery.py file and creates a new version file in the folder alembic_migrate/versions/. The version file name should look something like a0a05246e7f7_new_table_restaurant_added_length_of_.py. The first part of file name is the version id and the second part is the commit message we passed through -m.</li><li>Our final command migrate upgrade head looks for the latest version file, reads the changes in the file and changes the tables accordingly.</li></ul><p>That’s it! Let’s verify if the database got changed or not. We start the sqlite database shell and look through the table structure of the three tables:</p><pre>sqlite3 foodelivery.db<br>sqlite&gt; pragma table_info(&#39;user&#39;)</pre><p><strong>OUTPUT</strong><br> The above command shows the following output:</p><pre>0|user_id|INTEGER|1||1</pre><pre>1|firstname|VARCHAR(20)|0||0</pre><pre>2|lastname|VARCHAR(20)|0||0</pre><pre>3|dob|DATE|0||0</pre><pre>4|contact|NUMERIC|1||0</pre><pre>5|address|VARCHAR(300)|0||0</pre><p>Note the change in the length of the 5th column address. It’s now 300!</p><p>Let’s verify if our restaurant table is created or not:</p><pre>sqlite&gt; pragma table_info(&#39;restaurant&#39;);</pre><p><strong>OUTPUT</strong><br> The above command results in the following output:</p><pre>0|restaurant_id|INTEGER|1||1</pre><pre>1|restaurant_name|VARCHAR(50)|0||0</pre><pre>2|address|VARCHAR(300)|0||0</pre><pre>3|minimum_order_amount|FLOAT|0||0</pre><p>Bingo! Our restaurant table is created in the database!</p><p>This completes another end to end flow of altering the schema of an existing table and adding a new table. To summarise the flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*3w-3UMTUAJun9t1i_Gk-yw.png" /><figcaption>alter table by changing schema in YAML file</figcaption></figure><p>Modelgen performs these operations behind the scenes using <a href="https://alembic.sqlalchemy.org/en/latest/">Alembic</a>.</p><h3>Time Travel</h3><p>One of the issues we run into when changing the schema of database tables is figuring out how to undo any changes or go back in time to a previous version of the schema. Let’s pretend we were wrong about changing the address column length and adding the restaurant table in our example. They aren’t required! What should we do now? What is the best way to get around this issue?</p><p>Let’s try to answer these questions.</p><p>For travel back in time, we first need to know which version is currently active in the database. To know that, we use migrate current subcommand. To know the active version:</p><pre>modelgen migrate current -p sqlite:///foodelivery.db</pre><p>migrate current tells you which version is the database at, at this point in time. The output of the command should look something like this:</p><pre>INFO  [alembic.runtime.migration] Context impl SQLiteImpl.</pre><pre>INFO  [alembic.runtime.migration] Will assume non-transactional DDL.</pre><pre>a0a05246e7f7 (head)     # <strong>Note this line</strong></pre><p>Note the last line of the output. a0a05246e7f7 is the id of the active version which is deployed to the database.</p><p>We now list all the versions and look through the history of changes made to the database. To do so, we use migrate history subcommand:</p><pre>modelgen migrate history -p sqlite:///foodelivery.db</pre><p>migrate history scans the alembic_migrate/versions folder and lists all the versions we have so far.</p><p>The output of this command should be similar to this:</p><pre>cb88ceb46594 -&gt; a0a05246e7f7 (head), new table restaurant added, length of address column of user table changed from 200 to 300</pre><pre>&lt;base&gt; -&gt; cb88ceb46594, initial migration</pre><p>Note the version ids and the commit messages. Those are the commit messages we entered while creating or changing the database.</p><p>From our previous command, we know the id of the active version which is a0a05246e7f7. We want to move back to the previous schema. From the above command, we know the id of the previous version is cb88ceb465941.</p><p>Let’s try to move to this version now. Inorder to do this, we use migrate downgrade subcommand:</p><pre>modelgen migrate downgrade cb88ceb46594 -p sqlite:///foodelivery.db</pre><p>We need to pass the id of the version we want the database to downgrade to. We can now verify the changes in the database using the sqlite3 commands from the previous sections.</p><p>migrate downgrade command pulls down the database from newer version to and older version. In this case, it pulls the database down from version a0a05246e7f7 to cb88ceb46594.<br> In this section, we’ll look at how to migrate from a newer version to an older one, as well as from an older version to a newer one.</p><p>In alchemy-modelgen’s terms, migrating to an older version is referred to as a downgrade, while migrating to a newer version is referred to as an upgrade.</p><p>Let’s suppose after a few months, we want to move again to the newer version of the schema. We need the address column’s length to be 300 and we need the restaurant table now. How to do that?</p><p>In order to move to a newer version of schema (or upgrade schema in alchemy-modelgen’s terms), we start by listing the current active version:</p><pre>modelgen migrate current -p sqlite:///foodelivery.db</pre><p>The command should output something similar to:</p><pre>INFO  [alembic.runtime.migration] Context impl SQLiteImpl.</pre><pre>INFO  [alembic.runtime.migration] Will assume non-transactional DDL.</pre><pre>cb88ceb46594</pre><p>Note the current version id.</p><p>Next step is to list all the versions and look through the history of the versions to determine which version we want to upgrade our database to. To do this, we use the command migrate history:</p><pre>modelgen migrate history -p sqlite:///foodelivery.db</pre><p>The command should output somthing similar to:</p><pre>cb88ceb46594 -&gt; a0a05246e7f7 (head), new table restaurant added, length of address column of user table changed from 200 to 300<br>&lt;base&gt; -&gt; cb88ceb46594, initial migration</pre><p>As we can see, our current version cb88ceb46594 needs to be upgraded to a0a05246e7f7. We do that with migrate upgrade command:</p><pre>modelgen migrate upgrade a0a05246e7f7 -p sqlite:///foodelivery.db</pre><p>The database should be upgraded to the version a0a05246e7f7 where we have the restaurant table and the column length of address column of the user table is 300, instead of 200!</p><h3>Conclusion</h3><p>In this post, we learned how to perform database operations using a YAML file as the table schema’s source. In the next post, we’ll look at how to perform database operations using another database as the table schema source.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b9ac41b102" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alchemy modelgen: Database Migrations made Easier (Part 1)]]></title>
            <link>https://shrinivdeshmukh.medium.com/alchemy-modelgen-database-migrations-made-easier-151f0d44ad2?source=rss-62bb2f9dfa3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/151f0d44ad2</guid>
            <category><![CDATA[schema-versioning]]></category>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[time-travel]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Shrinivas Deshmukh]]></dc:creator>
            <pubDate>Mon, 31 May 2021 14:53:46 GMT</pubDate>
            <atom:updated>2021-06-02T11:03:31.547Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part 1 of the alchemy-modelgen series. In this post, we’ll explore the tool alchemy-modelgen and get to know the features and API’s of this tool.</p><p>alchemy-modelgen is tool which makes RDBMS (such as Redshift, PostgreSQL, Snowflake, MySQL, etc.) management easy by abstracting typical mundane tasks like writing and storing multiple SQL files, modifying tables and tracking these modifications, etc.</p><p>alchemy-modelgen enables database/warehouse construction either using YAML based schema-configuration files or through replication of existing database schema. It also facilitates schema versioning and tracking, at the same time enabling time travel back to earlier versions.</p><p>Underneath, alchemy-modelgen uses <a href="https://pypi.org/project/alembic/">alembic</a> for table creation, modification, and version management, and <a href="https://github.com/agronholm/sqlacodegen">sqlacodegen</a> for schema extraction from existing databases and warehouses.</p><h3>What is Database Migration?</h3><p>Database migration refers to movement of your data structure from one platform to another.</p><p>Let’s look at a typical use case for data migration. In an enterprise, the application was built on a relatively slower databases like MySQL or PostgreSQL. But as the volume of the data grew, the process of analyzing the data became cumbersome. In order to tackle this, the enterprise decided to shift from MySQL to a big data handler database like <a href="https://aws.amazon.com/redshift/">AWS Redshift</a> for example.</p><p>To migrate your data to Redshift, we first need to migrate all the table structure from MySQL to Redshift. Generally, in an enterprise the number of tables are in two digits. Imagine the amount of time and precision this would require, especially when the tables have numerous columns and have constraints like primary key, unique or null constraint.</p><p>Let’s take another use case. Let’s say we want to setup a data warehouse using Redshift. This could be done in many ways:</p><ul><li>Create the tables manually</li><li>Write big SQL files</li><li>Use an ORM tool like hibernate (for java), sqlalchemy (for python)</li></ul><p>In all of the above approaches, a lot of coding and maintenance is involved. Also, we need to have specialized skills to create and maintain the tables like fluency with SQL, understanding of ORM tools and so forth. And what if we need to change the structure? Let’s say we want to add or delete a column, or change the data type of a column? What happens then? What if we change the structure now, and we want to move back to the old structure? How to maintain different versions of the table structure? We’ll try to answer these question in the following sections.</p><h3>Table of Contents</h3><ul><li><a href="#6f25">Overview</a></li><li><a href="#a2f1">API</a></li><li><a href="#9f3e">Initializing modelgen</a></li><li><a href="#6144">Defining schema in YAML file</a></li><li><a href="#ffc6">Pulling schema from existing database or data warehouse</a></li><li><a href="#e1d5">Table creation in database or data warehouse</a></li><li><a href="#1038">Table alteration in database or data warehouse</a></li><li><a href="#c3ff">Version maintenance or schema versioning</a></li><li><a href="#10d8">Conclusions</a></li></ul><h3>Overview</h3><p>alchemy-modelgen is a tool which simplifies typical database management tasks. This includes identifying tables, altering their schema, and versioning of these updates.</p><p>Tables can be constructed using two approaches:</p><ul><li>Specifying the database model through a YAML file including tables, columns, constraints and relationships. (YAML files are easy to write, do not require programming skills, and can be stored in any storage location (local, cloud buckets, git, etc).</li><li>Replicating the database model of an existing database or warehouse. This is especially applicable for data migration workflows.</li></ul><p>Schema changes are extremely common and typically require manual queries to be run in order to make these changes. Furthermore, recording these changes is needed in order to roll back these changes or return to a previous version of the schema. alchemy-modelgen handles this out of the box, preserving all iterations of the table schema and enabling roll back to any previous state.</p><p>Let’s look into the usage of alchemy-modelgen in the following sections.</p><p><strong>Note:</strong> python version &gt;= 3.8 is required</p><h3>API</h3><p>alchemy-modelgen can be installed from pypi using:</p><pre>pip install alchemy-modelgen</pre><p>modelgen, a command-line utility, is included in the kit. The command modelgen is used to carry out all of the executions.</p><h3>Initializing modelgen</h3><p>Before conducting any database operations, modelgen must be initialized. To begin, type the following command:</p><pre>modelgen init -d ./modelgen_folder</pre><p>./modelgen_folder refers to the folder that modelgen will build. The folder may be assigned any name; the only requirement is that it does not already exist.</p><p>(./modelgen_folder will be used as an example initialization folder in the following parts of this article. The folder name should be the same as the one used to initialize modelgen.)</p><p>The above command results in the following folder structure:</p><pre>modelgen_folder<br>├── alembic_migrate<br>│   └── __init__.py<br>│   └── env.py<br>│   └── script.py.mako<br>│   └── versions<br>│       └── __init__.py<br>│   └── README<br>├── templates<br>│   └── example.yaml<br>└── alembic.ini</pre><p>The tool includes a sample YAML file that shows how to write tables, define schema, and specify constraints, among other things. The file can be found in the modelgen_folder/templates/example.yaml folder.</p><p>The initialized directory (modelgen_folder in this case, essentially, cd modelgen_folder) should always be the working directory for all modelgen operations.</p><h3>Defining schema in YAML file and registering it with modelgen</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebcbc7177ab7f9f6e9f23ae57a25a90c/href">https://medium.com/media/ebcbc7177ab7f9f6e9f23ae57a25a90c/href</a></iframe><p>In order to register this YAML schema with modelgen, we run modelgen createmodel after it is specified in YAML:</p><pre>modelgen createmodel -s yaml -p &lt;path/to/your/template.yaml&gt; -a</pre><p>In the above command, the parameters -s , -p and -a are:</p><ul><li>-s: whether it’s a yaml file or an existing database/warehouse to read schema from, should be database or yaml</li><li>-p: path of the YAML schema file</li><li>-a: enables support for database migration. It is disabled by default</li></ul><p>The recommended location for the YAML file is modelgen_folder/templates/. However, the file can be stored at any path or location.</p><p>Some databases, such as <a href="https://aws.amazon.com/redshift/">AWS Redshift</a>, may have additional parameters such as diststyle, distkey, and sortkey. Please read this <a href="https://github.com/shree14/sqlalchemy-modelgen/blob/main/docs/yaml_creation.md#injecting-extra-parameters">document</a> to learn more about this advanced use.</p><h3>Pulling schema from existing database or datawarehouse</h3><p>It is possible to extract the schema of all tables and views from an existing database or warehouse using modelgen. The procedure is as follows:</p><ol><li>Set modelgen_folder as current working directory</li><li>Pull schema from database/warehouse</li></ol><pre>cd modelgen_folder</pre><pre>modelgen createmodel -s database --outfile models/&lt;FILENAME&gt;.py -p &lt;SQLALCHEMY_DATABASE_URL&gt; -a</pre><p>In the above command, the parameters -s, --outfile , -p and -a are:</p><ul><li>-s: whether it’s a yaml file or an existing database/warehouse to read schema from, should be database or yaml</li><li>--outfile: The schema from the database/warehouse should be saved in this file. models/&lt;FILENAME&gt;.py should always be the path, where &lt;FILENAME&gt; can be any name you like.</li><li>-p: The database/warehouse’s url. The sqlalchemy url syntax should be followed for this URL. The syntax of sqlalchemy is as follows:<br>database+connector://username:password@host:port/database</li></ul><p>Database connections supported by modelgen are:</p><ul><li>MySQL: mysql+mysqlconnector://username:password@host:port/database</li><li>Postgresql: postgresql+psycopg2://username:password@host:port/database</li><li>Redshift: redshift+psycopg2://username:password@host:port/database</li><li>snowflake: snowflake://username:password@account, more info can be found <a href="https://github.com/snowflakedb/snowflake-sqlalchemy">here</a></li></ul><h3>Table creation in database or datawarehouse</h3><p>It’s time to move the schema to our actual target database/warehouse, either through the YAML file or by pulling from an existing database/warehouse. Under the hood, modelgen uses a migration tool called alembic to accomplish this.</p><ul><li>First, let’s make a migration revision. Revisions in migration are identical to git commits. Your updates are saved to the local repository using these revisions. Revisions can also be thought of as snapshots of the yaml schema written in a language that modelgen can understand. These revisions are saved in the alembic_migrate/versions/ folder by modelgen.</li></ul><pre>modelgen migrate revision --autogenerate -m &#39;&lt;COMMIT_MESSAGE&gt;&#39; -p &lt;SQLALCHEMY_DATABASE_URL&gt;</pre><p>Depending on what the new revision is doing, the &lt;COMMIT MESSAGE&gt; may be contextual. If this is the first migration, the commit message may be initial migration, making our final command:</p><pre>modelgen migrate revision --autogenerate -m &#39;initial migration&#39; -p &lt;SQLALCHEMY_DATABASE_URL&gt;</pre><p>The parameter -p corresponds to the sqlalchemy URL of the target database/warehouse.</p><ul><li>Now the tables can be created in the target database/warehouse</li></ul><pre>modelgen migrate upgrade head -p &lt;SQLALCHEMY_DATABASE_URL&gt;</pre><ul><li>The tables should now be reflected in the database/warehouse</li></ul><h3>Table alteration in database or data warehouse</h3><p>The addition of a new column, modifying the datatype of a column, increasing or reducing the length of a column, or imposing or eliminating restrictions on a column are all examples of table alterations. The procedure to alter tables is:</p><ul><li><strong>Make changes in the YAML schema file</strong></li></ul><p>Let’s take the YAML template from the earlier section of this article:</p><p>The original template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebcbc7177ab7f9f6e9f23ae57a25a90c/href">https://medium.com/media/ebcbc7177ab7f9f6e9f23ae57a25a90c/href</a></iframe><p>Let’s change the length of column address from 200 to 350 and add a new column called country:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c99046fca5cfbd6782c08071f3258f5d/href">https://medium.com/media/c99046fca5cfbd6782c08071f3258f5d/href</a></iframe><ul><li><strong>Create migration revision</strong></li></ul><pre>modelgen migrate revision --autogenerate -m &#39;initial migration&#39; -p &lt;SQLALCHEMY_DATABASE_URL&gt; </pre><ul><li><strong>Alter the tables in the database/warehouse</strong></li></ul><pre>modelgen migrate upgrade head -p &lt;SQLALCHEMY_DATABASE_URL&gt; </pre><h3>Version maintenance or schema versioning</h3><p>Modelgen uses alembic to keep track of schema versions under the hood. To upgrade or downgrade to any old/new version, we begin by listing the versions, obtaining the version id, and then upgrading/downgrading using the version id.</p><ul><li><strong>List all the versions</strong></li></ul><pre>modelgen migrate history -p &lt;SQLALCHEMY_DATABASE_URL&gt; </pre><ul><li><strong>Get the version id</strong></li></ul><p>The output of the above command would look something like this:</p><pre>787cf0fee9c1 -&gt; 16225b6adae3 (head), add new column country, change address length from 200 to 350</pre><pre>&lt;base&gt; -&gt; 787cf0fee9c1, initial migration </pre><p>The id 787cf0fee9c1 refers to the older migration, while the id 16225b6adae3 refers to the most recent migration.</p><p>The most recent migration is also the one that is active in the database/warehouse right now.</p><p>Let’s suppose we want to go back to the edition with the id 787cf0fee9c1. We can do so by running the following command:</p><pre>modelgen migrate downgrade 787cf0fee9c1 -p &lt;SQLALCHEMY_DATABASE_URL&gt;</pre><p>The database/warehouse tables should now be at the same state as 787cf0fee9c1.</p><p>If we want to go back to the most recent schema version again with the id 16225b6adae3, we can use the following command:</p><pre>modelgen migrate ugrade 16225b6adae3 -p &lt;SQLALCHEMY_DATABASE_URL&gt; </pre><h3>Conclusions</h3><p>We looked at alchemy-modelgen, its functionality, and how to use it in this post. <a href="https://shrinivdeshmukh.medium.com/alchemy-modelgen-database-migrations-made-easier-part-2-18b9ac41b102"><strong>Click here</strong></a> to read Part 2 of this series.</p><p>Support for more databases and warehouses will be included in future releases. Please visit the <a href="https://github.com/shree14/sqlalchemy-modelgen">GitHub repository</a> if you want to learn more or contribute to the project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=151f0d44ad2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>