File size: 26,829 Bytes
98f6c3a
 
 
 
 
 
 
 
d4b70b5
 
98f6c3a
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
 
 
 
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
 
 
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
 
 
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
 
 
 
d4b70b5
 
98f6c3a
d4b70b5
 
 
 
98f6c3a
 
 
 
 
d4b70b5
 
ac8d4a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4b70b5
 
98f6c3a
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
 
 
98f6c3a
 
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
 
98f6c3a
 
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
 
 
98f6c3a
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
a538f32
ac8d4a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a538f32
 
ac8d4a4
a538f32
ac8d4a4
 
 
 
d4b70b5
98f6c3a
d4b70b5
 
98f6c3a
d4b70b5
 
98f6c3a
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
a538f32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4b70b5
a538f32
d4b70b5
a538f32
 
 
 
 
d4b70b5
a538f32
 
 
ac8d4a4
 
 
 
 
 
 
 
 
a538f32
 
ac8d4a4
 
 
 
 
 
 
 
 
 
 
a538f32
 
ac8d4a4
a538f32
ac8d4a4
 
 
 
a538f32
 
 
 
 
 
 
 
 
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
 
ac8d4a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
d4b70b5
98f6c3a
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
 
 
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
d4b70b5
98f6c3a
 
 
 
d4b70b5
98f6c3a
 
 
 
 
d4b70b5
98f6c3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
"""
Database utility module for HTTP API operations with Turso database.
This module provides functions for interacting with the Turso database using the HTTP API.
"""

import os
import logging
import time
import requests as req
from typing import List, Dict, Any, Optional, Tuple

# Configure logging
logger = logging.getLogger("auth-server")

def get_http_url() -> Tuple[str, str]:
    """
    Get the HTTP URL and auth token for the Turso database.

    Returns:
        Tuple[str, str]: The HTTP URL and auth token.
    """
    # Extract the database URL and auth token
    db_url = os.getenv("TURSO_DATABASE_URL", "")
    auth_token = os.getenv("TURSO_AUTH_TOKEN", "")

    # Convert URL from libsql:// to https://
    if db_url.startswith("libsql://"):
        http_url = db_url.replace("libsql://", "https://")
    else:
        http_url = db_url

    # Ensure the URL doesn't have a trailing slash
    http_url = http_url.rstrip('/')

    return http_url, auth_token

def get_headers(auth_token: str) -> Dict[str, str]:
    """
    Get the headers for the HTTP request.

    Args:
        auth_token (str): The authentication token.

    Returns:
        Dict[str, str]: The headers for the HTTP request.
    """
    return {
        "Authorization": f"Bearer {auth_token}",
        "Content-Type": "application/json"
    }

def execute_query(sql: str, params: List[Dict[str, Any]] = None, operation_id: str = None) -> Dict[str, Any]:
    """
    Execute a SQL query using the HTTP API.

    Args:
        sql (str): The SQL query to execute.
        params (List[Dict[str, Any]], optional): The parameters for the query. Defaults to None.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        Dict[str, Any]: The response from the database.
    """
    if operation_id is None:
        operation_id = f"query_{int(time.time())}"

    # Only log at debug level for routine operations
    logger.debug(f"[{operation_id}] Executing query: {sql}")

    http_url, auth_token = get_http_url()
    headers = get_headers(auth_token)

    # Prepare the query
    query = {
        "requests": [
            {
                "type": "execute",
                "stmt": {
                    "sql": sql,
                    "args": params or []
                }
            },
            {"type": "close"}
        ]
    }

    # Send the request
    try:
        response = req.post(f"{http_url}/v2/pipeline", headers=headers, json=query)
        response.raise_for_status()
        result = response.json()
        logger.debug(f"[{operation_id}] Query executed successfully")
        return result
    except Exception as e:
        logger.error(f"[{operation_id}] Error executing query: {str(e)}")
        raise

def execute_pipeline(pipeline_requests: List[Dict[str, Any]], operation_id: str = None) -> Dict[str, Any]:
    """
    Execute a pipeline of SQL queries using the HTTP API.

    Args:
        pipeline_requests (List[Dict[str, Any]]): The requests to execute.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        Dict[str, Any]: The response from the database.
    """
    if operation_id is None:
        operation_id = f"pipeline_{int(time.time())}"

    logger.debug(f"[{operation_id}] Executing pipeline with {len(pipeline_requests)} requests")

    http_url, auth_token = get_http_url()
    headers = get_headers(auth_token)

    # Prepare the pipeline
    pipeline = {
        "requests": pipeline_requests + [{"type": "close"}]
    }

    # Send the request
    try:
        response = req.post(f"{http_url}/v2/pipeline", headers=headers, json=pipeline)
        response.raise_for_status()
        result = response.json()
        logger.debug(f"[{operation_id}] Pipeline executed successfully")
        return result
    except Exception as e:
        logger.error(f"[{operation_id}] Error executing pipeline: {str(e)}")
        raise

