Path: blob/main/resources/init_db.py
469 views
#!/usr/bin/env python1# type: ignore2from __future__ import annotations34import os5import sys6import time7import uuid8from optparse import OptionParser910import singlestoredb as s2111213# Handle command-line options14usage = 'usage: %prog [options] sql-file'15parser = OptionParser(usage=usage, add_help_option=False)16parser.add_option(17'-h', '--host', default='127.0.0.1',18help='database hostname or IP address',19)20parser.add_option(21'-P', '--port', type='int', default=3306,22help='database port',23)24parser.add_option(25'--password',26help='user password',27)28parser.add_option(29'-u', '--user',30help='username',31)32parser.add_option(33'-d', '--database',34help='database name to use',35)36parser.add_option(37'-H', '--http-port', type='int',38help='enable HTTP API on given port',39)40parser.add_option(41'--help',42help='display usage information',43)4445(options, args) = parser.parse_args()4647if len(args) != 1 or options.help:48parser.print_help()49sys.exit(1)5051sql_file = args[0]52if sql_file and not os.path.isfile(sql_file):53print('ERROR: Could not locate SQL file: {sql_file}', file=sys.stderr)54sys.exit(1)5556database = options.database57if not database:58database = 'TEMP_{}'.format(uuid.uuid4()).replace('-', '_')5960tries = 2561while True:6263try:64with s2.connect(65f'mysql://{options.host}:{options.port}',66user=options.user, password=options.password,67) as conn:68with conn.cursor() as cur:69try:70cur.execute('SET GLOBAL default_partitions_per_leaf=2')71cur.execute('SET GLOBAL log_file_size_partitions=1048576')72cur.execute('SET GLOBAL log_file_size_ref_dbs=1048576')73except s2.OperationalError:74pass75cur.execute(f'CREATE DATABASE IF NOT EXISTS {database};')76cur.execute(f'USE {database};')77if options.http_port:78conn.enable_data_api(int(options.http_port))79with open(sql_file, 'r') as infile:80for cmd in infile.read().split(';\n'):81cmd = cmd.strip()82if cmd:83cmd += ';'84cur.execute(cmd)85break8687except Exception as exc:88print(f'WARNING: {exc}')89time.sleep(30)90tries -= 191if tries < 0:92raise939495