Source code for agentscope.service.sql_query.sqlite
# -*- coding: utf-8 -*-""" Query in sqlite """fromtypingimportOptionalfromtypingimportAnyfrom...service.service_responseimportServiceResponsefrom...utils.commonimport_if_change_databasefrom...service.service_statusimportServiceExecStatustry:importsqlite3exceptImportError:sqlite3=None
[docs]defquery_sqlite(database:str,query:str,allow_change_data:bool=False,maxcount_results:Optional[int]=None,**kwargs:Any,)->ServiceResponse:"""Executes query within sqlite database. Args: database (`str`): The name of the database to use. query (`str`): The query to execute. allow_change_data (`bool`, defaults to `False`): Whether to allow changing data in the database. Defaults to `False` to avoid accidental changes to the database. maxcount_results (`int`, defaults to `None`): The maximum number of results to return. Returns: `ServiceResponse`: A `ServiceResponse` object that contains execution results or error message. """# Check if the query is safeifnotallow_change_dataandnot_if_change_database(query):raiseValueError("Unsafe SQL query detected. Only SELECT statements are allowed. ""If you want to allow changing data in the database, ""set `allow_change_data` to `True`.",)# Limit the number of results by adding LIMIT keywords if necessaryifmaxcount_resultsisnotNone:if"limit"notinquery.lower():query+=f" LIMIT {maxcount_results}"try:conn=sqlite3.connect(database,**kwargs)cursor=conn.cursor()cursor.execute(query)results=cursor.fetchall()# commit the change if neededif_if_change_database(query):conn.commit()cursor.close()conn.close()returnServiceResponse(status=ServiceExecStatus.SUCCESS,content=results,)exceptExceptionase:returnServiceResponse(status=ServiceExecStatus.ERROR,# TODO: more specific error messagecontent=str(e),)