<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Nick</title>
    <description>The latest articles on DEV Community by Nick (@nickcosmo).</description>
    <link>https://dev.to/nickcosmo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F569543%2F296370ff-e875-4427-abd4-8043baf72a82.jpeg</url>
      <title>DEV Community: Nick</title>
      <link>https://dev.to/nickcosmo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nickcosmo"/>
    <language>en</language>
    <item>
      <title>Handling Concurrency with Row Level Locking in PostgreSQL</title>
      <dc:creator>Nick</dc:creator>
      <pubDate>Mon, 23 Jun 2025 23:05:22 +0000</pubDate>
      <link>https://dev.to/nickcosmo/handling-concurrency-with-row-level-locking-in-postgresql-1p3</link>
      <guid>https://dev.to/nickcosmo/handling-concurrency-with-row-level-locking-in-postgresql-1p3</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In any scalable system where multiple requests are being handled at the same time. Whether it's a microservice architecture, a monolithic backend, or even direct access to a database, concurrency becomes a critical concern. These issues often arise in subtle ways, especially when requests attempt to read and write shared data simultaneously.&lt;/p&gt;

&lt;p&gt;Concurrency issues can easily be overlooked because they are often edge cases at a certain scale. But if concurrency handling is not addressed early, they can result in data loss and many lost hours of debugging strange inconsistencies.&lt;/p&gt;

&lt;p&gt;One strategy to address this sort of problem is at the database layer. I will cover one such approach by using PostgreSQL's row-level locking feature, specifically the &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; statement. Taking the time to understand these sorts of problems and having a strategy in place will surely save you and your team trouble down the road.&lt;/p&gt;

&lt;h2&gt;
  
  
  Background
&lt;/h2&gt;

&lt;p&gt;Let's start with some quick background on locking in databases. This term may not be familiar to you if you haven't worked closely with how your database behaves under the hood, but I assure you, you have encountered locking before. For instance, take a standard update statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UPDATE users SET name = 'Nick' WHERE id = 1;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This operation does a few things behind the scenes: it locates the data from the target row, locks it, and then updates that value. The row-level lock is put on the row to ensure no other transactions can modify the row until the current one finishes. This operation usually happens so fast that we don't think about the lock, but it is absolutely there.&lt;/p&gt;

&lt;p&gt;Locking behavior is governed through something called the isolation level. This specifies how transactions interact with another transaction's data. By default PostgreSQL (and most other databases) have an isolation level of &lt;code&gt;READ COMMITTED&lt;/code&gt;. This means that the only data that can be read is data that has been committed, where uncommitted data  (aka &lt;em&gt;dirty reads&lt;/em&gt;) are not visible. Some databases (like SQL Server) allow &lt;code&gt;READ UNCOMMITTED&lt;/code&gt;, which permits dirty reads. However, PostgreSQL does not truly support this level and you should in general avoid changing this.&lt;/p&gt;

&lt;p&gt;We won’t go any deeper into isolation levels from here, but it’s worth understanding this concept before diving into row-level locking. Now, back to the problem at hand!&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem
&lt;/h2&gt;

&lt;p&gt;Let's use a simple example of having an account that users can withdraw money from.  You would probably have an endpoint in your service layer to withdraw from the account, which might have some SQL statements that look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Start a transaction
BEGIN;

-- Read the current account balance
SELECT balance
FROM accounts
WHERE id = '1';

-- Perform some validation...

-- Update the account balance
UPDATE accounts SET balance = balance - 300 WHERE id = '1';

-- Commit the transaction
COMMIT;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple right? But what happens when two transactions perform this operation at the same time? &lt;/p&gt;

&lt;p&gt;If there were two concurrent transactions, the account balance could be calculated incorrectly due to a race condition between the two transactions.&lt;/p&gt;

&lt;p&gt;Let's say the account starts with a balance of &lt;code&gt;1000&lt;/code&gt;. Transaction 1 and Transaction 2 both begin and read the current balance, both see &lt;code&gt;1000&lt;/code&gt;. Transaction 1 subtracts &lt;code&gt;300&lt;/code&gt; and commits. Then Transaction 2 subtracts &lt;code&gt;500&lt;/code&gt; and commits.&lt;/p&gt;

&lt;p&gt;Now the final balance is &lt;code&gt;500&lt;/code&gt;, but &lt;strong&gt;a total of 800 was withdrawn&lt;/strong&gt;. Something’s clearly wrong. This is a classic race condition caused by a lack of concurrency control at the database level.&lt;/p&gt;

