tentaclio-postgres 0.1.0__py3-none-any.whl

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,20 @@
1
+ """This package implements the tentaclio postgres client"""
2
+
3
+ from importlib.metadata import PackageNotFoundError
4
+ from importlib.metadata import version as _version
5
+
6
+ from tentaclio import * # noqa
7
+
8
+ from .clients.postgres_client import PostgresClient
9
+ from .streams.postgres_handler import PostgresURLHandler
10
+
11
+ try:
12
+ __version__ = _version("tentaclio-postgres")
13
+ except PackageNotFoundError:
14
+ __version__ = "0.0.0"
15
+
16
+ # Db registry
17
+ DB_REGISTRY.register("postgresql", PostgresClient) # type: ignore
18
+
19
+ # postgres handler
20
+ STREAM_HANDLER_REGISTRY.register("postgresql", PostgresURLHandler()) # type: ignore
@@ -0,0 +1,7 @@
1
+ # Helper cli to encode urls.
2
+
3
+
4
+ from tentaclio.__main__ import main
5
+
6
+ if __name__ == "__main__":
7
+ main(prog_name="python -m tentaclio-postgres")
@@ -0,0 +1,9 @@
1
+ """The client module defines stream and query based clients.
2
+
3
+ Stream clients allow to read and write from stream based sources with ease,
4
+ and in an interchangable manner.
5
+
6
+ Query based clients unify how to access databases leveraging from sqlalchemy.
7
+ """
8
+
9
+ from .postgres_client import * # noqa
@@ -0,0 +1,87 @@
1
+ """Postgres query client.
2
+ Adds the convinience methods for loading csv data using copy_expert,
3
+ which is more performant than using sql alchemy functions.
4
+ """
5
+
6
+ import io
7
+ import os
8
+ from typing import Sequence
9
+
10
+ import pandas as pd
11
+ from tentaclio import protocols
12
+ from tentaclio.clients import decorators, sqla_client
13
+
14
+ __all__ = ["PostgresClient"]
15
+
16
+
17
+ class PostgresClient(sqla_client.SQLAlchemyClient):
18
+ """Postgres client, backed by a SQLAlchemy connection.
19
+ While connecting will check TENTACLIO__PG_APPLICATION_NAME to set
20
+ the applicationName in the connection string.
21
+ """
22
+
23
+ TENTACLIO__PG_APPLICATION_NAME = "TENTACLIO__PG_APPLICATION_NAME"
24
+
25
+ allowed_schemes = ["postgresql"]
26
+
27
+ def _extract_url_params(self):
28
+ super()._extract_url_params()
29
+ application_name = os.getenv(self.TENTACLIO__PG_APPLICATION_NAME, "")
30
+ if application_name != "":
31
+ if self.url_query is None:
32
+ self.url_query: dict = {}
33
+ # overrides the value that might be set in the tentaclio file
34
+ self.url_query["application_name"] = application_name
35
+
36
+ # Postgres Copy Expert methods:
37
+ @decorators.check_conn
38
+ def get_df_unsafe(self, sql_query: str, params: None = None, **kwargs) -> pd.DataFrame:
39
+ """Run a raw SQL query and return a data frame using COPY.
40
+ Params:
41
+ sql_query: query to execute
42
+ params: not supported; must be None
43
+ **kwargs: additional kwargs to pass to `pandas.read_csv`
44
+ """
45
+ if params is not None:
46
+ raise NotImplementedError(
47
+ "Support for `params` is not implemented; please provide a pre-formatted query."
48
+ )
49
+ copy_sql = f"COPY ({sql_query.rstrip(';')}) TO STDOUT WITH CSV HEADER"
50
+ buffer = io.StringIO()
51
+ raw_conn = self._get_raw_conn()
52
+ raw_conn.cursor().copy_expert(copy_sql, buffer)
53
+ buffer.seek(0)
54
+ df = pd.read_csv(buffer, **kwargs)
55
+ return df
56
+
57
+ @decorators.check_conn
58
+ def dump_df(self, df: pd.DataFrame, dest_table: str) -> None:
59
+ """Dump a data frame into an existing Postgres table."""
60
+ buff = io.StringIO()
61
+ df.to_csv(buff, index=False)
62
+ buff.seek(0)
63
+ self._copy_expert_csv(buff, df.columns, dest_table)
64
+
65
+ @decorators.check_conn
66
+ def dump_csv(
67
+ self, csv_reader: protocols.Reader, columns: Sequence[str], dest_table: str
68
+ ) -> None:
69
+ """Dump a csv reader into the database."""
70
+ self._copy_expert_csv(csv_reader, columns, dest_table)
71
+
72
+ def _copy_expert_csv(
73
+ self, csv_reader: protocols.Reader, columns: Sequence[str], dest_table: str
74
+ ) -> None:
75
+ """Dump a csv reader into the given table."""
76
+ sql_columns = ",".join(columns)
77
+ sql_query = f"""COPY {dest_table} ({sql_columns}) FROM STDIN
78
+ WITH CSV HEADER DELIMITER AS ','
79
+ NULL AS 'NULL';"""
80
+ raw_conn = self._get_raw_conn()
81
+ try:
82
+ raw_conn.cursor().copy_expert(sql_query, csv_reader)
83
+ except Exception:
84
+ raw_conn.rollback()
85
+ raise
86
+ else:
87
+ raw_conn.commit()
@@ -0,0 +1 @@
1
+ from .postgres_handler import * # noqa
@@ -0,0 +1,48 @@
1
+ """Handler for postgresql:// urls."""
2
+
3
+ from typing import Tuple
4
+
5
+ from tentaclio.protocols import ReaderClosable, WriterClosable
6
+ from tentaclio.streams import csv_db_stream
7
+ from tentaclio.urls import URL
8
+
9
+ from tentaclio_postgres.clients import postgres_client
10
+
11
+ __all__ = ["PostgresURLHandler"]
12
+
13
+
14
+ def _split_url(url: URL) -> Tuple[URL, str]:
15
+ parts = url.path.split("::")
16
+ if len(parts) != 2 or parts[1] == "":
17
+ raise ValueError("No table provided for dumping the csv data")
18
+ path = parts[0]
19
+ table = parts[1]
20
+ conn_url = URL.from_components(
21
+ scheme=url.scheme,
22
+ username=url.username,
23
+ password=url.password,
24
+ hostname=url.hostname,
25
+ port=url.port,
26
+ path=path,
27
+ query=url.query,
28
+ )
29
+ return conn_url, table
30
+
31
+
32
+ class PostgresURLHandler:
33
+ """Handler for opening writers and readers ."""
34
+
35
+ def open_reader_for(self, url: URL, mode: str, extras: dict) -> ReaderClosable:
36
+ """Not implemented."""
37
+ raise NotImplementedError("Reading csv from postgres not implemented")
38
+
39
+ def open_writer_for(self, url: URL, mode: str, extras: dict) -> WriterClosable:
40
+ """Open writer to dump the csv into a table in database.
41
+ This stream writer only works for csv data at the moment. The url must contain
42
+ a table as the last part of the path separated by a doble colon i.e.
43
+ `postgresql://user:pass@host/database::table`. The target table needs the columns
44
+ with the same names as the field names.
45
+ """
46
+ conn_url, table = _split_url(url)
47
+ client = postgres_client.PostgresClient(conn_url, **extras)
48
+ return csv_db_stream.DatabaseCsvWriter(client, table)
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: tentaclio-postgres
3
+ Version: 0.1.0
4
+ Summary: A python project containing all the dependencies for schema postgres for tentaclio.
5
+ Author-email: Octopus Energy <nerds@octopus.energy>
6
+ License-Expression: MIT
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE.txt
19
+ Requires-Dist: tentaclio
20
+ Requires-Dist: psycopg2-binary
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest; extra == "dev"
23
+ Requires-Dist: pytest-cov; extra == "dev"
24
+ Requires-Dist: pytest-mock; extra == "dev"
25
+ Requires-Dist: black; extra == "dev"
26
+ Requires-Dist: flake8; extra == "dev"
27
+ Requires-Dist: Flake8-pyproject; extra == "dev"
28
+ Requires-Dist: isort>=5.11.2; extra == "dev"
29
+ Requires-Dist: mypy; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+
33
+ # tentaclio-postgres
34
+
35
+ A package containing all the dependencies for the postgresql tentaclio schema .
36
+
37
+ ## Quick Start
38
+
39
+ This project comes with a `Makefile` which is ready to do basic common tasks
40
+
41
+ ```
42
+ $ make help
43
+ install Initalise the virtual env installing deps
44
+ clean Remove all the unwanted clutter
45
+ lock Lock dependencies
46
+ update Update dependencies (whole tree)
47
+ sync Install dependencies as per the lock file
48
+ lint Lint files with flake and mypy
49
+ format Run black and isort
50
+ test Run unit tests
51
+ circleci Validate circleci configuration (needs circleci cli)
52
+ ```
@@ -0,0 +1,11 @@
1
+ tentaclio_postgres/__init__.py,sha256=zqft6-mFQd0yzbV5gfYo8WjBys-CBBIlOw2fExNgEW4,604
2
+ tentaclio_postgres/__main__.py,sha256=Fx9uOFe0XHNiAC_hAwLBFO-6dYIxK8fGYDCA9mXbQwc,146
3
+ tentaclio_postgres/clients/__init__.py,sha256=lULFwiVzNtWEOdAsCbf4I9ECDaXwrSeMmo_NkmlA_iA,294
4
+ tentaclio_postgres/clients/postgres_client.py,sha256=SDWlX6O3gz2DCIYwv0vhpGCAZ-z50s8qZiN6dCKXJvM,3173
5
+ tentaclio_postgres/streams/__init__.py,sha256=9D2OcQ70_WgTdsQTf7_fpeESudeNbYvonwK5JApF51k,40
6
+ tentaclio_postgres/streams/postgres_handler.py,sha256=YDetA29332SZQ4YjAOeEB8NAB4vYB0rkCBl-_eMxC2c,1694
7
+ tentaclio_postgres-0.1.0.dist-info/licenses/LICENSE.txt,sha256=Aqv2h5R53YlGaQXl7XgUDMZPUxJK1HftERN2ExXJ_u4,1080
8
+ tentaclio_postgres-0.1.0.dist-info/METADATA,sha256=CzCf4_ILMtNi4Dq1TSZetpSg441JxZUKGjtq_J3ZuOk,1958
9
+ tentaclio_postgres-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
10
+ tentaclio_postgres-0.1.0.dist-info/top_level.txt,sha256=Srpz8siGsW7_npK27Ct1E3p4WizTSI0P5UyUEqWZLJE,19
11
+ tentaclio_postgres-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Octopus Energy Limited.
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 @@
1
+ tentaclio_postgres