<?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 Evgeny Bellyk on Medium]]></title>
        <description><![CDATA[Stories by Evgeny Bellyk on Medium]]></description>
        <link>https://medium.com/@evgenybellyk?source=rss-f14d3e7d633f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sjL4rkwl7wYySELe3VyuNw.png</url>
            <title>Stories by Evgeny Bellyk on Medium</title>
            <link>https://medium.com/@evgenybellyk?source=rss-f14d3e7d633f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:22:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evgenybellyk/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[SQLAlchemy Core Basic Operations: SELECT queries]]></title>
            <link>https://medium.com/@evgenybellyk/sqlalchemy-core-basic-operations-select-queries-9f316d23affe?source=rss-f14d3e7d633f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f316d23affe</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Evgeny Bellyk]]></dc:creator>
            <pubDate>Sun, 21 May 2023 12:20:30 GMT</pubDate>
            <atom:updated>2023-05-21T12:20:30.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqkD32MCb6BtDMzhIPKEmg.png" /></figure><h3>Intro</h3><p>Hi there, in the <a href="https://medium.com/@evgenybellyk/sqlalchemy-core-basic-operations-1799bd53db1">previous post</a> we discussed pros and cons of <strong>SQLAlchemy</strong> in comparison to <strong>raw SQL</strong>, created table and inserted data using both <strong>SQLite</strong> and <strong>SQLAlchemy</strong>.</p><p>In this post we are moving towards complex <strong>SELECT queries</strong> using both SQLite and SQLAlchemy. Enjoy!</p><h3>Preparation</h3><p>Firstly, let’s implement <strong>print_sqlite_cursor_as_table</strong>and <strong>print_sqlalchemy_cursor_as_table</strong>functions to output cursors as pretty tables:</p><pre>import sqlite3<br>import sqlalchemy<br><br>def print_formatted_table(table: list[list]):<br>    column_lengths = [<br>        max(len(table[i][column_num]) for i in range(len(table)))<br>        for column_num in range(len(table[0]))<br>    ]<br>    for row in table:<br>        print(&quot;|&quot;, end=&quot; &quot;)<br>        for item, column_length in zip(row, column_lengths):<br>            print(item.rjust(column_length), &quot;|&quot;, end=&quot; &quot;)<br>        print()<br><br><br>def print_sqlite_cursor_as_table(title: str, cursor: sqlite3.Cursor):<br>    headers = [d[0] for d in cursor.description]<br>    <br>    table: list[list[str]] = [headers]<br>    for row in cursor.fetchall():<br>        table.append(list(map(str, row)))<br>    <br>    print(title)<br>    print_formatted_table(table)<br>    print()<br><br><br>def print_sqlalchemy_cursor_as_table(<br>    connection: sqlalchemy.Connection,<br>    title: str,<br>    statement: sqlalchemy.Select,<br>):<br>    cursor = connection.execute(statement)<br><br>    headers = list(cursor.keys())<br><br>    table: list[list[str]] = [headers]<br>    for row in cursor.fetchall():<br>        table.append(list(map(str, row)))<br>    <br>    print(title)<br>    print_formatted_table(table)<br>    print()</pre><h3>Select all entries from the table</h3><p>In <strong>SQLite </strong>you would simply write a <em>SELECT FROM </em>statement. For example, in case of <em>items</em> table it can be written as follows:</p><pre>print_sqlite_cursor_as_table(<br>    &quot;All Items:&quot;,<br>    sqlite_cursor.execute(&quot;SELECT * FROM items&quot;)<br>)<br><br>&gt;&gt;&gt;<br>All Items:<br>| item_id | item_name | item_price | <br>|       1 |      Cola |        2.5 | <br>|       2 |     Chips |        3.0 | <br>|       3 |     Water |        1.2 | <br>|       4 |     Apple |        0.3 | <br>|       5 |   Avocado |       1.75 |</pre><p>In <strong>SQLAlchemy</strong> you should instead use <strong>select</strong> function and pass the table as a parameter:</p><pre>print_sqlalchemy_cursor_as_table(<br>    sqlalchemy_connection,<br>    &quot;All items:&quot;,<br>    sqlalchemy.select(items_table)<br>)<br><br>&gt;&gt;&gt;<br>All items:<br>| item_id | item_name | item_price | <br>|       1 |      Cola |        2.5 | <br>|       2 |     Chips |        3.0 | <br>|       3 |     Water |        1.2 | <br>|       4 |     Apple |        0.3 | <br>|       5 |   Avocado |       1.75 |</pre><h3>Select specific columns and order by</h3><p>Imagine, now you have to select only item names and prices ordered by price in descending order.</p><p>In <strong>SQLite</strong> you can specify column names, and use the <strong>ORDER BY</strong> operator:</p><pre>print_sqlite_cursor_as_table(<br>    &quot;Item names and prices:&quot;,<br>    sqlite_cursor.execute(<br>        &quot;&quot;&quot;<br>        SELECT<br>            item_name,<br>            item_price<br>        FROM items<br>        ORDER BY item_price DESC<br>        &quot;&quot;&quot;<br>    )<br>)<br><br>&gt;&gt;&gt;<br>Item names and prices:<br>| item_name | item_price | <br>|     Chips |        3.0 | <br>|      Cola |        2.5 | <br>|   Avocado |       1.75 | <br>|     Water |        1.2 | <br>|     Apple |        0.3 |</pre><p>What you do in <strong>SQLAlchemy</strong> is use table columns as parameters of <strong>select</strong> function (instead of the whole table), then call <strong>order_by</strong> method on the result and pass <strong>table_column.desc()</strong> parameter:</p><pre>print_sqlalchemy_cursor_as_table(<br>    sqlalchemy_connection,<br>    &quot;Item names and prices:&quot;,<br>    sqlalchemy.select(<br>        items_table.c.item_name,<br>        items_table.c.item_price<br>    ).order_by(items_table.c.item_price.desc())<br>)<br><br>&gt;&gt;&gt;<br>Item names and prices:<br>| item_name | item_price | <br>|     Chips |        3.0 | <br>|      Cola |        2.5 | <br>|   Avocado |       1.75 | <br>|     Water |        1.2 | <br>|     Apple |        0.3 |</pre><h3>Joins</h3><p>In <strong>SQLite</strong> you typically use <strong>FROM table_a JOIN table_b ON table_a.column_a = table_b.column_b</strong> syntax:</p><pre>print_sqlite_cursor_as_table(<br>    &quot;Operations with details:&quot;,<br>    sqlite_cursor.execute(<br>        &quot;&quot;&quot;<br>        SELECT<br>            o.operation_id,<br>            o.operation_date,<br>            i.item_name,<br>            i.item_price,<br>            d.amount,<br>            t.operation_type_name<br>        FROM operations o LEFT JOIN operation_descriptions d<br>            ON o.operation_id = d.operation_id<br>        JOIN items i<br>            ON d.item_id = i.item_id<br>        JOIN operation_types t<br>            ON o.operation_type_id = t.operation_type_id <br>        &quot;&quot;&quot;<br>    )<br>)<br><br>&gt;&gt;&gt;<br>Operations with details:<br>| operation_id | operation_date | item_name | item_price | amount | operation_type_name | <br>|            1 |     2022-04-22 |      Cola |        2.5 |      1 |                sell | <br>|            1 |     2022-04-22 |     Chips |        3.0 |      2 |                sell | <br>|            2 |     2022-04-22 |   Avocado |       1.75 |      1 |                sell | <br>|            3 |     2022-04-22 |   Avocado |       1.75 |      1 |              return | <br>|            4 |     2022-04-23 |     Water |        1.2 |      1 |                sell | <br>|            4 |     2022-04-23 |     Apple |        0.3 |      2 |                sell |</pre><p>How to repeat the same construction in <strong>SQLAlchemy</strong>? You can use the <strong>table_a.join(table_b, condition)</strong> syntax.</p><p>For example, if you are performing <em>INNER JOIN</em>, it can be written like that: <strong>table_a.join(table_b, table_a.c.id = table_b.c.id)</strong>.</p><p>If you are using <em>LEFT JOIN</em>, the <strong>isouter=True</strong> parameter should be passed:</p><pre>operations_details_statement = operations_table.join(<br>    operation_descriptions_table,<br>    operations_table.c.operation_id == \<br>        operation_descriptions_table.c.operation_id,<br>    isouter=True<br>).join(<br>    items_table,<br>    operation_descriptions_table.c.item_id == \<br>        items_table.c.item_id<br>).join(<br>    operation_types_table,<br>    operations_table.c.operation_type_id == \<br>        operation_types_table.c.operation_type_id<br>)</pre><p>Here, we extract the join statement to a variable. To use it in a select statement with specific columns, we can use <strong>select_from</strong> syntax:</p><pre>print_sqlalchemy_cursor_as_table(<br>    sqlalchemy_connection,<br>    &quot;Operations with details:&quot;,<br>    sqlalchemy.select(<br>        operations_table.c.operation_id,<br>        operations_table.c.operation_date,<br>        items_table.c.item_name,<br>        items_table.c.item_price,<br>        operation_descriptions_table.c.amount,<br>        operation_types_table.c.operation_type_name<br>    ).select_from(operations_details_statement)<br>)<br><br>&gt;&gt;&gt;<br>Operations with details:<br>| operation_id | operation_date | item_name | item_price | amount | operation_type_name | <br>|            1 |     2022-04-22 |      Cola |        2.5 |      1 |                sell | <br>|            1 |     2022-04-22 |     Chips |        3.0 |      2 |                sell | <br>|            2 |     2022-04-22 |   Avocado |       1.75 |      1 |                sell | <br>|            3 |     2022-04-22 |   Avocado |       1.75 |      1 |              return | <br>|            4 |     2022-04-23 |     Water |        1.2 |      1 |                sell | <br>|            4 |     2022-04-23 |     Apple |        0.3 |      2 |                sell | </pre><h3>Where, Group By and SQL functions</h3><p>In <strong>SQLite</strong> we can use SQL functions on columns, then filter entries with some condition and then aggregate them with <em>GROUP BY</em>. For example, if we decided to calculate each checks’ total, we could use this query:</p><pre>print_sqlite_cursor_as_table(<br>    &quot;Check sums:&quot;,<br>    sqlite_cursor.execute(<br>        &quot;&quot;&quot;<br>        SELECT<br>            o.operation_date,<br>            -- multiply amount of items on their price to get per-item total<br>            ROUND(SUM(d.amount * i.item_price), 2) AS check_sum<br>        FROM operations o LEFT JOIN operation_descriptions d<br>            ON o.operation_id = d.operation_id<br>        JOIN items i<br>            ON d.item_id = i.item_id<br>        JOIN operation_types t<br>            ON o.operation_type_id = t.operation_type_id<br>        WHERE t.operation_type_name = &#39;sell&#39;<br>        GROUP BY o.operation_id, o.operation_date<br>        &quot;&quot;&quot;<br>    )<br>)<br><br>&gt;&gt;&gt;<br>Check sums:<br>| operation_date | check_sum | <br>|     2022-04-22 |       8.5 | <br>|     2022-04-22 |      1.75 | <br>|     2022-04-23 |       1.8 |</pre><p>In <strong>SQLAlchemy</strong> to call SQL functions we would use <strong>sqlalchemy.sql.func</strong> module. For filtering and aggregation there are <strong>where(condition)</strong> and <strong>group_by(column1, column2, …)</strong> functions that are applied to the select query. Additionally, we can rename a column in select statement by using <strong>label(new_label)</strong> function on this column. In this query, let’s reuse <em>operations_details_statement</em> variable:</p><pre>from sqlalchemy.sql import func<br><br>print_sqlalchemy_cursor_as_table(<br>    sqlalchemy_connection,<br>    &quot;Check sums:&quot;,<br>    sqlalchemy.select(<br>        operations_table.c.operation_date,<br>        func.round(<br>            func.sum(<br>                operation_descriptions_table.c.amount * \<br>                    items_table.c.item_price<br>            ),<br>            2<br>        ).label(&quot;check_sum&quot;)<br>    ).select_from(<br>        operations_details_statement<br>    ).where(<br>        operation_types_table.c.operation_type_name == &quot;sell&quot;<br>    ).group_by(<br>        operations_table.c.operation_id,<br>        operations_table.c.operation_date<br>    )<br>)<br><br>&gt;&gt;&gt;<br>Check sums:<br>| operation_date | check_sum | <br>|     2022-04-22 |       8.5 | <br>|     2022-04-22 |      1.75 | <br>|     2022-04-23 |       1.8 | </pre><h3>CTEs and subqueries</h3><p>In SQL, <strong>CTE</strong> are much like <em>named queries</em> that can be used in a subsequent <em>SELECT</em> statement. They generally act like subqueries, but instead of copypasting same code to the subquery, we define it as a kind of variable.</p><p>For example, let’s find all the checks that has a total sum greater, than average, using <strong>SQLite</strong>:</p><pre>print_sqlite_cursor_as_table(<br>    &quot;Check greater than average:&quot;,<br>    sqlite_cursor.execute(<br>        &quot;&quot;&quot;<br>        WITH full_checks AS (<br>            SELECT<br>                o.operation_id,<br>                o.operation_date,<br>                i.item_name,<br>                d.amount,<br>                ROUND(d.amount * i.item_price, 2) AS item_sum<br>            FROM operations o LEFT JOIN operation_descriptions d<br>                ON o.operation_id = d.operation_id<br>            JOIN items i<br>                ON d.item_id = i.item_id<br>            JOIN operation_types t<br>                ON o.operation_type_id = t.operation_type_id<br>            WHERE t.operation_type_name = &#39;sell&#39;<br>        ), sell_checks AS (<br>            SELECT<br>                f.operation_id,<br>                f.operation_date,<br>                ROUND(SUM(f.item_sum), 2) AS check_sum<br>            FROM full_checks f<br>            GROUP BY f.operation_id, f.operation_date<br>        )<br>        <br>        SELECT<br>            f.operation_id,<br>            f.operation_date,<br>            f.item_name,<br>            f.item_sum<br>        FROM sell_checks s LEFT JOIN full_checks f<br>            ON s.operation_id = f.operation_id<br>        WHERE s.check_sum &gt; (SELECT AVG(check_sum) FROM sell_checks)<br>        &quot;&quot;&quot;<br>    )<br>)<br><br>&gt;&gt;&gt;<br>Check greater than average:<br>| operation_id | operation_date | item_name | item_sum | <br>|            1 |     2022-04-22 |     Chips |      6.0 | <br>|            1 |     2022-04-22 |      Cola |      2.5 | </pre><p>Alternatively, in <strong>SQLAlchemy</strong> we can call <strong>cte(cte_name)</strong> method on the query to turn it into the <strong>CTE</strong>:</p><pre>full_checks_cte = sqlalchemy.select(<br>    operations_table.c.operation_id,<br>    operations_table.c.operation_date,<br>    items_table.c.item_name,<br>    operation_descriptions_table.c.amount,<br>    func.round(<br>        operation_descriptions_table.c.amount * items_table.c.item_price,<br>        2<br>    ).label(&quot;item_sum&quot;)<br>).select_from(<br>    operations_details_statement<br>).where(<br>    operation_types_table.c.operation_type_name == &quot;sell&quot;<br>).cte(&quot;full_checks&quot;)<br><br><br>sell_checks_cte = sqlalchemy.select(<br>    full_checks_cte.c.operation_id,<br>    full_checks_cte.c.operation_date,<br>    func.round(<br>        func.sum(full_checks_cte.c.item_sum),<br>        2<br>    ).label(&quot;check_sum&quot;)<br>).select_from(<br>    full_checks_cte<br>).group_by(<br>    full_checks_cte.c.operation_id,<br>    full_checks_cte.c.operation_date<br>).cte(&quot;sell_checks&quot;)</pre><p>Later, we can use these <strong>CTE</strong>s in out select query. Also, <strong>SQLAlchemy</strong> warns us to use <strong>scalar_subquery()</strong> in subqueries to convert them to scalar values:</p><pre>print_sqlalchemy_cursor_as_table(<br>    sqlalchemy_connection,<br>    &quot;Check greater than average:&quot;,<br>    sqlalchemy.select(<br>        full_checks_cte.c.operation_id,<br>        full_checks_cte.c.operation_date,<br>        full_checks_cte.c.item_name,<br>        full_checks_cte.c.item_sum<br>    ).select_from(<br>        sell_checks_cte.join(<br>            full_checks_cte,<br>            sell_checks_cte.c.operation_id == full_checks_cte.c.operation_id,<br>            isouter=True<br>        )<br>    ).where(<br>        sell_checks_cte.c.check_sum &gt; sqlalchemy.select(<br>            func.avg(sell_checks_cte.c.check_sum)<br>        ).scalar_subquery()<br>    )<br>)<br><br>&gt;&gt;&gt;<br>Check greater than average:<br>| operation_id | operation_date | item_name | item_sum | <br>|            1 |     2022-04-22 |     Chips |      6.0 | <br>|            1 |     2022-04-22 |      Cola |      2.5 |</pre><h3>Conclusion</h3><p>In this part we’ve discovered complex <em>SELECT</em> queries. <strong>SQLAlchemy</strong> often provides some level of abstraction that allows us to reuse an existing code. Though sometimes <strong>SQLAlchemy</strong> is quite verbose, compared to <strong>raw SQL</strong>, it’s still easy to read and refactor these statements.</p><p>In further part we’ll continue using <strong>SQLAlchemy</strong> with <em>DELETE </em>and <em>UPDATE</em> operations. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f316d23affe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy Core Basic Operations]]></title>
            <link>https://medium.com/@evgenybellyk/sqlalchemy-core-basic-operations-1799bd53db1?source=rss-f14d3e7d633f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1799bd53db1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Evgeny Bellyk]]></dc:creator>
            <pubDate>Sun, 14 May 2023 12:45:27 GMT</pubDate>
            <atom:updated>2023-05-14T12:45:27.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7_UbOJguNRwn_dyzPHW1w.png" /></figure><h3>What is SQLAlchemy?</h3><blockquote>SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.</blockquote><blockquote><a href="https://www.sqlalchemy.org/">https://www.sqlalchemy.org/</a></blockquote><p>Making it simple, SQLAlchemy is just a way to interact with an SQL Database using Python objects and functions (instead of raw SQL strings)</p><h3>Why not raw SQL?</h3><p><strong>1. Improved code quality.</strong></p><p>Since you are using Python objects, you can also apply code-style checkers such as <strong>Pylint</strong> or <strong>Black</strong>.<br>In a <em>raw SQL</em> there’s often a situation where you have a huge string-block with sophisticated logic and poor formatting, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*fh-d4aYSOweaUSWF.png" /><figcaption>It might be hard to read through this query</figcaption></figure><p><strong>2. Scalability</strong>. Business requirements change often, so as a developer you have to adapt your code for this changes.</p><p>For example, when you altering a column of the table, in a <em>raw SQL</em> you have to change all the occurrences of this column in SQL queries, plus manually update database structure.</p><p>Using <em>SQLAlchemy</em>, you can automatically generate a <strong>migration</strong> (instructions for server how to rename a column) and change parameter of the class with the IDE’s <strong>refactoring</strong> functionality, as you usually do with classes.</p><p><strong>3. Security</strong>. <em>Raw SQL</em> is prone to <strong>SQL injections</strong>, so when it comes to production, you have to remember about all the places with parameters substitution and take care of safely handling them.</p><p>With <em>SQLAlchemy</em>, you can pass changable parameters to query functions and thus <em>SQLAlchemy</em> will take care of parameter substituion by itself!</p><h3>How to use it?</h3><p>So imagine situation where you have to interact with SQL Database.<br>For example it could be a backend service that operates with some items from a local grocery store (let it be simple CRUD) and builds some statistics based on purchases.</p><p>There is a database’s <em>schema</em>:</p><p><strong>Items</strong>:</p><pre>| item_id | item_name | item_price | <br>|       1 |      Cola |        2.5 | <br>|       2 |     Chips |        3.0 | <br>|       3 |     Water |        1.2 | <br>|       4 |     Apple |        0.3 | <br>|       5 |   Avocado |       1.75 |</pre><p><strong>Operations</strong>:</p><pre>| operation_id | operation_date | operation_type_id | <br>|            1 |     2022-04-22 |                 1 | <br>|            2 |     2022-04-22 |                 1 | <br>|            3 |     2022-04-22 |                 2 | <br>|            4 |     2022-04-23 |                 1 |</pre><p><strong>Operation types</strong>:</p><pre>| operation_type_id | operation_type_name | <br>|                 1 |                sell | <br>|                 2 |              return |</pre><p><strong>Operation descriptions</strong>:</p><pre>| description_id | operation_id | item_id | amount | <br>|              1 |            1 |       1 |      1 | <br>|              2 |            1 |       2 |      2 | <br>|              3 |            2 |       5 |      1 | <br>|              4 |            3 |       5 |      1 | <br>|              5 |            4 |       3 |      1 | <br>|              6 |            4 |       4 |      2 |</pre><p>Firstly you would take care of <em>table creation and filling</em>.</p><p><strong>Raw SQL</strong></p><p>In <em>raw SQL</em> and <strong>SQLite</strong> it would be written the following way (Python 3):</p><pre>import sqlite3<br><br># firstly, connect to the database and create a cursor<br>connection = sqlite3.connect(&quot;store_database.db&quot;)<br>cursor = connection.cursor()<br><br># then drop table if exists and create a new one<br>cursor.execute(&#39;&#39;&#39;DROP TABLE IF EXISTS items&#39;&#39;&#39;)<br>cursor.execute(<br>    &#39;&#39;&#39;<br>    CREATE TABLE items (<br>        item_id INTEGER PRIMARY KEY AUTOINCREMENT,<br>        item_name TEXT,<br>        item_price REAL<br>    )<br>    &#39;&#39;&#39;<br>)<br><br>cursor.execute(&#39;&#39;&#39;DROP TABLE IF EXISTS operation_types&#39;&#39;&#39;)<br>cursor.execute(<br>    &#39;&#39;&#39;<br>    CREATE TABLE operation_types (<br>        operation_type_id INTEGER PRIMARY KEY AUTOINCREMENT,<br>        operation_type_name TEXT<br>    )<br>    &#39;&#39;&#39;<br>)<br><br>cursor.execute(&#39;&#39;&#39;DROP TABLE IF EXISTS operations&#39;&#39;&#39;)<br>cursor.execute(<br>    &#39;&#39;&#39;<br>    CREATE TABLE operations (<br>        operation_id INTEGER PRIMARY KEY AUTOINCREMENT,<br>        operation_date DATE,<br>        operation_type_id INTEGER,<br>        FOREIGN KEY(operation_type_id) REFERENCES operation_types(operation_type_id)<br>    )<br>    &#39;&#39;&#39;<br>)<br><br>cursor.execute(&#39;&#39;&#39;DROP TABLE IF EXISTS operation_descriptions&#39;&#39;&#39;)<br>cursor.execute(<br>    &#39;&#39;&#39;<br>    CREATE TABLE operation_descriptions (<br>        description_id INTEGER PRIMARY KEY AUTOINCREMENT,<br>        operation_id INTEGER,<br>        item_id INTEGER,<br>        amount INTEGER,<br>        FOREIGN KEY(operation_id) REFERENCES operations(operation_id),<br>        FOREIGN KEY(item_id) REFERENCES items(item_id)<br>    )<br>    &#39;&#39;&#39;<br>)<br><br># don&#39;t forget to commit changes<br>connection.commit()</pre><p>And then you would insert some test data:</p><pre># insert multiple values<br>cursor.executemany(<br>    &quot;&quot;&quot;<br>    INSERT INTO items(<br>        item_id, item_name, item_price<br>    ) VALUES (?, ?, ?)<br>    &quot;&quot;&quot;,<br>    [<br>        (1, &quot;Cola&quot;, 2.5),<br>        (2, &quot;Chips&quot;, 3.0),<br>        (3, &quot;Water&quot;, 1.2),<br>        (4, &quot;Apple&quot;, 0.3),<br>        (5, &quot;Avocado&quot;, 1.75)<br>    ]<br>)<br><br>cursor.executemany(<br>    &quot;&quot;&quot;<br>    INSERT INTO operation_types(<br>        operation_type_id, operation_type_name<br>    ) VALUES (?, ?)<br>    &quot;&quot;&quot;,<br>    [<br>        (1, &quot;sell&quot;),<br>        (2, &quot;return&quot;)<br>    ]<br>)<br><br>cursor.executemany(<br>    &quot;&quot;&quot;<br>    INSERT INTO operations(<br>        operation_id, operation_date, operation_type_id<br>    ) VALUES (?, ?, ?)<br>    &quot;&quot;&quot;,<br>    [<br>        (1, &quot;2023-04-22&quot;, 1),<br>        (2, &quot;2023-04-22&quot;, 1),<br>        (3, &quot;2023-04-22&quot;, 2),<br>        (4, &quot;2023-04-23&quot;, 1)<br>    ]<br>)<br><br>cursor.executemany(<br>    &quot;&quot;&quot;<br>    INSERT INTO operation_descriptions(<br>        description_id, operation_id, item_id, amount<br>    ) VALUES (?, ?, ?, ?)<br>    &quot;&quot;&quot;,<br>    [<br>        (1, 1, 1, 1),<br>        (2, 1, 2, 2),<br>        (3, 2, 5, 1),<br>        (4, 3, 5, 1),<br>        (5, 4, 3, 1),<br>        (6, 4, 4, 2)<br>    ]<br>)<br><br># again, commit the changes<br>connection.commit()</pre><p><strong>SQLAlchemy Core</strong></p><p>How would you do the same with <strong>SQLAlchemy 2.0.9</strong> and <strong>Python 3.10</strong>?:</p><pre>from datetime import date<br><br>import sqlalchemy<br>from sqlalchemy import (<br>    MetaData, Table, Column, ForeignKey,<br>    Integer, Text, REAL, DATE<br>) # imports that map SQL types to Python types<br><br># firstly, connect to the database<br>engine = sqlalchemy.create_engine(&quot;sqlite:///store_database.db&quot;, echo=False)<br><br># metadata object stores information about tables and mapping between them<br>metadata = MetaData()<br><br>items_table = Table(<br>    &quot;items&quot;,<br>    metadata,<br>    # when defining a table,<br>    # create a Column with it&#39;s name and data type --<br>    # you can also pass column parameters,<br>    # such as primary key or default value<br>    Column(&quot;item_id&quot;, Integer(), primary_key=True),<br>    Column(&quot;item_name&quot;, Text()),<br>    Column(&quot;item_price&quot;, REAL()),<br>)<br><br>operation_types_table = Table(<br>    &quot;operation_types&quot;,<br>    metadata,<br>    Column(&quot;operation_type_id&quot;, Integer(), primary_key=True),<br>    Column(&quot;operation_type_name&quot;, Text()),<br>)<br><br>operations_table = Table(<br>    &quot;operations&quot;,<br>    metadata,<br>    Column(&quot;operation_id&quot;, Integer(), primary_key=True),<br>    Column(&quot;operation_date&quot;, DATE()),<br>    # foreign key constraint passed as an additonal parameter<br>    Column(&quot;operation_type_id&quot;, Integer(), ForeignKey(&quot;operation_types.operation_type_id&quot;)),<br>)<br><br>operation_descriptions_table = Table(<br>    &quot;operation_descriptions&quot;,<br>    metadata,<br>    Column(&quot;description_id&quot;, Integer(), primary_key=True),<br>    Column(&quot;operation_id&quot;, Integer(), ForeignKey(&quot;operations.operation_id&quot;)),<br>    Column(&quot;item_id&quot;, Integer(), ForeignKey(&quot;items.item_id&quot;)),<br>    Column(&quot;amount&quot;, Integer()),<br>)<br><br># firstly, drop all existing tables<br>metadata.drop_all(<br>    bind=engine,<br>    tables=[<br>        operation_descriptions_table,<br>        operations_table,<br>        operation_types_table,<br>        items_table<br>    ]<br>)<br><br># and secondly, create all tables<br>metadata.create_all(<br>    bind=engine,<br>    tables=[<br>        items_table,<br>        operation_types_table,<br>        operations_table,<br>        operation_descriptions_table<br>    ]<br>)</pre><p>And then fill the tables:</p><pre># connect to database to execute any query<br>with engine.connect() as connection:<br>    connection.execute(<br>        # execute accepts a query, that is constructed using the table object<br>        items_table.insert().values([<br>            {&quot;item_id&quot;: 1, &quot;item_name&quot;: &quot;Cola&quot;, &quot;item_price&quot;: 2.5},<br>            {&quot;item_id&quot;: 2, &quot;item_name&quot;: &quot;Chips&quot;, &quot;item_price&quot;: 3.0},<br>            {&quot;item_id&quot;: 3, &quot;item_name&quot;: &quot;Water&quot;, &quot;item_price&quot;: 1.2},<br>            {&quot;item_id&quot;: 4, &quot;item_name&quot;: &quot;Apple&quot;, &quot;item_price&quot;: 0.3},<br>            {&quot;item_id&quot;: 5, &quot;item_name&quot;: &quot;Avocado&quot;, &quot;item_price&quot;: 1.75},<br>        ])<br>    )<br><br>    connection.execute(<br>        operation_types_table.insert().values([<br>            {&quot;operation_type_id&quot;: 1, &quot;operation_type_name&quot;: &quot;sell&quot;},<br>            {&quot;operation_type_id&quot;: 2, &quot;operation_type_name&quot;: &quot;return&quot;},<br>        ])<br>    )<br><br>    connection.execute(<br>        operations_table.insert().values([<br>            {&quot;operation_id&quot;: 1, &quot;operation_date&quot;: date(2022, 4, 22), &quot;operation_type_id&quot;: 1},<br>            {&quot;operation_id&quot;: 2, &quot;operation_date&quot;: date(2022, 4, 22), &quot;operation_type_id&quot;: 1},<br>            {&quot;operation_id&quot;: 3, &quot;operation_date&quot;: date(2022, 4, 22), &quot;operation_type_id&quot;: 2},<br>            {&quot;operation_id&quot;: 4, &quot;operation_date&quot;: date(2022, 4, 23), &quot;operation_type_id&quot;: 1},<br>        ])<br>    )<br><br>    connection.execute(<br>        operation_descriptions_table.insert().values([<br>            {&quot;description_id&quot;: 1, &quot;operation_id&quot;: 1, &quot;item_id&quot;: 1, &quot;amount&quot;: 1},<br>            {&quot;description_id&quot;: 2, &quot;operation_id&quot;: 1, &quot;item_id&quot;: 2, &quot;amount&quot;: 2},<br>            {&quot;description_id&quot;: 3, &quot;operation_id&quot;: 2, &quot;item_id&quot;: 5, &quot;amount&quot;: 1},<br>            {&quot;description_id&quot;: 4, &quot;operation_id&quot;: 3, &quot;item_id&quot;: 5, &quot;amount&quot;: 1},<br>            {&quot;description_id&quot;: 5, &quot;operation_id&quot;: 4, &quot;item_id&quot;: 3, &quot;amount&quot;: 1},<br>            {&quot;description_id&quot;: 6, &quot;operation_id&quot;: 4, &quot;item_id&quot;: 4, &quot;amount&quot;: 2},<br>        ])<br>    )<br>    <br>    # commit changes<br>    connection.commit()</pre><h3><strong>Conclusion</strong></h3><p><strong>Raw SQL</strong> and <strong>SQLAlchemy Core</strong> syntaxes are very similar. The biggest pros of SQLAlchemy are using of Python objects and very laconic way to write queries.</p><p>In the next chapter, we’ll see how to write <strong>complex queries</strong> using both technologies. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1799bd53db1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What gives me the hope]]></title>
            <link>https://medium.com/@evgenybellyk/what-gives-me-the-hope-6a28a6f4cab5?source=rss-f14d3e7d633f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a28a6f4cab5</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[growth]]></category>
            <dc:creator><![CDATA[Evgeny Bellyk]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 05:53:02 GMT</pubDate>
            <atom:updated>2023-02-26T05:57:09.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tackYrhZg0gxpSjZ0tPow.png" /></figure><blockquote>People are designed to be bad</blockquote><p>But they are also designed to <em>become better</em>.</p><p>Many people have heard a story about two wolves living inside of each human, a Good one and a Bad one. They are constantly arguing, trying to make a person either good or bad.</p><p>I prefer another model of a human. Say you are a typical person. What usually drives you to improve? Do you want to be a better man? Or are you trying to reach more, being greedy?</p><p>There’s always a jealous part of you, a little gremlin, call it `<strong><em>Greedy</em></strong>`, who wants more than it can bite. Though there’s another gremlin, say `<strong><em>Satisfied</em></strong>`, who just feels it’s enough.</p><p>`<strong><em>Greedy</em></strong>` pushes you towards better relationships, a more paid job, or even more beautiful body, while `<strong><em>Satisfied</em></strong>` says: “Hah man, stop, you’ve already reached all you wanted!”</p><p>While `<strong><em>Greedy</em></strong>` says you’re incomplete, `<strong><em>Satisfied</em></strong>` claims you can’t make any further improvement.</p><p>You’ve found a beautiful, smart girlfriend? Then `<strong><em>Greedy</em></strong>` would notify you that you are probably incompatible in everyday life.</p><p>Trying to build a good body? `<strong><em>Satisfied</em></strong>` would not wait to remind you about new episodes of your favorite movie.</p><p>It’s an endless round.</p><p>Though I’m starting to understand something bigger…</p><blockquote>A colleague of mine, who works as a doctor in the local hospital, has a wife and a daughter, and a son after divorcing and usually makes 2 webinars a month for younger doctors.</blockquote><p>And every 6 months he becomes drunk as f*ck, forcing us to climb him away from the depression abyss.</p><p>I thought he was just the type of <em>lost</em> person, who doesn’t struggle with their usual life but has to spend some time to heal their brain (especially with alcohol).</p><p>But then he started a youtube channel for ophthalmologists. He recorded not as many as 4 videos a month, some boring medicine videos with colored pictures of the human’s eye. Yet it was a constant 4-video uploading per month.</p><p>“<em>Okay, probably midlife crisis</em>”, — I thought, and he started a tiktok account with videos — you got the idea — about medicine. But that time it was all for the patients.</p><p>I’ve visited his small office a couple of times and noticed that wine bottles have disappeared from the fridge, a huge stack of research papers has gone from his windowsill and it certainly has become less dusty.</p><p>“<em>He’s not satisfied,</em>” — I guessed. What surprised me is that he spent a decade in medicine without doing much progress. And then it boomed.</p><p>I made a mistake thinking that his `<strong><em>Greedy</em></strong>` lost the war — it’s just collected resources to make a fast punch!</p><p>So, I guess, you literally can’t lose this war.</p><blockquote>You can’t lose the war between `<strong>Greedy</strong>` and `<strong>Satisfied</strong>`</blockquote><p>You are this war. Tick. All these inconsistencies with <a href="https://medium.com/@notuntill/how-it-feels-to-fail-a-startup-979f36795b3d">a failed startup</a>, cruel love and emigration just formed a puzzle.</p><p>It wasn’t a conflict of my subpersonalities. It was a process of a deeper understanding of who I am, a process of accepting myself with my wishes and limits.</p><p>Two wolves no longer have to fight. Instead, they can help each other to pursue the same aim — to become happy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a28a6f4cab5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 Mistakes I Made As a Startup Founder]]></title>
            <link>https://medium.com/@evgenybellyk/top-5-mistakes-i-made-as-a-startup-founder-cf5de54f5e0a?source=rss-f14d3e7d633f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf5de54f5e0a</guid>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[mistakes]]></category>
            <category><![CDATA[motivation]]></category>
            <dc:creator><![CDATA[Evgeny Bellyk]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 07:56:49 GMT</pubDate>
            <atom:updated>2023-02-14T07:56:49.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcTXiovIWfhG_ARrVHYksw.jpeg" /></figure><p>As a startup cofounder, <a href="https://medium.com/@notuntill/how-it-feels-to-fail-a-startup-979f36795b3d">I’ve made a lot of mistakes</a>. Sleepless nights, destroyed relationships, terrible product hypotheses… I want to share the top 5 conclusions from my own startup with you, that would not only be useful in business, but also in a real life. Let’s go!</p><h4><strong>1. Life over work, not vice versa</strong></h4><p>Was it obvious? Yeah. Did I follow the rule “take some rest every 2 months”? Definitely, no.</p><p>We’re all human creatures, and getting inspired by something, we cannot think of any other subject. So didn’t I.</p><p>But it’s important to remember that permanent tension leads not only to tiredness but also to <strong>burnout</strong>. There are plenty of materials on <em>burnout</em> topic, and I strongly recommend you get through them to avoid such a disease!</p><h4><strong>2. Be patient</strong></h4><p>Actions don’t always directly lead to some consequences. For example, when people begin taking antidepressants, it gets some time for the drugs to start working. It is called <em>the cumulative effect</em>.</p><p>You’ve changed your website greeting message? Don’t expect users to instantly flood your product! Wait for some time before evaluating your actions.</p><h4>3. Create the simplest possible solution</h4><p>We all tend to believe that our problem requires <strong>that</strong> complex solution…</p><p>I made this mistake when decided to use machine learning in our startup. And as a result, we couldn’t find new team members to join us! My application was too complex.</p><p>So next time you decide that it is a good idea to use a new framework or follow sophisticated guidelines, remember that there’ll be other people to support and develop your creature. Take care of them!</p><h4>4. Don’t overdo</h4><p>Yeah, that sounds weird. Some may even think of how is it unfair against your employer or your colleagues.</p><p>Remember point 1, work-life balance? Truth is, that you have to take care of yourself. By constantly pushing yourself toward some <em>ideal</em> product, you’re just increasing your chances to burn out!</p><p>I have some other explanation for this point. In software development, you can easily distinguish a beginner from a pro by the number of their movements. When a beginner starts running around like a headless chicken, a pro clarifies all the requirements and then solves the problem with one precise stroke. You can even see it in the amount of written code!</p><h4>5. Choose the right time to quit</h4><p>The Aim of the startup, without any romanticization, is to earn money. So you always have to think about when it’s the best time to quit and earn as much as possible.</p><p>You have to track not only your money or your equity but also your skills and social network. When you see that the growth slows down, probably it’s time to look for a new place.</p><h4>Conclusion</h4><p>Building the startup feels like a permanent fight. You create a product, solve some problems, then a new one appears, and so on. But you have to remember that a startup, in the first place, is a great experience of handling difficulties.</p><p>We all learn by mistakes, and I hope that you’ll make <a href="https://medium.com/@notuntill/how-it-feels-to-fail-a-startup-979f36795b3d">your own way</a> through them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf5de54f5e0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How It Feels To Fail A Startup]]></title>
            <link>https://medium.com/@evgenybellyk/how-it-feels-to-fail-a-startup-979f36795b3d?source=rss-f14d3e7d633f------2</link>
            <guid isPermaLink="false">https://medium.com/p/979f36795b3d</guid>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[fail]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[depression]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Evgeny Bellyk]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 10:51:20 GMT</pubDate>
            <atom:updated>2023-02-14T07:58:41.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3635eUomE3zVrs5k-7kJQ.jpeg" /></figure><p>Well, it sucks. But as soon as I failed, I realized that there are lots of <a href="https://medium.com/@notuntill/top-5-mistakes-i-made-as-a-startup-founder-cf5de54f5e0a">previously closed opportunities</a>.</p><p>To begin with — I don’t account myself as a genius. Neither I believed that my first startup could survive.</p><p>During high school, I simply did all the things teenagers do — played computer games, hung out, and spent time in the depression.</p><p>There was a detail that differed me from my classmates: I tried to build an Outstanding Android Application. I’ve spent hundreds of hours on silly pet projects and tried multiple times to win in local scientific fairs (and sometimes even succeeded), but it all was wrong.</p><p>And there I started learning about AI and overhyping Machine learning…</p><h4>All goes from the opportunity</h4><p>Actually, it was boring. Dozens of formulas didn’t make me happy. Though I felt myself on the edge of the wave.</p><p>And one evening, as I routinely watched lectures with the left half of my brain and doom-scrolled the news with another half, I met an advertisement about a startup meetup in my town.</p><p>— <em>“You can’t know if you don’t try”</em> — I thought and prepared myself for the upcoming event.</p><p>The meetup was filled with buzzwords, weird people, and much embarrassment, but keeping things short — I met my first team here.</p><p>We began to work together quite frequently, won a hackathon, and even took a trip to another city — and all that time we developed our Product.</p><h4>From spark to fire</h4><p>I fell in love with our service. We built a neural network for ophthalmologists, I did a huge amount of research and ML. Users kept growing slowly, our clients intended to pay us more in the future year, and it all should’ve been good.</p><p><strong>2020s</strong>. And then unexpected happened. Covid seemed to be a great way to monetize our application, though a healthcare system was overwhelmed with dying patients. We balanced as we could.</p><p>It was a weird dance of trying to cut costs and gain extra monetization way.</p><p>Another product with a better strategy? It <strong>fails.</strong></p><p>New service? Let’s try. <strong>Fail.</strong></p><p>I did my best to not fall into despair, but things were becoming worse and worse. I started a job search.</p><p>As I found one, my cofounder said that I’d better switch to another job for full-time, cause <em>“Our startup seemed to fail. Sorry”</em>.</p><h4>It’s the rainy days that give us love for the sun</h4><p>Chin up! New job, new colleagues, new projects. Bureaucracy, antidepressants. Ghosts of the past.</p><p>I felt like constantly fighting with myself, saying: <strong>It’s all wrong!</strong></p><p>I guess everybody tried to fit an inconsistent shape, and it was so. Then I realized that a remote job allows me to try different things.</p><p>Want to take a course on new technology? Make it your <strong>morning routine</strong> instead of the road to your office!</p><p>Your friends are only available in the afternoon? Make use of an <strong>unfixed schedule</strong>!</p><p>Feeling depressed? <strong>Play with your cat</strong> and pet her!</p><p>Firstly I just couldn’t believe that there was joy in other activities, but it was indeed there. I started to enjoy my new job and, most important, I found time for myself!</p><blockquote>Living in a startup is like trying to feed the flame with your time</blockquote><p>It makes you live fast and it exhausts you quickly. Sadly, it’s not the thing you can understand from the inside.</p><p>Startup gave me the opportunity to <a href="https://medium.com/@notuntill/top-5-mistakes-i-made-as-a-startup-founder-cf5de54f5e0a">try lots of new things</a> and met lots of new people. But it also gave me a way to cope with the stress after losing something important.</p><p>I guess every person should try something similar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=979f36795b3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>