| 42 | |
| 43 | @staticmethod |
| 44 | def save(uid, sid, dbname, request): |
| 45 | try: |
| 46 | max_srno = db.session\ |
| 47 | .query(db.func.max(QueryHistoryModel.srno)) \ |
| 48 | .filter(QueryHistoryModel.uid == uid, |
| 49 | QueryHistoryModel.sid == sid, |
| 50 | QueryHistoryModel.dbname == dbname)\ |
| 51 | .scalar() |
| 52 | |
| 53 | # if no records present |
| 54 | if max_srno is None: |
| 55 | new_srno = 1 |
| 56 | else: |
| 57 | new_srno = max_srno + 1 |
| 58 | |
| 59 | # last updated flag is used to recognise the last |
| 60 | # inserted/updated record. |
| 61 | # It is helpful to cycle the records |
| 62 | last_updated_rec = db.session.query(QueryHistoryModel) \ |
| 63 | .filter(QueryHistoryModel.uid == uid, |
| 64 | QueryHistoryModel.sid == sid, |
| 65 | QueryHistoryModel.dbname == dbname, |
| 66 | QueryHistoryModel.last_updated_flag == 'Y') \ |
| 67 | .first() |
| 68 | |
| 69 | # there should be a last updated record |
| 70 | # if not present start from sr no 1 |
| 71 | if last_updated_rec is not None: |
| 72 | last_updated_rec.last_updated_flag = 'N' |
| 73 | |
| 74 | # if max limit reached then recycle |
| 75 | if new_srno > MAX_QUERY_HIST_STORED: |
| 76 | new_srno = ( |
| 77 | last_updated_rec.srno % MAX_QUERY_HIST_STORED) + 1 |
| 78 | else: |
| 79 | new_srno = 1 |
| 80 | |
| 81 | # if the limit is lowered and number of records present is |
| 82 | # more, then cleanup |
| 83 | if max_srno > MAX_QUERY_HIST_STORED: |
| 84 | db.session.query(QueryHistoryModel)\ |
| 85 | .filter(QueryHistoryModel.uid == uid, |
| 86 | QueryHistoryModel.sid == sid, |
| 87 | QueryHistoryModel.dbname == dbname, |
| 88 | QueryHistoryModel.srno > |
| 89 | MAX_QUERY_HIST_STORED)\ |
| 90 | .delete() |
| 91 | |
| 92 | history_entry = QueryHistoryModel( |
| 93 | srno=new_srno, uid=uid, sid=sid, dbname=dbname, |
| 94 | query_info=request.data, last_updated_flag='Y') |
| 95 | |
| 96 | db.session.merge(history_entry) |
| 97 | |
| 98 | db.session.commit() |
| 99 | except Exception: |
| 100 | db.session.rollback() |
| 101 | # do not affect query execution if history saving fails |