stream2pg 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.
stream2pg/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from stream2pg.sink import Stream2Pg
4
+
5
+ __all__ = ["Stream2Pg"]
stream2pg/config.py ADDED
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+ from enum import Enum
3
+ from typing import Any, Callable, Optional
4
+
5
+ from .errors import ConfigurationError
6
+
7
+
8
+ class ErrorStrategy(Enum):
9
+ RAISE = "raise"
10
+ SKIP_ON_ERROR = "skip_on_error"
11
+
12
+
13
+ def from_config(
14
+ config: dict[str, Any],
15
+ on_metrics: Optional[Callable[..., None]] = None,
16
+ ) -> dict[str, Any]:
17
+ missing = []
18
+ for key in ("postgres", "kafka", "processing"):
19
+ if key not in config:
20
+ missing.append(key)
21
+
22
+ if missing:
23
+ raise ConfigurationError(f"Missing required config keys: {', '.join(missing)}")
24
+
25
+ return {
26
+ "postgres": config["postgres"],
27
+ "kafka": config["kafka"],
28
+ "processing": config["processing"],
29
+ "on_metrics": on_metrics,
30
+ }
stream2pg/core.py ADDED
@@ -0,0 +1,117 @@
1
+ from __future__ import annotations
2
+ import json
3
+ import time
4
+ from typing import Any, Callable, Optional
5
+
6
+ from pyspark.sql import SparkSession
7
+ from pyspark.sql.functions import col
8
+ from pyspark.sql.types import StructType
9
+
10
+ from .config import ErrorStrategy
11
+ from .db import ensure_columns, ensure_table, insert_record
12
+
13
+
14
+ def create_spark_session(app_name: str = "KafkaToPostgres") -> SparkSession:
15
+ return (
16
+ SparkSession.builder.appName(app_name)
17
+ .config(
18
+ "spark.jars.packages",
19
+ "org.apache.spark:spark-sql-kafka-0-10_2.13:4.1.2",
20
+ )
21
+ .getOrCreate()
22
+ )
23
+
24
+
25
+ def process_batch(
26
+ batch_df: Any,
27
+ batch_id: int,
28
+ pg_config: dict[str, Any],
29
+ error_strategy: ErrorStrategy,
30
+ on_metrics: Optional[Callable[..., None]] = None,
31
+ ) -> None:
32
+ start_time = time.time()
33
+ row_count = 0
34
+ inserted_count = 0
35
+ skipped_count = 0
36
+
37
+ if batch_df.isEmpty():
38
+ return
39
+
40
+ row_count = batch_df.count()
41
+ conn = pg_config.get("connection")
42
+ if conn is None:
43
+ import psycopg2
44
+
45
+ conn = psycopg2.connect(
46
+ **{k: v for k, v in pg_config.items() if k != "connection"}
47
+ )
48
+ owns_connection = True
49
+ else:
50
+ owns_connection = False
51
+
52
+ try:
53
+ known_columns: dict[str, frozenset] = {}
54
+ for row in batch_df.toLocalIterator():
55
+ table_name = row.topic.replace("mobility-", "")
56
+ try:
57
+ record = json.loads(row.value)
58
+ except json.JSONDecodeError:
59
+ skipped_count += 1
60
+ if error_strategy == ErrorStrategy.RAISE:
61
+ raise
62
+ continue
63
+
64
+ ensure_table(conn, table_name)
65
+ current_schema = frozenset(record.keys())
66
+ if known_columns.get(table_name) != current_schema:
67
+ ensure_columns(conn, table_name, record)
68
+ known_columns[table_name] = current_schema
69
+
70
+ try:
71
+ insert_record(conn, table_name, record)
72
+ inserted_count += 1
73
+ except Exception:
74
+ if error_strategy == ErrorStrategy.RAISE:
75
+ raise
76
+ skipped_count += 1
77
+
78
+ conn.commit()
79
+ except Exception:
80
+ conn.rollback()
81
+ raise
82
+ finally:
83
+ if owns_connection:
84
+ conn.close()
85
+
86
+ elapsed_ms = int((time.time() - start_time) * 1000)
87
+ if on_metrics:
88
+ on_metrics(batch_id, row_count, inserted_count, skipped_count, elapsed_ms)
89
+
90
+
91
+ def create_kafka_stream(
92
+ spark: SparkSession,
93
+ kafka_config: dict[str, Any],
94
+ schema: Optional[StructType] = None,
95
+ ):
96
+ reader = (
97
+ spark.readStream.format("kafka")
98
+ .option(
99
+ "kafka.bootstrap.servers",
100
+ kafka_config.get("bootstrap_servers", "localhost:9092"),
101
+ )
102
+ .option(
103
+ "subscribePattern", kafka_config.get("subscribe_pattern", "mobility-.*")
104
+ )
105
+ .option("startingOffsets", kafka_config.get("starting_offsets", "earliest"))
106
+ .option(
107
+ "failOnDataLoss",
108
+ str(kafka_config.get("fail_on_data_loss", "false")).lower(),
109
+ )
110
+ )
111
+
112
+ df = reader.load()
113
+ df = df.select(
114
+ col("topic"),
115
+ col("value").cast("string").alias("value"),
116
+ )
117
+ return df
stream2pg/db.py ADDED
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+ from datetime import datetime
3
+ from typing import Any
4
+
5
+ import psycopg2
6
+ from psycopg2 import sql
7
+
8
+
9
+ def infer_sql_type(value: Any) -> str:
10
+ if isinstance(value, bool):
11
+ return "BOOLEAN"
12
+ if isinstance(value, int):
13
+ return "BIGINT"
14
+ if isinstance(value, float):
15
+ return "DOUBLE PRECISION"
16
+ if isinstance(value, str):
17
+ try:
18
+ datetime.fromisoformat(value.replace("Z", "+00:00"))
19
+ return "TIMESTAMP"
20
+ except Exception:
21
+ return "TEXT"
22
+ return "TEXT"
23
+
24
+
25
+ def ensure_table(conn: psycopg2.extensions.connection, table_name: str) -> None:
26
+ with conn.cursor() as cur:
27
+ cur.execute(
28
+ sql.SQL("CREATE TABLE IF NOT EXISTS {} (id BIGSERIAL PRIMARY KEY)").format(
29
+ sql.Identifier(table_name)
30
+ )
31
+ )
32
+
33
+
34
+ def ensure_columns(
35
+ conn: psycopg2.extensions.connection, table_name: str, record: dict
36
+ ) -> None:
37
+ with conn.cursor() as cur:
38
+ for key, value in record.items():
39
+ cur.execute(
40
+ """
41
+ SELECT EXISTS (
42
+ SELECT 1
43
+ FROM information_schema.columns
44
+ WHERE table_name = %s
45
+ AND column_name = %s
46
+ )
47
+ """,
48
+ (table_name, key),
49
+ )
50
+ exists = cur.fetchone()[0]
51
+ if not exists:
52
+ cur.execute(
53
+ sql.SQL("ALTER TABLE {} ADD COLUMN {} {}").format(
54
+ sql.Identifier(table_name),
55
+ sql.Identifier(key),
56
+ sql.SQL(infer_sql_type(value)),
57
+ )
58
+ )
59
+
60
+
61
+ def convert_value(value: Any) -> Any:
62
+ if isinstance(value, str):
63
+ try:
64
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
65
+ except Exception:
66
+ return value
67
+ return value
68
+
69
+
70
+ def insert_record(
71
+ conn: psycopg2.extensions.connection, table_name: str, record: dict
72
+ ) -> None:
73
+ columns = list(record.keys())
74
+ values = [convert_value(record[c]) for c in columns]
75
+ with conn.cursor() as cur:
76
+ cur.execute(
77
+ sql.SQL("INSERT INTO {} ({}) VALUES ({})").format(
78
+ sql.Identifier(table_name),
79
+ sql.SQL(", ").join(map(sql.Identifier, columns)),
80
+ sql.SQL(", ").join(sql.Placeholder() * len(columns)),
81
+ ),
82
+ values,
83
+ )
stream2pg/errors.py ADDED
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class ConfigurationError(Exception):
5
+ pass
stream2pg/sink.py ADDED
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Callable, Optional
3
+
4
+ from .config import ErrorStrategy, from_config
5
+ from .core import create_kafka_stream, create_spark_session, process_batch
6
+
7
+
8
+ class Stream2Pg:
9
+ def __init__(
10
+ self,
11
+ config: dict[str, Any],
12
+ on_metrics: Optional[Callable[..., None]] = None,
13
+ ):
14
+ self.config = from_config(config, on_metrics=on_metrics)
15
+ self.on_metrics = on_metrics
16
+
17
+ def run(self) -> None:
18
+ cfg = self.config
19
+
20
+ postgres_cfg = cfg["postgres"]
21
+ kafka_cfg = cfg["kafka"]
22
+ processing_cfg = cfg["processing"]
23
+
24
+ error_strategy_str = processing_cfg.get("error_strategy", "raise")
25
+ error_strategy = ErrorStrategy(error_strategy_str)
26
+
27
+ checkpoint_location = processing_cfg.get(
28
+ "checkpoint_location", "./checkpoints/kafka_to_postgres"
29
+ )
30
+
31
+ spark = create_spark_session()
32
+ spark.sparkContext.setLogLevel("WARN")
33
+
34
+ df = create_kafka_stream(spark, kafka_cfg)
35
+
36
+ def foreach_batch_fn(batch_df, batch_id):
37
+ process_batch(
38
+ batch_df,
39
+ batch_id,
40
+ postgres_cfg,
41
+ error_strategy,
42
+ on_metrics=self.on_metrics,
43
+ )
44
+
45
+ query = (
46
+ df.writeStream.foreachBatch(foreach_batch_fn)
47
+ .option("checkpointLocation", checkpoint_location)
48
+ .start()
49
+ )
50
+ query.awaitTermination()
51
+
52
+
53
+ def run(
54
+ config: dict[str, Any],
55
+ on_metrics: Optional[Callable[..., None]] = None,
56
+ ) -> None:
57
+ sink = Stream2Pg(config, on_metrics=on_metrics)
58
+ sink.run()
@@ -0,0 +1,294 @@
1
+ Metadata-Version: 2.4
2
+ Name: stream2pg
3
+ Version: 0.1.0
4
+ Summary: Kafka to PostgreSQL sink using Spark Structured Streaming
5
+ Author-email: Sahand Akramipour <sahandap@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/shndap/stream2pg
8
+ Project-URL: Documentation, https://github.com/shndap/stream2pg
9
+ Project-URL: Repository, https://github.com/shndap/stream2pg
10
+ Project-URL: Issues, https://github.com/shndap/stream2pg/issues
11
+ Keywords: kafka,spark,postgresql,streaming,etl
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Information Technology
15
+ Classifier: Topic :: Database
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Topic :: System :: Distributed Computing
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: psycopg2-binary>=2.9
27
+ Requires-Dist: pyspark>=3.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest; extra == "dev"
30
+ Requires-Dist: ruff; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ <div align="center">
34
+
35
+ # stream2pg
36
+
37
+ **Automatically stream JSON data from Kafka into PostgreSQL using Spark Structured Streaming.**
38
+
39
+ Create tables. Evolve schemas. Load data.
40
+
41
+ <a href="https://pypi.org/project/stream2pg/">
42
+ <img src="https://img.shields.io/pypi/v/stream2pg.svg" alt="PyPI">
43
+ </a>
44
+ <a href="https://pypi.org/project/stream2pg/">
45
+ <img src="https://img.shields.io/pypi/pyversions/stream2pg.svg" alt="Python">
46
+ </a>
47
+ <a href="LICENSE">
48
+ <img src="https://img.shields.io/github/license/YOUR_USERNAME/stream2pg">
49
+ </a>
50
+
51
+ </div>
52
+
53
+ ---
54
+
55
+ ## Features
56
+
57
+ - 🚀 Kafka → PostgreSQL streaming
58
+ - 🔄 Automatic schema evolution
59
+ - 📦 Spark Structured Streaming
60
+ - 🐘 PostgreSQL integration
61
+ - 📊 Metrics callbacks
62
+ - ⚡ Minimal configuration
63
+
64
+
65
+
66
+ ## How It Works
67
+
68
+ Given Kafka messages like:
69
+
70
+ ```json
71
+ {
72
+ "vehicle_id": 42,
73
+ "speed": 18.7,
74
+ "timestamp": "2025-01-01T12:00:00Z"
75
+ }
76
+ ```
77
+
78
+ `stream2pg` will:
79
+
80
+ 1. Subscribe to matching Kafka topics
81
+ 2. Create PostgreSQL tables automatically
82
+ 3. Infer column types
83
+ 4. Add new columns when unseen fields appear
84
+ 5. Insert records into PostgreSQL
85
+
86
+ No manual DDL required.
87
+
88
+
89
+
90
+ ## Installation
91
+
92
+ ### Development
93
+
94
+ ```bash
95
+ pip install -e .
96
+ ```
97
+
98
+ ### From PyPI
99
+
100
+ ```bash
101
+ pip install stream2pg
102
+ ```
103
+
104
+
105
+
106
+ ## Quick Start
107
+
108
+ ```python
109
+ from stream2pg import Stream2Pg
110
+
111
+ config = {
112
+ "postgres": {
113
+ "host": "localhost",
114
+ "port": 5432,
115
+ "dbname": "mobility",
116
+ "user": "postgres",
117
+ "password": "secret",
118
+ },
119
+ "kafka": {
120
+ "bootstrap_servers": "localhost:9092",
121
+ "subscribe_pattern": "mobility-.*",
122
+ "starting_offsets": "earliest",
123
+ "fail_on_data_loss": "false",
124
+ },
125
+ "processing": {
126
+ "error_strategy": "SKIP_ON_ERROR",
127
+ "checkpoint_location": "./checkpoints/kafka_to_postgres",
128
+ },
129
+ }
130
+
131
+ sink = Stream2Pg(config)
132
+ sink.run()
133
+ ```
134
+
135
+
136
+
137
+ ## Metrics
138
+
139
+ A metrics callback can be provided to observe batch execution.
140
+
141
+ ```python
142
+ def on_metrics(
143
+ batch_id,
144
+ row_count,
145
+ inserted_count,
146
+ skipped_count,
147
+ elapsed_ms,
148
+ ):
149
+ print(
150
+ f"Batch {batch_id}: "
151
+ f"{inserted_count} inserted, "
152
+ f"{skipped_count} skipped "
153
+ f"in {elapsed_ms} ms"
154
+ )
155
+
156
+ sink = Stream2Pg(config, on_metrics=on_metrics)
157
+ sink.run()
158
+ ```
159
+
160
+
161
+
162
+ ## Functional API
163
+
164
+ If you prefer not to instantiate the class directly:
165
+
166
+ ```python
167
+ from stream2pg import run
168
+
169
+ run(config)
170
+ ```
171
+
172
+
173
+
174
+ ## Configuration
175
+
176
+ ### PostgreSQL
177
+
178
+ ```python
179
+ {
180
+ "host": "localhost",
181
+ "port": 5432,
182
+ "dbname": "mobility",
183
+ "user": "postgres",
184
+ "password": "secret",
185
+ }
186
+ ```
187
+
188
+ ### Kafka
189
+
190
+ ```python
191
+ {
192
+ "bootstrap_servers": "localhost:9092",
193
+ "subscribe_pattern": "mobility-.*",
194
+ "starting_offsets": "earliest",
195
+ "fail_on_data_loss": "false",
196
+ }
197
+ ```
198
+
199
+ ### Processing
200
+
201
+ ```python
202
+ {
203
+ "error_strategy": "SKIP_ON_ERROR",
204
+ "checkpoint_location": "./checkpoints/kafka_to_postgres",
205
+ }
206
+ ```
207
+
208
+
209
+
210
+ ## Error Handling
211
+
212
+ ### `RAISE`
213
+
214
+ Fail the current batch immediately when an error occurs.
215
+
216
+ ```python
217
+ "error_strategy": "RAISE"
218
+ ```
219
+
220
+ ### `SKIP_ON_ERROR`
221
+
222
+ Skip invalid records and continue processing the remaining batch.
223
+
224
+ ```python
225
+ "error_strategy": "SKIP_ON_ERROR"
226
+ ```
227
+
228
+
229
+
230
+ ## API Reference
231
+
232
+ ### `Stream2Pg`
233
+
234
+ ```python
235
+ Stream2Pg(config, on_metrics=None)
236
+ ```
237
+
238
+ Creates a streaming sink instance.
239
+
240
+ Parameters:
241
+
242
+ | Parameter | Description |
243
+ | | - |
244
+ | `config` | Configuration dictionary |
245
+ | `on_metrics` | Optional metrics callback |
246
+
247
+
248
+
249
+ ### `Stream2Pg.run()`
250
+
251
+ Starts the Kafka → PostgreSQL streaming pipeline.
252
+
253
+ ```python
254
+ sink.run()
255
+ ```
256
+
257
+
258
+
259
+ ### `run()`
260
+
261
+ Convenience wrapper around `Stream2Pg`.
262
+
263
+ ```python
264
+ from stream2pg import run
265
+
266
+ run(config)
267
+ ```
268
+
269
+
270
+
271
+ ### Exceptions
272
+
273
+ #### `ConfigurationError`
274
+
275
+ Raised when the provided configuration is invalid.
276
+
277
+ ```python
278
+ from stream2pg.errors import ConfigurationError
279
+ ```
280
+
281
+
282
+
283
+ ## Requirements
284
+
285
+ * Python 3.9+
286
+ * Apache Spark
287
+ * Kafka
288
+ * PostgreSQL
289
+
290
+
291
+
292
+ ## License
293
+
294
+ [MIT](./LICENSE)
@@ -0,0 +1,11 @@
1
+ stream2pg/__init__.py,sha256=ZkQc0w7vhOdFPYjh6dAs-ch6Sgbwcd-BD2bzR2d_TKc,98
2
+ stream2pg/config.py,sha256=YupmwD8aAPmckp2joj2-pINLRMt-_p1t_7m0jXxQadk,755
3
+ stream2pg/core.py,sha256=crxuiWuNZbn6YamL6ST-eChbyOoUHHocS1otI7ZeVj4,3292
4
+ stream2pg/db.py,sha256=PZlcXlws23DmsLMgMLf5niLjtbYO_u4cy-PGQnTFPGI,2475
5
+ stream2pg/errors.py,sha256=rlRy0gR3wUULpMwLN4T0K2XEz0fA9e1yBQyI4XDukFE,83
6
+ stream2pg/sink.py,sha256=q8YbyZ6HfRbz_ukKcuDZHRxLpgq08CR5LswaLjQAMag,1650
7
+ stream2pg-0.1.0.dist-info/licenses/LICENSE,sha256=fc2MP3yg9KGEIFxFo8vDYQlRKACFnEnaRmHT03OJsFo,1074
8
+ stream2pg-0.1.0.dist-info/METADATA,sha256=skvzVqyaErQbTSwC6iQj3A-KcG7M75xQ_z4sQHRpYfs,5473
9
+ stream2pg-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ stream2pg-0.1.0.dist-info/top_level.txt,sha256=aVAVSZVoY2i4p2og17v4kHHb-Dy2nSroV0ana5_q4xQ,10
11
+ stream2pg-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sahand Akramipour
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
+ stream2pg