{"id":18604098,"url":"https://github.com/gravmatt/sqlitemodel","last_synced_at":"2025-10-12T10:07:13.220Z","repository":{"id":38362059,"uuid":"53532216","full_name":"gravmatt/sqlitemodel","owner":"gravmatt","description":"wrapper for the sqlite3 database that enables you to create models you can easily save, query and retrieve from the database.","archived":false,"fork":false,"pushed_at":"2018-02-13T21:21:10.000Z","size":19,"stargazers_count":18,"open_issues_count":2,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-25T03:34:58.722Z","etag":null,"topics":["python","sqlite","sqlite3-database"],"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/gravmatt.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}},"created_at":"2016-03-09T21:14:02.000Z","updated_at":"2024-05-25T16:36:14.000Z","dependencies_parsed_at":"2022-08-25T04:50:49.952Z","dependency_job_id":null,"html_url":"https://github.com/gravmatt/sqlitemodel","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gravmatt%2Fsqlitemodel","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gravmatt%2Fsqlitemodel/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gravmatt%2Fsqlitemodel/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gravmatt%2Fsqlitemodel/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gravmatt","download_url":"https://codeload.github.com/gravmatt/sqlitemodel/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248281415,"owners_count":21077423,"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":["python","sqlite","sqlite3-database"],"created_at":"2024-11-07T02:16:37.273Z","updated_at":"2025-10-12T10:07:08.187Z","avatar_url":"https://github.com/gravmatt.png","language":"Python","readme":"# sqlitemodel\n\nsqlitemodel is a wrapper for the sqlite3 database that enables you to\ncreate models you can easily save, query and retrieve from the database.\n\nThis is build with three classes who abstract the database communication\nand the object management.\n\n## Installation\n\nInstall through **pip**.\n\n```\n$ pip install sqlitemodel\n```\n\nor get from source\n\n```\n$ git clone https://github.com/gravmatt/sqlitemodel.git\n$ cd sqlitemodel\n$ python setup.py install\n```\n\n## Classes\n\n* [**Model** - Abstraction class to build database models](#model)\n\n* [**SQL** - SQL query builder](#sql)\n\n* [**Database** - sqlite database interface](#database)\n\n## Model\n\nClass to abstract the model communication with the database.\n\n### Usage\n\n**Import**\n\n```\nfrom sqlitemodel import Model, Database\n\n# IMPORTANT\nDatabase.DB_FILE = 'path/to/database.db'\n```\n\n**Set the path to the database when your application starts or before you try to accessing the database.**\n\n#### Example\n\nBuilding a user class that inherits the Model class to show how it works.\n\n```\nclass User(Model):\n    def __init__(self, id=None):\n        Model.__init__(self, id, dbfile=None, foreign_keys=False, parse_decltypes=False)\n\n        self.firstname = ''\n        self.lastname = ''\n        self.age = ''\n\n        # Tries to fetch the object by its rowid from the database\n        self.getModel()\n\n\n    # Tells the database class the name of the database table\n    def tablename(self):\n        return 'users'\n\n\n    # Tells the database class more about the table columns in the database\n    def columns(self):\n        return [\n            {\n              'name': 'firstname',\n              'type': 'TEXT'\n            },\n            {\n              'name': 'lastname',\n              'type': 'TEXT'\n            },\n            {\n              'name': 'age',\n              'type': 'INTEGER'\n            }\n        ]\n```\n\nThe two methods `tablename()` and `columns()` are required, to map the table columns with the `Model` objects.\n\n`id` argument and the `getModel()` method in the constructor are optional.\n\nIt also possible to use the `selectCopy()` method to query for any data in the database table and fill the model object with the result.\n\n```\nselectCopy(SQL() | raw_sql_query_string)\n```\n\nEx:\n\n```\nclass User(Model):\n    def __init__(self, id=None, email=None):\n        Model.__init__(self, id)\n        if(email):\n            self.selectCopy(SQL().WHERE('email', '=', email))\n```\n\n**The `Model` class constructor has an optional `dbfile` argument. If it is set, the static variable `Database.DB_FILE` is ignored.**\n\n#### Working with the User class\n\n**Creating a new User**\n\n```\n# create a new user\nuser = User()\n\n# creating the table inside the database\nuser.createTable()\n\n# add infos about the user\nuser.firstname = 'Rene'\nuser.lastname = 'Tanczos'\nuser.age = 25\n\n# save the user into the database\nuser.save()\n```\n\n**Retriving the User from the database**\n\n```\n# get it by id\nuser = User(1)\n\n# get the user by his firstname and lastname\n# User().selectOne(SQL())\nuser = User().selectOne(SQL().WHERE('firstname', '=', 'Rene').AND().WHERE( 'lastname', '=', 'Tanczos'))\n\n# Or get more the one user\n# this method will return an array of matching users\nusers = User().select(SQL().WHERE('age', '=', 25))\n```\n\n## SQL\n\nClass to build SQL query to reduce misspelling and to abstract this problem a bit.\n\n### Usage\n\n**Import**\n\n```\nfrom sqlitemodel import SQL\n```\n\n**INSERT**\n\n```\nsql = SQL().INSERT('users').VALUES(firstname='Rene', lastname='tanczos')\n\nprint sql.toStr()\n# INSERT INTO users (firstname,lastname) VALUES (?,?);\n\nprint sql.getValues()\n# ('Rene', 'tanczos')\n```\n\n**UPDATE**\n\n```\nsql = SQL().UPDATE('users').SET('firstname', 'Rene').SET('lastname', 'Tanczos').WHERE('firstname', '=', 'Rene').AND().WHERE('lastname', '=', 'Tanczos')\n\nprint sql.toStr()\n# UPDATE users SET firstname=?, lastname=? WHERE firstname=? AND lastname=?;\n\nprint sql.getValues()\n# ('Rene', 'Tanczos', 'Rene', 'Tanczos')\n```\n\n**SELECT**\n\n```\nsql = SQL().SELECT('name', 'age', 'size').FROM('users').WHERE('age', '=', 27).AND().WHERE('size', '\u003c', 190).ORDER_BY('age', 'ASC').LIMIT(0, 10)\n\nprint sql.toStr()\n# SELECT name, age, size FROM users WHERE age=? AND size\u003c? ORDER BY age ASC LIMIT 0,10;\n\nprint sql.getValues()\n# (27, 190)\n```\n\n`WHERE`\n\nThe WHERE method has a optional `isRaw` parameter.\n\nIf set to `True`, the SQL class paste the value directly into the sql query and does not use the `?` symbol.\n\n```\nWHERE('size', '\u003c', 190, isRaw=True)\n```\n\n**DELETE**\n\n```\nsql = SQL().DELETE('users').WHERE('id', '=', 4)\n\nprint sql.toStr()\n# DELETE FROM users WHERE id=?;\n\nprint sql.values\n# (4,)\n```\n\n## Database\n\nRepresents the database.\n\n### Usage\n\nFirst you should set the database file path to your sqlite3 database.\n\nDon't worry if it doesn't exist yet. Sqlite3 automatically creates a database file on the selected path if it doesn't exists.\n\n```\nfrom sqlitemodel import Database\n```\n\n#### Set the path to the database\n\nIt is recommended to set the path to the database after starting the application by the static variable inside the *Database* class.\n\n```\nDatabase.DB_FILE = 'path/to/database.db'\n\ndb = Database()\n```\n\nBut the path can be also set inside the *Database* constructor while the object initializes.\n\n```\ndb = Database('path/to/database.db')\n```\n\n#### **with** statement\n\nThe *Database* class supports the *with* statement whitch is recommended to use.\n\n```\nwith Database() as db:\n    users = db.select(SQL().SELECT().FROM('users'))\n```\n\nThe database connection get automatically closed after the *with* block is processed.\n\n#### Methods\n\nAll of this method using a *Model* object as first argument, so that the *Database* object knows how to use it.\n\n```\nclose()\n# close connection\n\ncreateTable(model)\n# create the database table if not exists by the the model object\n\nsave(model)\n# create or update a model object and return it id\n\ndelete(model)\n# delete a model object and return True/False\n\nselect(model, SQL() | sql query , values=())\n# return a array of the given model\n\nselectOne(model, SQL() | sql query, values=())\n# return the first matching entry of the given model\n\nselectById(model, id)\n# return the a model object by his id\n```\n\nIf there is some data without a *Model*, it can be retrieved as raw data of a *list* or *list* of *Dict* objects.\n\n```\ngetRaw(SQL() | sql query, values=(), max=-1)\n# return an array of results.\n# index 0 is the header of the table\n\ngetDict(SQL() | sql query, values=(), max=-1)\n# return a list array with a Dict object.\n# the key of the Dict object is the column name\n```\n\nTo count the results of a query, the method *zeroZero()* can be used.\n\n```\nzeroZero(SQL() | sql query)\n# It return the the first column of the first line ( result[0][0] )\n# That why the method is called zeroZero()\n```\n\nTo check if a table or column exists, the functions *table_exists()* and *column_exists()* can be used.\nBoth will return a boolean value if the table/column was found or not.\n\n```\ntable_exists('tablename')\n# True or False\n\ncolumn_exists('tablename', 'column_name')\n# True or False\n```\n\n## Licence\n\nThe MIT License (MIT)\n\nCopyright (c) 2016-2017 René Tanczos\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgravmatt%2Fsqlitemodel","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgravmatt%2Fsqlitemodel","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgravmatt%2Fsqlitemodel/lists"}