Skip to content

Postgress Connector API Reference

PostgreSQLOperation

PostgreSQLOperation handles PostgreSQL database operations safely with retries, context-managed cursors, table creation, and CRUD operations with proper logging.

Attributes:

Name Type Description
postgres_config PostgresDBConfig

Configuration object containing PostgreSQL connection details.

Examples:

>>> from src.entity.config_entity import PostgresDBConfig
>>> config = PostgresDBConfig()
>>> db_client = PostgreSQLOperation(config)
>>> db_client.create_table()
>>> article = {
...     "title": "Sample Article",
...     "author": "John Doe",
...     "source": "BBC",
...     "published_date": "2025-09-27T10:00:00Z",
...     "scraped_date": "2025-09-27T11:00:00Z",
...     "summary": "This is a summary",
...     "content": "Full content here",
...     "url": "https://example.com/article1",
...     "category": "News"
... }
>>> db_client.insert_article(article)
>>> db_client.table_exists()
True
Source code in src/clients/postgress_connector.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
class PostgreSQLOperation:
    """
    PostgreSQLOperation handles PostgreSQL database operations safely with retries, context-managed cursors,
    table creation, and CRUD operations with proper logging.

    Attributes
    ----------
    postgres_config : PostgresDBConfig
        Configuration object containing PostgreSQL connection details.

    Examples
    --------
    >>> from src.entity.config_entity import PostgresDBConfig
    >>> config = PostgresDBConfig()
    >>> db_client = PostgreSQLOperation(config)
    >>> db_client.create_table()
    >>> article = {
    ...     "title": "Sample Article",
    ...     "author": "John Doe",
    ...     "source": "BBC",
    ...     "published_date": "2025-09-27T10:00:00Z",
    ...     "scraped_date": "2025-09-27T11:00:00Z",
    ...     "summary": "This is a summary",
    ...     "content": "Full content here",
    ...     "url": "https://example.com/article1",
    ...     "category": "News"
    ... }
    >>> db_client.insert_article(article)
    >>> db_client.table_exists()
    True
    """
    def __init__(self, postgres_config: PostgresDBConfig):
        """
        Initialize PostgreSQLOperation with configuration.

        Parameters
        ----------
        postgres_config : PostgresDBConfig
            Contains all necessary DB connection info like host, port, user, password, and table name.
        """
        self.postgres_config = postgres_config

    @retry(wait=wait_fixed(2), stop=stop_after_attempt(5))
    def get_connection(self):
        """
        Establish a connection to PostgreSQL with retry logic.

        Returns
        -------
        connection : psycopg2.extensions.connection
            Active connection object.

        Raises
        ------
        psycopg2.OperationalError
            If connection cannot be established after retries.

        Examples
        --------
        >>> conn = db_client.get_connection()
        >>> conn.closed
        0
        """
        return psycopg2.connect(
            dbname=self.postgres_config.POSTGRES_DATABASE_NAME,
            user=self.postgres_config.POSTGRES_USER,
            password=self.postgres_config.POSTGRES_PASSWORD,
            host=self.postgres_config.POSTGRES_HOST,
            port=self.postgres_config.POSTGRES_PORT
        )

    @contextmanager
    def connection_cursor(self):
        """
        Context manager for PostgreSQL connection and cursor.

        Ensures commit on success and rollback on failure.

        Yields
        ------
        conn : psycopg2.extensions.connection
        cursor : psycopg2.extensions.cursor

        Raises
        ------
        Exception
            Any exception during DB operation is propagated after rollback.

        Examples
        --------
        >>> with db_client.connection_cursor() as (conn, cursor):
        ...     cursor.execute("SELECT 1;")
        ...     cursor.fetchone()
        (1,)
        """
        start_time = time.perf_counter()
        conn = self.get_connection()
        cursor = conn.cursor()
        try:
            yield conn, cursor
            conn.commit()
        except Exception as e:
            conn.rollback()
            logger.error(
                "Database operation failed",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "stack_trace": str(e),
                    "duration_ms": calculate_duration(start_time),
                }
            )
            raise
        finally:
            cursor.close()
            conn.close()

    def table_exists(self) -> bool:
        """
        Check if the target table exists in the 'public' schema.

        Returns
        -------
        exists : bool
            True if table exists, False otherwise.

        Raises
        ------
        CustomException
            If the check fails due to a DB error.

        Examples
        --------
        >>> db_client.table_exists()
        True
        """
        check_query = """
        SELECT EXISTS (
            SELECT FROM information_schema.tables
            WHERE table_schema = 'public' AND table_name = %s
        );
        """
        start_time = time.perf_counter()
        with self.connection_cursor() as (_, cursor):
            try:
                cursor.execute(check_query, (self.postgres_config.POSTGRES_TABLE_NAME,))
                exists = cursor.fetchone()[0]
                logger.info(
                    f"Table '{self.postgres_config.POSTGRES_TABLE_NAME}' exists: {exists}",
                    extra={
                        "service": service_name,
                        "host": self.postgres_config.POSTGRES_HOST,
                        "duration_ms": calculate_duration(start_time),
                    }
                )
                return exists
            except Exception as e:
                logger.error(
                    "Failed to check if table exists",
                    extra={
                        "service": service_name,
                        "host": self.postgres_config.POSTGRES_HOST,
                        "stack_trace": str(e),
                        "duration_ms": calculate_duration(start_time),
                    }
                )
                raise CustomException("Table existence check failed", e)

    def create_table(self):
        """
        Create the main articles table if it does not exist.

        Table structure:
        - id : SERIAL PRIMARY KEY
        - title : TEXT NOT NULL
        - author : TEXT
        - source : TEXT
        - publish_date : TIMESTAMP
        - scraped_date : TIMESTAMP
        - summary : TEXT
        - content : TEXT
        - url : TEXT UNIQUE NOT NULL
        - category : TEXT
        - created_at : TIMESTAMP DEFAULT CURRENT_TIMESTAMP

        Raises
        ------
        psycopg2.Error
            If table creation fails.

        Examples
        --------
        >>> db_client.create_table()
        Table 'articles' ensured to exist.
        """

        start_time = time.perf_counter()
        create_table_query = sql.SQL("""
        CREATE TABLE IF NOT EXISTS {table} (
            id SERIAL PRIMARY KEY,
            title TEXT NOT NULL,
            author TEXT,
            source TEXT,
            publish_date TIMESTAMP,
            scraped_date TIMESTAMP,
            summary TEXT,
            content TEXT,
            url TEXT UNIQUE NOT NULL,
            category TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
        """).format(
                table=sql.Identifier(self.postgres_config.POSTGRES_TABLE_NAME)
            )
        with self.connection_cursor() as (_, cursor):
            cursor.execute(create_table_query)
            logger.info(
                f"Table {self.postgres_config.POSTGRES_TABLE_NAME} ensured to exist.",
                extra={
                        "service": service_name,
                        "host": self.postgres_config.POSTGRES_HOST,
                        "duration_ms": calculate_duration(start_time),
                    }
                )

    def insert_article(self, article_data: Dict):
        """
        Insert an article into the database.

        Uses `ON CONFLICT (url) DO NOTHING` to avoid duplicates.

        Parameters
        ----------
        article_data : dict
            Dictionary containing keys:
            'title', 'author', 'source', 'published_date', 'scraped_date',
            'summary', 'content', 'url', 'category'

        Raises
        ------
        CustomException
            If insertion fails.

        Examples
        --------
        >>> article = {
        ...     "title": "Test",
        ...     "author": "Alice",
        ...     "source": "BBC",
        ...     "published_date": "2025-09-27T10:00:00Z",
        ...     "scraped_date": "2025-09-27T11:00:00Z",
        ...     "summary": "Test summary",
        ...     "content": "Full content",
        ...     "url": "https://example.com/test",
        ...     "category": "News"
        ... }
        >>> db_client.insert_article(article)
        Article inserted: https://example.com/test
        """

        start_time = time.perf_counter()
        insert_query = sql.SQL("""
        INSERT INTO {table}
        (title, author, source, publish_date, scraped_date, summary, content, url, category)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        ON CONFLICT (url) DO NOTHING
        """).format(
                table=sql.Identifier(self.postgres_config.POSTGRES_TABLE_NAME)
            )
        try:
            values = (
                article_data.get("title"),
                article_data.get("author"),
                article_data.get("source"),
                self._parse_date(article_data.get("published_date")),
                self._parse_date(article_data.get("scraped_date")),
                article_data.get("summary"),
                article_data.get("content"),
                article_data.get("url"),
                article_data.get("category"),
            )
            with self.connection_cursor() as (_, cursor):
                cursor.execute(insert_query, values)
                logger.info(
                    f"Article inserted: {article_data.get('url')}",
                    extra={
                        "service": service_name,
                        "host": self.postgres_config.POSTGRES_HOST,
                        "duration_ms": calculate_duration(start_time),
                    }
                )
        except Exception as e:
            logger.error(
                "Failed to insert article",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "stack_trace": str(e),
                    "duration_ms": calculate_duration(start_time),
                }
            )
            raise CustomException("Article insert failed", e)

    def _parse_date(self, date_str):
        """
        Parse ISO 8601 datetime string to Python datetime object.

        Parameters
        ----------
        date_str : str
            Datetime string, e.g. '2025-09-27T10:00:00Z'

        Returns
        -------
        datetime or None
            Parsed datetime object or None if invalid or empty.

        Examples
        --------
        >>> db_client._parse_date("2025-09-27T10:00:00Z")
        datetime.datetime(2025, 9, 27, 10, 0, tzinfo=datetime.timezone.utc)
        >>> db_client._parse_date(None)
        None
        """

        start_time = time.perf_counter()
        if not date_str:
            return None
        try:
            return datetime.fromisoformat(date_str.replace("Z", "+00:00"))
        except ValueError as e:
            logger.warning(
                "Invalid datetime format",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "stack_trace": str(e),
                    "duration_ms": calculate_duration(start_time),
                }
            )
            return None

    def create_test_table(self):
        start_time = time.perf_counter()
        create_table_query = ("""
        CREATE TABLE IF NOT EXISTS {table} (
            id SERIAL PRIMARY KEY,
            url TEXT UNIQUE NOT NULL,
        );
        """).format(
            table = sql.Identifier(self.postgres_config.POSTGRES_TABLE_NAME)
        )
        with self.connection_cursor() as (_, cursor):
            cursor.execute(create_table_query)
            logger.info(
                f"Table {self.postgres_config.POSTGRES_TABLE_NAME} ensured to exist.",
                extra={
                        "service": service_name,
                        "host": self.postgres_config.POSTGRES_HOST,
                        "duration_ms": calculate_duration(start_time),
                }
            )


    def insert_test_article(self, article_data: Dict):
        start_time = time.perf_counter()
        insert_query = sql.SQL("""
        INSERT INTO {table}
        (id, url)
        VALUES (%s, %s)
        ON CONFLICT (url) DO NOTHING
        """).format(
            table=sql.Identifier(self.postgres_config.POSTGRES_TABLE_NAME)
            )
        try:
            values = (
                article_data.get("task_id"),
                article_data.get("url"),
            )
            with self.connection_cursor() as (_, cursor):
                cursor.execute(insert_query, values)
                logger.info(
                    f"Article inserted: {article_data.get('url')}",
                    extra={
                        "service": service_name,
                        "host": self.postgres_config.POSTGRES_HOST,
                        "duration_ms": calculate_duration(start_time),
                }
            )
        except Exception as e:
            logger.error(
                "Failed to insert article",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "stack_trace": str(e),
                    "duration_ms": calculate_duration(start_time),
                }
            )
            raise CustomException("Article insert failed", e)