&lt;p&gt;This problem is illustrated by the ladder diagram below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk7kuq1cqlfxcvbyfslob.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk7kuq1cqlfxcvbyfslob.png" alt="Concurrency Problem Ladder Diagram" width="800" height="1127"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Solving Concurrency with Row-Level Locking
&lt;/h2&gt;

&lt;p&gt;In order to be able to ensure that the balance stays accurate, row-level locking can be used to set a lock on the data so it cannot be edited. At a high level, what we want to do is tell the database, "hey, database, I'm going to edit this row, make sure nothing happens to it while I work on it". This can be done with a locking method in PostgreSQL with a &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; command. This command will put a lock on the row until the transaction in which it is included either commits or rolls back, so in turn can serialize these sorts of updates coming into the database.&lt;/p&gt;

&lt;p&gt;The set of commands to execute this would not look any different, except the initial read through the &lt;code&gt;SELECT&lt;/code&gt; clause would have &lt;code&gt;FOR UPDATE&lt;/code&gt; added to the end.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Start a transaction
BEGIN;

-- Read the current account balance
SELECT balance FROM accounts WHERE id = '1' FOR UPDATE;

-- Perform some validation...

-- Update the account balance
UPDATE accounts SET balance = balance - 300 WHERE id = '1';

-- Commit the transaction
COMMIT;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if two transactions try to withdraw from the same account:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Transaction 1 acquires the lock.&lt;/li&gt;
&lt;li&gt;Transaction 2 is &lt;strong&gt;blocked&lt;/strong&gt; until Transaction 1 commits or rolls back.&lt;/li&gt;
&lt;li&gt;Transaction 2 then reads the updated balance and proceeds correctly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65mb39q9y639ys1vz48v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65mb39q9y639ys1vz48v.png" alt="Concurrency Solution Ladder Diagram" width="800" height="945"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, with this simple measure, we can ensure that the account balance stays accurate even during concurrent transactions. YAY!&lt;/p&gt;

&lt;h2&gt;
  
  
  Performance Considerations
&lt;/h2&gt;

&lt;p&gt;While this approach solves concurrency issues, it can also bring along an increase in request latency. Since each transaction that accesses the same row must wait for the previous one to complete, these operations become serialized, effectively forming a queue. This ensures data integrity but can slow things down under heavy load.&lt;/p&gt;

&lt;p&gt;In many cases, the tradeoff is worth it: consistency is more important than raw speed. However, if low latency is critical to your application, you may want to explore asynchronous, event-driven architectures instead. These systems allow you to decouple processing from user-facing requests, helping reduce perceived latency while still preserving correctness in eventual consistency models.&lt;/p&gt;

&lt;h2&gt;
  
  
  Is This the Right Approach for You?
&lt;/h2&gt;

&lt;p&gt;Row-level locking is a powerful tool, but I do want to add that it may not be suitable for all applications.&lt;/p&gt;

&lt;p&gt;The case for adding this will depend on your business case. In a financial application like in the above example, accuracy is a must. Think bank accounts, ticket sales, and inventory control. In these cases strict concurrency control is crucial.&lt;/p&gt;

&lt;p&gt;But in other situations, perfect accuracy may not be worth the complexity or performance tradeoff. For example counting views or likes on a post or maybe tracking analytics events. In these cases it may be acceptable for the number to be slightly off due to concurrency.&lt;/p&gt;

&lt;p&gt;The key is to understand your product requirements so you can make an informed decision and define your approach.&lt;/p&gt;

&lt;h2&gt;
  
  
  Look Out for Deadlocks!
&lt;/h2&gt;

&lt;p&gt;While row-level locking prevents race conditions, it can introduce deadlocks if not used carefully. In the example above, we do not run the risk of a deadlock because there is a single account being worked on in each transaction. &lt;/p&gt;

&lt;p&gt;Deadlocks occur when two (or more) transactions wait on each other for data in a circular fashion.&lt;/p&gt;

&lt;p&gt;Transaction 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT balance FROM accounts WHERE id = '1' FOR UPDATE;
-- later
SELECT balance FROM accounts WHERE id = '2' FOR UPDATE;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Transaction 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT balance FROM accounts WHERE id = '2' FOR UPDATE;
-- later
SELECT balance FROM accounts WHERE id = '1' FOR UPDATE;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both transactions are now waiting for the other to commit or roll back, that's a Deadlock!&lt;/p&gt;

