api-foundry-query-engine 0.0.1__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.
Files changed (27) hide show
  1. api_foundry_query_engine-0.0.1/.gitignore +11 -0
  2. api_foundry_query_engine-0.0.1/LICENSE +201 -0
  3. api_foundry_query_engine-0.0.1/PKG-INFO +14 -0
  4. api_foundry_query_engine-0.0.1/api_foundry_query_engine/adapters/adapter.py +67 -0
  5. api_foundry_query_engine-0.0.1/api_foundry_query_engine/adapters/case_change_adapter.py +79 -0
  6. api_foundry_query_engine-0.0.1/api_foundry_query_engine/adapters/gateway_adapter.py +112 -0
  7. api_foundry_query_engine-0.0.1/api_foundry_query_engine/connectors/connection.py +32 -0
  8. api_foundry_query_engine-0.0.1/api_foundry_query_engine/connectors/connection_factory.py +110 -0
  9. api_foundry_query_engine-0.0.1/api_foundry_query_engine/connectors/oracle_connector.py +29 -0
  10. api_foundry_query_engine-0.0.1/api_foundry_query_engine/connectors/postgres_connection.py +105 -0
  11. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/dao.py +23 -0
  12. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/operation_dao.py +141 -0
  13. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_custom_query_handler.py +66 -0
  14. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_delete_query_handler.py +36 -0
  15. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_insert_query_handler.py +102 -0
  16. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_query_handler.py +386 -0
  17. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_select_query_handler.py +305 -0
  18. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_subselect_query_handler.py +63 -0
  19. api_foundry_query_engine-0.0.1/api_foundry_query_engine/dao/sql_update_query_handler.py +59 -0
  20. api_foundry_query_engine-0.0.1/api_foundry_query_engine/handler.py +48 -0
  21. api_foundry_query_engine-0.0.1/api_foundry_query_engine/operation.py +15 -0
  22. api_foundry_query_engine-0.0.1/api_foundry_query_engine/services/service.py +60 -0
  23. api_foundry_query_engine-0.0.1/api_foundry_query_engine/services/transactional_service.py +43 -0
  24. api_foundry_query_engine-0.0.1/api_foundry_query_engine/utils/api_model.py +175 -0
  25. api_foundry_query_engine-0.0.1/api_foundry_query_engine/utils/app_exception.py +22 -0
  26. api_foundry_query_engine-0.0.1/api_foundry_query_engine/utils/logger.py +60 -0
  27. api_foundry_query_engine-0.0.1/pyproject.toml +34 -0