__init__(postgres_config)

Initialize PostgreSQLOperation with configuration.

Parameters:

Name Type Description Default
postgres_config PostgresDBConfig

Contains all necessary DB connection info like host, port, user, password, and table name.

required
Source code in src/clients/postgress_connector.py
50
51
52
53
54
55
56
57
58
59
def __init__(self, postgres_config: PostgresDBConfig):
    """
    Initialize PostgreSQLOperation with configuration.

    Parameters
    ----------
    postgres_config : PostgresDBConfig
        Contains all necessary DB connection info like host, port, user, password, and table name.
    """
    self.postgres_config = postgres_config

connection_cursor()

Context manager for PostgreSQL connection and cursor.

Ensures commit on success and rollback on failure.

Yields:

Name Type Description
conn connection
cursor cursor

Raises:

Type Description
Exception

Any exception during DB operation is propagated after rollback.

Examples:

>>> with db_client.connection_cursor() as (conn, cursor):
...     cursor.execute("SELECT 1;")
...     cursor.fetchone()
(1,)
Source code in src/clients/postgress_connector.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@contextmanager
def connection_cursor(self):
    """
    Context manager for PostgreSQL connection and cursor.

    Ensures commit on success and rollback on failure.

    Yields
    ------
    conn : psycopg2.extensions.connection
    cursor : psycopg2.extensions.cursor

    Raises
    ------
    Exception
        Any exception during DB operation is propagated after rollback.

    Examples
    --------
    >>> with db_client.connection_cursor() as (conn, cursor):
    ...     cursor.execute("SELECT 1;")
    ...     cursor.fetchone()
    (1,)
    """
    start_time = time.perf_counter()
    conn = self.get_connection()
    cursor = conn.cursor()
    try:
        yield conn, cursor
        conn.commit()
    except Exception as e:
        conn.rollback()
        logger.error(
            "Database operation failed",
            extra={
                "service": service_name,
                "host": self.postgres_config.POSTGRES_HOST,
                "stack_trace": str(e),
                "duration_ms": calculate_duration(start_time),
            }
        )
        raise
    finally:
        cursor.close()
        conn.close()

