sqlthon 0.0.15__tar.gz → 0.1.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: sqlthon
3
- Version: 0.0.15
3
+ Version: 0.1.0
4
4
  Summary: A simple package for SQLite3 operations
5
5
  Author-email: SAUMS <mohamnown@gmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sqlthon"
7
- version = '0.0.15'
7
+ version = '0.1.0'
8
8
  description = "A simple package for SQLite3 operations"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -15,7 +15,7 @@ Channel: https://ble.ir/saums_channel
15
15
  from .core import Connect, Field
16
16
 
17
17
  __all__ = ['Connect', 'Field']
18
- __version__ = '0.0.15'
18
+ __version__ = '0.1.0'
19
19
  __author__ = "SAUMS"
20
20
  __email__ = "saums1391@gmail.com"
21
21
  __description__ = "Operate With SQLite3 Buy Simple"
@@ -1,6 +1,7 @@
1
1
  class Field:
2
2
  __slots__ = ("name",)
3
3
  def __init__(self, name):
4
+ _analysis_code(name)
4
5
  self.name = name
5
6
 
6
7
  def __gt__(self, value): return _Expression(self, ">", value)
@@ -47,6 +48,8 @@ class _Expression:
47
48
  class _Aggregate:
48
49
  __slots__ = ("func", "column")
49
50
  def __init__(self, func, column="*"):
51
+ if not column == "*":
52
+ _analysis_code(column)
50
53
  self.func = func
51
54
  self.column = column
52
55
 
@@ -88,7 +91,17 @@ def _compile(expr):
88
91
  sql = f'"{expr.left.name}" {expr.op} ?'
89
92
  params = (expr.right,)
90
93
  return sql, params
91
-
94
+
95
+
96
+ def _analysis_code(query):
97
+ from re import match
98
+ if isinstance(query, (list, tuple)):
99
+ for i in query:
100
+ _analysis_code(i)
101
+ return
102
+ if not match("^[A-Za-z_][A-Za-z0-9_.(), ]*$", query) or "sqlite_" in query.lower():
103
+ raise YouHackerError(f"you hacker for {query!r}.") from None
104
+
92
105
 
93
106
  class Connect:
94
107
  __slots__ = ("_con", "_cur", "_changes", "_path")
@@ -102,11 +115,13 @@ class Connect:
102
115
 
103
116
  # ____________| TABLE |____________
104
117
  def add_table(self, table_name: str, *columns: tuple, if_not_exists=False) -> None:
118
+ _analysis_code(table_name)
105
119
  query = "CREATE TABLE "
106
120
  if if_not_exists:
107
121
  query += "IF NOT EXISTS "
108
122
  query += f"{table_name} ("
109
123
  for column in columns:
124
+ _analysis_code(column)
110
125
  name, type = column[0], column[1]
111
126
  try:
112
127
  limits = column[2]
@@ -119,48 +134,72 @@ class Connect:
119
134
  self._changes.append((query,))
120
135
 
121
136
  def rename_table(self, old_name_table: str, new_name_table: str) -> None:
137
+ _analysis_code(old_name_table)
138
+ _analysis_code(new_name_table)
122
139
  self._changes.append((f"ALTER TABLE {old_name_table} RENAME TO {new_name_table}",))
123
140
 
124
141
  def drop_table(self, table_name: str) -> None:
142
+ _analysis_code(table_name)
125
143
  self._changes.append((f"DROP TABLE {table_name}",))
126
144
 
127
145
  def exist_table(self, table_name: str) -> bool:
