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
|
%global _empty_manifest_terminate_build 0
Name: python-data-api-mapper
Version: 1.2.4
Release: 1
Summary: A very simplistic AWS Aurora Serverless Data API mapper
License: MIT License
URL: https://github.com/get-carefull/data-api-mapper
Source0: https://mirrors.aliyun.com/pypi/web/packages/ee/aa/3d9f5f6eeaf48abd2b87059f1a6719735fc52635e7c72251c9279e9c00c7/data-api-mapper-1.2.4.tar.gz
BuildArch: noarch
%description
# Data API Mapper
The **Data API Mapper** is a lightweight wrapper for Amazon Aurora Serverless Data API. It's STRONGLY inspired by [DataApiClient](https://github.com/jeremydaly/data-api-client).
Currently, it only maps PostgreSQL types, but it can be easily extended to add MySQL.
## Motivation
Check https://github.com/jeremydaly/data-api-client#why-do-i-need-this
## How to use this module
```python
import os
import boto3
from data_api_mapper import DataAPIClient
db_name = os.getenv('DB_NAME')
db_cluster_arn = os.getenv('DB_CLUSTER_ARN')
secret_arn = os.getenv('SECRET_ARN')
rds_client = boto3.client('rds-data')
data_client = DataAPIClient(rds_client, secret_arn, db_cluster_arn, db_name)
```
## Running a query
Once initialized, running a query is super simple. Use the `query()` method and pass in your SQL statement:
```python
result = data_client.query('SELECT * FROM myTable')
```
By default, this will return your rows as an array of dictionaries with column names as key names and the values as values, converted to python types:
For example, for this database:
```sql
CREATE TABLE aurora_data_api_test (
id SERIAL,
a_name TEXT,
doc JSONB DEFAULT '{}',
num_numeric NUMERIC (10, 5) DEFAULT 0.0,
num_float float,
num_integer integer,
ts TIMESTAMP WITH TIME ZONE,
field_string_null TEXT NULL,
field_long_null integer NULL,
field_doc_null JSONB NULL,
field_boolean BOOLEAN NULL,
tz_notimezone TIMESTAMP,
a_date DATE
);
INSERT INTO aurora_data_api_test (a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone, a_date)
VALUES ('first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
VALUES ('second row', '{"string_vale": "string2", "int_value": 2, "float_value": 2.22}', 2.22, 2.22, 2, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
```
this query
```pyton
self.data_client.query("select * from aurora_data_api_test where id (1,2)"
```
will return:
```python
[{'id': 1, 'a_name': 'first row', 'doc': {'int_value': 1, 'float_value': 1.11, 'string_vale': 'string1'}, 'num_numeric': Decimal('1.12345'), 'num_float': 1.11, 'num_integer': 1, 'ts': datetime.datetime(1976, 11, 2, 8, 45, tzinfo=datetime.timezone.utc), 'field_string_null': None, 'field_long_null': None, 'field_doc_null': None, 'field_boolean': None, 'tz_notimezone': datetime.datetime(2021, 3, 3, 15, 51, 48, 82288, tzinfo=datetime.timezone.utc), 'a_date': datetime.date(1976, 11, 2)},
{'id': 2, 'a_name': 'prueba', 'doc': {'a_date': '1976-11-02', 'num_int': 1, 'num_float': 45.6, 'somestring': 'hello'}, 'num_numeric': Decimal('100.76540'), 'num_float': 10.123, 'num_integer': 1, 'ts': datetime.datetime(1976, 11, 2, 8, 45, tzinfo=datetime.timezone.utc), 'field_string_null': None, 'field_long_null': None, 'field_doc_null': None, 'field_boolean': True, 'tz_notimezone': datetime.datetime(2021, 3, 3, 15, 51, 48, 82288, tzinfo=datetime.timezone.utc), 'a_date': datetime.date(1976, 11, 2)}]
```
By default, `query()` receives a dictionary that maps PostgreSQL types to python types.
```python
POSTGRES_PYTHON_MAPPER = {
'jsonb': JsonbToDict,
'timestamptz': TimestampzToDatetimeUTC,
'timestamp': TimestampzToDatetimeUTC,
'date': DateToDate,
'numeric': NumericToDecimal,
}
class DataAPIClient:
def __init__(self, rds_client, secret_arn, cluster_arn, database_name) -> None:
...
def query(self, sql, parameters=None, mapper=POSTGRES_PYTHON_MAPPER):
...
```
There is also a mapper for AppSync, you can check the mappers [here](https://github.com/get-carefull/data-api-mapper/blob/master/data_api_mapper/converters.py).
<br>
If you use MySQL you need a mapper.
## Running a query with parameters
To query with parameters, you can use named parameters in your SQL, and then provide an object containing your parameters as the second argument to the `query()` method and the client does the conversion for you:
```python
import datetime
result = data_client.query(
'SELECT * FROM myTable WHERE id = :id AND created > :createDate',
{ 'id': 2, 'createDate': datetime.date(2021,6,1) }
)
```
For all the conversions, check [here](https://github.com/get-carefull/data-api-mapper/blob/master/data_api_mapper/data_api.py#L10)
## Transactions
```python
class TestDataAPI(unittest.TestCase):
data_client = None
@classmethod
def setUpClass(cls):
db_name = os.getenv('DB_NAME')
db_cluster_arn = os.getenv('DB_CLUSTER_ARN')
secret_arn = os.getenv('SECRET_ARN')
rds_client = boto3.client('rds-data')
data_client = DataAPIClient(rds_client, secret_arn, db_cluster_arn, db_name)
initial_sql = """
DROP TABLE IF EXISTS aurora_data_api_test;
CREATE TABLE aurora_data_api_test (
id SERIAL,
a_name TEXT,
doc JSONB DEFAULT '{}',
num_numeric NUMERIC (10, 5) DEFAULT 0.0,
num_float float,
num_integer integer,
ts TIMESTAMP WITH TIME ZONE,
field_string_null TEXT NULL,
field_long_null integer NULL,
field_doc_null JSONB NULL,
field_boolean BOOLEAN NULL,
tz_notimezone TIMESTAMP,
a_date DATE
);
INSERT INTO aurora_data_api_test (a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone, a_date)
VALUES ('first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
VALUES ('second row', '{"string_vale": "string2", "int_value": 2, "float_value": 2.22}', 2.22, 2.22, 2, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
"""
data_client.query(sql=initial_sql)
cls.data_client = data_client
def test_transaction(self):
transaction = self.data_client.begin_transaction()
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (345, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288');
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id = 345")
self.assertEqual(1, len(inside_transaction))
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (346, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288');
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(2, len(inside_transaction))
before_commit = self.data_client.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(0, len(before_commit))
transaction.commit()
after_commit = self.data_client.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(2, len(after_commit))
def test_transaction_rollback(self):
transaction = self.data_client.begin_transaction()
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (355, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288')
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id = 355")
self.assertEqual(1, len(inside_transaction))
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (356, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288')
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(2, len(inside_transaction))
before_rollback = self.data_client.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(0, len(before_rollback))
transaction.rollback()
after_rollback = self.data_client.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(0, len(after_rollback))
@classmethod
def tearDownClass(cls):
cls.data_client.query('DROP TABLE IF EXISTS aurora_data_api_test')
```
%package -n python3-data-api-mapper
Summary: A very simplistic AWS Aurora Serverless Data API mapper
Provides: python-data-api-mapper
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-data-api-mapper
# Data API Mapper
The **Data API Mapper** is a lightweight wrapper for Amazon Aurora Serverless Data API. It's STRONGLY inspired by [DataApiClient](https://github.com/jeremydaly/data-api-client).
Currently, it only maps PostgreSQL types, but it can be easily extended to add MySQL.
## Motivation
Check https://github.com/jeremydaly/data-api-client#why-do-i-need-this
## How to use this module
```python
import os
import boto3
from data_api_mapper import DataAPIClient
db_name = os.getenv('DB_NAME')
db_cluster_arn = os.getenv('DB_CLUSTER_ARN')
secret_arn = os.getenv('SECRET_ARN')
rds_client = boto3.client('rds-data')
data_client = DataAPIClient(rds_client, secret_arn, db_cluster_arn, db_name)
```
## Running a query
Once initialized, running a query is super simple. Use the `query()` method and pass in your SQL statement:
```python
result = data_client.query('SELECT * FROM myTable')
```
By default, this will return your rows as an array of dictionaries with column names as key names and the values as values, converted to python types:
For example, for this database:
```sql
CREATE TABLE aurora_data_api_test (
id SERIAL,
a_name TEXT,
doc JSONB DEFAULT '{}',
num_numeric NUMERIC (10, 5) DEFAULT 0.0,
num_float float,
num_integer integer,
ts TIMESTAMP WITH TIME ZONE,
field_string_null TEXT NULL,
field_long_null integer NULL,
field_doc_null JSONB NULL,
field_boolean BOOLEAN NULL,
tz_notimezone TIMESTAMP,
a_date DATE
);
INSERT INTO aurora_data_api_test (a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone, a_date)
VALUES ('first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
VALUES ('second row', '{"string_vale": "string2", "int_value": 2, "float_value": 2.22}', 2.22, 2.22, 2, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
```
this query
```pyton
self.data_client.query("select * from aurora_data_api_test where id (1,2)"
```
will return:
```python
[{'id': 1, 'a_name': 'first row', 'doc': {'int_value': 1, 'float_value': 1.11, 'string_vale': 'string1'}, 'num_numeric': Decimal('1.12345'), 'num_float': 1.11, 'num_integer': 1, 'ts': datetime.datetime(1976, 11, 2, 8, 45, tzinfo=datetime.timezone.utc), 'field_string_null': None, 'field_long_null': None, 'field_doc_null': None, 'field_boolean': None, 'tz_notimezone': datetime.datetime(2021, 3, 3, 15, 51, 48, 82288, tzinfo=datetime.timezone.utc), 'a_date': datetime.date(1976, 11, 2)},
{'id': 2, 'a_name': 'prueba', 'doc': {'a_date': '1976-11-02', 'num_int': 1, 'num_float': 45.6, 'somestring': 'hello'}, 'num_numeric': Decimal('100.76540'), 'num_float': 10.123, 'num_integer': 1, 'ts': datetime.datetime(1976, 11, 2, 8, 45, tzinfo=datetime.timezone.utc), 'field_string_null': None, 'field_long_null': None, 'field_doc_null': None, 'field_boolean': True, 'tz_notimezone': datetime.datetime(2021, 3, 3, 15, 51, 48, 82288, tzinfo=datetime.timezone.utc), 'a_date': datetime.date(1976, 11, 2)}]
```
By default, `query()` receives a dictionary that maps PostgreSQL types to python types.
```python
POSTGRES_PYTHON_MAPPER = {
'jsonb': JsonbToDict,
'timestamptz': TimestampzToDatetimeUTC,
'timestamp': TimestampzToDatetimeUTC,
'date': DateToDate,
'numeric': NumericToDecimal,
}
class DataAPIClient:
def __init__(self, rds_client, secret_arn, cluster_arn, database_name) -> None:
...
def query(self, sql, parameters=None, mapper=POSTGRES_PYTHON_MAPPER):
...
```
There is also a mapper for AppSync, you can check the mappers [here](https://github.com/get-carefull/data-api-mapper/blob/master/data_api_mapper/converters.py).
<br>
If you use MySQL you need a mapper.
## Running a query with parameters
To query with parameters, you can use named parameters in your SQL, and then provide an object containing your parameters as the second argument to the `query()` method and the client does the conversion for you:
```python
import datetime
result = data_client.query(
'SELECT * FROM myTable WHERE id = :id AND created > :createDate',
{ 'id': 2, 'createDate': datetime.date(2021,6,1) }
)
```
For all the conversions, check [here](https://github.com/get-carefull/data-api-mapper/blob/master/data_api_mapper/data_api.py#L10)
## Transactions
```python
class TestDataAPI(unittest.TestCase):
data_client = None
@classmethod
def setUpClass(cls):
db_name = os.getenv('DB_NAME')
db_cluster_arn = os.getenv('DB_CLUSTER_ARN')
secret_arn = os.getenv('SECRET_ARN')
rds_client = boto3.client('rds-data')
data_client = DataAPIClient(rds_client, secret_arn, db_cluster_arn, db_name)
initial_sql = """
DROP TABLE IF EXISTS aurora_data_api_test;
CREATE TABLE aurora_data_api_test (
id SERIAL,
a_name TEXT,
doc JSONB DEFAULT '{}',
num_numeric NUMERIC (10, 5) DEFAULT 0.0,
num_float float,
num_integer integer,
ts TIMESTAMP WITH TIME ZONE,
field_string_null TEXT NULL,
field_long_null integer NULL,
field_doc_null JSONB NULL,
field_boolean BOOLEAN NULL,
tz_notimezone TIMESTAMP,
a_date DATE
);
INSERT INTO aurora_data_api_test (a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone, a_date)
VALUES ('first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
VALUES ('second row', '{"string_vale": "string2", "int_value": 2, "float_value": 2.22}', 2.22, 2.22, 2, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
"""
data_client.query(sql=initial_sql)
cls.data_client = data_client
def test_transaction(self):
transaction = self.data_client.begin_transaction()
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (345, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288');
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id = 345")
self.assertEqual(1, len(inside_transaction))
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (346, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288');
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(2, len(inside_transaction))
before_commit = self.data_client.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(0, len(before_commit))
transaction.commit()
after_commit = self.data_client.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(2, len(after_commit))
def test_transaction_rollback(self):
transaction = self.data_client.begin_transaction()
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (355, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288')
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id = 355")
self.assertEqual(1, len(inside_transaction))
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (356, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288')
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(2, len(inside_transaction))
before_rollback = self.data_client.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(0, len(before_rollback))
transaction.rollback()
after_rollback = self.data_client.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(0, len(after_rollback))
@classmethod
def tearDownClass(cls):
cls.data_client.query('DROP TABLE IF EXISTS aurora_data_api_test')
```
%package help
Summary: Development documents and examples for data-api-mapper
Provides: python3-data-api-mapper-doc
%description help
# Data API Mapper
The **Data API Mapper** is a lightweight wrapper for Amazon Aurora Serverless Data API. It's STRONGLY inspired by [DataApiClient](https://github.com/jeremydaly/data-api-client).
Currently, it only maps PostgreSQL types, but it can be easily extended to add MySQL.
## Motivation
Check https://github.com/jeremydaly/data-api-client#why-do-i-need-this
## How to use this module
```python
import os
import boto3
from data_api_mapper import DataAPIClient
db_name = os.getenv('DB_NAME')
db_cluster_arn = os.getenv('DB_CLUSTER_ARN')
secret_arn = os.getenv('SECRET_ARN')
rds_client = boto3.client('rds-data')
data_client = DataAPIClient(rds_client, secret_arn, db_cluster_arn, db_name)
```
## Running a query
Once initialized, running a query is super simple. Use the `query()` method and pass in your SQL statement:
```python
result = data_client.query('SELECT * FROM myTable')
```
By default, this will return your rows as an array of dictionaries with column names as key names and the values as values, converted to python types:
For example, for this database:
```sql
CREATE TABLE aurora_data_api_test (
id SERIAL,
a_name TEXT,
doc JSONB DEFAULT '{}',
num_numeric NUMERIC (10, 5) DEFAULT 0.0,
num_float float,
num_integer integer,
ts TIMESTAMP WITH TIME ZONE,
field_string_null TEXT NULL,
field_long_null integer NULL,
field_doc_null JSONB NULL,
field_boolean BOOLEAN NULL,
tz_notimezone TIMESTAMP,
a_date DATE
);
INSERT INTO aurora_data_api_test (a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone, a_date)
VALUES ('first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
VALUES ('second row', '{"string_vale": "string2", "int_value": 2, "float_value": 2.22}', 2.22, 2.22, 2, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
```
this query
```pyton
self.data_client.query("select * from aurora_data_api_test where id (1,2)"
```
will return:
```python
[{'id': 1, 'a_name': 'first row', 'doc': {'int_value': 1, 'float_value': 1.11, 'string_vale': 'string1'}, 'num_numeric': Decimal('1.12345'), 'num_float': 1.11, 'num_integer': 1, 'ts': datetime.datetime(1976, 11, 2, 8, 45, tzinfo=datetime.timezone.utc), 'field_string_null': None, 'field_long_null': None, 'field_doc_null': None, 'field_boolean': None, 'tz_notimezone': datetime.datetime(2021, 3, 3, 15, 51, 48, 82288, tzinfo=datetime.timezone.utc), 'a_date': datetime.date(1976, 11, 2)},
{'id': 2, 'a_name': 'prueba', 'doc': {'a_date': '1976-11-02', 'num_int': 1, 'num_float': 45.6, 'somestring': 'hello'}, 'num_numeric': Decimal('100.76540'), 'num_float': 10.123, 'num_integer': 1, 'ts': datetime.datetime(1976, 11, 2, 8, 45, tzinfo=datetime.timezone.utc), 'field_string_null': None, 'field_long_null': None, 'field_doc_null': None, 'field_boolean': True, 'tz_notimezone': datetime.datetime(2021, 3, 3, 15, 51, 48, 82288, tzinfo=datetime.timezone.utc), 'a_date': datetime.date(1976, 11, 2)}]
```
By default, `query()` receives a dictionary that maps PostgreSQL types to python types.
```python
POSTGRES_PYTHON_MAPPER = {
'jsonb': JsonbToDict,
'timestamptz': TimestampzToDatetimeUTC,
'timestamp': TimestampzToDatetimeUTC,
'date': DateToDate,
'numeric': NumericToDecimal,
}
class DataAPIClient:
def __init__(self, rds_client, secret_arn, cluster_arn, database_name) -> None:
...
def query(self, sql, parameters=None, mapper=POSTGRES_PYTHON_MAPPER):
...
```
There is also a mapper for AppSync, you can check the mappers [here](https://github.com/get-carefull/data-api-mapper/blob/master/data_api_mapper/converters.py).
<br>
If you use MySQL you need a mapper.
## Running a query with parameters
To query with parameters, you can use named parameters in your SQL, and then provide an object containing your parameters as the second argument to the `query()` method and the client does the conversion for you:
```python
import datetime
result = data_client.query(
'SELECT * FROM myTable WHERE id = :id AND created > :createDate',
{ 'id': 2, 'createDate': datetime.date(2021,6,1) }
)
```
For all the conversions, check [here](https://github.com/get-carefull/data-api-mapper/blob/master/data_api_mapper/data_api.py#L10)
## Transactions
```python
class TestDataAPI(unittest.TestCase):
data_client = None
@classmethod
def setUpClass(cls):
db_name = os.getenv('DB_NAME')
db_cluster_arn = os.getenv('DB_CLUSTER_ARN')
secret_arn = os.getenv('SECRET_ARN')
rds_client = boto3.client('rds-data')
data_client = DataAPIClient(rds_client, secret_arn, db_cluster_arn, db_name)
initial_sql = """
DROP TABLE IF EXISTS aurora_data_api_test;
CREATE TABLE aurora_data_api_test (
id SERIAL,
a_name TEXT,
doc JSONB DEFAULT '{}',
num_numeric NUMERIC (10, 5) DEFAULT 0.0,
num_float float,
num_integer integer,
ts TIMESTAMP WITH TIME ZONE,
field_string_null TEXT NULL,
field_long_null integer NULL,
field_doc_null JSONB NULL,
field_boolean BOOLEAN NULL,
tz_notimezone TIMESTAMP,
a_date DATE
);
INSERT INTO aurora_data_api_test (a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone, a_date)
VALUES ('first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
VALUES ('second row', '{"string_vale": "string2", "int_value": 2, "float_value": 2.22}', 2.22, 2.22, 2, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288', '1976-11-02');
"""
data_client.query(sql=initial_sql)
cls.data_client = data_client
def test_transaction(self):
transaction = self.data_client.begin_transaction()
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (345, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288');
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id = 345")
self.assertEqual(1, len(inside_transaction))
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (346, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288');
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(2, len(inside_transaction))
before_commit = self.data_client.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(0, len(before_commit))
transaction.commit()
after_commit = self.data_client.query("select * from aurora_data_api_test where id in (345,346)")
self.assertEqual(2, len(after_commit))
def test_transaction_rollback(self):
transaction = self.data_client.begin_transaction()
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (355, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288')
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id = 355")
self.assertEqual(1, len(inside_transaction))
transaction.query('''
INSERT INTO aurora_data_api_test (id, a_name, doc, num_numeric, num_float, num_integer, ts, tz_notimezone)
VALUES (356, 'first row', '{"string_vale": "string1", "int_value": 1, "float_value": 1.11}', 1.12345, 1.11, 1, '1976-11-02 08:45:00 UTC', '2021-03-03 15:51:48.082288')
''')
inside_transaction = transaction.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(2, len(inside_transaction))
before_rollback = self.data_client.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(0, len(before_rollback))
transaction.rollback()
after_rollback = self.data_client.query("select * from aurora_data_api_test where id in (355,356)")
self.assertEqual(0, len(after_rollback))
@classmethod
def tearDownClass(cls):
cls.data_client.query('DROP TABLE IF EXISTS aurora_data_api_test')
```
%prep
%autosetup -n data-api-mapper-1.2.4
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-data-api-mapper -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Tue Jun 20 2023 Python_Bot <Python_Bot@openeuler.org> - 1.2.4-1
- Package Spec generated
|