create_table()

Create the main articles table if it does not exist.

Table structure: - id : SERIAL PRIMARY KEY - title : TEXT NOT NULL - author : TEXT - source : TEXT - publish_date : TIMESTAMP - scraped_date : TIMESTAMP - summary : TEXT - content : TEXT - url : TEXT UNIQUE NOT NULL - category : TEXT - created_at : TIMESTAMP DEFAULT CURRENT_TIMESTAMP

Raises:

Type Description
Error

If table creation fails.

Examples:

>>> db_client.create_table()
Table 'articles' ensured to exist.
Source code in src/clients/postgress_connector.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def create_table(self):
    """
    Create the main articles table if it does not exist.

    Table structure:
    - id : SERIAL PRIMARY KEY
    - title : TEXT NOT NULL
    - author : TEXT
    - source : TEXT
    - publish_date : TIMESTAMP
    - scraped_date : TIMESTAMP
    - summary : TEXT
    - content : TEXT
    - url : TEXT UNIQUE NOT NULL
    - category : TEXT
    - created_at : TIMESTAMP DEFAULT CURRENT_TIMESTAMP

    Raises
    ------
    psycopg2.Error
        If table creation fails.

    Examples
    --------
    >>> db_client.create_table()
    Table 'articles' ensured to exist.
    """

    start_time = time.perf_counter()
    create_table_query = sql.SQL("""
    CREATE TABLE IF NOT EXISTS {table} (
        id SERIAL PRIMARY KEY,
        title TEXT NOT NULL,
        author TEXT,
        source TEXT,
        publish_date TIMESTAMP,
        scraped_date TIMESTAMP,
        summary TEXT,
        content TEXT,
        url TEXT UNIQUE NOT NULL,
        category TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    """).format(
            table=sql.Identifier(self.postgres_config.POSTGRES_TABLE_NAME)
        )
    with self.connection_cursor() as (_, cursor):
        cursor.execute(create_table_query)
        logger.info(
            f"Table {self.postgres_config.POSTGRES_TABLE_NAME} ensured to exist.",
            extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "duration_ms": calculate_duration(start_time),
                }
            )

