<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dipesh Kumar Singh</title>
    <description>The latest articles on DEV Community by Dipesh Kumar Singh (@dipesh_2301_kumar).</description>
    <link>https://dev.to/dipesh_2301_kumar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1685647%2F27d85ce8-b052-49f9-ba41-a84b96f88fdb.jpg</url>
      <title>DEV Community: Dipesh Kumar Singh</title>
      <link>https://dev.to/dipesh_2301_kumar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dipesh_2301_kumar"/>
    <language>en</language>
    <item>
      <title>LLD- In Memory Database Python</title>
      <dc:creator>Dipesh Kumar Singh</dc:creator>
      <pubDate>Wed, 26 Jun 2024 07:08:55 +0000</pubDate>
      <link>https://dev.to/dipesh_2301_kumar/lld-in-memory-database-python-1e9p</link>
      <guid>https://dev.to/dipesh_2301_kumar/lld-in-memory-database-python-1e9p</guid>
      <description>&lt;p&gt;&lt;strong&gt;Problem Statement:&lt;/strong&gt;&lt;br&gt;
The objective is to design and implement an in-memory SQL-like database, which should support the following set of operations/functionality:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It should be possible to create, or delete tables in a database.&lt;/li&gt;
&lt;li&gt;A table definition comprises columns which have types. They can also have constraints. The supported column types are string and int.&lt;/li&gt;
&lt;li&gt;Users can give the constraint of string type that can have a maximum length of 20 characters.&lt;/li&gt;
&lt;li&gt;Users can give the constraint of int type that can have a minimum value of 1024.&lt;/li&gt;
&lt;li&gt;Support for mandatory fields&lt;/li&gt;
&lt;li&gt;It should be possible to insert records in a table.&lt;/li&gt;
&lt;li&gt;It should be possible to print all records in a table.&lt;/li&gt;
&lt;li&gt;It should be possible to filter and display records whose column values match a given value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Requirements Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Database Operations:&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Create, update, or delete tables.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Table Definition:&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Tables consist of columns with types and optional constraints.&lt;br&gt;
Supported column types: string (max length 20) and int (min value 1024).&lt;br&gt;
Support for mandatory fields.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Data Operations:&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Insert records into a table.&lt;br&gt;
Print all records in a table.&lt;br&gt;
Filter and display records based on column values matching a given value.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Class Diagram&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Database&lt;/strong&gt;: Manages multiple tables.&lt;br&gt;
&lt;strong&gt;Table&lt;/strong&gt;: Contains columns and records.&lt;br&gt;
&lt;strong&gt;Column&lt;/strong&gt;: Abstract base class for StringColumn and IntColumn.&lt;br&gt;
&lt;strong&gt;StringColumn&lt;/strong&gt;: Represents a column of type string with optional constraints.&lt;br&gt;
&lt;strong&gt;IntColumn&lt;/strong&gt;: Represents a column of type int with optional constraints.&lt;br&gt;
&lt;strong&gt;Record&lt;/strong&gt;: Represents a record (row) in a table.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation:&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

from abc import ABC,abstractmethod

class ColumnType:
    STRING="string"
    INT="int"

class Column(ABC):
    def __init__(self,name,column_type,required=False):
        self.name=name
        self.column_type=column_type
        self.required=required

    @abstractmethod
    def validate(self,value):
        pass

class StringColumn(Column):
    MAX_LENGTH=20
    def __init__(self,name,required=False):
        super().__init__(name,ColumnType.STRING,required)

    def validate(self,value):
        if not isinstance(value,str):
            return False
        if len(value)&amp;gt;self.MAX_LENGTH:
            print("Max length exceeeded !!")
            return False
        return True
class IntColumn(Column):
    MAX_LENGTH=1024
    MIN_LENGTH=-1024
    def __init__(self,name,required=False):
        super().__init__(name,ColumnType.INT,required)

    def validate(self,value):
        if not isinstance(value,int):
            return False
        if len(value)&amp;lt;self.MIN_LENGTH or len(value)&amp;gt;self.MAX_LENGTH:
            print("Min or Max length exceeeded !!")
            return False
        return True

class Record:
    def __init__(self,values):
        self.values=values

class Table:
    def __init__(self,name):
        self.name=name 
        self.columns={}
        self.records=[]

    def add_column(self,column):
        self.columns[column.name]=column

    def insert_record(self,values):
        record=Record(values)
        for column_name,column_obj in self.columns.items():
            if column_obj.required and column_name not in values:
                 raise Exception(f"Missing required column '{column_name}' in record.")
        self.records.append(record)

    def print_records(self):
        for record in self.records:
            print(record.values)

    def filter_records(self,column_name,value):
        filtered_records=[]
        for record in self.records:
            if column_name in record.values and record.values[column_name]==value:
                filtered_records.append(record.values)
        return filtered_records

class Database:
    def __init__(self):
        self.tables={}

    def create_table(self,table_name):
        if table_name in self.tables:
            raise Exception(f"table {table_name} already exists !!")
        self.tables[table_name]=Table(table_name)

    def delete_table(self,table_name):
        if table_name not in self.tables:
            raise Exception(f"table {table_name} does not exist !!")
        del self.tables[table_name]

    def get_table(self,table_name):
        if table_name not in self.tables:
            raise Exception(f"table {table_name} does not  exists !!")
        return self.tables[table_name]




if __name__=="__main__":
    db=Database()
    db.create_table("Employees")
    print(db.tables)

    db.get_table("Employees").add_column(StringColumn("Username",required=True))
    db.get_table("Employees").add_column(IntColumn("age",required=True))

    db.get_table("Employees").insert_record({"Username":"Alice","age":27})
    db.get_table("Employees").insert_record({"Username":"bob","age":28})
    db.get_table("Employees").insert_record({"Username":"Carl","age":20})

    print("All records in 'users' table:")
    db.get_table("Employees").print_records()

    filtered_records = db.get_table("Employees").filter_records("Username", "Carl")
    print("\nFiltered records where name is 'Carl':")
    for record in filtered_records:
        print(record)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjapdnzkk6pjwov3662wu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjapdnzkk6pjwov3662wu.png" alt="output for the inmemory db"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SOLID Principles:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Single Responsibility Principle: Each class has a clear and single responsibility (e.g., Database manages tables, Table manages columns and records).&lt;/p&gt;

&lt;p&gt;Open/Closed Principle: Code is open for extension (e.g., adding new column types) but closed for modification.&lt;/p&gt;

&lt;p&gt;Liskov Substitution Principle: Subclasses (StringColumn, IntColumn) can be substituted for their base class (Column).&lt;/p&gt;

&lt;p&gt;Interface Segregation Principle: No explicit interfaces in Python, but classes are designed to expose necessary methods (validate for columns, CRUD operations for tables).&lt;/p&gt;

&lt;p&gt;Dependency Inversion Principle: High-level modules (e.g., Database, Table) depend on abstractions (Column), not concretions.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This implementation provides a basic in-memory SQL-like database system in Python, fulfilling the given requirements while adhering to OOP and SOLID principles.&lt;/p&gt;

</description>
      <category>python</category>
      <category>lld</category>
      <category>systemdesign</category>
      <category>solidprinciples</category>
    </item>
  </channel>
</rss>