128
- return table_name in [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='table'")]
146
+ _analysis_code(table_name)
147
+ return table_name in [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
129
148
 
130
149
  def copy_table(self, table_name: str, new_name_table: str) -> None:
150
+ _analysis_code(table_name)
151
+ _analysis_code(new_name_table)
131
152
  self._changes.append((f"CREATE TABLE {new_name_table} AS SELECT * FROM {table_name}"),)
132
153
 
133
154
  def get_tables(self) -> list:
134
- return [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='table'")]
155
+ return [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
135
156
 
136
157
  # ____________| COLUMN |____________
137
158
  def add_column(self, table_name: str, column_name: str, column_type: str, limits: list | str=[]) -> None:
159
+ _analysis_code(table_name)
160
+ _analysis_code(column_name)
161
+ _analysis_code(column_type)
138
162
  if limits:
163
+ _analysis_code(limits)
139
164
  limits = " ".join(limits)
140
165
  else:
141
166
  limits = ""
142
167
  self._changes.append((f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} {limits}",))
143
168
 
144
169
  def drop_column(self, table_name: str, column_name: str) -> None:
170
+ _analysis_code(table_name)
171
+ _analysis_code(column_name)
145
172
  self._changes.append((f"ALTER TABLE {table_name} DROP COLUMN {column_name}",))
146
173
 
147
174
  def rename_column(self, table_name: str, old_name_column: str, new_name_column: str) -> None:
175
+ _analysis_code(table_name)
176
+ _analysis_code(old_name_column)
177
+ _analysis_code(new_name_column)
148
178
  self._changes.append((f"ALTER TABLE {table_name} RENAME COLUMN {old_name_column} TO {new_name_column}",))
149
179
 
150
180
  def exist_column(self, table_name: str, column_name: str) -> bool:
151
- return column_name in [i[1] for i in self.run_query(f"PRAGMA table_info({table_name})")]
181
+ _analysis_code(table_name)
182
+ _analysis_code(column_name)
183
+ return column_name in [i[1] for i in self._cur.execute(f"PRAGMA table_info({table_name})").fetchall()]
152
184
 
153
185
  def get_columns(self, table_name: str) -> list:
154
- return [i[1] for i in self.run_query(f"PRAGMA table_info({table_name})")]
186
+ _analysis_code(table_name)
187
+ return [i[1] for i in self._cur.execute(f"PRAGMA table_info({table_name})").fetchall()]
155
188
 
156
189
  # ____________| RECORD |____________
157
190
  def find_record(self, table_name: str, columns: None | tuple=None, compound: None | tuple=None, condition: None | _Expression=None, bundle: None | tuple=None, filter_bundle: None | tuple=None, sort: None | tuple=None, several: None | int=None, jump: int=0, unique: bool=False):
191
+ _analysis_code(table_name)
158
192
  query = "SELECT "
159
193
  param = ()
160
194
  if unique:
161
195
  query += "DISTINCT "
196
+ if columns:
197
+ _analysis_code(columns)
162
198
  query += f"{', '.join(columns) if columns else '*'} FROM {table_name}"
163
199
  if compound:
200
+ if compound[0].upper() not in ("INNER", "LEFT"):
201
+ raise YouHackerError(f"you hacker for {query!r}.") from None
202
+ _analysis_code(compound)
164
203
  query += f" {compound[0]} JOIN \"{compound[1]}\" ON {compound[2]} = {compound[3]}"
165
204
  if condition:
166
205
  _: tuple = _compile(condition)
@@ -168,6 +207,7 @@ class Connect:
168
207
  param += _[1]
169
208
  del _
170
209
  if bundle:
210
+ _analysis_code(bundle)
171
211
  query += f" GROUP BY {", ".join(bundle)}"
172
212
  if filter_bundle:
173
213
  __: tuple = _compile(filter_bundle)
@@ -176,39 +216,53 @@ class Connect:
176
216
  del __
177
217
 
178
218
  if sort:
219
+ _analysis_code(sort)
179
220
  query += " ORDER BY "
180
221
  if sort[-1].upper() == "ASC" or sort[-1].upper() == "DESC":
181
222
  query += f"{", ".join(sort[:-1])} {sort[-1]}"
182
223
  else:
183
224
  query += ", ".join(sort)
184
225
  if several is not None:
226
+ if not isinstance(several, int):
227
+ raise YouHackerError(f"you hacker for {several!r}.")
185
228
  query += f" LIMIT {several}"
186
229
  if jump:
230
+ if not isinstance(jump, int):
231
+ raise YouHackerError(f"you hacker for {jump!r}.")
187
232
  query += f" OFFSET {jump}"
188
- return self.run_query(query, param)
233
+ return self._cur.execute(query, param).fetchall()
189
234
 
190
235
  def add_record(self, table_name: str, record_info: tuple) -> None:
236
+ _analysis_code(table_name)
191
237
  self._changes.append((f"INSERT INTO {table_name} VALUES({', '.join(['?']*len(record_info))})", record_info))
192
238
 
193
239
  def add_records(self, table_name: str, info_records: tuple) -> None:
194
- self._cur.executemany(f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_records[0]))})", info_records)
195
- self._con.commit()
240
+ _analysis_code(table_name)
241
+ try:
242
+ self._cur.executemany(f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_records[0]))})", info_records)
243
+ self._con.commit()
244
+ except Exception as e:
245
+ _handler_error(e)
196
246
 
