drifTech-lib 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 driftbluestone
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: drifTech-lib
3
+ Version: 0.1.0
4
+ Summary: Common files/functions across most drifTech software
5
+ Author: driftbluestone
6
+ Author-email: driftbluestone <driftbluestone@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.14
12
+ Project-URL: Source, https://github.com/driftbluestone/drifTech-lib
13
+ Description-Content-Type: text/markdown
14
+
15
+ Common files/functions across most drifTech software
@@ -0,0 +1 @@
1
+ Common files/functions across most drifTech software
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = [
3
+ "uv_build >= 0.12.5, <0.13.0",
4
+ "psycopg[binary]",
5
+ "orjson",
6
+ ]
7
+ build-backend = "uv_build"
8
+
9
+ [project]
10
+ name = "drifTech-lib"
11
+ version = "0.1.0"
12
+ description = "Common files/functions across most drifTech software"
13
+ readme = "README.md"
14
+ requires-python = ">=3.14"
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ license = "MIT"
20
+ license-files = ["LICEN[CS]E*"]
21
+
22
+ [[project.authors]]
23
+ name = "driftbluestone"
24
+ email = "driftbluestone@gmail.com"
25
+
26
+ [project.urls]
27
+ Source = "https://github.com/driftbluestone/drifTech-lib"
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = [
3
+ "uv_build >= 0.12.5, <0.13.0",
4
+ "psycopg[binary]",
5
+ "orjson"
6
+ ]
7
+ build-backend = "uv_build"
8
+
9
+ [project]
10
+ name = "drifTech-lib"
11
+ version = "0.1.0"
12
+ authors = [{name = "driftbluestone", email = "driftbluestone@gmail.com"}]
13
+ description = "Common files/functions across most drifTech software"
14
+ readme = "README.md"
15
+ requires-python = ">=3.14"
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ license = "MIT"
21
+ license-files = ["LICEN[CS]E*"]
22
+
23
+ [project.urls]
24
+ Source = "https://github.com/driftbluestone/drifTech-lib"
@@ -0,0 +1,2 @@
1
+ from . import db, jsonIO
2
+ __all__ = ["db", "jsonIO"]
@@ -0,0 +1,132 @@
1
+ """
2
+ Module for interacting with PostgreSQL
3
+ """
4
+ import psycopg, logging
5
+ from typing import Any
6
+ from psycopg import sql
7
+
8
+ __all__ = ["SCHEMA", "run", "single", "multiple", "insert", "delete", "get", "table"]
9
+
10
+ SCHEMA: sql.Identifier = None
11
+ cursor: psycopg.Cursor = None
12
+ connection: psycopg.Connection = None
13
+
14
+ def table(name: str, columns: list[str]):
15
+ """
16
+ Create a table. Columns should be formatted like `column_name TYPE` e.g. `server_id BIGINT PRIMARY KEY` or `data JSONB`
17
+ """
18
+ run(f"CREATE TABLE IF NOT EXISTS {SCHEMA.as_string()}.{name} ({", ".join(columns)});")
19
+
20
+ def check_connection():
21
+ cursor.execute("SELECT version();")
22
+ db_version = cursor.fetchone()
23
+
24
+ logging.info("Connection Successful")
25
+ logging.info(f"PostgreSQL version: {db_version[0]}")
26
+
27
+ def close_connection():
28
+ cursor.close()
29
+ connection.close()
30
+ logging.info("Database connection closed.")
31
+
32
+ def run(*args):
33
+ cursor.execute(*args)
34
+ connection.commit()
35
+
36
+ def single(*args):
37
+ cursor.execute(*args)
38
+ result = cursor.fetchone()
39
+ if isinstance(result, tuple) and len(result) == 1:
40
+ return result[0]
41
+ return result
42
+
43
+ def multiple(*args):
44
+ cursor.execute(*args)
45
+ return cursor.fetchall()
46
+
47
+ def insert(table: str, key: tuple[str, ...], field: tuple[str, ...], value: tuple[Any, ...]):
48
+ """Actually an upsert function."""
49
+ if not isinstance(key, tuple):
50
+ raise ValueError("Argument `key` must be a tuple.")
51
+ if not isinstance(field, tuple):
52
+ raise ValueError("Argument `field` must be a tuple.")
53
+ if not isinstance(value, tuple):
54
+ raise ValueError("Argument `value` must be a tuple.")
55
+ if len(key) + len(field) != len(value):
56
+ raise ValueError("len(key) + len(field) must equal len(value).")
57
+ if not key:
58
+ raise ValueError("Arguments `key`, `field`, and `value` cannot be empty.")
59
+
60
+ query = "INSERT INTO {schema}.{table} ({fields}) VALUES ({values}) ON CONFLICT ({keys}) DO"
61
+ if field:
62
+ query += " UPDATE SET {assignments}"
63
+ else:
64
+ query += " NOTHING"
65
+
66
+ query = sql.SQL(query).format(
67
+ schema = SCHEMA,
68
+ table = sql.Identifier(table),
69
+ fields = sql.SQL(", ").join(sql.Identifier(f) for f in (key + field)),
70
+ values = sql.SQL(", ").join(sql.Placeholder() for _ in value),
71
+ keys = sql.SQL(", ").join(sql.Identifier(k) for k in key),
72
+ assignments = sql.SQL(", ").join(sql.SQL("{f} = EXCLUDED.{f}").format(
73
+ f=sql.Identifier(f)) for f in field if f not in key
74
+ )
75
+ )
76
+ run(query, value)
77
+
78
+ def delete(table: str, key: tuple[str, ...], value: tuple[Any, ...]):
79
+ if not isinstance(key, tuple):
80
+ raise ValueError("Argument `key` must be a tuple")
81
+ if not isinstance(value, tuple):
82
+ raise ValueError("Argument `value` must be a tuple")
83
+ if len(key) != len(value):
84
+ raise ValueError("Arguments `key` and `value` must be equal in length")
85
+ if not key:
86
+ raise ValueError("Arguments `key` and `value` cannot be empty")
87
+
88
+ query = sql.SQL("DELETE FROM {schema}.{table} WHERE {key}").format(
89
+ schema = SCHEMA,
90
+ table = sql.Identifier(table),
91
+ key = sql.SQL(" AND ").join(sql.SQL("{k} = %s").format(
92
+ k = sql.Identifier(k)) for k in key
93
+ )
94
+ )
95
+ run(query, value)
96
+
97
+ def get(table: str, value: tuple[Any], key: tuple[str], column: tuple[str]):
98
+ if not isinstance(key, tuple):
99
+ raise ValueError("Argument `key` must be a tuple")
100
+ if not isinstance(value, tuple):
101
+ raise ValueError("Argument `value` must be a tuple")
102
+ if len(key) != len(value):
103
+ raise ValueError("Arguments `key` and `value` must be equal in length")
104
+ if not key:
105
+ raise ValueError("Arguments `key` and `value` cannot be empty")
106
+
107
+ query = sql.SQL("SELECT {column} FROM {schema}.{table} WHERE {key}").format(
108
+ schema = SCHEMA,
109
+ table = sql.Identifier(table),
110
+ column = sql.SQL(", ").join(sql.Identifier(c) for c in column), # CANNOT PUT "*" IN HERE
111
+ key = sql.SQL(" AND ").join(sql.SQL("{k} = %s").format(
112
+ k = sql.Identifier(k)) for k in key
113
+ )
114
+ )
115
+
116
+ return single(query, value)
117
+
118
+ def start(schema: str, host: str, name: str, user: str, password: str, port: int):
119
+ global SCHEMA, connection, cursor
120
+ SCHEMA = sql.Identifier(schema)
121
+ logging.info("Connecting to database...")
122
+ connection = psycopg.connect(
123
+ host=host,
124
+ dbname=name,
125
+ user=user,
126
+ password=password,
127
+ port=port
128
+ )
129
+ cursor = connection.cursor()
130
+ check_connection()
131
+ logging.info("Connected to database.")
132
+ connection.execute(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA.as_string()};")
@@ -0,0 +1,55 @@
1
+ """
2
+ Module for writing / reading json with orjson
3
+
4
+ Functions prefixed with `a` are asyncronous and run on a seperate thread,
5
+
6
+ Functions suffixed with `s` or `b` input / return string or bytes, respectively
7
+ """
8
+ import orjson, asyncio
9
+ from pathlib import Path
10
+ from orjson import JSONDecodeError
11
+ __all__ = [
12
+ "read", "load", "write", "dump",
13
+ "dumps", "dumpb", "loads", "loadb",
14
+ "aread", "aload", "awrite", "adump",
15
+ "JSONDecodeError"
16
+ ]
17
+ def read(path: str | Path) -> object:
18
+ with open(path, "rb") as file:
19
+ return orjson.loads(file.read())
20
+
21
+ def load(path: str | Path) -> object:
22
+ with open(path, "rb") as file:
23
+ return orjson.loads(file.read())
24
+
25
+ def write(path: str | Path, data, indent: int = True) -> None:
26
+ with open(path, "wb") as file:
27
+ file.write(orjson.dumps(data, option=1 if indent else None))
28
+
29
+ def dump(path: str | Path, data, indent: int = True) -> None:
30
+ with open(path, "wb") as file:
31
+ file.write(orjson.dumps(data, option=1 if indent else None))
32
+
33
+ def dumps(data) -> str:
34
+ return orjson.dumps(data).decode()
35
+
36
+ def dumpb(data) -> bytes:
37
+ return orjson.dumps(data)
38
+
39
+ def loads(data: str) -> object:
40
+ return orjson.loads(data.encode())
41
+
42
+ def loadb(data: bytes) -> object:
43
+ return orjson.loads(data)
44
+
45
+ async def aread(path: str | Path) -> object:
46
+ return await asyncio.to_thread(read, path)
47
+
48
+ async def aload(path: str | Path) -> object:
49
+ return await asyncio.to_thread(load, path)
50
+
51
+ async def awrite(path: str | Path, data, indent: int = True) -> None:
52
+ return await asyncio.to_thread(write, path, data, indent)
53
+
54
+ async def adump(path: str | Path, data, indent: int = True) -> None:
55
+ return await asyncio.to_thread(dump, path, data, indent)