(document, debug=False)
| 68 | |
| 69 | # "sql" key in document should have a valid query |
| 70 | def featurebase_query(document, debug=False): |
| 71 | # try to run the query |
| 72 | try: |
| 73 | sql = document.get("sql") |
| 74 | |
| 75 | # Specify the file path where you want to save the SQL string |
| 76 | """ |
| 77 | file_path = "output.sql" |
| 78 | |
| 79 | # Open the file in write mode |
| 80 | with open(file_path, "a") as file: |
| 81 | # Write the SQL string to the file |
| 82 | file.write("%s\n" % sql) |
| 83 | """ |
| 84 | |
| 85 | result = requests.post( |
| 86 | config.featurebase_endpoint+"/query/sql", |
| 87 | data=sql.encode('utf-8'), |
| 88 | headers={ |
| 89 | 'Content-Type': 'text/plain', |
| 90 | 'X-API-Key': '%s' % config.featurebase_token, |
| 91 | } |
| 92 | ) |
| 93 | if debug: |
| 94 | print(document.get('sql')) |
| 95 | print(result.text) |
| 96 | result = result.json() |
| 97 | |
| 98 | except Exception as ex: |
| 99 | # bad query? |
| 100 | print("error: ", ex) |
| 101 | exc_type, exc_obj, exc_tb = sys.exc_info() |
| 102 | document['error'] = "%s: %s" % (exc_tb.tb_lineno, ex) |
| 103 | return document |
| 104 | |
| 105 | if result.get('error', ""): |
| 106 | # featurebase reports and error |
| 107 | document['explain'] = "Error returned by FeatureBase: %s" % result.get('error') |
| 108 | document['error'] = result.get('error') |
| 109 | document['data'] = result.get('data') |
| 110 | |
| 111 | elif result.get('data', []): |
| 112 | # got some data back from featurebase |
| 113 | document['data'] = result.get('data') |
| 114 | document['schema'] = result.get('schema') |
| 115 | |
| 116 | field_names = [] |
| 117 | |
| 118 | for field in result.get('schema').get('fields'): |
| 119 | field_names.append(field.get('name')) |
| 120 | |
| 121 | document['results'] = apply_schema(result.get('data'), field_names) |
| 122 | else: |
| 123 | document['explain'] = "Query was successful, but returned no data." |
| 124 | |
| 125 | return document |
| 126 | |
| 127 |
no test coverage detected