&lt;p&gt;PostgreSQL will recognize this issue and abort one of the transactions. In general, you should watch out for this pattern and keep a consistent order when acquiring locks to avoid this altogether.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Concurrency can be sneaky and should be handled early on during application development. Fortunately, with features like &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, PostgreSQL gives us the tools we need to handle concurrency safely. By applying these patterns early, you can save yourself a lot of debugging time and ensure your system scales with integrity.&lt;/p&gt;

&lt;p&gt;If you want to go further into this topic, check out some of the other features PostgreSQL has to offer, including table and page-level locks. You can read more about them in the documentation here: &lt;a href="https://www.postgresql.org/docs/current/explicit-locking.html#EXPLICIT-LOCKING" rel="noopener noreferrer"&gt;13.3 - Explicit Locking&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I hope you enjoyed this article. Please leave a comment if I missed anything or if you have used row-level locking in your projects!&lt;/p&gt;

&lt;p&gt;Thanks for reading :)&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>sql</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Create an Auto-Incrementing Version Column With PostgreSQL Triggers</title>
      <dc:creator>Nick</dc:creator>
      <pubDate>Tue, 04 Feb 2025 19:51:19 +0000</pubDate>
      <link>https://dev.to/nickcosmo/create-an-auto-incrementing-version-column-with-postgresql-triggers-1605</link>
      <guid>https://dev.to/nickcosmo/create-an-auto-incrementing-version-column-with-postgresql-triggers-1605</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;When building database schemas, there will often be the desire to create a versioning column on all or some database tables. A developer's knee-jerk reaction may be to implement this at the code level. This approach can be quite simple depending on how your code is architected. Say you have a single CRUD service/module in your application, you could just add some logic there to increment a version column during an update. This approach can work fine but it is yet one more thing that needs to be kept track of in case your code-level patterns change from refactoring. &lt;/p&gt;

&lt;p&gt;Utilizing a database trigger is a simple and more efficient approach to solving this problem. This is something that PostgreSQL (Postgres), among most modern databases, supports as a feature and its use can be quite powerful. To illustrate how this can be done we will walk through how to build a trigger in Postgres to implement an auto-incrementing versioning column.&lt;/p&gt;

&lt;p&gt;Within this post, I will assume you have minimal knowledge of Postgres triggers and will explain every step of the way.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Are Triggers and How Do They Work?
&lt;/h2&gt;

&lt;p&gt;Postgres triggers let you create a declaration to execute a function within the database that ties into certain actions. Some might think of these as "hooks" that hook into database actions. The actions that I am referring to here are the DML statements &lt;code&gt;INSERT&lt;/code&gt;, &lt;code&gt;UPDATE&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt;. These actions are specified in the SQL standard. The logic contained in the function that is triggered can be further specified to fire either &lt;code&gt;BEFORE&lt;/code&gt; or &lt;code&gt;AFTER&lt;/code&gt; the action that is taking place. In addition to the previously mentioned DML commands, Postgres also supports adding triggers around the &lt;code&gt;TRUNCATE&lt;/code&gt; action which not all databases support.&lt;/p&gt;

&lt;p&gt;Another point to keep in mind is that triggers are transactional. This means that triggers are part of the same transaction as the statement that fired them and if the transaction is rolled back, the trigger's actions are also rolled back. This is important to keep in mind for debugging purposes and something to consider from an observability perspective when implementing triggers. Whenever you are adding more logic to your database there could, of course, be more failure points to consider that now lie outside of the code level.&lt;/p&gt;

&lt;h2&gt;
  
  
  Building A Postgres Trigger
&lt;/h2&gt;

&lt;p&gt;To first clarify what our goal is here. We will create a table with a column called &lt;code&gt;version&lt;/code&gt; that will initialize to 0, and our goal will be for each &lt;code&gt;UPDATE&lt;/code&gt; statement executed against a row in this table, the &lt;code&gt;version&lt;/code&gt; column will increment by 1.&lt;/p&gt;

&lt;p&gt;Let's start with a DML statement to create a table to apply our trigger.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE table_1 (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  version INTEGER NOT NULL DEFAULT 0,
  name VARCHAR NOT NULL
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this statement, I have added three columns to the table &lt;code&gt;table_1&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;id&lt;/code&gt; - This is set as our primary key and defaults to use the native Postgres function of &lt;code&gt;gen_random_uuid()&lt;/code&gt; to give us a unique identifier for each row in the table.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;version&lt;/code&gt; - This will serve as the version column we will increment with our trigger. It is set to default to 0.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;name&lt;/code&gt; - A &lt;code&gt;VARCHAR&lt;/code&gt; column we will use to test applying our updates.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now to get something to work with, let's insert a row to our new table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO table_1 (name) VALUES ('Nick');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you run a &lt;code&gt;SELECT&lt;/code&gt; statement you should see a new record in &lt;code&gt;table_1&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT * FROM table_1;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first step to creating a trigger is to create a function. That may sound a little strange but creating a trigger is a two-part process. First, create a function, then create the trigger which will utilize the function. All the magic will happen inside the function which must be set as a special type of Postgres function. The function is created in a similar fashion to any other function or stored procedure except it must not take any arguments and must return a type of &lt;code&gt;TRIGGER&lt;/code&gt;. In our case, the function will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE OR REPLACE FUNCTION increment_version() 
RETURNS TRIGGER AS $$
BEGIN
    NEW.version = COALESCE(OLD.version, 0) + 1;
    RETURN NEW;
