postgresdb3 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: postgresdb3
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Python uchun oddiy PostgreSQL wrapper
5
5
  Home-page: https://github.com/AlijonovUz/PostgresDB
6
6
  Author: Abdulbosit Alijonov
@@ -10,6 +10,7 @@ Classifier: Operating System :: OS Independent
10
10
  Requires-Python: >=3.7
11
11
  Description-Content-Type: text/markdown
12
12
  Requires-Dist: psycopg2>=2.9
13
+ Requires-Dist: asyncpg>=0.31.0
13
14
  Dynamic: author
14
15
  Dynamic: classifier
15
16
  Dynamic: description
@@ -0,0 +1,2 @@
1
+ from .sync_db import PostgresDB
2
+ from .async_db import AsyncPostgresDB
@@ -0,0 +1,228 @@
1
+ import asyncpg
2
+ from typing import Any, List, Optional
3
+
4
+
5
+ class AsyncPostgresDB:
6
+ """
7
+ Async PostgreSQL helper class for CRUD operations and schema management.
8
+
9
+ Ushbu class `asyncpg` kutubxonasidan foydalanib,
10
+ PostgreSQL bilan asynchronous CRUD va schema operatsiyalarini bajaradi.
11
+ Aiogram kabi async frameworklar bilan to‘g‘ridan-to‘g‘ri ishlash uchun mos.
12
+ """
13
+
14
+ def __init__(self, database: str, user: str, password: str, host: str = "localhost", port: int = 5432):
15
+ """
16
+ PostgreSQL bazasiga ulanishni tayyorlaydi.
17
+
18
+ Args:
19
+ database (str): Bazaning nomi.
20
+ user (str): Foydalanuvchi nomi.
21
+ password (str): Parol.
22
+ host (str): Server manzili (default: "localhost").
23
+ port (int): Port (default: 5432).
24
+ """
25
+ self.database = database
26
+ self.user = user
27
+ self.password = password
28
+ self.host = host
29
+ self.port = port
30
+ self.pool: Optional[asyncpg.pool.Pool] = None
31
+
32
+ async def manager(self, sql: str, *params, fetchone=False, fetchall=False, commit=False):
33
+ """
34
+ Markaziy metod: barcha SQL so‘rovlarni bajaradi.
35
+
36
+ Args:
37
+ sql (str): Bajariladigan SQL so‘rov.
38
+ *params: SQL parametrlarini berish.
39
+ fetchone (bool): True bo‘lsa, faqat bitta qator qaytaradi.
40
+ fetchall (bool): True bo‘lsa, barcha natijalarni qaytaradi.
41
+ commit (bool): True bo‘lsa, tranzaksiya commit qilinadi.
42
+
43
+ Returns:
44
+ fetchone=True bo‘lsa: asyncpg.Record
45
+ fetchall=True bo‘lsa: list[asyncpg.Record]
46
+ commit=True bo‘lsa: None
47
+ """
48
+ if not self.pool:
49
+ self.pool = await asyncpg.create_pool(
50
+ database=self.database,
51
+ user=self.user,
52
+ password=self.password,
53
+ host=self.host,
54
+ port=self.port
55
+ )
56
+
57
+ async with self.pool.acquire() as conn:
58
+ if commit:
59
+ await conn.execute(sql, *params)
60
+ return
61
+ if fetchone:
62
+ return await conn.fetchrow(sql, *params)
63
+ if fetchall:
64
+ return await conn.fetch(sql, *params)
65
+
66
+ async def close_pool(self):
67
+ """
68
+ Connection poolni yopadi.
69
+ """
70
+ if self.pool:
71
+ await self.pool.close()
72
+ self.pool = None
73
+
74
+ async def create(self, table: str, columns: str):
75
+ """
76
+ Jadval yaratadi (agar mavjud bo‘lsa o‘tkazib yuboradi).
77
+
78
+ Args:
79
+ table (str): Jadval nomi.
80
+ columns (str): Ustunlar va turlari, misol: "id SERIAL PRIMARY KEY, name TEXT".
81
+ """
82
+ await self.manager(f"CREATE TABLE IF NOT EXISTS {table} ({columns})", commit=True)
83
+
84
+ async def drop(self, table: str):
85
+ """
86
+ Jadvalni o‘chiradi (agar mavjud bo‘lsa).
87
+
88
+ Args:
89
+ table (str): Jadval nomi.
90
+ """
91
+ await self.manager(f"DROP TABLE IF EXISTS {table} CASCADE", commit=True)
92
+
93
+ async def select(
94
+ self, table: str, columns: str = "*",
95
+ where: Optional[List[Any]] = None,
96
+ join: Optional[List[tuple]] = None,
97
+ group_by: Optional[str] = None,
98
+ order_by: Optional[str] = None,
99
+ limit: Optional[int] = None,
100
+ fetchone: bool = False
101
+ ):
102
+ """
103
+ Jadvaldan ma'lumotlarni tanlash.
104
+
105
+ Args:
106
+ table (str): Asosiy jadval nomi.
107
+ columns (str): Tanlanadigan ustunlar (default: "*").
108
+ where (Optional[List[Any]]): ("shart", [qiymatlar])
109
+ join (Optional[List[tuple]]): [("INNER JOIN", "orders", "users.id = orders.user_id")]
110
+ group_by (Optional[str]): GROUP BY ustuni.
111
+ order_by (Optional[str]): ORDER BY qoidasi.
112
+ limit (Optional[int]): LIMIT qiymati.
113
+ fetchone (bool): True bo‘lsa faqat bitta qator qaytaradi.
114
+
115
+ Returns:
116
+ asyncpg.Record yoki list[asyncpg.Record]
117
+ """
118
+ sql = f"SELECT {columns} FROM {table}"
119
+ params: List[Any] = []
120
+
121
+ if join:
122
+ for join_type, join_table, on_condition in join:
123
+ sql += f" {join_type} {join_table} ON {on_condition}"
124
+
125
+ if where:
126
+ condition, values = where
127
+ sql += f" WHERE {condition}"
128
+ params.extend(values)
129
+
130
+ if group_by:
131
+ sql += f" GROUP BY {group_by}"
132
+
133
+ if order_by:
134
+ sql += f" ORDER BY {order_by}"
135
+
136
+ if limit is not None:
137
+ sql += f" LIMIT $%d" % (len(params) + 1)
138
+ params.append(limit)
139
+
140
+ return await self.manager(sql, *params, fetchone=fetchone, fetchall=not fetchone)
141
+
142
+ async def insert(self, table: str, columns: str, values: List[Any]):
143
+ """
144
+ Jadvalga yangi qator qo‘shadi.
145
+
146
+ Args:
147
+ table (str): Jadval nomi.
148
+ columns (str): Ustunlar nomi, misol: "name, age".
149
+ values (List[Any]): Qiymatlar, misol: ["Ali", 25].
150
+ """
151
+ placeholders = ", ".join(f"${i+1}" for i in range(len(values)))
152
+ sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
153
+ await self.manager(sql, *values, commit=True)
154
+
155
+ async def update(self, table: str, set_column: str, set_value: Any, where_column: str, where_value: Any):
156
+ """
157
+ Jadvaldagi qatorni yangilaydi.
158
+
159
+ Args:
160
+ table (str): Jadval nomi.
161
+ set_column (str): O‘zgartiriladigan ustun.
162
+ set_value (Any): Yangi qiymat.
163
+ where_column (str): Filtrlash ustuni.
164
+ where_value (Any): Filtrlash qiymati.
165
+ """
166
+ sql = f"UPDATE {table} SET {set_column} = $1 WHERE {where_column} = $2"
167
+ await self.manager(sql, set_value, where_value, commit=True)
168
+
169
+ async def delete(self, table: str, where_column: str, where_value: Any):
170
+ """
171
+ Jadvaldan qator o‘chiradi.
172
+
173
+ Args:
174
+ table (str): Jadval nomi.
175
+ where_column (str): Filtrlash ustuni.
176
+ where_value (Any): Filtrlash qiymati.
177
+ """
178
+ sql = f"DELETE FROM {table} WHERE {where_column} = $1"
179
+ await self.manager(sql, where_value, commit=True)
180
+
181
+ async def list_tables(self, schema: str = "public") -> List[str]:
182
+ """
183
+ Bazadagi barcha jadvallarni ro‘yxat sifatida qaytaradi.
184
+
185
+ Args:
186
+ schema (str): Schema nomi, default "public".
187
+
188
+ Returns:
189
+ List[str]: Jadval nomlari
190
+ """
191
+ sql = """
192
+ SELECT table_name
193
+ FROM information_schema.tables
194
+ WHERE table_schema = $1
195
+ ORDER BY table_name
196
+ """
197
+ result = await self.manager(sql, schema, fetchall=True)
198
+ return [r["table_name"] for r in result]
199
+
200
+ async def describe_table(self, table: str, schema: str = "public"):
201
+ """
202
+ Jadval ustunlari haqida ma'lumot beradi.
203
+
204
+ Args:
205
+ table (str): Jadval nomi.
206
+ schema (str): Schema nomi, default "public".
207
+
208
+ Returns:
209
+ list[asyncpg.Record]: Har bir ustun bo‘yicha ma’lumot
210
+ """
211
+ sql = """
212
+ SELECT column_name, data_type, is_nullable, column_default
213
+ FROM information_schema.columns
214
+ WHERE table_schema = $1 AND table_name = $2
215
+ ORDER BY ordinal_position
216
+ """
217
+ return await self.manager(sql, schema, table, fetchall=True)
218
+
219
+ async def alter(self, table: str, action: str):
220
+ """
221
+ Jadval strukturasi o‘zgartirish (ALTER TABLE).
222
+
223
+ Args:
224
+ table (str): Jadval nomi.
225
+ action (str): ALTER TABLE dan keyingi SQL qismi, misol: "ADD COLUMN age INT".
226
+ """
227
+ sql = f"ALTER TABLE {table} {action}"
228
+ await self.manager(sql, commit=True)
@@ -147,3 +147,43 @@ class PostgresDB:
147
147
  """
148
148
  sql = f"DELETE FROM {table} WHERE {where_column} = %s"
149
149
  return self.manager(sql, (where_value,), commit=True)
150
+
151
+ def list_tables(self, schema="public"):
152
+ """
153
+ Bazadagi mavjud jadvallar ro'yxatini qaytaradi.
154
+
155
+ schema: str — schema nomi (standart: public)
156
+ """
157
+ sql = """
158
+ SELECT table_name
159
+ FROM information_schema.tables
160
+ WHERE table_schema = %s
161
+ ORDER BY table_name; \
162
+ """
163
+ return self.manager(sql, (schema,), fetchall=True)
164
+
165
+ def describe_table(self, table, schema="public"):
166
+ """
167
+ Jadval ustunlari haqida ma'lumot beradi.
168
+ """
169
+ sql = """
170
+ SELECT column_name,
171
+ data_type,
172
+ is_nullable,
173
+ column_default
174
+ FROM information_schema.columns
175
+ WHERE table_schema = %s
176
+ AND table_name = %s
177
+ ORDER BY ordinal_position; \
178
+ """
179
+ return self.manager(sql, (schema, table), fetchall=True)
180
+
181
+ def alter(self, table, action):
182
+ """
183
+ Universal ALTER TABLE metodi.
184
+
185
+ table: str — jadval nomi
186
+ action: str — ALTER TABLE dan keyingi qism
187
+ """
188
+ sql = f"ALTER TABLE {table} {action}"
189
+ return self.manager(sql, commit=True)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: postgresdb3
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Python uchun oddiy PostgreSQL wrapper
5
5
  Home-page: https://github.com/AlijonovUz/PostgresDB
6
6
  Author: Abdulbosit Alijonov
@@ -10,6 +10,7 @@ Classifier: Operating System :: OS Independent
10
10
  Requires-Python: >=3.7
11
11
  Description-Content-Type: text/markdown
12
12
  Requires-Dist: psycopg2>=2.9
13
+ Requires-Dist: asyncpg>=0.31.0
13
14
  Dynamic: author
14
15
  Dynamic: classifier
15
16
  Dynamic: description
@@ -2,7 +2,8 @@ README.md
2
2
  pyproject.toml
3
3
  setup.py
4
4
  postgresdb3/__init__.py
5
- postgresdb3/core.py
5
+ postgresdb3/async_db.py
6
+ postgresdb3/sync_db.py
6
7
  postgresdb3.egg-info/PKG-INFO
7
8
  postgresdb3.egg-info/SOURCES.txt
8
9
  postgresdb3.egg-info/dependency_links.txt
@@ -0,0 +1,2 @@
1
+ psycopg2>=2.9
2
+ asyncpg>=0.31.0
@@ -5,10 +5,11 @@ with open("README.md", "r", encoding="utf-8") as f:
5
5
 
6
6
  setup(
7
7
  name="postgresdb3",
8
- version="0.1.0",
8
+ version="0.2.0",
9
9
  packages=find_packages(),
10
10
  install_requires=[
11
- "psycopg2>=2.9"
11
+ "psycopg2>=2.9",
12
+ "asyncpg>=0.31.0"
12
13
  ],
13
14
  author="Abdulbosit Alijonov",
14
15
  description="Python uchun oddiy PostgreSQL wrapper",
@@ -1 +0,0 @@
1
- from .core import PostgresDB
@@ -1 +0,0 @@
1
- psycopg2>=2.9
File without changes
File without changes
File without changes