Skip to content

Commit 8f0a59d

Browse files
committed
Update README.md
1 parent db2fced commit 8f0a59d

File tree

7 files changed

+112
-36
lines changed

7 files changed

+112
-36
lines changed

README.md

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,10 @@ There are several generally accepted data types for storing information in the d
3838

3939
* `cursor` - This **property** returns the cursor for the database (directly the thing that works with database cells)
4040
* `connector` - This **property** returns the connector for the database (the thing through which the connection to the database is established)
41-
* `create_table` - This **method** creates a table in the database
41+
* `tables` - This **property** returns the list of table names
42+
* `add_table` - This **method** creates a table in the database
4243
* `get_table` - This **method** get the "Table" object for further interaction with it.
44+
* `delete_table` - This **method** delete table with `table_name` name
4345

4446
#### SQLite3_table.py
4547

@@ -55,4 +57,39 @@ There are several generally accepted data types for storing information in the d
5557
* `get_all_keys` - This **method** returns all values of all identifiers (a column whose values are unique for each row)
5658
* `commit` - This **method** confirms the entry in the table
5759

58-
### Examples
60+
### Examples
61+
62+
Для работы с `SQLite3Module` достаточно его просто импортировать в ваш проект, основным файлом является `SQLite3Module/SQLite3_base.py`.
63+
```Python3
64+
import os
65+
from SQLite3Module.SQLite3_base import *
66+
67+
68+
my_sqlite3_database = DataBase(path=os.getcwd(), filename="my_BD.sqlite3")
69+
```
70+
Теперь не надо знать язык `SQL` чтобы создать таблицу, достаточно просто вызвать соответствующий метод и передать в него соответствующие параметры.
71+
*В данном конкеретном случае, уникальным ключом `primary_key` будет колонка `user_id`.*
72+
```Python3
73+
my_sqlite3_database.add_table(tablename="my_first_table",
74+
columns={"user_id": DBType.INTEGER,
75+
"firstname": DBType.TEXT,
76+
"lastname": DBType.TEXT,
77+
"real value": DBType.REAL})
78+
```
79+
Yes, we can creating one more table :)
80+
Чтобы изменить `primary_key` нужно при инициализации таблицы, явно указать колонку, которую вы хотите сделать основной.
81+
Например, вот так:
82+
```Python3
83+
my_sqlite3_database.add_table(tablename="my_second_table",
84+
columns={"user_id": DBType.INTEGER,
85+
"firstname": DBType.TEXT,
86+
"lastname": DBType.TEXT,
87+
"real value": DBType.REAL},
88+
primary_key="real value")
89+
```
90+
Естественно, что можно создать, то можно и удалить.
91+
**Удаление таблицы не отменяемое действие!!!**
92+
```Python3
93+
my_sqlite3_database.delete_table(table_name="my_first_table")
94+
```
95+

SQLite3Module/SQLite3_base.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,22 @@ def connector(self) -> sqlite3.Connection:
3535
"""
3636
return self.__connector
3737

38-
def create_table(self, name: str, labels: Dict[str, DBType], primary_key: str = None) -> None:
38+
@property
39+
def tables(self) -> List[str]:
40+
return list(self.__tables.keys())
41+
42+
def add_table(self, tablename: str, columns: Dict[str, DBType], primary_key: str = None) -> None:
3943
"""
4044
This method creates a table in the database
41-
:param name: Table name
42-
:param labels: A dictionary where the key is the column name and the value is the data type
45+
:param tablename: Table name
46+
:param columns: A dictionary where the key is the column name and the value is the data type
4347
:param primary_key: Key column
4448
"""
45-
table = Table(name=name,
49+
table = Table(tablename=tablename,
4650
cursor=self.__cursor,
4751
connector=self.__connector)
48-
table.create_table(labels=labels, primary_key=primary_key)
49-
self.__tables[name] = table
52+
table.create_table(columns=columns, primary_key=primary_key)
53+
self.__tables[tablename] = table
5054

5155
def get_table(self, table_name: str) -> Table:
5256
"""
@@ -57,6 +61,10 @@ def get_table(self, table_name: str) -> Table:
5761
raise Exception(f"Table \'{table_name}\' not exist in DataBase!")
5862
return self.__tables[table_name]
5963