def insert_record(table: str, data: Dict[str, Any], operation_id: str = None) -> Optional[int]:
    """
    Insert a record into a table.

    Args:
        table (str): The table to insert into.
        data (Dict[str, Any]): The data to insert.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        Optional[int]: The ID of the inserted record, or None if the insert failed.
    """
    if operation_id is None:
        operation_id = f"insert_{int(time.time())}"

    logger.debug(f"[{operation_id}] Inserting record into {table}")

    # Prepare the SQL and parameters
    columns = list(data.keys())
    placeholders = ["?"] * len(columns)
    sql = f"INSERT INTO {table} ({', '.join(columns)}) VALUES ({', '.join(placeholders)})"

    params = []
    for key, value in data.items():
        if isinstance(value, str):
            params.append({"type": "text", "value": value})
        elif isinstance(value, int):
            params.append({"type": "integer", "value": str(value)})
        elif isinstance(value, float):
            params.append({"type": "float", "value": str(value)})
        elif value is None:
            params.append({"type": "null", "value": None})
        else:
            params.append({"type": "text", "value": str(value)})

    # Execute the query directly instead of using pipeline
    try:
        # Direct query execution is more reliable
        result = execute_query(sql, params, operation_id)

        # Check for errors
        if "results" in result and len(result["results"]) > 0:
            if result["results"][0]["type"] == "error":
                error_msg = result["results"][0]["error"]["message"]
                logger.error(f"[{operation_id}] Insert error: {error_msg}")
                return None

        # Try to get the last inserted ID with a separate query
        try:
            id_result = execute_query("SELECT last_insert_rowid()", operation_id=f"{operation_id}_get_id")

            last_id = None
            if "results" in id_result and len(id_result["results"]) > 0:
                if id_result["results"][0]["type"] == "ok":
                    response = id_result["results"][0]["response"]
                    if "result" in response and "rows" in response["result"] and len(response["result"]["rows"]) > 0:
                        row = response["result"]["rows"][0]

                        # Get the value safely
                        if len(row) > 0:
                            cell = row[0]
                            if isinstance(cell, dict) and "value" in cell:
                                try:
                                    last_id = int(cell["value"])
                                    logger.info(f"[{operation_id}] Record inserted with ID: {last_id}")
                                    return last_id
                                except (ValueError, TypeError) as e:
                                    logger.warning(f"[{operation_id}] Error converting ID to integer: {str(e)}")
                                    # Try to return the value as is
                                    return cell["value"]
                            else:
                                logger.warning(f"[{operation_id}] Unexpected cell format: {cell}")
                        else:
                            logger.warning(f"[{operation_id}] Empty row in last_insert_rowid result")
        except Exception as e:
            logger.error(f"[{operation_id}] Error getting last insert ID: {str(e)}")

        # If we can't get the ID, try to find it by other means
        logger.warning(f"[{operation_id}] Insert succeeded but couldn't get ID")
        return None
    except Exception as e:
        logger.error(f"[{operation_id}] Error inserting record: {str(e)}")
        return None

def update_record(table: str, data: Dict[str, Any], condition: str, condition_params: List[Dict[str, Any]], operation_id: str = None) -> bool:
    """
    Update a record in a table.

    Args:
        table (str): The table to update.
        data (Dict[str, Any]): The data to update.
        condition (str): The condition for the update (e.g., "id = ?").
        condition_params (List[Dict[str, Any]]): The parameters for the condition.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        bool: True if the update succeeded, False otherwise.
    """
    if operation_id is None:
        operation_id = f"update_{int(time.time())}"

    logger.debug(f"[{operation_id}] Updating record in {table}")

    # Prepare the SQL and parameters
    set_clauses = [f"{key} = ?" for key in data.keys()]
    sql = f"UPDATE {table} SET {', '.join(set_clauses)} WHERE {condition}"

    params = []
    for key, value in data.items():
        if isinstance(value, str):
            params.append({"type": "text", "value": value})
        elif isinstance(value, int):
            params.append({"type": "integer", "value": str(value)})
        elif isinstance(value, float):
            params.append({"type": "float", "value": str(value)})
        elif value is None:
            params.append({"type": "null", "value": None})
        else:
            params.append({"type": "text", "value": str(value)})

    # Add condition parameters
    params.extend(condition_params)

    try:
        result = execute_query(sql, params, operation_id)

        # Check for errors
        if "results" in result and len(result["results"]) > 0:
            if result["results"][0]["type"] == "error":
                error_msg = result["results"][0]["error"]["message"]
                logger.error(f"[{operation_id}] Update error: {error_msg}")
                return False

            # Check affected rows
            affected_rows = result["results"][0]["response"]["result"]["affected_row_count"]
            logger.debug(f"[{operation_id}] Updated {affected_rows} rows")
            return affected_rows > 0

        return False
    except Exception as e:
        logger.error(f"[{operation_id}] Error updating record: {str(e)}")
        return False

