<?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 Shivam Panchal on Medium]]></title>
        <description><![CDATA[Stories by Shivam Panchal on Medium]]></description>
        <link>https://medium.com/@godwin1100?source=rss-9e32d5c64c9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CMUURLiSgLWmwOeEnYauuA.jpeg</url>
            <title>Stories by Shivam Panchal on Medium</title>
            <link>https://medium.com/@godwin1100?source=rss-9e32d5c64c9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:48:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@godwin1100/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[Python Packaging: Setup.py]]></title>
            <link>https://godwin1100.medium.com/python-packaging-setup-py-ae04b3d41653?source=rss-9e32d5c64c9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae04b3d41653</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-packaging]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shivam Panchal]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 00:31:42 GMT</pubDate>
            <atom:updated>2024-09-02T00:31:42.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XklStYMkr6EMGZGBkawz0A.png" /><figcaption>Python Packaging: Setup.py</figcaption></figure><p>Packaging Python projects efficiently is a crucial skill for any developer, whether for open-source or internal packages or personal projects. Packaging ensures that applications are easily distributable and maintainable. One of the fundamental tools in this process is setup.py, a script used in Python to manage the distribution of software packages.</p><p>In this blog, we’ll delve into the essentials of setup.py, exploring its role in the Python ecosystem, how it simplifies the packaging process, and best practices for creating your setup scripts. To make the learning experience practical and engaging, we’ll walk through a hands-on project that demonstrates real-world applications of setup.py features, including console_scripts for creating command-line tools, extra_requires for optional dependencies, and namespace_packages for bundling asset files and last but not least we will publish the package to the Python Package Index (PyPI).</p><p>Whether you’re a novice aiming to understand the basics or an experienced coder looking to refine your packaging techniques, this guide will equip you with the knowledge to streamline your Python projects effectively.</p><p>You can access the completed code on <a href="https://github.com/GodWin1100/Blogs/tree/main/04-Python-Packaging_Setup.py/setuppy_blog">GitHub</a> and follow along. View the publish package at: <a href="https://test.pypi.org/project/setuppy-blog/">https://test.pypi.org/project/setuppy-blog/</a></p><h3>Flow</h3><ol><li><a href="https://github.com/GodWin1100/Blogs/tree/main/04-Python-Packaging_Setup.py">Read on Github?</a></li><li><a href="#0563">What is Python Packaging</a></li><li><a href="#1057">What is </a><a href="#1057">Setup.py</a> <br>1. <a href="#e6d8">Deprecation</a></li><li><a href="#5586">Folder Structure</a><br>1. <a href="#2917">__init__.py </a><br>2. <a href="#d639">__main__.py</a> <br>3. <a href="#df67">__about__.py</a></li><li><a href="#c7ea">Setup.py Keywords</a><br>1. <a href="#d9b0">Basic keywords</a><br>2. <a href="#6db5">Detailed Description keywords</a><br>3. <a href="#259c">CLI keywords</a><br>4. <a href="#5084">Extra Packages keywords</a><br>5. <a href="#5b36">Classifiers keywords</a><br>6. <a href="#891c">Package Data keywords</a></li><li><a href="#e90d">Building with </a><a href="#e90d">build</a></li><li><a href="#508c">Publishing with </a><a href="#508c">twine</a> <br>1. <a href="#00b3">Command to Publish</a><br>2. <a href="#5c7d">Upload to Python Repository</a><br>3. <a href="#4e57">keyring support</a></li><li><a href="#b8c1">Bonus</a></li><li><a href="#f17a">Reach Out</a></li></ol><h3>What is Python Packaging?</h3><p>Python packaging refers to the process of bundling Python code into a format that can be easily distributed and installed by others. This involves creating a distributable format such as a source distribution (sdist/tar file) or a built distribution (wheel), which can be uploaded to package indexes like PyPI (Python Package Index) and installed using tools like pip.</p><h3>What is `Setup.py`?</h3><p>The setup.py file plays a central role in this process. It is a Python script traditionally used to configure the various aspects of a Python package. This file includes metadata about the package (such as name, version, author, and license) and instructions on installing it and its dependencies.</p><blockquote>Over time, tools like setuptools and wheel have become the standard for packaging, and pyproject.toml is becoming more prevalent for configuration, but setup.py remains widely used and supported.</blockquote><h4>Deprecation</h4><p>The use of setup.py as a command line tool is deprecated and not as a build backend. Setup.py is a valid configuration file for Setuptools that happens to be written in Python, instead of in TOML (pyproject.toml).</p><p>You can read more about that on its official site: <a href="https://packaging.python.org/en/latest/discussions/setup-py-deprecated/">Is </a><a href="https://packaging.python.org/en/latest/discussions/setup-py-deprecated/">setup.py deprecated?</a></p><h3>Folder Structure</h3><p>We will be following src-layout structure for developing and building the package. The tree structure of our package will be as follows</p><pre>root # Root/Base path<br>│   LICENSE<br>│   pyproject.toml # for build isolation<br>│   README.md<br>│   requirements.txt<br>│   setup.py # setup.py/setup.cfg/pyproject.toml<br>│<br>├───src<br>│   └───setuppy_blog # package name<br>│       │   __about__.py<br>│       │   __init__.py<br>│       │   __main__.py<br>│       │<br>│       ├───cli # All CLI functionalities related code<br>│       │       say.py<br>│       │       __init__.py<br>│       │<br>│       ├───func<br>│       │       basic_math.py<br>│       │       say.py<br>│       │       __init__.py<br>│       │<br>│       ├───templates # Static Asset required by the package (namespace package)<br>│       │       follow.json<br>│       │       note.txt<br>│       │<br>│       └───utils<br>│               __init__.py<br>│<br>└───tests # Contains the test related to the package<br>        test_basic_math.py<br>        __init__.py</pre><p>In Python, three special files play crucial roles within a package: __init__.py, __main__.py, and __about__.py. Together, these files contribute to the effective structuring, execution, and documentation of Python packages, enhancing their functionality and usability.</p><h4>__init__.py</h4><p>The __init__.py file serves to mark a directory as a Python package, allowing its modules to be imported. This file can also contain initialization code that runs when the package is first imported, setting up any necessary package-wide configurations or variables. Directories not containing __init__.py are normal directories.</p><h4>__main__.py</h4><p>The __main__.py file enables a package to be executed as a standalone script. When the package is invoked using the command python -m package_name , the interpreter executes the code within __main__.py . This makes it the entry point for the packages’s runtime operations, providing a way to run the package directly from the command line.</p><h4>__about__.py</h4><p>Lastly, the __about__.py file is typically employed to store metadata about the package, such as its version, author, and license information. Unlike the other two, __about__.py is primarily used for descriptive purposes, providing essential information about the package without affecting its functionality. Together, these files help structure, execute, and describe Python packages effectively.</p><h3>`Setup.py` Keywords</h3><h4>Basic keywords</h4><ul><li><strong>name: </strong>The name of the package, used for distribution and installation (e.g., setuppy_blog).</li><li><strong>version: </strong>The version number of the package, following semantic versioning (e.g., 1.0.0).</li><li><strong>description:</strong> A summary of what the package does (e.g., Python package for Setup.py Blog).</li><li><strong>author:</strong> The name of the package author (e.g., Shivam Panchal).</li><li><strong>author_email:</strong> The email address of the package author (e.g., shivamjpanchal1@gmail.com).</li><li><strong>url:</strong> specifies the homepage URL for the package, typically a link to the project’s main website, documentation, or repository.</li><li><strong>license:</strong> The license under which the package is distributed (e.g., MIT).</li><li><strong>package_dir:</strong> A dictionary mapping package names to directories on the filesystem (e.g., {&#39;&#39;: ‘src’}), the keys are package names and the values are the directories where these packages are located.</li><li><strong>packages:</strong> A list of all Python import packages that should be included in the distribution (e.g., [‘setuppy_blog’, ‘setuppy_blog.cli’, ‘setuppy_blog.func’, ‘setuppy_blog.utils’]).</li><li><strong>find_packages:</strong> A function to automatically discover all packages and sub-packages which includes __init__.py (e.g., find_packages(where=’src’)).</li><li><strong>python_requires:</strong> The Python version compatibility requirement (e.g., &gt;=3.10).</li><li><strong>install_requires:</strong> A list of dependencies required for the package to work (e.g., [‘click’, ‘cowsay’]).</li></ul><pre>from setuptools import find_packages, setup<br><br><br>about = {}<br>with open(<br>    os.path.join(repo_path, &quot;src&quot;, &quot;setuppy_blog&quot;, &quot;__about__.py&quot;), &quot;r&quot;, &quot;utf-8&quot;<br>) as f:<br>    exec(f.read(), about)<br><br><br>setup(<br>    name=about[&quot;__title__&quot;],  # name of the package<br>    version=about[&quot;__version__&quot;],  # version of the package<br>    description=about[&quot;__description__&quot;],  # description of the package<br>    author=about[&quot;__author__&quot;], # author of the package<br>    author_email=about[&quot;__author_email__&quot;], # email id of the author<br>    url=about[&quot;__url__&quot;], # homepage URL for the package, such as the GitHub repository or project documentation<br>    license=about[&quot;__license__&quot;], # license under which package will be distributed<br>    package_dir={&quot;&quot;: &quot;src&quot;}, # directory where packages are located<br>    packages=find_packages(where=&quot;src&quot;), # find all packages and list them<br>    python_requires=&quot;&gt;=3.10&quot;, # compatible python version<br>    install_requires=[ # external packages required for our package to work<br>        &quot;click==8.1.7&quot;,<br>        &quot;cowsay==6.1&quot;,<br>    ],<br>)</pre><h4>Detailed Description keywords</h4><p>The long_description and long_description_content_type keywords affect how your package’s detailed description is presented on the Python Package Index (PyPI) and other package repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87lJHUg3QqpWOfzcKc6wSg.png" /><figcaption>Long Description View</figcaption></figure><ul><li><strong>long_description:</strong> This provides a comprehensive description of your package, which will appear on your package’s PyPI page. It is typically used to give users more detailed information about what the package does, how to install it, how to use it, etc. This often includes the content from your README file (e.g., open(‘README.md’).read()).</li><li><strong>long_description_content_type:</strong> This specifies the format of the long description, informing PyPI how to render it. Common formats include ‘text/markdown’ for Markdown and &#39;text/x-rst&#39; for reStructuredText. Setting this correctly ensures that your long description is properly rendered on the PyPI website, with correct formatting for headers, links, code blocks, etc.</li></ul><pre>...<br>with open(&quot;README.md&quot;, &quot;r&quot;, &quot;utf-8&quot;) as f:<br>    readme = f.read()<br><br>setup(<br>    ...<br>    long_description=readme, # A detailed description of the package<br>    long_description_content_type=&quot;text/markdown&quot;, # The format of the long description<br>    ...<br>)</pre><h4>CLI keywords</h4><ul><li><strong>entry_points: </strong>Defines a mapping of entry points, which can be used to create command-line scripts or plugins. Each entry in the list maps a command name (e.g., blog-math) to a function in your package (e.g., setuppy_blog.cli:main). When the package is installed, it generates a script in the Python environment’s <strong>bin</strong> directory, allowing the user to run blog-math from the command line, which in turn executes the specified function.</li><li>Two common types are console_scripts and gui_scripts.<br>- <strong>console_scripts:</strong> These are command-line interface (CLI) tools.<br>- <strong>gui_scripts:</strong> These are for graphical user interface (GUI) applications. Similar to console_scripts, but intended for applications that should be run with a graphical interface. This will launch a GUI application without running in a terminal window.</li></ul><pre>...<br>setup(<br>    ...<br>    entry_points={<br>        &quot;console_scripts&quot;: [<br>            &quot;blog-math = setuppy_blog.cli:main&quot;, # will create blog-math.exe, and on invocation will execute setuppy_blog.cli:main function<br>            &quot;blog-say = setuppy_blog.cli.say:cli&quot;, # will create blog-say.exe, and on invocation will execute setuppy_blog.cli.say:cli function<br>        ]<br>    },<br>    ...<br>)</pre><blockquote>Instead of executing python -m setuppy_blog (invokes __main__.py which in turn calls setuppy_blog.cli.say:cli) user can now directly invoke blog-say, this makes your package more user-friendly and accessible, particularly for command-line tools and applicates that require a simple interface for execution.</blockquote><p>entry_points syntax is as follows: &lt;name&gt; = &lt;package_or_module&gt;[:&lt;object&gt;[.&lt;attr&gt;[.&lt;nested-attr&gt;]*]]</p><ul><li><strong>&lt;name&gt;:</strong> The name of the command-line script you want to create.<br>- Example: my-script</li><li><strong>=:</strong> This separates the script name from the module and function specification.<br>- Example: my-script =</li><li><strong>&lt;package_or_module&gt;:</strong> The Python package or module where the callable is located.<br>- Example: my_package.my_module</li><li><strong>[:&lt;object&gt;]:</strong> (Optional) The specific callable (function or class) within the module. If omitted, it defaults to the module itself.<br>- Example: my_package.my_module:my_function, setuppy_blog.cli:main</li><li><strong>[.&lt;attr&gt;]:</strong> (Optional) An attribute of the specified object, used if the callable is an attribute of an object rather than a top-level function or class.<br>- Example: my_package.my_module:MyClass.my_method</li><li><strong>[.&lt;nested-attr&gt;*]:</strong> (Optional) Further nested attributes, used for more deeply nested callable.<br>- Example: my_package.my_module:MyClass.my_method.sub_method</li></ul><h4>Extra package keywords</h4><ul><li><strong>extras_require: </strong>This allows you to specify optional dependencies for your package, which users can choose to install if they need additional features. This is useful for keeping the core package lightweight while providing the flexibility to include extra functionalities for those who need them. These optional dependencies are defined in a dictionary where the keys are names for the optional features and the values are lists of dependencies required for those features.</li></ul><pre>...<br>setup(<br>    ...<br>    extras_require={<br>        &quot;feeds&quot;: [&quot;feedparser&quot;], # this group includes packages useful for feeds feature<br>        &quot;quotes&quot;: [&quot;requests&quot;], # this group includes packages useful for quotes feature<br>        &quot;dev&quot;: [&quot;feedparser&quot;, &quot;requests&quot;, &quot;build&quot;, &quot;twine&quot;], # this group includes packages useful for build<br>        &quot;all&quot;: [&quot;feedparser&quot;, &quot;requests&quot;], # this group includes all the feature packages except build<br>    },<br>    ...<br>)</pre><p>Users can install these optional dependencies using the `extras` syntax with pip</p><pre>pip install setuppy-blog # core package<br>pip install &quot;setuppy-blog[feeds]&quot; # core package + feeds feature<br>pip install &quot;setuppy-blog[quotes]&quot; # core package + quotes feature<br>pip install &quot;setuppy-blog[all]&quot;  # core package + all user feature<br>pip install &quot;setuppy-blog[dev]&quot;  # all user features + dev features</pre><h4>Classifiers keywords</h4><ul><li><strong>classifiers: </strong>It provides metadata about your package, helping users and tools to understand the package’s intended audience, environment, license, and other attributes. These classifiers are predefined strings listed in the <a href="https://pypi.org/classifiers/">Python Package Index (PyPI) classifiers</a>. This enhances the package’s visibility on PyPI and ensures it reaches the appropriate audience effectively. Classifiers are also used as filters for browsing projects on <a href="https://pypi.org/search/">PyPI</a>.</li><li>Here are some commonly used classifiers that might be appropriate for a wide range of packages:<br>- Development Status<br>- Intended Audience<br>- Programming Language<br>- Environment<br>- License<br>- Topic<br>- Framework<br>- Operating System</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*DbqlJoMKqbIAMiKJ0inD5Q.png" /><figcaption>Classifier View</figcaption></figure><pre>...<br>setup(<br>    ...<br>    classifiers=[<br>        &quot;Development Status :: 6 - Mature&quot;,<br>        &quot;Intended Audience :: Developers&quot;,<br>        &quot;License :: OSI Approved :: MIT License&quot;,<br>        &quot;Natural Language :: English&quot;,<br>        &quot;Programming Language :: Python :: 3&quot;,<br>        &quot;Programming Language :: Python :: 3.10&quot;,<br>        &quot;Topic :: Software Development :: Build Tools&quot;,<br>        &quot;Topic :: Software Development :: Libraries :: Python Modules&quot;,<br>        &quot;Topic :: Documentation&quot;,<br>        &quot;Environment :: Console&quot;,<br>        &quot;Typing :: Typed&quot;,<br>        &quot;Operating System :: OS Independent&quot;,<br>    ],<br>    ...<br>)</pre><h4>Package Data keywords</h4><p>- <strong>package_data:</strong> keyword argument is used to specify additional files that should be included in the package when it is distributed. This is crucial for including non-code files such as templates, static files, configuration files, or any other data files that the package might need to function properly. The value of package_data is a dictionary where the keys are package names and the values are lists of patterns matching the files to be included.</p><pre>...<br>packages = [*find_packages(where=&quot;src&quot;), &quot;setuppy_blog.templates&quot;]<br>...<br>setup(<br>    ...<br>    packages=packages,<br>    package_data={&quot;setuppy_blog.templates&quot;: [&quot;*.json&quot;]}, # `setuppy_blog.templates` refers to `src/setuppy_blog/templates`<br>    ...<br>)</pre><p>Data files are normally added in a directory that does not contain __init__.py, we need to add such package&#39;s path manually as seen above or we can use find_namespace_packages instead of find_packages. Even if additional files are added in a Python package directory, i.e. includes __init__.py, it will include only `.py` files and not data files or other extension files.</p><h3>Building with `build`</h3><p>Building a Python package involves creating a distributable version of your project, which can be uploaded to package repositories like PyPI(Python Package Index) or installed directly. The build tool is a Python package that can be installed with pip install build. To build the package, first, get to the root of your directory where your setup.py/pyproject.toml exists and execute python -m build. This package simplifies the build process and it will generate distribution files for your package. These files are placed in the dist directory by default. The output typically includes</p><ul><li><strong>Source Distribution (sdist):</strong> This is a tarball (e.g., .tar.gz file) containing the source code of your package and can be used to build your package from a source.</li><li><strong>Built Distribution (wheel):</strong> This is the binary distribution (e.g., .whl file) that is ready for installation. Wheels are preferred for installation because they do not require building or compilation, making the process faster and simpler.</li></ul><p>The generated distribution file naming convention will be as follows</p><pre>dist/<br>    {your_package_name}-{version}-{python_tag}-{abi_tag}-{platform_tag}.whl<br>    {your_package_name}-{version}.tar.gz<br>-----<br>dist/<br>    setuppy_blog-1.0.0-py3-none-any.whl<br>    setuppy_blog-1.0.0.tar.gz</pre><h4>Deprecated</h4><p>With deprecated commands of setup.py, distribution files can be generated as follows</p><pre># Create Source Distribution:<br>python setup.py sdist<br><br># Create Wheel Distribution:<br>python setup.py bdist_wheel<br># requires wheel python package to be installed</pre><h3>Publishing with `twine`</h3><p>When we execute the command to create our distribution, a new directory dist/ is created under our project’s root directory that contains your distribution file(s) to be uploaded.</p><p>We will use <a href="https://twine.readthedocs.io/en/stable/">twine</a> to upload the distribution files. It requires a <strong>username</strong>, <strong>password</strong>, and the <strong>URL</strong> of the repository (PyPI or TestPyPI). If we want to publish to the official <strong>PyPI</strong> the URL is typically https://upload.pypi.org/legacy/. For <strong>TestPyPI</strong>, it’s https://test.pypi.org/legacy/.</p><p>Install twine with pip install twine</p><h4>Command to Publish</h4><pre># will prompt for username and password<br>twine upload /path/to/distribution/files<br>twine upload dist/*<br><br># Will take username and password via args<br>twine upload -u &lt;USERNAME&gt; -p &lt;PASSWORD&gt; /path/to/distribution/files<br>twine upload -u __token__ -p &lt;TOKEN&gt; dist/*</pre><h4><strong>Upload to Python Repository</strong></h4><pre>twine upload --repository testpypi dist/* # Upload to Test PyPI Index<br>twine upload -r testpypi dist/* # Upload to Test PyPI Index<br><br># --repository-url overwrites --repository<br>twine upload --repository-url https://test.pypi.org/legacy/ dist/* # Upload to given repository URL</pre><h4><strong>`keyring` support</strong></h4><p>Twine supports storing the username and password securely using <a href="https://pypi.org/project/keyring/">keyring</a>. Once Twine is installed, use the keyring program to set a <strong>username</strong> and <strong>password</strong> to use for each repository to which you may upload.</p><p>For example, to set the username and password for the repository keyring set &lt;repository_url&gt; &lt;your-username&gt;, and enter the password when prompted. The next time you run twine, it will prompt you for a username, and then get the appropriate password from keyring.</p><p>In some cases, the presence of Keyring will cause unexpected or undesirable prompts from the backing system or when executing the script via the CI/CD pipeline. In these cases, it may be desirable to disable Keyring altogether. To disable Keyring, run: keyring --disable</p><h3>Bonus</h3><h4>Virtual Environment</h4><p>A virtual environment is an isolated Python environment that allows you to manage dependencies for different projects separately. This ensures that the packages and versions used in one project do not interfere with those in another. It is good to have one virtual environment for every Python-based project, as it will isolate the dependencies of every project from the system and each other.</p><ul><li>To create a virtual environment using the venv module: python -m venv &lt;venv_folder&gt;. Common names for virtual environment folders are <strong>venv</strong>,<strong> env</strong>, <strong>.venv</strong>, <strong>.env</strong>, and <strong>myenv</strong>. Do not forget to add the virtual environment folder to <a href="https://blog.devgenius.io/git-mastering-the-essentials-06f06ee7ad72#7e5d">.gitignore</a> the file.</li><li>To activate the virtual environment on Windows: &lt;venv_folder&gt;\Scripts\activate and on Linux &amp; macOS: source &lt;venv_folder&gt;\bin\activate</li><li>To deactivate the virtual environment on Windows: deactivate and on Linux &amp; macOS: source deactivate</li></ul><h4>Modernize `Setup.py`</h4><p>To modernize a setup.py based project, the project must contain a pyproject.toml file at the root of its source tree i.e. at the same level as of setup.py and should include [build-system] as follows</p><pre>[build-system]<br>requires = [&quot;setuptools&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;</pre><ul><li>[build-system]: Specifies the build system requirements for the project.</li><li>requires: Lists the packages that are required to build the project.</li><li>build-backend: This defines the backend tool to use for building the project.</li></ul><p>This triggers the build isolation feature that improves the reliability and reproducibility of Python package builds.</p><p><strong>Build isolation</strong> is the feature where the build process is isolated from the user’s current environment. This means that the build process does not use the packages installed in the user’s environment but instead creates a temporary, clean environment for the build dependencies and reproducibility.</p><blockquote>NOTE: The presence of a pyproject.toml file (even if empty) triggers pip to change its default behavior to use build isolation.</blockquote><h3>Reach Out</h3><p>For more intuitive blogs follow me on <a href="https://godwin1100.medium.com/">Medium</a> &amp; <a href="https://github.com/GodWin1100">Github</a>.<br>You can also reach out to me via <a href="https://www.linkedin.com/in/godwin1100/">LinkedIn</a> or <a href="https://twitter.com/l_shivam_l">X(Twitter)</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae04b3d41653" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git: Mastering the Essentials]]></title>
            <link>https://blog.devgenius.io/git-mastering-the-essentials-06f06ee7ad72?source=rss-9e32d5c64c9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/06f06ee7ad72</guid>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-beginner]]></category>
            <category><![CDATA[git-basics]]></category>
            <dc:creator><![CDATA[Shivam Panchal]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 19:22:03 GMT</pubDate>
            <atom:updated>2024-02-23T19:22:03.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqhSSjffh_9hKsNJ8Nz67Q.png" /><figcaption>Git: Mastering the Essentials</figcaption></figure><p>In the ever-evolving landscape of technology, the term “Git” resonates across all domains, playing a pivotal role in the daily workflow of professionals ranging from junior developers to seasoned leads. Git is a powerful tool that can transform the way you work with code and seamlessly collaborate with peers and colleagues working on the same piece. It helps track changes to source code during software development, making it easier to manage, share, and collaborate on projects.</p><p>To facilitate a hands-on understanding of Git through practical application for readers at different proficiency levels, I have segregated the topic into three proficiency categories. Let’s start with the Git essentials and nomenclature required for beginners and smartly leverage ourselves to seasonal lead. For practical implementation and practice of the Git concepts, a shell script is included to bootstrap local, remote, and clone repositories.</p><h3>Flow</h3><ol><li><a href="https://github.com/GodWin1100/Blogs/tree/main/03-Git_Mastering-the-Essentials">Read on Github?</a></li><li><a href="#640f">What is Git?</a></li><li><a href="#c02d">Nomenclature</a></li><li><a href="#2910">Workflow</a></li><li><a href="#deba">Git Installation</a></li><li><a href="#6e0d">Configuring Git</a></li><li><a href="#ff88">Initialize a Git repository</a></li><li><a href="#c4e6">Staging the Resources</a></li><li><a href="#a898">Status of Repository</a></li><li><a href="#9919">Committing the Changes</a></li><li><a href="#caf4">Create a Branch</a></li><li><a href="#b43a">Merging Branch</a></li><li><a href="#1a7f">Remote Repository</a></li><li><a href="#aecb">Pushing to Remote</a></li><li><a href="#f879">Pulling from Remote</a></li><li><a href="#5846">Branch Tracking</a></li><li><a href="#2559">Cloning the Repository</a></li><li><a href="#1290">Diving into the Basics</a><br>1. <a href="#94ea">git config </a><br>2. <a href="#52c5">git commit </a><br>3. <a href="#ea1d">git log </a><br>4. <a href="#8968">git branch </a><br>5. <a href="#7aa3">git remote </a><br>6. <a href="#52f9">git merge </a><br>7. <a href="#6249">git push </a><br>8. <a href="#9917">git rm </a><br>9. <a href="#c925">git checkout</a></li><li><a href="#efbd">Bonus</a></li><li><a href="#deca">Reach Out</a></li></ol><h3>What is Git?</h3><p>Git is a free and open-source distributed Version Control System (VCS) that is an integral part of the software development life cycle, and it is prevalent to workforces of all sizes, whether it’s a small-scale start-up or a big tech giant. Version control systems refer to software tools that assist teams in tracking and managing changes to source code over time. Git excels in tracking changes to source code, streamlining project management, non-linear development, and enhancing the overall efficiency of collaborative efforts. One can interact with Git using the CLI and GUI locally. Popular platforms like <a href="https://github.com/">GitHub</a>, <a href="https://about.gitlab.com/">GitLab</a>, and <a href="https://bitbucket.org/product/">Bitbucket</a> provide hosting services for Git repositories, making it easier for teams to collaborate, share code, and manage their codebase.</p><h3>Nomenclature</h3><p>Let’s understand basic nomenclature around the Git space to get familiar with its terms and usage.</p><ul><li><strong>local repository:</strong> A directory named <strong>.git</strong> that contains all of your necessary repository files; a Git repository skeleton. The local repository has exactly the same features and functionality as any other Git repository.</li><li><strong>commit:</strong> Commit is a snapshot of changes made to the files in a repository. It represents a specific version in the repository’s history.</li><li><strong>branch:</strong> It is a separate or new line of development that allows one to work on the code base without affecting the main codebase(default branch) until it’s merged with the default branch. The default branch name generally is <strong><em>main</em></strong> (previously <strong><em>master</em></strong>).</li><li><strong>blob:</strong> A blob in Git is a binary large object that represents the content of a file without any metadata. It stores the file’s data in its raw form.</li><li><strong>tree:</strong> A tree represents a snapshot of the project’s directory structure at a specific commit. It stores references to blobs(file contents) and other trees (subdirectories). The Git working tree consists of all the files and directories we add to the Git repository that are located outside of the <strong>.git</strong> folder.</li><li><strong>working directory/workspace/checkout:</strong> Local checkout of your code. It’s any directory on your filesystem that has a repository associated with it (has <strong>.git</strong> sub-directory folder). It includes all the files and sub-directories in that directory.</li><li><strong>untracked:</strong> “Untracked” refers to files that are not currently monitored/tracked by the VCS. It needs to be explicitly added to the staging area to track.</li><li><strong>tracked:</strong> “Tracked” refers to files being tracked and managed by the VCS. It is an asset that Git knows about and keeps track of it.</li><li><strong>staged/index/cache/staging area:</strong> The staging area in Git is a temporary storage area, where changes are placed before committing them to the repository. It holds a snapshot of the changes that are set to be included in the next commit.</li><li><strong>committed:</strong> “Committed” refers to the state where changes have been successfully saved to the version control system. The changes are now part of the repository’s history.</li><li><strong>modified:</strong> Git sees the tracked file as “modified”; it indicates that changes have been made but not yet committed since the workspace’s last commit.</li><li><strong>ignore:</strong> Exclude files or directories from being tracked by version control. Generally done by creating a .gitignore file and listing the patterns of files and folders to be ignored.</li><li><strong>remote repository:</strong> A repository that is hosted on a server or another location, separate from the local repository on your machine.</li><li><strong>origin (remote name):</strong> “origin” is a default alias often used to refer to the main remote repository from which a local repository was cloned.</li><li><strong>upstream (remote name):</strong> When you fork a repository, the original repository is often referred to as the “upstream” repository.</li><li><strong>upstream branch:</strong> The term “upstream branch” generally refers to the branch in the remote repository that a local branch is tracking.</li><li><strong>.gitignore:</strong> .gitignore is a configuration file in Git that specifies files and directories to be ignored by version control.</li></ul><h3>Workflow</h3><h4>Git Workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*cZFl9NBvUCB50zWrEji9Bw.png" /><figcaption>Git Workflow</figcaption></figure><ol><li><strong>Working Directory:</strong> Make changes to files in the working directory.</li><li><strong>Staging Area:</strong> Add changes to the staging area to prepare them for the next commit.</li><li><strong>Local Repository:</strong> Commit the staged changes to the local repository, creating a snapshot of the project’s state.</li><li><strong>Remote Repository:</strong> Push committed changes from the local repository to the remote repository for collaboration and version control.</li></ol><h4>Lifecycle of file status</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*4MVXoq0S0m2uaURbBB_1Tw.png" /><figcaption>Lifecycle of File Status in Git repository</figcaption></figure><ol><li><strong>Untracked: </strong>File is not yet tracked by Git.</li><li><strong>Unmodified: </strong>File is tracked, and there are no changes since the last commit.</li><li><strong>Modified: </strong>Changes have been made to the file since the last commit.</li><li><strong>Staged: </strong>Modified changes are marked to be included in the next commit.</li></ol><h3>Git Installation</h3><p>Git is available for all operating systems, including Linux, Windows, and MacOS. One can follow the installation guide <a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">Installing Git</a> or download directly from <a href="https://git-scm.com/downloads">Git Downloads</a> based on the OS.</p><p>After successful installation, check whether the Git executable is set up correctly and accessible. We can run a git command from CLI to check its version and verify it. Execute the following command</p><pre>git --version</pre><h3>Configuring Git</h3><p>Now we can start configuring Git with basic configuration, let’s register the user’s name and email, and set the default branch name explicitly. It’s not an obligation to set a username and email when working locally, but it’s a must when collaborating with others on cloud platforms. Let’s set the user’s name and email at a global level which will provide your identity</p><pre>git config --global user.name &quot;John Doe&quot;<br>git config --global user.email &quot;johndoe@example.com&quot;</pre><p>The default branch name in Git is master. The current standard naming convention followed by the remote repository for the default branch is main, we can configure this locally by</p><pre>git config --global init.defaultbranch main</pre><blockquote>--global flag ensures that configurations are applied at a global level and not at the local repository level</blockquote><h3>Initialize a Git repository</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*IIXurocK4D4SsDIrWs2y3A.png" /><figcaption>Initial Git Repository</figcaption></figure><p>We can get a Git repository on our local machine in two ways: by cloning the existing repository (more about that in the later section) and by initializing a fresh repository for an incredible project. Let’s see how to initialize a fresh Git repository.</p><pre>git init</pre><p>This will initialize a local git repository (<strong>.git</strong> hidden folder) in the current directory.</p><p>What if we want to create a git repository with an initial branch different from the configured initial branch?</p><pre>git init -b &lt;name&gt;<br># or<br>git init --initial-branch &lt;name&gt;</pre><h3>Staging the Resources</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*bFrhAyhKX5TYJ2item9Z0w.png" /><figcaption>Staging the Resources</figcaption></figure><p>After setting up our local repository, let’s create resources and add them to the repository to start tracking.</p><pre>git add /path/of/dir-or-file<br># add all files and folder of current dir<br>git add .<br># add particular files<br>git add ./file1 ./folder/file1 ./file2</pre><p>The git add command will add the untracked and modified files and folders to the staging area.</p><h3>Status of Repository</h3><p>With so many changes going on with files and directories within the repository, it becomes hard to remember which file is staged, deleted, or modified.</p><p>For the same reason, Git provides a git status command that shows the status of every resource that is tracked, modified, deleted, added, renamed, or untracked.</p><pre>git status</pre><h3>Committing the Changes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*REk2ssC45046oW4fzeF1wQ.png" /><figcaption>Committing the Changes</figcaption></figure><p>It’s time to commit all the stage resources to our repository.</p><pre>git commit</pre><p>Each commit requires a message that is associated with it; thus, executing the above command will open the configured editor to provide the message. The message ought to be a short one-liner that clarifies the modifications in the commit.</p><p>For a faster commit, we can use the -m flag to add the message during the commit process.</p><pre>git commit -m &lt;message&gt;<br># or<br>git commit --message &lt;message&gt;</pre><p>Modified tracked files need to be staged, and we can stage them with git add. git commit also provides the -a flag to add all the modified tracked files to the staging area.</p><pre>git commit add .<br>git commit -m &lt;message&gt;<br># ------------------------------------------------------------ #<br>git commit -am &lt;message&gt; # add modified files to staging area<br># or<br>git commit --all -m &lt;message&gt;</pre><blockquote>Untracked files are to be added explicitly by git add to be tracked and staged.</blockquote><h3>Create a Branch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*2Qs3Q3hLmq0uwChNUyTcHQ.png" /><figcaption>Branch(first) created</figcaption></figure><p>Need to multitask on the same project and task are poles apart? No worries, create a new branch and start working on another task simultaneously just be sure to commit the changes before switching the branch.</p><pre>git branch &lt;branch_name&gt; # create new branch<br>git checkout &lt;branch_name&gt; # switch to branch<br># ------------------------------------------------------------ #<br>git checkout -b &lt;branch_name&gt; # create a new branch and switch</pre><p>To switch to any branch, we can execute git checkout &lt;branch_name&gt; more on this in the later section of the blog.</p><h3>Merging Branch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*eAHZwWLSnS63wijImHSYXg.png" /><figcaption>Merge the Branch</figcaption></figure><p>Once multitasking is complete, it’s time to consolidate all the branches into a branch. Merging a branch is simple with the git merge command. Ensure that your active current branch is the desired branch where you want to merge (the destination branch).</p><pre>git checkout &lt;destination_branch&gt; # ensure you are on destination branch<br>git merge &lt;branch_name&gt; # source branch to merge with destination branch</pre><blockquote>If there’s a conflict during the merge, Git will prompt to manually resolve the conflict, stage the changes, and continue with the merge.</blockquote><h3>Remote Repository</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*urFEwvZkCAK2F2LM1dvllA.png" /><figcaption>Add Remote URL</figcaption></figure><p>It’s time to push our repository to the remote server so others can collaborate. The remote server can be any other Git repository locally or cloud services like GitHub, GitLab, BitBucket, etc. First, we need to add a remote repository server to our local git repo</p><pre>git remote add &lt;remote_name&gt; &lt;remote_url&gt;</pre><p>One will be named origin, indicating the repository from which you cloned your local repository. It’s the default remote repository where you push changes or pull updates.</p><pre>git remote add origin &lt;remote_url_local_clone&gt;</pre><p>Another will be named upstream, which you set up manually to track the original repository in the context of forks or copies. The upstream remote is necessary when contributing to other repositories to keep the local repository in sync with the original repository.</p><pre>git remote add upstream &lt;remote_url_original_repo_of_fork&gt;</pre><h3>Pushing to Remote</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*x4I5crJQ-Qf_S1Ej8ZAExQ.png" /><figcaption>Push commits to Remote</figcaption></figure><p>It’s time to push the branch from the local to the remote repository. It is sweet and simple to push just like</p><pre>git push &lt;remote_name&gt; &lt;branch_name&gt;</pre><p>The remote repository will reject the push if you are not authorized and the local repository is not in sync with the remote. We need to pull the updates from the remote to the local repository to sync, and then we can push our changes.</p><h3>Pulling from Remote</h3><p>The git pull command pulls the updates from the remote repository locally similar to git push</p><pre>git pull &lt;remote_name&gt; &lt;branch_name&gt;</pre><p>This will pull the changes from the remote repository locally, and if any conflict arises, it will require a manual resolution.</p><h3>Branch Tracking</h3><p>Branch tracking refers to the association between a local and a remote branch. Git can set up tracking so the local branch knows which remote branch it corresponds to. This tracking information helps Git users manage changes, push updates, and pull changes efficiently.</p><p>For a new branch created locally or an existing branch without an upstream branch, we can set the tracking branch while pushing it to remote with the -u or --set-upstream flag, which will associate the remote branch with the local branch with the same name.</p><pre><br>git push -u &lt;remote_name&gt; &lt;local_branch_name&gt;<br># or<br>git push --set-upstream &lt;remote_name&gt; &lt;local_branch_name&gt;</pre><p>For existing branches without upstream, we can set the upstream with</p><pre><br>git branch -u &lt;upstream_branch&gt;<br># or<br>git branch --set-upstream-to=&lt;remote_name&gt;/&lt;upstream_branch&gt;</pre><p>This allows us to run the git push and git pull commands without specifying the remote and branch names.</p><pre>git push # will push from the upstream branch<br>git pull # will pull from the upstream branch</pre><h3>Cloning the Repository</h3><p>We can clone the existing repository from the remote or local repository that will clone(download) every branch, commit, and tag to the desired directory with remote <strong>(<em>origin</em>)</strong> and branch tracking configured according to the source repository.</p><pre>git clone &lt;repo_uri_repo_path&gt; [&lt;dir&gt;] # will create dir with remote repo name<br># ---------------------------- #<br>git clone &lt;repo_uri&gt; # to clone remote repository<br># ---------------------------- #<br>git clone &lt;repo_path&gt; # to clone local repository</pre><p>This will create a directory with the name of the remote repository that contains the Git repository. The repo_uri/repo_path will be the remote repository (origin), and cloned branches will have an upstream branch to track.</p><h3>Diving into the Basics</h3><p>Now that we are familiar with the required basic commands, it’s time to dive deep into those commands to learn how to use them more efficiently.</p><p>To check available flags and commands of Git, one can append -h that shows inline help in stdout or --help that opens webpage help.</p><p>To exit the pager output in the Git output one can press q key.</p><h4>git config</h4><p>Git searches for configuration settings first at the local repository level, giving them priority over global settings. By default, when using git config, configurations are applied specifically to the local repository. If you want to apply configurations globally, you need to set the --global flag.</p><p>To list all the configuration</p><pre>git config --list # list both local and global config<br>git config --local --list # list local config<br>git config --global --list # list global config</pre><p>To check specific configuration’s value</p><pre>git config --get &lt;config_key&gt; # return the value of config_key<br>git config &lt;config_key&gt; # return the value of config_key<br># ------------------ #<br>git config user.name # return user.name</pre><p>To change the default editor</p><pre>git config --global core.editor &lt;executable_path_name&gt; # set globally</pre><blockquote>Configuration for setting core.editor: <a href="https://git-scm.com/book/en/v2/Appendix-C%3A-Git-Commands-Setup-and-Config">https://git-scm.com/book/en/v2/Appendix-C%3A-Git-Commands-Setup-and-Config</a></blockquote><h4>git commit</h4><p>Updating the last commit message, useful to correct any typo mistake</p><pre>git commit --amend # will open default editor to edit the message<br># or<br>git commit --amend -m &lt;message&gt; # update old message with &lt;message&gt;</pre><h4>git log</h4><p>The git log command shows logs for the current branch with the following details in the following format</p><pre>commit &lt;commit_hash&gt;<br>Author: &lt;author_name&gt; &lt;author_email&gt;<br>Date: &lt;date&gt;<br><br>  &lt;commit_message&gt;<br></pre><blockquote>To exit paginated git log view, one needs to press q key.</blockquote><p>To view logs of other branches we can use</p><pre>git log &lt;branch_name&gt;</pre><p>Want to check only the last <strong><em>n</em></strong> logs?</p><pre>git log -n &lt;n&gt;<br># or<br>git log -$<br># ---------- #<br>git log -n 5 # show last 5 logs<br># or<br>git log -5 # show last 5 logs</pre><p>Only interested in the commit message and commit hash of logs? No problem you can try</p><pre>git log --oneline</pre><p>that shows logs in the following format</p><pre>abbreviated_commit_hash &lt;commit_message&gt;</pre><h4>git branch</h4><p>To list all branches in the git repository</p><pre># list local branches<br>git branch<br># or<br>git branch -l<br># or<br>git branch --list<br># ----------- #<br># list local and remote branch<br>git branch -a<br># or<br>git branch --all</pre><p>To view the branch and its upstream tracking branch</p><pre><br>git branch -vv<br># &lt;branch_name&gt; &lt;abbr_commit_hash&gt; [&lt;upstream_branch&gt;] &lt;latest_commit_message&gt;</pre><p>There will be a marker (<strong>*</strong>) in front of the current branch while listing all the branches or to check the current branch name, one can execute</p><pre>git branch --show-current</pre><p>To delete the local branch from the git repository</p><pre>git branch -d &lt;branch_name&gt; # delete fully merged branch with current branch<br># or<br>git branch --delete &lt;branch_name&gt; # delete fully merged branch with current branch</pre><p>To delete a branch even if not merged</p><pre>git branch -D &lt;branch_name&gt;</pre><h4>git remote</h4><p>List all git remotes</p><pre>git remote<br># ----------- #<br>git remote -v # shows URl for fetch and push</pre><p>See details for specific remote</p><pre>git remote show &lt;remote_name&gt;</pre><p>To remove remote</p><pre>git remote remove &lt;remote_name&gt;<br># or<br>git remote rm &lt;remote_name&gt;</pre><h4>git merge</h4><p>During the merge, one can encounter conflict, which you need to resolve manually and then continue with the merge. Let’s look at some options that we have during the conflict.</p><p>To confirm the resolution of the merge conflict, one needs to resolve the conflict, add the files to the stage, and perform a commit or continue with the merge.</p><pre># after resolving the conflict in the file<br>git add &lt;file&gt;<br>git commit -m &lt;message&gt;<br># or<br>git commit -am &lt;message&gt;<br># --------------------- #<br>git add &lt;file&gt;<br>git merge --continue # will commit and open editor to write message</pre><blockquote>git commit and git merge --continue are basically doing the same, but git merge --continue presents a consistent UI with other Git commands.</blockquote><p>To abort the merge process completely and undo everything to state before the merge.</p><pre>git merge --abort</pre><p>To exit the merge process without completing the merge, leaving your working directory and index in a partially merge state.</p><pre>git merge --quit</pre><h4>git push</h4><p>The git push command is used to push changes and updates to the remote repository. To push all branches at once</p><pre>git push --all &lt;repository&gt; [&lt;branch_name&gt;]<br># or<br>git push --branches &lt;repository&gt; [&lt;branch_name&gt;]</pre><p>To delete a branch from the remote repository</p><pre>git push -d &lt;repository&gt; &lt;branch_name&gt;<br># or<br>git push --delete &lt;repository&gt; &lt;branch_name&gt;</pre><h4>git rm</h4><p>The git rm command can remove files from the working tree and the index. It is primarily used to remove tracked files from the index.</p><pre>git rm &lt;file_path&gt; # remove from index and working tree</pre><p>To remove files from cached/index. Beware that the file will not be tracked and will not be available if the index is changed, as git keeps the state in sync. To avoid such a scenario, add files in .gitignore from the get-go.</p><pre>git rm --cached &lt;file_path&gt; # keeps in tree and remove from index</pre><p>To remove the directory one needs to use -r flag</p><pre>git rm -r &lt;dir_path&gt; # removes files and folder recursively</pre><p>Git won’t allow you to remove files and directories in case it’s modified or exist in Git but not in the working tree, to remove such files and directories</p><pre>git rm -f &lt;file_path&gt;<br># or<br>git rm --force &lt;file_path&gt;</pre><h4>git checkout</h4><p>To switch the current branch one can do</p><pre>git checkout &lt;branch_name&gt;</pre><p>To traverse to the previous commit state</p><pre>git checkout &lt;commit_sha&gt;</pre><p>To discard all the changes of modified files/directories</p><pre>git checkout -- &lt;file_dir_path&gt;<br># ------------------------- #<br>git checkout -- . # will discard all the changes from current dir and sub dir</pre><h3>Bonus</h3><h4>.gitignore</h4><p>.gitignore is a file used by Git to determine which files and directories to ignore when tracking changes in a Git repository. You need to specify certain files or patterns of files that you don’t want Git to consider as part of your VCS. Following are the patterns:</p><pre># Line beginning with # are treated as comment<br>filename.txt # - Ignore Specific Files:<br>dirname/ # - Ignore Specific Directories:<br>*.log # ignore all .log files # - Ignore Patterns:<br># - Negation: order matters for negation<br>*.txt # ignore all .txt file<br>!important.txt # to negate the pattern one can prefix ! to the pattern. !important.txt will be tracked</pre><p>To get language or project-specific .gitignore, one can get the file template from <a href="https://github.com/github/gitignore">https://github.com/github/gitignore</a></p><h4>Practical Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*KJgrONmtKA76P5DUatUmBA.gif" /><figcaption>Visualization of Shell Script</figcaption></figure><p>For practical implementation, you can download the shell script from <a href="https://github.com/GodWin1100/Blogs/blob/main/03-Git_Mastering-the-Essentials/Git_Mastering-the-Essentials.sh"><strong><em>GitHub</em></strong></a> and execute it locally, the script will create a local repository, a remote repository locally, and a cloned repository that will simulate practical Git implementation as shown above.</p><p>To execute the shell script sh ./Git_Mastering-the-Essentials.sh, you get <strong>sh.exe </strong>installed with Git Installation.</p><h4>Message Convention</h4><p>Using a consistent commit message convention offers several benefits like clarity and readability, semantic versioning, facilitates collaboration, code maintenance and refactoring, or automated tools integration.</p><p>A popular convention is the “Conventional Commits” convention, which defines a standard format for commit messages. According to Conventional Commits, a commit message should have the following structure:</p><pre>&lt;type&gt;[scope]: &lt;description&gt;<br><br>[optional body]<br><br>[optional footer(s)]</pre><ul><li><strong>Type:</strong> Describes the type of change being made. Common types include:<br>- <em>feat:</em> A new feature<br>- <em>fix:</em> A bug fix<br>- <em>docs:</em> Changes in documentation<br>- <em>style:</em> Changes that do not affect the meaning of the code (eg. formatting, whitespaces, semicolons)<br>- <em>refactor:</em> Code changes that neither fix a bug nor add a feature<br>- <em>test:</em> Adding missing tests or correcting existing tests<br>- <em>chore:</em> Changes to the build process or auxiliary tools<br>- <em>perf:</em> Changes that improve the performance</li><li><strong>Scope:</strong> (Optional) Describes the part of the code affected within the scope of the commit (e.g., module, file, component).</li><li><strong>Description:</strong> A brief description of the changes being made or the subject of the commit.</li><li><strong>Body:</strong> (Optional) Must start one blank line after the description. Provides a more detailed description of the changes. This can include contextual information for the change, any breaking changes, etc. For breaking changes, the Body must start with “BREAKING CHANGE”.</li><li><strong>Footer(s):</strong> (Optional) Additional metadata about the commit, such as references to issues or pull requests.</li></ul><p>Example</p><pre>git commit -a # edit the message in editor<br># or<br>git commit -am &quot;feat(blog): Git: Mastering the Essentials added&quot; -m &quot;- Table of content added<br>- Included Workflow image asset<br>- Info added regarding basic workflow<br>- Added deep dive for commands&quot; -m &quot;Closes #123&quot;</pre><pre># git log output:<br>feat(blog): Git: Mastering the Essentials added<br><br>- Table of content added<br>- Included Workflow image asset<br>- Info added regarding basic workflow<br>- Added deep dive for commands<br><br>Closes #123</pre><h3>Reach Out</h3><p>For more intuitive blogs follow me on <a href="https://godwin1100.medium.com/">Medium</a> &amp; <a href="https://github.com/GodWin1100">Github</a>. <br>You can also reach out to me via <a href="https://www.linkedin.com/in/godwin1100/">LinkedIn</a> or <a href="https://twitter.com/l_shivam_l">X(Twitter)</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06f06ee7ad72" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/git-mastering-the-essentials-06f06ee7ad72">Git: Mastering the Essentials</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ORM: Bridging Code and DBMS]]></title>
            <link>https://blog.devgenius.io/orm-bridging-code-and-dbms-b61dbb0ce798?source=rss-9e32d5c64c9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61dbb0ce798</guid>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <dc:creator><![CDATA[Shivam Panchal]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 22:27:41 GMT</pubDate>
            <atom:updated>2024-03-03T17:12:10.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEIoa2uS-dfQ02Y2p09vjA.png" /><figcaption>ORM</figcaption></figure><p>If you are new to programming backed by databases, you may have come across the term <strong>ORM</strong> during your research. This blog aims to unravel the complexities of ORM, compare it to traditional SQL queries, shed light on its internal workings, and showcase a practical implementation of use cases with ORMs in NodeJs, Python, and Java.</p><p>Whether you’re a seasoned developer or just starting your journey, understanding ORM can greatly enhance your ability to work with databases and streamline your projects.</p><p>By the end of this blog, you’ll have a solid understanding of ORM and how it works. You’ll also have the tools to explore ORM in Nodejs, Python, and Java, making this blog a valuable resource for developers at all levels of expertise. So, let’s embark on this ORM journey together and unlock the power of efficient data management in your projects.</p><p>For curious learners of <strong><em>SQL</em></strong>, <strong><em>Nodejs</em></strong>, and <strong><em>Python</em></strong> resources are available on the GitHub page, which includes implementations in <strong>Sequelize</strong>(NodeJs) and <strong>SQLAlchemy</strong>(Python).</p><h3>Flow</h3><ol><li><a href="https://github.com/GodWin1100/Blogs/tree/main/02-ORM_Bridging_Code_and_DBMS">Read on GitHub?</a></li><li><a href="#87dc">What is ORM?</a></li><li><a href="#06c1">ORM Mechanics?</a></li><li><a href="#a048">Patterns of ORM</a><br>1. <a href="#1956">Active Record</a><br>2. <a href="#6a1d">Data Mapper</a></li><li><a href="#cde2">Context of Use Case Instance</a><br>1. <a href="#d11b">Enhanced ER Diagram</a></li><li><a href="#c797">Pros of ORM</a></li><li><a href="#447a">Cons of ORM</a></li><li><a href="#ad37">Key Takeaways</a></li><li><a href="#2706">Bonus</a></li><li><a href="#0b8e">Reach Out</a></li></ol><h3>What is ORM?</h3><p>An <strong>ORM,</strong> or <strong>Object Relational Mapper</strong>, is a part of software designed to align and translate the data representations used by databases and those used in object-oriented programming. The ORM provides an object-oriented interface to data records within the database; this creates, in effect, a “<em>virtual object database”</em> which could be used from within the programming language.</p><figure><img alt="ORM mapper which acts as a translator layer between program and database" src="https://cdn-images-1.medium.com/max/781/1*F40NnZYjIyEJQHEO072A8w.png" /><figcaption>ORM</figcaption></figure><p>In general, ORMs serve as an <strong>abstraction layer</strong> between the database and the program, enabling programmers to read, write, and manipulate objects without having to consider how those objects relate to their data sources and without drastically changing the object-oriented paradigm. Programmers can seamlessly execute a range of data-related tasks, including creating, reading, updating, and deleting (CRUD) operations in a database system without the cognitive burden of dealing with SQL queries tailored to the database.</p><h3>ORM Mechanics</h3><p>The <strong>Engine</strong> and <strong>Dialect</strong> are two crucial parts that are required for the operation of the Object-Relational Mapping (ORM) architecture. The Engine manages the database connections and transaction handling, requiring configuration details such as the connection string. The Dialect translates high-level, database-agnostic queries generated by the ORM into database-specific SQL statements.</p><p>In addition to these, you need to define object-to-database mappings, which involve specifying how your application’s objects correspond to the database tables. Querying is simplified using the ORM’s high-level querying capabilities; transaction management ensures data consistency; and data type conversion handles the conversion between programming language data types and database data types. Performance-enhancing capabilities like caching, faster query execution, and schema creation and migration may also be included in ORM frameworks.</p><h3>Patterns of ORM</h3><p>Several different patterns can be used to implement Object-Relational Mapping (ORM):</p><ul><li><strong>Active Record</strong>: The Active Record pattern is a simple and easy-to-use ORM pattern where each database record is represented by a corresponding object in the application.</li><li><strong>Data Mapper</strong>: The Data Mapper pattern separates the application’s data model from the database, and provides a way to map the data stored in the database to objects in the application and vice versa.</li><li><strong>Table Data Gateway</strong>: The Table Data Gateway pattern is a simple and efficient ORM pattern that maps a single database table to a corresponding class in the application.</li><li><strong>Unit of Work</strong>: The Unit of Work pattern keeps track of all the changes that have been made to the objects in the application, and ensures that the database is updated accordingly when the transaction is committed.</li></ul><p>The most popular patterns in the ORM and at the corporate level are <strong>Active Record</strong> and <strong>Data Mapper</strong>. We’ll be exploring these patterns in great detail.</p><h4>Active Record</h4><p>The <strong>Active Record</strong> pattern is one of the most widely used ORM patterns, especially for small to mid-size web backends. It maps a database record to a corresponding object in the application, and each database record is represented by an instance of an Active Record class. The class provides methods for performing database operations such as insertion, retrieval, update, and deletion. As a result, it allows the object to manage its persistence and retrieval, eliminating the need for a separate data access layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*qNKzLft0Eok_UJSLaTAZVw.png" /><figcaption>Active Record ORM</figcaption></figure><p>The fundamental idea behind the active record pattern is that your database records are “<em>active</em>” in your system, much like the OOPs paradigm, where the database table or view is wrapped into a class and each object instance is bound to a specific row in the table. In the Active Record pattern, every operation is auto-committed, and for the transactional operation, we need to create a session or context as provided by the framework.<br>For instance, in the Active Record pattern, the class might have a <strong>save</strong>method that inserts or updates the database record, a <strong>find</strong> method that retrieves a record from the database, and a <strong>delete</strong> method that removes the record from the database.</p><pre>data_obj = new TableClass({ firstName: &quot;John&quot;, lastName: &quot;Doe&quot;, age: 25 });<br><br>// to save<br>data_obj.save();<br><br>// to update<br>data_obj.age = 30;<br>data_obj.save();<br><br>// to find<br>data_obj2 = TableClass.findOne();<br><br>// to delete<br>data_obj.destroy(); // delete() or remove()</pre><p><strong>Pros:</strong></p><ul><li>Simple and maintainable.</li><li>Easy to understand and beginner-friendly</li></ul><p><strong>Cons:</strong></p><ul><li>Active Record is tightly coupled with Database</li><li>Lack of flexibility</li><li>Hard to write test cases</li><li>Performance Bottlenecks</li></ul><h4>Data Mapper</h4><p>A <strong>Data Mapper</strong> is a Data Access Layer that performs bidirectional transfers of data between a <em>persistent data store(database)</em> and an <em>in-memory data representation(object)</em>. The Data Mapper pattern provides a clear separation between the application’s data model and the database. Each data mapper class/repository is responsible for mapping a specific type of object, and it knows how to convert the data stored in the database into objects and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*m2MVHOrMvDxZG4IVeinadA.png" /><figcaption>Data Mapper ORM</figcaption></figure><p>The benefit of the Data Mapper pattern is that data objects do not need to know anything about how data is stored in the database. This means that the objects will be lighter because they don’t have to inherit ORM methods, but there will be a stricter process for interacting with the database because you can’t just call the object method anywhere in your code.</p><p>The biggest difference between the data mapper pattern and the active record pattern is that the data mapper is meant to be a layer between the actual business logic of the application and the database that persists its data, whereas the active record seeks to invisibly bridge the gaps between the two as seamlessly as possible, the role of the data mapper is to allow you to consider the two more independently.</p><p>For example, if you have a <strong>User</strong> class in your application, you would have a <strong>userMapper</strong> class or <strong>userRepository</strong> that would be responsible for loading and saving <strong>User</strong> objects from and to the database. The <strong>userMapper</strong> class or <strong>userRepository</strong> would have methods such as <strong>findById</strong> and <strong>save</strong> that would handle the retrieval and persistence of <strong>User</strong> objects, respectively.</p><pre>const userRepository = MyDataSource.getRepository(User);<br><br>const user = new User();<br>user.firstName = &quot;John&quot;;<br>user.lastName = &quot;Doe&quot;;<br>user.age = 25;<br><br>// to save<br>userRepository.save(user);<br><br>// to find<br>const allUsers = userRepository.find();<br><br>// to update<br>userRepository.update(1, { age: 30 });<br><br>const john = userRepository.findOneBy({<br>  id: 1,<br>}); // find by id<br>// to delete<br>userRepository.remove(john);</pre><p><strong>Pros:</strong></p><ul><li>Distinct separation of application and database</li><li>Greater flexibility and maintainability</li><li>Much more performant</li></ul><p><strong>Cons:</strong></p><ul><li>Increased complexity</li><li>Intimidating to understand</li><li>Lack of control</li></ul><h3>Context of Use Case Instance</h3><p>In this scenario, you are given the responsibility to design a database schema for a Content Management System (CMS) that will allow users to create, manage, and interact with various types of content. The schema will include tables for user management, content, role-based access control, and user-generated comments. <em>(For simplicity not considering workspace/team, tag table, and accurate temporal attributes).</em></p><h4>Enhanced Entity-Relationship Diagram:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krU8HULluFNXcnWIg1u4wQ.png" /><figcaption>EERD of Content Management System</figcaption></figure><h4><strong>Use Case Code</strong></h4><ul><li><a href="https://github.com/GodWin1100/Blogs/blob/main/02-ORM_Bridging_Code_and_DBMS/Raw_SQL_Query.md"><strong>SQL Raw Queries</strong></a></li><li><a href="https://github.com/GodWin1100/Blogs/blob/main/02-ORM_Bridging_Code_and_DBMS/NodeJs_Sequelize.mjs"><strong>Sequelize: NodeJs ORM</strong></a></li><li><a href="https://github.com/GodWin1100/Blogs/blob/main/02-ORM_Bridging_Code_and_DBMS/Python_SQLAlchemy.ipynb"><strong>SQLAlchemy: Python ORM</strong></a></li></ul><blockquote><strong>- </strong>Raw SQL Queries related to complete use case.<strong><br>- </strong>Sequelize ORM code for the same Raw SQL Queries and some extras.<strong><br>- </strong>Python ORM code for the same Raw SQL Queries and some extras.<br>- Contains Code, its Output along with the log of background SQL queries fired by each ORM function.</blockquote><h3>Pros of ORM</h3><ul><li><strong>Object-Oriented Approach:</strong> ORM aligns with modern software development practices, which promotes quicker development with less boilerplate SQL code. It easily integrates with Model-View-Controller design patterns.</li><li><strong>Database Interaction:</strong> ORM simplifies database operations, making code more readable and maintainable and making it easy to switch between different database systems with minimal code changes.</li><li><strong>Abstraction of Complex SQL:</strong> ORM abstracts SQL complexities, making it accessible to developers.</li><li><strong>Security and Maintainability:</strong> Provides security against database interactions by employing parameterized queries, protection against SQL injections, automatic data sanitization, and consistent security practices.</li></ul><h3>Cons of ORM</h3><ul><li><strong>Performance Overhead:</strong> ORM can lead to slower database interactions due to generated queries not being fully optimized for the database system.</li><li><strong>Learning Curve:</strong> Requires time to learn the ORM framework and its concepts.</li><li><strong>Limited Control:</strong> Limits fine-tuning and optimization of database interactions.</li><li><strong>Complexity in Mapping:</strong> Handling complex database structures or non-standard schemas can be cumbersome, which leads to poor mapping and performance.</li><li><strong>Maintainability:</strong> ORM may struggle to reconcile the differences between objects and databases, especially in complex databases, and as the application evolves, mapping needs to be maintained and in sync with the database.</li></ul><h3>Key Takeaways</h3><p>The use of ORMs can significantly simplify database operations by offering beneficial abstractions. They can assist you in rapid development and iteration while bridging the conceptual gaps between database structures and application logic. It employs out-of-the-box database security practices for communication between the program and the database. However, many of these advantages act as a double-edged sword. ORM can prevent you from the underlying understanding of your databases, make it challenging to debug, or increase performance overhead.</p><h3>Bonus</h3><h4>ORMs</h4><ul><li>Node.js<br>- <a href="https://sequelize.org/">Sequelize</a> <em>(Active Record)<br>-</em> <a href="https://typeorm.io/">TypeORM</a> <em>(Data Mapper and Active Record)<br></em>- <a href="https://www.prisma.io/">Prisma</a> <em>(Data Mapper)<br></em>- <a href="https://mongoosejs.com/">Mongoose</a> <em>(NoSQL, Active Record)</em></li><li>Java<br>- <a href="https://hibernate.org/orm/">Hibernate</a> <em>(Data Mapper)</em></li><li>Python<br>- <a href="https://www.sqlalchemy.org/">SQLAlchemy</a> <em>(Data Mapper)<br></em>- <a href="https://docs.djangoproject.com/en/4.2/topics/db/">Django’s ORM</a> <em>(Active Record)</em></li></ul><h4>Relationship in RDBMS</h4><p>To learn more about relationships in RDBMS you can go and read my blog <a href="https://godwin1100.medium.com/relationships-of-rdbms-f2edc98e0951">Relationships of RDBMS</a> which includes ER Diagram, ER Diagram notation, DDL command for each relation, and practical implementation of Blog Site Database.</p><h4>Database Tools</h4><p>Want to connect with several databases using a database management tool? Comparable to <strong>ORM </strong>for linking different databases, but with visual interaction? <a href="https://dbeaver.io/"><strong>DBeaver</strong></a> is the get-go. It is a cross-platform, free, open-source, ever-evolving database tool that anyone working with databases can use. It supports all popular SQL databases and provides a data editor, SQL editor, and database maintenance tools. It also offers a commercial version that can be considered an enhanced, robust edition of the open-source variant.</p><p>More tools similar to <strong>DBeaver</strong> are <a href="https://www.jetbrains.com/datagrip/"><strong>DataGrip</strong></a><strong> </strong>by JetBrains, <a href="https://tableplus.com/"><strong>TablePlus</strong></a>, <a href="https://www.dbvis.com/"><strong>dbvis</strong></a>, and minimalistic yet notable <a href="https://dbeaver.io/"><strong>Beekeeper Studio</strong></a>.</p><h3>Reach Out</h3><p>For more intuitive blogs follow me on <a href="https://godwin1100.medium.com/">Medium</a> &amp; <a href="https://github.com/GodWin1100">Github</a>. <br>You can also reach out to me via <a href="https://www.linkedin.com/in/godwin1100/">LinkedIn</a> or <a href="https://twitter.com/l_shivam_l">X(Twitter)</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61dbb0ce798" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/orm-bridging-code-and-dbms-b61dbb0ce798">ORM: Bridging Code and DBMS</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relationships of RDBMS]]></title>
            <link>https://blog.devgenius.io/relationships-of-rdbms-f2edc98e0951?source=rss-9e32d5c64c9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2edc98e0951</guid>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-relationship]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[rdbms-relationship]]></category>
            <dc:creator><![CDATA[Shivam Panchal]]></dc:creator>
            <pubDate>Sun, 08 Oct 2023 16:44:17 GMT</pubDate>
            <atom:updated>2024-05-25T18:25:02.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JEoyLoa_tUuvPTF44ju23A.png" /></figure><p>In this article, we will take a close detailed look at RDBMS relations with actual use case context and its application, including <strong>One-to-one</strong>, <strong>One-to-many,</strong> <strong>Many-to-many,</strong> and <strong>Self-referencing(Recursive) relations</strong>. <br>To build effective relationships one needs to know the type of relations, where, when &amp; how to apply them, building effective relationships in a database is crucial because it promotes referential integrity enforcement, which in turn facilitates database standardization.</p><p>For SQL query we will be using MySQL syntax and will stick to one SQL system for all the examples &amp; code snippets.</p><h3>Flow</h3><ol><li><a href="https://github.com/GodWin1100/Blogs/tree/main/01-Relationships_of_RDBMS">Read on GitHub?</a></li><li><a href="#8e2a">What is RDBMS?</a></li><li><a href="#88bd">How the relationship is maintained</a></li><li><a href="#4984">Context of Use Case Instance</a></li><li><a href="#c709">What is an ER Diagram?</a></li><li><a href="#2dd2">Types of Relationship</a><br>1. <a href="#ce59">One-to-One Relation</a><br>2. <a href="#53c7">One-to-Many Relation</a><br>3. <a href="#0ba9">Many-to-Many Relation</a><br>4. <a href="#200e">Self Referencing/Recursive Relation</a></li><li><a href="#3458">Key Takeaways</a></li><li><a href="#c0a6">Bonus</a></li><li><a href="#86ae">Reach Out</a></li></ol><h3>What is RDBMS?</h3><ul><li><strong>RDBMS</strong> stands for <strong>Relational Database Management System</strong>.</li><li><strong>Relations</strong> can exist between any <strong>two entities</strong> and in database terms, <strong>entities</strong> are generally referred to as <strong>database tables.</strong></li><li>It’s <strong>relational</strong> as there may <strong>exist</strong> a type of <strong>relation</strong> between two <strong>tables</strong> from the same database. Except there could be a Self-referencing (Recursive) relation within the table itself.</li></ul><h3>How the relationship is maintained</h3><ul><li>Every table has a <strong>PRIMARY KEY</strong> which is a <strong>UNIQUE</strong> identifier of data/record in each table, with the help of this key we can identify and relate each <strong>UNIQUE</strong> record with another <strong>UNIQUE</strong> record.</li><li>To create a relation between two tables namely Table A and Table B. We keep the reference to the <strong>PRIMARY KEY</strong> of Table A as a <strong>FOREIGN KEY</strong> in Table B or vice versa.</li><li>When two tables have a relation between them and Table B requires reference to Table A but not vice versa then Table A can be referred to as Parent Table and Table B as Child Table, i.e. Child Table has information which logically depends on the Parent Table. The rule of thumb is to keep the <strong>FOREIGN KEY</strong> column in the Child Table and some business cases may demand it to be in the Parent Table.</li><li>If the table has a <strong>FOREIGN KEY</strong> constraint then it has a relation with other data records/tables and the type of relation can be identified based on the constraints on <strong>FOREIGN KEY</strong>.</li><li>When updating or deleting related records we need to ensure integrity is maintained for that purpose we can add additional constraints of <strong>ON DELETE</strong> &amp; <strong>ON UPDATE</strong> to <strong>FOREIGN KEY</strong> with valid values of <strong>RESTRICT</strong>, <strong>CASCADE</strong>, <strong>SET NULL</strong>, <strong>SET DEFAULT</strong>, or <strong>NO ACTION</strong>.</li></ul><h3>Context of Use Case Instance</h3><p>You have been given a task to design a database schema for a blog site where the author can write blogs and publish them with the facility to add one or more appropriate tags. After a certain no. of engagement author can add their personal bank information to monetize their account which will be stored in a separate encrypted table. Other authors can add constructive comments to the desired blog. The site should have the facility to filter the blog based on the tags, if a sub-category is selected then fetch all blogs having matching sub-category tag and if a parent-category is selected then fetch all blogs with parent-category tag and its sub-category tag too. Following are the gathered Crux points:</p><ul><li>A blog can be authored by a single author only.</li><li>A single author can publish multiple blogs.</li><li>Blog will have a minimum of one or more tags of category or sub-categories.</li><li>The author can add private finance information.</li><li>A blog can have comments from other users.</li><li>If a sub-category tag is added there is no need to enforce the parent category tag explicitly, but if the filter is applied to the parent category then all blog of the parent category &amp; sub-category needs to be fetched.</li><li>The tag will have core categories and sub-categories.</li></ul><h3>What is an ER Diagram?</h3><p>An <strong>Entity-Relationship Diagram</strong> (ERD) in RDBMS is a visual representation of a database’s structure. It helps to design databases by illustrating what data is stored, its structure, and how entities are linked. It consists of:</p><ol><li><strong>Entities</strong> Objects or concepts or tables in the database, like “Blog”, “Author”, “Tag” or “Finance”.</li><li><strong>Attributes</strong> Properties of entities, such as “BlogID”, “AuthorID”, “AuthorName” or “TagName”.</li><li><strong>Relationships</strong> Connections between entities, showing how they relate to each other, like “Author publishes the blog”.</li><li><strong>Cardinality</strong> The number of instances of one entity that can be related to the number of instances of another entity., e.g., “1–1” for one-to-one or “1-M” for one-to-many relationships.</li></ol><h4>ER Diagram Cardinality Notation</h4><figure><img alt="Crow’s foot notation for Cardinality which includes for one, many, one and only one, zero or one, one or many cardinalities." src="https://cdn-images-1.medium.com/max/599/1*QU6aeQxuo2m9-XoTZWMyFw.png" /></figure><h3>Types of Relationship</h3><p>There are 3 main types of relationships in RDBMS</p><ul><li>One-to-One</li><li>One-to-Many</li><li>Many-to-Many</li></ul><figure><img alt="ER Diagram for one-to-one, one-to-many, many-to-many and self-referencing/recursive relationship" src="https://cdn-images-1.medium.com/max/782/1*d22WI6lqqH4jnNV2cJxNwg.png" /></figure><ul><li>Self/Recursive Relation: This is a special case where the record is referenced to another record from the same table with any one of the 3 relationship types.</li></ul><h3>One-to-One Relation</h3><p>A <strong>one-to-one</strong> relationship is a type of relationship between two tables where each record in one table can be associated with exactly one record in another table, and vice versa. This means that for every row/data record in the first table, there can be a corresponding and <strong>UNIQUE</strong> row in the second table, and vice versa.<br>For one-to-one relations, there can be unidirectional or bidirectional integrity of <strong>FOREIGN KEY</strong> constraints.</p><ul><li>If it’s unidirectional and <strong>FOREIGN KEY</strong> is in the child table then the <strong>FOREIGN KEY</strong> column can have the constraint of <strong>NOT NULL</strong> which will ensure the parent record exists for the child record.</li><li>If it’s unidirectional and <strong>FOREIGN KEY</strong> is in the parent table then the <strong>FOREIGN KEY</strong> column cannot have the constraint of <strong>NOT NULL</strong>. As the child is dependent on the parent and if the parent record is not available then the child record will not be available before the parent record.</li><li>If it’s bidirectional then none of the <strong>FOREIGN KEY</strong>columns will have <strong>NOT NULL</strong> constraint. It’s similar to the paradox of “What came first? Chicken or Egg?</li></ul><p>Take an example of inserting data records in the one-to-one setup where <strong>1</strong> is related to <strong>a</strong><br> 1. Add record <strong>1</strong> in Table A<br> 2. Add record <strong>a</strong> in Table B<br> 3. Associate <strong><em>a</em></strong> from Table B in the record <strong><em>1</em></strong> of Table A</p><blockquote><strong>In a one-to-one relation setting, </strong><strong>FOREIGN KEY should have a </strong><strong>UNIQUE constraint which ensures relationship integrity.</strong></blockquote><h4>Use Case</h4><p>The author can add their finance information to the system and there will be one-to-one relation mapping as authors are allowed to add only 1 finance information.<br>The author’s details will be in the Author table and its finance information will be in the Finance table. The author will be the parent table and Finance will be the child table.</p><h4>Enhanced ER Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*ng9K2KyYSuRhg_boVWOcdQ.png" /><figcaption>One-to-one Relationship</figcaption></figure><h4>Create Query</h4><pre>CREATE TABLE `blogs`.`author` (<br>  `AuthorID` INT AUTO_INCREMENT,<br>  `AuthorName` VARCHAR(255) NOT NULL,<br>  `PenName` VARCHAR(45) NOT NULL,<br>  PRIMARY KEY (`AuthorID`));<br><br>CREATE TABLE `blogs`.`finance` (<br>  `FinanceID` INT NOT NULL AUTO_INCREMENT,<br>  `CardNo` VARCHAR(16) NOT NULL,<br>  `CardType` VARCHAR(45) NOT NULL,<br>  `AuthorID` INT UNIQUE NOT NULL,<br>  PRIMARY KEY (`FinanceID`),<br> FOREIGN KEY (`AuthorID`)<br>    REFERENCES `blogs`.`author` (`AuthorID`)<br>    ON DELETE NO ACTION<br>    ON UPDATE NO ACTION);</pre><h4>Insert Query</h4><pre>INSERT INTO `blogs`.`author` (`AuthorName`, `PenName`) VALUES (&#39;John Doe&#39;, &#39;blogger&#39;);<br>INSERT INTO `blogs`.`author` (`AuthorName`, `PenName`) VALUES (&#39;Jane Doe&#39;, &#39;techie&#39;);<br>INSERT INTO `blogs`.`finance` ( `CardNo`, `CardType`, `AuthorID`) VALUES (&#39;123&#39;, &#39;visa&#39;, &#39;2&#39;);<br>INSERT INTO `blogs`.`finance` ( `CardNo`, `CardType`, `AuthorID`) VALUES (&#39;789&#39;, &#39;visa prem&#39;, &#39;1&#39;);</pre><h4>Fetch Query</h4><pre>SELECT * FROM blogs.author;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f96c8adf1e86c3d6a091180856574b18/href">https://medium.com/media/f96c8adf1e86c3d6a091180856574b18/href</a></iframe><pre>SELECT * FROM blogs.finance;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7079dd5aa8c4b7f67c99f601811870a7/href">https://medium.com/media/7079dd5aa8c4b7f67c99f601811870a7/href</a></iframe><pre>SELECT * FROM blogs.author JOIN blogs.finance USING(AuthorID);<br>-- SELECT * FROM blogs.author JOIN blogs.finance ON author.AuthorId=finance.AuthorId;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a60c6605136a87c2c670c9275c071566/href">https://medium.com/media/a60c6605136a87c2c670c9275c071566/href</a></iframe><h3>One-to-Many Relation</h3><p>A <strong>one-to-many</strong> relationship is the most commonly used relationship among tables. In this type of relationship, data records from the parent table can be linked to zero or more data records in the child table. However, one record from the child table cannot be linked to more than one record in the parent table. For one-to-many relations, there can be only a unidirectional <strong>FOREIGN KEY</strong> constraint in the child table.</p><blockquote><strong>In a one-to-many relation setting, </strong><strong>FOREIGN KEY will not have a </strong><strong>UNIQUE constraint which allows for many(duplicate) references.</strong></blockquote><h4>Use Case</h4><p>There are multiple instances in our use case for one-to-many such as a single author can publish multiple blogs, a blog can have multiple comments, we can have a core tag table and sub-tag table which can hold mapping of core &amp; sub-category tag, etc.<br>For reference let’s select an instance of a blog that can have multiple comments, where the blog will be stored in the blog table and comments will be stored in the comment table.</p><h4>Enhanced ER Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*vUgmTIJKs_KPMv0nCQstYw.png" /><figcaption>One-to-many Relationship</figcaption></figure><h4>Create Query</h4><pre>CREATE TABLE `blogs`.`blog` (<br>  `BlogID` INT NOT NULL AUTO_INCREMENT,<br>  `AuthorID` INT NOT NULL,<br>  `Title` VARCHAR(100) NOT NULL,<br>  `PublishDate` DATE NOT NULL,<br>  PRIMARY KEY (`BlogID`),<br>  FOREIGN KEY (`AuthorID`)<br>    REFERENCES `blogs`.`author` (`AuthorID`)<br>    ON DELETE RESTRICT<br>    ON UPDATE RESTRICT);<br><br><br>CREATE TABLE `blogs`.`comment` (<br>  `CommentID` INT NOT NULL AUTO_INCREMENT,<br>  `Comment` VARCHAR(255) NOT NULL,<br>  `BlogID` INT NOT NULL,<br>  `Commentor` INT NULL,<br>  PRIMARY KEY (`CommentID`),<br>  FOREIGN KEY (`Commentor`)<br>    REFERENCES `blogs`.`author` (`AuthorID`)<br>    ON DELETE SET NULL<br>    ON UPDATE SET NULL,<br>  FOREIGN KEY (`BlogID`)<br>    REFERENCES `blogs`.`blog` (`BlogID`)<br>    ON DELETE CASCADE<br>    ON UPDATE CASCADE);</pre><h4>Insert Query</h4><pre>INSERT INTO `blogs`.`blog` (`AuthorID`, `Title`, `PublishDate`) VALUES (&#39;1&#39;, &#39;John&#39;&#39;s Adventure&#39;, &#39;2023-09-10&#39;);<br>INSERT INTO `blogs`.`blog` (`AuthorID`, `Title`, `PublishDate`) VALUES (&#39;1&#39;, &#39;Anonymous John Doe&#39;, &#39;2023-10-07&#39;);<br>INSERT INTO `blogs`.`blog` (`AuthorID`, `Title`, `PublishDate`) VALUES (&#39;2&#39;, &#39;Uncommon Jane Doe&#39;, &#39;2023-10-20&#39;);<br>INSERT INTO `blogs`.`blog` (`AuthorID`, `Title`, `PublishDate`) VALUES (&#39;1&#39;, &#39;RDBMS&#39;&#39;s Relationship&#39;, &#39;2023-10-31&#39;);<br>INSERT INTO `blogs`.`comment` (`Comment`, `BlogID`, `Commentor`) VALUES (&#39;Nice Adventure&#39;, &#39;1&#39;, &#39;2&#39;);<br>INSERT INTO `blogs`.`comment` (`Comment`, `BlogID`, `Commentor`) VALUES (&#39;Yeah Thanks&#39;, &#39;1&#39;, &#39;1&#39;);<br>INSERT INTO `blogs`.`comment` (`Comment`, `BlogID`, `Commentor`) VALUES (&#39;May I know the place?&#39;, &#39;1&#39;, &#39;2&#39;);<br>INSERT INTO `blogs`.`comment` (`Comment`, `BlogID`, `Commentor`) VALUES (&#39;I think it&#39;&#39;s gonna be good&#39;, &#39;4&#39;, &#39;2&#39;);<br>INSERT INTO `blogs`.`comment` (`Comment`, `BlogID`, `Commentor`) VALUES (&#39;Wish me the Best&#39;, &#39;4&#39;, &#39;1&#39;);</pre><h4>Fetch Query</h4><pre>SELECT * FROM blogs.blog;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5868726bdcbba022c35081bb9b932141/href">https://medium.com/media/5868726bdcbba022c35081bb9b932141/href</a></iframe><pre>SELECT * FROM blogs.comment;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be2c8e755413128df22a83e83df1f121/href">https://medium.com/media/be2c8e755413128df22a83e83df1f121/href</a></iframe><pre>SELECT * FROM blogs.blog LEFT JOIN blogs.comment USING(BlogID);</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/613b44f22888ddf4c1e88a858572abc5/href">https://medium.com/media/613b44f22888ddf4c1e88a858572abc5/href</a></iframe><h3>Many-to-Many Relation</h3><p><strong>Many-to-many</strong> is a relation where a record from one table can be associated with many rows from another table and vice versa, i.e. parent records can have multiple child records &amp; child records can have multiple parent records.<br>This type of relationship can be created using a third table called the “Junction table” or “Bridging table” which will hold the mapping of both tables.</p><blockquote><strong>In many-to-many relations, none of the two tables will hold </strong><strong>FOREIGN KEY. </strong><strong>FOREIGN KEY will be residing in Junction/Bridging Table which will have a Composite Primary Key consisting of </strong><strong>FOREIGN KEYs referencing Parent and child records.</strong></blockquote><h4>Use Case</h4><p>A blog can have one or more tags and multiple blogs can fall under the same category or sub-category.</p><h4>Enhanced ER Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*DeLDW8d7_3MntWA8jfMQ6w.png" /><figcaption>Many-to-many Relationship</figcaption></figure><h4>Create Query</h4><p>Blog table created in One-to-many relation<br>Tag table created in Recursive relation</p><pre>CREATE TABLE `blogs`.`blogtag` (<br>  `BlogID` INT  NOT NULL,<br>  `TagID` INT  NOT NULL,<br>  PRIMARY KEY (`BlogID`, `TagID`),<br>  FOREIGN KEY (`BlogID`)<br>    REFERENCES `blogs`.`blog` (`BlogID`)<br>    ON DELETE CASCADE<br>    ON UPDATE CASCADE,<br>  FOREIGN KEY (`TagID`)<br>    REFERENCES `blogs`.`tag` (`TagID`)<br>    ON DELETE RESTRICT<br>    ON UPDATE RESTRICT);</pre><h4>Insert Query</h4><p>Blog table populated in One-to-many relations.<br>Tag table populated in Recursive relations.</p><pre>INSERT INTO `blogs`.`blogtag` (`BlogID`, `TagID`) VALUES (&#39;1&#39;, &#39;2&#39;);<br>INSERT INTO `blogs`.`blogtag` (`BlogID`, `TagID`) VALUES (&#39;1&#39;, &#39;6&#39;);<br>INSERT INTO `blogs`.`blogtag` (`BlogID`, `TagID`) VALUES (&#39;2&#39;, &#39;5&#39;);<br>INSERT INTO `blogs`.`blogtag` (`BlogID`, `TagID`) VALUES (&#39;3&#39;, &#39;5&#39;);<br>INSERT INTO `blogs`.`blogtag` (`BlogID`, `TagID`) VALUES (&#39;4&#39;, &#39;4&#39;);</pre><h4>Fetch Query</h4><p>Blog table record in One-to-many relations.<br>Tag table record in Recursive relations.</p><pre>SELECT * FROM blogs.blogtag;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c55c67b6c996ab43bd48cbd465d85866/href">https://medium.com/media/c55c67b6c996ab43bd48cbd465d85866/href</a></iframe><pre>SELECT * FROM blogs.blog JOIN blogs.blogtag USING(BlogID) JOIN blogs.tag USING(TagID);</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49b9c9f1049c3b58506d6b20adaf9fcf/href">https://medium.com/media/49b9c9f1049c3b58506d6b20adaf9fcf/href</a></iframe><h3>Self-referencing/Recursive Relation</h3><p>A <strong>self-referencing/recursive</strong> relationship in a database occurs when a column in a table relates to another column in the same table i.e. parent and child table are the same which means that the table contains a <strong>FOREIGN KEY</strong> column that references its <strong>PRIMARY KEY</strong>(<strong>UNIQUE</strong>) column. Recursive relations can exhibit any of the <strong><em>one-to-one</em></strong><em>, </em><strong><em>one-to-many</em></strong><em>, or </em><strong><em>many-to-many</em></strong><em> </em>relations. This type of relationship is often used to model <strong>hierarchical </strong>or <strong>recursive </strong>data structures where each row in the table has a parent or ancestor within the same table.</p><blockquote><strong>In self-referencing relation, the </strong><strong>FOREIGN KEY column will hold a reference to the </strong><strong>PRIMARY KEY(</strong><strong>UNIQUE) column of the same table.</strong></blockquote><h4>Use Case</h4><p>The core tag can have many sub-categories which can be modeled as one-to-many relations with the help of two tables or in a single table with recursive relations exhibiting one-to-many relations. The decision of self-referencing table completely depends on one’s personal choice.</p><h4>Enhanced ER Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*rDYLguhsVAdoRr9VkWSUvg.png" /><figcaption>Self-referencing/Recursive Relationship</figcaption></figure><h4>Create Query</h4><pre>CREATE TABLE `blogs`.`tag` (<br>  `TagID` INT NOT NULL AUTO_INCREMENT,<br>  `TagName` VARCHAR(45) NOT NULL,<br>  `ParentTag` INT NULL,<br>  PRIMARY KEY (`TagID`));<br><br>ALTER TABLE `blogs`.`tag`<br>ADD CONSTRAINT `ParentTag`<br>FOREIGN KEY (`ParentTag`)<br>  REFERENCES `blogs`.`tag` (`TagID`)<br>  ON DELETE SET NULL<br>  ON UPDATE SET NULL;</pre><h4>Insert Query</h4><pre>INSERT INTO `blogs`.`tag` (`TagName`) VALUES (&#39;Region&#39;);<br>INSERT INTO `blogs`.`tag` (`TagName`, `ParentTag`) VALUES (&#39;Mountains&#39;, &#39;1&#39;);<br>INSERT INTO `blogs`.`tag` (`TagName`) VALUES (&#39;Tech&#39;);<br>INSERT INTO `blogs`.`tag` (`TagName`, `ParentTag`) VALUES (&#39;RDBMS&#39;, &#39;3&#39;);<br>INSERT INTO `blogs`.`tag` (`TagName`) VALUES (&#39;Biography&#39;);<br>INSERT INTO `blogs`.`tag` (`TagName`) VALUES (&#39;Adventure&#39;);</pre><h4>Fetch Query</h4><pre>SELECT * FROM blogs.tag;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5da10bf85d3eae10a1b035e69a00030/href">https://medium.com/media/d5da10bf85d3eae10a1b035e69a00030/href</a></iframe><pre>SELECT t1.TagID, t1.TagName, t2.TagName AS ParentTag FROM blogs.tag t1 LEFT JOIN blogs.tag t2 ON t1.ParentTag=t2.TagID;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f193116afefb08bbf1567445a0463d5/href">https://medium.com/media/0f193116afefb08bbf1567445a0463d5/href</a></iframe><h3>Key Takeaways</h3><ul><li>RDBMS has 3 main types of relations namely <strong>one-to-one,</strong> <strong>one-to-many,</strong> and <strong>many-to-many.</strong></li><li><strong>One-to-one</strong> has a <strong>UNIQUE</strong> constraint on the <strong>FOREIGN KEY</strong> column, it can be a unidirectional or bidirectional relation.</li><li><strong>One-to-many</strong> does not have a <strong>UNIQUE</strong> constraint on the <strong>FOREIGN KEY</strong> column, it will be unidirectional, and the <strong>FOREIGN KEY</strong> column will be in the child table.</li><li><strong>Many-to-many</strong> requires a Junction/Bridging table to maintain a relationship that has composite primary keys consisting of <strong>FOREIGN KEY</strong>s referencing Parent and child records.</li><li><strong>Recursive relation</strong> is mainly used to maintain hierarchy relation and it contains a <strong>FOREIGN KEY</strong> column that references its <strong>PRIMARY KEY</strong>(<strong>UNIQUE</strong>) column and it can exhibit any one type of relationship.</li></ul><h3>Bonus</h3><h4>Complete Enhanced Entity Relationship Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ys9vasqLBsZeMnJY4yURAg.png" /></figure><h4>Recursive Fetching</h4><p>Recursive CTE will fetch all the records from the hierarchy in a top-to-bottom or bottom-to-top approach.</p><h4>Bottom-to-Top</h4><pre>WITH RECURSIVE cte (TagID, TagName, ParentTag) AS (<br>  SELECT t1.* FROM tag t1 WHERE t1.TagID=2<br>  UNION ALL<br>  SELECT t2.* FROM tag t2 INNER JOIN cte ON t2.TagID = cte.ParentTag<br>)<br>SELECT * FROM cte;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee317522e5824b2f8dfff51086bf3099/href">https://medium.com/media/ee317522e5824b2f8dfff51086bf3099/href</a></iframe><h4>Top-to-Bottom</h4><pre>WITH RECURSIVE cte (TagID, TagName, ParentTag) AS (<br>  SELECT t1.* FROM tag t1 WHERE t1.TagID=1<br>  UNION ALL<br>  SELECT t2.* FROM tag t2 INNER JOIN cte ON t2.parentTag = cte.TagID<br>)<br>SELECT * FROM cte;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6aa06874c4533cc9463e840141458f5/href">https://medium.com/media/b6aa06874c4533cc9463e840141458f5/href</a></iframe><h4>Object Relationship Mapper (ORM)</h4><ul><li><strong>Object-relational mapping</strong> (ORM) is a programming technique that uses <strong>object-oriented programming</strong> (OOP) features in the relational database management system (RDBMS) world. To deep dive into ORM with practical use cases implemented in <strong>NodeJs</strong> and <strong>Python </strong>read my blog <a href="https://blog.devgenius.io/orm-bridging-code-and-dbms-b61dbb0ce798">ORM: Bridging Code and DBMS</a>.</li><li>It often provides a level of database independence i.e. user can learn an ORM framework that can be implemented on various databases which takes the hassle of remembering different keywords for the same logic in several SQL Systems. ORM frameworks protect against SQL injection attacks by handling parameterized queries &amp; input sanitization automatically.</li><li>It comes with its own set of disadvantages as it adds to performance overhead, requires learning of programming language &amp; ORM framework, can introduce complexity, and hurdle the optimization and database-specific features that may not be available in ORM.</li><li><strong><em>ORMs Framework</em></strong> for programming language: <strong>SQLAlchemy</strong>(<strong>Python</strong>), <strong>Sequelize</strong>(<strong>NodeJs</strong>), <strong>Hibernate</strong>(<strong>Java</strong>), <strong>ActiveRecord</strong>(<strong>Ruby</strong>), etc.</li></ul><h4>Reach Out</h4><p>For more intuitive blogs follow me on <a href="https://godwin1100.medium.com/">Medium</a> &amp; <a href="https://github.com/GodWin1100">Github</a>. <br>You can also reach out to me via <a href="https://www.linkedin.com/in/godwin1100/">LinkedIn</a> or <a href="https://twitter.com/l_shivam_l">X(Twitter)</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2edc98e0951" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/relationships-of-rdbms-f2edc98e0951">Relationships of RDBMS</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>