sqlthon 0.0.15__tar.gz → 0.1.1__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.1
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.1'
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.1'
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,24 @@ 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 any(word in query.lower() for word in ("sqlite_", "union", "select", "blob", "pragma")):
103
+ for i in {"NOT", "NULL", "PRIMARY", "KEY", "UNIQUE", "DEFAULT",
104
+ "CHECK", "AUTOINCREMENT", "REFERENCES", "COLLATE",
105
+ "TRUE", "FALSE", "CURRENT_TIMESTAMP", "ON", "DELETE",
106
+ "UPDATE", "CASCADE", "RESTRICT", "SET", "NO", "ACTION",
107
+ "PRECISION", "DOUBLE", "UNSIGNED", "BIG", "INT",
108
+ "NATIVE", "CHARACTER", "VARYING",}:
109
+ if not i in query:
110
+ raise YouHackerError(f"you hacker for {query!r}.") from None
111
+
92
112
 
93
113
  class Connect:
94
114
  __slots__ = ("_con", "_cur", "_changes", "_path")
@@ -102,15 +122,17 @@ class Connect:
102
122
 
103
123
  # ____________| TABLE |____________
104
124
  def add_table(self, table_name: str, *columns: tuple, if_not_exists=False) -> None:
125
+ _analysis_code(table_name)
105
126
  query = "CREATE TABLE "
106
127
  if if_not_exists:
107
128
  query += "IF NOT EXISTS "
108
129
  query += f"{table_name} ("
109
130
  for column in columns:
131
+ _analysis_code(column)
110
132
  name, type = column[0], column[1]
111
133
  try:
112
134
  limits = column[2]
113
- query += f"{name} {type} {" ".join(limits)}"
135
+ query += f"""{name} {type} {" ".join(limits)}"""
114
136
  except:
115
137
  query += f"{name} {type}"
116
138
 
@@ -119,48 +141,72 @@ class Connect:
119
141
  self._changes.append((query,))
120
142
 
121
143
  def rename_table(self, old_name_table: str, new_name_table: str) -> None:
144
+ _analysis_code(old_name_table)
145
+ _analysis_code(new_name_table)
122
146
  self._changes.append((f"ALTER TABLE {old_name_table} RENAME TO {new_name_table}",))
123
147
 
124
148
  def drop_table(self, table_name: str) -> None:
149
+ _analysis_code(table_name)
125
150
  self._changes.append((f"DROP TABLE {table_name}",))
126
151
 
127
152
  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'")]
