diff --git a/README.md b/README.md index 910ea07..2107723 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,13 @@ True >> _dbmanager.delete_record(table="STUDENTS", primary_key="1010") ``` +### Filter record/s from a table + +```console +>> _dbmanager.filter_records(table="STUDENTS", values={"year":"2022"}) +[{'student_id': '1010', 'name': 'ABC', 'mark': 10, 'year': '2022'}, {'student_id': '1011', 'name': 'DEF', 'mark': 100, 'year': '2022'}] +``` + ## 🌱 Contributing Guide - Fork the project from the `alpha` branch and submit a Pull Request (PR) diff --git a/ReallySimpleDB/manager.py b/ReallySimpleDB/manager.py index 79f8c76..7309d96 100644 --- a/ReallySimpleDB/manager.py +++ b/ReallySimpleDB/manager.py @@ -277,6 +277,41 @@ def delete_record(self, table:str, primary_key, database:str=""): self.connection.commit() return True + + def filter_records(self, table:str, values:dict, database:str=""): + if self.connection == "" and not len(database): + raise TypeError("delete_record() missing 1 required positional argument: 'database'") + + if len(database): + self.create_connection(database) + + if self.is_table(table_name=table, database=database): + cursor = self.connection.cursor() + + sql = "SELECT * FROM {} WHERE ".format(table) + + for value in values: + try: + sql += value + "='" + values[value] + "' AND " + except TypeError: + sql += value + "=" + str(values[value]) + " AND " + + sql = sql[:-5] + ";" + + cursor.execute(sql) + rows = cursor.fetchall() + + columns = self.get_columns(table=table, database=database) + records = [] + tmp_dict = {} + + for row in rows: + for index, data in enumerate(row): + tmp_dict[columns[index]] = data + records.append(tmp_dict) + tmp_dict = {} + + return records def close_connection(self): self.connection.close() diff --git a/tests/test_manager.py b/tests/test_manager.py index 8156b40..c3dca6e 100644 --- a/tests/test_manager.py +++ b/tests/test_manager.py @@ -1,6 +1,4 @@ -from ast import Assert import os -from re import X from ReallySimpleDB import dbmanager _dbmanager = dbmanager() @@ -117,6 +115,13 @@ def test_get_all_records(): assert _dbmanager.get_all_records(table="STUDENTS") == [{'student_id': '1010', 'name': 'ABC', 'mark': 10, 'year': '2022'}, {'student_id': '1011', 'name': 'DEF', 'mark': 100, 'year': '2022'}] +def test_filter_record_1(): + assert _dbmanager.filter_records(table="STUDENTS", values={"year":"2022"}) == [{'student_id': '1010', 'name': 'ABC', 'mark': 10, 'year': '2022'}, + {'student_id': '1011', 'name': 'DEF', 'mark': 100, 'year': '2022'}] + +def test_filter_record_2(): + assert _dbmanager.filter_records(table="STUDENTS", values={"mark":100, "year":"2022"}) == [{'student_id': '1011', 'name': 'DEF', 'mark': 100, 'year': '2022'}] + def test_delete_record_1(): assert _dbmanager.delete_record(table="STUDENTS", primary_key="1010")