get_connection()

Establish a connection to PostgreSQL with retry logic.

Returns:

Name Type Description
connection connection

Active connection object.

Raises:

Type Description
OperationalError

If connection cannot be established after retries.

Examples:

>>> conn = db_client.get_connection()
>>> conn.closed
0
Source code in src/clients/postgress_connector.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@retry(wait=wait_fixed(2), stop=stop_after_attempt(5))
def get_connection(self):
    """
    Establish a connection to PostgreSQL with retry logic.

    Returns
    -------
    connection : psycopg2.extensions.connection
        Active connection object.

    Raises
    ------
    psycopg2.OperationalError
        If connection cannot be established after retries.

    Examples
    --------
    >>> conn = db_client.get_connection()
    >>> conn.closed
    0
    """
    return psycopg2.connect(
        dbname=self.postgres_config.POSTGRES_DATABASE_NAME,
        user=self.postgres_config.POSTGRES_USER,
        password=self.postgres_config.POSTGRES_PASSWORD,
        host=self.postgres_config.POSTGRES_HOST,
        port=self.postgres_config.POSTGRES_PORT
    )

insert_article(article_data)

Insert an article into the database.

Uses ON CONFLICT (url) DO NOTHING to avoid duplicates.

Parameters:

Name Type Description Default
article_data dict