def delete_record(table: str, condition: str, condition_params: List[Dict[str, Any]], operation_id: str = None) -> bool:
    """
    Delete a record from a table.

    Args:
        table (str): The table to delete from.
        condition (str): The condition for the delete (e.g., "id = ?").
        condition_params (List[Dict[str, Any]]): The parameters for the condition.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        bool: True if the delete succeeded, False otherwise.
    """
    if operation_id is None:
        operation_id = f"delete_{int(time.time())}"

    logger.info(f"[{operation_id}] Deleting record from {table}")

    # Prepare the SQL
    sql = f"DELETE FROM {table} WHERE {condition}"

    try:
        result = execute_query(sql, condition_params, operation_id)

        # Check for errors
        if "results" in result and len(result["results"]) > 0:
            if result["results"][0]["type"] == "error":
                error_msg = result["results"][0]["error"]["message"]
                logger.error(f"[{operation_id}] Delete error: {error_msg}")
                return False

            # Check affected rows
            affected_rows = result["results"][0]["response"]["result"]["affected_row_count"]
            logger.info(f"[{operation_id}] Deleted {affected_rows} rows")
            return affected_rows > 0

        return False
    except Exception as e:
        logger.error(f"[{operation_id}] Error deleting record: {str(e)}")
        return False

def select_records(table: str, columns: List[str] = None, condition: str = None,
                  condition_params: List[Dict[str, Any]] = None, limit: int = None,
                  offset: int = None, order_by: str = None, operation_id: str = None) -> List[Dict[str, Any]]:
    """
    Select records from a table.

    Args:
        table (str): The table to select from.
        columns (List[str], optional): The columns to select. Defaults to None (all columns).
        condition (str, optional): The condition for the select. Defaults to None.
        condition_params (List[Dict[str, Any]], optional): The parameters for the condition. Defaults to None.
        limit (int, optional): The maximum number of records to return. Defaults to None.
        offset (int, optional): The number of records to skip. Defaults to None.
        order_by (str, optional): The order by clause. Defaults to None.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        List[Dict[str, Any]]: The selected records.
    """
    if operation_id is None:
        operation_id = f"select_{int(time.time())}"

    logger.debug(f"[{operation_id}] Selecting records from {table}")

    # Prepare the SQL
    cols = "*" if not columns else ", ".join(columns)
    sql = f"SELECT {cols} FROM {table}"

    if condition:
        sql += f" WHERE {condition}"

    if order_by:
        sql += f" ORDER BY {order_by}"

    if limit:
        sql += f" LIMIT {limit}"

    if offset:
        sql += f" OFFSET {offset}"

    try:
        result = execute_query(sql, condition_params, operation_id)

        # Check for errors
        if "results" in result and len(result["results"]) > 0:
            if result["results"][0]["type"] == "error":
                error_msg = result["results"][0]["error"]["message"]
                logger.error(f"[{operation_id}] Select error: {error_msg}")
                return []

            # Extract the records
            response = result["results"][0]["response"]
            if "result" in response and "rows" in response["result"]:
                rows = response["result"]["rows"]
                cols = response["result"]["cols"]

                # Convert rows to dictionaries
                records = []
                for row in rows:
                    record = {}
                    for i, col in enumerate(cols):
                        try:
                            # Get column name safely
                            col_name = col.get("name", f"column_{i}")

                            # Get cell data safely
                            cell = row[i] if i < len(row) else {}

                            # Get value and type safely
                            value = cell.get("value") if isinstance(cell, dict) else cell
                            cell_type = cell.get("type") if isinstance(cell, dict) else None

                            # Convert value based on type
                            if cell_type == "integer" and value is not None:
                                try:
                                    value = int(value)
                                except (ValueError, TypeError):
                                    value = 0
                            elif cell_type == "float" and value is not None:
                                try:
                                    value = float(value)
                                except (ValueError, TypeError):
                                    value = 0.0
                            elif cell_type == "null":
                                value = None

                            # Store the value
                            record[col_name] = value
                        except Exception as e:
                            # Handle any errors
                            logger.warning(f"[{operation_id}] Error processing column {i}: {str(e)}")
                            record[f"column_{i}"] = None

                    records.append(record)

                logger.debug(f"[{operation_id}] Selected {len(records)} records")
                return records

        logger.debug(f"[{operation_id}] No records found")
        return []
    except Exception as e:
        logger.error(f"[{operation_id}] Error selecting records: {str(e)}")
        return []

