正如其他答案所示,您可能不想将 SQLite 用作云中的主数据库。
但是,作为一个有趣的项目的一部分,我编写了一个 Amazon Athena 数据源连接器,允许您查询 SQLite databases in S3 from Athena。为此,我为 S3 编写了一个只读 SQLite 接口。
SQLite 有一个OS Interface or VFS 的概念。使用名为 APSW 的 Python SQLite 包装器,您可以为任意文件系统编写 VFS 实现。这就是我在我的项目中所做的,我在下面包含了实现。
为了使用它,你首先要注册 VFS,然后用这个实现创建一个新的 SQLite 连接作为驱动程序。
我应该注意到这根本没有优化,因此可能仍需要根据您的查询从 S3 读取完整的数据库。但在这种特定情况下听起来不是问题。
S3FS = S3VFS() # S3VFS defined below
# This odd format is used due to SQLite requirements
sqlite_uri = "file:/{}/{}.sqlite?bucket={}&immutable=1".format(
S3_PREFIX,
DATABASE_NAME,
S3_BUCKET
)
connection = apsw.Connection(sqlite_uri,
flags=apsw.SQLITE_OPEN_READONLY | apsw.SQLITE_OPEN_URI,
vfs=S3FS.vfsname
)
cursor = connection.cursor()
一旦有了游标,就可以像这样执行标准 SQL 语句:
for x,y,z in cursor.execute("select x,y,z from foo"):
print (cursor.getdescription()) # shows column names and declared types
print (x,y,z)
VFS 实现(需要 APSW 库和 boto3 以实现 S3 连接)
import apsw
import sys
import boto3
VFS_S3_CLIENT = boto3.client('s3')
class S3VFS(apsw.VFS):
def __init__(self, vfsname="s3", basevfs=""):
self.vfsname=vfsname
self.basevfs=basevfs
apsw.VFS.__init__(self, self.vfsname, self.basevfs)
def xOpen(self, name, flags):
return S3VFSFile(self.basevfs, name, flags)
class S3VFSFile():
def __init__(self, inheritfromvfsname, filename, flags):
self.bucket = filename.uri_parameter("bucket")
self.key = filename.filename().lstrip("/")
print("Initiated S3 VFS for file: {}".format(self._get_s3_url()))
def xRead(self, amount, offset):
response = VFS_S3_CLIENT.get_object(Bucket=self.bucket, Key=self.key, Range='bytes={}-{}'.format(offset, offset + amount))
response_data = response['Body'].read()
return response_data
def xFileSize(self):
client = boto3.client('s3')
response = client.head_object( Bucket=self.bucket, Key=self.key)
return response['ContentLength']
def xClose(self):
pass
def xFileControl(self, op, ptr):
return False
def _get_s3_url(self):
return "s3://{}/{}".format(self.bucket, self.key)