64+
def delate_table(self, table_name: str) -> None:
65+
self.__cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
66+
del self.__tables[table_name]
67+
6068
def __create_cursor(self, path_to_file: str) -> None:
6169
"""
6270
This method creates a cursor (entity, to interact with the database)
@@ -82,7 +90,7 @@ def __is_filename_valid(filename: str) -> str:
8290
This method checks if this string is the path to the folder/file
8391
:param filename: The intended path to the file
8492
"""
85-
if filename.endswith(".db"):
93+
if filename.endswith(".db") or filename.endswith(".sqlite3"):
8694
return filename
8795
else:
8896
raise Exception(f"The filename \'{filename}\' is not valid!")

SQLite3Module/SQLite3_table.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55

66
class Table:
7-
def __init__(self, name: str, cursor: sqlite3.Cursor, connector: sqlite3.Connection):
8-
self.__name = name
7+
def __init__(self, tablename: str, cursor: sqlite3.Cursor, connector: sqlite3.Connection):
8+
self.tablename = tablename
99
self.__cursor = cursor
1010
self.__connector = connector
1111
self.__primary_key = None
@@ -21,27 +21,27 @@ def column_names(self) -> List[str]:
2121
This property returns a list of column names
2222
"""
2323
if not self.__is_loaded:
24-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
24+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
2525
return list(self.__table_labels.keys())
2626

27-
def create_table(self, labels: Dict[str, DBType], primary_key: str = None) -> None:
27+
def create_table(self, columns: Dict[str, DBType], primary_key: str = None) -> None:
2828
"""
2929
This method creates a table with the specified columns. If "primary_key" is not specified, then the first
3030
column will be considered the identifier, otherwise - the one selected by the user.
31-
:param labels: A dictionary where the key is the column name and the value is the data type
31+
:param columns: A dictionary where the key is the column name and the value is the data type
3232
:param primary_key: The column that will be considered the key
3333
"""
3434
if self.__is_loaded:
3535
raise Exception("DataBase is already exist!")
3636
if primary_key is not None:
37-
if primary_key not in labels:
37+
if primary_key not in columns:
3838
raise Exception(f"Column \'{primary_key}\' not exist in table labels!")
3939
self.__primary_key = primary_key
4040
else:
41-
self.__primary_key = list(labels.keys())[0]
42-
self.__cursor.execute(f"CREATE TABLE IF NOT EXISTS {self.__name} ({Table.__prep_labels(labels)})")
41+
self.__primary_key = list(columns.keys())[0]
42+
self.__cursor.execute(f"CREATE TABLE IF NOT EXISTS {self.tablename} ({Table.__prep_labels(columns)})")
4343
self.__connector.commit()
44-
self.__table_labels = labels
44+
self.__table_labels = columns
4545
self.__is_loaded = True
4646

4747
def get_from_cell(self, key: str, column_name: str) -> Any:
@@ -52,10 +52,10 @@ def get_from_cell(self, key: str, column_name: str) -> Any:
5252
:param column_name: The name of the column from which the value should be returned
5353
"""
5454
if not self.__is_loaded:
55-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
55+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
5656
if column_name not in self.__table_labels:
5757
raise Exception(f"Column \'{column_name}\' not exist in table labels!")
58-
self.__cursor.execute(f"SELECT {column_name} FROM {self.__name} WHERE {self.__primary_key} = '{key}'")
58+
self.__cursor.execute(f"SELECT {column_name} FROM {self.tablename} WHERE {self.__primary_key} = '{key}'")
5959
return self.__cursor.fetchone()[0]
6060

6161
def set_to_cell(self, key: str, column_name: str, new_value: Any, commit: bool = True) -> None:
@@ -67,10 +67,10 @@ def set_to_cell(self, key: str, column_name: str, new_value: Any, commit: bool =
6767
:param commit: Is it worth committing (often a commit is needed 1 time in 10-100 operations)
6868
"""
6969
if not self.__is_loaded:
70-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
70+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
7171
if column_name not in self.__table_labels:
7272
raise Exception(f"Column \'{column_name}\' not exist in table labels!")
73-
self.__cursor.execute(f"UPDATE {self.__name} SET {column_name} = '{new_value}' WHERE {self.__primary_key} = '{key}'")
73+
self.__cursor.execute(f"UPDATE {self.tablename} SET {column_name} = '{new_value}' WHERE {self.__primary_key} = '{key}'")
7474
if commit:
7575
self.__connector.commit()
7676

@@ -81,12 +81,12 @@ def add_row(self, row: list, commit: bool = True) -> None:
8181
:param commit: Is it worth committing (often a commit is needed 1 time in 10-100 operations)
8282
"""
8383
if not self.__is_loaded:
84-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
84+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
8585
if len(row) != len(self.__table_labels):
8686
raise Exception(f"There are only {len(self.__table_labels)} columns in the database "
87-
f"\'{self.__name}\', and you are trying to write {len(row)}")
87+
f"\'{self.tablename}\', and you are trying to write {len(row)}")
8888
values = ", ".join(["'" + str(i) + "'" for i in row])
89-
self.__cursor.execute(f"INSERT INTO {self.__name} VALUES ({values})")
89+
self.__cursor.execute(f"INSERT INTO {self.tablename} VALUES ({values})")
9090
if commit:
9191
self.__connector.commit()
9292