def get_record_by_id(table: str, id: int, columns: List[str] = None, operation_id: str = None) -> Optional[Dict[str, Any]]:
    """
    Get a record by ID.

    Args:
        table (str): The table to select from.
        id (int): The ID of the record.
        columns (List[str], optional): The columns to select. Defaults to None (all columns).
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        Optional[Dict[str, Any]]: The record, or None if not found.
    """
    if operation_id is None:
        operation_id = f"get_by_id_{int(time.time())}"

    try:
        condition = "id = ?"
        condition_params = [{"type": "integer", "value": str(id)}]

        records = select_records(table, columns, condition, condition_params, limit=1, operation_id=operation_id)

        if records and len(records) > 0:
            logger.debug(f"[{operation_id}] Found record by ID {id}: {records[0]}")
            return records[0]

        logger.warning(f"[{operation_id}] No record found with ID {id} in table {table}")
        return None
    except Exception as e:
        logger.error(f"[{operation_id}] Error getting record by ID {id}: {str(e)}")

        # Try a direct query as a fallback
        try:
            logger.info(f"[{operation_id}] Trying direct query as fallback")
            cols = "*" if not columns else ", ".join(columns)
            sql = f"SELECT {cols} FROM {table} WHERE id = ? LIMIT 1"

            result = execute_query(sql, [{"type": "integer", "value": str(id)}], operation_id=f"{operation_id}_fallback")

            if "results" in result and len(result["results"]) > 0 and result["results"][0]["type"] == "ok":
                response = result["results"][0]["response"]
                if "result" in response and "rows" in response["result"] and len(response["result"]["rows"]) > 0:
                    row = response["result"]["rows"][0]
                    cols = response["result"]["cols"]

                    record = {}
                    for i, col in enumerate(cols):
                        try:
                            # Get column name safely
                            col_name = col.get("name", f"column_{i}")

                            # Get cell data safely
                            cell = row[i] if i < len(row) else {}

                            # Get value and type safely
                            value = cell.get("value") if isinstance(cell, dict) else cell
                            cell_type = cell.get("type") if isinstance(cell, dict) else None

                            # Convert value based on type
                            if cell_type == "integer" and value is not None:
                                try:
                                    value = int(value)
                                except (ValueError, TypeError):
                                    value = 0
                            elif cell_type == "float" and value is not None:
                                try:
                                    value = float(value)
                                except (ValueError, TypeError):
                                    value = 0.0
                            elif cell_type == "null":
                                value = None

                            # Store the value
                            record[col_name] = value
                        except Exception as e:
                            # Handle any errors
                            logger.warning(f"[{operation_id}] Error processing column {i}: {str(e)}")
                            record[f"column_{i}"] = None

                    logger.info(f"[{operation_id}] Found record by ID {id} using fallback: {record}")
                    return record

            logger.warning(f"[{operation_id}] No record found with ID {id} using fallback")
            return None
        except Exception as e2:
            logger.error(f"[{operation_id}] Error in fallback query: {str(e2)}")
            return None