153
+ _analysis_code(table_name)
154
+ return table_name in [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
129
155
 
130
156
  def copy_table(self, table_name: str, new_name_table: str) -> None:
157
+ _analysis_code(table_name)
158
+ _analysis_code(new_name_table)
131
159
  self._changes.append((f"CREATE TABLE {new_name_table} AS SELECT * FROM {table_name}"),)
132
160
 
133
161
  def get_tables(self) -> list:
134
- return [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='table'")]
162
+ return [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
135
163
 
136
164
  # ____________| COLUMN |____________
137
165
  def add_column(self, table_name: str, column_name: str, column_type: str, limits: list | str=[]) -> None:
166
+ _analysis_code(table_name)
167
+ _analysis_code(column_name)
168
+ _analysis_code(column_type)
138
169
  if limits:
170
+ _analysis_code(limits)
139
171
  limits = " ".join(limits)
140
172
  else:
141
173
  limits = ""
142
174
  self._changes.append((f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} {limits}",))
143
175
 
144
176
  def drop_column(self, table_name: str, column_name: str) -> None:
177
+ _analysis_code(table_name)
178
+ _analysis_code(column_name)
145
179
  self._changes.append((f"ALTER TABLE {table_name} DROP COLUMN {column_name}",))
146
180
 
147
181
  def rename_column(self, table_name: str, old_name_column: str, new_name_column: str) -> None:
182
+ _analysis_code(table_name)
183
+ _analysis_code(old_name_column)
184
+ _analysis_code(new_name_column)
148
185
  self._changes.append((f"ALTER TABLE {table_name} RENAME COLUMN {old_name_column} TO {new_name_column}",))
149
186
 
150
187
  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})")]
188
+ _analysis_code(table_name)
189
+ _analysis_code(column_name)
190
+ return column_name in [i[1] for i in self._cur.execute(f"PRAGMA table_info({table_name})").fetchall()]
152
191
 
153
192
  def get_columns(self, table_name: str) -> list:
154
- return [i[1] for i in self.run_query(f"PRAGMA table_info({table_name})")]
193
+ _analysis_code(table_name)
194
+ return [i[1] for i in self._cur.execute(f"PRAGMA table_info({table_name})").fetchall()]
155
195
 
156
196
  # ____________| RECORD |____________
157
197
  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):
198
+ _analysis_code(table_name)
158
199
  query = "SELECT "
159
200
  param = ()
160
201
  if unique:
161
202
  query += "DISTINCT "
162
- query += f"{', '.join(columns) if columns else '*'} FROM {table_name}"
203
+ if columns:
204
+ _analysis_code(columns)
205
+ query += f"""{", ".join(columns) if columns else "*"} FROM {table_name}"""
163
206
  if compound:
207
+ if compound[0].upper() not in ("INNER", "LEFT"):
208
+ raise YouHackerError(f"you hacker for {query!r}.") from None
209
+ _analysis_code(compound)
164
210
  query += f" {compound[0]} JOIN \"{compound[1]}\" ON {compound[2]} = {compound[3]}"
165
211
  if condition:
166
212
  _: tuple = _compile(condition)
@@ -168,6 +214,7 @@ class Connect:
168
214
  param += _[1]
169
215
  del _
170
216
  if bundle:
217
+ _analysis_code(bundle)
171
218
  query += f" GROUP BY {", ".join(bundle)}"
172
219
  if filter_bundle:
173
220
  __: tuple = _compile(filter_bundle)
@@ -176,39 +223,53 @@ class Connect:
176
223
  del __
177
224
 
178
225
  if sort:
226
+ _analysis_code(sort)
179
227
  query += " ORDER BY "
180
228
  if sort[-1].upper() == "ASC" or sort[-1].upper() == "DESC":
181
229
  query += f"{", ".join(sort[:-1])} {sort[-1]}"
182
230
  else:
183
231
  query += ", ".join(sort)
184
232
  if several is not None:
233
+ if not isinstance(several, int):
234
+ raise YouHackerError(f"you hacker for {several!r}.")
185
235
  query += f" LIMIT {several}"
186
236
  if jump:
237
+ if not isinstance(jump, int):
238
+ raise YouHackerError(f"you hacker for {jump!r}.")
187
239
  query += f" OFFSET {jump}"
188
- return self.run_query(query, param)
240
+ return self._cur.execute(query, param).fetchall()
189
241
 
190
242
  def add_record(self, table_name: str, record_info: tuple) -> None:
191
- self._changes.append((f"INSERT INTO {table_name} VALUES({', '.join(['?']*len(record_info))})", record_info))
243
+ _analysis_code(table_name)
244
+ self._changes.append((f"""INSERT INTO {table_name} VALUES({", ".join(["?"]*len(record_info))})""", record_info))
192
245
 
193
246
  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()
247
+ _analysis_code(table_name)
248
+ try:
249
+ self._cur.executemany(f"""INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_records[0]))})""", info_records)
250
+ self._con.commit()
251
+ except Exception as e:
252
+ _handler_error(e)
196
253
 
197
254
  def delete_record(self, table_name, condition):
255
+ _analysis_code(table_name)
198
256
  query = f"DELETE FROM {table_name}"
199
257
  sql_where, params = _compile(condition)
200
258
  query += " WHERE " + sql_where
201
259
  self._changes.append((query, params))
202
260
 
203
261
  def delete_all_record(self, table_name: str) -> None:
262
+ _analysis_code(table_name)
204
263
  self._changes.append((f"DELETE FROM {table_name}",))
205
264
 
206
265
  def edit_record(self, table_name, new_info_record, condition=None):
266
+ _analysis_code(table_name)
207
267
  query = f"UPDATE {table_name} SET "
208
268
  params = ()
209
269
 
210
270
  set_parts = []
211
271
  for key, value in new_info_record.items():
272
+ _analysis_code(key)
212
273
  set_parts.append(f'"{key}" = ?')
213
274
  params += (value,)
214
275
  query += ", ".join(set_parts)
@@ -221,10 +282,13 @@ class Connect:
221
282
  self._changes.append((query, params))
222
283
 
223
284
  def count_record(self, table_name: str) -> int:
224
- return self.run_query(f"SELECT COUNT(*) FROM {table_name}")[0][0]
285
+ _analysis_code(table_name)
286
+ return self._cur.execute(f"SELECT COUNT(*) FROM {table_name}").fetchall()[0][0]
225
287
 
226
288
  def upsert_record(self, table_name: str, info_record: tuple, conflict: tuple) -> None:
227
- query = f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_record))}) ON CONFLICT(\"{'", "'.join(conflict)}\") DO UPDATE SET "
289
+ _analysis_code(table_name)
290
+ _analysis_code(conflict)
291
+ query = f"""INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_record))}) ON CONFLICT(\"{'", "'.join(conflict)}\") DO UPDATE SET """
228
292
  param = info_record
229
293
  colue = dict(zip(self.get_columns(table_name), info_record)) # columns value
230
294
  for i in conflict:
@@ -237,39 +301,55 @@ class Connect:
237
301
 
238
302
  # ____________| INDEX |_________
239
303
  def add_index(self, table_name: str, column_name: str, unique: bool=False) -> None:
304
+ _analysis_code(table_name)
305
+ _analysis_code(column_name)
240
306
  self._changes.append((f"CREATE INDEX{" UNIQUE" if unique else ""} {table_name}_{column_name} ON {table_name} ({column_name})",))
241
307
 
242
308
  def delete_index(self, table_name: str, column_name: str) -> None:
309
+ _analysis_code(table_name)
310
+ _analysis_code(column_name)
243
311
  self._changes.append((f"DROP INDEX {table_name}_{column_name}",))
244
312
 
245
313
  # ____________| VIEW |_________
246
314
  def add_view(self, view_name: str, query: str) -> None:
247
- self._changes.append((f"CREATE VIEW {view_name} AS {query}",))
315
+ raise YouHackerError("add_view is disabled for security reasons.")
248
316
 
249
317
  def delete_view(self, view_name: str) -> None:
318
+ _analysis_code(view_name)
250
319
  self._changes.append((f"DROP VIEW {view_name}",))
251
320
 
252
321
  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'")]
322
+ _analysis_code(view_name)
323
+ return view_name in [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='view'").fetchall()]
254
324
 
255
325
  # ____________| BACKUP |_________
256
326
  def backup_database(self, backup_path: str | None=None) -> None:
257
327
  from shutil import copy2
328
+ from os.path import abspath, dirname, join
258
329
  self._con.commit()
330
+ allowed_dir = dirname(abspath(self._path))
259
331
  if backup_path:
332
+ if not abspath(backup_path).startswith(allowed_dir):
333
+ raise YouHackerError(f"you hacker for {backup_path!r}.")
260
334
  copy2(self._path, backup_path)
261
335
  else:
262
- copy2(self._path, "".join(self._path.split(".")[:-1]))
336
+ copy2(self._path, join(allowed_dir, "backup.db"))
263
337
 
264
338
  # ____________| PANDAS |_________
265
339
  def to_dataframe(self, table_name: str) -> "pd.DataFrame":
340
+ _analysis_code(table_name)
266
341
  import pandas as pd
267
342
  columns = self.get_columns(table_name)
268
- result = self.run_query(f"SELECT * FROM {table_name}")
343
+ result = self._cur.execute(f"SELECT * FROM {table_name}").fetchall()
269
344
  return pd.DataFrame(result, columns=columns)
270
345
 
271
346
  # ____________| CSV |_________
272
347
  def load_csv(self, table_name: str, csv_path: str) -> None:
348
+ _analysis_code(table_name)
349
+ from os.path import abspath, dirname
350
+ allowed_dir = dirname(abspath(self._path))
351
+ if not abspath(csv_path).startswith(allowed_dir):
352
+ raise YouHackerError(f"you hacker for {csv_path!r}.")
273
353
  import csv as _csv
274
354
 
275
355
  with open(csv_path) as file:
@@ -289,8 +369,13 @@ class Connect:
289
369
  self.add_records(table_name, tuple(records))
290
370
 
291
371
  def to_csv(self, table_name: str, csv_path: str) -> None:
372
+ _analysis_code(table_name)
373
+ from os.path import abspath, dirname
374
+ allowed_dir = dirname(abspath(self._path))
375
+ if not abspath(csv_path).startswith(allowed_dir):
376
+ raise YouHackerError(f"you hacker for {csv_path!r}.")
292
377
  import csv as _csv
293
- with open(csv_path, "w", newline="", encoding="utf-8") as f:
378
+ with open(csv_path, "w") as f:
294
379
  writer = _csv.writer(f)
295
380
  writer.writerow(self.get_columns(table_name))
296
381
  for row in self.find_record(table_name):
@@ -298,7 +383,7 @@ class Connect:
298
383
 
299
384
  # ____________| OTHER |_________
300
385
  def last_id(self) -> int:
301
- return self.run_query("SELECT last_insert_rowid()")[0][0]
386
+ return self._cur.execute("SELECT last_insert_rowid()").fetchall()[0][0]
302
387
 
303
388
  def database_info(self) -> dict:
304
389
  from os.path import basename, exists, getsize
@@ -307,13 +392,11 @@ class Connect:
307
392
  "size": getsize(self._path) if exists(self._path) else 0,
308
393
  "count_tables": len(self.get_tables())
309
394
  }
395
+
310
396
 
311
397
  # ____________| BASIC |_________
312
398
  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()
399
+ raise YouHackerError("run_query is disabled for security reasons.")
317
400
 
318
401
  def optimize(self) -> None:
319
402
  self.save_to_database()
@@ -325,8 +408,9 @@ class Connect:
325
408
  with self._con:
326
409
  for sql_code in self._changes:
327
410
  self._cur.execute(*sql_code)
328
- finally:
329
411
  self._changes.clear()
412
+ except Exception as e:
413
+ _handler_error(e)
330
414
 
331
415
  def close(self):
332
416
  self._con.close()
@@ -337,4 +421,127 @@ class Connect:
337
421
 
338
422
  def __exit__(self, exc_type, exc_value, exc_tb) -> None:
339
423
  self.save_to_database()
340
- self.close()
424
+ self.close()
425
+
426
+
427
+ # ____________| ERRORS |_________
428
+ class SqlthonError(Exception):pass
429
+ class YouHackerError(SqlthonError, PermissionError):pass
430
+ class TableError(SqlthonError):pass
431
+ class TableNotFoundError(TableError):pass
432
+ class TableAlreadyExistsError(TableError):pass
433
+ class ColumnError(SqlthonError):pass
434
+ class ColumnNotFoundError(ColumnError):pass
435
+ class RecordError(SqlthonError):pass
436
+ class UniqueConstraintError(RecordError):pass
437
+ class NotNullConstraintError(RecordError):pass
438
+ class DataTypeError(RecordError):pass
439
+ class ForeignKeyError(RecordError):pass
440
+ class CheckConstraintError(RecordError):pass
441
+ class PrimaryKeyError(RecordError):pass
442
+ class QueryError(SqlthonError):pass
443
+ class SyntaxError(QueryError):pass
444
+ class NoSuchFunctionError(QueryError):pass
445
+ class WrongNumberOfArgumentsError(QueryError):pass
446
+ class DatabaseError(SqlthonError):pass
447
+ class DatabaseLockedError(DatabaseError):pass
448
+ class DatabaseReadOnlyError(DatabaseError):pass
449
+ class DatabaseCorruptError(DatabaseError):pass
450
+ class DatabaseFullError(DatabaseError):pass
451
+ class DatabaseBusyError(DatabaseError):pass
452
+ class IndexError(SqlthonError):pass
453
+ class IndexNotFoundError(IndexError):pass
454
+ class IndexAlreadyExistsError(IndexError):pass
455
+ class ViewError(SqlthonError):pass
456
+ class ViewNotFoundError(ViewError):pass
457
+ class ViewAlreadyExistsError(ViewError):pass
458
+ class TransactionError(SqlthonError):pass
459
+ class TransactionAlreadyActiveError(TransactionError):pass
460
+ class TransactionNotActiveError(TransactionError):pass
461
+ class BackupError(SqlthonError):pass
462
+ class BackupPathError(BackupError):pass
463
+ class BackupPermissionError(BackupError):pass
464
+ class CsvError(SqlthonError):pass
465
+ class CsvFileNotFoundError(CsvError):pass
466
+ class CsvFormatError(CsvError):pass
467
+ class PandasError(SqlthonError):pass
468
+ class PandasNotInstalledError(PandasError):pass
469
+ class ValidationError(SqlthonError):pass
470
+ class InvalidColumnCountError(ValidationError):pass
471
+ class InvalidValueError(ValidationError):pass
472
+
473
+
474
+ def _handler_error(e: Exception):
475
+ msg = str(e).lower()
476
+
477
+ if "no such table" in msg:
478
+ raise TableNotFoundError(f"no table with name {msg.split()[-1]!r}.") from None
479
+
480
+ elif "already exists" in msg:
481
+ raise TableAlreadyExistsError(f"table {msg.split()[1]!r} alredy existed.") from None
482
+
483
+ elif "no such column" in msg:
484
+ raise ColumnNotFoundError(f"no column with name {msg.split()[-1]!r}.") from None
485
+
486
+ elif "unique constraint" in msg:
487
+ raise UniqueConstraintError(f"this field {msg.split()[-1]!r} already existed.") from None
488
+
489
+ elif "not null constraint" in msg:
490
+ raise NotNullConstraintError(f"this field cannot be left empty and you sent it {msg.split()[-1]!r}.") from None
491
+
492
+ elif "datatype mismatch" in msg:
493
+ raise DataTypeError(msg) from None
494
+
495
+ elif "foreign key constraint" in msg:
496
+ raise ForeignKeyError(msg) from None
497
+
498
+ elif "check constraint" in msg:
499
+ raise CheckConstraintError(f"check constraint failed {msg.split(": ")[-1]!r}.") from None
500
+
501
+ elif "primary key" in msg:
502
+ raise PrimaryKeyError(msg) from None
503
+
504
+ elif "no such function" in msg:
505
+ raise NoSuchFunctionError(f"no function with name {msg.split()[-1]!r}.") from None
506
+
507
+ elif "wrong number of arguments" in msg:
508
+ raise WrongNumberOfArgumentsError(msg) from None
509
+
510
+ elif "syntax error" in msg:
511
+ raise SyntaxError(f"invalid {msg.split()[-1].replace('"', "'")}") from None
512
+
513
+ elif "database is locked" in msg:
514
+ raise DatabaseLockedError(msg) from None
515
+
516
+ elif "readonly database" in msg:
517
+ raise DatabaseReadOnlyError(msg) from None
518
+
519
+ elif "malformed" in msg:
520
+ raise DatabaseCorruptError(msg) from None
521
+
522
+ elif "disk is full" in msg:
523
+ raise DatabaseFullError(msg) from None
524
+
525
+ elif "database is busy" in msg:
526
+ raise DatabaseBusyError(msg) from None
527
+
528
+ elif "no such index" in msg:
529
+ raise IndexNotFoundError(f"no index with name {msg.split()[-1]!r}.") from None
530
+
531
+ elif "index already exists" in msg:
532
+ raise IndexAlreadyExistsError(f"index {msg.split()[1]!r} already existed.") from None
533
+
534
+ elif "no such view" in msg:
535
+ raise ViewNotFoundError(f"no view with name {msg.split()[-1]!r}.") from None
536
+
537
+ elif "view already exists" in msg:
538
+ raise ViewAlreadyExistsError(f"view {msg.split()[1]!r} already existed.") from None
539
+
540
+ elif "transaction within a transaction" in msg:
541
+ raise TransactionAlreadyActiveError(msg) from None
542
+
543
+ elif "no transaction is active" in msg:
544
+ raise TransactionNotActiveError(msg) from None
545
+
546
+ else:
547
+ 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.1
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