Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/resources/init_db.py
469 views
1
#!/usr/bin/env python
2
# type: ignore
3
from __future__ import annotations
4
5
import os
6
import sys
7
import time
8
import uuid
9
from optparse import OptionParser
10
11
import singlestoredb as s2
12
13
14
# Handle command-line options
15
usage = 'usage: %prog [options] sql-file'
16
parser = OptionParser(usage=usage, add_help_option=False)
17
parser.add_option(
18
'-h', '--host', default='127.0.0.1',
19
help='database hostname or IP address',
20
)
21
parser.add_option(
22
'-P', '--port', type='int', default=3306,
23
help='database port',
24
)
25
parser.add_option(
26
'--password',
27
help='user password',
28
)
29
parser.add_option(
30
'-u', '--user',
31
help='username',
32
)
33
parser.add_option(
34
'-d', '--database',
35
help='database name to use',
36
)
37
parser.add_option(
38
'-H', '--http-port', type='int',
39
help='enable HTTP API on given port',
40
)
41
parser.add_option(
42
'--help',
43
help='display usage information',
44
)
45
46
(options, args) = parser.parse_args()
47
48
if len(args) != 1 or options.help:
49
parser.print_help()
50
sys.exit(1)
51
52
sql_file = args[0]
53
if sql_file and not os.path.isfile(sql_file):
54
print('ERROR: Could not locate SQL file: {sql_file}', file=sys.stderr)
55
sys.exit(1)
56
57
database = options.database
58
if not database:
59
database = 'TEMP_{}'.format(uuid.uuid4()).replace('-', '_')
60
61
tries = 25
62
while True:
63
64
try:
65
with s2.connect(
66
f'mysql://{options.host}:{options.port}',
67
user=options.user, password=options.password,
68
) as conn:
69
with conn.cursor() as cur:
70
try:
71
cur.execute('SET GLOBAL default_partitions_per_leaf=2')
72
cur.execute('SET GLOBAL log_file_size_partitions=1048576')
73
cur.execute('SET GLOBAL log_file_size_ref_dbs=1048576')
74
except s2.OperationalError:
75
pass
76
cur.execute(f'CREATE DATABASE IF NOT EXISTS {database};')
77
cur.execute(f'USE {database};')
78
if options.http_port:
79
conn.enable_data_api(int(options.http_port))
80
with open(sql_file, 'r') as infile:
81
for cmd in infile.read().split(';\n'):
82
cmd = cmd.strip()
83
if cmd:
84
cmd += ';'
85
cur.execute(cmd)
86
break
87
88
except Exception as exc:
89
print(f'WARNING: {exc}')
90
time.sleep(30)
91
tries -= 1
92
if tries < 0:
93
raise
94
95