END
$$ LANGUAGE plpgsql;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A couple of points to note on the above statement:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I use &lt;code&gt;CREATE OR REPLACE&lt;/code&gt; here which works as an "upsert" action for the function. If this is the first time creating a function just writing &lt;code&gt;CREATE&lt;/code&gt; would have worked just fine.&lt;/li&gt;
&lt;li&gt;The function is declared to return a trigger with &lt;code&gt;RETURNS TRIGGER&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;OLD&lt;/code&gt; and &lt;code&gt;NEW&lt;/code&gt; variables are available inside all Postgres triggers and correspond to the old table record and new table record respectively. The value for the column &lt;code&gt;version&lt;/code&gt; is accessed through dot notation.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;LANGUAGE plpgsql&lt;/code&gt; declares that the function is written in the &lt;code&gt;PL/pgSQL&lt;/code&gt; procedural language.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Having the function, we can now apply the trigger to our table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE OR REPLACE TRIGGER update_version 
BEFORE UPDATE ON table_1 
FOR EACH ROW
EXECUTE FUNCTION increment_version();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The statement to apply the trigger is a little more simple than creating the function. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The trigger is created with the name &lt;code&gt;update_version&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;BEFORE UPDATE&lt;/code&gt; specifies that we would like to fire the trigger before an update statement executes on &lt;code&gt;table_1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;FOR EACH ROW&lt;/code&gt; specifies that this should apply to every row affected by the update statement.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;EXECUTE FUNCTION increment_version()&lt;/code&gt; declares that our function from the previous step will be called here.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The trigger is now applied. If you execute an update statement to the record we created earlier, you should see the version column increment by 1 with each update.&lt;/p&gt;

&lt;p&gt;With the function already created it becomes very easy to extend this trigger to new tables. You would simply run the &lt;code&gt;CREATE OR REPLACE TRIGGER&lt;/code&gt; statement against the table where you would want to apply the trigger. For example, if we had another table, &lt;code&gt;table_2&lt;/code&gt;, we could execute the statement below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE OR REPLACE TRIGGER update_version 
BEFORE UPDATE ON table_2 
FOR EACH ROW
EXECUTE FUNCTION increment_version();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One point to note is that we used the same name for the trigger, &lt;code&gt;update_version&lt;/code&gt;, on this new table, and that is perfectly ok! Trigger names must be unique within the context of the same table, but they can be the same across different tables. So, if we created a new trigger on &lt;code&gt;table_2&lt;/code&gt;, we would have to give it a name other than &lt;code&gt;update_version&lt;/code&gt; since this is now taken.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding Better Validation
&lt;/h2&gt;

&lt;p&gt;At this point, you may be asking yourself, "What if the table didn't have a &lt;code&gt;version&lt;/code&gt; column?". The answer to this is that the function we wrote would raise an error, and as mentioned before the trigger is transactional so it would make the entire transaction that this action was a part of rollback. If you are very careful and have good test coverage this may not be something to worry about, and the errors would surface rather quickly since you would be seeing a ton of failures coming from update operations. But, alas, programmers are human (for now), and we make mistakes. &lt;/p&gt;

&lt;p&gt;To beef up the validation, we can update our function with an extra bit of logic that would put in a fail-safe for us in case the &lt;code&gt;version&lt;/code&gt; column did not exist on the table. Here is the revised function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE OR REPLACE FUNCTION increment_version() 
RETURNS TRIGGER AS $$
DECLARE
    table_columns TEXT[];
    column_exists BOOLEAN;
BEGIN
    SELECT ARRAY_AGG(column_name)
     INTO table_columns 
     FROM information_schema.columns 
     WHERE table_name = TG_TABLE_NAME 
     AND table_schema = TG_TABLE_SCHEMA;

    column_exists := 'version' = ANY(table_columns);

    IF column_exists IS TRUE THEN
        NEW.version = COALESCE(OLD.version, 0) + 1;
    END IF;

    RETURN NEW;