197
247
  def delete_record(self, table_name, condition):
248
+ _analysis_code(table_name)
198
249
  query = f"DELETE FROM {table_name}"
199
250
  sql_where, params = _compile(condition)
200
251
  query += " WHERE " + sql_where
201
252
  self._changes.append((query, params))
202
253
 
203
254
  def delete_all_record(self, table_name: str) -> None:
255
+ _analysis_code(table_name)
204
256
  self._changes.append((f"DELETE FROM {table_name}",))
205
257
 
206
258
  def edit_record(self, table_name, new_info_record, condition=None):
259
+ _analysis_code(table_name)
207
260
  query = f"UPDATE {table_name} SET "
208
261
  params = ()
209
262
 
210
263
  set_parts = []
211
264
  for key, value in new_info_record.items():
265
+ _analysis_code(key)
212
266
  set_parts.append(f'"{key}" = ?')
213
267
  params += (value,)
214
268
  query += ", ".join(set_parts)
@@ -221,9 +275,12 @@ class Connect:
221
275
  self._changes.append((query, params))
222
276
 
223
277
  def count_record(self, table_name: str) -> int:
224
- return self.run_query(f"SELECT COUNT(*) FROM {table_name}")[0][0]
278
+ _analysis_code(table_name)
279
+ return self._cur.execute(f"SELECT COUNT(*) FROM {table_name}").fetchall()[0][0]
225
280
 
226
281
  def upsert_record(self, table_name: str, info_record: tuple, conflict: tuple) -> None:
282
+ _analysis_code(table_name)
283
+ _analysis_code(conflict)
227
284
  query = f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_record))}) ON CONFLICT(\"{'", "'.join(conflict)}\") DO UPDATE SET "
228
285
  param = info_record
229
286
  colue = dict(zip(self.get_columns(table_name), info_record)) # columns value
@@ -237,39 +294,55 @@ class Connect:
237
294
 
238
295
  # ____________| INDEX |_________
239
296
  def add_index(self, table_name: str, column_name: str, unique: bool=False) -> None:
297
+ _analysis_code(table_name)
298
+ _analysis_code(column_name)
240
299
  self._changes.append((f"CREATE INDEX{" UNIQUE" if unique else ""} {table_name}_{column_name} ON {table_name} ({column_name})",))
241
300
 
242
301
  def delete_index(self, table_name: str, column_name: str) -> None:
302
+ _analysis_code(table_name)
303
+ _analysis_code(column_name)
243
304
  self._changes.append((f"DROP INDEX {table_name}_{column_name}",))
244
305
 
245
306
  # ____________| VIEW |_________
246
307
  def add_view(self, view_name: str, query: str) -> None:
247
- self._changes.append((f"CREATE VIEW {view_name} AS {query}",))
308
+ raise YouHackerError("add_view is disabled for security reasons.")
248
309
 
249
310
  def delete_view(self, view_name: str) -> None:
311
+ _analysis_code(view_name)
250
312
  self._changes.append((f"DROP VIEW {view_name}",))
251
313
 
252
314
  def exist_view(self, view_name: str) -> bool:
253
- return view_name in [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='view'")]
315
+ _analysis_code(view_name)
316
+ return view_name in [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='view'").fetchall()]
254
317
 
255
318
  # ____________| BACKUP |_________
256
319
  def backup_database(self, backup_path: str | None=None) -> None:
257
320
  from shutil import copy2
321
+ from os.path import abspath, dirname, join
258
322
  self._con.commit()
323
+ allowed_dir = dirname(abspath(self._path))
259
324
  if backup_path:
325
+ if not abspath(backup_path).startswith(allowed_dir):
326
+ raise YouHackerError(f"you hacker for {backup_path!r}.")
260
327
  copy2(self._path, backup_path)
261
328
  else:
262
- copy2(self._path, "".join(self._path.split(".")[:-1]))
329
+ copy2(self._path, join(allowed_dir, "backup.db"))
263
330
 
264
331
  # ____________| PANDAS |_________
265
332
  def to_dataframe(self, table_name: str) -> "pd.DataFrame":
333
+ _analysis_code(table_name)
266
334
  import pandas as pd
267
335
  columns = self.get_columns(table_name)
268
- result = self.run_query(f"SELECT * FROM {table_name}")
336
+ result = self._cur.execute(f"SELECT * FROM {table_name}").fetchall()
269
337
  return pd.DataFrame(result, columns=columns)
270
338
 
271
339
  # ____________| CSV |_________
272
340
  def load_csv(self, table_name: str, csv_path: str) -> None:
341
+ _analysis_code(table_name)
342
+ from os.path import abspath, dirname
343
+ allowed_dir = dirname(abspath(self._path))
344
+ if not abspath(csv_path).startswith(allowed_dir):
345
+ raise YouHackerError(f"you hacker for {csv_path!r}.")
273
346
  import csv as _csv
274
347
 
275
348
  with open(csv_path) as file:
@@ -289,6 +362,11 @@ class Connect:
289
362
  self.add_records(table_name, tuple(records))
290
363
 
291
364
  def to_csv(self, table_name: str, csv_path: str) -> None:
365
+ _analysis_code(table_name)
366
+ from os.path import abspath, dirname
367
+ allowed_dir = dirname(abspath(self._path))
368
+ if not abspath(csv_path).startswith(allowed_dir):
369
+ raise YouHackerError(f"you hacker for {csv_path!r}.")
292
370
  import csv as _csv
293
371
  with open(csv_path, "w", newline="", encoding="utf-8") as f:
294
372
  writer = _csv.writer(f)
@@ -298,7 +376,7 @@ class Connect:
298
376
 
299
377
  # ____________| OTHER |_________
300
378
  def last_id(self) -> int:
301
- return self.run_query("SELECT last_insert_rowid()")[0][0]
379
+ return self._cur.execute("SELECT last_insert_rowid()").fetchall()[0][0]
302
380
 
303
381
  def database_info(self) -> dict:
304
382
  from os.path import basename, exists, getsize
@@ -307,13 +385,11 @@ class Connect:
307
385
  "size": getsize(self._path) if exists(self._path) else 0,
308
386
  "count_tables": len(self.get_tables())
309
387
  }
388
+
310
389
 
311
390
  # ____________| BASIC |_________
312
391
  def run_query(self, code: str, parameters: tuple=()) -> list:
313
- self._cur.execute(code, parameters)
314
- if not code.upper().startswith("SELECT"):
315
- self._con.commit()
316
- return self._cur.fetchall()
392
+ raise YouHackerError("run_query is disabled for security reasons.")
317
393
 
318
394
  def optimize(self) -> None:
319
395
  self.save_to_database()
@@ -325,6 +401,9 @@ class Connect:
325
401
  with self._con:
326
402
  for sql_code in self._changes:
327
403
  self._cur.execute(*sql_code)
404
+ except Exception as e:
405
+ _handler_error(e)
406
+
328
407
  finally:
329
408
  self._changes.clear()
330
409
 
@@ -337,4 +416,127 @@ class Connect:
337
416
 
338
417
  def __exit__(self, exc_type, exc_value, exc_tb) -> None:
339
418
  self.save_to_database()
340
- self.close()
419
+ self.close()
420
+
421
+
422
+ # ____________| ERRORS |_________
423
+ class SqlthonError(Exception):pass
424
+ class YouHackerError(SqlthonError, PermissionError):pass
425
+ class TableError(SqlthonError):pass
426
+ class TableNotFoundError(TableError):pass
427
+ class TableAlreadyExistsError(TableError):pass
428
+ class ColumnError(SqlthonError):pass
429
+ class ColumnNotFoundError(ColumnError):pass
430
+ class RecordError(SqlthonError):pass
431
+ class UniqueConstraintError(RecordError):pass
432
+ class NotNullConstraintError(RecordError):pass
433
+ class DataTypeError(RecordError):pass
434
+ class ForeignKeyError(RecordError):pass
435
+ class CheckConstraintError(RecordError):pass
436
+ class PrimaryKeyError(RecordError):pass
437
+ class QueryError(SqlthonError):pass
438
+ class SyntaxError(QueryError):pass
439
+ class NoSuchFunctionError(QueryError):pass
440
+ class WrongNumberOfArgumentsError(QueryError):pass
441
+ class DatabaseError(SqlthonError):pass
442
+ class DatabaseLockedError(DatabaseError):pass
443
+ class DatabaseReadOnlyError(DatabaseError):pass
444
+ class DatabaseCorruptError(DatabaseError):pass
445
+ class DatabaseFullError(DatabaseError):pass
446
+ class DatabaseBusyError(DatabaseError):pass
447
+ class IndexError(SqlthonError):pass
448
+ class IndexNotFoundError(IndexError):pass
449
+ class IndexAlreadyExistsError(IndexError):pass
450
+ class ViewError(SqlthonError):pass
451
+ class ViewNotFoundError(ViewError):pass
452
+ class ViewAlreadyExistsError(ViewError):pass
453
+ class TransactionError(SqlthonError):pass
454
+ class TransactionAlreadyActiveError(TransactionError):pass
455
+ class TransactionNotActiveError(TransactionError):pass
456
+ class BackupError(SqlthonError):pass
457
+ class BackupPathError(BackupError):pass
458
+ class BackupPermissionError(BackupError):pass
459
+ class CsvError(SqlthonError):pass
460
+ class CsvFileNotFoundError(CsvError):pass
461
+ class CsvFormatError(CsvError):pass
462
+ class PandasError(SqlthonError):pass
463
+ class PandasNotInstalledError(PandasError):pass
464
+ class ValidationError(SqlthonError):pass
465
+ class InvalidColumnCountError(ValidationError):pass
466
+ class InvalidValueError(ValidationError):pass
467
+
468
+
469
+ def _handler_error(e: Exception):
470
+ msg = str(e).lower()
471
+
472
+ if "no such table" in msg:
473
+ raise TableNotFoundError(f"no table with name {msg.split()[-1]!r}.") from None
474
+
475
+ elif "already exists" in msg:
476
+ raise TableAlreadyExistsError(f"table {msg.split()[1]!r} alredy existed.") from None
477
+
478
+ elif "no such column" in msg:
479
+ raise ColumnNotFoundError(f"no column with name {msg.split()[-1]!r}.") from None
480
+
481
+ elif "unique constraint" in msg:
482
+ raise UniqueConstraintError(f"this field {msg.split()[-1]!r} already existed.") from None
483
+
484
+ elif "not null constraint" in msg:
485
+ raise NotNullConstraintError(f"this field cannot be left empty and you sent it {msg.split()[-1]!r}.") from None
486
+
487
+ elif "datatype mismatch" in msg:
488
+ raise DataTypeError(msg) from None
489
+
490
+ elif "foreign key constraint" in msg:
491
+ raise ForeignKeyError(msg) from None
492
+
493
+ elif "check constraint" in msg:
494
+ raise CheckConstraintError(f"check constraint failed {msg.split(": ")[-1]!r}.") from None
495
+
496
+ elif "primary key" in msg:
497
+ raise PrimaryKeyError(msg) from None
498
+
499
+ elif "no such function" in msg:
500
+ raise NoSuchFunctionError(f"no function with name {msg.split()[-1]!r}.") from None
501
+
502
+ elif "wrong number of arguments" in msg:
503
+ raise WrongNumberOfArgumentsError(msg) from None
504
+
505
+ elif "syntax error" in msg:
506
+ raise SyntaxError(f"invalid {msg.split()[-1].replace('"', "'")}") from None
507
+
508
+ elif "database is locked" in msg:
509
+ raise DatabaseLockedError(msg) from None
510
+
511
+ elif "readonly database" in msg:
512
+ raise DatabaseReadOnlyError(msg) from None
513
+
514
+ elif "malformed" in msg:
515
+ raise DatabaseCorruptError(msg) from None
516
+
517
+ elif "disk is full" in msg:
518
+ raise DatabaseFullError(msg) from None
519
+
520
+ elif "database is busy" in msg:
521
+ raise DatabaseBusyError(msg) from None
522
+
523
+ elif "no such index" in msg:
524
+ raise IndexNotFoundError(f"no index with name {msg.split()[-1]!r}.") from None
525
+
526
+ elif "index already exists" in msg:
527
+ raise IndexAlreadyExistsError(f"index {msg.split()[1]!r} already existed.") from None
528
+
529
+ elif "no such view" in msg:
530
+ raise ViewNotFoundError(f"no view with name {msg.split()[-1]!r}.") from None
531
+
532
+ elif "view already exists" in msg:
533
+ raise ViewAlreadyExistsError(f"view {msg.split()[1]!r} already existed.") from None
534
+
535
+ elif "transaction within a transaction" in msg:
536
+ raise TransactionAlreadyActiveError(msg) from None
537
+
538
+ elif "no transaction is active" in msg:
539
+ raise TransactionNotActiveError(msg) from None
540
+
541
+ else:
542
+ raise SqlthonError(msg) from None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlthon
3
- Version: 0.0.15
3
+ Version: 0.1.0
4
4
  Summary: A simple package for SQLite3 operations
5
5
  Author-email: SAUMS <mohamnown@gmail.com>
6
6
  License: MIT
File without changes
File without changes