@@ -96,8 +96,8 @@ def get_row(self, key: str) -> Dict[str, Any]:
9696
:param key: Unique identifier
9797
"""
9898
if not self.__is_loaded:
99-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
100-
self.__cursor.execute(f"SELECT * FROM {self.__name} WHERE {self.__primary_key} = '{key}'")
99+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
100+
self.__cursor.execute(f"SELECT * FROM {self.tablename} WHERE {self.__primary_key} = '{key}'")
101101
request = self.__cursor.fetchall()
102102
if len(request) == 0:
103103
raise Exception("There are no values for this query!")
@@ -112,8 +112,8 @@ def delete_row(self, key: str) -> None:
112112
:param key: Unique identifier
113113
"""
114114
if not self.__is_loaded:
115-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
116-
self.__cursor.execute(f"DELETE FROM {self.__name} WHERE {self.__primary_key} = '{key}'")
115+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
116+
self.__cursor.execute(f"DELETE FROM {self.tablename} WHERE {self.__primary_key} = '{key}'")
117117
self.__connector.commit()
118118

119119
def get_column(self, column_name: str) -> List[Any]:
@@ -122,19 +122,19 @@ def get_column(self, column_name: str) -> List[Any]:
122122
:param column_name: Column name
123123
"""
124124
if not self.__is_loaded:
125-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
125+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
126126
if column_name not in self.__table_labels:
127127
raise Exception(f"Column \'{column_name}\' not exist in table labels!")
128-
self.__cursor.execute(f"SELECT {column_name} FROM {self.__name}")
128+
self.__cursor.execute(f"SELECT {column_name} FROM {self.tablename}")
129129
return [sfa[0] for sfa in self.__cursor.fetchall()]
130130

131131
def get_all_keys(self) -> List[Any]:
132132
"""
133133
This method returns all values of all identifiers (a column whose values are unique for each row)
134134
"""
135135
if not self.__is_loaded:
136-
raise Exception(f"DataBase \'{self.__name}\' is not exist!. Try using \'Table.create_table\'.")
137-
self.__cursor.execute(f"SELECT {self.__primary_key} FROM {self.__name}")
136+
raise Exception(f"DataBase \'{self.tablename}\' is not exist!. Try using \'Table.create_table\'.")
137+
self.__cursor.execute(f"SELECT {self.__primary_key} FROM {self.tablename}")
138138
return [sfa[0] for sfa in self.__cursor.fetchall()]
139139

140140
def commit(self) -> None:

SQLite3Module/__init__.py

Lines changed: 0 additions & 3 deletions
This file was deleted.

example.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import os
2+
from SQLite3Module.SQLite3_base import *
3+
4+
my_sqlite3_database = DataBase(path=os.getcwd(), filename="my_BD.sqlite3") # Creating (or connection) DataBase
5+
my_sqlite3_database.add_table(tablename="my_first_table", # Setting name of table
6+
columns={"user_id": DBType.INTEGER,
7+
"firstname": DBType.TEXT,
8+
"lastname": DBType.TEXT,
9+
"real value": DBType.REAL})
10+
11+
my_sqlite3_database.add_table(tablename="my_second_table", # Yes, we can creating one more table
12+
columns={"user_id": DBType.INTEGER,
13+
"firstname": DBType.TEXT,
14+
"lastname": DBType.TEXT,
15+
"real value": DBType.REAL},
16+
primary_key="real value")
17+
18+
# my_sqlite3_database.delete_table(table_name="my_first_table") # If we want to delete table
19+
20+
print(my_sqlite3_database.get_table("my_second_table")) # I
21+
22+

my_BD.sqlite3

12 KB
Binary file not shown.

setup.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from setuptools import setup
2+
3+
setup(
4+
name='example.py',
5+
version='1.0.0',
6+
packages=[''],
7+
url='https://github.com/Stepan-coder/PythonSQLite3',
8+
license='MIT',
9+
author='StepanBorodin',
10+
author_email='stepan.borodin2016@bk.ru',
11+
description='The simplest SQLile3 ORM for non - production develop :)'
12+
)

0 commit comments

Comments
 (0)