Dictionary containing keys: 'title', 'author', 'source', 'published_date', 'scraped_date', 'summary', 'content', 'url', 'category'

required

Raises:

Type Description
CustomException

If insertion fails.

Examples:

>>> article = {
...     "title": "Test",
...     "author": "Alice",
...     "source": "BBC",
...     "published_date": "2025-09-27T10:00:00Z",
...     "scraped_date": "2025-09-27T11:00:00Z",
...     "summary": "Test summary",
...     "content": "Full content",
...     "url": "https://example.com/test",
...     "category": "News"
... }
>>> db_client.insert_article(article)
Article inserted: https://example.com/test
Source code in src/clients/postgress_connector.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def insert_article(self, article_data: Dict):
    """
    Insert an article into the database.

    Uses `ON CONFLICT (url) DO NOTHING` to avoid duplicates.

    Parameters
    ----------
    article_data : dict
        Dictionary containing keys:
        'title', 'author', 'source', 'published_date', 'scraped_date',
        'summary', 'content', 'url', 'category'

    Raises
    ------
    CustomException
        If insertion fails.

    Examples
    --------
    >>> article = {
    ...     "title": "Test",
    ...     "author": "Alice",
    ...     "source": "BBC",
    ...     "published_date": "2025-09-27T10:00:00Z",
    ...     "scraped_date": "2025-09-27T11:00:00Z",
    ...     "summary": "Test summary",
    ...     "content": "Full content",
    ...     "url": "https://example.com/test",
    ...     "category": "News"
    ... }
    >>> db_client.insert_article(article)
    Article inserted: https://example.com/test
    """

    start_time = time.perf_counter()
    insert_query = sql.SQL("""
    INSERT INTO {table}
    (title, author, source, publish_date, scraped_date, summary, content, url, category)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
    ON CONFLICT (url) DO NOTHING
    """).format(
            table=sql.Identifier(self.postgres_config.POSTGRES_TABLE_NAME)
        )
    try:
        values = (
            article_data.get("title"),
            article_data.get("author"),
            article_data.get("source"),
            self._parse_date(article_data.get("published_date")),
            self._parse_date(article_data.get("scraped_date")),
            article_data.get("summary"),
            article_data.get("content"),
            article_data.get("url"),
            article_data.get("category"),
        )
        with self.connection_cursor() as (_, cursor):
            cursor.execute(insert_query, values)
            logger.info(
                f"Article inserted: {article_data.get('url')}",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "duration_ms": calculate_duration(start_time),
                }
            )
    except Exception as e:
        logger.error(
            "Failed to insert article",
            extra={
                "service": service_name,
                "host": self.postgres_config.POSTGRES_HOST,
                "stack_trace": str(e),
                "duration_ms": calculate_duration(start_time),
            }
        )
        raise CustomException("Article insert failed", e)

table_exists()

Check if the target table exists in the 'public' schema.

Returns:

Name Type Description
exists bool

True if table exists, False otherwise.

Raises:

Type Description
CustomException

If the check fails due to a DB error.

Examples:

>>> db_client.table_exists()
True
Source code in src/clients/postgress_connector.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def table_exists(self) -> bool:
    """
    Check if the target table exists in the 'public' schema.

    Returns
    -------
    exists : bool
        True if table exists, False otherwise.

    Raises
    ------
    CustomException
        If the check fails due to a DB error.

    Examples
    --------
    >>> db_client.table_exists()
    True
    """
    check_query = """
    SELECT EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_schema = 'public' AND table_name = %s
    );
    """
    start_time = time.perf_counter()
    with self.connection_cursor() as (_, cursor):
        try:
            cursor.execute(check_query, (self.postgres_config.POSTGRES_TABLE_NAME,))
            exists = cursor.fetchone()[0]
            logger.info(
                f"Table '{self.postgres_config.POSTGRES_TABLE_NAME}' exists: {exists}",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "duration_ms": calculate_duration(start_time),
                }
            )
            return exists
        except Exception as e:
            logger.error(
                "Failed to check if table exists",
                extra={
                    "service": service_name,
                    "host": self.postgres_config.POSTGRES_HOST,
                    "stack_trace": str(e),
                    "duration_ms": calculate_duration(start_time),
                }
            )
            raise CustomException("Table existence check failed", e)