{"id":21684754,"url":"https://github.com/codecaine-zz/simple_sqlite_crud","last_synced_at":"2025-03-20T11:27:22.160Z","repository":{"id":230648941,"uuid":"779893662","full_name":"codecaine-zz/simple_sqlite_crud","owner":"codecaine-zz","description":"General Sqlite3 CRUD class","archived":false,"fork":false,"pushed_at":"2024-12-23T23:39:29.000Z","size":19,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-25T12:07:15.572Z","etag":null,"topics":["class","crud","python","sqlite3"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codecaine-zz.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2024-03-31T04:30:00.000Z","updated_at":"2024-12-23T23:39:33.000Z","dependencies_parsed_at":"2024-03-31T05:44:57.932Z","dependency_job_id":null,"html_url":"https://github.com/codecaine-zz/simple_sqlite_crud","commit_stats":null,"previous_names":["codecaine-zz/simple_sqlite_crud"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codecaine-zz%2Fsimple_sqlite_crud","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codecaine-zz%2Fsimple_sqlite_crud/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codecaine-zz%2Fsimple_sqlite_crud/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codecaine-zz%2Fsimple_sqlite_crud/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codecaine-zz","download_url":"https://codeload.github.com/codecaine-zz/simple_sqlite_crud/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244603027,"owners_count":20479748,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["class","crud","python","sqlite3"],"created_at":"2024-11-25T16:17:00.257Z","updated_at":"2025-03-20T11:27:22.126Z","avatar_url":"https://github.com/codecaine-zz.png","language":"Python","readme":"# SQLite CRUD Example\n\nThis repository contains a simple example of how to perform CRUD (Create, Read, Update, Delete) operations using SQLite and SQLAlchemy in Python.\n\n## File Overview\n\n### Example\n\n```python\nBase = declarative_base()\n\n\nclass Employee(Base):\n    __tablename__ = \"employees\"\n    id = Column(Integer, primary_key=True, autoincrement=True)\n    first_name = Column(String)\n    last_name = Column(String)\n    email = Column(String)\n    department = Column(String)\n\n    def __repr__(self) -\u003e str:\n        return (\n            f\"\u003cEmployee(id={self.id}, first_name='{self.first_name}', \"\n            f\"last_name='{self.last_name}', email='{self.email}', \"\n            f\"department='{self.department}')\u003e\"\n        )\n\n\nclass Department(Base):\n    __tablename__ = \"departments\"\n    id = Column(Integer, primary_key=True, autoincrement=True)\n    name = Column(String, unique=True)\n    location = Column(String)\n\n    def __repr__(self) -\u003e str:\n        return (\n            f\"\u003cDepartment(id={self.id}, name='{self.name}', \"\n            f\"location='{self.location}')\u003e\"\n        )\n\n\nclass SQLiteCRUD:\n    def __init__(self, db_name: str) -\u003e None:\n        self.engine = create_engine(f\"sqlite:///{db_name}\")\n\n        @event.listens_for(self.engine, \"connect\")\n        def regexp_connection(dbapi_connection, connection_record):\n            import re\n\n            def regexp(expr, item):\n                return re.search(expr, item) is not None\n\n            dbapi_connection.create_function(\"REGEXP\", 2, regexp)\n\n        Base.metadata.create_all(self.engine)\n        self.Session = sessionmaker(bind=self.engine)\n        self.session: Session = self.Session()\n\n    def insert(self, obj: Base) -\u003e None:\n        try:\n            self.session.add(obj)\n            self.session.commit()\n        except IntegrityError:\n            self.session.rollback()\n            print(\n                f\"Warning: Could not insert {obj}. A unique constraint was violated.\"\n            )\n        except Exception as e:\n            self.session.rollback()\n            print(f\"Error: {e}\")\n\n    def read(\n        self, table: Base, conditions: Optional[Dict[str, Any]] = None\n    ) -\u003e List[Base]:\n        query = self.session.query(table)\n        if conditions:\n            for attr, condition in conditions.items():\n                if isinstance(condition, dict):\n                    for op, value in condition.items():\n                        if op == \"lt\":\n                            query = query.filter(getattr(table, attr) \u003c value)\n                        elif op == \"gt\":\n                            query = query.filter(getattr(table, attr) \u003e value)\n                        elif op == \"lte\":\n                            query = query.filter(getattr(table, attr) \u003c= value)\n                        elif op == \"gte\":\n                            query = query.filter(getattr(table, attr) \u003e= value)\n                        elif op == \"neq\":\n                            query = query.filter(getattr(table, attr) != value)\n                        elif op == \"contains\":\n                            query = query.filter(getattr(table, attr).contains(value))\n                        elif op == \"in_\":\n                            query = query.filter(getattr(table, attr).in_(value))\n                        elif op == \"regex\":\n                            query = query.filter(\n                                getattr(table, attr).op(\"REGEXP\")(value)\n                            )\n                        # Add more operators as needed\n                else:\n                    query = query.filter(getattr(table, attr) == condition)\n        return query.all()\n\n    def update(\n        self, table: Base, conditions: Dict[str, Any], data: Dict[str, Any]\n    ) -\u003e None:\n        query = self.session.query(table)\n        for attr, value in conditions.items():\n            query = query.filter(getattr(table, attr) == value)\n        query.update(data)\n        self.session.commit()\n\n    def delete(self, table: Base, conditions: Dict[str, Any]) -\u003e None:\n        query = self.session.query(table)\n        for attr, value in conditions.items():\n            query = query.filter(getattr(table, attr) == value)\n        query.delete()\n        self.session.commit()\n\n    def close(self) -\u003e None:\n        self.session.close()\n\n\nif __name__ == \"__main__\":\n    # Example usage:\n    db = SQLiteCRUD(\"company.db\")\n\n    # Insert a new employee\n    db.insert(\n        Employee(\n            id=1,\n            first_name=\"John\",\n            last_name=\"Doe\",\n            email=\"john.doe@example.com\",\n            department=\"Engineering\",\n        )\n    )\n\n    # Insert more employees\n    db.insert(\n        Employee(\n            id=2,\n            first_name=\"Jane\",\n            last_name=\"Smith\",\n            email=\"jane.smith@example.com\",\n            department=\"Marketing\",\n        )\n    )\n    db.insert(\n        Employee(\n            id=3,\n            first_name=\"Alice\",\n            last_name=\"Johnson\",\n            email=\"alice.johnson@example.com\",\n            department=\"Engineering\",\n        )\n    )\n\n    # Read employees from the 'Engineering' department\n    print(\"Engineering Department:\", db.read(Employee, {\"department\": \"Engineering\"}))\n\n    # Read employees with the last name 'Smith'\n    print(\"Employees with last name Smith:\", db.read(Employee, {\"last_name\": \"Smith\"}))\n\n    # Read employees with the first name 'Alice' and department 'Engineering'\n    print(\n        \"Alice in Engineering:\",\n        db.read(Employee, {\"first_name\": \"Alice\", \"department\": \"Engineering\"}),\n    )\n\n    # Read the 'employees' table\n    print(\"All employees:\", db.read(Employee))\n\n    # Update an employee's email\n    db.update(Employee, {\"id\": 1}, {\"email\": \"j.doe@example.com\"})\n\n    # Verify the update operation\n    print(\"Updated employee with id 1:\", db.read(Employee, {\"id\": 1}))\n\n    # Read the 'employees' table again\n    print(\"All employees after update:\", db.read(Employee))\n\n    # Delete an employee\n    db.delete(Employee, {\"id\": 1})\n\n    # Read the 'employees' table one more time\n    print(\"All employees after deletion:\", db.read(Employee))\n\n    # Example of using new filters\n    print(\"Employees with id greater than 1:\", db.read(Employee, {\"id\": {\"gt\": 1}}))\n    print(\n        \"Employees with first name containing 'Jane':\",\n        db.read(Employee, {\"first_name\": {\"contains\": \"Jane\"}}),\n    )\n    print(\n        \"Employees with id less than or equal to 3:\",\n        db.read(Employee, {\"id\": {\"lte\": 3}}),\n    )\n    print(\"Employees with id not equal to 2:\", db.read(Employee, {\"id\": {\"neq\": 2}}))\n    print(\"Employees with id in [1, 3]:\", db.read(Employee, {\"id\": {\"in_\": [1, 3]}}))\n    print(\n        \"Employees with email matching regex '.*@example.com':\",\n        db.read(Employee, {\"email\": {\"regex\": \".*@example.com\"}}),\n    )\n\n    # Insert a new department\n    db.insert(Department(id=1, name=\"Engineering\", location=\"Building A\"))\n\n    # Insert more departments\n    db.insert(Department(id=2, name=\"Marketing\", location=\"Building B\"))\n    db.insert(Department(id=3, name=\"HR\", location=\"Building C\"))\n\n    # Read departments\n    print(\"All departments:\", db.read(Department))\n\n    # Update a department's location\n    db.update(Department, {\"id\": 1}, {\"location\": \"Building D\"})\n\n    # Verify the update operation\n    print(\"Updated department with id 1:\", db.read(Department, {\"id\": 1}))\n\n    # Delete a department\n    db.delete(Department, {\"id\": 1})\n\n    # Read the 'departments' table one more time\n    print(\"All departments after deletion:\", db.read(Department))\n\n    # Close the database connection\n    db.close()\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodecaine-zz%2Fsimple_sqlite_crud","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodecaine-zz%2Fsimple_sqlite_crud","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodecaine-zz%2Fsimple_sqlite_crud/lists"}