aboutsummaryrefslogtreecommitdiff
path: root/ustayml/db.py
diff options
context:
space:
mode:
authorMitsuo Tokumori <rtokumori@pucp.edu.pe>2023-11-12 18:18:35 -0500
committerMitsuo Tokumori <rtokumori@pucp.edu.pe>2023-11-12 18:18:35 -0500
commitfcd9465d564b08ae289417fb0616942b38fd0836 (patch)
treef4d93b9c9ebde6aff9f8c2157bae62aeb4229c37 /ustayml/db.py
parent8c82c32015b2c780f2b5662ff495f55153a5a26f (diff)
Move pagination functions to db.py
Diffstat (limited to 'ustayml/db.py')
-rw-r--r--ustayml/db.py16
1 files changed, 15 insertions, 1 deletions
diff --git a/ustayml/db.py b/ustayml/db.py
index 8fb1ec9..25d0188 100644
--- a/ustayml/db.py
+++ b/ustayml/db.py
@@ -1,3 +1,4 @@
+import math
import psycopg
import click
@@ -51,4 +52,17 @@ def init_db_command():
def init_app(app):
app.teardown_appcontext(close_db) # callback after returning response
- app.cli.add_command(init_db_command) \ No newline at end of file
+ app.cli.add_command(init_db_command)
+
+
+# Helper functions
+
+def get_paginated_items(query: str, params: list=[], pagination: dict={}):
+ limit = pagination.get('pagesize', 100)
+ offset = pagination.get('page', 0) * limit
+ with get_db().cursor() as cursor:
+ cursor.execute(f"{query} LIMIT %s OFFSET %s;", params + [limit, offset])
+ pagination['n_pages'] = math.ceil(cursor.rowcount / limit)
+ pagination['rowcount'] = cursor.rowcount
+ items = cursor.fetchall()
+ return items \ No newline at end of file