END
$$ LANGUAGE plpgsql;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The updated function has some new logic to add the validation.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A query is made to read the columns of our table by querying against the &lt;code&gt;information_schema.columns&lt;/code&gt; table, which is maintained under the hood by Postgres. A filter is made against the query with &lt;code&gt;TG_TABLE_NAME&lt;/code&gt; and &lt;code&gt;TG_TABLE_SCHEMA&lt;/code&gt;, which are variables that are available inside Postgres triggers and correspond to the name of the table and the schema where the table is located.&lt;/li&gt;
&lt;li&gt;A check is made to see whether the &lt;code&gt;version&lt;/code&gt; column exists with &lt;code&gt;column_exists := 'version' = ANY(table_columns);&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The operation to increment the &lt;code&gt;version&lt;/code&gt; column is made conditional depending on whether or not the column exists on the table.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since we have overwritten the function with &lt;code&gt;CREATE OR REPLACE FUNCTION&lt;/code&gt;, the name has not changed and this update will automatically go into effect wherever it is applied!&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We were able to create a basic Postgres trigger to add versioning to our database records. This is a very simple use case, and the applications of Postgres triggers are endless. Hopefully this gives some insight into how easy it can be to implement a Postgres trigger and gets you thinking about what code-level logic can transition to your database layer.&lt;/p&gt;

&lt;p&gt;To read more about Postgres triggers, you can check out the docs &lt;a href="https://www.postgresql.org/docs/current/sql-createtrigger.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>database</category>
      <category>sql</category>
    </item>
    <item>
      <title>Reusable NestJS Interceptors with a Factory Pattern</title>
      <dc:creator>Nick</dc:creator>
      <pubDate>Thu, 23 Jan 2025 20:49:33 +0000</pubDate>
      <link>https://dev.to/nickcosmo/reusable-nestjs-interceptors-with-a-factory-pattern-11gg</link>
      <guid>https://dev.to/nickcosmo/reusable-nestjs-interceptors-with-a-factory-pattern-11gg</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;Anyone diving into developing APIs with NestJS has seen the benefits of binding logic to API endpoints with interceptors. While interceptors are a great tool to add code execution before your endpoints, they come with some code overhead to create an interceptor for every case in your application. I recently found myself creating interceptors for very similar use cases within a NestJS API and discovered a nice, reusable method of creating interceptors utilizing a factory pattern which alleviates some of the code bloat.&lt;/p&gt;

&lt;p&gt;The factory pattern focuses on code reusability and efficiency. It uses an abstract class as a common interface in a factory function to create a NestJS interceptor on the fly rather than creating an individual interceptor.&lt;/p&gt;

&lt;p&gt;Within this post I will assume that you have some basic understanding of NestJS. If you are brand new to NestJS I would recommend to have a &lt;a href="https://docs.nestjs.com/" rel="noopener noreferrer"&gt;look at the docs&lt;/a&gt;, specifically the "Overview" section of the docs before reading this article.&lt;/p&gt;

&lt;p&gt;This pattern will also be utilizing TypeScript and I will assume you are familiar with some of the basic patterns of TypeScript (generics, class syntax, typing).&lt;/p&gt;

&lt;h2&gt;
  
  
  App Setup
&lt;/h2&gt;

&lt;p&gt;To set the scene, we will begin with a very standard NestJS application. Say we have a REST API with a POST endpoint at &lt;code&gt;/user/create&lt;/code&gt; where we create new user records.&lt;/p&gt;