@@ -0,0 +1,11 @@
1
+ .DS_STORE
2
+ *.pyc
3
+ dist/
4
+ __pycache__/
5
+ venv
6
+ build/
7
+ coverage.xml
8
+ htmlcov/
9
+ .coverage.*
10
+ .coverage
11
+ .vscode/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.3
2
+ Name: api-foundry-query-engine
3
+ Version: 0.0.1
4
+ Summary: The AWS lambda service handler use by the `api_foundry` project is a powerful tool designed to automate the deployment of REST APIs on AWS using Lambda services to access and interact with relational databases (RDBMS). This project leverages the OpenAPI specification to define and manage the APIs
5
+ Project-URL: Documentation, https://github.com/DanRepik/api-foundry
6
+ Project-URL: Source, https://github.com/DanRepik/api-foundry
7
+ Author-email: Daniel Repik <danrepik@icloud.com>
8
+ License-File: LICENSE
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Requires-Python: >=3.9
12
+ Requires-Dist: boto3
13
+ Requires-Dist: pyhumps
14
+ Requires-Dist: pyyaml
@@ -0,0 +1,67 @@
1
+ import abc
2
+ from typing import Optional
3
+
4
+ from api_foundry_query_engine.operation import Operation
5
+ from api_foundry_query_engine.services.transactional_service import TransactionalService
6
+ from api_foundry_query_engine.utils.logger import logger
7
+ from api_foundry_query_engine.services.service import Service
8
+
9
+ log = logger(__name__)
10
+
11
+
12
+ class Adapter(metaclass=abc.ABCMeta):
13
+ service: Service
14
+
15
+ @classmethod
16
+ def __subclasshook__(cls, __subclass: type) -> bool:
17
+ return (
18
+ hasattr(__subclass, "marshal")
19
+ and callable(__subclass.marshal)
20
+ and hasattr(__subclass, "umarshal")
21
+ and callable(__subclass.unmarshal)
22
+ )
23
+
24
+ def __init__(self, service: Optional[Service] = None) -> None:
25
+ self.service = service if service is not None else TransactionalService()
26
+
27
+ def unmarshal(self, event) -> Operation:
28
+ """
29
+ Unmarshal the event in a tuple for processing
30
+
31
+ Parameters:
32
+ - event (dict): Lambda event object.
33
+
34
+ Returns:
35
+ - Operation containing the entity, action, and parameters
36
+ """
37
+ raise NotImplementedError
38
+
39
+ def marshal(self, result: list[dict]):
40
+ """
41
+ Marshal the result into a event response
42
+
43
+ Parameters:
44
+ - result (list): the data set to return in the response
45
+
46
+ Returns:
47
+ - the event response
48
+ """
49
+ return result
50
+
51
+ def process_event(self, event):
52
+ """
53
+ Process Lambda event using a domain function.
54
+
55
+ Parameters:
56
+ - service_function (callable): The service function to be executed.
57
+ - event (dict): Lambda event object.
58
+
59
+ Returns:
60
+ - any: Result of the domain function.
61
+ """
62
+ operation = self.unmarshal(event)
63
+
64
+ result = self.service.execute(operation)
65
+ log.debug(f"adapter result: {result}")
66
+
67
+ return self.marshal(result)
@@ -0,0 +1,79 @@
1
+ from humps import camelize, decamelize
2
+
3
+ from api_foundry_query_engine.adapters.adapter import Adapter
4
+ from api_foundry_query_engine.utils.logger import logger
5
+ from api_foundry_query_engine.operation import Operation
6
+
7
+ log = logger(__name__)
8
+
9
+
10
+ class CaseChangeAdapter(Adapter):
11
+ """
12
+ Handles changing case from snake to camel and back
13
+ """
14
+
15
+ def unmarshal(self, event) -> Operation:
16
+ """
17
+ Unmarshal the event in a tuple for processing
18
+
19
+ Parameters:
20
+ - event (dict): Lambda event object.
21
+
22
+ Returns:
23
+ - tuple: Tuple containing entity operation, store_params, query_params and metadata params.
24
+ """
25
+ operation = super().unmarshal(event)
26
+
27
+ # determine case
28
+ self.camel_case = (
29
+ operation.metadata_params.get("_case", "snake") == "camel"
30
+ or self.__check_camel_case(operation.store_params)
31
+ or self.__check_camel_case(operation.query_params)
32
+ )
33
+ log.info(f"camel_case: {self.camel_case}")
34
+
35
+ if self.camel_case:
36
+ return Operation(
37
+ path=operation.entity,
38
+ action=operation.action,
39
+ store_params=decamelize(operation.store_params),
40
+ query_params=decamelize(operation.query_params),
41
+ metadata_params=operation.metadata_params,
42
+ )
43
+
44
+ return operation
45
+
46
+ def marshal(self, result: list[dict]):
47
+ """
48
+ Marshal the result into a event response
49
+
50
+ Parameters:
51
+ - result (list): the data set to return in the response
52
+
53
+ Returns:
54
+ - the event response
55
+ """
56
+ super().marshal(result)
57
+
58
+ if not self.camel_case:
59
+ return result
60
+
61
+ converted_result = []
62
+ for item in result:
63
+ converted_result.append(camelize(item))
64
+
65
+ # convert back to camel case if needed
66
+ return converted_result
67
+
68
+ def __check_camel_case(self, params: dict) -> bool:
69
+ if params is not None:
70
+ # check the keys for an upper case character
71
+ for param in params:
72
+ if (
73
+ param != param.lower()
74
+ and param != param.upper()
75
+ and "_" not in param
76
+ ):
77
+ return True
78
+
79
+ return False
@@ -0,0 +1,112 @@
1
+ import json
2
+
3
+ from api_foundry_query_engine.adapters.adapter import Adapter
4
+ from api_foundry_query_engine.operation import Operation
5
+
6
+ actions_map = {
7
+ "GET": "read",
8
+ "POST": "create",
9
+ "PUT": "update",
10
+ "DELETE": "delete",
11
+ }
12
+
13
+
14
+ class GatewayAdapter(Adapter):
15
+ def marshal(self, result: list[dict]):
16
+ """
17
+ Marshal the result into a event response
18
+
19
+ Parameters:
20
+ - result (list): the data set to return in the response
21
+
22
+ Returns:
23
+ - the event response
24
+ """
25
+ return super().marshal(result)
26
+
27
+ def unmarshal(self, event):
28
+ """
29
+ Get parameters from the Lambda event.
30
+
31
+ Parameters:
32
+ - event (dict): Lambda event object.
33
+
34
+ Returns:
35
+ - tuple: Tuple containing data, query and metadata parameters.
36
+ """
37
+ entity = event.get("resource").split("/")[1]
38
+ action = actions_map.get(event.get("httpMethod").upper(), "read")
39
+
40
+ event_params = {}
41
+
42
+ path_parameters = self._convert_parameters(event.get("pathParameters"))
43
+ if path_parameters is not None:
44
+ event_params.update(path_parameters)
45
+
46
+ queryStringParameters = self._convert_parameters(
47
+ event.get("queryStringParameters")
48
+ )
49
+ if queryStringParameters is not None:
50
+ event_params.update(queryStringParameters)
51
+
52
+ query_params, metadata_params = self.split_params(event_params)
53
+
54
+ store_params = {}
55
+ body = event.get("body")
56
+ if body is not None and len(body) > 0:
57
+ store_params = json.loads(body)
58
+
59
+ return Operation(
60
+ entity=entity,
61
+ action=action,
62
+ store_params=store_params,
63
+ query_params=query_params,
64
+ metadata_params=metadata_params,
65
+ )
66
+
67
+ def _convert_parameters(self, parameters):
68
+ """
69
+ Convert parameters to appropriate types.
70
+
71
+ Parameters:
72
+ - parameters (dict): Dictionary of parameters.
73
+
74
+ Returns:
75
+ - dict: Dictionary with parameters converted to appropriate types.
76
+ """
77
+ if parameters is None:
78
+ return None
79
+
80
+ result = {}
81
+ for parameter, value in parameters.items():
82
+ try:
83
+ result[parameter] = int(value)
84
+ except ValueError:
85
+ try:
86
+ result[parameter] = float(value)
87
+ except ValueError:
88
+ result[parameter] = value
89
+ return result
90
+
91
+ def split_params(self, parameters: dict):
92
+ """
93
+ Split a dictionary into two dictionaries based on keys.
94
+
95
+ Parameters:
96
+ - dictionary (dict): Input dictionary.
97
+
98
+ Returns:
99
+ - tuple: A tuple containing two dictionaries.
100
+ The first dictionary contains metadata_params,
101
+ and the second dictionary query_params.
102
+ """
103
+ query_params = {}
104
+ metadata_params = {}
105
+
106
+ for key, value in parameters.items():
107
+ if key.startswith("__"):
108
+ metadata_params[key] = value
109
+ else:
110
+ query_params[key] = value
111
+
112
+ return query_params, metadata_params
@@ -0,0 +1,32 @@
1
+ from api_foundry_query_engine.utils.logger import logger
2
+
3
+ # Initialize the logger
4
+ log = logger(__name__)
5
+
6
+ db_config_map = dict()
7
+
8
+
9
+ class Cursor:
10
+ def execute(self, sql: str, params: dict, selection_results: dict) -> list[dict]:
11
+ raise NotImplementedError
12
+
13
+ def close(self):
14
+ raise NotImplementedError
15
+
16
+
17
+ class Connection:
18
+ def __init__(self, db_config: dict) -> None:
19
+ super().__init__()
20
+ self.db_config = db_config
21
+
22
+ def engine(self) -> str:
23
+ return self.db_config["engine"]
24
+
25
+ def cursor(self) -> Cursor:
26
+ raise NotImplementedError
27
+
28
+ def commit(self):
29
+ raise NotImplementedError
30
+
31
+ def close(self):
32
+ raise NotImplementedError
@@ -0,0 +1,110 @@
1
+ import boto3
2
+ import json
3
+ import os
4
+
5
+ from api_foundry_query_engine.connectors.connection import Connection
6
+ from api_foundry_query_engine.utils.app_exception import ApplicationException
7
+ from api_foundry_query_engine.utils.logger import logger
8
+
9
+ log = logger(__name__)
10
+
11
+
12
+ class ConnectionFactory:
13
+ db_config_map: dict[str, dict]
14
+
15
+ def __init__(self):
16
+ self.db_config_map = dict()
17
+
18
+ def get_connection(self, database: str) -> Connection:
19
+ """
20
+ Factory function to create a database connector based on the
21
+ specified engine and schema.
22
+
23
+ Args:
24
+ - engine (str): The database engine type
25
+ ('postgres', 'oracle', or 'mysql').
26
+ - schema (str): The schema for the database.
27
+
28
+ Returns:
29
+ - Connector: An instance of the appropriate Connector subclass.
30
+ """
31
+
32
+ # Get the secret name based on the engine and database from the secrets map
33
+ log.info(f"database: {database}")
34
+ db_config = self.db_config_map.get(database)
35
+ if not db_config:
36
+ secret_name = json.loads(os.environ.get("SECRETS", "{}")).get(database)
37
+ log.info(f"secret_name: {secret_name}")
38
+
39
+ if secret_name:
40
+ db_config = self.__get_secret(secret_name)
41
+ else:
42
+ raise ValueError(f"Secret not found for database: {database}")
43
+
44
+ engine = db_config.get("engine")
45
+ if not engine:
46
+ raise ApplicationException(
47
+ 500, "Database 'engine' is not defined in the secret."
48
+ )
49
+
50
+ if engine == "postgres":
51
+ from .postgres_connection import PostgresConnection
52
+
53
+ return PostgresConnection(db_config)
54
+
55
+ # Add support for other engines here if needed in the future
56
+
57
+ raise ValueError(f"Unsupported database engine: {engine}")
58
+
59
+ def __get_secret(self, db_secret_name: str):
60
+ """
61
+ Get the secret from AWS Secrets Manager.
62
+
63
+ Parameters:
64
+ - db_secret_name (str): The name of the AWS Secrets Manager secret.
65
+
66
+ Returns:
67
+ - dict: The database configuration obtained from the secret.
68
+ """
69
+ endpoint_url = os.environ.get("AWS_ENDPOINT_URL") # LocalStack endpoint
70
+ sts_client = boto3.client("sts", endpoint_url=endpoint_url)
71
+
72
+ secret_account_id = os.environ.get("SECRET_ACCOUNT_ID", None)
73
+ log.info(f"secret_account_id: {secret_account_id}")
74
+
75
+ if secret_account_id:
76
+ # If a secret account ID is provided, assume a role in that account
77
+ secret_role = os.environ.get("ROLE_NAME", None)
78
+ assume_role_response = sts_client.assume_role(
79
+ RoleArn=f"arn:aws:iam::{secret_account_id}:role/{secret_role}",
80
+ RoleSessionName="AssumeRoleSession",
81
+ )
82
+
83
+ credentials = assume_role_response["Credentials"]
84
+
85
+ secretsmanager = boto3.client(
86
+ "secretsmanager",
87
+ aws_access_key_id=credentials["AccessKeyId"],
88
+ aws_secret_access_key=credentials["SecretAccessKey"],
89
+ aws_session_token=credentials["SessionToken"],
90
+ endpoint_url=endpoint_url,
91
+ )
92
+ else:
93
+ # If no secret account ID is provided, use the default account
94
+ log.info(f"endpoint_url: {endpoint_url}")
95
+ secretsmanager = boto3.client(
96
+ "secretsmanager",
97
+ # endpoint_url=endpoint_url,
98
+ )
99
+
100
+ # Get the secret value from AWS Secrets Manager
101
+ log.info(f"db_secret_name: {db_secret_name}")
102
+ db_secret = secretsmanager.describe_secret(SecretId=db_secret_name)
103
+ db_secret = secretsmanager.get_secret_value(SecretId=db_secret_name)
104
+ log.debug(f"loading secret name: {db_secret}")
105
+
106
+ # Return the parsed JSON secret string
107
+ return json.loads(db_secret.get("SecretString"))
108
+
109
+
110
+ connection_factory = ConnectionFactory()
@@ -0,0 +1,29 @@
1
+ from api_foundry_query_engine.utils.logger import logger
2
+ from api_foundry_query_engine.utils.app_exception import ApplicationException
3
+ from api_foundry_query_engine.connectors.connection import Connector
4
+
5
+ log = logger(__name__)
6
+
7
+
8
+ class OracleConnnector(Connector):
9
+ def __init__(self, db_secret_name: str) -> None:
10
+ super().__init__(db_secret_name)
11
+
12
+ def close(self):
13
+ pass
14
+
15
+ def execute(self, cursor, sql: str, parameters: dict):
16
+ from oracledb import Error, IntegrityError, ProgrammingError
17
+
18
+ log.debug(f"sql: {sql}, parameters: {parameters}")
19
+ try:
20
+ cursor.execute(sql, parameters)
21
+ except IntegrityError as err:
22
+ (error,) = err.args
23
+ raise ApplicationException(409, error.message)
24
+ except ProgrammingError as err:
25
+ (error,) = err.args
26
+ raise ApplicationException(400, error.message)
27
+ except Error as err:
28
+ (error,) = err.args
29
+ raise ApplicationException(500, error.message)