<?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 Asheet  on Medium]]></title>
        <description><![CDATA[Stories by Asheet  on Medium]]></description>
        <link>https://medium.com/@heyasheet?source=rss-504c3f1187ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0IFNd0wqMtBRYDcM4JfQ_g@2x.jpeg</url>
            <title>Stories by Asheet  on Medium</title>
            <link>https://medium.com/@heyasheet?source=rss-504c3f1187ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:03:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@heyasheet/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[The Art of Letting Go: Why We Grip the Past and How to Free the Future]]></title>
            <link>https://heyasheet.medium.com/the-art-of-letting-go-why-we-grip-the-past-and-how-to-free-the-future-b2f9cba191c9?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f9cba191c9</guid>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 10:52:15 GMT</pubDate>
            <atom:updated>2026-09-05T10:52:15.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzupye1Kph2g4CR8u2GVIg.png" /></figure><p>We are culturally conditioned to acquire. From a young age, we are taught how to gain friends, accumulate wealth, build careers, and collect milestones. We are handed a blueprint for holding on, but almost no one teaches us how to put things down.</p><p>Whether it is a relationship that has run its course, a career path that no longer fits, an old grudge, or a former version of yourself, holding on past the expiration date is a universal human default. We grip tightly because the familiar, even when painful, feels safer than the void of the unknown.</p><p>But clinging to what was actively prevents you from stepping into what could be.<strong> Letting go is not a passive event, it is a deliberate, active skill</strong>.</p><h3>The Sunk Cost of Identity</h3><p>In economics, the “sunk cost fallacy” is the tendency to continue investing in a losing proposition simply because of what you have already put into it. We do the exact same thing with our lives.</p><p>You stay in the draining relationship because you’ve invested five years. You stick with the miserable career because of the expensive degree hanging on your wall. You hold onto a resentment because letting it go feels like letting the other person off the hook.</p><p>The hardest part of letting go isn’t actually losing the person, the job, or the situation. The hardest part is losing the identity you built around it. When you release a piece of your past, you are forced to answer a terrifying question: <strong><em>Who am I without this?</em></strong></p><p>We hold on because we confuse the things we are attached to with our actual selves. But you are not your relationships, your job title, or your past mistakes. You are the consciousness experiencing them.</p><h3>Detachment is Not Apathy</h3><p>A common misconception is that letting go means you no longer care, that you are giving up, or that the thing you are releasing didn’t matter. This binary thinking keeps us trapped.</p><p>Detachment is not apathy. Apathy is an emotional deadening, it is the refusal to feel. Detachment, on the other hand, is the deep acceptance of reality. It is recognizing that you cannot force a square peg into a round hole, no matter how hard you push.</p><p>When you truly let go, you are not saying, “This didn’t matter.” You are saying, “This mattered deeply, it shaped me, but it is no longer meant for me.” You can have immense love for a chapter of your life while simultaneously recognizing that the page needs to turn.</p><h3>The Mechanics of the Release</h3><p>Letting go is rarely a light-switch moment. It is not a decision you make once, it is a decision you make a hundred times a day until the muscle memory of gripping finally begins to fade.</p><ul><li><strong>Acknowledge the phantom future:</strong> Often, we are not mourning the reality of what we lost, we are mourning the fantasy of what we thought it would become. To let go, you have to brutally separate the actual reality of the situation from the potential you projected onto it. Grieve the unlived future so you can deal with the present.</li><li><strong>Stop negotiating with reality:</strong> The mind loves to play the “what if” game. <strong><em>What if I had said this? What if they change?</em> </strong>Letting go requires radical acceptance of what <em>is</em>, right now, without caveat.</li><li><strong>Unclench incrementally:</strong> If you are holding a rope tightly and suddenly let go, your hands will ache. The same is true emotionally. Start by creating small windows of distance. Unfollow the account. Box up the mementos. Stop checking the inbox. You don’t have to erase the past, but you must stop inviting it into your present.</li></ul><blockquote>Nature operates in continuous cycles of death and rebirth. Trees do not clutch their dead leaves in the winter, they drop them to the ground so that energy can be redirected to the roots, preserving life for the spring.</blockquote><p>When you refuse to let go, your hands are too full to catch anything new. The art of letting go is ultimately the art of making space. It is trusting that the emptiness you feel right now is not a permanent void, but a clearing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f9cba191c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Tax of Context Switching]]></title>
            <link>https://heyasheet.medium.com/the-hidden-tax-of-context-switching-81d9516dde3f?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/81d9516dde3f</guid>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 03:06:34 GMT</pubDate>
            <atom:updated>2026-08-27T03:06:34.222Z</atom:updated>
            <content:encoded><![CDATA[<p>Why doing five things at once means doing none of them well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lQxgB2U5wf7iSCc4.png" /></figure><p>You answer a Slack message mid-code-review, jump into a “quick” meeting, return to your inbox, then try to remember where you were in that document. By 6 PM you’ve been busy all day and finished almost nothing.</p><p>That’s not a discipline problem. It’s a context-switching problem, and it’s quietly one of the most expensive habits in modern work.</p><h3>The reload tax</h3><p>Your brain isn’t a browser with infinite tabs. Every complex task requires loading “state”, the variables, threads, and half-formed ideas you hold in working memory. When you switch tasks, that state gets flushed. When you return, you pay to rebuild it.</p><blockquote><em>Research (</em><a href="https://ics.uci.edu/~gmark/chi08-mark.pdf">The Cost of Interrupted Work: More Speed and Stress</a><em>) from UC Irvine’s Gloria Mark found it takes roughly 23 minutes to fully refocus after an interruption. If you switch every 15 minutes, you’re never actually operating at full depth. You’re perpetually rebooting</em></blockquote><h3>Attention residue</h3><p>Worse, switching doesn’t even give you a clean break. Sophie Leroy’s research on “attention residue” showed that part of your mind stays stuck on the previous task — especially if you left it unfinished. You sit in the new meeting, but a fragment of you is still debugging that function. Both tasks get a diminished version of you.</p><h3>The compounding costs</h3><p>The damage stacks up in ways that are easy to miss:</p><p><strong>Quality drops.</strong> Deep work — writing, analysis, design, engineering — depends on holding complexity in your head. Fragmented attention means shallower thinking and more errors. Some studies put the productivity loss from heavy multitasking at up to 40%.</p><p><strong>Fatigue arrives early.</strong> Switching burns disproportionate mental energy. Decision fatigue that used to hit at 4 PM now hits at noon.</p><p><strong>Focus atrophies.</strong> Chronic switching trains your brain to crave novelty. Even when you finally get a free afternoon, sustained concentration feels harder than it used to. It’s a muscle, and it weakens.</p><p><strong>Nothing sticks.</strong> Fragmented attention encodes memory poorly. You end the day having touched everything and retained nothing.</p><p><strong>Burnout creeps in.</strong> The cruelest part: high-switching days feel exhausting <em>and</em> unproductive. That gap between effort and visible progress is a fast track to burnout.</p><h3>What actually helps</h3><p>You can’t eliminate switching, but you can stop bleeding from it:</p><ol><li><strong>Time-block your deep work.</strong> Protect 2–3 hour windows for your hardest task. Treat them like meetings with your most important client — because they are.</li><li><strong>Batch the shallow stuff.</strong> Check email and Slack at set intervals instead of continuously. Three focused inbox sessions beat forty micro-checks.</li><li><strong>Kill notifications during focus blocks.</strong> Every ping is a lottery ticket for a 23-minute refocus penalty.</li><li><strong>Finish or park deliberately.</strong> Before switching, write one line about where you stopped and what’s next. It drains attention residue and cheapens the reload later.</li><li><strong>Negotiate team norms.</strong> Async-first communication, meeting-free mornings, and explicit response-time expectations make focus a shared default instead of a personal battle.</li></ol><h3>The Bottom line</h3><p>Busyness is not throughput. The people who seem to produce twice as much aren’t working twice as hard — they’re switching half as often. Guard your attention like the finite, expensive resource it is, because every switch has a price, and the bill always comes due.</p><p><em>If this resonated, share it with the colleague who just interrupted you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81d9516dde3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rigidity is a Trap!]]></title>
            <link>https://heyasheet.medium.com/rigidity-is-a-trap-b7afca559735?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7afca559735</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[behavior-change]]></category>
            <category><![CDATA[human-behavior]]></category>
            <category><![CDATA[cognitive-flexibility]]></category>
            <category><![CDATA[tennis]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 19:00:56 GMT</pubDate>
            <atom:updated>2026-08-25T19:00:56.823Z</atom:updated>
            <content:encoded><![CDATA[<p>What a painful first week on the tennis court taught me about the cost of psychological rigidity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MM0ml9mT_QXszx6J.png" /></figure><p>I recently started taking tennis classes, and the first lesson came from my shoulder muscles.</p><p>Every time I tried to smash the ball, my upper body locked up. Instead of a smooth, fluid motion, the stiffness caused a sharp jerk, a flash of pain, and a completely cut-short follow-through. My muscles were fighting the natural trajectory of the swing. In trying to force power through sheer rigidity, I was actually sabotaging the movement, and hurting myself in the process.</p><p>It didn’t take long to realize this wasn’t just a physical bottleneck. The same mechanics apply to how we navigate life.</p><p>When we lock ourselves into rigid beliefs, unyielding expectations, or the subtle trap of thinking we know better than everyone else, we lose our range of motion. We stop absorbing the momentum around us. Rigidity makes us brittle, leaving us prone to reactive outbursts when reality doesn’t bend to our will.</p><p>The antidote isn’t passivity; it’s flexibility. It is about being deeply observant and responsive without being reactive. It requires the quiet humility of knowing you aren’t the center of the universe, believing that you still have everything to learn, in every room you walk into.</p><p>When you release the tension of having to prove yourself or control every outcome, your follow-through becomes effortless. You lessen the possibility of emotional burnout and injury. You move forward making informed, adaptive choices, riding the momentum of life rather than fighting it.</p><p>Keep your grip loose, your mind open, and let the swing finish.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7afca559735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If Everyone Agrees, Someone Isn’t Thinking]]></title>
            <link>https://heyasheet.medium.com/if-everyone-agrees-someone-isnt-thinking-bcf66889a118?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcf66889a118</guid>
            <category><![CDATA[dissent-and-dialogue]]></category>
            <category><![CDATA[conflict-resolution]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[relationships]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 18:11:37 GMT</pubDate>
            <atom:updated>2026-08-24T18:11:37.551Z</atom:updated>
            <content:encoded><![CDATA[<p>How Disagreement Builds Trust and Drives Lasting Success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M0gRLpA3XLvwm9Yo.png" /></figure><p>We often think that a perfect relationship means endless agreement. Whether it is a marriage, a tech company, or a nation, we tend to view arguments as signs of trouble.</p><p>However, the truth is quite the opposite. Complete agreement is often a sign of fear, apathy, or hidden resentment. For any relationship to be truly healthy, it needs two things: dissent and dialogue.</p><p>Here is a breakdown of what these words mean, why they matter, how they work in the real world, and what to do when things go wrong.</p><h3><strong>What is Dissent?</strong></h3><p>Dissent is simply the act of disagreeing with a popular opinion, a rule, or a decision made by someone in power. It is the moment you say, “I see things differently,” or “I do not think this is the right way forward.”</p><p>Dissent is not rebellion for the sake of causing trouble. True dissent comes from a place of care. You speak up because you want to prevent a mistake, improve a situation, or protect the group from a bad choice.</p><h3><strong>What is Dialogue?</strong></h3><p>If dissent is the spark, dialogue is the fireplace that keeps it safe. Dialogue is a conversation between two or more people with the goal of reaching a mutual understanding.</p><p>It is very different from a debate. In a debate, you listen only to find weaknesses in the other person’s argument so you can win. In a dialogue, you listen to learn, understand, and find common ground.</p><h3><strong>Responsibilities of the Person Hearing Dissent</strong></h3><p>When someone disagrees with us, our natural reaction is to become defensive. We might feel attacked or shut down. However, the person or party in power has a major responsibility to handle dissent correctly.</p><p><strong>Listen without punishing:</strong> The leader must create a safe environment. If people are punished, mocked, or demoted for speaking up, they will stop doing it.</p><p><strong>Separate the message from the messenger:</strong> Do not take the disagreement personally. Focus on the facts of the argument rather than who is making it.</p><p><strong>Keep an open mind:</strong> Accept that you might be wrong. Acknowledge the valid points the other person brings to the table.</p><h3><strong>What to Do When the Other Party Refuses to Listen</strong></h3><p>It is easy to practice dialogue when the other person plays by the rules. But what happens when you speak up and the other party shuts down, gets defensive, or completely ignores you? If the person in power refuses to listen, here are the steps you can take.</p><p><strong>Shift from the Topic to the Process: </strong>When someone takes offence, continuing to argue about the facts will not work. Their emotions are now in the way. Stop talking about the disagreement itself and talk about how the conversation is going.</p><blockquote><em>You can say something like: </em>“I feel like you are getting defensive, and that is not my goal. I care about this project, and I want to make sure we are both on the same page. Can we take a step back?”<em> This lowers the temperature.</em></blockquote><p><strong>Check Your Own Tone and Timing: </strong>Before assuming the other person is entirely at fault, look at how you presented your dissent. Did you challenge them in front of a large group? Did you bring it up when they were already highly stressed?</p><blockquote><em>If you put them on the spot, their natural human reaction is to protect their ego. If this happens, back off and request a private, one-on-one meeting later. Say: </em>“Let us drop this for now. Can we chat about this privately tomorrow morning?”</blockquote><p><strong>Ask Questions Instead of Making Statements: </strong>When people feel attacked, they stop listening to statements. A great way to bypass their defense mechanism is to ask open-ended questions. This forces them to think rather than react.</p><blockquote><em>Instead of saying, </em>“Your plan is going to fail because of X,”<em> try asking, </em>“How do you plan to handle the risk of X?”<em> By asking the question, you let them discover the flaw themselves, which makes them much less likely to take offence.</em></blockquote><p><strong>Focus on Shared Goals: </strong>Remind the other person that you are both on the same team. People often take offense because they think your dissent is a personal attack on their ability or character.</p><blockquote><em>Align yourself with their goals by saying: </em>“I know we both want this product to launch successfully,”<em> or </em>“I know we both want this family to be financially secure. I am raising this point only because I want to help us achieve that.”</blockquote><p><strong>Document Your View and Pick Your Battles: </strong>If you have tried everything and they still refuse to care, you have to decide if the issue is worth the fight.</p><p>In a professional setting, write a polite, objective email summarizing your perspective. Frame it as a helpful alternative, not a protest. This creates a record proving you tried to help. After that, let it go. You cannot force someone to listen if they choose to plug their ears. Save your energy for the issues that matter most.</p><h3><strong>The Takeaway</strong></h3><p>Relationships do not break because people disagree. They break because people stop talking honestly, or because leaders stop listening.</p><p>Dissent brings new ideas and flags hidden dangers. Dialogue builds the bridge to resolve those differences. When you combine both, you get relationships that are resilient, innovative, and built to last.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcf66889a118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No, Instagram Reels Has Not Permanently Fried Your Brain (Here is How to Fix Your Focus)]]></title>
            <link>https://heyasheet.medium.com/no-instagram-reels-has-not-permanently-fried-your-brain-here-is-how-to-fix-your-focus-bfb17665b74d?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb17665b74d</guid>
            <category><![CDATA[attention-span]]></category>
            <category><![CDATA[brain-training]]></category>
            <category><![CDATA[social-media-addiction]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 18:04:00 GMT</pubDate>
            <atom:updated>2026-08-24T18:04:00.275Z</atom:updated>
            <content:encoded><![CDATA[<p>The hyperbole surrounding short-form video is wrong, but the attention fragmentation is real. Here is the neurobiology of why you cannot focus and a 4-step protocol to fix it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uQ7eu4HFjTQSgTVn.png" /></figure><p>Scroll through any social feed today and you will inevitably hit a post claiming that Tiktok, Instagram Reels, and YouTube Shorts are “one of the most harmful human creations,” causing “unrecoverable brain damage.”</p><p>It is an easy narrative to buy into. Anyone who has opened an app for “just two minutes” only to blink and realize forty-five minutes have vanished knows the feeling of brain fog that follows. But the idea that your cognitive capacity is permanently ruined is scientifically false.</p><p>Your brain has not been destroyed. It has simply adapted to an environment of hyper-novelty. Thanks to neuroplasticity, it can adapt right back.</p><p><strong>The Mechanics of the Scroll</strong></p><p>Short-form media is not inherently evil, but it is engineered with unprecedented precision. When you swipe through 15-second clips, three things happen simultaneously:</p><p><strong>The Variable Reward Loop:</strong> Like a slot machine, you do not know if the next clip will be boring or hilarious. That unpredictability triggers rapid dopamine spikes, training your brain to seek the next pull of the lever.</p><p><strong>Context Switching at Scale:</strong> In five minutes, you might watch a global news clip, a recipe, a stand-up comedy bit, and a fitness tip. Your brain is forced to rapidly reset its context over and over, draining working memory.</p><p><strong>Threshold Inflation:</strong> Constant exposure to high-frequency novelty raises the baseline threshold of what keeps your attention. Low-stimulation tasks like reading a dense chapter, listening to a lecture, or writing a report suddenly feel unbearably tedious.</p><p>The result is not structural damage. It is an attention calibration problem.</p><p><strong>The 4-Step Focus Restoration Protocol</strong></p><p>Because the brain reorganizes itself based on how you use it, you can retrain your focus using deliberate behavioral shifts.</p><p>1. <strong>Create Behavioral Friction:</strong> Dopamine loops rely on zero friction between impulse and reward. Interrupt the cycle by removing apps from your home screen, setting daily app limits with passwords held by someone else, or deleting the apps to use them only via a mobile web browser.</p><p>2. <strong>Train with 20-Minute Focus Blocks:</strong> Rebuilding focus is like lifting weights. Pick a single, non-digital task and set a timer for 20 minutes. Commit to zero context-switching with no checking tabs and no glancing at your phone. Once 20 minutes feels easy, scale up to 45-minute blocks.</p><p>3. <strong>Consume “Slow” Media:</strong> Swap rapid, low-effort inputs for deep, high-effort inputs. Commit to 30 minutes a day of uninterrupted long-form reading through books, long-form journalism, or physical print. This forces the brain back into sustained processing mode.</p><p>4. <strong>Protect Idle Time:</strong> The urge to grab your phone while waiting in line at the grocery store or sitting at a red light is a symptom of baseline overstimulation. Reclaim those micro-moments. Let your mind wander without immediate digital input to reset your baseline reward expectations.</p><p>Your attention span is not broken. It is just out of shape. Start small, stay consistent, and let neuroplasticity do the heavy lifting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfb17665b74d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context About Context Package in Golang]]></title>
            <link>https://heyasheet.medium.com/context-about-context-package-in-golang-487ef60d9acc?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/487ef60d9acc</guid>
            <category><![CDATA[golang-packages]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Sat, 29 May 2021 05:50:24 GMT</pubDate>
            <atom:updated>2021-05-29T05:50:24.992Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is about the context package of golang and how to get started with it. We’ll also disucss the various use cases of it. After reading this blog user should have comprehensive understanding of context package of golang.</p><h3>Pre-requisites</h3><ul><li><strong>goroutines</strong>: goroutines are the light weight threads which can be used to execute functions concurrently with other functions. You can read more about goroutines at <a href="https://tour.golang.org/concurrency/1">link</a></li><li><strong>channels</strong>: channels can be thought of as a pipe that connect multiple concurrent goroutines. Read more about channels at <a href="https://tour.golang.org/concurrency/2">link</a></li><li><strong>defer</strong>: A defer statement postpones the execution of a function until the surrounding function returns. Read more at <a href="https://tour.golang.org/flowcontrol/12">link</a></li></ul><p><strong>Why should we use </strong><a href="https://golang.org/pkg/context/"><strong>context</strong></a><strong>?</strong></p><p>Let’s take the example of following timeline for any action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*WV1ZVsxNdC9-_wR8KnF75g.png" /></figure><ul><li>An action starts at time instant t0.</li><li>Action completes at time instant t5.</li><li>This action initiates three different goroutines namely, goroutine 1, goroutine 2 and goroutine 3 etc.</li><li>goroutine 1 starts and completes at t1 and completes at t’1.</li><li>goroutine 2 starts and completes at t2 and completes at t’2.</li><li>goroutine 3 starts and completes at t3 and completes at t’3.</li></ul><p>If due to some unavoidable reason if above action has to be terminated at time instant t4, It’s importnat to terminate goroutines 2 and 3 as well in order to avoid the sideeffects that’ll be caused by goroutines 2 and 3. Context provides the ability to time-out and terminate goroutines to handle such cases.</p><h3>Using context | Examples</h3><p><strong>Example 1: </strong><a href="https://play.golang.org/p/oTZHJZNVgzn"><strong>run</strong></a></p><pre>func operationOne(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Println(&quot;context canceled for op-1&quot;)<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d\n&quot;, n)<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }<br><br>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    operationOne(ctx)<br>  }</pre><p><strong><em>Observations from example 1</em></strong></p><ul><li>function operationOne is not being called in a separate goroutine, it’s blocking call and main funtion won’t exits util operationOne returns.</li><li>function operationOne is being passed context as argument.</li><li>context is not being cancelled or being mark as Done.</li><li>operationOne will never return as context is not being cancelled at all.</li></ul><p><strong>Example 2: </strong><a href="https://play.golang.org/p/XNIQxgrNe6T"><strong>run</strong></a></p><pre>func operationOne(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Println(&quot;context canceled for op-1&quot;)<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d\n&quot;, n)<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    go operationOne(ctx)<br>    time.Sleep(5 * time.Second)<br>  }</pre><p><strong><em>Observations from example 2</em></strong></p><ul><li>function operationOne is being called in a separate goroutine.</li><li>function operationOne is being passed context as argument.</li><li>main function will return after 5 seconds from the start of execution.</li><li>context will cancelled at return of main function.</li></ul><p><strong>Example 3: </strong><a href="https://play.golang.org/p/rHnsEO9UvGQ"><strong>run</strong></a></p><pre>func operationOne(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Println(&quot;context canceled for op-1&quot;)<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d\n&quot;, n)<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }<br><br>  func operationTwo(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Println(&quot;context canceled for op-2&quot;)<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationTwo: %d\n&quot;, n)<br>        time.Sleep(250 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }<br><br>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    d := time.Now().Add(5000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    go operationOne(ctx)<br><br>    d = time.Now().Add(10000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    go operationTwo(ctx)<br><br>    time.Sleep(20 * time.Second)<br>  }</pre><p><strong><em>Observations from example 3</em></strong></p><ul><li>function <em>operationOne</em> and operationTwo are being called in a separate goroutines.</li><li>drived context with differenty deadlines are being passed to <em>operationOne</em> and operationTwo functions.</li><li>main function will return after 20 seconds from the start of execution.</li><li>function operationOne will return after 5 seconds as deadline of context passed to it will be reached.</li><li>function operationTwo will return after 10 seconds as deadline of context passed to it will be reached.</li><li>main function will return only after 20 seconds even though <em>operationOne</em> and operationTwo will be completed in first 10 seconds.</li></ul><p><strong>Example 4: </strong><a href="https://play.golang.org/p/jV30esabmo6"><strong>run</strong></a></p><pre>func operationOne(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Println(&quot;context canceled for op-1&quot;)<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d\n&quot;, n)<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func operationTwo(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Println(&quot;context canceled for op-2&quot;)<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationTwo: %d\n&quot;, n)<br>        time.Sleep(250 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    d := time.Now().Add(5000 * time.Millisecond)<br>    ctx, _ = context.WithDeadline(context.Background(), d)<br>    go operationOne(ctx)</pre><pre>    d = time.Now().Add(10000 * time.Millisecond)<br>    ctx, _ = context.WithDeadline(context.Background(), d)<br>    go operationTwo(ctx)</pre><pre>    time.Sleep(3 * time.Second)<br>  }</pre><p><strong><em>Observations from example 4</em></strong></p><ul><li>function <em>operationOne</em> and operationTwo are being called in a separate goroutines.</li><li>drived context with differenty deadlines are being passed to <em>operationOne</em> and operationTwo functions.</li><li>function operationOne will return after 5 seconds as deadline of context passed to it will be reached.</li><li>function operationTwo will return after 10 seconds as deadline of context passed to it will be reached.</li><li>main function will return after first 3 seconds.</li></ul><p>what will happen to other two goroutines?</p><ul><li>This is a case of context leak. even after return of main function other two drived contexts passed to operationOne* and operationTwo will not be discarded. To avoid context leak it’s a good practice to use defer cancel() even for drived contexts</li></ul><p><strong>Example 5: </strong><a href="https://play.golang.org/p/d6ctLQiukYk"><strong>run</strong></a></p><pre>type Key string</pre><pre>  func operationOne(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d : opeartion_id = %s\n&quot;, n, ctx.Value(Key(&quot;op_id&quot;)))<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func operationTwo(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationTwo: %d : opeartion_id = %s\n&quot;, n, ctx.Value(Key(&quot;op_id&quot;)))<br>        time.Sleep(250 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    d := time.Now().Add(5000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    ctx = context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;ONE&quot;)<br>    go operationOne(ctx)</pre><pre>    d = time.Now().Add(10000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    ctx = context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;TWO&quot;)<br>    go operationTwo(ctx)</pre><pre>    time.Sleep(20 * time.Second)<br>  }</pre><p><strong><em>Observations from example 5</em></strong></p><ul><li>function <em>operationOne</em> and operationTwo are being called in a separate goroutines.</li><li>drived context with differenty deadlines are being passed to <em>operationOne</em> and operationTwo functions.</li><li>a variable op_id and it’s value is also being passed with drived context in both the cases.</li><li>main function will return after 20 seconds from the start of execution.</li><li>function operationOne will return after 5 seconds as deadline of context passed to it will be reached.</li><li>function operationTwo will return after 10 seconds as deadline of context passed to it will be reached.</li><li>main function will return only after 20 seconds even though <em>operationOne</em> and operationTwo will be completed in first 10 seconds.</li></ul><p><strong>Example 6: </strong><a href="https://play.golang.org/p/47a0qVAflzm"><strong>run</strong></a></p><pre>type Key string</pre><pre>  func operationOneChild(ctx context.Context) {<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Println(&quot;Child of operation one&quot;)<br>        time.Sleep(100 * time.Millisecond)<br>      }<br>    }</pre><pre>  }</pre><pre>  func operationOne(ctx context.Context) {<br>    n := 1<br>    // go operationOneChild(context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;CHILD OF ONE&quot;))<br>    go operationOneChild(nil)<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d : opeartion_id = %s\n&quot;, n, ctx.Value(Key(&quot;op_id&quot;)))<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func operationTwo(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationTwo: %d : opeartion_id = %s\n&quot;, n, ctx.Value(Key(&quot;op_id&quot;)))<br>        time.Sleep(250 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    d := time.Now().Add(5000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    ctx = context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;ONE&quot;)<br>    go operationOne(ctx)</pre><pre>    d = time.Now().Add(10000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    ctx = context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;TWO&quot;)<br>    go operationTwo(ctx)</pre><pre>    time.Sleep(20 * time.Second)<br>  }</pre><p><strong><em>Observations from example 6</em></strong></p><ul><li>function <em>operationOne</em> and operationTwo are being called in a separate goroutines.</li><li>drived context with differenty deadlines are being passed to <em>operationOne</em> and operationTwo functions.</li><li>function operationOne will return after 5 seconds as deadline of context passed to it will be reached.</li><li>function operationTwo will return after 10 seconds as deadline of context passed to it will be reached.</li><li>main function will return only after 20 seconds even though <em>operationOne</em> and operationTwo will be completed in first 10 seconds.</li><li>nil drived context is being passed to function operationOneChild which will panic with following result.</li></ul><pre>panic: runtime error: invalid memory address or nil pointer dereference<br>  [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xf3966]</pre><pre>  goroutine 9 [running]:<br>  main.operationOneChild(0x0, 0x0)<br>    /tmp/sandbox968352470/prog.go:14 +0xa6<br>  created by main.operationOne<br>    /tmp/sandbox968352470/prog.go:28 +0x40</pre><p><strong>Example 7: </strong><a href="https://play.golang.org/p/gsWBnLDl7Bm"><strong>run</strong></a></p><pre>type Key string</pre><pre>  func operationOneChild(ctx context.Context) {<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Println(&quot;Child of operation one&quot;)<br>        time.Sleep(100 * time.Millisecond)<br>      }<br>    }</pre><pre>  }</pre><pre>  func operationOne(ctx context.Context) {<br>    n := 1<br>    go operationOneChild(context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;CHILD OF ONE&quot;))<br>    // go operationOneChild(nil)<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationOne: %d : opeartion_id = %s\n&quot;, n, ctx.Value(Key(&quot;op_id&quot;)))<br>        time.Sleep(500 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func operationTwo(ctx context.Context) {<br>    n := 1<br>    for {<br>      select {<br>      case &lt;-ctx.Done():<br>        fmt.Printf(&quot;context canceled for %s\n&quot;, ctx.Value(Key(&quot;op_id&quot;)))<br>        return // returning not to leak the goroutine<br>      default:<br>        fmt.Printf(&quot;OperationTwo: %d : opeartion_id = %s\n&quot;, n, ctx.Value(Key(&quot;op_id&quot;)))<br>        time.Sleep(250 * time.Millisecond)<br>        n++<br>      }<br>    }<br>  }</pre><pre>  func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br>    d := time.Now().Add(5000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    ctx = context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;ONE&quot;)<br>    go operationOne(ctx)</pre><pre>    d = time.Now().Add(10000 * time.Millisecond)<br>    ctx, cancel = context.WithDeadline(context.Background(), d)<br>    defer cancel()<br>    ctx = context.WithValue(ctx, Key(&quot;op_id&quot;), &quot;TWO&quot;)<br>    go operationTwo(ctx)</pre><pre>    time.Sleep(20 * time.Second)<br>  }</pre><p><strong><em>Observations from example 7</em></strong></p><ul><li>function <em>operationOne</em> and operationTwo are being called in a separate goroutines.</li><li>drived context with differenty deadlines are being passed to <em>operationOne</em> and operationTwo functions.</li><li>function operationOne will return after 5 seconds as deadline of context passed to it will be reached.</li><li>function operationTwo will return after 10 seconds as deadline of context passed to it will be reached.</li><li>main function will return only after 20 seconds even though <em>operationOne</em> and operationTwo will be completed in first 10 seconds.</li><li>context which is being passed to operationOneChild is non nil, non drived context. This child go routine will also be terminated on cancellation of parent context.</li></ul><h3>Things to keep in mind while using the context</h3><ul><li>Incoming requests to a server should create a Context.</li><li>Outgoing calls to servers should accept a Context.</li><li>The chain of function calls between them must propagate the Context.</li><li>Replace the current Context with the derived Context.</li><li>Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it.</li><li>Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.</li><li>The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines.</li></ul><p>Thanks for reading the blog. If you have any suggestions about plugins to use, please let me know in comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=487ef60d9acc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres indexes and their types]]></title>
            <link>https://heyasheet.medium.com/postgres-indexes-and-their-types-8b0d3dc9ca58?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b0d3dc9ca58</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[index]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 17:15:02 GMT</pubDate>
            <atom:updated>2018-10-04T17:15:02.831Z</atom:updated>
            <content:encoded><![CDATA[<p>Indexes are a common way to enhance database performance. An index allows the database server to find and retrieve specific rows much faster than it could do without an index. Without an index, the system would scan the entire table row by row to find all the matching records. But indexes also add overhead to the database system as a whole, so they should be used sensibly.</p><p><strong>Following command can be used to create the index on one or more columns of a table.</strong></p><pre>CREATE INDEX index-name ON table-name (column-names);</pre><p>While the creation of index only by default Postgres allows only reads to occur on the table. writes(<em>INSERT</em>, <em>UPDATE</em>, <em>DELETE</em>) are blocked. If Index creation takes a long time then it is often unacceptable. Indexes can be created concurrently without blocking writes.</p><p><strong>Following command can be used to create index concurrently on one or more columns of a table.</strong></p><pre>CREATE INDEX CONCURRENTLY index-name ON table-name (column-names);</pre><p><strong>Command to remove the index</strong></p><pre>DROP INDEX index-name;</pre><h3>Index Types</h3><p>Postgres provides several index types namely <em>B-tree</em>, <em>Hash</em>, <em>GIST</em>, <em>SP-GIST</em>, <em>GIN, </em>and <em>BRIN</em>. Each index type uses the different algorithm. By default <em>CREATE INDEX</em> command create <em>B-Tree</em> indexes.</p><h4>Criteria for using different index types</h4><p><strong>B-Tree index</strong></p><p>B-Tree indexes can be used to handle equality and range queries on data that can be sorted into some order. B-tree index will be considered to use by query planner, whenever the indexed column has any of the following comparison operators.</p><pre>&lt;, &lt;=, =, &gt;=, &gt;, BETWEEN, IN, LIKE, ~ etc.</pre><p><strong>Hash index</strong></p><p>B-Tree indexes can be used to handle simple equality queries on data. B-tree index will be considered to use by query planner, whenever the indexed column has comparison using <em>=</em> operator.</p><p><strong>GIST index</strong></p><p>GIST stands for Generalized Search Tree. It is a balanced, tree-structured access method, that acts as a base template in which to implement arbitrary indexing schemes. B-trees, R-trees and many other indexing schemes can be implemented in GIST. Accordingly, the particular operators with which a GIST index can be used vary depending on the indexing strategy (the operator class). the following table has the listing of the operator class, indexed data type, and operators. For more info please visit <a href="https://www.postgresql.org/docs/9.5/static/gist-intro.html">here</a>.</p><p><strong>Following command can be used to create GIST INDEX</strong></p><pre>CREATE INDEX index-name ON table-name USING GIST (column-name operator-class);</pre><h4>GIN index</h4><p>GIN stands for Generalized Inverted Index. GIN is designed for handling cases where the items to be indexed are composite values, and the queries to be handled by the index need to search for element values that appear within the composite items. A GIN index stores a set of (key, posting list) pairs, where a posting list is a set of row IDs in which the key occurs. This can be used to the index array, jsonb types of columns.</p><p><a href="https://www.postgresql.org/docs/9.5/static/gin-builtin-opclasses.html">built-in operator classes</a></p><h3>Unique indexes</h3><p>Uniqueness on the column/columns to be indexed can be enforced by unique indexes. Currently, Only B-tree indexes can be declared unique. When an index is declared unique, multiple table rows with equal indexed values are not allowed. Null values are not considered equal. A multicolumn unique index will only reject cases where all indexed columns are equal in multiple rows. PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table.</p><p>Following command can be used to create the unique index on one or more columns of a table.</p><pre>CREATE UNIQUE INDEX index-name ON table-name (column-names);</pre><h3>Partial indexes</h3><p>A partial index is an index built over a subset of a table; the subset is defined by a conditional expression (called the predicate of the partial index). The predicate can be defined in WHERE clause. The index contains entries only for those table rows that satisfy the predicate. B-Tree partial indexes can also be declared unique.</p><p>Usage of the index for a query can be examined with EXPLAIN command(prepend EXPLAIN in SELECT QUERY). Use ANALYZE command to collect statistics about the distribution of the values in the table. Detailed guidelines can be found <a href="https://www.postgresql.org/docs/9.5/static/indexes-examine.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0d3dc9ca58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch upserts in child tables of a partition set created using pg partman]]></title>
            <link>https://heyasheet.medium.com/batch-upserts-in-child-tables-of-a-partition-set-created-using-pg-partman-31c78c90f51?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/31c78c90f51</guid>
            <category><![CDATA[pg-partman]]></category>
            <category><![CDATA[table-partitioning]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 17:07:54 GMT</pubDate>
            <atom:updated>2018-10-04T17:07:54.722Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is in continuation to the previous post. This post deals with the problem of batch upserts in different child tables of same partition set created using pg_<em>partman</em>.</p><p>This uses <em>ON CONFLICT</em> clause. This clause specifies an alternative action for raising a unique violation or exclusion constraint violation error. The _create<em>parent()</em> function in partman schema allows us to specify the alternative action that <em>ON CONFLICT</em> clause will use in the case when insertion returns a violation error.</p><h3>Specify an action for ON CONFLICT while creating partition set</h3><p>following function creates partition set as in the previous post, but here an action is passed for <em>ON CONFLICT</em> to handle the case of unique constraint violation.</p><pre>select partman.create_parent(p_parent_table := &#39;public.users&#39;, <br>	p_control := &#39;created_at&#39;, <br>	p_type := &#39;partman&#39;, <br>	p_interval := &#39;daily&#39;, <br>	p_automatic_maintenance := &#39;on&#39;,<br>	p_upsert := &#39;ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email, last_name = EXCLUDED.last_name, updated_at = EXCLUDED.updated_at&#39;,<br>	p_debug := TRUE);</pre><p><strong>Note</strong> <br>The column on which ON CONFLICT is used must have unique constraint defined on it. In the above example, the column <em>id</em> is the primary key of the <em>users</em> table defined in the previous post.</p><h3>Insert statement that will cause violation error</h3><pre>insert into users <br>        (id, first_name, last_name, email, created_at, updated_at)<br>	values (1, &#39;foo&#39;, &#39;bar&#39;, &#39;foo@exmplae.com&#39;, now(), now()),<br>	       (2, &#39;abc&#39;, &#39;pqr&#39;, &#39;abc@example.com&#39;, now(), now());</pre><p>Let’s say if records corresponding to above insert statement already exist in different/same child tables then it will end up using the <em>ON CONFLICT</em>clause and will do the defined action. As per this example, it will update the email, last_name and updated_at columns of users table. If there is any suggestion please reach out to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31c78c90f51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-based table partitioning using pg partman]]></title>
            <link>https://heyasheet.medium.com/time-based-table-partitioning-using-pg-partman-74de4bb595f8?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/74de4bb595f8</guid>
            <category><![CDATA[pg-partman]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[table-partitioning]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 16:59:12 GMT</pubDate>
            <atom:updated>2018-10-04T16:59:12.583Z</atom:updated>
            <content:encoded><![CDATA[<p>Table partitioning is splitting of a large table in smaller tables based on values of some attribute in the table. This post is about partitioning tables using <a href="https://github.com/keithf4/pg_partman">pg_partman</a>. It provides the following two types of table partitioning,</p><ul><li>Time-based table partitioning</li><li>Serial id based partitioning. Follow below sections to do time-based table partitioning. I will be using the postgres database to describe the example</li></ul><h3>Installing and setting up pg_partman</h3><ul><li>run following commands to install pg_partman</li></ul><pre>git clone https://github.com/keithf4/pg_partman<br>cd pg_partman<br>make install<br>make NO_BGW=1 install</pre><p>After running above commands successfully, pg_partman should be installed on your machine. running the command in step 4 will provide plain PL/PGSQL functions only. These functions can be used to implement partitioning logic.</p><ul><li>create schema and extension for partman by logging into the postgreSQL database. I am using PostgreSQL interactive terminal to run following commands</li></ul><pre>create database test-partman;<br>\c test-partman;<br>create schema partman;<br>create extension pg_partman schema partman;</pre><h3>Creating a database table</h3><p>Create a table in the database <em>test-partman</em> by running the following query in PostgreSQL interactive terminal.</p><pre>create table users(<br>	id bigserial  primary key,<br>	first_name varchar not null,<br>	last_name varchar,<br>	email varchar not null,<br>	created_at timestamp without time zone not null,<br>	updated_at timestamp without time zone not null<br>);</pre><h3>Creating a partition set</h3><p>A partition set includes a parent table and inherited child tables. To create a partition set _<a href="https://github.com/keithf4/pg_partman/blob/master/doc/pg_partman.md#creation-functions">create_parent()</a>_ is used. During running this function an <a href="https://www.postgresql.org/docs/9.1/static/explicit-locking.html"><em>ACCESS EXCLUSIVE</em></a> lock is taken on the parent table. On running following function a record is added in the part_config table under the partman schema.</p><p>Let me demystify arguments passed to the above function.</p><ul><li>p_parent_<em>table</em> is the name of the parent table, here users table is under the public schema. This argument is of type text.</li><li>p_<em>control</em> is the name of the column in the parent table. Partitioning is based on this column. As partman provides time/serial id based partitioning so data type of this column in the table must of time or integer type. This argument is of type text.</li><li>p_<em>type</em> is about the type of partitioning. Type of partitioning can of native or partman type. In this example, I have used the partman type. This argument is of type text.</li><li>p_<em>interval</em> is the time interval of each partition. In this example, I used ‘daily’ interval. so the child table will be created for each date. This argument is of type text.</li><li>p_automatic_<em>maintenance</em> is used to set the automatic maintenance when run_<em>maintenance()</em> is called. Maintenance is about the creation of new child tables and deleting older child tables based on retention period config. This argument is of type text.</li><li>p_<em>debug</em> turns on the printing the additional debugging information in the console. This argument is of type boolean</li></ul><h3>Setting the retention period</h3><p>To set the retention policy it is required to update the retention column in partman.part_<em>config</em> table for the record created as a result of the above function. run following query to set the retention policy for child tables.</p><pre>UPDATE partman.part_config <br>	SET retention = &#39;5 days&#39;, retention_keep_table=false <br>	WHERE parent_table=&#39;public.users&#39;;</pre><h3>Running maintenance</h3><p>run_<em>maintenance()</em> function is used to run the maintenance on all the tables for which _automatic<em>maintenance</em> is set to ‘on’ or on the specific table whose name is passed as an argument to this function. Following function is used to run maintenance on <em>public.users</em> table.</p><pre>select partman.run_maintenance(<br>	p_parent_table := &#39;public.users&#39;,<br>	p_debug := TRUE);</pre><p>After following above sections successfully you should have implemented time-based partitioning. If you have any suggestions please let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74de4bb595f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up vim for golang]]></title>
            <link>https://heyasheet.medium.com/setting-up-vim-for-golang-6cfb054940d?source=rss-504c3f1187ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cfb054940d</guid>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[vim-go]]></category>
            <category><![CDATA[pathogen]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Asheet ]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 16:43:31 GMT</pubDate>
            <atom:updated>2018-10-04T16:43:31.853Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been using vim for more than three months. Now I do most of my editing on vim. In this post, I shall be describing setting up vim for golang from scratch. Vim config that I shall be posting here is available <a href="https://github.com/asheet-kumar/vim-config">here</a>. I play with my vim configuration frequently to increase productivity and improve my experience with vim. Follow below sections to set up your vim.</p><h3>Set up a plugin manager</h3><p>There are many available plugin managers like <a href="https://github.com/tpope/vim-pathogen">pathogen</a>, <a href="https://github.com/junegunn/vim-plug">vim-plug</a>, <a href="http://vimhelp.appspot.com/repeat.txt.html#packages">vim packages</a> etc. I use <a href="https://github.com/tpope/vim-pathogen">pathogen</a>.</p><ul><li>Run the following command to install <em>pathogen.vim</em>.</li></ul><pre>mkdir -p ~/.vim/autoload ~/.vim/bundle &amp;&amp; \<br>curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim</pre><ul><li>Create a <em>.vimrc</em> file in the home directory.</li></ul><pre>cd ~<br>touch .vimrc</pre><ul><li>Add following lines in the <em>.vimrc</em> file.</li></ul><pre>execute pathogen#infect()<br>syntax on<br>filetype plugin indent on</pre><h3>Set up a file explorer</h3><p><a href="https://github.com/scrooloose/nerdtree">NerdTree</a> gives ability to browse and open files and directories. It allows us to perform simple file operations like <em>create</em>, <em>delete</em>, <em>rename</em> a file or directory. Run following command to install nerdtree.</p><pre>git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree</pre><ul><li>Add following lines in <em>.vimrc</em> to configure nerdtree</li></ul><pre>&quot; open a NERDTree automatically when vim starts up<br>autocmd vimenter * NERDTree<br><br>&quot; open a NERDTree automatically when vim starts up if no files were specified<br>autocmd StdinReadPre * let s:std_in=1<br>autocmd VimEnter * if argc() == 0 &amp;&amp; !exists(&quot;s:std_in&quot;) | NERDTree | endif<br><br>&quot; open NERDTree automatically when vim starts up on opening a directory<br>autocmd StdinReadPre * let s:std_in=1<br>autocmd VimEnter * if argc() == 1 &amp;&amp; isdirectory(argv()[0]) &amp;&amp; !exists(&quot;s:std_in&quot;) | exe &#39;NERDTree&#39; argv()[0] | wincmd p | ene | endif<br><br>&quot; map a specific key or shortcut to open NERDTree<br>map &lt;F2&gt; :NERDTreeToggle&lt;CR&gt;<br><br>&quot; close vim if the only window left open is a NERDTree<br>autocmd bufenter * if (winnr(&quot;$&quot;) == 1 &amp;&amp; exists(&quot;b:NERDTree&quot;) &amp;&amp; b:NERDTree.isTabTree()) | q | endif<br><br>&quot; change default arrows<br>let g:NERDTreeDirArrowExpandable = &#39;▸&#39;<br>let g:NERDTreeDirArrowCollapsible = &#39;▾&#39;</pre><h3>Install a color scheme</h3><p><a href="http://vimcolors.com/">Vim colors</a> is a collection of nice color schemes for <em>vim</em>. I like <a href="http://vimcolors.com/?utf8=%E2%9C%93&amp;order=relevance&amp;query=codeschool"><em>codeschool</em></a> color scheme. To install a color scheme create directory colors under <em>.vim</em> directory then add your color scheme<em>.vim</em>file in <em>colors</em> directory and add following lines in the <em>.vimrc</em> file.</p><pre>syntax enable<br>set background=dark<br>colorscheme _name-of-colorscheme_</pre><h3>Set up support for Go language. Install <a href="https://github.com/fatih/vim-go">vim-go</a> plugin</h3><p>This plugin adds Go language support for Vim. It has many useful features listed <a href="https://github.com/fatih/vim-go/blob/master/doc/vim-go.txt">here</a>. Run the following command to install <em>vim-go</em> plugin.</p><pre>git clone https://github.com/fatih/vim-go.git ~/.vim/bundle/vim-go</pre><p>After installing vim-go plugin, run following command from vim to install necessary binaries.</p><pre>:GoInstallBinaries</pre><p>After following above sections successfully you should have your vim configured for Golang. Vim is highly configurable. You can configure vim as per your preferences. If you have any suggestions about plugins to use, please let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cfb054940d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>