&lt;p&gt;To follow the standard NestJS patterns, we would have a controller, service, and module.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Controller
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Post('create')
    createOneUser(@Body() dto: CreateOneUserDto) {
        return this.userService.createOne(dto);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Service
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable()
export class UserService {
    createOne(dto: CreateOneUserDto): string {
        // User create stuff goes here...
        return `User created successfully`;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Module
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Module({
    imports: [],
    controllers: [UserController],
    providers: [
        UserService
    ],
    exports: [],
})
export class UserModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a very standard setup of a NestJS Module so I won't go into any detail on the above code.&lt;/p&gt;

&lt;p&gt;Now, say we want to add a validation step to the &lt;code&gt;createOneUser&lt;/code&gt; controller method before we call our service. This is a case where one would typically reach for an interceptor to add this validation step. The standard pattern would be to implement a standalone interceptor that could hold some validation logic to execute before creating a new user, but what if we wanted to do the same thing in another module for a separate entity model? This would typically require us to create another interceptor to essentially do the same thing. This is the problem we will aim to solve with the factory pattern.&lt;/p&gt;

&lt;p&gt;NestJS provides many other ways of binding logic to your endpoints, such as pipes and guards, but for this example, we will create an interceptor with our factory. Hopefully, you will see that this pattern could easily be re-crafted for pipes and guards as well.&lt;/p&gt;

&lt;h2&gt;
  
  
  Building An Interceptor Factory
&lt;/h2&gt;

&lt;p&gt;To design this pattern for code reuse, we will introduce an additional service, a validation service, that will be called from the interceptor. So the interceptor will operate more like a pass-through to the new validation service. The flow would then look something like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Interceptor -&amp;gt; Validation Service -&amp;gt; Controller -&amp;gt; Service&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, to start creating our factory we will begin by creating an abstract class to use as a common interface for our validation service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export abstract class BaseValidationService&amp;lt;T extends any = any&amp;gt; {
    abstract validateCreate(dto: T): T;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This establishes an abstract class called &lt;code&gt;BaseValidationService&lt;/code&gt; which we can extend to ensure we have a common interface for our validation service, and for future validation services that may use this pattern. This gives us type safety as we integrate our validation service into the factory. An abstract method of &lt;code&gt;validateCreate&lt;/code&gt; has been defined which we can use to hold the validation logic for our endpoint.&lt;/p&gt;

&lt;p&gt;For the validation service, we will create a new injectable service that will extend the base service we just defined. We could create a validation service like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable()
export class UserValidationService extends BaseValidationService&amp;lt;CreateOneUserDto&amp;gt; {
    constructor() {
        super();
    }

    validateCreate(body: CreateOneUserDto): CreateOneUserDto {
        if (body.id.length &amp;lt; 5) {
            throw new HttpException(
                'id must be greater than 5 digits',
                HttpStatus.BAD_REQUEST,
            );
        }

        return body;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This complies with the format of the &lt;code&gt;BaseValidationService&lt;/code&gt; through class inheritance and your IDE should give you some notice if something is wrong with how you are extending the abstract class. We define the &lt;code&gt;validateCreate&lt;/code&gt; function which, for example purposes, will validate that a value for the &lt;code&gt;id&lt;/code&gt; key in the body is greater than 5 digits. This is something that could typically be accomplished with a package like &lt;code&gt;class-validator&lt;/code&gt; but this is just to illustrate the pattern.&lt;/p&gt;

&lt;p&gt;Now, finally, to create the factory we can write a new factory function that will create an interceptor that will route the request to the validation service method we just defined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const ValidationCreateFactory = (
    validation: new (...args: any[]) =&amp;gt; BaseValidationService,
) =&amp;gt; {

    @Injectable()
    class ValidationInterceptor implements NestInterceptor {
        constructor(
            @Inject(validation.name)
            readonly validationService: BaseValidationService,
        ) {}

        async intercept(
            context: ExecutionContext, 
            next: CallHandler
        ): Promise&amp;lt;Observable&amp;lt;any&amp;gt;&amp;gt; {
            let body = context.switchToHttp().getRequest().body;
            body = await this.validationService.validateCreate(body);
            return next.handle().pipe();
        }
    }

    return ValidationInterceptor;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To take a step back and look at what this is doing. This is a function that accepts a class in the shape of our abstract class of &lt;code&gt;BaseValidationService&lt;/code&gt; and returns a NestJS interceptor. Inside the interceptor, we go through a fairly standard flow of grabbing the HTTP request body and passing it as an argument to the &lt;code&gt;validateCreate&lt;/code&gt; method in the validation service. &lt;/p&gt;

&lt;p&gt;One special thing to note is how the interceptor can grab the instance of the validation service from the Nest DI graph. This is accomplished with the &lt;code&gt;@Inject&lt;/code&gt; decorator, where a token for the validation service is used to create the dependency in its constructor method. This will be important as we add the validation service to our module where we will need to use the long-hand syntax for creating dependencies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Module({
    imports: [],
    controllers: [UserController],
    providers: [
        UserService,
        {
            useClass: UserValidationService,
            provide: UserValidationService.name,
        },
    ],
    exports: [],
})
export class UserModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now utilize the factory function to put everything together inside the controller with the &lt;code&gt;@UseInterceptors&lt;/code&gt; decorator much like we would add any typical interceptor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Post('create')
    @UseInterceptors(ValidationCreateFactory(UserValidationService))
    createOneUser(@Body() dto: CreateOneUserDto) {
        return this.userService.createOne(dto);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have implemented a reusable pattern that would be able to add a validation step to any create endpoint in this Nest application. In case other entity models were added to this API, the separate module could easily tap into this pattern to add a validation step by simply creating a new validation service and using the &lt;code&gt;ValidationCreateFactory&lt;/code&gt; function that we have defined. Looking further, imagine if there was an update endpoint where we wanted to validate the body of a separate update endpoint. We could create another factory to route the request to a separate validation method, that could be called &lt;code&gt;validateUpdate&lt;/code&gt;. This is where you would really start to notice the code reusability benefits of this pattern.&lt;/p&gt;

&lt;h2&gt;
  
  
  Considerations
&lt;/h2&gt;

&lt;p&gt;There is one special thing to note about this pattern. You will notice that the factory is just a function, which means that each time it is used will equate to a separate function call. Within a large application, this could result in some cold start performance issues as each factory call will be executed each time the app starts up. In most small applications this would probably be negligible but something to note in case you adopt a pattern like this in your application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I hope you liked this post and took something away from it. Patterns like this can be really nice when using a framework like NestJS where there is a lot of class-based tooling. Keep in mind the performance drawback to this pattern but if it makes sense to use it in your application I hope you explore the possible use cases!&lt;/p&gt;

&lt;p&gt;Thanks for reading :).&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>api</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Creating an Array of Unique Objects in Javascript</title>
      <dc:creator>Nick</dc:creator>
      <pubDate>Thu, 09 May 2024 01:50:31 +0000</pubDate>
      <link>https://dev.to/nickcosmo/creating-an-array-of-unique-objects-in-javascript-2m6b</link>
      <guid>https://dev.to/nickcosmo/creating-an-array-of-unique-objects-in-javascript-2m6b</guid>
      <description>&lt;p&gt;I recently uncovered a nifty trick to be able to create a unique array of objects in Javascript that you should definitely add to your tool belt.&lt;/p&gt;

&lt;p&gt;Have you ever found yourself building up some sort of array that contains objects that may contain duplicates? What I mean is ending up with something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arrayOfObjs = [
  {id: '123', code: 'ABC'},
  {id: '456', code: 'DEF'},
  {id: '123', code: 'ABC'},
  ...
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, how can we remove the duplicates here?&lt;/p&gt;

&lt;p&gt;In these sorts of situations my instinct is to use lodash, but this can be done with plain old Javascript.&lt;/p&gt;

&lt;p&gt;By utilizing the &lt;code&gt;Map&lt;/code&gt; constructor and creating a new &lt;code&gt;Map&lt;/code&gt; instance, this array can be filtered down to unique values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arrayOfObjsMap = new Map(
  arrayOgObjs.map((item) =&amp;gt; {
    return [JSON.stringify(item), item];
  }),
);

const uniqueArrayOfObjs = arrayOfObjsMap.values();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method of removing duplicates from the array takes advantage of the fact that keys in Maps are unique, so the removal of duplicates will inherently be taken care of through the construction of this Map.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Map&lt;/code&gt; constructor can take an iterable (&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/Map" rel="noopener noreferrer"&gt;per the MDN docs&lt;/a&gt;) which can represent key-value pairs for the &lt;code&gt;Map&lt;/code&gt; object. So, by using &lt;code&gt;JSON.stringify()&lt;/code&gt; on the iteratees of our array we are able to create a unique string when constructing our &lt;code&gt;Map&lt;/code&gt; keys which serves as the unique identifier for our objects. Then by simply calling &lt;code&gt;values()&lt;/code&gt; on the new &lt;code&gt;Map&lt;/code&gt; instance we are back to having an array of objects but now we have no duplicates.&lt;/p&gt;

&lt;p&gt;Hope you find this useful!&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Using Function Parameters with Conditional Types in Typescript</title>
      <dc:creator>Nick</dc:creator>
      <pubDate>Thu, 04 Apr 2024 02:26:45 +0000</pubDate>
      <link>https://dev.to/nickcosmo/typescript-hack-using-function-parameters-with-conditional-types-5bid</link>
      <guid>https://dev.to/nickcosmo/typescript-hack-using-function-parameters-with-conditional-types-5bid</guid>
      <description>&lt;p&gt;Lately, I find myself wanting to conditionally return one of two different types from a function, while still getting Typescript's static typing benefits. This is possible by constructing a conditional type in Typescript. &lt;/p&gt;

&lt;p&gt;The concept itself is quite simple but becomes powerful when combined with querying data – which we will uncover towards the end of this post. But first, a contrived example...&lt;/p&gt;

&lt;h2&gt;
  
  
  A Basic Example
&lt;/h2&gt;

&lt;p&gt;Say you have two different interfaces a &lt;code&gt;Cat&lt;/code&gt; interface and a &lt;code&gt;Dog&lt;/code&gt; interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Cat {
 sound: 'meow';
}

interface Dog {
 sound: 'woof';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you would like to conditionally return one of the two from a function.&lt;/p&gt;

&lt;p&gt;With conditional types, a ternary-like syntax can be used to construct a new type &lt;code&gt;CatOrDog&lt;/code&gt; that can return either a &lt;code&gt;Cat&lt;/code&gt; or &lt;code&gt;Dog&lt;/code&gt; based on a generic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type CatOrDog&amp;lt;T extends 'cat' | 'dog'&amp;gt; = T extends 'cat' ? Cat : Dog;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This new type can then be used in a function to conditionally return a &lt;code&gt;Cat&lt;/code&gt; or a &lt;code&gt;Dog&lt;/code&gt; based on a function parameter to dictate which we should expect to receive from a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getCatOrDog&amp;lt;T extends 'cat' | 'dog'&amp;gt;(option: T): CatOrDog&amp;lt;T&amp;gt;  {
 if (option === 'cat') {
  return {sound: 'meow'};
 }

 if (option === 'dog') {
  return {sound: 'woof'};
 }
}

getCatOrDog('cat'); // returns Cat
getCatOrDog('dog'); // returns Dog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above function will conditionally return a &lt;code&gt;Cat&lt;/code&gt; or a &lt;code&gt;Dog&lt;/code&gt; type depending on what is passed into the &lt;code&gt;option&lt;/code&gt; parameter. This leads to a great developer experience as you can take advantage of Typescript's static type checking here and some modern IDEs can give you intelli-sense to flag any type errors when using this function during development.&lt;/p&gt;

&lt;p&gt;Now that we have a basic example in place, let's move on to a more useful situation...&lt;/p&gt;

&lt;h2&gt;
  
  
  A Practical Use Case
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;CatOrDog&lt;/code&gt; example is a contrived use of this pattern. The benefits become quite apparent when you combine this with fetching data from a database, which is where I find myself reaching for this pattern most often (usually with an ORM like TypeORM).&lt;/p&gt;

&lt;p&gt;Say you have an application where you store user information in a table called &lt;code&gt;user&lt;/code&gt; and contact information in a separate table called &lt;code&gt;contact_info&lt;/code&gt; and there is a 1:1 relationship between the two tables, you may have interfaces set up similar to the following, which represent an entity structure in your database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface User {
 id: string;
 name: string;
}

interface ContactInfo {
 phone: string;
 address: string;
 userId: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then say when you query users you may want to conditionally hydrate the contact information for a user. You could make a conditional type that uses a function parameter, as we did before, to determine whether you should expect to receive an instance of &lt;code&gt;User&lt;/code&gt; or &lt;code&gt;User &amp;amp; ContactInfo&lt;/code&gt;. The function can use the same function parameter to add a join to a query based on the input value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type UserOrUserWithContactInfo&amp;lt;T extends boolean&amp;gt; = T extends true ? User &amp;amp; ContactInfo : User;

async function fetchUser&amp;lt;T extends boolean&amp;gt;(id: string, withContactInfo: T): Promise&amp;lt;UserOrUserWithContactInfo&amp;lt;T&amp;gt;&amp;gt; {
 const query = `
  SELECT *
  FROM user
 `

 if (withContactInfo) {
  query += `
   LEFT JOIN contact_info on user.id = contact_info."userId"
  `
 }

 const query += `
  WHERE user.id = '${id}'
 `

 // assume this executes our query string
 return connection.query(query);
}

await fetchUsers(false); // returns User
await fetchUsers(true); // returns User &amp;amp; ContactInfo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when using this function you can benefit from static type checking by conditionally adding a join to a query to fetch the contact information related to a user. This utilizes the new &lt;code&gt;UserOrUserWithContactInfo&lt;/code&gt; conditional type which returns either a &lt;code&gt;User&lt;/code&gt; or &lt;code&gt;User &amp;amp; ContactInfo&lt;/code&gt; based on the &lt;code&gt;boolean&lt;/code&gt; value that we pass to the &lt;code&gt;withContactInfo&lt;/code&gt; function parameter.&lt;/p&gt;

&lt;p&gt;You can read more about Typescript conditional types &lt;a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>typescript</category>
    </item>
  </channel>
</rss>