def count_records(table: str, condition: str = None, condition_params: List[Dict[str, Any]] = None, operation_id: str = None) -> int:
    """
    Count records in a table.

    Args:
        table (str): The table to count records in.
        condition (str, optional): The condition for the count. Defaults to None.
        condition_params (List[Dict[str, Any]], optional): The parameters for the condition. Defaults to None.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        int: The number of records.
    """
    if operation_id is None:
        operation_id = f"count_{int(time.time())}"

    logger.info(f"[{operation_id}] Counting records in {table}")

    # Prepare the SQL
    sql = f"SELECT COUNT(*) FROM {table}"

    if condition:
        sql += f" WHERE {condition}"

    try:
        result = execute_query(sql, condition_params, operation_id)

        # Check for errors
        if "results" in result and len(result["results"]) > 0:
            if result["results"][0]["type"] == "error":
                error_msg = result["results"][0]["error"]["message"]
                logger.error(f"[{operation_id}] Count error: {error_msg}")
                return 0

            # Extract the count
            response = result["results"][0]["response"]
            if "result" in response and "rows" in response["result"] and response["result"]["rows"]:
                try:
                    row = response["result"]["rows"][0]

                    # Get the value safely
                    if len(row) > 0:
                        cell = row[0]
                        if isinstance(cell, dict) and "value" in cell:
                            try:
                                count = int(cell["value"])
                                logger.info(f"[{operation_id}] Counted {count} records")
                                return count
                            except (ValueError, TypeError) as e:
                                logger.warning(f"[{operation_id}] Error converting count to integer: {str(e)}")
                                return 0
                        else:
                            logger.warning(f"[{operation_id}] Unexpected cell format in count: {cell}")
                            return 0
                    else:
                        logger.warning(f"[{operation_id}] Empty row in count result")
                        return 0
                except Exception as e:
                    logger.error(f"[{operation_id}] Error extracting count: {str(e)}")
                    return 0

        logger.warning(f"[{operation_id}] Count failed")
        return 0
    except Exception as e:
        logger.error(f"[{operation_id}] Error counting records: {str(e)}")
        return 0

def record_exists(table: str, condition: str, condition_params: List[Dict[str, Any]], operation_id: str = None) -> bool:
    """
    Check if a record exists in a table.

    Args:
        table (str): The table to check.
        condition (str): The condition for the check.
        condition_params (List[Dict[str, Any]]): The parameters for the condition.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        bool: True if the record exists, False otherwise.
    """
    count = count_records(table, condition, condition_params, operation_id)
    return count > 0

def create_table_if_not_exists(table: str, schema: str, operation_id: str = None) -> bool:
    """
    Create a table if it doesn't exist.

    Args:
        table (str): The table to create.
        schema (str): The schema for the table.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        bool: True if the table was created or already exists, False otherwise.
    """
    if operation_id is None:
        operation_id = f"create_table_{int(time.time())}"

    logger.info(f"[{operation_id}] Creating table {table} if not exists")

    # Prepare the SQL
    sql = f"CREATE TABLE IF NOT EXISTS {table} ({schema})"

    try:
        result = execute_query(sql, operation_id=operation_id)

        # Check for errors
        if "results" in result and len(result["results"]) > 0:
            if result["results"][0]["type"] == "error":
                error_msg = result["results"][0]["error"]["message"]
                logger.error(f"[{operation_id}] Create table error: {error_msg}")
                return False

            logger.info(f"[{operation_id}] Table {table} created or already exists")
            return True

        return False
    except Exception as e:
        logger.error(f"[{operation_id}] Error creating table: {str(e)}")
        return False

def execute_transaction(queries: List[Tuple[str, List[Dict[str, Any]]]], operation_id: str = None) -> bool:
    """
    Execute a transaction with multiple queries.

    Args:
        queries (List[Tuple[str, List[Dict[str, Any]]]]): The queries to execute.
        operation_id (str, optional): A unique identifier for the operation. Defaults to None.

    Returns:
        bool: True if the transaction succeeded, False otherwise.
    """
    if operation_id is None:
        operation_id = f"transaction_{int(time.time())}"

    logger.info(f"[{operation_id}] Executing transaction with {len(queries)} queries")

    # Prepare the pipeline
    requests = [{"type": "execute", "stmt": {"sql": "BEGIN"}}]

    for sql, params in queries:
        requests.append({
            "type": "execute",
            "stmt": {
                "sql": sql,
                "args": params or []
            }
        })

    requests.append({"type": "execute", "stmt": {"sql": "COMMIT"}})

    try:
        result = execute_pipeline(requests, operation_id)

        # Check for errors
        for i, res in enumerate(result.get("results", [])):
            if res.get("type") == "error":
                error_msg = res.get("error", {}).get("message", "Unknown error")
                logger.error(f"[{operation_id}] Transaction error in query {i}: {error_msg}")

                # Try to rollback
                try:
                    execute_query("ROLLBACK", operation_id=f"{operation_id}_rollback")
                except:
                    pass

                return False

        logger.info(f"[{operation_id}] Transaction executed successfully")
        return True
    except Exception as e:
        logger.error(f"[{operation_id}] Error executing transaction: {str(e)}")

        # Try to rollback
        try:
            execute_query("ROLLBACK", operation_id=f"{operation_id}_rollback")
        except:
            pass

        return False