stream2pg 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 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,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,262 @@
1
+ <div align="center">
2
+
3
+ # stream2pg
4
+
5
+ **Automatically stream JSON data from Kafka into PostgreSQL using Spark Structured Streaming.**
6
+
7
+ Create tables. Evolve schemas. Load data.
8
+
9
+ <a href="https://pypi.org/project/stream2pg/">
10
+ <img src="https://img.shields.io/pypi/v/stream2pg.svg" alt="PyPI">
11
+ </a>
12
+ <a href="https://pypi.org/project/stream2pg/">
13
+ <img src="https://img.shields.io/pypi/pyversions/stream2pg.svg" alt="Python">
14
+ </a>
15
+ <a href="LICENSE">
16
+ <img src="https://img.shields.io/github/license/YOUR_USERNAME/stream2pg">
17
+ </a>
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ ## Features
24
+
25
+ - 🚀 Kafka → PostgreSQL streaming
26
+ - 🔄 Automatic schema evolution
27
+ - 📦 Spark Structured Streaming
28
+ - 🐘 PostgreSQL integration
29
+ - 📊 Metrics callbacks
30
+ - ⚡ Minimal configuration
31
+
32
+
33
+
34
+ ## How It Works
35
+
36
+ Given Kafka messages like:
37
+
38
+ ```json
39
+ {
40
+ "vehicle_id": 42,
41
+ "speed": 18.7,
42
+ "timestamp": "2025-01-01T12:00:00Z"
43
+ }
44
+ ```
45
+
46
+ `stream2pg` will:
47
+
48
+ 1. Subscribe to matching Kafka topics
49
+ 2. Create PostgreSQL tables automatically
50
+ 3. Infer column types
51
+ 4. Add new columns when unseen fields appear
52
+ 5. Insert records into PostgreSQL
53
+
54
+ No manual DDL required.
55
+
56
+
57
+
58
+ ## Installation
59
+
60
+ ### Development
61
+
62
+ ```bash
63
+ pip install -e .
64
+ ```
65
+
66
+ ### From PyPI
67
+
68
+ ```bash
69
+ pip install stream2pg
70
+ ```
71
+
72
+
73
+
74
+ ## Quick Start
75
+
76
+ ```python
77
+ from stream2pg import Stream2Pg
78
+
79
+ config = {
80
+ "postgres": {
81
+ "host": "localhost",
82
+ "port": 5432,
83
+ "dbname": "mobility",
84
+ "user": "postgres",
85
+ "password": "secret",
86
+ },
87
+ "kafka": {
88
+ "bootstrap_servers": "localhost:9092",
89
+ "subscribe_pattern": "mobility-.*",
90
+ "starting_offsets": "earliest",
91
+ "fail_on_data_loss": "false",
92
+ },
93
+ "processing": {
94
+ "error_strategy": "SKIP_ON_ERROR",
95
+ "checkpoint_location": "./checkpoints/kafka_to_postgres",
96
+ },
97
+ }
98
+
99
+ sink = Stream2Pg(config)
100
+ sink.run()
101
+ ```
102
+
103
+
104
+
105
+ ## Metrics
106
+
107
+ A metrics callback can be provided to observe batch execution.
108
+
109
+ ```python
110
+ def on_metrics(
111
+ batch_id,
112
+ row_count,
113
+ inserted_count,
114
+ skipped_count,
115
+ elapsed_ms,
116
+ ):
117
+ print(
118
+ f"Batch {batch_id}: "
119
+ f"{inserted_count} inserted, "
120
+ f"{skipped_count} skipped "
121
+ f"in {elapsed_ms} ms"
122
+ )
123
+
124
+ sink = Stream2Pg(config, on_metrics=on_metrics)
125
+ sink.run()
126
+ ```
127
+
128
+
129
+
130
+ ## Functional API
131
+
132
+ If you prefer not to instantiate the class directly:
133
+
134
+ ```python
135
+ from stream2pg import run
136
+
137
+ run(config)
138
+ ```
139
+
140
+
141
+
142
+ ## Configuration
143
+
144
+ ### PostgreSQL
145
+
146
+ ```python
147
+ {
148
+ "host": "localhost",
149
+ "port": 5432,
150
+ "dbname": "mobility",
151
+ "user": "postgres",
152
+ "password": "secret",
153
+ }
154
+ ```
155
+
156
+ ### Kafka
157
+
158
+ ```python
159
+ {
160
+ "bootstrap_servers": "localhost:9092",
161
+ "subscribe_pattern": "mobility-.*",
162
+ "starting_offsets": "earliest",
163
+ "fail_on_data_loss": "false",
164
+ }
165
+ ```
166
+
167
+ ### Processing
168
+
169
+ ```python
170
+ {
171
+ "error_strategy": "SKIP_ON_ERROR",
172
+ "checkpoint_location": "./checkpoints/kafka_to_postgres",
173
+ }
174
+ ```
175
+
176
+
177
+
178
+ ## Error Handling
179
+
180
+ ### `RAISE`
181
+
182
+ Fail the current batch immediately when an error occurs.
183
+
184
+ ```python
185
+ "error_strategy": "RAISE"
186
+ ```
187
+
188
+ ### `SKIP_ON_ERROR`
189
+
190
+ Skip invalid records and continue processing the remaining batch.
191
+
192
+ ```python
193
+ "error_strategy": "SKIP_ON_ERROR"
194
+ ```
195
+
196
+
197
+
198
+ ## API Reference
199
+
200
+ ### `Stream2Pg`
201
+
202
+ ```python
203
+ Stream2Pg(config, on_metrics=None)
204
+ ```
205
+
206
+ Creates a streaming sink instance.
207
+
208
+ Parameters:
209
+
210
+ | Parameter | Description |
211
+ | | - |
212
+ | `config` | Configuration dictionary |
213
+ | `on_metrics` | Optional metrics callback |
214
+
215
+
216
+
217
+ ### `Stream2Pg.run()`
218
+
219
+ Starts the Kafka → PostgreSQL streaming pipeline.
220
+
221
+ ```python
222
+ sink.run()
223
+ ```
224
+
225
+
226
+
227
+ ### `run()`
228
+
229
+ Convenience wrapper around `Stream2Pg`.
230
+
231
+ ```python
232
+ from stream2pg import run
233
+
234
+ run(config)
235
+ ```
236
+
237
+
238
+
239
+ ### Exceptions
240
+
241
+ #### `ConfigurationError`
242
+
243
+ Raised when the provided configuration is invalid.
244
+
245
+ ```python
246
+ from stream2pg.errors import ConfigurationError
247
+ ```
248
+
249
+
250
+
251
+ ## Requirements
252
+
253
+ * Python 3.9+
254
+ * Apache Spark
255
+ * Kafka
256
+ * PostgreSQL
257
+
258
+
259
+
260
+ ## License
261
+
262
+ [MIT](./LICENSE)
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "stream2pg"
7
+ version = "0.1.0"
8
+ description = "Kafka to PostgreSQL sink using Spark Structured Streaming"
9
+ readme = {file = "README.md", content-type = "text/markdown"}
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [
14
+ {name = "Sahand Akramipour", email = "sahandap@gmail.com"},
15
+ ]
16
+ keywords = ["kafka", "spark", "postgresql", "streaming", "etl"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: Information Technology",
22
+
23
+ "Topic :: Database",
24
+ "Topic :: Software Development :: Libraries",
25
+ "Topic :: System :: Distributed Computing",
26
+
27
+ "Programming Language :: Python :: 3",
28
+ "Programming Language :: Python :: 3.9",
29
+ "Programming Language :: Python :: 3.10",
30
+ "Programming Language :: Python :: 3.11",
31
+ "Programming Language :: Python :: 3.12",
32
+ ]
33
+ dependencies = [
34
+ "psycopg2-binary>=2.9",
35
+ "pyspark>=3.0",
36
+ ]
37
+
38
+ [project.optional-dependencies]
39
+ dev = [
40
+ "pytest",
41
+ "ruff",
42
+ ]
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/shndap/stream2pg"
46
+ Documentation = "https://github.com/shndap/stream2pg"
47
+ Repository = "https://github.com/shndap/stream2pg"
48
+ Issues = "https://github.com/shndap/stream2pg/issues"
49
+
50
+ [tool.setuptools.packages.find]
51
+ where = ["src"]
52
+
53
+ [tool.setuptools.package-dir]
54
+ "" = "src"
55
+
56
+ [tool.pytest.ini_options]
57
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from stream2pg.sink import Stream2Pg
4
+
5
+ __all__ = ["Stream2Pg"]
@@ -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
+ }
@@ -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
@@ -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
+ )
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class ConfigurationError(Exception):
5
+ pass
@@ -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,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/stream2pg/__init__.py
5
+ src/stream2pg/config.py
6
+ src/stream2pg/core.py
7
+ src/stream2pg/db.py
8
+ src/stream2pg/errors.py
9
+ src/stream2pg/sink.py
10
+ src/stream2pg.egg-info/PKG-INFO
11
+ src/stream2pg.egg-info/SOURCES.txt
12
+ src/stream2pg.egg-info/dependency_links.txt
13
+ src/stream2pg.egg-info/requires.txt
14
+ src/stream2pg.egg-info/top_level.txt
15
+ tests/test_config.py
16
+ tests/test_db.py
@@ -0,0 +1,6 @@
1
+ psycopg2-binary>=2.9
2
+ pyspark>=3.0
3
+
4
+ [dev]
5
+ pytest
6
+ ruff
@@ -0,0 +1 @@
1
+ stream2pg
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+ from stream2pg.config import ErrorStrategy, from_config
5
+ from stream2pg.errors import ConfigurationError
6
+
7
+
8
+ class TestFromConfig:
9
+ def test_raises_on_missing_postgres_key(self):
10
+ config = {
11
+ "kafka": {"bootstrap_servers": "localhost:9092"},
12
+ "processing": {"error_strategy": "raise"},
13
+ }
14
+ with pytest.raises(ConfigurationError) as exc_info:
15
+ from_config(config)
16
+ assert "postgres" in str(exc_info.value)
17
+
18
+ def test_raises_on_missing_kafka_key(self):
19
+ config = {
20
+ "postgres": {"host": "localhost"},
21
+ "processing": {"error_strategy": "raise"},
22
+ }
23
+ with pytest.raises(ConfigurationError) as exc_info:
24
+ from_config(config)
25
+ assert "kafka" in str(exc_info.value)
26
+
27
+ def test_raises_on_missing_processing_key(self):
28
+ config = {
29
+ "postgres": {"host": "localhost"},
30
+ "kafka": {"bootstrap_servers": "localhost:9092"},
31
+ }
32
+ with pytest.raises(ConfigurationError) as exc_info:
33
+ from_config(config)
34
+ assert "processing" in str(exc_info.value)
35
+
36
+ def test_returns_config_with_on_metrics(self):
37
+ config = {
38
+ "postgres": {"host": "localhost"},
39
+ "kafka": {"bootstrap_servers": "localhost:9092"},
40
+ "processing": {"error_strategy": "raise"},
41
+ }
42
+ on_metrics = lambda *args: None
43
+ result = from_config(config, on_metrics=on_metrics)
44
+ assert result["postgres"] == config["postgres"]
45
+ assert result["kafka"] == config["kafka"]
46
+ assert result["processing"] == config["processing"]
47
+ assert result["on_metrics"] == on_metrics
48
+
49
+
50
+ class TestErrorStrategy:
51
+ def test_raise_value(self):
52
+ assert ErrorStrategy.RAISE.value == "raise"
53
+
54
+ def test_skip_on_error_value(self):
55
+ assert ErrorStrategy.SKIP_ON_ERROR.value == "skip_on_error"
56
+
57
+ def test_from_str(self):
58
+ assert ErrorStrategy("raise") == ErrorStrategy.RAISE
59
+ assert ErrorStrategy("skip_on_error") == ErrorStrategy.SKIP_ON_ERROR
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+
5
+ import pytest
6
+ from stream2pg.db import convert_value, infer_sql_type
7
+
8
+
9
+ class TestInferSqlType:
10
+ def test_boolean(self):
11
+ assert infer_sql_type(True) == "BOOLEAN"
12
+ assert infer_sql_type(False) == "BOOLEAN"
13
+
14
+ def test_integer(self):
15
+ assert infer_sql_type(42) == "BIGINT"
16
+ assert infer_sql_type(-1) == "BIGINT"
17
+
18
+ def test_float(self):
19
+ assert infer_sql_type(3.14) == "DOUBLE PRECISION"
20
+
21
+ def test_string_timestamp(self):
22
+ assert infer_sql_type("2024-01-01T00:00:00") == "TIMESTAMP"
23
+ assert infer_sql_type("2024-01-01T00:00:00Z") == "TIMESTAMP"
24
+
25
+ def test_string_text(self):
26
+ assert infer_sql_type("hello") == "TEXT"
27
+ assert infer_sql_type("not a date") == "TEXT"
28
+
29
+ def test_none(self):
30
+ assert infer_sql_type(None) == "TEXT"
31
+
32
+
33
+ class TestConvertValue:
34
+ def test_string_timestamp_with_z(self):
35
+ result = convert_value("2024-01-01T00:00:00Z")
36
+ assert isinstance(result, datetime)
37
+
38
+ def test_string_timestamp_with_offset(self):
39
+ result = convert_value("2024-01-01T00:00:00+00:00")
40
+ assert isinstance(result, datetime)
41
+
42
+ def test_string_regular(self):
43
+ result = convert_value("hello")
44
+ assert result == "hello"
45
+
46
+ def test_non_string(self):
47
+ assert convert_value(42) == 42
48
+ assert convert_value(3.14) == 3.14
49
+ assert convert_value(True) is True