MilanM commited on
Commit
312bffc
·
verified ·
1 Parent(s): 1ee731c

Create cloudant_helper_functions.py

Browse files
Files changed (1) hide show
  1. cloudant_helper_functions.py +55 -0
cloudant_helper_functions.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def cloudant_retrieve_documents(
2
+ client: CloudantV1,
3
+ db_name: str,
4
+ selectors: dict,
5
+ fields,
6
+ sort: dict = None,
7
+ limit: int = 100,
8
+ ):
9
+ """Retrieve documents from the cloudant database."""
10
+ cloudant = client
11
+ sort_by = sort or {
12
+ "sort": [
13
+ {"_id": "desc"},
14
+ ]
15
+ }
16
+ fields_to_retrieve = (
17
+ {"fields": fields} if isinstance(fields, list) else fields
18
+ )
19
+ if not isinstance(fields, (list, dict)):
20
+ raise ValueError("fields must be a list of strings or a dict")
21
+
22
+ retrieved_docs = cloudant.post_find(
23
+ db=db_name,
24
+ selector=selectors,
25
+ fields=fields_to_retrieve["fields"],
26
+ sort=sort,
27
+ limit=limit,
28
+ ).get_result()
29
+
30
+ return retrieved_docs
31
+
32
+
33
+ def ensure_database_exists(client: CloudantV1, db_name: str) -> bool:
34
+ """
35
+ Check if database exists and create it if it doesn't.
36
+
37
+ Args:
38
+ client (CloudantV1): Initialized Cloudant client
39
+ db_name (str): Database name to check/create
40
+
41
+ Returns:
42
+ bool: True if database exists or was created successfully
43
+ """
44
+ try:
45
+ # Try to get database info - will raise error if doesn't exist
46
+ client.get_database_information(db=db_name)
47
+ return True
48
+ except Exception:
49
+ try:
50
+ # Database doesn't exist, try to create it
51
+ client.put_database(db=db_name)
52
+ return True
53
+ except Exception as e:
54
+ print(f"Failed to create database {db_name}: {str(e)}")
55
+ raise