我的目标是将 SQLite 数据库文件上传到 AWS S3,使用 AWS Lambda 和 python (sqlite3
) 连接到数据库、查询数据库并返回部分数据。
将数据库文件上传到 S3 后,我编写了一个 Python 脚本(将成为 Lambda 函数),它成功从 S3 下载数据库,并使用 sqlite3 连接到它
,并返回一些查询结果。
问题是,当我获取完全相同的代码并将其放入 AWS Lambda 中时,出现以下错误:
{
"errorMessage": "malformed database schema (message_idx_undelivered_one_to_one_imessage) - near \"where\": syntax error",
"errorType": "DatabaseError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 11, in lambda_handler\n print(cursor.execute(\"select mycolumn from message limit 1\").fetchone())\n"
]
}
这是 python 脚本/Lambda 函数:
import sqlite3
import boto3
def lambda_handler(event, context):
s3 = boto3.resource("s3")
bucket = s3.Bucket("my-bucket")
bucket.download_file("my_database.db", "/tmp/my_database.db")
conn = sqlite3.connect("/tmp/my_database.db")
cursor = conn.cursor()
print(cursor.execute("select mycolumn from message limit 1").fetchone())
在本地运行此文件可以正常工作。我已确认我的本地环境和 Lambda 正在使用以下版本:
boto3: 1.20.32
python: 3.9.13
sqlite3: 2.6.0
Here是我正在尝试读取的数据库的架构。
为什么 Lambda 会产生此错误,而我的本地环境却不会?如何让 python 在 Lambda 函数中连接到数据库?
最佳答案
来自pastebin的摘录是你的数据库模式中的DDL,它在打开数据库时触发你的错误
CREATE INDEX message_idx_undelivered_one_to_one_imessage
ON message(
cache_roomnames,
service,
is_sent,
is_delivered,
was_downgraded,
item_type
) where cache_roomnames IS NULL
AND service = 'iMessage'
AND is_sent = 1
AND is_delivered = 0
AND was_downgraded = 0
AND item_type == 0;
从3.8.0版本开始,sqlite就集成了部分索引功能https://www.sqlite.org/partialindex.html 。 lambda 环境中的 sqlite3 版本可能太旧,无法处理这样的模式之王。 lambda 环境中 sqlite3 依赖项的版本提升应该可以解决您的问题。
关于python - AWS Lambda 函数无法连接到 S3 并查询 SQLite 数据库文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75311321/