<?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 Vedran Bilopavlović on Medium]]></title>
        <description><![CDATA[Stories by Vedran Bilopavlović on Medium]]></description>
        <link>https://medium.com/@vbilopav?source=rss-bbfad6df8d07------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bNH44cmtwewRk1TJ8kPLAw.jpeg</url>
            <title>Stories by Vedran Bilopavlović on Medium</title>
            <link>https://medium.com/@vbilopav?source=rss-bbfad6df8d07------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:34:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vbilopav/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[End-to-End Static Type Checking: PostgreSQL to TypeScript]]></title>
            <link>https://medium.com/@vbilopav/end-to-end-static-type-checking-postgresql-to-typescript-74664ea5159c?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/74664ea5159c</guid>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[type-safety]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 12:32:01 GMT</pubDate>
            <atom:updated>2025-12-31T12:32:01.416Z</atom:updated>
            <content:encoded><![CDATA[<p>Blogpost originally published on my website dedicated to <a href="https://npgsqlrest.github.io/">NpgsqlRest</a> platform.</p><p>You can read it also here:</p><p><a href="https://npgsqlrest.github.io/blog/end-to-end-static-type-checking-postgresql-typescript.html">https://npgsqlrest.github.io/blog/end-to-end-static-type-checking-postgresql-typescript.html</a></p><p>What if a database schema change could break your TypeScript build <em>before</em> it ever reaches production? With <a href="https://npgsqlrest.github.io/config/codegen.html">NpgsqlRest’s automatic type generation</a>, that’s exactly what happens. This post walks through a complete example demonstrating end-to-end static type checking from PostgreSQL functions to TypeScript client code.</p><h3>The Problem with Traditional API Development</h3><p>In typical REST API workflows, there’s a dangerous gap between your database schema and your client code:</p><ol><li>You change a column name in PostgreSQL</li><li>Your API continues to work (returning the new column name)</li><li>Your frontend code silently breaks at runtime</li><li>Users discover the bug, not your build system</li></ol><p>This gap exists because types are defined in multiple places — database schemas, API layer, and client code — with no automatic synchronization.</p><h3>Why PostgreSQL Functions?</h3><p>PostgreSQL functions are powerful tools that allow developers to encapsulate business logic within the database itself. When you keep logic within the database:</p><ul><li>Centralized Logic: All application instances interact with the data consistently. This is particularly beneficial in environments where multiple applications or instances access the same database.</li><li>Improved Performance: By pushing logic down to the database layer, you reduce the need for data to travel back and forth between the database and application.</li><li>Atomic Operations: Functions can be executed as a single transaction, ensuring operations are atomic and consistent — particularly useful when making changes that involve multiple tables.</li><li>Ease of Maintenance: When business logic resides in functions, it becomes easier to update and manage without having to redeploy the entire application. Fixing a bug or optimizing a query can be done directly in the database, with immediate effect across all instances.</li></ul><p>But perhaps the most underappreciated benefit is static type checking. PostgreSQL functions have explicit return types that the database enforces. This creates a natural contract that can be propagated all the way to your client code.</p><h3>The Solution: Single Source of Truth</h3><p>NpgsqlRest solves this by making PostgreSQL the single source of truth:</p><pre>PostgreSQL Function → NpgsqlRest → Generated TypeScript API Client → Your Application</pre><p>Any change to the PostgreSQL function signature automatically regenerates the TypeScript interfaces. If your application code references a property that no longer exists, the TypeScript compiler fails the build.</p><h3>Project Structure</h3><p>The example follows this structure:</p><pre>2_static_type_checking/<br>├── sql/<br>│   ├── R__example_2_tables.sql       # Schema and tables (repeatable)<br>│   ├── A__example_2_get_users.sql    # get_users() function (always run)<br>│   └── A__example_2_get_posts.sql    # get_posts() function (always run)<br>├── src/<br>│   ├── example2Api.ts                # Auto-generated by NpgsqlRest<br>│   └── app.ts                        # Hand-written application code<br>├── public/<br>│   └── index.html                    # HTML entry point<br>└── config.json                       # NpgsqlRest configuration</pre><p>The key insight is in the file naming convention:</p><ul><li>R__ prefix: Repeatable migrations - recreate schema and tables</li><li>A__ prefix: Always-run migrations - recreate functions on every build</li></ul><h3>The Database Schema</h3><p>The schema creates two simple tables: users and posts.</p><pre>-- R__example_2_tables.sql<br><br>-- recreate entire schema example_2<br>drop schema if exists example_2 cascade;<br>create schema example_2;<br><br>create table example_2.users (<br>    user_id int primary key generated always as identity,<br>    username text not null,<br>    email text not null,<br>    active boolean not null default true<br>);<br><br>insert into example_2.users (username, email, active) values<br>(&#39;alice&#39;, &#39;alice@example.com&#39;, true),<br>(&#39;bob&#39;, &#39;bob@example.com&#39;, true),<br>(&#39;charlie&#39;, &#39;charlie@example.com&#39;, true);<br><br>create table example_2.posts (<br>    post_id int primary key generated always as identity,<br>    user_id int references example_2.users(user_id) deferrable,<br>    content text not null,<br>    created_at timestamp not null default now()<br>);<br><br>insert into example_2.posts (user_id, content, created_at) values<br>(1, &#39;Hello world! This is my first post.&#39;, &#39;2024-01-15 10:30:00&#39;),<br>(1, &#39;Learning PostgreSQL is fun!&#39;, &#39;2024-01-16 14:20:00&#39;),<br>(2, &#39;Just joined this platform.&#39;, &#39;2024-01-17 09:00:00&#39;),<br>(3, &#39;Anyone here interested in databases?&#39;, &#39;2024-01-18 11:45:00&#39;),<br>(2, &#39;Working on a new project today.&#39;, &#39;2024-01-19 16:30:00&#39;);</pre><h3>Functions That Define the API Contract</h3><p>The magic happens in the function definitions. These functions are recreated on every build, which means:</p><ol><li>The function signature is always authoritative</li><li>NpgsqlRest regenerates TypeScript types from the current function definition</li><li>Any mismatch between the function and client code is caught at compile time</li></ol><h3>get_users()</h3><pre>-- A__example_2_get_users.sql<br><br>create or replace function example_2.get_users()<br>returns setof example_2.users<br>language sql<br>as $$<br>select user_id, username, email, active from example_2.users;<br>$$;<br><br>comment on function example_2.get_users() is &#39;HTTP GET&#39;;<br><br>do<br>$$<br>begin<br>    assert (<br>        select count(*) = 3<br>        from example_2.get_users()<br>        where (user_id, username, email, active) in (<br>            (1, &#39;alice&#39;, &#39;alice@example.com&#39;, true),<br>            (2, &#39;bob&#39;, &#39;bob@example.com&#39;, true),<br>            (3, &#39;charlie&#39;, &#39;charlie@example.com&#39;, true)<br>        )<br>    ), &#39;get_users() does not contain expected data&#39;;<br>end;<br>$$;</pre><p>Notice:</p><ul><li>returns setof example_2.users: The return type is the entire users table structure</li><li>comment on function ... is &#39;HTTP GET&#39;: This tells NpgsqlRest to <a href="https://npgsqlrest.github.io/annotations/http.html">expose it as a GET endpoint</a></li><li>The assert block: Built-in data validation test that runs on every migration</li></ul><h3>get_posts()</h3><pre>-- A__example_2_get_posts.sql<br><br>create or replace function example_2.get_posts()<br>returns table(<br>    username text,<br>    content text,<br>    created_at timestamp<br>)<br>language sql<br>as $$<br>select u.username, p.content, p.created_at<br>from example_2.posts p join example_2.users u using(user_id)<br>where u.active = true<br>$$;<br><br>comment on function example_2.get_posts() is &#39;HTTP GET&#39;;<br><br>do<br>$$<br>begin<br>    assert (<br>        select count(*) = 5<br>        from example_2.get_posts()<br>        where (username, content, created_at) in (<br>            (&#39;alice&#39;, &#39;Hello world! This is my first post.&#39;, &#39;2024-01-15 10:30:00&#39;::timestamp),<br>            (&#39;alice&#39;, &#39;Learning PostgreSQL is fun!&#39;, &#39;2024-01-16 14:20:00&#39;::timestamp),<br>            (&#39;bob&#39;, &#39;Just joined this platform.&#39;, &#39;2024-01-17 09:00:00&#39;::timestamp),<br>            (&#39;charlie&#39;, &#39;Anyone here interested in databases?&#39;, &#39;2024-01-18 11:45:00&#39;::timestamp),<br>            (&#39;bob&#39;, &#39;Working on a new project today.&#39;, &#39;2024-01-19 16:30:00&#39;::timestamp)<br>        )<br>    ), &#39;get_posts() does not contain expected data&#39;;<br>end;<br>$$;</pre><p>This function uses an explicit returns table(...) definition, specifying exactly which columns are returned. The function joins users and posts, filtering only active users.</p><h3>Static Type Checking at the SQL Level</h3><p>Before we even get to TypeScript, PostgreSQL itself performs static type checking on function definitions. This is a crucial first line of defense.</p><h3>How PostgreSQL Enforces Return Types</h3><p>When you define a function with returns table(...) or returns setof, PostgreSQL validates that your function body actually returns the declared types. If there&#39;s a mismatch, the function creation fails.</p><p>Consider this scenario — you have a function returning username text:</p><pre>create or replace function example_2.get_posts()<br>returns table(<br>    username text,<br>    content text,<br>    created_at timestamp<br>)<br>language sql<br>as $$<br>select u.username, p.content, p.created_at<br>from example_2.posts p join example_2.users u using(user_id)<br>where u.active = true<br>$$;</pre><p>Now imagine someone changes the username column in the users table to jsonb:</p><pre>alter table example_2.users alter column username type jsonb using to_jsonb(username);</pre><p>The next time you run your migration (which recreates the function), PostgreSQL will fail:</p><pre>ERROR:  return type mismatch in function declared to return record<br>DETAIL:  Final statement returns jsonb instead of text at column 1.</pre><p>The database itself caught the type error. This happens at migration time, before any application code runs, before any TypeScript is compiled.</p><h3>The Return Type Contract</h3><p>PostgreSQL function return types create an explicit contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_hBASe-JES7TiWk9F8EUQ.png" /></figure><p>This contract is enforced when:</p><ol><li>The function is created or replaced</li><li>The function is called</li></ol><p>If the underlying table structure changes in a way that breaks the contract, you discover it immediately when recreating the function — not when a user triggers the code path in production.</p><h3>Type Changes Propagate Naturally</h3><p>The workflow becomes:</p><ol><li>Change a column type in PostgreSQL</li><li>Function recreation fails during migration (if return type doesn’t match)</li><li>Update the function to handle the new type</li><li>NpgsqlRest regenerates TypeScript interfaces</li><li>TypeScript build fails if client code uses the old type</li><li>Update client code to match</li></ol><p>Every layer validates types. Errors surface at the earliest possible moment.</p><h3>Why Functions Are Recreated on Every Build</h3><p>The A__ prefix ensures these SQL files run on every database migration. This is the key to enforcing type checking:</p><p>Scenario: You decide to rename content to body in get_posts().</p><ol><li>You update the SQL function to return body instead of content</li><li>Database migration runs, recreating the function with the new signature</li><li>NpgsqlRest regenerates example2Api.ts with the new interface</li><li>TypeScript build fails: Property &#39;content&#39; does not exist on type &#39;IGetPostsResponse&#39;</li><li>You fix app.ts to use body instead of content</li><li>Build succeeds</li></ol><p>Without the function recreation on each build, the old TypeScript types would persist, and the error would only surface at runtime.</p><h3>Built-in Testing with SQL Assertions</h3><p>Each function file includes an assert block that validates the function returns expected data. These assertions run during migration, providing immediate feedback:</p><pre>do<br>$$<br>begin<br>    assert (<br>        select count(*) = 3<br>        from example_2.get_users()<br>        where (user_id, username, email, active) in (<br>            (1, &#39;alice&#39;, &#39;alice@example.com&#39;, true),<br>            (2, &#39;bob&#39;, &#39;bob@example.com&#39;, true),<br>            (3, &#39;charlie&#39;, &#39;charlie@example.com&#39;, true)<br>        )<br>    ), &#39;get_users() does not contain expected data&#39;;<br>end;<br>$$;</pre><p>If the assertion fails, the migration fails, and you know immediately that something is wrong. This creates a safety net ensuring:</p><ol><li>The function executes without errors</li><li>The function returns the expected structure</li><li>Test data is present and correct</li></ol><p>This is database-level unit testing that runs on every deployment.</p><h3>Unit Testing PostgreSQL Functions: Beyond Fixed Data</h3><p>The example above uses fixed test data that’s inserted during migration. This approach is simple and effective, but what about testing with dynamic data or edge cases? Let’s explore more robust testing patterns.</p><h3>Co-located Tests: Function and Test in the Same File</h3><p>The most practical approach is to place tests directly in the same file as the function being tested. Since these files run on every build (the A__ prefix), your tests execute automatically with every migration.</p><p>Here’s the complete pattern for A__example_2_get_users.sql:</p><pre>-- A__example_2_get_users.sql<br><br>create or replace function example_2.get_users()<br>returns setof example_2.users<br>language sql<br>as $$<br>select user_id, username, email, active from example_2.users;<br>$$;<br><br>comment on function example_2.get_users() is &#39;HTTP GET&#39;;<br><br>-- Test: Verify function returns expected fixed data<br>do<br>$$<br>begin<br>    assert (<br>        select count(*) = 3<br>        from example_2.get_users()<br>        where (user_id, username, email, active) in (<br>            (1, &#39;alice&#39;, &#39;alice@example.com&#39;, true),<br>            (2, &#39;bob&#39;, &#39;bob@example.com&#39;, true),<br>            (3, &#39;charlie&#39;, &#39;charlie@example.com&#39;, true)<br>        )<br>    ), &#39;get_users() does not contain expected data&#39;;<br>end;<br>$$;</pre><p>The function and its test live together. When the function changes, the test is right there to update.</p><h3>Test Isolation with Rollback</h3><p>Unit tests must not interfere with each other. They must maintain perfect isolation. The solution is simple: end your test block with rollback; to undo any data modifications.</p><pre>-- Test: get_users() returns newly inserted users<br>do<br>$$<br>begin<br>    -- Insert test data<br>    insert into example_2.users (username, email, active)<br>    values (&#39;test_user&#39;, &#39;test@example.com&#39;, true);<br><br>    -- Verify the function returns our test user<br>    assert (<br>        select count(*) = 1<br>        from example_2.get_users()<br>        where username = &#39;test_user&#39;<br>    ), &#39;get_users() should return the inserted test user&#39;;<br><br>    -- Rollback to undo the insert<br>    rollback;<br>end;<br>$$;</pre><p>The rollback; at the end ensures the test data never persists. Each test starts with a clean slate.</p><h3>Testing Multiple Scenarios</h3><p>You can have multiple test blocks in the same file, each testing a different scenario:</p><pre>-- A__example_2_get_posts.sql<br><br>create or replace function example_2.get_posts()<br>returns table(<br>    username text,<br>    content text,<br>    created_at timestamp<br>)<br>language sql<br>as $$<br>select u.username, p.content, p.created_at<br>from example_2.posts p join example_2.users u using(user_id)<br>where u.active = true<br>$$;<br><br>comment on function example_2.get_posts() is &#39;HTTP GET&#39;;<br><br>-- Test 1: Verify function returns expected fixed data<br>do<br>$$<br>begin<br>    assert (<br>        select count(*) = 5<br>        from example_2.get_posts()<br>        where (username, content, created_at) in (<br>            (&#39;alice&#39;, &#39;Hello world! This is my first post.&#39;, &#39;2024-01-15 10:30:00&#39;::timestamp),<br>            (&#39;alice&#39;, &#39;Learning PostgreSQL is fun!&#39;, &#39;2024-01-16 14:20:00&#39;::timestamp),<br>            (&#39;bob&#39;, &#39;Just joined this platform.&#39;, &#39;2024-01-17 09:00:00&#39;::timestamp),<br>            (&#39;charlie&#39;, &#39;Anyone here interested in databases?&#39;, &#39;2024-01-18 11:45:00&#39;::timestamp),<br>            (&#39;bob&#39;, &#39;Working on a new project today.&#39;, &#39;2024-01-19 16:30:00&#39;::timestamp)<br>        )<br>    ), &#39;get_posts() does not contain expected data&#39;;<br>end;<br>$$;<br><br>-- Test 2: Verify inactive users&#39; posts are excluded<br>do<br>$$<br>declare<br>    _count int;<br>begin<br>    -- Make charlie inactive<br>    update example_2.users set active = false where username = &#39;charlie&#39;;<br><br>    -- Count posts from charlie (should be 0 since he&#39;s now inactive)<br>    select count(*) into _count<br>    from example_2.get_posts()<br>    where username = &#39;charlie&#39;;<br><br>    assert _count = 0,<br>        &#39;get_posts() should not return posts from inactive users&#39;;<br><br>    rollback;<br>end;<br>$$;<br><br>-- Test 3: New posts from active users appear in results<br>do<br>$$<br>declare<br>    _result record;<br>begin<br>    -- Insert a new post<br>    insert into example_2.posts (user_id, content, created_at)<br>    values (1, &#39;Brand new post!&#39;, now());<br><br>    -- Verify it appears in results<br>    select * into _result<br>    from example_2.get_posts()<br>    where content = &#39;Brand new post!&#39;;<br><br>    assert _result.username = &#39;alice&#39;,<br>        &#39;New post should appear with correct username&#39;;<br><br>    rollback;<br>end;<br>$$;</pre><h3>Testing Against Empty Tables</h3><p>To test how a function behaves with no data:</p><pre>-- Test: Function handles empty tables gracefully<br>do<br>$$<br>declare<br>    _count int;<br>begin<br>    -- Delete all data<br>    delete from example_2.posts;<br>    delete from example_2.users;<br><br>    -- Test that function returns 0 rows (not an error)<br>    select count(*) into _count from example_2.get_users();<br>    assert _count = 0,<br>        &#39;get_users() should return 0 rows when table is empty&#39;;<br><br>    select count(*) into _count from example_2.get_posts();<br>    assert _count = 0,<br>        &#39;get_posts() should return 0 rows when table is empty&#39;;<br><br>    rollback;<br>end;<br>$$;</pre><h3>Deferrable Constraints: The Key to Test Data</h3><p>Notice in our schema definition:</p><pre>user_id int references example_2.users(user_id) deferrable</pre><p>The deferrable keyword is crucial for testing. By default, foreign key constraints are checked immediately when you insert a row. With deferrable constraints, checks can be deferred until the end of the transaction.</p><p>Since test transactions are rolled back anyway, deferrable constraints allow you to insert test data without worrying about inserting data into a dozen related tables first. This dramatically simplifies test setup.</p><pre>-- Test: Posts with deferred constraints<br>do<br>$$<br>begin<br>    -- Defer all constraint checks until transaction end<br>    set constraints all deferred;<br><br>    -- Insert post with non-existent user_id (constraint check deferred)<br>    insert into example_2.posts (user_id, content, created_at)<br>    values (999, &#39;Orphan post&#39;, now());<br><br>    -- We can test our function here<br>    -- The FK violation won&#39;t be checked because we&#39;ll rollback<br><br>    rollback;<br>end;<br>$$;</pre><h3>Why Database Testing is Fast</h3><p>A common misconception is that database testing is slow. In reality, PostgreSQL testing can be faster than application-level testing because:</p><ol><li>No network overhead: Tests run inside the database</li><li>Transaction rollback is instant: No need to truncate tables or restore backups</li><li>Parallel execution: Tests in separate transactions can run concurrently</li><li>No ORM overhead: Direct SQL execution</li></ol><p>The key is proper isolation through transactions, not through recreating entire databases for each test.</p><h3>Addressing Common Myths</h3><p>“Testing in a database is impossible”</p><p>This is simply not true for PostgreSQL. While testing stored procedures might be difficult in some database systems, PostgreSQL provides all the tools you need: anonymous blocks, assertions, and transaction control.</p><p>“Testing in a database is slow”</p><p>It’s actually faster than most alternatives. When your test ends with rollback;, there&#39;s no cleanup needed - no truncating tables, no restoring backups. The rollback is nearly instantaneous. Compare this to spinning up Docker containers or re-seeding test databases.</p><p>“You can’t do TDD with SQL”</p><p>You absolutely can. Write your test first in the function file:</p><pre>-- A__example_2_create_user.sql<br><br>-- Test first (this will fail until we implement create_user)<br>do<br>$$<br>begin<br>    perform example_2.create_user(&#39;newuser&#39;, &#39;new@example.com&#39;);<br><br>    assert exists (<br>        select 1 from example_2.users where username = &#39;newuser&#39;<br>    ), &#39;User should be created&#39;;<br><br>    rollback;<br>end;<br>$$;<br><br>-- Now implement the function to make the test pass<br>create or replace function example_2.create_user(_username text, _email text)<br>returns void<br>language sql<br>as $$<br>insert into example_2.users (username, email, active)<br>values (_username, _email, true);<br>$$;</pre><p>Red-green-refactor works just as well in SQL as anywhere else. The test runs on every build, ensuring the function continues to work as expected.</p><h3>The Generated TypeScript Client</h3><p>NpgsqlRest <a href="https://npgsqlrest.github.io/config/codegen.html">automatically generates</a> example2Api.ts based on the PostgreSQL function signatures:</p><pre>// autogenerated at 2025-12-31T12:06:45.2201980+01:00<br><br>const baseUrl = &quot;http://127.0.0.1:8080&quot;;<br><br>interface IGetPostsResponse {<br>    username: string | null;<br>    content: string | null;<br>    createdAt: string | null;<br>}<br><br>interface IGetUsersResponse {<br>    userId: number | null;<br>    username: string | null;<br>    email: string | null;<br>    active: boolean | null;<br>}<br><br>/**<br>* function example_2.get_posts()<br>* returns table(<br>*     username text,<br>*     content text,<br>*     created_at timestamp without time zone<br>* )<br>*/<br>export async function getPosts() : Promise&lt;{<br>    status: number,<br>    response: IGetPostsResponse[],<br>    error: {status: number; title: string; detail?: string | null} | undefined<br>}&gt; {<br>    const response = await fetch(baseUrl + &quot;/api/example-2/get-posts&quot;, {<br>        method: &quot;GET&quot;,<br>        headers: {<br>            &quot;Content-Type&quot;: &quot;application/json&quot;<br>        },<br>    });<br>    return {<br>        status: response.status,<br>        response: response.ok ? await response.json() as IGetPostsResponse[] : undefined!,<br>        error: !response.ok ? await response.json() as {status: number; title: string; detail?: string | null} : undefined<br>    };<br>}<br><br>/**<br>* function example_2.get_users()<br>* returns table(<br>*     user_id integer,<br>*     username text,<br>*     email text,<br>*     active boolean<br>* )<br>*/<br>export async function getUsers() : Promise&lt;{<br>    status: number,<br>    response: IGetUsersResponse[],<br>    error: {status: number; title: string; detail?: string | null} | undefined<br>}&gt; {<br>    const response = await fetch(baseUrl + &quot;/api/example-2/get-users&quot;, {<br>        method: &quot;GET&quot;,<br>        headers: {<br>            &quot;Content-Type&quot;: &quot;application/json&quot;<br>        },<br>    });<br>    return {<br>        status: response.status,<br>        response: response.ok ? await response.json() as IGetUsersResponse[] : undefined!,<br>        error: !response.ok ? await response.json() as {status: number; title: string; detail?: string | null} : undefined<br>    };<br>}</pre><p>Key features of the generated code:</p><ol><li>Interfaces match the PostgreSQL return types exactly — Column names are converted from snake_case to camelCase</li><li>Nullable fields use | null - Reflecting PostgreSQL&#39;s nullable columns</li><li>JSDoc comments include the original function signature — Making it easy to trace back to the source</li><li>Typed error handling — Errors have a consistent structure with status, title, and optional detail</li></ol><h3>The Application Code</h3><p>The hand-written application code in app.ts demonstrates how type safety flows through to the UI layer:</p><pre>import { getPosts, getUsers } from &quot;./example2Api.ts&quot;;<br><br>const app = document.getElementById(&quot;app&quot;)!;<br><br>// Render a single user row - uses IGetUsersResponse properties<br>function renderUserRow(user: {<br>    userId: number | null;<br>    username: string | null;<br>    email: string | null;<br>    active: boolean | null<br>}) {<br>    const row = document.createElement(&quot;tr&quot;);<br>    row.innerHTML = `<br>        &lt;td&gt;${user.userId}&lt;/td&gt;<br>        &lt;td&gt;${user.username ?? &quot;Anonymous&quot;}&lt;/td&gt;<br>        &lt;td&gt;${user.email ?? &quot;N/A&quot;}&lt;/td&gt;<br>        &lt;td&gt;${user.active ? &quot;✓&quot; : &quot;✗&quot;}&lt;/td&gt;<br>    `;<br>    return row;<br>}<br><br>// Render a single post - uses IGetPostsResponse properties<br>function renderPost(post: {<br>    username: string | null;<br>    content: string | null;<br>    createdAt: string | null<br>}) {<br>    const article = document.createElement(&quot;article&quot;);<br>    article.className = &quot;post&quot;;<br>    article.innerHTML = `<br>        &lt;header&gt;&lt;strong&gt;${post.username ?? &quot;Anonymous&quot;}&lt;/strong&gt;&lt;/header&gt;<br>        &lt;p&gt;${post.content ?? &quot;&quot;}&lt;/p&gt;<br>        &lt;footer&gt;&lt;small&gt;${<br>            post.createdAt<br>                ? new Date(post.createdAt).toLocaleString()<br>                : &quot;Unknown date&quot;<br>        }&lt;/small&gt;&lt;/footer&gt;<br>    `;<br>    return article;<br>}<br><br>// Load and display users<br>async function loadUsers() {<br>    const { status, response: users, error } = await getUsers();<br><br>    if (status !== 200) {<br>        app.innerHTML = `&lt;p&gt;Error loading users: ${error?.title}&lt;/p&gt;`;<br>        return;<br>    }<br><br>    const table = document.createElement(&quot;table&quot;);<br>    table.innerHTML = `<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;ID&lt;/th&gt;<br>                &lt;th&gt;Username&lt;/th&gt;<br>                &lt;th&gt;Email&lt;/th&gt;<br>                &lt;th&gt;Active&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>    `;<br>    const tbody = document.createElement(&quot;tbody&quot;);<br><br>    // Static type checking happens here!<br>    // If IGetUsersResponse changes (e.g., &quot;username&quot; renamed to &quot;name&quot;),<br>    // TypeScript will fail the build with: Property &#39;username&#39; does not exist<br>    for (const user of users) {<br>        tbody.appendChild(renderUserRow(user));<br>    }<br><br>    table.appendChild(tbody);<br>    app.appendChild(table);<br>}<br><br>// Load and display posts<br>async function loadPosts() {<br>    const { status, response: posts, error } = await getPosts();<br><br>    if (status !== 200) {<br>        app.innerHTML += `&lt;p&gt;Error loading posts: ${error?.title}&lt;/p&gt;`;<br>        return;<br>    }<br><br>    const postsSection = document.createElement(&quot;section&quot;);<br>    postsSection.innerHTML = &quot;&lt;h2&gt;Posts&lt;/h2&gt;&quot;;<br><br>    // Static type checking happens here!<br>    // If IGetPostsResponse changes (e.g., &quot;content&quot; renamed to &quot;body&quot;),<br>    // TypeScript will fail the build with: Property &#39;content&#39; does not exist<br>    for (const post of posts) {<br>        postsSection.appendChild(renderPost(post));<br>    }<br><br>    app.appendChild(postsSection);<br>}<br><br>// Initialize the app<br>async function init() {<br>    app.innerHTML = &quot;&lt;h1&gt;Users &amp; Posts&lt;/h1&gt;&quot;;<br>    await loadUsers();<br>    await loadPosts();<br>}<br><br>init();</pre><p>The critical type-checking points are in the loop bodies where we access properties:</p><ul><li>user.userId, user.username, user.email, user.active</li><li>post.username, post.content, post.createdAt</li></ul><p>If any of these properties are renamed or removed in the PostgreSQL function, the TypeScript build fails immediately.</p><h3>The Complete Type-Safe Workflow</h3><p>Here’s what happens during development:</p><pre># 1. Run database migrations (recreates functions every time)<br>bun run db:up<br><br># 2. Start NpgsqlRest (regenerates example2Api.ts from current functions)<br>bun run dev<br><br># 3. Build TypeScript (catches any type mismatches)<br>bun run build</pre><p>If you change a column name in a PostgreSQL function:</p><ol><li>db:up recreates the function with the new column</li><li>NpgsqlRest detects the schema change and regenerates example2Api.ts</li><li>bun run build fails because app.ts references the old column name</li><li>You update app.ts to use the new name</li><li>Build succeeds</li></ol><p>The error is caught at build time, not runtime. No more mysterious undefined values in production.</p><h3>Configuration</h3><p>The <a href="https://npgsqlrest.github.io/guide/configuration.html">NpgsqlRest configuration</a> enables type generation:</p><pre>{<br>  &quot;ApplicationName&quot;: &quot;static_type_checking&quot;,<br>  &quot;StaticFiles&quot;: {<br>    &quot;RootPath&quot;: &quot;./2_static_type_checking/public&quot;<br>  },<br>  &quot;NpgsqlRest&quot;: {<br>    &quot;IncludeSchemas&quot;: [ &quot;example_2&quot; ],<br>    &quot;RequiresAuthorization&quot;: false,<br>    &quot;ClientCodeGen&quot;: {<br>      &quot;FilePath&quot;: &quot;./2_static_type_checking/src/{0}Api.ts&quot;<br>    }<br>  }<br>}</pre><p>The {0} placeholder in FilePath is replaced with the schema name, so example_2 becomes example2Api.ts.</p><h3>Benefits of This Approach</h3><h3>1. Single Source of Truth</h3><p>PostgreSQL functions define both the API contract and the TypeScript types. No manual synchronization required.</p><h3>2. Compile-Time Safety</h3><p>Schema changes break the build, not production. You discover problems during development, not from user reports.</p><h3>3. Automatic Documentation</h3><p>The generated code includes JSDoc comments with the original PostgreSQL function signature. Your IDE shows exactly what the database returns.</p><h3>4. Database-Level Testing</h3><p>SQL assertions validate your functions return the expected data structure. Tests run on every migration.</p><h3>5. No Runtime Type Checking Overhead</h3><p>Types are enforced at compile time. The generated JavaScript has zero overhead compared to hand-written fetch calls.</p><h3>Conclusion</h3><p>End-to-end static type checking transforms how you build database-backed applications. By making PostgreSQL the single source of truth and regenerating types on every build, you catch schema mismatches before they reach production.</p><p>The key ingredients:</p><ol><li>PostgreSQL function return types that create explicit contracts enforced by the database</li><li>Always-run migrations (A__ prefix) that recreate functions and run tests on every build</li><li>Co-located tests in the same file as the function, using simple do $$ ... rollback; end; $$; blocks</li><li>Deferrable constraints that enable isolated, fast unit tests</li><li>NpgsqlRest’s type generation that creates TypeScript interfaces from PostgreSQL signatures</li><li>TypeScript compilation that catches property mismatches</li></ol><p>The result is a multi-layered type safety system:</p><pre>PostgreSQL Schema<br>      ↓ (enforced by DB)<br>PostgreSQL Functions + Tests<br>      ↓ (generated by NpgsqlRest)<br>TypeScript Interfaces<br>      ↓ (enforced by tsc)<br>Application Code</pre><p>Every layer validates types. Errors surface at the earliest possible moment — during development, not in production. Schema changes naturally propagate through the entire stack, with compilers and databases acting as your safety net.</p><p>Unit testing in PostgreSQL isn’t slow or difficult. With simple anonymous blocks, transaction rollback, and deferrable constraints, you can achieve the same TDD workflows you’d use in any other language — but with the added benefit of testing your actual database logic, not a mock of it.</p><h3>Why This Stack is Superior</h3><p>Compare this approach to traditional stacks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*myi9H3sp8jTlXm3kIXYLsQ.png" /></figure><p>You eliminate entire layers. No ORM mappings to maintain. No repository pattern boilerplate. No controller classes. No manual API documentation. No hand-written TypeScript interfaces that drift out of sync with reality.</p><p>The code you don’t write has no bugs.</p><h3>Performance That Scales</h3><p>This isn’t just about developer experience — it’s about production performance. NpgsqlRest’s architecture eliminates the overhead that traditional frameworks accumulate:</p><ul><li>No ORM overhead: Direct PostgreSQL protocol communication</li><li>No routing framework: Endpoints derived from database metadata</li><li>No serialization layer: PostgreSQL’s native JSON functions handle serialization</li><li>Minimal memory allocation: Optimized hot paths using buffer pooling</li></ul><p>The result? NpgsqlRest consistently outperforms traditional frameworks. In <a href="https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2025.html">benchmarks</a>, it achieves over 5,000 requests per second at 100 concurrent users — nearly 35% faster than the second-place framework and over 50% faster than hand-optimized Rust implementations.</p><h3>Maximum Type Safety, Minimum Code</h3><p>Traditional approaches require you to define types in multiple places and hope they stay synchronized:</p><pre>Database → ORM → Service → Controller → OpenAPI → Client SDK → Frontend</pre><p>Each arrow is a potential desynchronization point. Each layer requires manual maintenance.</p><p>With NpgsqlRest:</p><pre>Database → Generated Client → Frontend</pre><p>One source of truth. Zero manual synchronization. Types flow automatically from database to browser.</p><h3>The Bottom Line</h3><p>This stack delivers:</p><ul><li>Full end-to-end type safety from PostgreSQL to TypeScript</li><li>The least amount of code — no boilerplate layers to maintain</li><li>Superior performance — direct database-to-HTTP pipeline</li><li>Built-in testing that runs on every deployment</li><li>Automatic documentation through generated code</li></ul><p>When you combine database-enforced types, automated type generation, compile-time checking, and co-located SQL tests, you get a development experience where “it works on my machine” actually means “it will work in production.”</p><p>NpgsqlRest delivers the best performance with the least code — a rare combination that eliminates entire categories of bugs and maintenance burden.</p><p>More Blog Posts: <a href="https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2025.html">PostgreSQL REST API Benchmark 2025</a></p><p>Get Started: <a href="https://npgsqlrest.github.io/guide/quick-start.html">Quick Start Guide</a> · <a href="https://npgsqlrest.github.io/guide/installation.html">Installation</a> · <a href="https://npgsqlrest.github.io/config/codegen.html">Code Generation Config</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74664ea5159c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Start with a Logical Data Model]]></title>
            <link>https://medium.com/@vbilopav/why-start-with-a-logical-data-model-b1fb786ebbf1?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1fb786ebbf1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 11:39:13 GMT</pubDate>
            <atom:updated>2025-11-02T11:39:13.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpOz-qnI8axTF6b8GZoa1A.jpeg" /><figcaption>Image by Grok AI</figcaption></figure><p>The first thing that needs to be developed in a new system is a Logical Data Model, not the Domain Model. Not even a database. Logical Data Model first.</p><p>I came across a Reddit comment that said:</p><blockquote>Devs who use code first and their DB designs are always vile and inefficient.</blockquote><p>My reply was, well, that’s because <strong>they are taught to design the “domain model” and not the Data Model (either logical or physical).</strong></p><p>But why would a Domain Modeler jump into code first, you might ask? Aren&#39;t they trained to think in business or domain terms?</p><p>Yes, but the discussion was <strong>Code First vs DB First</strong> in ORM (Object-Relational Mapping) implementation.</p><h4>Why Code First Dominates</h4><p>ORM libraries in general employ two distinct mapping strategies: <strong>1)</strong> where you define your database first and then map to the ORM code, also known as <strong>DB First</strong>, or <strong>2)</strong> where you define code objects using the ORM library and then recreate your database automatically from those code definitions, also known as <strong>Code First</strong>.</p><p>If we take a quick look at the definition of the domain model, let&#39;s use a <a href="https://martinfowler.com/eaaCatalog/domainModel.html">Martin Fowler definition</a> from his catalog:</p><blockquote>A Domain Model creates a <strong>web of interconnected objects</strong>, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form.</blockquote><p>A domain model is actually an <strong>Object Model</strong> (as in, objects existing in computer memory and defined by the <strong>Object-Oriented language)</strong>. At least in its physical form, that is.</p><p>So, for a <strong>Domain Modeler and DDD practitioner</strong>, the Code First approach would be natural, or perhaps sometimes the only choice, and no wonder that <strong>Code First has become the default approach</strong>. There are, of course, practitioners who still do DB-first, but that is neither a general trend nor a default approach for many.</p><p>I will return to Domain Modeling later.</p><p>In any case, the results are, as this Redditor says, *<strong>vile and inefficient</strong>* <em>DB designs</em>.</p><p>Now, for the past couple of years, I have analyzed and reviewed a large number of blogs and articles on software development, with a particular focus on backend and database technologies. That is my hobby. Well, everyone has some strange and tedious hobbies, right?</p><p>And I don&#39;t think that I have ever crossed one that even mentions Logical Data Model as an integral and crucial first step of developing new software. Domain model, yes, there is plenty of that. But the Logical Data model, no.</p><p>Maybe this is a topic worth discussing.</p><p>So, let&#39;s unpack.</p><h4>What is a Logical Data Model (LDM) anyway?</h4><p>A Logical Data Model is a detailed representation of the data within your system. It defines <strong>entities, attributes, relationships, and constraints</strong> — independent of any physical implementation, such as a database schema or application code.</p><p>It’s an <strong>abstract model of reality</strong> within your domain that serves as a <strong>blueprint for your software</strong> — something you develop conceptually, often on paper, before any actual development begins.</p><p>In simplest terms, it’s a <strong>data blueprint</strong> that bridges the gap between the <strong>conceptual understanding</strong> (and conceptual models) of your domain and the <strong>physical implementation</strong> (for example, a database).</p><p>Typical form of an LDM is based on <strong>relational theory</strong> as its strong mathematical foundation. In such cases, the model is expressed through entities (which correspond to <strong>tables</strong>), attributes (<strong>columns</strong>), and relationships (<strong>foreign keys</strong> or associations).</p><p>It may be fully <strong>normalized</strong> to ensure data consistency, to avoid duplication, eliminate data anomalies and redundancies, etc.</p><p>It may even be <strong>strategically denormalized.</strong> For example, a star schema with precalculated aggregates, optimized for analytics instead of transactions.</p><p>That all depends on what you want to build and, of course, on <strong>deep, thoughtful analysis.</strong></p><h4>Blueprint For Your System</h4><p>Whatever it may be, normalized or denormalized and everything in between, LDM still remains a <strong>logical, abstract concept, </strong>something not yet implemented.</p><p>Maybe sometimes even in the form of healthy <strong>whiteboard exercise</strong>, or maybe more commonly in the form of very official <strong>corporate documentation</strong>. It may be in some digital form, it may be on a napkin during lunch break, or simply in someone&#39;s head — it is the <strong>blueprint</strong> for your future software.</p><p>Building any sort of physical object, let alone houses, bridges, and so on, <strong>requires a blueprint</strong>, and software is no exception.</p><p>Bottom line is that Logical Data Modeling is a mental process to formalize a concept of reality, but it is ultimately <strong>driven by the use cases</strong> for that data. We think about our use cases, and they show us how to model the data so that we might, for example:</p><ul><li><strong>Simplify the required manipulation</strong> use cases so we may normalize to eliminate anomalies, redundancy, and any potential oddities that may lead to confusion and problems doing our inserts, updates, or what have you.</li><li><strong>Simplify the required querying</strong> for our use cases. By modeling data, we can see clearly how we would get into trouble trying to query the data we need, and here is a chance to simplify that and adjust the model accordingly.</li><li>We can detect <strong>potential bottlenecks</strong> if the data grows, and we can adjust the model with a denormalized structure to improve performance, for example.</li><li>By modeling the data, we can see clearly from the start, for example, where <strong>we could benefit from insert-only models</strong> with a full history of state changes, but we can also see clearly where that approach might cause a problem for certain use cases, so we can do some <strong>meaningful trade-off/benefit analysis</strong>.</li><li>We can also derive from our Logical Data Model the type of database that would be suitable for our blueprint. If the Logical Model indicates data is in the shape of the documents, we might think about <strong>document databases</strong> if the model is simple enough, for example, and so on. The same goes for other types of databases.</li></ul><h4>We Used To Do Logical Data Models</h4><p>But not anymore as far as I can see.</p><p>In one of my previous articles, I wrote about the rise and fall of the <a href="https://medium.com/dev-genius/business-rules-in-database-movement-e0167dba19b7">Business Rules Movement</a>.</p><p>In short, Business Rules Movement strongly advocated storing all business rules together with data (as opposed to scattering them across different applications and services). And that database was, of course, a relational one with all its advanced capabilities in implementing those rules.</p><p>The movement, although hyped for a brief period of time, was rejected by the industry for a variety of reasons, such as:</p><ul><li>Adoption of <strong>Agile practices</strong> and the rise of the Agile movement.</li><li><strong>Fears of Vendor-Lock</strong> In and locking into proprietary platforms (which were expensive at that time).</li><li>Perceived complexity and <strong>technical limitations</strong> of technology at that time.</li></ul><p>As a result, the industry witnessed the emergence of completely new philosophies in software design. These philosophies advocated a completely opposite approach in regard to databases and business rules to address those concerns.</p><p>In the period from around 2003 until 2010, first there was a Domain Driven Design with Eric Evans’ Blue Book, and then a little bit later, Robert C. Martin and Clean Architecture.</p><p>And since these new designs have advocated the completely opposite approach, and the rules <strong>cannot be centralized with the data anymore</strong>, we have also witnessed a new emergence of new architectural styles specifically to address these issues, such as the first Service-Oriented Architecture or SOA, and then later Microservices.</p><p>But all that meant another thing: we also need a new approach for our conceptual-level or logical modeling. And that was, of course, the <strong>Domain Modeling, </strong>which replaced (for the most part) Logical Data Modeling. From now on, we will <strong>model the domain</strong>, not the data.</p><h4>Domain Is Expressed in Code</h4><p>As I indicated earlier, the <strong>physical implementation</strong> of the Domain Model is expressed in the computer language code. <strong>Not the one used to implement the model in an appropriate database — but the one that uses database(s).</strong></p><p>There is absolutely no doubt about this fact. Here are some quotes from prominent authors that I managed to find with the help of AI:</p><p><strong>1. From Eric Evans — the source of DDD</strong></p><p>In Domain-Driven Design: Tackling Complexity in the Heart of Software (2003), Evans defines the domain model as:</p><blockquote>The heart of software is its domain model, and the design of that model shapes the software’s structure.</blockquote><blockquote>The model is expressed in the code itself.</blockquote><p><strong>2. From Vaughn Vernon — Implementing Domain-Driven Design</strong></p><p>Vernon writes:</p><blockquote>A domain model is not just an analysis artifact — it is implemented in code. The model is expressed through the language’s constructs, such as classes, methods, and modules.</blockquote><p><strong>3. From DDD Reference (Evans, 2014)</strong></p><p>The DDD Reference Model document (Evans, 2014) says:</p><blockquote>The model lives in the code, embodied in the objects and their relationships.</blockquote><p><strong>4. From Martin Fowler — Patterns of Enterprise Application Architecture</strong></p><p>Fowler describes domain models as:</p><blockquote>An object model of the domain that incorporates both behavior and data.</blockquote><p><strong>5. From Functional DDD sources</strong></p><p>Scott Wlaschin (Domain Modeling Made Functional) explains:</p><blockquote>A domain model can be expressed in functional code using types, functions, and modules to capture business concepts.</blockquote><p>As we can see, the physical part of implementation is no longer in the database — it uses the database.</p><p>And subsequently, emphasis is not on data and data modeling anymore — the domain model prioritizes behavior and meaning rather than the data.</p><p>We could say— the shift was from what to how.</p><p>Does this mean that data modeling disappeared? Of course not. But I think we could say it was given a different priority at least.</p><h4>Start with the Logical Data Model first</h4><p>I think that projects should always start with a Logical Data Model first. Here is why:</p><ul><li><strong>Data is like a diamond. They are forever.</strong> Your objects, your functional constructs if you prefer functional over object-oriented programming — they are not. Chances are that the application might be rewritten. From monolith to microservices, back to vertical slice architecture, or whatever is popular now, or even from one language to another, from object-oriented to functional to whatever, chances are that the same data will still be there.</li><li>The data model is optimized for <strong>general-purpose queries (and commands)</strong>. Unlike domain modeling, which puts emphasis on behavior early on. Behavior is the first candidate for future changes; we all know that. If we design data for ease of general-purpose behavior (queries and commands), through the process of elimination of redundancies and anomalies, we can introduce true agility in our system. But if we start with behavior first, we will optimize the data model for that behavior, and that behavior might change.</li><li><strong>Data modeling is based on math and relational theory. Domain modeling is not.</strong> In fact, there is still no real consensus on the Domain data model; for example, there are differences in the aggregate root definition.</li><li>Logical Data Model enforces a <strong>ubiquitous language</strong> to the entire team, which is one of the most important strategic goals of Domain modeling. And through the process of domain modeling, you can easily <strong>detect boundaries early on</strong> and apply them accordingly, which is also one of the strategic goals of Domain modeling.</li></ul><p>Why would someone say that DB designs are always vile and inefficient? Maybe because we stopped doing meaningful data modeling?</p><p>I hope I managed to contribute to the debate on modern software design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1fb786ebbf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Functions Optimization Labels 101]]></title>
            <link>https://medium.com/@vbilopav/postgresql-functions-optimization-labels-101-4f207f8ec635?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f207f8ec635</guid>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 05:38:42 GMT</pubDate>
            <atom:updated>2025-10-20T06:37:35.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcxYVtSP61jQ7xE1eAPAZQ.jpeg" /><figcaption>PostgreSQL Functions Imagined by Grok</figcaption></figure><p>When creating a PostgreSQL function, you can declare many different labels that affect different aspects of your function. Some of them are optimization-oriented.</p><p>Here is my 101 breakdown, because I keep forgetting them, and the best way to learn for me is to write.</p><h3>VOLATILE (the default) / STABLE / IMMUTABLE</h3><p>These are mutually exclusive.</p><ul><li>VOLATILE might change the database and return different results for the same parameters. PostgreSQL cannot optimize these at all, and this is the default behavior.</li><li>STABLE can’t change the database and will return the same results for the same parameters within the same query. And, therefore, when called more than once in the same query, PostgreSQL will still execute this function only once, and hence the optimization.</li><li>IMMUTABLE can’t change the database and will always return the same results for the same parameters. Like a mathematical function, always the same. Most aggressive optimization will probably be called once per unique set of parameters and then cached. These types of functions can be used in indexing, where others cannot.</li></ul><p>It is important to note that if function IMMUTABLE calls STABLE, it will revert to STABLE, and if STABLE calls VOLATILE, it will revert to VOLATILE automatically, regardless of what is set during the creation, so check the metadata.</p><h3>PARALLEL UNSAFE (the default), RESTRICTED, and SAFE</h3><p>Sometimes the query planner will opportunistically decide that some operation will run in parallel. This won&#39;t happen on a small set, only when the planner estimates a performance benefit. In that case you may see something like this in the planner:</p><pre>Finalize Aggregate<br>    -&gt; Gather <br>         Workers Planned: 2 <br>         Workers Launched: 2</pre><ul><li>PARALLEL UNSAFE — forces planner to ditch parallel execution. These functions change databases and perform transactions.</li><li>PARALLEL RESTRICTED — restricts parallelism to something called the parallel group leader process. These functions can do temp tables, call cursors, and prepared statements.</li><li>PARALLEL SAFE — safe to run in parallel mode without restriction, enabling the planner to do parallelism when it chooses to do so.</li></ul><h3>COST (number, default 100) / ROWS (number, default 1000)</h3><ul><li>COST: Planner needs to know how much operations cost in terms of execution performances and functions that are, indeed, operations. PostgreSQL uses its own arbitrary measurement unit</li></ul><p>With a lower cost (typically 1–10), the planner will not care about optimization when calling this function, and it will call it any time it damn well pleases. But with a higher cost (1000+), the planner will try to optimize calls for this function.</p><p>Tackling this setting should be done if the query is indeed slow.</p><ul><li>ROWS (number, default 1000)</li></ul><p>The number of rows returned is indeed another information for the planner that can be used to optimize calls and plan execution better. Therefore, this can only be used in functions that return sets (SETOF or TABLE).</p><p>A planner cannot possibly know the number of rows returned, and it will assume that it is 1000. But you can, and if you do, you can set this parameter.</p><p>The practical implications of this optimization label depend on which joining strategy planner chooses, based on the row estimate. Is it a nested loop (a sort of database internal N+1, suitable strategy for small datasets) or a hashed join (when the planner decides it will make hashes first, and then use them to compare joining keys, much more efficient for larger sets than nested join)?</p><p>In any case, this parameter only makes sense if you tend to join a function that returns sets.</p><p>And the last optimization label:</p><h3>CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT</h3><p>If you have a function that is supposed to return NULL if one of the parameters is NULL, you can just say so by labeling it RETURNS NULL ON NULL INPUT or shorter STRICT. This tells the engine to avoid calling the function in that case — simply replace it with a NULL value.</p><p>Default is CALLED ON NULL INPUT, which is normal behavior, and it doesn’t need to be stated explicitly.</p><p>This concludes my short series on PostgreSQL optimization labels (some might call them hints).</p><p>Next I’ll deal with the PostgreSQL functions security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f207f8ec635" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Business Rules In Database Movement]]></title>
            <link>https://blog.devgenius.io/business-rules-in-database-movement-e0167dba19b7?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0167dba19b7</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 10:01:01 GMT</pubDate>
            <atom:updated>2025-09-22T06:44:12.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*lZynIQzxJtEgajCU50kQ4Q.png" /></figure><blockquote><em>Those who cannot remember the past are condemned to repeat it.</em></blockquote><p>Did you know that there was an entire movement in software development, complete with its own manifesto, thought leaders, and everything, dedicated almost exclusively to putting business logic in SQL databases?</p><p>I certainly didn’t. But it did happen in the late 1990s and early 2000s.</p><p>Their core philosophy was as follows:</p><p>- Data belongs to the organization, not the application. Today, we typically refer to the Bounded Context.</p><p>- Rules and constraints should be stored and enforced in the database (or a rules engine), not scattered across individual applications. Today, the Domain Model, of course. But, in essence, just don’t repeat yourself. The database is the source of truth, and no point in having to repeat the same logic across different applications, services, and business reports.</p><p>- Rules should be declarative using natural language (not imperative or procedural) to make them easily accessible to a business non-tech audience. Today, we say the Domain Experts, but essentially, the same business people.</p><p>- We should be focused on managing business rules, not hardware/software platforms and technology. Today, we would say implementation details, but in essence, it’s the same idea.</p><p>And so on. Does this sound familiar?</p><p>You can read the full manifesto here (PDF link): <a href="https://www.businessrulesgroup.org/brmanifesto/BRManifesto.pdf">https://www.businessrulesgroup.org/brmanifesto/BRManifesto.pdf</a></p><p>An even more fascinating story is why it fizzled out and almost completely disappeared.</p><p>According to my research, in the late 90s and early 20s, this movement was hyped, and indeed it was hyped, as confirmed by a stream of conferences, forums, workshops, and thought leaders from that era. Even the research and advisory companies like Gartner promoted the idea under the catchy motto “change the rules, not the code” and labeled it as “hot”.</p><p>And then there was a boom of startups building low-code platform tools on this idea, even industry giants like Oracle and IBM tried to incorporate some of these ideas into their own low-code, rule engines. However, the dot-com crash in the early 20s and many startups building BRMS/low-code tools died.</p><p>But much more importantly than the dot-com extinction event was a significant cultural shift in the software development world that occurred shortly thereafter:</p><h3>1) The Agile Movement</h3><p>Developers preferred flexibility and speed over centralized governance. DBAs and architects pushing data-centric models often lost out to agile, app-centric teams.</p><p>In simple terms, development teams from that era had dedicated DBAs, and a dedicated DBA is supposed to implement all those rules in the databases, close to data itself, using declarative SQL:</p><pre>ALTER TABLE loans ADD CONSTRAINT CHECK NOT (status = &#39;approved&#39; AND credit_score &lt; 650);<br>ALTER TABLE users ADD CONSTRAINT UNIQUE(email);<br>ALTER TABLE users ALTER COLUMN email SET NOT NULL;</pre><p>That was not agile enough, obviously. Those rules should reside in an RDBMS or BRMS (Business Rules Management System), and you will need a specialized person for that.</p><h3>2) Vendor Lock-In</h3><p>Obviously, such centralization meant locking into proprietary platforms, which usually meant paying large tech companies a significant amount of money for an extended period, as free and open-source alternatives weren’t yet viable solutions.</p><h3>3) Perceived Complexity and Technical Limitations</h3><p>A single, centralized solution is perceived as more complex than a decentralized one, which tends to be repetitive and scattered across various services.</p><p>Furthermore, some of the emerging development practices accepted as standard today, such as source control and automated testing, weren’t exactly a priority for this new, centralized RDBMS and BRMS world managed by DBAs.</p><p>So what happened then?</p><h3>The Evolution</h3><p>The entire software development process started evolving in a different direction, one that is supposed to give more power to the individual programmer and take it away from those DBAs. Arguably, it was successful since dedicated DBAs have become a rare breed these days, at least from my perspective.</p><p>First, in the 2000s, after the dot-com crash, there was an emergence of alternative philosophies.</p><ul><li>First around in 2003 and onward, Eric Evans’ Blue Book and DDD.</li><li>And thereafter, in the 2010s and onward, Robert C. Martin and Clean Architecture.</li></ul><p>Both of these philosophies, which are now widely accepted, argue that business rules don’t belong to a centralized data and business rules engines like RDBMS and similar — but rather to the domain model or the architecture core, respectively.</p><p>They argue that RDBMS and similar systems are and should be concerned only with storing and retrieving data, and the decision engine should be moved back to the application.</p><p>This meant reintroducing business rules back into the application layer, as the industry shifted toward 3-tier architectures with business logic in the middle tier, rather than in the database.</p><p>But this also meant that those same rules will inevitably have to be repeated across various applications, services, and reports, which is, of course, suboptimal, to say the least. To address this issue, we saw:</p><ul><li>First, the emergence of Service-Oriented Architecture or SOA in the mid-2000s. The idea was to centralize logic in services where programmers have control.</li><li>And then the emergence of Microservices in the 2010s and onward, with rules scattered across many different specialized services.</li></ul><h3>Where Are We Today</h3><p>Today, RDMBS are here to stay, and any component developer (at least the backend developer) should also be a DBA.</p><p>After 20+ years, perhaps it is time to revisit some of the arguments that led the industry to reject the Business Rules Movement in the late 90s and early 2000s.</p><h3>Vendor Lock In:</h3><p>PostgreSQL is free, open-source, portable, and has a massive ecosystem of support. You’re no longer tied to Oracle licenses just to run stored procedures or triggers.</p><h3>Switching Scaling Issues</h3><p>DDD/CA proponents see relying on a database as dangerous: switching DBs or scaling across multiple persistence stores becomes nearly impossible. Scaling relational databases horizontally was <em>hard</em> and proprietary.</p><p>But today, there are also numerous distributed and extremely scalable Postgres-compatible free and open source variants as well, such as Citus, Timescale, etc. Scaling isn’t much of a killer anymore. It is challenging, but then again, scaling will always be a challenge.</p><p>And with PostgreSQL and its variants, which offer advanced polyglot capabilities covering well over 90 percent of needs, is there still a need to switch? Portability is much less relevant today.</p><h3>Separation of Concerns</h3><p>This was a misunderstanding from the beginning; SQL rules are domain semantics, and SQL is not storage code by any means. Postgres doesn’t care <em>where</em> it runs; it enforces rules consistently.</p><h3>Testing &amp; Tooling</h3><p>Today, testing DB rules is very straightforward using rollbac-tests, migrations in containers, fixtures, and tools like pgTAP.</p><p>It is a weak spot compared to modern app languages with powerful IDEs, refactoring capabilities, and type systems, but it is very much doable and manageable.</p><p>The real gap is developer culture: fewer devs are fluent in SQL as a <em>primary modeling language</em>.</p><h3>Big Picture</h3><p>The database-centric philosophy is much more defensible in 2025 than it was in 2005. RDMBS and SQL are here to stay, and they are evolving and getting better.</p><p>The main “barrier” now is cultural: developers are trained to think in code-first terms, not data-first.</p><p>However, we do live in 2025, not in 2005.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0167dba19b7" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/business-rules-in-database-movement-e0167dba19b7">Business Rules In Database Movement</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Rely on PostgreSQL Functions for Everything: Pros, Cons, and Best Practice — Article Review]]></title>
            <link>https://medium.com/@vbilopav/why-i-rely-on-postgresql-functions-for-everything-pros-cons-and-best-practice-article-review-987eba321234?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/987eba321234</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 10:59:16 GMT</pubDate>
            <atom:updated>2025-08-20T10:59:16.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I Rely on PostgreSQL Functions for Everything: Pros, Cons, and Best Practice — Article Review</h3><p>Ok, I’m going to do a review of this article, which is the subject of my long-term interest. You can find the original article on Medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*WMN0ry5PtGLonazo1uYVvg.jpeg" /></figure><blockquote><em>PostgreSQL functions are powerful tools that allow developers to encapsulate database logic within the database itself.</em></blockquote><p>It’s actually so-called business logic. A minor nitpicking, but words matter, especially for people obsessed with keeping business logic out of the database.</p><h3>Benefits</h3><blockquote><em>Centralized Logic: Keeping logic within the database ensures that all application instances interact with the data consistently. This is particularly beneficial in environments where multiple applications or instances of an application access the same database.</em></blockquote><p>Yep, your database can serve many different applications and services, and it often does.</p><p>What are you going to do, write the same queries and commands with the same logic all over again each time? Or create a service that other services call into and end up with unintentional Microservices?</p><p>Madness.</p><blockquote><em>Improved Performance: By pushing logic down to the database layer, you can reduce the need for data to travel back and forth between the database and application. This minimizes latency and can significantly improve the performance of data-intensive operations.</em></blockquote><p>Yes, no more unnecessary ping-pong between client and server, you just need one call, and that is it. You are going to run at least one query, anyhow.</p><blockquote><em>Atomic Operations: Functions in PostgreSQL can be executed as a single transaction, ensuring that operations are atomic and consistent. This is particularly useful when making changes that involve multiple tables or require complex processing.</em></blockquote><blockquote><em>Ease of Maintenance: When business logic resides in functions, it becomes easier to update and manage without having to redeploy the entire application. For example, fixing a bug in a function or optimizing a query can be done directly in the database, with immediate effect across all instances of the application.</em></blockquote><p>One atomic replace command (that would be alter on other systems) executed in milliseconds with zero downtime can solve so many problems. And it is incredibly satisfying and easy.</p><blockquote><em>Security: Functions can be used to encapsulate sensitive operations, exposing only the necessary interfaces to application developers. This can reduce the risk of SQL injection attacks and unauthorized data access.</em></blockquote><p>This is one of the most powerful and sadly largely unutilized database features.</p><blockquote><em>Reduced Application Complexity: By moving complex logic into functions, the application code can remain cleaner and simpler. This separation of concerns allows application developers to focus on building features rather than managing complex SQL queries within the application.</em></blockquote><p>As a matter of fact, when applying this approach, this is what happens:</p><ul><li>You are moving code from running in the application to running in your PostgreSQL database.</li><li>As a logical consequence, your application code is getting smaller and more predictable.</li><li>Applying this approach consistently will lead to the application code acting like an automatic middleware between the API endpoint and the database, leading to inevitable automation.</li><li>The role of application code will remain largely on real infrastructure, like security subsystems for authentication and authorization, external services communication, e-mails, caching, coordination, etc.</li><li>This all can be automated to extent. Since now, our application layer is actually infrastructure, not the database as it was thought traditionally (e.g., Clean Architecture, etc).</li></ul><p>It is important to note that business logic isn’t actually reduced; it just moved from one place to another. The law of conservation of energy states that energy cannot be created or destroyed, but can only be transformed from one form to another. The same goes for business logic complexity.</p><blockquote><em>Reusable Code: Functions can be reused across different parts of an application or even by different applications that access the same database. This reduces code duplication and ensures consistency in data processing.</em></blockquote><p>I already commented on this. With this approach, different applications and services can and will access the same database, and the same logic will now apply in a consistent manner.</p><p>These issues can be mitigated by building a central service that will serve all other applications and services in a consistent manner. Which is not a bad solution, but unlike database functions, it needs to be rebuilt and redeployed.</p><p>Another solution would be to build a shared library to be used in different applications and schemas, but then good luck with proper versioning and supporting all those technologies.</p><blockquote><em>Version Control and Rollback: With tools like Flyway or Liquibase, functions can be version-controlled and rolled back if needed. This allows for better management of database changes and helps maintain synchronization between database and application versions.</em></blockquote><p>This is not so much a benefit but rather a challenge in organizing your new code.</p><p>As a matter of fact, you really don’t need a migration system like Flyway to maintain your PostgreSQL functions as part of your code. Here is what you can do, for example:</p><ul><li>Create a new project folder for those functions and procedures. You can even create sub-directories, per schema, or any organization you prefer.</li><li>Put every function or procedure in a separate SQL file with the same name as “<strong>create or replace function</strong>” statement.</li><li>Configure your psql tool to execute every file in that project folder on command.</li><li>And since that is a project directory, it will be version-controlled as any other would.</li><li>You can even add that command to your build process to make sure that your server is always up to date with the latest code.</li></ul><p>If you apply this last point (add psql run command to your build pipeline), a funny thing can happen. You can have at least basic static type checking, at least for the pure SQL functions, since they are evaluated against the schema (unlike PL/pgSQL), especially if you embrace the BEGIN ATOMIC syntax.</p><p>What do I mean by that?</p><p>Simple SQL function like this, for example:</p><pre>create or replace function todo.get_item_title(<br>    _id bigint<br>)<br>returns text<br>language sql<br>as <br>$$<br>select title from todo.my_items where id = _id<br>$$;</pre><p>Will fail when we try to do CREATE OR REPLACE, that is, on creation time — if the table (or some of the fields) doesn’t exist:</p><pre>relation &quot;todo.my_items&quot; does not exist<br>LINE 8: select title from todo.my_items where id = _id<br>^</pre><p>And with BEGIN ATOMIC syntax, we can still use a pure SQL function that will give us this static type checking, even with multiple SQL statements, for example:</p><pre>create or replace function todo.get_item_title(<br>    _id bigint,<br>    _user_id bigint<br>)<br>returns text<br>language sql<br>begin atomic<br><br>-- log action<br>insert into todo.logs (user_id, action)<br>values (_user_id, &#39;get_item_title&#39;);<br><br>-- retrive title<br>select title from todo.items where id = id;<br>end;</pre><p>No need for procedural PL/pgSQL functions that will treat any code as a string that will be evaluated on invocation, which means delayed type checking. In addition to that, pure SQL functions can be much better optimized, and BEGIN ATOMIC syntax has better error reporting.</p><p>In any case, a simple psql command (in a shell script) can run all CREATE OR REPLACE function files in your project directory. You can have schema migrations in a separate system, anyway you prefer.</p><p>Btw. This is something that migration systems like Flyway call repeatable migrations. The only difference is that Flyway will execute a repeatable migration file if it finds the content hash to be different from the one recorded in the database from the last run, and effectively runs only files that are changed from the last migration. But this is a minor pick, and this too can be added to the shell script with the psql command.</p><blockquote><em>Schema Evolution Management: When database schema changes are wrapped in functions, it becomes easier to manage updates. Instead of deploying multiple application versions to handle schema changes, you can simply update the function while keeping the application code untouched.</em></blockquote><p>This is a major and underrated benefit of this approach.</p><p>What it wants to say is that database functions, used in this way, can act as a database layer over your physical schema.</p><p>Assuming your function interface doesn’t change, it hides the physical schema below, allowing for changes and evolution independently. In practice, that means that you can change your tables and your physical schema all you want, normalize, denormalize, do whatever you have to do with your tables, as long as the function interface is unchanged — you don’t need to rebuild or redeploy your application.</p><p>And that physical schema can then change without breaking or redeploying the application. Normalize, denormalize, do whatever you need to do, and no redeploy.</p><p>Ok, let’s dive now into the other side.</p><h3>Challenges</h3><blockquote><em>Performance Overhead: Functions, especially those written in procedural languages like PL/pgSQL, can introduce performance overhead if not optimized correctly. Poorly written functions can lead to inefficient execution plans and slow performance.</em></blockquote><p>The author forgot to mention that the function doesn’t have to be PL/pgSQL. It can be pure SQL, without procedural extension overhead.</p><p>But it can also be JavaScript, Python, or C# (coming soon), but that doesn’t matter.</p><p>Performance challenges are essentially the same as with the traditional approach, except in this environment, there is no ping-pong with the server.</p><p>You can have optimized and uptimized queries and commands in functions or issued by your application code; it really doesn’t matter. The only difference here is that there is no more unnecessary ping-pong back and forth between the database and the application. Not even by accident.</p><p>And in addition to this, pure SQL functions are much better optimized, parsed, and an execution plan is created on creation, rather than invocation. I am surprised how few people use this type of function.</p><blockquote><em>Debugging Difficulties: Debugging functions can be more challenging than debugging application code. Tools for debugging database functions are not as robust or user-friendly as those available for modern programming languages.</em></blockquote><p>There are no debugging difficulties, to be honest. This is a common myth. Although the approach is a bit different, I’ll explain:</p><p>First, pure SQL can not be debugged since it is declarative. The same way you can’t debug HTML or CSS. That doesn’t make sense. That is true for the traditional approach as well. For example, you may have a traditional system with ORM, and the best you can do is extract the exact SQL being generated, and then you can just, you know, look at it. You can examine, but you can’t debug declarative SQL.</p><p>Of course, not in the traditional sense, large and complex SQL statements are debugged by executing part by part, thinking, making hypotheses, and then testing those hypotheses, but that is a subject for a different article.</p><p>On the other hand, procedural extension functions like PL/pgSQL can be debugged, even with traditional tools. For example, the pgAdmin administration tool has a built-in PL/pgSQL debugger, and JetBrains offers a PL/pgSQL debugger extension for their line of development tools. But there are a couple of gotchas:</p><ul><li>First, it needs to be enabled on a server, which is not by default. Requires reconfiguration.</li><li>Secondly, I would not allow that anywhere but on local instances. We don’t want to stop the entire server so that little Timmy can examine the variable. There are better ways.</li></ul><p>A better way to debug PL/pgSQL functions (or procedures) is to add appropriate RAISE statements and just print out the values you want to examine. It is used in the same way as console.log is used for debugging in JavaScript.</p><pre>raise info &#39;Retrieving title for item with ID: %&#39;, _id;</pre><p>There are gotchas here, too:</p><p>For example, if you run a function with this RAISE statement in any of the client tools, you will see this printed out. However, if you call this function from the application, you won’t see anything, and you won’t even find this message in PostgreSQL logs.</p><p>PostgreSQL by default logs only WARNING and ERROR levels — it ignores INFO level from this example. This can be changed in settings, but it is not advisable since your PostgreSQL logs would start growing in order of magnitude.</p><p>Instead, this INFO-level event is sent to a client connection to handle appropriately. This means, depending on the application library you are using, your connection object will have an event handler, and that event handler needs to be handled as you see fit (write to application logs, usually).</p><p>There is also one more advanced debugging technique that can help with pure SQL debugging.</p><p>There is a special data type available only for PL/pgSQL functions, and it is called record. We can create a function that simply prints out the record from the argument:</p><pre>create or replace function public.print_record(<br>    _record record<br>)<br>returns void<br>language plpgsql<br>as<br>$$<br>begin<br>    raise info &#39;%&#39;, _record;<br>end;<br>$$;</pre><p>Now, imagine you have a complex SQL with dozens of nested subqueries, window functions, CTEs, advanced grouping, etc., and you need to examine a subquery on the sixth level of depth to figure out what is going on. Now, with this helper function, you can simply add one extra field to your subquery:</p><pre>select <br>    id, <br>    title, <br>    print_record(todo.items.*) -- print out the conetext of the record<br>from todo.items;</pre><p>But, use this with caution; RAISE INFO solves 99% of the debugging needs.</p><p>Oh, wait, but there is more!</p><p>As I mentioned, PostgreSQL functions can also be written using language extensions such as JavaScript, Python, C#, GO, and many others. There is nothing stopping you from simply copying and pasting that code from the function with the language extension into your debuggable environment, calling it, and debugging it there as you normally would.</p><p>So, I would say yes, PostgreSQL functions can be debugged. And it’s not a big deal.</p><p>What else do we have …</p><blockquote><em>Potential for Spaghetti Logic: Without careful design, functions can lead to complex, interconnected logic that’s difficult to maintain and understand. Over-reliance on functions without proper documentation can turn the database into a black box.</em></blockquote><p>Isn’t that the issue with everything? I don’t see how this PostgreSQL function is specific? Hint: Use schemas for better organization, use subfolders and directories for better organization, have some naming convention, etc. You know, the usual…</p><blockquote><em>Version Control and Deployment Complexity: While version control tools like Flyway can help manage function updates, coordinating changes between application code and database functions requires careful planning to avoid breaking changes.</em></blockquote><p>We already discussed this, and not only is it not complex, but it has its own benefits.</p><blockquote><em>Lock-In to Specific Database Features: Using functions and advanced SQL features can create a tight coupling to PostgreSQL, making it harder to migrate to another database system in the future.</em></blockquote><p>What else would you need except PostgreSQL?</p><h3>Final Words</h3><p>This was supposed to be my morning LinkedIn post, but it got out of hand. I hope you enjoyed it. If you have any questions or doubts, feel free to ask in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=987eba321234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture Book Review And Analysis — THE DATABASE IS A DETAIL]]></title>
            <link>https://medium.com/@vbilopav/clean-architecture-book-review-and-analysis-the-database-is-a-detail-eda7424e8ce2?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda7424e8ce2</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 07:42:48 GMT</pubDate>
            <atom:updated>2026-07-28T07:06:27.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clean Architecture Book Review And Analysis — THE DATABASE IS A DETAIL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*f2DOldJ6mAiQx3GX1E1SZQ.jpeg" /></figure><p>This is my analysis and a detailed review of the book Clean Architecture: A Craftsman’s Guide to Software Structure and Design (Robert C. Martin Series), 1st edition (September 10, 2017), only one chapter of my particular interest: chapter 30, THE DATABASE IS A DETAIL. Originally published as a series of posts on my LinkedIn page.</p><h3>Part 1: Intro</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*bmggn1ptR8g7kfnovjmI8w.jpeg" /></figure><p>The claim is that the database is a non-entity when it comes to architecture. Basically, it is as important as the design of a doorknob to the architecture of your home. And you are a bad software designer if you “allow low-level mechanisms to pollute the system architecture.”.</p><p>Nothing could be further from the truth, in my opinion.</p><p>Which database to use in your system, and he is talking here about that, not about the data modeling — is one of the most important decisions you can make that will have long-term consequences.</p><p>There are so many considerations that come into this decision that it is even hard to count them all…</p><p>- Are we going to have analytical processing needs? We may have to look at specialized OLAP databases like Snowflake or Clickhouse,</p><p>- Are we going to have a real-time transaction or at least transaction-heavy processing needs? We may have to look at specialized OLTP databases like CockroachDB or this new DynamoDB.</p><p>- Are general-purpose databases that can do both well enough, like PostgreSQL or SQL Server or MySQL, good enough for our requirements?</p><p>- Some of those can do one thing better, and another thing just basics; how does that match our requirements?</p><p>- Can we use some kind of combination and get the best of all worlds? How much complexity penalty will we have to pay?</p><p>- What about graph and tree processing? Do we have those requirements, and if we do, how much do we estimate the amount of hierarchical data we will need to process? Maybe we can think about specialized Graph databases, too. Those can process an insane amount of hierarchical data, but on the other hand, the general-purpose databases can handle smaller amounts just fine.</p><p>- Do we have search features, and if we do, they will do a search over what type and amount of data? There are, of course, specialized databases for that kind of thing.</p><p>- What about scaling? How much scaling might we need in the future? Is it a read-only request scaling, a write-only request scaling, or both? It’s different for different databases, and wrong decisions may heavily influence this…</p><p>And on and on and on.</p><p>Doorknob, you say?</p><h3>Part 2: RELATIONAL DATABASES</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*mEkFI1kbqKd8ml5OFJCJzw.jpeg" /></figure><p>In this part, Martin discusses Relational Databases to prove his point that Databases and in particular Relational Databases, because I don’t see him even mention any other kind — are, in fact, a detail.</p><p>The problem in this chapter is that Edgar Codd did not define the principles of relational databases — he defined the principles of the relational model.</p><p>It may sound like a small nitpick, but it’s an extremely important distinction: The relational model has nothing to do with technology. It is neither the data storage nor the access technology of any kind.</p><p>It’s just a relational model of data, which later became the theoretical foundation for relational databases. He did not define the principles of relational databases — which involve things, for example, indexing, concurrency control, etc.</p><p>It’s based on mathematics and mathematical theory — not technology. That’s why it is so elegant and robust, as he points out. It involves things like set theory, relational calculus, and relational algebra. The theorems and proofs, and hence the elegance.</p><p>So, if you start with the wrong premise, what will your conclusions be?</p><p>Later, he goes on to say how it is an architectural error to pass the relational data (rows and tables) into your application because “it couples use cases, business rules, and in some cases even the UI to the relational structure of the data”.</p><p>I am truly failing to understand this. Relational data has tuples (one or many rows) and attributes (what it is, name, email, amount, type, whatever).</p><p>Why would it be an error to use your data that is structured for your use case? If my users have data about, let’s say, invoices, they would want to see particular invoices or invoices in a row or multiple rows (tuples), and they would like to know the amount, the date, or the customer, etc.</p><p>Is it an error to use your own data?</p><p>Unfortunately, he doesn’t explain, and what would be the alternative? Maybe in the next part …</p><h3>Part 3: WHY ARE DATABASE SYSTEMS SO PREVALENT?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*eysPer5SQSUPELR_nvkuZg.jpeg" /></figure><p>We start with a flawed premise: “Databases Only Exist Because of Disks”, and disks are slow, which then implies that with the disappearance of disks, databases will become irrelevant.</p><p>That is outright not true, there is no other way to put it.</p><p>They are not *just* mitigating disk slowness that they are — but a bunch of other things too (data integrity, transactional correctness, concurrency control, security, optimizations, etc) — but primarily, they act as a reliable source of truth for your system.</p><p>Memory is volatile by nature, it is gone forever when the process exits, you can’t rely on memory. Furthermore, different parts of the application (or applications) usually need a different view of the same data. Therefore, there is a need for a single source of truth structured in an accessible and predictable way that eliminates redundancies and anomalies.</p><p>Those things have nothing to do with *disks*.</p><p>Quote: “To mitigate the time delay imposed by disks, you need indexes”.</p><p>Let’s say we have built a memory structure like a linked list or a hash table that holds memory records or object instances with properties and all about Invoices. And we have a lot of them, a gigabyte or two. And let’s say we need to find all invoices with an amount equal to 100. Iteration takes too long to check every item in that list or hash table. What can we do?</p><p>I know, maybe we can build a balanced balanced tree memory structure, what a great idea. This structure would help us avoid all those costly iterations that run forever, and it is flexible and versatile. We can call it just B-Tree in short… And how do you think those indexes work?</p><p>I’m not trying to be facetious too much here, but this is a fundamental misunderstanding of how indexes work and why they exist — right here.</p><p>If we would also add a concurrency control so that more threads and processes can access our search tree, and also some mechanism to transfer to and retrieve from non-volatile memory (aka storage), and perhaps expose all that API through some kind of language … you see where I’m going with this?</p><p>Indexes have nothing to do with no “disks”. There are many kinds of indexes, and they all implement different structures.</p><p>It seems that it has some kind of beef or quarrel with relational databases in particular. Yes, file systems are document-based, but he doesn’t even mention document databases or “docubases” in short. Those exist, too, and there is a big use case for those, too. And not to mention that relational databases can store, retrieve, and index documents efficiently.</p><h3>Part 5: DETAILS and BUT WHAT ABOUT PERFORMANCE?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*5ZZUTsujyv6hWuFXHy_shw.jpeg" /></figure><p>In these two parts, Martin is basically summarizing his false premises from the previous parts of this chapter:</p><p>- A database is “just a mechanism to move the data back and forth between the surface of the disk and the RAM”.<br>- “Nothing more than big buckets of bits we store our data on a long-term basis.”</p><p>For him, databases are indistinguishable from storage devices.</p><p>And, when you start from a wrong premises like these, inevitably, the conclusion will also be wrong:</p><p>- “We should not care about the form that the data takes while it<br>is on the surface of a rotating magnetic disk.” (from an architectural point of view).</p><p>That is certainly true. And that is why, among other things — we use databases. Their engines are taking care of that issue for us, so we don’t have to (from an architectural point of view).</p><p>— “but when it comes to data storage, it’s a concern that can be entirely encapsulated and separated from the business rules.”</p><p>Here is the false assumption again: the database is not data storage, and it takes care of the storage concern for us.</p><p>What are the implications of this fact (from an architectural point of view)?</p><p>Virtually all databases regularly collect statistics about your data, from shape and volume to everything and anything related. Why do they need so many statistics? When it receives a request for the data (in the form of a query or otherwise) — it will use those same statistics to find the optimal algorithm and the most appropriate data structure for the stated intent with that data.</p><p>Think about it for a second: it will find the most suitable algorithm (accompanied by an appropriate data structure) for your declared intent, and then execute it for you.</p><p>So, what does it mean in practice? Not only that storage is abstracted, but so are the algorithms and data structures. To an extent, of course, it’s a leaky abstraction, but abstraction nevertheless.</p><p>It means that operators are relieved from lower-level concerns such as storage devices, algorithms, and data structures. It means that tools and languages like SQL and others that we use to declare our intentions with the data are at a higher-level generation of languages and tools. While Martin wrongfully counts them as “low-level data access mechanisms.”</p><p>And most importantly, if you are relieved from all of these things: storage, memory, algorithms, data structures, and so on, what is it that is left?</p><p>That’s right, the business rules. The business logic if you will. You know, the things your clients and users actually care about.</p><h3>Part 6: ANECDOTE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*x2gVo56L9KXPXkKQxxcmcQ.jpeg" /></figure><p>In my opinion, anecdotes can be a very powerful persuasion technique. Nothing like a good anecdote to prove I am right and you are wrong, although it is still a logical fallacy.</p><p>Almost everyone in his team (clients, marketing, and hardware engineers) wanted him to use RDBMS, and he fought back. He wanted to keep the data in memory and then save and load it to and from raw files, instead of an RDBMS.</p><p>His hardware engineer, quote: “held meetings behind my back with the executives” and, quote, “clained that RDBMS was somehow more reliable than the<br>random access files that we were using”, implying that use of the database and RDBMS in particular doesn’t provide any kind of reliability compared to the file system.</p><p>But here is the problem: his hardware engineer was right.</p><p>Databases are built to ensure durability, atomicity, and consistency, even under the worst of conditions. That means that you can be left with corrupted or incomplete data when saving your linked lists to files. On the other hand, databases will use a myriad of different incredibly sophisticated techniques like Write Ahead Log, Checkpoints, different recovery protocols, snapshots, 2-Phase Commits, Crash Recovery, etc., all just to avoid partial writes and corruption of data.</p><p>And if you use a file system instead of the database, you would have to re-implement those features yourself just to achieve the same level of reliability.</p><p>Those techniques and advanced algorithms were developed and perfected over many decades in a collaborative effort of a huge number of very talented people. You would have to do a lifetime of programming efforts to achieve even a comparable level of reliability, and that is even questionable.</p><blockquote>I stuck to my engineering principles in the face of incredible ignorance.</blockquote><p>No, actually, you refused to admit you are wrong.</p><p>I would like to take a step back for a second and give Martin the benefit of the doubt:</p><p>- Marketing should not be involved in this kind of decision.<br>- Modern Software Development Marketing is absolutely atrocious. It consistently corrupts the entire industry. All for money.</p><p>That doesn’t mean we shouldn’t be open to rational arguments.</p><p>And in the end, Martin quit and became a consultant.</p><p>But now comes the funny part — so did I. And like Martin, I too have a similar anecdote.</p><p>The only difference is that I was on the other side of the argument. But I lost too (maybe thanks to this book?) and became a consultant.</p><h3>Part 7: CONCLUSION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*g7llCyH_vF5Z8Db_CEvcdw.jpeg" /></figure><p>There’s not much to be said about the conclusion part, it just repeats the same wrong assumptions and the same wrong conclusion from the previous parts.</p><p>A lie that is repeated many times doesn’t become a truth, no more than a database becomes a “storage device”. But it does create an illusion of truth.</p><p>So I asked my new AI friend to summarize — how much of an impact this book has had on business software development and architecture. Here are his estimates:</p><blockquote>— AI CONTENT — <br>Rough Estimate</blockquote><blockquote>Explicit Adoption: Approximately 20–30% of modern business software projects (especially in enterprise, microservices, or complex domains) explicitly follow Clean Architecture’s structure, consciously applying its layers and rules.</blockquote><blockquote>Implicit/Partial Adoption: Around 70–80% of projects incorporate at least some of its principles (e.g., dependency inversion, separation of concerns), often through frameworks, patterns, or cultural alignment with maintainable design.</blockquote><blockquote>Non-Adoption: The remaining 20–30% (e.g., prototypes, small apps, or highly specialized systems like AI or serverless) may ignore Clean Architecture in favor of simpler or domain-specific approaches.</blockquote><blockquote>Conclusion</blockquote><blockquote>Clean Architecture has a substantial but not universal impact on modern business software. Its principles are deeply embedded in professional development practices, particularly in enterprise and microservices contexts, with 70–80% of projects reflecting its ideas to some degree. Explicit adoption is lower, around 20–30%, due to project constraints, team preferences, or alternative paradigms. Its influence is strongest where maintainability, scalability, and testability are priorities, but its rigidity can make it less prevalent in rapid-development or niche domains. For a definitive picture, more industry-wide data (e.g., surveys of development teams) would be needed, but current trends suggest it’s a cornerstone of modern software architecture.</blockquote><p>Approximately 20–30% of modern business software projects explicitly follow Clean Architecture!?</p><p>And you thought that the Vibe Coding was bad?</p><p>Now, maybe not all of those involved in these projects have a lack of understanding about database fundamentals. But in that case, they have a lack of understanding of what the architecture book they follow is trying to teach.</p><p>I don’t know how many times I have encountered digital content with pictures of these famous concentric circles representing Clean Architecture with no database system in sight, be it in blogs, posts, or any type of content. All virtue signaling, zero understanding.</p><p>In the end, let me rephrase his quote: “If you think good architecture is expensive, try the Clean Architecture.”.</p><p>THE END</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda7424e8ce2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Business Logic Belongs to Database]]></title>
            <link>https://medium.com/@vbilopav/business-logic-belongs-to-database-97fc03118fcf?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/97fc03118fcf</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 11:20:25 GMT</pubDate>
            <atom:updated>2024-11-22T11:20:25.456Z</atom:updated>
            <content:encoded><![CDATA[<p>I don’t understand why people in software development discussions act like doing logic outside the database is the default position.</p><p>It is not.</p><p>Some are even having severe cognitive dissonance reactions to the mere mention that the database can contain some logic.</p><p>I’m getting brain cancer from this endless discussion, so let me try to end this once and for all:</p><p>Not only that, but the database should contain business logic by default — <strong>the database is your application</strong>.</p><p><strong>Database clients are your application details</strong> or application clients — they have a much shorter lifespan than your database, which will live as long as the data lives.</p><p>Yes, you can migrate the data from one database system to another, but that is very challenging and hard — compared to changes in the UI, reporting engine, web app, mobile… or what have you.</p><p>What are you going to do? Will you rewrite business logic every time you change the application?</p><p>One database can serve many applications and many different application clients. You can have multiple applications, such as desktop, web, different services, reporting systems, etc.</p><p>And they are being constantly rewritten as new tech comes along.</p><p>What are you going to do, write the same business logic all over again for every new application client that hooks up to your database?</p><p>Well, maybe, you’re charging per hour, I don’t know.</p><p>Furthermore, your application will be way faster if the logic is executed in the database. Not only are network operations dramatically reduced, but you can execute computes while doing table or index scans.</p><p>What, you are going to download the entire dataset into client memory just to be able to compute something that you could do in the first place?</p><p>And you’re going to do that for every existing and every new application client that comes along?</p><p>Maybe you are sponsored by the cloud vendors; they like slow apps and are making good money from them.</p><p>Some business logic is even impossible to put on the application client, like constraint logic, uniqueness, and so on.</p><p>What, you’re going to scatter logic between different systems in the name of maintainability? And no, that is not “data logic”; that’s just coping. Either it is logic, or it’s not logic at all. It determines how your data is stored, accessed, and changed according to certain rules that we call business logic.</p><p>Then, when you do decide that you wish to download your data to an application client to apply some business logic, you have to use imperative language and approach for the most part. This means iterating through the dataset, telling the computer how to transform the data, and writing algorithms.</p><p>Don’t you wish to use a declarative approach? Just tell what instead of how, and let the computer figure out that for themselves. I mean, it’s a hell of less typing.</p><p>And yes, you can put it in a source code, even if you put logic in the database. And yes, you can write tests, and no, they’re not slow, and yes you can even go TDD or BDD and yes, you can integrate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97fc03118fcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Always Use PostgreSQL Functions For Everything]]></title>
            <link>https://blog.devgenius.io/why-i-always-use-postgresql-functions-for-everything-aa501a33842a?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa501a33842a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 11:47:54 GMT</pubDate>
            <atom:updated>2024-08-31T10:59:31.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiP7Nf_LRPhES0yaEABuAA.jpeg" /><figcaption>Photo VB, Vicinity of Makarska, Croatia</figcaption></figure><p>As a general rule, every single command or query for the application use — I always wrap up in a <a href="https://www.postgresql.org/docs/current/sql-createfunction.html">PostgreSQL user-defined function</a>!</p><p>Sometimes, it’s the <a href="https://www.postgresql.org/docs/current/sql-createprocedure.html">PostgreSQL stored procedures</a> when I need fine-grained transaction handling, for example, but that is really rare. It’s mostly PostgreSQL user-defined functions for the majority of cases.</p><p>To use the terminology from the OOP world — they are my <strong>data contracts.</strong></p><p><strong>The formal agreements for data exchange</strong> between the PostgreSQL and the application instances, to be precise.</p><p>In particular:</p><ul><li><strong>Function (or procedure) parameters — are my input data contracts.</strong></li><li><strong>Function results (or lack thereof) — are my output data contracts.</strong></li></ul><p><strong>Functions encapsulate commands, queries, and table access</strong>. Those are private parts. Data contracts are public. They do not change unless the application changes, too.</p><p>Let me give you a real-world example for a better understanding.</p><p>Suppose we have this big table with lots of data:</p><pre>create table device_measurements (<br>    id bigint not null generated always as identity primary key,<br>    device_id int not null references devices(device_id),<br>    timestamp timestamp not null,<br>    value numeric not null<br>);</pre><p>Now, this table is a standard table in a legacy system created by the ORM tool. Therefore, it has a standard, auto-generated integer primary key (although not very useful, but there it is).</p><p>There are a couple of standard indexes, like the one on the <strong>device_id</strong> and one on the <strong>timestamp</strong>.</p><p>Now, this legacy application, for purposes of analytical reporting, is creating a <strong>huge amount of exact same queries with different parameters</strong>:</p><pre>select &quot;timestamp&quot;, device_id, value<br>from device_measurements <br>where device_id = $1<br>order by id desc</pre><p>The first thing to say is that when the application runs a large number of the same queries with different parameters, that’s a <strong>big code smell</strong> and is highly likely an issue that needs to be refactored and rewritten.</p><p>It is very likely that those parameter values are fetched from a different query, and now we’re doing another query for each result of the first one. Long story short, it’s very likely that we are looking at the <strong>N+1 antipattern </strong>at work, which makes the entire application slow and sluggish resource hog.</p><p>However, resolving those N+1 antipatterns requires very careful and thoughtful analysis first and foremost, and then an entire rewrite of that entire portion, <strong>which is a commodity not every legacy system can afford.</strong></p><p>N+1 makes the application sluggish at best (it crashes at worst), but sluggish is still usable.</p><p>So, the first step is to understand what we want to get with that query. What is thy intention? And after we figure that out, we can extract input and output data contracts. Let’s see:</p><ul><li>The intention is to return the latest device measurement. The one record that was last to be inserted.</li><li>Input data contracts are just the device_id number.</li><li>An output data contract is a single record that returns the timestamp, device ID, and value.</li></ul><p>That gives us the following function:</p><pre>create or replace function get_latest_device_measurement(<br>    _device_id integer<br>) <br>returns table (<br>    &quot;timestamp&quot; timestamp,<br>    device_id integer,<br>    value double precision<br>) <br>security definer <br>language sql as <br>$$<br>select <br>    &quot;timestamp&quot;, device_id, value <br>from <br>    device_measurements<br>where<br>    device_id = _device_id<br>order by id desc<br>limit 1;<br>$$;</pre><ul><li>The name clearly describes the intention of our function. What are we getting out?</li><li>Input parameters and the return type define our data contracts.</li></ul><p>And now, we can replace that query in our legacy application with a function call like this:</p><pre>select &quot;timestamp&quot;, device_id, value from get_latest_device_measurement($1)</pre><p>This makes our query and data access readable and maintainable. It’s basically — the <strong>Clean Code version of the SQL</strong>.</p><p><strong>Uncle Bob would be proud.</strong></p><p>Now, performance-wise, we didn’t do anything, really. Yet. But we did make our application <strong>infinitely more maintainable</strong>. Continue reading.</p><p>As time goes on, data grows. Who could have predicted that?</p><p>Jokes aside, for many different reasons that I will not get into — the decision was made to migrate the system to Timescale DB and to partition this big table on the timestamp field.</p><p>Timescale partitions don’t allow having a unique index on a field that is not used for partitioning, which is, in our case, a timestamp field.</p><p>That means that the primary key on the ID field has to be dropped - in order to build partitions correctly.</p><p>Hell, it wasn’t that useful anyway; it’s there only because of the ORM.</p><p>Except, of course, when it comes to our “get latest measurement” function. Dropping that primary key index made our reporting analytics unusable because this function from above relied on the primary key index.</p><p>Luckily for us, these types of functions can be changed (altered) in an atomic transaction, which doesn’t require any downtime or any application change or redeployment:</p><pre>create or replace function get_latest_device_measurement(<br>    _device_id integer<br>) <br>returns table (<br>    &quot;timestamp&quot; timestamp,<br>    device_id integer,<br>    value double precision<br>) <br>security definer <br>language sql as <br>$$<br>select <br>    &quot;timestamp&quot;, device_id, value <br>from <br>    device_measurements<br>where<br>    device_id = _device_id<br>order by &quot;timestamp&quot; desc<br>limit 1;<br>$$;</pre><p>Now, that worked fine; the right index was used, we had a few partitions, and the report was usable again.</p><p>However, as time goes on, data grows. Who could have predicted that again?</p><p>As it turns out, although this version used indices, it had to do an index scan for each partition separately. As the number of partitions grew, our reporting analytics became unusable again. We obviously need a slightly different strategy.</p><p>Given the nature of our problem (locate the record with the highest timestamp for a given device) — the following index would be appropriate:</p><pre>create index on device_measurements (device_id, timestamp desc);</pre><p>So now, we can query the max timestamp for a given device and later use that to locate the entire record with our existing indexes on timestamp and device_id:</p><pre>create or replace function get_latest_device_measurement(<br>    _device_id integer<br>) <br>returns table (<br>    &quot;timestamp&quot; timestamp,<br>    device_id integer,<br>    value double precision<br>) <br>security definer<br>language sql as<br>$$<br>with cte as (<br>    select max(timestamp) <br>    from device_measurements<br>    where thing_id = _device_id<br>)<br>select <br>    m.timestamp, m.device_id, m.value<br>from <br>    device_measurements m<br>    join cte ON m.timestamp = cte.max<br>where <br>    m.device_id = _device_id<br>limit 1;<br>$$;</pre><p>The execution plan shows us that only one partition is index scanned to locate the latest record with this approach.</p><p>This works like a charm; our reporting analytics are usable again, and everything is fine.</p><p>Again, we didn’t even have to touch the application, let alone redeploy anything. <strong>Zero timeouts.</strong></p><p>However, as time goes on, data grows. Again! Who could have predicted that!? Crazy, right?</p><p>Now, we have a large number of partitions, not just a few. The execution plan shows us that the query scans only the last partition, but it lasts almost a second. That is slow, considering that it runs in an N+1 loop and issues many queries like that, and the overall effect is slow analytics.</p><p>Now, if we examine the execution plan carefully, we can see that the planning time for a query is too long, almost an entire second, while the execution time is really fast.</p><p>That doesn’t tell us much, except that the engine takes a bit longer time to figure out what it will do. That may be because we have a large number of partitions, or maybe not, but we can try this:</p><p>Query only from the physical partition (or chunk, as the TimescalDB calls it). The last partition (with the highest timestamp date) — should contain the latest record we are looking for.</p><p>Now, our function has to execute a bit of the dynamic SQL, and it may look like this:</p><pre><br>create or replace function get_latest_device_measurement(<br>    _device_id integer<br>) <br>returns table (<br>    &quot;timestamp&quot; timestamp,<br>    device_id integer,<br>    value double precision<br>) <br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _table text;<br>    _record record;<br>begin<br>    select chunk_schema || &#39;.&#39; || chunk_name <br>    into _table<br>    from timescaledb_information.chunks c<br>    where <br>        hypertable_schema = &#39;public&#39; <br>        and hypertable_name = &#39;device_measurements&#39;<br>    order by range_end desc <br>    limit 1;<br><br>    execute format(<br>        $sql$<br>        with cte as (<br>            select max(timestamp) from %1$s<br>            where device_id = $1<br>        )<br>        select <br>            m.timestamp, m.device_id, m.value<br>        from %1$s m<br>        join cte ON m.timestamp = cte.max<br>        where m.device_id = $1<br>        limit 1;<br>        $sql$, _table<br>    ) using _device_id into _record;<br><br>    return query<br>    select _record.timestamp, _record.device_id, _record.value;<br>end;<br>$$;</pre><p>And it is a great success; the latest measurements are returned very fast again and reporting analytics is usable again.</p><p>However, as time goes on, data grows. Again! Who could have predicted that!?</p><p>Nah, I’m just joking. Of course, that data grows, but we have options. For example:</p><ul><li>I could have created a trigger on this table that would update another table with the latest timestamps and the latest values for each device. This table with redundant data containing only the latest values should be really small and fast. Then, we can alter our function to return values from that table.</li><li>I could have created a materialized view containing the latest values for each device. There is an option in Timescale DB that utilizes so-called <a href="https://www.timescale.com/blog/materialized-views-the-timescale-way/">continuous aggregation</a>, which automatically refreshes materialized view from the hypertables. Then, we can alter our function to return values from that table.</li></ul><p>And so on. The point is we can do a lot of different things, and <strong>not once the application has to be changed or redeployed.</strong></p><p>Zero timeouts, baby.</p><p>When various software architects talk about encapsulation and power abstraction — they are making a huge mistake when they not talking about database functions and procedures.</p><p>And they usually don’t.</p><p><strong>Another big benefit of this approach is security.</strong></p><p>Security is important; that’s what everyone says. However, when it comes to database security, it is usually completely ignored because developers will prioritize the use of ORM tools over security.</p><p>With this approach, we can easily implement a security principle called the <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">Principle of Least Privilege</a> or simply Least Privilege Security.</p><p>That means that every account must have the least number of privileges to perform the core function. In the army, they call this approach a <strong>need-to-know basis</strong>. Essentially, you are only allowed to know what is necessary to perform your tasks. Because if you are captured by the enemy, you can’t tell them what you don’t know. The army takes security very seriously, and so should we.</p><p>In any case, with PostgreSQL, we can easily configure our database users so they can only execute these functions. They don’t have access to the tables; they are the private parts. The enemy can steal your application database credentials, but they can never delete your data. Or at least, they can do only what the application does.</p><p>Let’s see what it would look like with PostgreSQL.</p><p>First, let’s create an application user that can’t do anything except login:</p><pre>create role app_user with<br>    login<br>    nosuperuser<br>    nocreatedb<br>    nocreaterole<br>    noinherit<br>    noreplication<br>    connection limit -1<br>    password &#39;******&#39;;</pre><p>Note, that you can set the correct and very secret password with ALTER ROLE command.</p><p>This user doesn’t have any privileges and can only log in. So far, so good.</p><p>Now, what I like to do is create my function/procedure layer in a<strong> separate schema</strong> like this:</p><pre>create schema if not exists measurements;<br><br>create or replace function measurements.get_latest(<br>    _device_id integer<br>) <br>returns table (<br>    &quot;timestamp&quot; timestamp,<br>    device_id integer,<br>    value double precision<br>) <br>security definer<br>language sql as<br>$$<br>with cte as (<br>    select max(timestamp) <br>    from device_measurements<br>    where thing_id = _device_id<br>)<br>select <br>    m.timestamp, m.device_id, m.value<br>from <br>    device_measurements m<br>    join cte ON m.timestamp = cte.max<br>where <br>    m.device_id = _device_id<br>limit 1;<br>$$;</pre><p>Now, we can group our functionalities and behavior encapsulated in user-defined functions and procedures — based on similarity. All measurement functionalities are in the measurement schema. We can also adjust the function name to remove redundant wording. Now it’s simply:</p><pre>measurements.get_latest</pre><p>So much Clean Code 🥰</p><p>If I don’t need measurement functionalities anymore for some reason, I can drop them all with one command:</p><pre>create schema if exists measurements cascade;</pre><p>This will also drop all associated objects in that schema (our measurement functions).</p><p>Similarly, I can also give an execute privilege to our application user for all functions in this schema:</p><pre>grant execute on all functions in schema measurements TO app_user;</pre><p>This applies to <strong>existing functions only</strong>.</p><p>We can also alter the default schema privileges to automatically give execute privileges to all existing functions — and the new ones yet to be created — to a specific user role:</p><pre>alter default privileges in schema measurements<br>grant execute on functions to app_user;</pre><p>It all depends on how strict we want to be with our least-privilege security.</p><p>Note that the user doesn’t have any access to tables or anything else. That’s because it’s the least privileged. That is why every function or procedure has to be created with the <a href="https://www.postgresql.org/docs/current/sql-createfunction.html"><strong>security definer</strong></a> security label. <strong>This label instructs function execution to be executed under a user context of the role that created this function, and that is usually the superuser or administrator role.</strong></p><p>PostgreSQL user-defined functions and stored procedures can help us to improve:</p><ul><li>Readability.</li><li>Maintainability.</li><li>Availability.</li><li>And, last but the not the least — Security.</li></ul><p><strong>It’s the Clean Code for your PostgreSQL, and you should start using them.</strong></p><blockquote>While I like postgres functions and the example is nice, the fact that you can change them without touching the application code isn’t that much of a big advantage.</blockquote><blockquote>SQL needs to be managed with the same release process and cycle as the app.</blockquote><p>My response:</p><p>What we usually do is to use a <a href="https://www.red-gate.com/products/flyway/community/">Flyway migration mechanism </a>or similar (there others too). So, in this case, all functions would go to a <a href="https://documentation.red-gate.com/fd/using-repeatable-migrations-to-manage-data-190578952.html">repeatable migration file </a>— one migration file per function.</p><p>And when the function is changed, it is not changed directly on the server. but rather, it is changed in that repeatable migration file (and tested locally).</p><p>That file is then committed and pushed where it needs to be committed and pushed. And, in that case, we only deploy migration, which will, in turn, only update (or alter) that function that is changed.</p><p>So that solved that problem for us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa501a33842a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/why-i-always-use-postgresql-functions-for-everything-aa501a33842a">Why I Always Use PostgreSQL Functions For Everything</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Temporal Tables Schema Management With PostgreSQL]]></title>
            <link>https://blog.devgenius.io/automatic-temporal-tables-schema-management-with-postgresql-2e56ba046279?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e56ba046279</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[administration]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 10:38:32 GMT</pubDate>
            <atom:updated>2025-01-24T12:26:55.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*WehLAcRbRL25YwMOXh0a_Q.jpeg" /><figcaption>Rijeka Neretva, Mostar, photo: VB</figcaption></figure><p>In my <a href="https://medium.com/@vbilopav/custom-temporal-tables-in-postgresql-5a0e4045ab30">previous article</a>, I explored a simple way <strong>how to automatically create and maintain temporal tables with historical data</strong> using nothing but PostgreSQL table triggers.</p><p><a href="https://medium.com/@vbilopav/custom-temporal-tables-in-postgresql-5a0e4045ab30">You can read the article</a>, but the full solution is really simple; it just requires a bit of dynamic SQL and a trigger, and that is it. The entire script creates everything needed is provided in the article.</p><p>For every history-enabled or temporal table, the system will create a new table with the same name in a special history schema that will:</p><ul><li>Have identical column structure,</li><li>Without any keys or constraints.</li><li>With one additional column at the end called <strong>_data_valid_to</strong> (leading underscore to minimize potential name collisions) - it just holds information about the maximum timestamp when that record was last valid.</li></ul><p>And that’s it. It works well.</p><p>However, there is a <strong>big problem</strong> with this approach: <strong>It doesn’t support schema changes</strong> well (or rather, at all).</p><p>That means if we alter the schema of our temporal table, we <strong>won’t be able to do any more updates or deletes </strong>on that table because the history table is out of sync, and the history insert will fail.</p><p>So, when we do an alter of the temporal table, we also must do an identical alter of the history table.</p><p>PostgreSQL has an interesting feature called <a href="https://www.postgresql.org/docs/current/event-triggers.html">event triggers</a> that could be used to do this kind of work for us automatically. Event triggers, unlike standard table triggers, are global event handlers that will run on any schema changes (any DDL command) and are perfect for keeping history schema in sync.</p><p>However, I would advise against it.</p><p><strong>Any ALTER TABLE command does table lock until the command is finished.</strong> Depending on the type of ALTER TABLE, this could be a write lock (add column, drop column) or even a read-and-write lock (change column type).</p><p>It is in our best interest to <strong>minimize the number of possible ALTER TABLE</strong> executions in a database. Sometimes, they are inevitable, but at least we don’t have to do any additional locking on history tables if we don’t have to.</p><p>Furthermore, the changes in a data type are problematic: not only do they require a type conversion on the entire table, but the nature itself of historic tables is such that older records may have one type and newer ones may have a different type as the schema is changed through time.</p><p>The solution is obvious: JSON.</p><p>However, we can still use event triggers to record schema changes to another table that will record schema change history and then establish a relation between data history and schema history.</p><p>Sounds good?</p><p>The entire solution is below in one big installable script.</p><p>You can run it in your database, and it will create a new schema called <strong>temporal_support</strong> with a couple of support functions for the entire system, which we will demonstrate afterward.</p><pre>create schema temporal_support;<br><br>create function temporal_support._consts(_key text)<br>returns text<br>language sql<br>immutable<br>parallel safe<br>as<br>$$<br>select case _key<br>    when &#39;trigger_function_name&#39; then &#39;temporal_support._temporal_table_after_trigger&#39;<br>    when &#39;trigger_name&#39; then &#39;temporal_table_after_delete_or_update_trigger&#39;<br>    when &#39;history_schema_suffix&#39; then &#39;__history&#39;<br>    when &#39;schema_table_suffix&#39; then &#39;__schema_history&#39;<br>    else null<br>end;<br>$$;<br><br>create function temporal_support._exec(<br>    _command text,<br>    variadic _args text[]<br>)<br>returns void<br>language plpgsql as<br>$$<br>declare<br>    _names text[] = array[]::text[];<br>    _values text[] = array[]::text[];<br>    i int;<br>begin<br>    for i in 1..array_length(_args, 1) by 2 loop<br>        _names = array_append(_names, _args[i]);<br>        _values = array_append(_values, _args[i+1]);<br>        _command = replace(_command, &#39;%&#39; || _args[i], &#39;%&#39; || array_length(_names, 1));<br>    end loop;<br>    _command = format(_command, variadic _values);<br>    raise info &#39;%&#39;, replace(_command, &#39;    &#39;, &#39;&#39;);<br>    execute _command;<br>end;<br>$$;<br><br>create function temporal_support._table_exists(<br>    _schema text,<br>    _name text<br>)<br>returns boolean<br>language sql as<br>$$<br>select exists(<br>    select 1 <br>    from information_schema.tables <br>    where <br>        table_schema = _schema<br>        and table_name = _name<br>        and table_type = &#39;BASE TABLE&#39;<br>);<br>$$;<br><br>create function temporal_support._temporal_table_exists(<br>    _schema text,<br>    _name text<br>)<br>returns boolean<br>language sql as<br>$$<br>select exists(<br>    select 1 <br>    from information_schema.tables tbl<br>    join information_schema.triggers tr <br>    on tbl.table_schema = tr.event_object_schema and tbl.table_name = tr.event_object_table and tr.trigger_name = temporal_support._consts(&#39;trigger_name&#39;)<br>    where <br>        table_schema = _schema<br>        and table_name = _name<br>        and table_type = &#39;BASE TABLE&#39;<br>    limit 1<br>);<br>$$;<br><br>create function temporal_support._temporal_exists(<br>    _schema text,<br>    _name text<br>)<br>returns boolean<br>language sql as<br>$$<br>select exists(<br>    select 1 <br>    from information_schema.triggers<br>    where <br>        event_object_schema = _schema<br>        and event_object_table = _name<br>        and trigger_name = temporal_support._consts(&#39;trigger_name&#39;)<br>    limit 1<br>);<br>$$;<br><br>create function temporal_support._schema_exists(_name text) returns boolean language sql as &#39;select exists(select 1 from pg_namespace where nspname = _name);&#39;;<br><br>create or replace function temporal_support._update_schema_history(<br>    _schema text,<br>    _table text<br>)<br>returns void<br>language plpgsql as<br>$$<br>declare<br>    _record record;<br>    _history_schema text;<br>    _schema_table text;<br>    _schema_data text[];<br><br>    _history_schema_suffix constant text = temporal_support._consts(&#39;history_schema_suffix&#39;);<br>    _schema_table_suffix constant text = temporal_support._consts(&#39;schema_table_suffix&#39;);<br>begin<br>    _history_schema = _schema || _history_schema_suffix;<br>    _schema_table = _table || _schema_table_suffix;<br><br>    execute format(<br>        $sql$select * from %1$I.%2$I where schema_id = (select max(schema_id) from %1$I.%2$I);$sql$,<br>        _history_schema, _schema_table<br>    ) into _record;<br><br>    _schema_data = (<br>        select<br>            array_agg(<br>                trim(concat(<br>                    quote_ident(c.column_name),<br>                    &#39; &#39;,<br>                    (c.udt_schema || &#39;.&#39; || c.udt_name)::regtype::text,<br>                    &#39; &#39;,<br>                    case when c.is_nullable = &#39;NO&#39; then &#39;NOT NULL &#39; else &#39;&#39; end, <br>                    case<br>                        when c.is_generated &lt;&gt; &#39;NEVER&#39; then &#39;GENERATED &#39; || c.is_generated || &#39; AS &#39; || c.generation_expression<br>                        when c.column_default is not null then &#39;DEFAULT &#39; || c.column_default<br>                    end<br>                )) order by c.ordinal_position<br>            )<br>        from <br>            information_schema.columns c<br>        where<br>            c.table_schema = _schema<br>            and c.table_name = _table<br>    );<br><br>    if _record.data = _schema_data then<br>        return;<br>    end if;<br><br>    execute format(<br>        $sql$insert into %1$I.%2$I (data) values ($1);$sql$,<br>        _history_schema, _schema_table<br>    ) using _schema_data;<br>end;<br>$$;<br><br><br>create function temporal_support._temporal_table_after_trigger()<br>returns trigger<br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _history_schema text;<br>    _table text;<br>    _schema_table text;<br><br>    _history_schema_suffix constant text = temporal_support._consts(&#39;history_schema_suffix&#39;);<br>    _schema_table_suffix constant text = temporal_support._consts(&#39;schema_table_suffix&#39;);<br>begin<br>    _history_schema = TG_TABLE_SCHEMA::text || _history_schema_suffix;<br>    _table = TG_TABLE_NAME::text;<br>    _schema_table = _table || _schema_table_suffix;<br><br>    execute format(<br>        $sql$insert into %1$I.%2$I (data, schema_id) select $1, (select max(schema_id) from %1$I.%3$I);$sql$, <br>        _history_schema, <br>        _table,<br>        _schema_table<br>    ) using row_to_json(old.*);<br><br>    return null;<br>end;<br>$$;<br><br>create function temporal_support._temporal_history_before_trigger()<br>returns trigger<br>security definer<br>language plpgsql as<br>$$<br>begin<br>    raise exception &#39;%&#39;, format(&#39;Table %1$I.%2$I is a history table and cannot be modified (updated or deleted)&#39;, TG_TABLE_SCHEMA, TG_TABLE_NAME);<br>end;<br>$$;<br><br>create function temporal_support._sql_drop_event_trigger()<br>returns event_trigger<br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _record record;<br>    _schema text;<br>    _history_schema text;<br>    _schema_table_name text;<br>    _trigger_name constant text = &#39;temporal_support.table_after_trigger&#39;;<br>    _history_schema_suffix constant text = temporal_support._consts(&#39;history_schema_suffix&#39;);<br>    _schema_table_suffix constant text = temporal_support._consts(&#39;schema_table_suffix&#39;);<br>begin<br>    for _record in (<br>        select object_type, schema_name, object_name from pg_event_trigger_dropped_objects()<br>    )<br>    loop<br>        if _record.object_type = &#39;table&#39; then<br><br>            if _record.schema_name like &#39;%&#39; || _history_schema_suffix then -- table is in history schema<br>                _schema = split_part(_record.schema_name, _history_schema_suffix, 1);<br>                if temporal_support._temporal_table_exists(_schema, _record.object_name) then<br>                    -- prevent dropping table with active history<br>                    raise exception &#39;Cannot drop active history for table %.%&#39;, _schema, _record.object_name;<br>                end if;<br>            else -- normal table<br>                -- delete any history table still remaining<br><br>                _history_schema = _record.schema_name || _history_schema_suffix;<br>                if temporal_support._table_exists(_history_schema, _record.object_name) then <br>                    perform temporal_support._exec(<br>                        $sql$drop table if exists %history_schema$I.%table_name$I;$sql$, <br>                        &#39;history_schema&#39;, _history_schema,<br>                        &#39;table_name&#39;, _record.object_name<br>                    );<br>                end if; <br>                _schema_table_name = _record.object_name || _schema_table_suffix;<br>                if temporal_support._table_exists(_history_schema, _schema_table_name) then <br>                    perform temporal_support._exec(<br>                        $sql$drop table if exists %history_schema$I.%schema_table_name$I;$sql$, <br>                        &#39;history_schema&#39;, _history_schema,<br>                        &#39;schema_table_name&#39;, _schema_table_name<br>                    );<br>                end if; <br><br>            end if; -- end table is in history schema<br>        end if; -- end table<br>    end loop;<br>end;<br>$$;<br>create event trigger sql_drop_event_trigger on sql_drop execute function temporal_support._sql_drop_event_trigger();<br><br>create function temporal_support._ddl_command_end_event_trigger()<br>returns event_trigger<br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _record record;<br>    _table_name text;<br>begin<br>    for _record in (<br>        select object_type, command_tag, schema_name, object_identity from pg_event_trigger_ddl_commands ()<br>    )<br>    loop<br>        if _record.object_type = &#39;table&#39; and _record.command_tag = &#39;ALTER TABLE&#39; then<br>            _table_name = trim(&#39;&quot;&#39; from split_part(_record.object_identity, &#39;.&#39;, 2));<br>            if temporal_support._temporal_exists(_record.schema_name, _table_name) then<br>                perform temporal_support._update_schema_history(_record.schema_name, _table_name);<br>            end if;<br>        end if;<br>    end loop;<br>end;<br>$$;<br>create event trigger ddl_command_end_event_trigger <br>on ddl_command_end<br>when tag in (&#39;ALTER TABLE&#39;)<br>execute function temporal_support._ddl_command_end_event_trigger();<br><br>--<br>-- function that initializes temporal support for argument tables<br>--<br>create function temporal_support.init_temporal_tables(<br>    variadic _tables text[]<br>)<br>returns void<br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _record record;<br>    _history_schema text;<br>    _schema_table text;<br><br>    _trigger_func constant text = temporal_support._consts(&#39;trigger_function_name&#39;);<br>    _trigger_name constant text = temporal_support._consts(&#39;trigger_name&#39;);<br>    _history_schema_suffix constant text = temporal_support._consts(&#39;history_schema_suffix&#39;);<br>    _schema_table_suffix constant text = temporal_support._consts(&#39;schema_table_suffix&#39;);<br>begin<br>    for _record in (<br>        select table_schema, table_name <br>        from <br>            information_schema.tables tbl<br>            left join information_schema.triggers tr <br>            on tbl.table_schema = tr.event_object_schema and tbl.table_name = tr.event_object_table and tr.trigger_name = _trigger_name<br>        where <br>            -- filter out tables that already have trigger<br>            tr.event_object_table is null<br>            -- schema.table in array or just table in array for public<br>            and (<br>                (table_schema &lt;&gt; &#39;public&#39; and table_schema || &#39;.&#39; || table_name = any(_tables))<br>                or<br>                (table_schema = &#39;public&#39; and table_name = any(_tables))<br>            )<br>            and table_type = &#39;BASE TABLE&#39;<br>    )<br>    loop<br>        _history_schema = _record.table_schema || _history_schema_suffix;<br>        _schema_table = _record.table_name || _schema_table_suffix;<br><br>        if not temporal_support._schema_exists(_history_schema) then<br>            perform temporal_support._exec(&#39;create schema %history_schema$I&#39;, <br>                &#39;history_schema&#39;, _history_schema<br>            );<br>        end if;<br><br>        if not temporal_support._table_exists(_history_schema, _schema_table) then<br>            perform temporal_support._exec(<br>                $sql$<br>                create table %history_schema$I.%schema_table_name$I (<br>                    schema_id int not null generated always as identity primary key,<br>                    data text[] not null,<br>                    timestamp timestamptz not null default now()<br>                );<br>                create trigger temporal_history_before_trigger before delete or update on %history_schema$I.%schema_table_name$I <br>                for each row execute function temporal_support._temporal_history_before_trigger();<br>                $sql$,<br>                &#39;history_schema&#39;, _history_schema,<br>                &#39;schema_table_name&#39;, _schema_table<br>            );<br>        end if;<br><br>        if not temporal_support._table_exists(_history_schema, _record.table_name) then<br>            perform temporal_support._exec(<br>                $sql$<br>                create table %history_schema$I.%table_name$I (<br>                    clock_ts timestamptz not null default clock_timestamp() primary key,<br>                    tran_ts timestamptz not null default now(),<br>                    data jsonb not null,<br>                    schema_id int not null references %history_schema$I.%schema_table_name$I(schema_id)<br>                );<br>                create trigger temporal_history_before_trigger before delete or update on %history_schema$I.%table_name$I <br>                for each row execute function temporal_support._temporal_history_before_trigger();<br>                $sql$,<br>                &#39;history_schema&#39;, _history_schema,<br>                &#39;table_name&#39;, _record.table_name,<br>                &#39;schema_table_name&#39;, _schema_table<br>            );<br>        end if;<br><br>        perform temporal_support._exec(<br>            $sql$<br>            create trigger %trigger_name$I after delete or update on %table_schema$I.%table_name$I for each row execute function %trigger_function_name$s();<br>            $sql$, <br>            &#39;trigger_name&#39;, _trigger_name, <br>            &#39;trigger_function_name&#39;, _trigger_func, <br>            &#39;table_schema&#39;, _record.table_schema,<br>            &#39;table_name&#39;, _record.table_name<br>        );<br><br>        perform temporal_support._update_schema_history(_record.table_schema, _record.table_name);<br>    end loop;<br>end;<br>$$;<br><br>--<br>-- function that deinitializes (removes) temporal support for argument tables<br>--<br>create function temporal_support.remove_temporal_tables(<br>    _drop_history boolean,<br>    variadic _tables text[]<br>)<br>returns void<br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _record record;<br>    _history_schema text;<br>    _schema_table text;<br><br>    _trigger_name constant text = temporal_support._consts(&#39;trigger_name&#39;);<br>    _history_schema_suffix constant text = temporal_support._consts(&#39;history_schema_suffix&#39;);<br>    _schema_table_suffix constant text = temporal_support._consts(&#39;schema_table_suffix&#39;);<br>begin<br>    for _record in (<br>        select distinct table_schema, table_name <br>        from <br>            information_schema.tables tbl<br>            join information_schema.triggers tr <br>            on tbl.table_schema = tr.event_object_schema and tbl.table_name = tr.event_object_table and tr.trigger_name = _trigger_name<br>        where<br>            -- schema.table in array or just table in array for public<br>            (<br>                (table_schema &lt;&gt; &#39;public&#39; and table_schema || &#39;.&#39; || table_name = any(_tables))<br>                or<br>                (table_schema = &#39;public&#39; and table_name = any(_tables))<br>            )<br>            and table_type = &#39;BASE TABLE&#39;<br>    )<br>    loop<br>        _history_schema = _record.table_schema || _history_schema_suffix;<br><br>        -- remove trigger<br>        perform temporal_support._exec(<br>            $sql$<br>            drop trigger if exists %trigger_name$I on %table_schema$I.%table_name$I;<br>            $sql$, <br>            &#39;trigger_name&#39;, _trigger_name,<br>            &#39;table_schema&#39;, _record.table_schema,<br>            &#39;table_name&#39;, _record.table_name<br>        );<br><br>        if _drop_history is true then<br>            -- remove history table<br>            _schema_table = _record.table_name || _schema_table_suffix;<br>            perform temporal_support._exec(<br>                $sql$<br>                drop table if exists %history_schema$I.%table_name$I;<br>                drop table if exists %history_schema$I.%schema_table_name$I;<br>                $sql$, <br>                &#39;history_schema&#39;, _history_schema,<br>                &#39;table_name&#39;, _record.table_name,<br>                &#39;schema_table_name&#39;, _schema_table<br>            );<br>        end if;<br>    end loop;<br>end;<br>$$;</pre><h3><strong>1) Create temporal support with the script above:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*3bFc5cXRgGp1QRMVN2DFfA.png" /></figure><p>Note that you can always drop this schema with temporal support when you don’t need this subsystem in your database.</p><h3><strong>2) Create a test table:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*WyD5sJUr3XsD5chkEylPAA.png" /></figure><h3>3) Initialize the temporal support for this table:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*WJNIfNcGBJSTjVP58MNFVQ.png" /></figure><p>Note that you can see all commands executed in a messages pane.</p><p>As we can see, the temporal initialization will create:</p><ul><li>The new schema for historical data from the tables from the public schema is called <strong>public__history (</strong>suffix configurable).</li><li>The new table for data history: <strong>public__history.test</strong></li><li>The new table for schema history: <strong>public__history.test__schema_history</strong></li></ul><p>From this point on, everything is automatic and handled by triggers.</p><p>The schema history table will contain an initial schema for the table test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*yVw_8MnBVt1uUWUBa5e8bA.png" /></figure><p>The schema definition is in the text array field called data, which will contain the exact same column definitions in the order of creation. Note that, in this version, constraints, indexes, sequences, and triggers are not recorded. Constraints may be added in later versions.</p><p>The data history table is still empty.</p><h3>4) Make some history</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*cT3KZJiAyA37q-5h9_gPkQ.png" /></figure><p>Note that inserts are in atomic transactions, and updates and deletes are in normal transactions. That is for a reason. Let’s see the data history now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*fS1UgYK_SoIL4Al7MyIMug.png" /></figure><ul><li><strong>clock_ts </strong>is the exact timestamp of the data change. It is also a primary key since it is always unique.</li><li><strong>tran_ts</strong> is the transaction timestamp of the transaction that made this change. You can see that all three records have the same value of the transaction timestamp since those changes were made under transaction (see data change above).</li><li><strong>data</strong> is the JSON representation of the record.</li><li><strong>schema_id</strong> is a foreign key to the schema version table.</li></ul><h3>5) Schema changes:</h3><p>Let’s do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*CrqGV_cDkXhkUn9dTT5jFg.png" /></figure><p>We’ve set it as not null on column <strong>t</strong> and added column <strong>i</strong>. Let’s see what schema history says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*kwLdzKmn0-TzoPBVltEMKg.png" /></figure><p>Excellent. As we can see, the timestamps for the last two changes are the same because, obviously, they ran together in the same transaction.</p><h3>6) New changes:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*UcT9ol3YtHmdneihbwKPrQ.png" /></figure><p>Let’s see what we have now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*9q94-Rwaj5WYTHLxVr-toA.png" /></figure><p>As we can see, those two changes are referring to the latest schema version id = 3. That is correct.</p><p>This system now handles schema changes correctly and without extra table locking caused by the ALTER TABLE commands while recording all data and schema changes.</p><p>We can de-initialize temporal support with this call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*kmaNAny1WQcnUnndDcTrNg.png" /></figure><p>Note that the first Boolean parameter tells us whether we should drop history objects or not.</p><p>And that’s it; if you need it, you can copy the code yourself and tweak and customize it further for your needs.</p><p>It will run very fast with minimal overhead.</p><p>It also has extra triggers that prevent you from manipulating or dropping history tables while it’s an active history table for some other temporal-enabled table. You must de-initialize temporal support first. If you drop the temporal table, the active history is dropped as well. So, the system is always consistent and doesn’t leave garbage.</p><p>The only limitation that I’m aware of is that the routine that records schema changes is not parallel-safe, so if you run many parallel ALTER TABLE commands, it may record the same schema change twice, but it won’t fail.</p><p>But it would help if you didn’t do the multiple ALTER TABLE on the same table in parallel anyhow (I don’t think it’s possible due to the ALTER locking anyway). So it’s not even a limitation anyway.</p><p>Anyway, that’s all I have for now. My temporal system for PostgreSQL is now perfect, and you can use it if you want.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e56ba046279" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automatic-temporal-tables-schema-management-with-postgresql-2e56ba046279">Automatic Temporal Tables Schema Management With PostgreSQL</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Utility Functions]]></title>
            <link>https://medium.com/@vbilopav/postgresql-utility-functions-c2134309da42?source=rss-bbfad6df8d07------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2134309da42</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Vedran Bilopavlović]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 10:47:01 GMT</pubDate>
            <atom:updated>2024-08-20T10:47:01.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIlm5vtiDmRhQD8sCt1A1Q.jpeg" /><figcaption>Photo VB, Baško Polje, Adriatic Sea</figcaption></figure><p>These are some PostgreSQL utility functions that someone may find useful when either doing PostgreSQL administration or development.</p><p>It is a good practice to create them in separate schema (something like <strong>sys</strong> or <strong>utils</strong>) so that they can be easily dropped and recreated with one command. But in this case, the public schema with an underscore before the name (to indicate they are actually private functions) will do.</p><p>So let’s start:</p><ul><li><strong>Drop all functions or procedures overload versions:</strong></li></ul><pre>create or replace procedure _drop(<br>    variadic _names text[]<br>) <br>language plpgsql<br>as <br>$$<br>declare <br>    _name text;<br>    _rec record;<br>    _cmd text;<br>    _executed boolean;<br>begin<br>    foreach _name in array _names loop<br>        _executed = false;<br>        for _rec in (<br>            select p.oid::regprocedure::text as proc, p.prokind as kind<br>            from pg_proc p join pg_namespace n <br>            on p.pronamespace = n.oid <br>                and (<br>                    (n.nspname = split_part(_name, &#39;.&#39;, 1) and proname = split_part(_name, &#39;.&#39;, 2))<br>                    or (n.nspname = &#39;public&#39; and proname = _name)<br>                )<br>            where p.prokind in (&#39;f&#39;, &#39;p&#39;)<br>        )<br>        loop<br>            if _rec.kind = &#39;f&#39; then<br>                _cmd = &#39;drop function &#39; || _rec.proc;<br>            elsif _rec.kind = &#39;p&#39; then<br>                _cmd = &#39;drop procedure &#39; || _rec.proc;<br>            else<br>                continue;<br>            end if;<br>            raise info &#39;%&#39;, _cmd;<br>            execute _cmd;<br>            _executed = true;<br>        end loop;<br><br>        if not _executed then<br>            raise warning &#39;Function or procedure &quot;%&quot; does not exist&#39;, _name;<br>        end if;<br>    end loop;<br>end;<br>$$;</pre><p>Usage:</p><pre>select _drop(&#39;my_function&#39;);<br>-- or<br>select _drop(&#39;my_schema.my_function&#39;);</pre><p>When we write functions, we often change parameters, and when we create a new function with different parameters, <strong>the old function will stay created, and PostgreSQL will create a new, overloaded version</strong> with new parameters.</p><p>Many times during development, if we forget to drop old versions, we may end up with many versions of the same function, which naturally leads to confusion and problems.</p><p>This function solves that problem by dropping all function versions from the argument or arguments.</p><p>Arguments are variadic arrays, meaning you can pass multiple function or procedure names:</p><pre>select _drop(&#39;function1&#39;, &#39;function2&#39;, &#39;function3&#39;);</pre><p>Names be schema-qualified (schema.name) or simple names that are assumed public.</p><p>This function is usually placed at the top of the repeatable migration script before creating a function (or functions for overload versions) to make sure that all versions are dropped before creating new ones.</p><ul><li><strong>Execute dynamic SQL statements and accept named parameters.</strong></li></ul><pre>create or replace function _exec(<br>    _command text,<br>    variadic _args text[]<br>)<br>returns void<br>security definer<br>language plpgsql as<br>$$<br>declare<br>    _names text[] = array[]::text[];<br>    _values text[] = array[]::text[];<br>    i int;<br>begin<br>    for i in 1..array_length(_args, 1) by 2 loop<br>        _names = array_append(_names, _args[i]);<br>        _values = array_append(_values, _args[i+1]);<br>        _command = replace(_command, &#39;%&#39; || _args[i], &#39;%&#39; || array_length(_names, 1));<br>    end loop;<br>    _command = format(_command, variadic _values);<br>    raise info &#39;%&#39;, replace(_command, &#39;    &#39;, &#39;&#39;);<br>    execute _command;<br>end;<br>$$;</pre><p>Usage:</p><pre>select _exec(<br>  $sql$<br>  create %obj$s if not exists %name$I; <br>  drop %obj$s if exists %name$I cascade;<br>  $sql$, <br>    &#39;obj&#39;, &#39;schema&#39;, <br>    &#39;name&#39;, &#39;test&#39;<br>);</pre><p>Or, within the PL/pgSQL block:</p><pre>do<br>$$<br>begin<br>    perform _exec(<br>        $sql$<br>        create %obj$s if not exists %name$I; <br>        drop %obj$s if exists %name$I cascade;<br>        $sql$, <br>            &#39;obj&#39;, &#39;schema&#39;, <br>            &#39;name&#39;, &#39;test&#39;<br>    );<br>end;<br>$$;</pre><p>The <a href="https://www.postgresql.org/docs/current/sql-execute.html">execute SQL statement</a> will only work within the PL/pgSQL block (either named function or anonymous block).</p><p>This function gives us the ability to execute dynamic SQL from anywhere.</p><p>It will also create a log of the command to be executed just before execution.</p><p>And finally, it accepts named parameters. The second parameter is a variadic array where every odd parameter is a parameter name, for example:</p><pre>select _exec(<br>  $sql$<br>  create %obj$s if not exists %name$I; <br>  drop %obj$s if exists %name$I cascade;<br>  $sql$, <br>    &#39;obj&#39;, &#39;schema&#39;, -- name obj, value schema<br>    &#39;name&#39;, &#39;test&#39;   -- name name, value test<br>);</pre><p>It works by using the <a href="https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-FORMAT">PostgreSQL format</a> function by simply replacing names with appropriate positions. This means that standard formatting rules and flags still apply.</p><p>Note that this is a utility function for administration purposes, and it is frequently used when administering data and databases. For application purposes, parameters need to be sanitized for malicious injections.</p><ul><li><strong>SQL Server has an IIF function, but PostgreSQL doesn’t. Let’s make one.</strong></li></ul><pre>create or replace function _iif(<br>    _condition boolean,<br>    _true anyelement, <br>    _false anyelement<br>)<br>returns anyelement<br>immutable<br>parallel safe<br>language sql as<br>&#39;select case when _condition then _true else _false end&#39;;</pre><p>As we know, SQL Server has IIF, and as <a href="https://www.w3schools.com/sql/func_sqlserver_iif.asp">w3schools </a>shows us, we can use something like this:</p><pre>SELECT IIF(500&lt;1000, &#39;YES&#39;, &#39;NO&#39;);</pre><p>And now, we can do the same with PostgreSQL. However, if we try to run this on PostgreSQL:</p><pre>SELECT _iif(500&lt;1000, &#39;YES&#39;, &#39;NO&#39;);</pre><p>We will get an error: <strong>could not determine polymorphic type because input has type unknown</strong>.</p><p>This is because the case statement can’t resolve the correct return type. So we must either force the explicit typecast:</p><pre>SELECT _iif(500&lt;1000, &#39;YES&#39;::text, &#39;NO&#39;);</pre><p>Or, create _iif overload versions for many different types (text, int, etc.).</p><p>That is until the PostgreSQL typing system improves.</p><p>So, those would be my three most commonly used PostgreSQL utility functions.</p><p>Do you have some of your useful utility functions?</p><p>I’d love to hear and learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2134309da42" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>