<?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 Zack on Medium]]></title>
        <description><![CDATA[Stories by Zack on Medium]]></description>
        <link>https://medium.com/@xiaweiliang94?source=rss-2881bf2ce4bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b7oUrhavZk4p4VNR</url>
            <title>Stories by Zack on Medium</title>
            <link>https://medium.com/@xiaweiliang94?source=rss-2881bf2ce4bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:28:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xiaweiliang94/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[Recovering with Confidence: A Deep Dive into DBMS Recovery Managers and Recovery Algorithm]]></title>
            <link>https://levelup.gitconnected.com/recovering-with-confidence-a-deep-dive-into-dbms-recovery-managers-and-recovery-algorithm-c2824f7a3b52?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2824f7a3b52</guid>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-development]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Thu, 18 May 2023 02:45:25 GMT</pubDate>
            <atom:updated>2023-05-18T02:45:25.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing what the recovery manager is, the data structure of log files, and one of the most famous recovery algorithms: ARIES.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-D3N4Rvi-7zxmbVUFsrSLw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kehfam">Olu Famule </a>from Unsplash</figcaption></figure><h3>Introduction</h3><p>In the world of Database Management Systems (DBMS), a recovery manager plays a vital role in ensuring the integrity, reliability, and recoverability of data. It is a crucial component that safeguards databases from unexpected failures, such as system crashes, software errors, or hardware malfunctions. To achieve this, recovery managers employ various techniques, such as logging, checkpointing, and transaction rollback. Let’s delve into a detailed discussion of these points below:</p><h3>Logging</h3><p>The log is a history of actions executed by the DBMS. Physically, the log is a file of records stored in stable storage, which is assumed to survive crashes.</p><p>It is written for those actions:</p><ul><li><strong>Updating a page</strong>: When the page is updated by a transaction, an update type record will be added to the log.</li><li><strong>Commit a transaction</strong>: When a transaction decides to commit, it force-writes a commit type log record containing the transaction id.</li><li><strong>Abort a transaction</strong>: When a transaction is aborted, an abort type log record containing the transaction id is appended to the log.</li><li><strong>End</strong>: When a transaction is aborted or committed, some additional actions must be taken beyond writing the abort or commit log record. After all these additional steps are completed, an end type log record containing the transaction id is appended to the log.</li><li><strong>Undoing an update</strong>: When a transaction is rolled back because the transaction is aborted, or during recovery from a crash, a Undoing log is written.</li></ul><h4><strong>WAL (Write Ahead Log) Protocol</strong></h4><p>The Write-Ahead Logging (WAL) protocol is a technique used in computer systems to ensure data consistency and durability in the event of a system crash or failure.</p><p>It forces every update log record must be written to stable storage first before the corresponding page that it describes gets written to disk. If the page changes were written before the log records and there was a crash, we would not know what operations to updo because its log was lost.</p><p>When a transaction is committed, the database updates are written to the log file first, and then the changes are applied to the database files, even if a no-force approach is being used. In the event of a crash or failure, the database can recover by replaying the log file to restore the database to its previous state.</p><p>These rules above are known as the WAL protocol, which guarantees that every log records are available when a crash happened.</p><h3>Data structure for recovery</h3><h4>Log records</h4><p>After taking a look at all those protocols of the log, let’s discuss what to log, and what information will be stored in the log file. We can split the metadata in the log into two different parts: one is the common part which is the same as all different log records, and another is the additional part which depends on the type of the log record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*z32lRcyuikidJ9GC_8kEQg.png" /><figcaption>The common part of the log record</figcaption></figure><p><strong>Common Part</strong></p><p><strong>LSN</strong>: Every transaction that modifies the data in the database generates one or more log records. Each of these log records is assigned a unique <strong>log sequence number (LSN)</strong> that identifies the order in which the transaction occurred. The purpose of the LSN is to provide a way to identify and track the order of transactions and changes made to the database. The LSN is an important component of database recovery mechanisms, which use the transaction log to restore the database to a previous state in the event of a failure or other problem.</p><p><strong>prevLSN</strong>: To link the different records, the log also contains the ‘<strong>prevLSN</strong>’ which refers to the log sequence number (LSN) of the previous log record that was written before the current log record.</p><p><strong>transID</strong>: The <strong>transID</strong> is the id of the transaction generating this log record.</p><p><strong>Type</strong>: This field indicates the type of the log record. As mentioned above, the type of log records are update type; commit type; abort type; end type; and compensation log record.</p><p><strong>Additional Part</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eUNsVzbAH3d30UO6iJECQ.png" /><figcaption>The additional part of the log record</figcaption></figure><p>For the update log record, it contains several additional fields except for the common part.</p><p><strong>pageID</strong>: The page id of the modified page.</p><p><strong>length</strong>: The length in bytes of the change.</p><p><strong>offset:</strong> The offset of the change.</p><p><strong>before-image</strong>: The value before change.</p><p><strong>after-image</strong>: The value after updating.</p><h4>Transaction table</h4><p>In a database management system, a transaction table is a data structure that is used to keep track of the status of transactions that are currently active or have recently been completed. It contains:</p><p><strong>TransID</strong>: Transaction ID</p><p><strong>State</strong>: Status of the transactions. The status of a transaction can be that it is in progress, is committed, or is aborted.</p><p><strong>LastLSN</strong>: The LSN of the most recent log record for this transaction.</p><h4>Dirty page table</h4><p>This table contains one entry for each dirty page in the buffer pool, that is, the page contains data that has been changed but not yet written to disk. The entry contains a field <strong>recLSN</strong>, which is the LSN of the first log record that caused the page to become dirty.</p><h4>Checkpoint</h4><p>The checkpoint is a snapshot of the DBMS state which can reduce the amount of work to be done while restarting. Checkpointing in a DBMS is a process that writes the current state of the database from memory to disk to ensure the database is consistent and up-to-date. This includes all transactions that have been committed, as well as any changes that have been made to the database but not yet committed. It is triggered periodically or when the amount of modified data reaches a certain threshold. While it does help with faster recovery in case of a system failure, its primary purpose is to ensure the durability and consistency of the data.</p><h3>Introduction to ARIES</h3><p>ARIES stands for “Algorithm for Recovery and Isolation Exploiting Semantics”, it is a recovery algorithm that is designed to work with a steal, no-force approach and is used to ensure that a database can be restored to a consistent state after a failure, such as a system crash or power outage. ARIES was developed in the late 1980s by researchers at IBM, and it has since become a widely used algorithm for database recovery in many commercial database management systems.</p><p>When the ARIES algorithm is invoked after a crash, these three phases will be executed:</p><ol><li>Analysis Phase: In this phase, ARIES analyzes the log file to determine the most recent checkpoint and the transactions that were active at the time of the checkpoint. It also determines the transactions that were in progress at the time of the failure by scanning the log backward from the end to the most recent checkpoint.</li><li>Redo Phase: In this phase, ARIES applies the log records that were written after the most recent checkpoint to bring the database up to the state it was in just before the failure. This is done by replaying the log records in forward order.</li><li>Undo Phase: In this phase, all the transactions that did not commit will be undone, so that the recovered database reflects only the actions of committed transactions.</li></ol><h3>ARIES Recovery Algorithm</h3><p>The previous sections are mainly about what information we maintain to recover the whole database, now in this section let’s focus on the ARIES algorithm and take a look at how the recovery manager uses this algorithm and the previous metadata that we have to reconstruct the database.</p><p>When a database crashes, all we have are the logs in the disk, and the ARIES will use those logs and proceed in three phases:</p><p><strong>Analysis Phase:</strong></p><p>In this phase, the recovery manager mainly does three things:</p><ol><li>Locate the point in the log at which to start the next phase — Redo phase</li><li>Figure out the transactions that were active at the time of the crash and must be undone.</li><li>Determines pages in the buffer pool that were dirty at the time of the crash.</li><li>It starts from the most recent checkpoint all the way to the end of the log. And for each record in the log, this phase follows these rules:</li></ol><ul><li>Record is an END:</li></ul><p>Remove this transaction from the transaction table</p><ul><li>Record is not an END:</li></ul><p>Add transaction to the transaction table if it does not exist</p><p>Set transaction’s lastLSN to the record’s LSN</p><ul><li>If the record is a update record:</li></ul><p>Add the transaction into the dirty page table if it does not exist</p><p>Set every dirty page recLSN to the record’s LSN</p><ul><li>If is COMMIT or ABORT record:</li></ul><p>If the log record is a commit record, the status is set to C, otherwise, it is set to U (indicating that it is to be undone).</p><p>For the final pass, it is important to take into account that transactions might have been in various stages such as running, committing, or aborting during the crash occurrence. Therefore, it becomes necessary to reevaluate the transactions in the transaction table. Remember these two guidelines while conducting the final pass:</p><ul><li>If the transaction was in the process of committing, we add an END record to the log and remove it from the transactions table.</li><li>If the transaction was running, we change its status in the transaction table to aborting and add an ABORT record to the log.</li></ul><p><strong>Redo Phase</strong></p><p>Once the analysis phase is done, we can start the redo phase. In this phase, we redo all the transactions that haven’t written their changes to disk before the crash, all the metadata that we mentioned before will help us determine which transaction should be redone. This phase will start from the smallest recLSN in the dirty page table, scan forward until the end of the log file and redo all the UPDATE and CLR operations that do not meet any of the conditions below, which means if a transaction meets any of the three conditions we won’t redo it:</p><ul><li>If the affected page is not in the dirty page table: it means that all the changes that this transaction did have been written to disk before the crash, so we don’t need to redo it.</li><li>The affected page is in the dirty page table but its recLSN in the dirty page table is greater than the LSN of the log record being checked.</li><li>The affected page’s pageLSN on the disk is greater than or equal to the LSN of the current log record</li></ul><p><strong>Undo Phase</strong></p><p>Finally, we will start the undo phase, unlike another two phases, the undo phase scan back from the end of the log. It will check all the transactions that were active at the time of the crash and abort them.</p><p>In this phase, there has one metadata to track: the <em>undoNextLSN</em>. This field stores the LSN of the operation that we want to next undo for that transaction (derived from the prevLSN of operation currently being undone).</p><p>And once we finish undoing all the operations in one transaction, we will write the END record for that transaction.</p><p>Here is the pseudocode for the undo phase:</p><pre>toUndo = {lastLSN of all transactions in transaction table}<br>while !toUndo.isEmpty():<br> currRecord = max(toUndo)<br> if currRecord.type == CLR:<br>  if currRecord.undoNextLSN == NULL:<br>   # Write END record for currRecord.transaction_id<br>  else:<br>   toUndo.add(currRecord.undoNextLSN)<br> else:<br>  if currRecord.type == UPDATE:<br>   # Undo update in the DB<br>        # Write CLR record for currRecord.transaction_id<br>        if currRecord.prevLSN != NULL:<br>         toUndo.add(currRecord.prevLSN)<br>        if currRecord.prevLSN == NULL:<br>         # Write END record for currRecord.transaction_id<br> toUndo.remove(currRecord)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2824f7a3b52" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/recovering-with-confidence-a-deep-dive-into-dbms-recovery-managers-and-recovery-algorithm-c2824f7a3b52">Recovering with Confidence: A Deep Dive into DBMS Recovery Managers and Recovery Algorithm</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The syntax of URLs: Decoding All Those %$#@! Symbols]]></title>
            <link>https://levelup.gitconnected.com/the-syntax-of-urls-decoding-all-those-symbols-5fae699237f4?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fae699237f4</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[url]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 12:50:17 GMT</pubDate>
            <atom:updated>2023-04-25T12:50:17.130Z</atom:updated>
            <content:encoded><![CDATA[<p>This article provides a comprehensive overview of the syntax of URLs, breaking down each component and its function in web addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa_n61kpI8dm6YvA3veJjA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fonsheijnsbroek_amsterdam_photos">Fons Heijnsbroek</a><strong> </strong>from Unsplash</figcaption></figure><p>A URL (Uniform Resource Locator) is a string of characters that identifies the location of a resource on the internet. It is a standard way of specifying the address of a web page, file, or other resource on the internet.</p><p>And most URLs use a general URL syntax, which contains nine different parts:</p><pre>&lt;scheme&gt;://&lt;user&gt;:&lt;password&gt;@&lt;domain&gt;:&lt;port&gt;/&lt;path&gt;;&lt;params&gt;?&lt;query&gt;#&lt;frag&gt;</pre><p>Here is a list of a brief introduction to these nine parts:</p><ul><li><strong>scheme</strong>: Which protocol to use, such as HTTP, HTTPS, FTP</li><li><strong>user</strong>: The username some schemes required</li><li><strong>password</strong>: The password that the username needs</li><li><strong>domain</strong>: The domain name identifies the location of the resource on the internet. It can be an IP address or a registered domain name and may include subdomains, such as <a href="http://www.example.com/">www.example.com</a> or subdomain.example.com</li><li><strong>port</strong>: The port number on which the server hosting the resource is listening</li><li><strong>path</strong>: Path parameters are used to identify a specific resource or object within the URL hierarchy. It usually separated from previous parts by /.</li><li><strong>params</strong>: Used by some schemes to specify input parameters. Params are name/value pairs. A URL can contain multiple params fields, separated from themselves and the rest of the path by semicolons (;).</li><li><strong>query</strong>: Separated from the previous URL parts by ?, this parameter is an optional parameter that provides additional information to the server or modifies the behavior of the request.</li><li><strong>frag</strong>: The fragment identifier is an optional string of characters that identifies a specific section of the resource, such as a section within an HTML document or a specific time stamp within a video. It is separated from the URL by a hash symbol (#).</li></ul><p>Now I think you already have a brief understanding of the URL syntax, now let’s discuss more details using examples:</p><h3>&lt;scheme&gt;</h3><p>The protocol or schema in a URL (Uniform Resource Locator) is a string that identifies the method used to access the resource on the internet. It specifies the rules and conventions for communication between web servers and clients, including how data is transferred and how errors are handled.</p><p>There are several different protocols or schemas that can be used in URLs, including:</p><ol><li>HTTP (Hypertext Transfer Protocol): This is the most commonly used protocol for transferring data on the internet, and is used to transfer web pages and other resources between web servers and clients.</li><li>HTTPS (HTTP Secure): This is a secure version of HTTP that encrypts data in transit using SSL/TLS encryption. It is used to protect sensitive data, such as login credentials and payment information.</li><li>FTP (File Transfer Protocol): This protocol is used to transfer files between servers and clients, and is commonly used for uploading and downloading files to and from a web server.</li><li>SMTP (Simple Mail Transfer Protocol): This protocol is used for sending email messages between servers, and is commonly used by email clients and servers.</li><li>Telnet: This protocol is used to remotely access and control servers and other network devices.</li><li>SSH (Secure Shell): This protocol is used to provide secure remote access to servers and other network devices, and is commonly used for managing and administering servers.</li></ol><p>In a URL, the protocol or schema is specified at the beginning of the URL, followed by a colon and two forward slashes (//). For example, the URL “<a href="https://www.example.com/">https://www.example.com/</a>&quot; specifies that the resource is accessed using HTTPS.</p><h3>&lt;user&gt; &amp; &lt;password&gt;</h3><p>The username and password in a URL are used for authentication purposes and allow the user to access resources that require authentication. Many servers require a username and password before you can access its data.</p><p>There is an example in the FTP server:</p><pre>ftp://anonymous:my_passwd@ftp.prep.ai.mit.edu/pub/gnu</pre><p>This is the example for HTTP:</p><pre>https://username:password@example.com/path/to/resource</pre><h3>&lt;domain&gt; &amp; &lt;port&gt;</h3><p>In a URL, the host and port refer to the destination server and the network port that the server is listening on for incoming connections. To extract correct information, we need to know which machine is hosting the resource and where on that machine we can find the data on that machine. This is why we need these two parameters in the URL.</p><p>The host is the domain name or IP address of the server that you want to access. It is usually located after the protocol and the two forward slashes (//) in the URL, and before the path, query parameters, and fragment identifier. For example, in the URL “<a href="https://www.example.com/path/to/resource">https://www.example.com/path/to/resource</a>&quot;, the host is “<a href="http://www.example.com/">www.example.com</a>&quot;.</p><p>The port is a number that identifies a specific network port on the server that you want to connect to. It is usually specified after the host, separated by a colon (“:”) character. If the port is not specified, the default port for the protocol is used (for example, port 80 for HTTP, port 443 for HTTPS, and port 21 for FTP). For example, in the URL “<a href="https://www.example.com/path/to/resource">https://www.example.com:443/path/to/resource</a>&quot;, the port is “443”.</p><h3>&lt;path&gt;</h3><p>The path in a URL refers to the specific resource or page on the server that the client wants to access.</p><p>The path is a hierarchical sequence of directory and file names that represent the location of the resource on the server’s file system. It starts after the host and port (if specified) and ends before any query parameters or fragment identifier.</p><p>For example, in the URL “<a href="https://www.example.com/path/to/resource.html">https://www.example.com/path/to/resource.html</a>&quot;, the path is “/path/to/resource.html”. The server would use this path to locate the specific HTML file that the client wants to access and return it in the HTTP response.</p><h3>&lt;params&gt;</h3><p>URLs often need more than just an address to ensure that servers can access the correct resources. For example, some protocols like FTP require additional information to properly transfer data, such as specifying whether to use binary or text mode. Using the wrong mode can result in scrambled or corrupted data, which can cause errors or make resources unusable.</p><p>This component usually starts with a semicolon character (;):</p><pre>https://www.example.com;type=d</pre><p>In the example URL above, the ‘type’ is the name of the param and the value is ‘d’</p><h3>&lt;query&gt;</h3><p>Sometimes a simple host or path isn’t enough to specify a request and additional information is needed. This is where the query component of a URL comes into play. The query component is used to pass specific information to the server about the request being made. Parameters in the form of key-value pairs can be added to a URL and are typically included at the end of the URL after a question mark (?). In this article, we’ll take a closer look at query parameters and their role in helping to pass specific information between web clients and servers.</p><p>The format for a parameter in a URL is as follows:</p><pre>https://www.example.com/path/to/resource?key1=value1&amp;key2=value2</pre><p>In this example, the URL contains two parameters, “key1” and “key2”, with values of “value1” and “value2”, respectively. The parameters are separated by an ampersand (&amp;), and the entire parameter string is preceded by a question mark (?).</p><p>The main difference between the query components and params components is the query components start at the question mark (?), while params components start at the semicolon (;), and param components are often used to provide additional metadata about a resource, such as content type or language, while query components are used to modify the behavior of a server or application, such as filtering search results or sorting data.</p><h3>&lt;frag&gt;</h3><p>Some resource types like HTML can be divided into more detailed components, for example, one HTML page might contain several image elements, and the URL provides a way to identify such sections within certain resources called fragment components. The fragment component in a URL is a type of identifier that refers to a specific location within a web page or document. It is also known as a fragment identifier or hash.</p><p>The fragment component is added to the end of a URL after a hash (#) symbol, followed by a string of characters that identifies a specific section or element within the page. When the URL is accessed, the browser will scroll to the specified section or element within the page.</p><p>For example, consider the following URL:</p><pre>https://www.example.com/about#team</pre><p>In this example, the fragment component is “#team”, which refers to a specific section or element within the “about” page on the example.com website. When the URL is accessed, the browser will scroll to the section or element of the page that is identified by the “team” fragment.</p><p>Thanks for reading!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fae699237f4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-syntax-of-urls-decoding-all-those-symbols-5fae699237f4">The syntax of URLs: Decoding All Those %$#@! Symbols</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Your Data: A “more lazy” way to add double quotes into your javascript “JSON”.]]></title>
            <link>https://javascript.plainenglish.io/transforming-your-data-a-more-lazy-way-to-add-double-quotes-into-your-javascript-json-3ff1ffd65143?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff1ffd65143</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 14:18:10 GMT</pubDate>
            <atom:updated>2023-04-20T14:18:10.098Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing an easy way to convert JavaScript Object into JSON</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNvKbVD0ubf5Zf2AUX1Hlw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin">Caspar Camille Rubin</a> from Unsplash</figcaption></figure><p>An object is a javascript data type, a collection of key-value pairs, where each key is a string and each value can be of any type, including other objects. And the JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.</p><p>JSON data is also represented as a collection of key-value pairs, and also has a similar syntax to the javascript object, thus lots of people often confuse these two different things.</p><h3>JavaScript Objects VS JSON</h3><ul><li>JavaScript Objects can be without double quotes but all the keys in JSON should be wrapped with double quotes.</li></ul><pre>// Javascript object<br>{ name: &quot;John&quot;, age: 22 }<br>// JSON<br>{ &quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 22 }</pre><ul><li>JavaScript Objects can have functions as the value, but the JSON cannot.</li></ul><pre>// JavaScript object<br>{name: &quot;John&quot;, getFullName: function(){return &quot;John Wick&quot;}}<br>// JSON can&#39;t contain function<br>{&quot;name&quot;: &quot;John&quot;}</pre><ul><li>JavaScript can only be used in JavaScript, but JSON can be used by other programming language.</li></ul><h3>Convert JavaScript Object to JSON</h3><p>Now, let’s talk about how to convert JavaScript Objects to JSON.</p><p>We can use the command JSON.stringify() to turn a JavaScript Object string into JSON, but I&#39;m too lazy to write any code 🤪.</p><p>We can also add the double quotes manually, but what if the Object contains more than 100 key-value pairs 🤯?</p><p>There is an easier way to implement that: using Google Chrome.</p><p>What we need to do is just open a Google Chrome tab, right click, and select inspect to open the Google Chrome Dev Tool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdVo0wjPKdYlcn1FirsIrg.png" /><figcaption>Open Google Chrome Dev Tool</figcaption></figure><p>Then navigate to Console Tab, and paste the JavaScript Object that you want to convert into the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44PLioUhA5YNp-0_VRn8dw.png" /></figure><p>Press enter.</p><p>OK, now you will see a well-formatted JSON appears, select it, and copy it, now you get JSON-type data!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNWnS7hdIpGUIQmhIdY9tA.png" /></figure><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff1ffd65143" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/transforming-your-data-a-more-lazy-way-to-add-double-quotes-into-your-javascript-json-3ff1ffd65143">Transforming Your Data: A “more lazy” way to add double quotes into your javascript “JSON”.</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Data Retrieval Efficiency: how does the basic tree structure affect DBMS]]></title>
            <link>https://levelup.gitconnected.com/maximizing-data-retrieval-efficiency-how-does-the-basic-tree-structure-affect-dbms-7af37e117735?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7af37e117735</guid>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 20:20:04 GMT</pubDate>
            <atom:updated>2023-04-18T20:20:04.147Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing tree-based indexing in current DBMS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bn_rymdjHiTq0J6nmHNe0A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ferminrp">Fermin Rodriguez Penelas</a><strong> </strong>from Unsplash</figcaption></figure><p>The modern DBMS uses multiple techniques to store and retrieve data more efficiently. One way is to organize data entries through the hash function, another way to organize data items is to build a tree structure.</p><p>If you are interested in hash-based indexing, you can look at this article:</p><p><a href="https://medium.com/gitconnected/exploring-the-role-of-hash-based-indexing-in-modern-database-architecture-4d882f294d05">https://medium.com/gitconnected/exploring-the-role-of-hash-based-indexing-in-modern-database-architecture-4d882f294d05</a>.</p><h3>Introduction</h3><p>Tree-based indexing is a highly efficient method that helps DBMS retrieve and organize data. The data is arranged in a tree-like structure, where each node encompasses a range of values and pointers to its child nodes. The data entries are located in the leaf nodes, which are the lowest level of the tree. When a query is executed, the DBMS can use the ranges and pointers of each node to quickly locate the data that matches the query conditions, without the need to scan through the entire database. Retrieving a node only requires a single disk I/O, making this technique a powerful tool for improving database query performance, particularly when dealing with large datasets.</p><p>The image below shows an example, this example uses age as a search key, and we can find correct data entries through this tree structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XA_OfRT_rDXv8LP1xZK3w.png" /><figcaption>Tree-based indexing structure</figcaption></figure><p>If we want to retrieve all people&#39;s information whose age ranges from 30 to 44, we can start from the root node first, then go to node A, then node B, then the second child node of node B contains all the data entries.</p><p>Same as hash-based indexing, tree-based indexing can also be split into two different types of structure: static index structure: ISAM tree, and dynamic index structure: B+ tree. Let’s discuss each structure in detail.</p><h3>Indexed Sequential Access Method (ISAM)</h3><p>In the ISAM tree structure, the data entries are exclusively stored in the leaf nodes, which may also have overflow pages attached to them. It is worth noting that the leaf nodes are sorted sequentially in the file to support range search when the storage structure is established. Conversely, the non-leaf nodes hold the index information required to locate the correct data entries, but they do not contain any data entry information themselves. As previously mentioned, the ISAM tree structure is wholly static, with the exception of the overflow pages.</p><h4>Search</h4><p>Now, let’s take a look at how the ISAM tree implements all those basic operations.</p><p>When it comes to search operations, the ISAM tree follows a straightforward process that is similar to the example in the previous section. For an equality search, the process begins at the root node and follows the subtree based on the index information in the root node, ultimately reaching the leaf node that contains the required data entry. In the case of a range search query, the starting point in the leaf level is determined in a similar fashion, and all the data pages within the specified range are retrieved in order, including any overflow pages that may be necessary.</p><p>The following example illustrates the search operation in the ISAM index structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFVUqLSHta3XiWPTkj_WCw.png" /><figcaption>Sample ISAM tree</figcaption></figure><p>If we want to search for a data item whose value is 37, we will start at the root node first, since 37 is less than 40, then we will go to the left child tree of the root node, then since 37 is larger than 33, then go to the third child tree, in the end, we can find that data entry in this data page.</p><p>For a range search, if we want to retrieve the value range from 15 to 40, we can first get the start point of this range which is 15. Then start from the root node again, then goes to the left child tree, and find the 15 in the first data page. Since all the leaf nodes are sorted sequentially, we can then start from 15, and retrieve 20, 27, 33, and 37 sequentially until 40.</p><h4><strong>Insertion and Deletion</strong></h4><p>To insert a record, we should first locate the position of the correct page at the leaf level, and then add that record to this page, if the page is full, an overflow page will be added.</p><p>As for deletion, it will be handled by removing the data entry that we want to delete. Same as insertion, if the data entry is the last one in the overflow page, then simply remove that overflow page. And if the data entry is the last record on the primary page, just keep that page empty as it is and serve this empty page as a placeholder for future insertion.</p><h3>B+ Trees</h3><p>Static structure indexing, such as ISAM or static hash-based indexing, faces a common issue whereby the overflow page chains can become increasingly lengthy and adversely impact performance as the file size grows. To address this problem, dynamic indexing techniques like the B+ tree were developed.</p><p>There are some properties of the B+ tree in DBMS:</p><ul><li>Data entries are only stored in leaf nodes</li><li>The B+ tree is of the order n where n is fixed for every B+ tree, all nodes contain the same amount of values</li><li>All internal nodes contain keys</li><li>All leaf nodes are at the same height</li><li>The leaf nodes are linked using a linked list</li></ul><p>Here is an example, each non-leaf entry is a (key value, node pointer) pair, at the leaf level, the entries are actual data records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwgcuO_VkFgD62K4rnW5jA.png" /><figcaption>Example of a B+ tree</figcaption></figure><h4><strong>Search</strong></h4><p>The search function is used to find the leaf node in which a given data entry belongs. Here is the pseudocode of this algorithm:</p><pre>func find_data(search key value K) returns nodepointer<br>  // Given a search key value, return its leaf node<br>  return tree_search(root, K)<br><br>func tree_search(nodepointer, search key value K) returns nodepointer<br>  if nodepointer is a leaf, return nodepointer;<br>  // Suppose each internal node&#39;s length is M, Pi represent pointer of the ith element in current node<br>  else<br>    if K &lt; K1 then return tree_search(P0, K); // If the value that we search less than the smallest value in current node, search the left most child tree<br>    else<br>      if K &gt;= Km then return tree_search(PM, K); // If the value larger than the largest value, search for the right most child tree<br>      else<br>        find i such that Ki &lt;= K &lt; Ki+1; // Else find a position i where the ith element less or equal to the value, (i+1)th is larger than the value, follow the ith pointer<br>        return tree_search(Pi, K)</pre><p>Using the example above, if we want to search for 2, we should follow the first pointer since 2 &lt; 13.</p><p>To search for 14, we follow the second pointer, since 13 &lt; 15 &lt; 17.</p><h4>Insert</h4><p>To insert a data entry, we first find the leaf node that this data entry belongs to, then insert it into this node. The insert algorithm makes sure:</p><ul><li>No overflow chain will be created after insertion, even when the node is full</li><li>The tree remains balanced: all paths from the root to leaf nodes will be the same after insertion</li><li>When splitting is required, we need to split that leaf node into two nodes, first contains ceil((m-1)/2) value, another contains the left, this will make sure this B+ tree&#39; balance is not alerted.</li></ul><p>I’ll discuss more details in an example, still using the B+ tree above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwgcuO_VkFgD62K4rnW5jA.png" /></figure><p>To insert ‘8’ into this tree, we first need to find out which leaf node it belongs to. Apparently, ‘8’ belongs to the leftmost leaf node. But this node is already full, then what should we do?</p><p>Because the B+ tree will not create any overflow page for insertion, we can’t simply create a new node and link it to the leaf node, what we need to do is to split the node into two nodes first, one contains ‘2’ and ‘3’, another contains ‘5’ ‘7’ and new added ‘8’. The figure below shows the node after splitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpfXnDAYnrCpJiS-FbXv3Q.png" /><figcaption>Split Leaf node during the insert of ‘8’</figcaption></figure><p>After splitting, we need to insert the newly generated node back into the tree structure. So, firstly, find out the ‘5’ which is the entry pointing to this node, and ‘copy it up’ to the parent node which is the root node in this example.</p><p>But since the root node is also full, then we need to split the root node again to insert ‘5’. Similar to leaf nodes, the root node should split in the middle, thus it will become: ‘5’, ‘13’ and ‘17’ ‘24’ ‘30’. But unlike the leaf node ‘copy up’ the first value of the split node, for internal nodes, we just ‘push up’ the entry key, instead of copy and push up. Thus the tree’s height will increase and the whole structure will change to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypo14lY4e9qLWnXCK6qZcw.png" /><figcaption>B+ after inserting ‘8’</figcaption></figure><h4><strong>Delete</strong></h4><p>The delete algorithm takes a data entry, finds the leaf node that this data entry belongs to, and then deletes this entry.</p><p>The figure below is an example that I’m using to illustrate the delete algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypo14lY4e9qLWnXCK6qZcw.png" /><figcaption>Example B+ tree</figcaption></figure><p><strong>When the value belongs to a node that has more than 2 values</strong></p><p>To delete ‘19’, we first need to find ‘19’, which is in the fourth leaf node, then we simply delete it and nothing will change because this leaf node still has two values left.</p><p><strong>Redistribution of leaf node after deletion</strong></p><p>Let’s keep using the tree after deleting ‘19’.</p><p>To delete ‘20’ after removing ‘19’, the process is slightly different. First, we must locate the leaf node containing ‘20’ and delete it. Subsequently, we notice that there is only one data entry left in that node after removing ‘20’, which is less than half of the maximum allowable number of keys in one node. As a result, we must borrow the first entry in the parent node, which is ‘24’, move it down to this leaf node, and remove it from the original node it belonged to. After borrowing ‘24’, ‘27’ becomes the first data entry in the fifth leaf node, so we ‘copy up’ this entry to its parent node. The tree looks like the image below after removing ‘19’ and ‘20’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZRfgXYmMxhbKIoBJdK73A.png" /><figcaption>B+ tree after removing ‘19’ and ‘20’</figcaption></figure><p><strong>Merging two nodes after deletion</strong></p><p>If we try to delete ‘24’, we will find another problem. After removing ‘24’, this leaf node will only have ‘22’, and since its sibling node has only two values ‘27’ and ‘29’, thus, we should merge these two nodes together.</p><p>In contrast to the splitting process, we will merge the data entries in the first, the second non-leaf nodes, and the index entry of their parent. In this example, we will merge ‘22’, ‘27’, and ‘29’, after merging, ‘22’ will be the lowest entry of this merged leaf node, and ’27’ in its parent node will be removed.</p><p>Removing ‘27’ created a non-leaf node that has just one entry, less than the minimum number of entries that one node should contain. And since this parent page’s sibling page contains only two numbers, thus we can merge these two non-leaf pages together.</p><p><strong>Redistribution of entries between non-leaf-level pages</strong></p><p>The above example illustrates a situation in which we can merge two non-leaf-level pages, but what if the total number of data entries in two pages is larger than the maximum number of entries that one node can contain?</p><p>Here is another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOry2tLgfbvTcMGujz9mIA.png" /><figcaption>Redistribution of non-leaf nodes example</figcaption></figure><p>In the given example, the second layer nodes contain more than 4 values, which means that even if we delete one of them, it is impossible to fit all data entries into a single node. Therefore, simply removing one non-leaf node is not a viable option. Instead, we must redistribute the values between the non-leaf node and its sibling nodes.</p><p>Since the non-leaf node containing the key value 30 has a sibling that can spare entries, we move half of the entries over from this sibling node. After that, the ‘17’ becomes the new low-key value, thus similar to redistribution in the insertion section, we move ‘17’ to the root node and ‘push down’ the original value ‘22’.</p><p>After redistribution, the tree looks like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETVOWP9ScpsNL5OJaYA1Hw.png" /><figcaption>Example tree after redistribution</figcaption></figure><h3>Summary</h3><p>To sum up, this article provides an introduction to tree-based indexing, which is one of the most commonly used indexing techniques in DBMS. It mainly focuses on the details of two popular types of tree-based indexing, ISAM and B+ tree. In each section, the article uses graphs and examples to explain how ISAM and B+ tree implement insert and delete operations.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7af37e117735" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/maximizing-data-retrieval-efficiency-how-does-the-basic-tree-structure-affect-dbms-7af37e117735">Maximizing Data Retrieval Efficiency: how does the basic tree structure affect DBMS</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Role of Hash-Based Indexing in Modern Database Architecture]]></title>
            <link>https://levelup.gitconnected.com/exploring-the-role-of-hash-based-indexing-in-modern-database-architecture-4d882f294d05?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d882f294d05</guid>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 17:37:11 GMT</pubDate>
            <atom:updated>2023-04-07T17:37:11.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing one of the most popular indexing techniques: hash-based indexing, explaining its different types and their structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0qYamLxrVSgJvZZ5.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jakeblucker">Jake Blucker</a> from Unsplash</figcaption></figure><p>Suppose we have a database that contains huge amount of data, and now we need to retrieve some of the data from it, how does DBMS find out those data and send them to us? An easy way is to search all the index values and reach the desired data. But since this database is too big, it will be inefficient to find data through this index structure. Hashing is one of the techniques to solve this problem, with the help of hashing, we can retrieve data faster and easier.</p><h3>What is Hash-based Indexing</h3><p>The hash-based indexing are using a technique called hashing to quickly find values that match the given search key value. For example, if the files of student records are hashed on name, then we can get all student information based on the name that we provided.</p><p>In this structure, we have several <strong>buckets</strong>; all the data in a file are grouped in buckets, and the buckets and <strong>search keys</strong> are linked through the <strong>hash function</strong>. The first bucket consists of the primary page and additional pages linked in a chain. Given a bucket number, a hash-based index structure allows us to retrieve the primary page for the bucket in one or two disk l/Os.</p><p>The image below illustrates this approach. The data in buckets is hashed on age, and the hash function will first convert the age to its binary representation, then group each data to different buckets based on the last two bits of the binary representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*m6BId5-gA9SO3WX0.png" /><figcaption>Hash indexing structure</figcaption></figure><p>Hash-based indexing can be classified into two types: static hashing and dynamic hashing, based on whether the index structure can be extended. Let’s discuss each of these types in detail.</p><h3>Static hashing</h3><p>This is the simplest hash-indexing technique, same as what I said before, it contains several buckets, and each bucket consists of primary bucket pages, and additional space, the additional space is the overflow page added after the primary bucket, one key was linked to one bucket and was connected through a hash function. The reason it is called static is the <strong>number of buckets</strong> in this structure is fixed, we cannot add or delete buckets in this hash map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uZC9XTr3GWfwqNhg.png" /><figcaption>Structure of Static Hashing</figcaption></figure><p>When inserting a data item in static hashing, we use a hash function to identify the appropriate bucket and append the data to it. If the bucket is already full, we allocate a new overflow page and store the data there. Similarly, when deleting a data item, we use the hash function to locate the corresponding bucket. If the data entry is the only one in an overflow page, we can simply remove that page.</p><p>This data structure can be pretty effective since the insert and delete operations only need two I/Os (read and write), but its disadvantage is also pretty obvious. As the file grows, the overflow page chains can be pretty long which might cost lots of time while searching in the chain. Since the number of buckets is fixed, when one of the files shrinks greatly, a lot of empty buckets will waste tons of space.</p><p>The alternative is to use dynamic hashing techniques which are what we are going to talk about: <strong>extendible</strong> and <strong>linear hashing</strong>.</p><h3>Dynamic hashing</h3><h4><strong>Extendible hashing</strong></h4><p>As the name shows, not like static hashing, extendible hashing can increase the number of buckets. To tell the program when should it increase buckets and how many buckets it should increase, we have to use a special hash function.</p><p>Compare to the original static indexing structure, the extendible hashing added a <strong>directory of pointers</strong> to buckets, so the whole process changes to using the hash function to find the correct pointer in the directory, through that pointer find the correct page that we want to search. Whenever we need to increase the number of buckets, we can double the size of the directory first and split only the bucket that overflowed.</p><p>There is a simple example for illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XmqtgXPECd1JaHy3.png" /><figcaption>Extendible Hashing example</figcaption></figure><p>There has a directory that consists of an array of size 4, and each position has a pointer point to a bucket, so in this example, there are totally four buckets. For each bucket, we assume that each bucket can hold four data items. And for the hash function, we assume that it will take the last 2 bits of the data items’ binary representation, it will find the pointer based on that 2 bits, and use the pointer to locate the correct bucket. For example the binary representation of 4 is 100, and the last two bits are 00, so 4 should go to the bucket to which the 00 pointer pointed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*BW67SRELbrEA7FpM.png" /><figcaption>Split bucket A</figcaption></figure><p>If we want to insert one value into bucket C, that’s fine, because bucket C still has space for extra data, but what if we want to insert 20 into the bucket? Based on the hash function, the binary representation of 20 is 10100, it should go to bucket A, but bucket A is already full. Thus we should split A into A1 and A2. After we split bucket A, there will not have enough pointers in the directory, thus we should also double the size of the directory. So now, we need three bits to discriminate between the pages that we have. Since the size of the directory is way smaller than buckets, so the cost of doubling it is more acceptable than doubling the pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*VN2wzUMrK95ODPwe.png" /><figcaption>Update directory and depth</figcaption></figure><p>Now through this example, we can find the basic technique used in extendible hashing is that hash function which will take the last k bits, the k depends on the size of the directory. The number of k is called the <strong>global depth</strong> of the hashed file. In the example above, before insertion, the global depth is 2, it changes to 3 after insertion.</p><p>And also as you can see in the example, splitting a bucket may increase the number of pointer but also may not need to increase. To know when should we increase the directory size, we can maintain a <strong>local depth</strong> for each bucket. Initially, the local depth is equal to the global depth, we increment global depth by 1 each time the directory doubles, and we increment local depth each time when that bucket splits. Whenever the local depth is less than the global depth which means splitting this bucket will not cause directory doubling, on the contrary, if the local depth is equal to the global depth, we need to double the directory to contain the new split bucket.</p><p>On the other hand, same as insertion, if we delete the last data entity in one bucket, it can be merged with its split image and decrease the local depth. And if each directory pointer and its split image points to the same bucket, we can halve the directory and reduce the global depth.</p><h4>Linear Hashing</h4><p>Linear hashing is another dynamic hashing technique, since for Extendible hashing, we still need to double the size of the directory when there will be an overflow page, people came up with another way to do hash indexing without using the directory, it is called Linear hashing.</p><p>Compare to Extendible hashing, Linear hashing is more complicated, before we talk about any detail, let’s figure out some terms and prerequisites:</p><p><strong>Hash function of Linear hashing:</strong></p><p>First of all, is the hash function, this scheme uses a list of hash functions: h0, h1, h2 …., and the range of each function is twice bigger than its predecessor. For example, the hi function range is M, which means it will map a data item into one of the M buckets, then the range of hi+1 will be 2M, which will map data into 2M buckets. Then if we know the number of bucket M, we can get the hash function:</p><pre>hi(value) = value mod (2^i * M)</pre><p>For example, for the h1 function, 4 buckets, the data that we want to insert is 10, then the hashed value is “10 mod (2 * 4)”, which is 2.</p><p><strong>Depth:</strong></p><p>Same to extendible hashing, linear hashing also has depth information. It maintains a number d, which means we only look at the last d bits of the result of the hash function. If M is chosen to be a power of 2, then d0 is the number of bits needed to represent M, and di = d0+i.</p><p><strong>Round of splitting:</strong></p><p>Another thing that we should know about is rounds of splitting. During round number <em>Level</em>, only the <em>hLevel </em>and <em>hLevel+1 </em>will be used. And there will have a next pointer which point at the bucket which needs to split, whenever the current bucket is split, the “next” pointer will move to the next bucket, and the buckets will be split from the first bucket in this round to the last one in the round <em>Level</em>. Thus, unlike the extendible hashing, when inserting trigger bucket splitting, we do not split the bucket that needs to be split, we split the next pointer-pointed bucket. And also, since the bucket may not split after full, we can add an overflow page after it in the Linear hashing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*rxpprGeF9iIWlLyo.png" /><figcaption>Structure of files in one round</figcaption></figure><p>After introducing all those terms, its time to describe Linear Hashing in an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*OW2bqWRz0D5-jbPn.png" /><figcaption>Linear Hashing example</figcaption></figure><p>Now let’s create a Linear hash table. In the beginning, the round level is 0, number of buckets at level 0 is 4, thus the number of buckets at level <em>i </em>will be 2^i * 4, since the number of buckets at level0 M is 4 = ²², the depth of level 0 d0 = 2, so in this example, we will take a look at the last two bits of the number.</p><ul><li>For number 32, 32 mod (²⁰ * 4) = 0, the last two bits are 00, thus, it should go to the first bucket;</li><li>For number 9, 9 mod (²⁰ * 4) = 1, the last two bits are 01, thus it goes to the second bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*yeDUak6LFOvDv2v7.png" /><figcaption>Linear Hashing after inserting 43</figcaption></figure><p>Then we can insert all the other numbers based on the hash function. Now if we want to insert 43 into this hash file, based on the hash function, 43 should go to the last bucket, but we can notice that the last bucket is full, to finish this insertion, since the linear hashing will not split the bucket which needs to split, we need to add an overflow page after the last bucket to contain 43 and we need to trigger a split. Whenever a split is triggered the <em>Next</em> bucket is split, and the next level hash function hlevel+1 should be used to redistribute data items in the <em>Next</em> bucket. The hlevel+1 function is:</p><pre>hlevel+1(value) = &lt;value&gt; mod (2^(1evel+1) * 4)</pre><p>And since the number of level+1 buckets is 8 = ²³ now, the depth changes to 3. So based on the new hash function, 32 stays at the first bucket, but 44 and 36 will move to the newly inserted bucket. After all that, the <em>Next</em> pointer will +1 and move to the next bucket.</p><p>There is something that needs to be mentioned, since now we have two hash functions in this round, h0 and h1, we have to choose which function should we use. If the result of h0 of one data item is in the range from the <em>Next</em> bucket to the last bucket, we can keep using h0, since these buckets haven’t been split. On the contrary, if fall in the range from bucket0 to the <em>Next</em> bucket, which has been split, then we should choose h1 as the hash function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v5H60UdagRtLpT9b.png" /><figcaption>After one split, add a new bucket, move the next pointer, and the bucket that has been split will use the previous hash function</figcaption></figure><p>When Next is at the last bucket and a split is triggered, we split the last bucket. Now we will start a new round, Level will be incremented by 1, the number of buckets will double, and <em>Next</em> will reset to 0.</p><h3>Summary</h3><p>In this article, I primarily discuss hash-based indexing, which is divided into two types: static hashing and dynamic hashing. Static hashing has a fixed number of buckets, which can result in inefficiency in certain scenarios. On the other hand, dynamic hashing includes extendible hashing and linear hashing. Extendible hashing utilizes a directory to extend the number of buckets, while linear hashing eliminates the directory, splits the buckets in a round-robin fashion, and allows for two hash functions to exist simultaneously.</p><p>Thanks for reading!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d882f294d05" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/exploring-the-role-of-hash-based-indexing-in-modern-database-architecture-4d882f294d05">Exploring the Role of Hash-Based Indexing in Modern Database Architecture</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Data Management with a Buffer Manager: Exploring the Heart of Database Systems]]></title>
            <link>https://levelup.gitconnected.com/efficient-data-management-with-a-buffer-manager-exploring-the-heart-of-database-systems-a8944c24c33f?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8944c24c33f</guid>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 17:36:24 GMT</pubDate>
            <atom:updated>2023-04-07T17:36:24.456Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing what is buffer manager in DBMS and the strategy it uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDEbmybyUqi4YFihPbiiHg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jakeblucker">Jake Blucker</a> from Unsplash</figcaption></figure><h3>What is buffer and buffer pool in database</h3><p>In the database, the buffer represents a temporary storage area in the main memory, which is used to cache database pages. Compare to the memory, the read and write speed of the disk is pretty slow, thus, when users want to get access to data from the disk, it might take a large amount of time. To improve performance, the DBMS uses a buffer to temporarily hold frequently accessed data in memory.</p><p>It can also ensure data consistency. Suppose one transaction adds certain values to the database, this update will first be written to the buffer before being written to disk. When this transaction fails, the DBMS can still roll back the changes and return to a consistent state.</p><p>The buffer pool is a collection of <strong>pages</strong> which is the data from the database. Memory is converted into a buffer pool by partitioning the space into frames that pages can be placed in. The main memory pages in the buffer pool are called <strong>frames</strong>, it is a unit of the buffer pool. A buffer frame can hold the same amount of data as a page can.</p><h3>What is the Buffer manager</h3><p>The buffer manager is one of the most important components of DBMS, which shuffles data from main memory to disk. It ensures the data requests and updates made by programs are satisfied by copying data from disk to buffer pool or from buffer pool to disk.</p><p>When a user requests data from the database, the buffer manager first checks if the data is already in the buffer pool. If it is, the buffer manager retrieves the data from memory and returns it to the user. If the data is not in the buffer pool, the buffer manager retrieves it from disk and loads it into memory.</p><p>The buffer manager also manages the write operations to the buffer pool. When a user modifies data in the database, the buffer manager writes the changes to the buffer pool instead of directly to the disk. The changes are then written to disk later when the buffer manager deems it necessary.</p><p>The buffer manager is a critical component of a DBMS as it can significantly impact the system’s performance. A well-designed buffer manager can help to reduce the number of disk accesses required, which can improve the overall performance of the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*moz3yzl_NmnKj2KR3CYQuQ.png" /><figcaption>Buffer pool in DBMS</figcaption></figure><h3>Buffer pool metadata</h3><p>To track frames more efficiently, the buffer manager keeps some information for each frame in the pool. Here is an example:</p><pre>Frame ID |  Page ID  |    dirty     |  pin_count<br>-----------------------------------------------------<br>    0    |     5     |      1       |      3<br>    1    |     2     |      0       |      2<br>    2    |     3     |      1       |      0</pre><p>This table contains 4 pieces of information:</p><ul><li><strong>Frame ID</strong>: the id of each frame in the buffer pool</li><li><strong>Page ID</strong>: for determining which page a frame currently contains</li><li><strong>dirty</strong>: for determining whether the page has been modified since it was brought into the buffer pool from disk., if the page has been modified the Boolean variable; dirty is set as 1. otherwise 0</li><li><strong>pin_count</strong>: for tracking the number of requestors <strong>currently using a page</strong>, each time the page is requested, the “pin_count” will increase, whenever it fulfills the request the “pin_count” will decrease</li></ul><h3>Replacement strategies</h3><p>The buffer manager is responsible for caching data from disk in memory so that the user can access different pages faster. But the size of it is limited, so what would happen if the buffer pool becomes full? How does it decide which block should be evicted to make more room for new data?</p><p>There are multiple replacement strategies that are used by the current buffer manager, the goal of these strategies is to maximize the efficiency of the buffer pool by evicting blocks that are least likely to be accessed again in the near future.</p><p><strong>Least Recently Used (LRU) policy</strong></p><p>The best-known replacement policy is LRU. It works by maintaining a list of pages in memory and keeping track of the order in which each page was last accessed. When a page needs to be evicted from memory to make room for a new page, the page that was least recently used (i.e., the page that has not been accessed for the longest period of time) is chosen for eviction.</p><p>To implement the LRU page replacement algorithm, a queue of pointers is maintained. Each pointer in that queue point to a frame which pin_count is 0. Whenever the pin_count of that page goes to 0, it will be added to the end of that queue. And this algorithm will pick up the frame to replace at the head of the queue.</p><p><strong>Clock Replacement</strong></p><p>Sometimes the LRU policy can be costly, in order to make it more effective, the clock replacement was invented. In this policy, we don’t need to maintain a queue, but just a variable called current, and the page was chosen for replacement using the current variable. This variable ranges from 1 to X and X is the number of buffer frames. It is in a circular order so you can regard the whole frame being arranged in a circle like a clock&#39;s face, the current variable is the clock hand. Same as LRU, in this policy, each page will have a variable called reference, it will be turned on when pin_count goes to 0.</p><p>So, the whole process is: the algorithm will first choose the current frame for replacement. If that frame&#39;s reference bit is false, then the current clock hand will go to the next frame, and increase the current page&#39;s pin_count, until find a frame that has 0 pin_count.</p><p><strong>Most Recently Used (MRU) policy</strong></p><p>MRU follows the opposite strategy of LRU. The MRU selects the buffer page that has been accessed most recently and removes it from the buffer when a new page needs to be loaded.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8944c24c33f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/efficient-data-management-with-a-buffer-manager-exploring-the-heart-of-database-systems-a8944c24c33f">Efficient Data Management with a Buffer Manager: Exploring the Heart of Database Systems</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Redux Performance with Memoized Selectors: Best Practices and Implementation Tips]]></title>
            <link>https://javascript.plainenglish.io/boosting-redux-performance-with-memoized-selectors-best-practices-and-implementation-tips-51b4cf59d47c?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b4cf59d47c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 18:47:13 GMT</pubDate>
            <atom:updated>2023-03-18T18:47:13.943Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing what is memoized selector, why we need it, and how to implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMPc7WjXp4O3kjcQYt-Rfw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fonsheijnsbroek_amsterdam_photos">Fons Heijnsbroek</a> from <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>What is createSelector</h3><p>createSelector is a function from the reselect library that is commonly used in Redux applications. It is used to create a memoized selector function that can efficiently compute derived data from the Redux store.</p><p>A selector is a function that takes the Redux store state as input and returns a derived value. createSelector allows you to define a selector function that will only recalculate its output if its input values change. This can improve the performance of your application by reducing unnecessary recalculations of derived data.</p><h3>Why createSelector</h3><p>If you are working with redux, you must be familiar with selectors, they are functions in Redux that are used to extract and transform data from the Redux store. They are a key concept in Redux because they allow you to compute derived data from the store, which can be more efficient and performant than computing it in your components.</p><p>But if we go deeper, we will find that the selector will recalculate every time when you call it, even though that value is still the same!</p><p>This is the reason why the createSelector came up with, to solve this problem, and make selector only compute when the redux state value change.</p><h3>Example</h3><p>Let’s explain it through an example:</p><p>First of all, we need to create a react app, there are several tools to create that, and I prefer using create-react-app, so if you have npx and Node.js installed, you can run this code below to start a new react app:</p><pre>npx create-react-app Memoized_selector // &quot;Memoized_selector&quot; is the name of the react app</pre><p>After that, you can start this app through:</p><pre>cd Memoized_selector<br>npm start</pre><p>Now we can start editing files for this app; in ./src/App.js we can add those codes:</p><pre>import &#39;./App.css&#39;;<br>import {useSelector, useDispatch} from &quot;react-redux&quot;;<br>import { createSelector } from &quot;@reduxjs/toolkit&quot;;<br>​<br>import { buttonId } from &quot;./btnSlice&quot;;<br>​<br>function App() {<br>    // This is original selector which will be executed whenever you call it<br>    const clickedBtnId = useSelector((state: any) =&gt; {console.log(&quot;button id selector&quot;); return state[&#39;btn&#39;][&#39;btnId&#39;]})<br>    <br>    // This is the memoized selector build by createSelector, it will only trigger when the &#39;state[&#39;btn&#39;][&#39;btnId&#39;]&#39; changed<br>    // const clickedBtnId = useSelector(createSelector(<br>    //    (state) =&gt; {return state[&#39;btn&#39;][&#39;btnId&#39;]},<br>    //   (buttonId) =&gt; {console.log(&#39;memoized button id selector&#39;); return buttonId}<br>    //))<br>    <br>    // Dispatch function of redux<br>    const dispatch = useDispatch()<br>    <br>    // Update redux state when click on buttons<br>    const onBtnClick = (e) =&gt; {<br>        dispatch(buttonId(e.target.id))<br>    }<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;div className=&quot;reduxTextContainer&quot;&gt;<br>            &lt;div className = &quot;changeValueTo&quot;&gt;Button that you clicked: &lt;/div&gt;<br>            &lt;div className = &quot;btnValueContainer&quot;&gt;{clickedBtnId}&lt;/div&gt;<br>            &lt;div className = &quot;btnGrid&quot;&gt;<br>                &lt;div className = &quot;btnCell&quot; id = &#39;a&#39; onClick={onBtnClick}&gt;a&lt;/div&gt;<br>                &lt;div className = &quot;btnCell&quot; id = &#39;b&#39; onClick={onBtnClick}&gt;b&lt;/div&gt;<br>                &lt;div className = &quot;btnCell&quot; id = &#39;c&#39; onClick={onBtnClick}&gt;c&lt;/div&gt;<br>                &lt;div className = &quot;btnCell&quot; id = &#39;d&#39; onClick={onBtnClick}&gt;d&lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>  );<br>}<br>​<br>export default App;</pre><p>In the code above, I build four different buttons, each of them containing one letter. Whenever you click on one of the buttons, the onBtnClick function will be triggered, this function will grab the button id and dispatch it to redux.</p><p>And also don’t forget the CSS to make this page prettier:</p><pre>.App {<br>  text-align: center;<br>  height: 100vh;<br>​<br>}<br>​<br>.reduxTextContainer{<br>  width: 500px;<br>  height: 650px;<br>  border-radius: 10px;<br>  background-color: #D5D5D5;<br>​<br>  margin-left: 50%;<br>  margin-top: 30px;<br>  transform: translate(-50%, 0);<br>}<br>.reduxTextContainer{<br>  position: relative;<br>  width: 500px;<br>  height: 350px;<br>  border-radius: 10px;<br>  background-color: #D5D5D5;<br>​<br>  margin-left: 50%;<br>  margin-top: 30px;<br>  transform: translate(-50%, 0);<br>}<br>.changeValueTo{<br>  position: relative;<br>  font-family: &quot;Helvetica neue&quot;;<br>  font-style: normal;<br>  font-weight: 700;<br>  font-size: 20px;<br>  line-height: 16px;<br>​<br>  top: 210px;<br>}<br>.btnValueContainer{<br>  position: relative;<br>  top: 230px;<br>​<br>  font-size: 70px;<br>​<br>}<br>.btnGrid{<br>  position: absolute;<br>  bottom: 200px;<br>  left: 50%;<br>  transform: translate(-50%, 0);<br>​<br>  width: 90%;<br>  height: 100px;<br>  background: gray;<br>  border-radius: 10px;<br>  padding-top: 1px;<br>  box-sizing: border-box; <br>​<br>  display: grid;<br>  grid-template-columns: repeat(4, 1fr);<br>  grid-gap: 10px;<br>}<br>.btnCell{<br>  width: 90%;<br>  height: 90%;<br>  position: relative;<br>  top: 50%;<br>  left: 50%;<br>  transform: translate(-50%, -50%);<br>  box-sizing: border-box; <br>​<br>  background-color: black;<br>  color: white;<br>  border-radius: 10px;<br>  font-size: 40px;<br>  padding-top: 15px;<br>​<br>}</pre><p>To use redux state, you have to create a slice; we can create a new file called “btnSlice.js”:</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br>​<br>export const btnSlice = createSlice({<br>    name: &quot;btn&quot;,<br>    initialState: {<br>        btnId: &#39;&#39;<br>    },<br>    reducers: {<br>        buttonId: (state, action) =&gt; {<br>            return {<br>                ...state,<br>                btnId: action.payload<br>            }<br>        }<br>    }<br>})<br>​<br>export const { buttonId } = btnSlice.actions<br>export default btnSlice.reducer</pre><p>This file creates all the components that redux needs. We initiate the redux state using initialState value, create one reducer buttonId for the onBtnClick function in the App component. And export a relative action.</p><p>Now when you should be able to see this page in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNNLajqpLYlb9ZO3NcBuOA.png" /><figcaption>Page shows on localhost:3000(by default)</figcaption></figure><p>When you click on any of the black boxes, the value of that box will show below, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFpZqoUA3rp6ynFVWjtHfQ.png" /><figcaption>After clicking on the ‘a’ button</figcaption></figure><p>And also, you can see “button id selector” in the console.</p><p>Now let’s click on one of the buttons twice, you will see the “button id selector” twice, even though the state hasn’t been changed (we click on the same button, and the value this component passes to redux state is the same).</p><p>Then let’s did a little change to the selector in the App component:</p><pre>function App() {<br>    // This is original selector which will be executed whenever you call it<br>    //const clickedBtnId = useSelector((state: any) =&gt; {console.log(&quot;button id selector&quot;); return state[&#39;btn&#39;][&#39;btnId&#39;]})<br>    <br>    // This is the memoized selector build by createSelector, it will only trigger when the &#39;state[&#39;btn&#39;][&#39;btnId&#39;]&#39; changed<br>    const clickedBtnId = useSelector(createSelector(<br>        (state) =&gt; {return state[&#39;btn&#39;][&#39;btnId&#39;]},<br>        (buttonId) =&gt; {console.log(&#39;memoized button id selector&#39;); return buttonId}<br>    ))</pre><p>Now, we are using the createSelector for building a memoized selector.</p><p>After that, no matter how many times we click on the same button, we should only see one ‘memoized button id selector’ in the console.</p><p>Thanks for reading this post.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em> community and follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em> and</em><strong><em> </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Learn how to build awareness and adoption for your startup with </em></strong><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b4cf59d47c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/boosting-redux-performance-with-memoized-selectors-best-practices-and-implementation-tips-51b4cf59d47c">Boosting Redux Performance with Memoized Selectors: Best Practices and Implementation Tips</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Think Twice Before Using console.log, and Tips for Avoiding Performance Pitfalls]]></title>
            <link>https://medium.com/@xiaweiliang94/why-you-should-think-twice-before-using-console-log-and-tips-for-avoiding-performance-pitfalls-1228efc27360?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1228efc27360</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[console]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 23:15:16 GMT</pubDate>
            <atom:updated>2023-03-15T23:15:16.357Z</atom:updated>
            <content:encoded><![CDATA[<p>How does console.log affect your application performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrhwD4iKPfFb0-jVNakxUA.jpeg" /><figcaption>Image from <a href="https://unsplash.com/">https://unsplash.com/</a></figcaption></figure><h3>Does console.log affect the performance?</h3><p>Unfortunately, the answer is yes, and it may make the loading time way longer than the function without console.log. We can test it through console.time in this example:</p><p>Suppose we have two HTML files, one is:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;script&gt;<br>        console.time(&#39;console.log performance test&#39;)<br>        function performanceTest(){<br>            let counter = 0<br>            for(let i = 0; i &lt;= 100000; i++){<br>                counter += 1<br>            }<br>            return counter<br>        }<br>        performanceTest()<br>        console.timeEnd(&#39;console.log performance test&#39;)<br>    &lt;/script&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;testContainer&quot;&gt;This is a js console.log performance test&lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The second one is:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;script&gt;<br>        console.time(&#39;console.log performance test&#39;)<br>        function performanceTest(){<br>            let counter = 0<br>            for(let i = 0; i &lt;= 100000; i++){<br>                counter += 1<br>                console.log(counter) // This is the only difference between these two files<br>            }<br>            return counter<br>        }<br>        performanceTest()<br>        console.timeEnd(&#39;console.log performance test&#39;)<br>    &lt;/script&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;testContainer&quot;&gt;This is a js console.log performance test&lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The only difference is second HTML file has console.log(counter) to print the `counter` variable into the web console.</p><p>After we run two files, we can get this result:</p><p>For the first HTML:</p><pre>console.log performance test: 0.76416015625 ms</pre><p>For the second one:</p><pre>console.log performance test: 988.362060546875 ms</pre><p>The execution time may differ on different machines, web browsers, etc. But the first executing time is around 1000 times faster than the second one.</p><p>Based on that, we can give a conclusion that the console.log do affect the performance of your code.</p><h3>Why does that happen?</h3><p>When an object is passed as an argument to the console.log function, it is first converted into a string through a process called serialization, and then displayed in the console. This serialization process can consume a significant amount of memory, particularly when dealing with large or complex objects.</p><p>The serialization process involves converting the object to a string representation that can be output to the console. This typically involves creating a new string in memory and copying the data from the object into the string. For large or complex objects, this can require a significant amount of memory.</p><p>In addition to the memory used for serialization, the output of console.log can also consumes memory, particularly if you are logging a large number of objects or strings. Each log statement generates a new line of output in the console, which can add up over time and consume memory.</p><p>We can test it through the same example just do a little change to the javascript code, there is a performance memory API for javascript, and we can use it to estimate the memory used by console.log:</p><pre>function performanceTest(){<br>    let counter = 0<br>    for(let i = 0; i &lt;= 100000; i++){<br>        counter += 1<br>        // console.log(counter)<br>    }<br>    return counter<br>}<br><br>// Log the memory usage before the call<br>const startMemory = performance.memory.usedJSHeapSize;<br><br>// Call console.log with a large number of object<br>performanceTest();<br><br>// Log the memory usage after the call<br>const endMemory = performance.memory.usedJSHeapSize;<br><br>// Calculate the approximate memory used by the console.log call<br>const logMemory = endMemory - startMemory;<br>console.log(logMemory)</pre><p>After running the code above, the function without console.log cost 0 bytes memory, while the function with console.log cost 1818704 bytes. And that is the reason for how console.log slows down the app.</p><h3>How to hide it easily using code?</h3><p>While developing, it’s advisable to limit the usage of console.log to a minimum, even though it can be helpful for debugging purposes. However, it&#39;s crucial to avoid using it in production mode or on a live server as it can pose several risks. As previously mentioned, console.log can slow down your application, consume more memory, and increase the computation power needed. Additionally, it can potentially expose critical information about your application, making it vulnerable to security threats.</p><p>The good news is that there’s a relatively simple way to remove all the console.log statements from your project without the need to delete them one by one.</p><p>You can create a .env file at the root of your program and put this code in it:</p><pre>if (env === &#39;production&#39;) {<br>    console.log = function () {};<br>}</pre><p>This code means, if the environment is production, then all the console.log functions will be empty functions; while if not in the production environment, all the console.log still works.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1228efc27360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Autovacuum Process in PostgreSQL: Everything you need to know]]></title>
            <link>https://levelup.gitconnected.com/understanding-the-autovacuum-process-in-postgresql-everything-you-need-to-know-ab389af7719d?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab389af7719d</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 03:44:52 GMT</pubDate>
            <atom:updated>2023-03-08T03:44:52.706Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing autovacuum in PostgreSQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8s_A80KR2fo-pz9thEhtyA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jae462">Jay Antol</a> from <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Mark works as a developer for a company that uses a database to store customer data. One day, he received a complaint from a customer that their account was slow to load and the website was unresponsive.</p><p>Mark investigated the issue and found that the customer_data table, which stores information about all the company&#39;s customers, had grown to a massive size over time even though the real data that in this table is not that large. The table contained millions of rows, and many of them were dead rows that were not marked as free.</p><p>Mark realized that this was causing a problem called “bloat”, where the size of the table grows over time due to the accumulation of dead space. This was slowing down the database queries and causing the website to be unresponsive.</p><p>Are there any ways to help Mark solve this problem?</p><p>Fortunately, PostgreSQL offers a command called VACUUM that scans tables and frees space taken up by dead tuples. However, determining when and how often to run this command can be challenging. If the command is run too infrequently, tables may grow larger than desired, as Mark discovered. On the other hand, running the command too often can lead to other issues, such as increased overhead and table fragmentation, which can also negatively impact performance.</p><p>So what should we do then?</p><p>Luckily, the PostgreSQL developer has already considered this situation and has come up with a process that will run in the background and monitors the activity on the tables in the database. When certain thresholds are met, such as a certain percentage of dead rows or a certain amount of changes to the table, it will initiate a vacuum or analyze operation on the table. It is called AUTOVACUUM.</p><h3>What is autovacuum</h3><p>In PostgreSQL, AUTOVACUUM is a process that automatically reclaims storage space and optimizes the performance of database tables. When a row is deleted or updated in a table, the old version of the row becomes a dead row that takes up space in the table until it is reclaimed by a vacuum operation. Autovacuum periodically scans tables to remove dead rows and free up space, thereby preventing the table from becoming bloated and slowing down queries.</p><p>The AUTOVACUUM process consists of two separate processes: <strong>AUTOVACUUM VACUUM</strong> and <strong>AUTOVACUUM ANALYZE</strong>.AUTOVACUUM VACUUM is like the original vacuum, reclaiming storage space taken by dead tuples. AUTOVACUUM ANALYZE is responsible for updating table statistics to ensure that queries are optimized for performance.</p><h3>How to enable autovacuum</h3><p>The autovacuum is enabled by default, but there are some ways to check whether it is enabled or not, and if it is disabled, we can re-enable it:</p><p><strong>Check if </strong><strong>autovacuum is enabled in your PostgreSQL:</strong></p><pre>SHOW autovacuum;</pre><p>If autovacuum is enabled, you will see a result like this:</p><pre>autovacuum<br>--------------<br>on</pre><p><strong>Turn on </strong><strong>autovacuum:</strong></p><p>If autovacuum is not enabled, you can enable it by modifying the postgresql.conf file. Locate the postgresql.conf file in your PostgreSQL installation directory (e.g., /etc/postgresql/12/main/postgresql.conf) and open it in a text editor.</p><p>Find the line that starts with &quot;autovacuum&quot; and make sure it is set to &quot;on&quot;. The default value is &quot;on&quot;, so if it&#39;s set to &quot;off&quot;, change it to &quot;on&quot;.</p><pre>autovacuum = on<br>track_counts = on</pre><p>The track_counts is a configuration parameter that enables or disables the tracking of statistics on the number of inserts, updates, and deletes on each table in the database. Autovacuum uses that to determine when to run a vacuum operation on a certain table.</p><h3>How to log autovacuum</h3><p>Now after knowing how to turn on/off the autovacuum, you might want to ask how can I print out the log information of autovacuum?</p><p>To do that, you can go to postgresql.conf file again, find the ‘log_autovacuum_min_duration’ parameter:</p><pre>log_autovacuum_min_duration = 1000</pre><p>This parameter controls the minimum duration of any SQL statement that will be logged, including autovacuum statements. The default value is -1, which means that all statements will be logged. If you want to log only statements that take longer than a certain duration, you can set this value to the desired threshold in milliseconds.</p><p>In the example above, PostgreSQL will log the statement that takes longer than 1000 ms.</p><h3>When to run autovacuum vacuum/analyze?</h3><p>Vacuuming will be required when the number of dead tuples exceeds a certain threshold, more specifically it depends on the equation below:</p><pre>num_of_dead_tuple &gt;= autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * number of tuples</pre><p>Let’s understand these parameters in detail:</p><p><strong>autovacuum_vacuum_scale_factor</strong>: In PostgreSQL, autovacuum_scale_factor is a configuration parameter that determines the threshold at which the autovacuum process will trigger a table. It is a floating-point value and its default value is 0.2, which means that autovacuum will trigger when the table has had at least 20% of its rows modified or deleted.</p><p><strong>autovacuum_vacuum_threshold</strong>: it is a configuration parameter in PostgreSQL that specifies the minimum number of dead rows that must exist in a table before the autovacuum process will initiate a VACUUM operation to reclaim the space used by those dead rows. By default, autovacuum_vacuum_threshold is set to 50, which means that the autovacuum process will initiate a VACUUM operation if the number of dead rows in a table exceeds 50 or more rows.</p><p>Similarly, the autovacuum analysis equation is the same:</p><pre>num_of_inserts/deletes/updates &gt;= autovacuum_analyze_threshold + autovacuum_analyze_scale_factor * number of tuples</pre><p>Also, the same as above:</p><p><strong>autovacuum_analyze_scale_factor:</strong> This parameter is a fraction of the table records. The default value of it is 0.1, which means, only after the number of modified tuples is larger than 10% of the table size, will the autovacuum analyze operation initiate.</p><p><strong>autovacuum_analyze_threshold:</strong> It is a parameter that defines the minimum number of row inserts, updates, and deletes that must occur in a table before initiating the ANALYZE operation. The default value of it is also 50.</p><p>Thanks for reading!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab389af7719d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-the-autovacuum-process-in-postgresql-everything-you-need-to-know-ab389af7719d">Understanding the Autovacuum Process in PostgreSQL: Everything you need to know</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of VACUUM: Keeping Your PostgreSQL Database in Top Shape]]></title>
            <link>https://levelup.gitconnected.com/the-magic-of-vacuum-keeping-your-postgresql-database-in-top-shape-991a40ae101?source=rss-2881bf2ce4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/991a40ae101</guid>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-development]]></category>
            <dc:creator><![CDATA[Zack]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 01:40:49 GMT</pubDate>
            <atom:updated>2023-02-27T01:40:49.694Z</atom:updated>
            <content:encoded><![CDATA[<p>Introducing what VACUUM is in PostgreSQL, what it does, and also the difference between regular VACUUM and VACUUM FULL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OJ7AE8076R7_SQgnOebTQ.jpeg" /></figure><h3>What is vacuuming</h3><p>PostgreSQL implements concurrency control through MVCC (Multi-Version Concurrency Control) (<em>If you would like to learn more about MVCC and how it is implemented in PostgreSQL, go </em><a href="https://medium.com/gitconnected/a-deep-dive-into-postgresql-visibility-management-18c2fd6746e4"><em>here</em></a>), which means different transactions are able to work with the same data concurrently but see different views of the data items. When a transaction deletes a tuple, it needs to be able to see the original version of the tuple in case it needs to be rolled back. If the original tuple was immediately removed, the transaction could not roll back correctly.</p><p>PostgreSQL retains deleted tuples in the table instead of immediately removing them, which results in space being occupied by those tuples. This approach works fine for smaller tables, but for tables where frequent updates and deletions are performed, the table size could significantly increase, leading to performance degradation. To address this, the VACUUM process is used to reclaim the occupied space and optimize the performance of the database. By using VACUUM, we can optimize the performance of the PostgreSQL database and maintain the health of our application.</p><h3>Prerequisite</h3><p><strong>Dead tuple</strong></p><p>In PostgreSQL, a “dead tuple” refers to a row or record in a table that has been marked for deletion but has not yet been physically removed from the table. When a row is deleted from a table, it is not immediately removed from the table’s underlying storage. Instead, the database marks the row as “dead” and leaves it in place until a process called VACUUM reclaims the space.</p><p>A dead tuple in PostgreSQL is still visible to queries, but its contents are no longer relevant or accessible. In other words, the data stored in a dead tuple is effectively deleted, but the space it occupies in the table is not yet freed up.</p><p>In PostgreSQL, you cannot directly query or view dead tuples in a table. Dead tuples are not visible to regular queries, and they do not appear in the results of a SELECT statement.</p><p>However, you can use the PostgreSQL command line utility psql and run a VACUUM VERBOSE command to get a report on the number of dead tuples that were removed by the vacuum operation. The verbose option will display information about the table, including the number of dead tuples that were removed during the VACUUM operation.</p><h3><strong>Concurrent </strong>VACUUM</h3><p>VACUUM reclaims storage occupied by dead tuples. It is used to remove dead rows and free up space for future updates.</p><p>The VACUUM command scans the table and removes any dead rows, as well as reclaims the space they occupied. This helps to compact the table and reduce fragmentation. The VACUUM command can also analyze the table to update statistics used by the query optimizer.</p><p>We can have a look at how this command does through this example:</p><p>First, we can create a table in our database:</p><pre>CREATE TABLE table1(col text) WITH (autovacuum_enabled = off);</pre><p>Then insert one record into it and update that data once;</p><pre>INSERT INTO table1(col) VALUES (&#39;a&#39;);<br>UPDATE table1 SET col = &#39;b&#39;;</pre><p>Now we should have one tuple in table1 and one dead tuple</p><p>Then we can create a function to print out all tuples in this table:</p><pre><br>CREATE FUNCTION heap_page(relname text, pageno integer)<br>RETURNS TABLE(ctid tid, state text, xmin text, xmax text, t_ctid tid)<br>AS $$<br>SELECT (pageno,lp)::text::tid AS ctid,<br>       CASE lp_flags<br>         WHEN 0 THEN &#39;unused&#39;<br>         WHEN 1 THEN &#39;normal&#39;<br>         WHEN 2 THEN &#39;redirect to &#39;||lp_off<br>         WHEN 3 THEN &#39;dead&#39;<br>       END AS state,<br>       t_xmin || CASE<br>         WHEN (t_infomask &amp; 256) &gt; 0 THEN &#39; (c)&#39;<br>         WHEN (t_infomask &amp; 512) &gt; 0 THEN &#39; (a)&#39;<br>         ELSE &#39;&#39;<br>       END AS xmin,<br>       t_xmax || CASE<br>         WHEN (t_infomask &amp; 1024) &gt; 0 THEN &#39; (c)&#39;<br>         WHEN (t_infomask &amp; 2048) &gt; 0 THEN &#39; (a)&#39;<br>         ELSE &#39;&#39;<br>       END AS xmax,<br>       t_ctid<br>FROM heap_page_items(get_raw_page(relname,pageno))<br>ORDER BY lp;<br>$$ LANGUAGE SQL;</pre><p>After running this function, we can get:</p><pre>SELECT * FROM heap_page(&#39;table1&#39;,0);</pre><pre> ctid  | state  |  xmin   | xmax  | t_ctid <br>-------+--------+---------+-------+--------<br> (0,1) | normal | 809 (c) | 810   | (0,2)<br> (0,2) | normal | 810     | 0 (a) | (0,2)<br>(2 rows)</pre><p>The second record is the current tuple, while the first one is the dead tuple.</p><p>Now we execute the VACUUM command:</p><pre>VACUUM table1;<br>SELECT * FROM heap_page(&#39;table1&#39;, 0);</pre><p>The result is:</p><pre> ctid  |     state     |  xmin   | xmax  | t_ctid <br>-------+---------------+---------+-------+--------<br> (0,1) | redirect to 2 |         |       | <br> (0,2) | normal        | 810 (c) | 0 (a) | (0,2)<br>(2 rows)</pre><p>Now only one tuple remains in the table, the dead tuple gets vacuumed away.</p><h3>FULL VACUUM</h3><p>In PostgreSQL, there is another way to do vacuum, called full vacuum. It refers to a command VACCUM FULL which will perform a complete vacuuming of a table or index.</p><p>VACUUM scans through the table or index and marks dead rows for deletion. It then frees up the space occupied by the dead rows for future use. VACUUM also updates statistics on the table, which can be used by the query optimizer to generate more efficient query plans.</p><p>VACUUM FULL is more aggressive and does a more thorough job of cleaning up the table or index. It physically reorganizes the table or index, moves data around to eliminate fragmentation, and compacts the table or index as much as possible. This can result in a significant reduction in the size of the table or index, but it can also take much longer to run than a regular VACUUM.</p><p>It’s important to note that VACUUM FULL can cause significant downtime and may require exclusive access to the table, whereas VACUUM can be run concurrently with other operations. As such, VACUUM FULL should only be used when absolutely necessary, such as when there is a significant amount of bloat or fragmentation in the table or index.</p><p>Now let me explain to you with an example, suppose we still using the table that we created before ‘table1’, and then insert 100000 rows of “a” and 100000 “b” by running this code:</p><pre>DO $$   <br>BEGIN   <br><br>FOR i IN 1..100000 LOOP<br>INSERT INTO table1(col) VALUES (&#39;a&#39;); <br>END loop;<br><br>FOR i IN 1..100000 LOOP  <br>INSERT INTO table1(col) VALUES (&#39;b&#39;); <br>END loop;<br><br>END $$;</pre><p>After that we can run this code to get the current size of the table1:</p><pre>SELECT pg_size_pretty(pg_table_size(&#39;table1&#39;)) table_size;</pre><p>Now, the result should be:</p><pre> table_size <br>------------<br> 7112 kB<br>(1 row)</pre><p>Then, we need to delete some rows to create several dead tuples:</p><pre>DELETE FROM table1 WHERE col = &#39;a&#39;;    </pre><p>After that, we can run the pg_table_size again to get the size of the table1 again:</p><pre> table_size <br>------------<br> 7112 kB<br>(1 row)</pre><p>Apparently, the size of this table will not change before we do any vacuum operations.</p><p>Now let&#39;s do a concurrent vacuum first, and measure the size again:</p><pre>VACUUM table1;<br>SELECT pg_size_pretty(pg_table_size(&#39;table1&#39;)) table_size;</pre><p>The result is:</p><pre> table_size <br>------------<br> 7120 kB<br>(1 row)</pre><p>As we can see, the size doesn’t change much, that’s because when you run the regular VACUUM command on table1, it will scan through the table and reclaim the dead rows’ space but it will not physically reorganize the table, thus <strong>the result will be a table with some free space than can be reused by new rows</strong>.</p><p>Then let’s do a Full vacuum:</p><pre>VACUUM FULL table1;     <br>SELECT pg_size_pretty(pg_table_size(&#39;table1&#39;)) table_size;</pre><p>The result changes to:</p><pre> table_size <br>------------<br> 3552 kB<br>(1 row)</pre><p>The space decreased to half of the previous size, that’s because the “VACUUM FULL” physically reorganized the table to eliminate fragmentation and compact it as much as possible.</p><p>Thanks for reading!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991a40ae101" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-magic-of-vacuum-keeping-your-postgresql-database-in-top-shape-991a40ae101">The Magic of VACUUM: Keeping Your PostgreSQL Database in Top Shape</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>