Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/singlestoredb/alchemy/__init__.py
469 views
1
#!/usr/bin/env python3
2
import inspect
3
from typing import Any
4
from urllib.parse import quote
5
6
try:
7
import sqlalchemy
8
from sqlalchemy_singlestoredb import * # noqa: F403, F401
9
has_sqlalchemy = True
10
except ImportError:
11
import warnings
12
warnings.warn(
13
'sqlalchemy_singlestoredb must be installed to use this module',
14
RuntimeWarning,
15
)
16
has_sqlalchemy = False
17
18
from ..connection import build_params
19
from ..connection import connect
20
21
22
def create_engine(*args: Any, **kwargs: Any) -> Any:
23
"""
24
Create an SQLAlchemy engine for SingleStoreDB.
25
26
Parameters
27
----------
28
**kwargs : Any
29
The parameters taken here are the same as for
30
`sqlalchemy.create_engine`. However, this function can be
31
called without any parameters in order to inherit parameters
32
set by environment variables or parameters set in by
33
options in Python code.
34
35
See Also
36
--------
37
`sqlalchemy.create_engine`
38
39
Returns
40
-------
41
SQLAlchemy engine
42
43
"""
44
if not has_sqlalchemy:
45
raise RuntimeError('sqlalchemy_singlestoredb package is not installed')
46
47
if len(args) > 1:
48
raise ValueError(
49
'`args` can only have a single element '
50
'containing the database URL',
51
)
52
53
if args:
54
kwargs['host'] = args[0]
55
56
conn_params = {}
57
sa_params = {}
58
59
conn_args = inspect.getfullargspec(connect).args
60
61
for key, value in kwargs.items():
62
if key in conn_args:
63
conn_params[key] = value
64
else:
65
sa_params[key] = value
66
67
params = build_params(**conn_params)
68
driver = params.pop('driver', None)
69
host = params.pop('host')
70
port = params.pop('port')
71
user = params.pop('user', None)
72
password = params.pop('password', None)
73
database = params.pop('database', '')
74
75
if not driver:
76
driver = 'singlestoredb+mysql'
77
elif not driver.startswith('singlestoredb'):
78
driver = f'singlestoredb+{driver}'
79
80
if user is not None and password is not None:
81
url = f'{driver}://{quote(user)}:{quote(password)}@' \
82
f'{host}:{port}/{quote(database)}'
83
elif user is not None:
84
url = f'{driver}://{quote(user)}@{host}:{port}/{quote(database)}'
85
elif password is not None:
86
url = f'{driver}://:{quote(password)}@{host}:{port}/{quote(database)}'
87
else:
88
url = f'{driver}://{host}:{port}/{quote(database)}'
89
90
return sqlalchemy.create_engine(url, connect_args=params, **sa_params)
91
92