Skip to content

Commit

Permalink
Replace file descriptor with file-like object
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-slac committed May 8, 2017
1 parent 325a5aa commit 31e008a
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions python/lsst/db/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
@author Jacek Becla, SLAC
"""
from builtins import object

from __future__ import print_function
from builtins import object

# standard library
import logging as log
Expand Down Expand Up @@ -400,38 +401,40 @@ def loadSqlScript(conn, script, dbName=None):
url = conn.engine.url
if url.get_backend_name() == "mysql":

# check file, if it has 'read' attribute assume it's a file object
# check file, if it has 'read' attribute assume it's a file object,
# otherwise assume it's file name, open it and close later.
cleanup = None
if not hasattr(script, 'read'):
script = open(script)
cleanup = script.close

# make tmpfile to store credentials and options
fd, fname = tempfile.mkstemp(text=True)
# write credentials and options to a temporary file, we have to
# close it but will delete it after mysql finishes.
cfg = tempfile.NamedTemporaryFile("w", delete=False)
fname = cfg.name

os.write(fd, b"[client]\n")
os.write(fd, b"batch\n")
os.write(fd, b"quick\n")
print("[client]", file=cfg)
print("batch", file=cfg)
print("quick", file=cfg)

# convert to UTF-8 if there are unicode chars, hope mysql can read it
encoding = "utf-8"
if url.host:
os.write(fd, 'host={}\n'.format(url.host).encode(encoding))
print('host={}'.format(url.host), file=cfg)
if url.port:
os.write(fd, 'port={}\n'.format(url.port).encode(encoding))
print('port={}'.format(url.port), file=cfg)
socket = url.query.get('unix_socket')
if socket:
os.write(fd, 'socket="{}"\n'.format(socket).encode(encoding))
print('socket="{}"'.format(socket), file=cfg)
if url.username:
os.write(fd, 'user="{}"\n'.format(url.username).encode(encoding))
print('user="{}"'.format(url.username), file=cfg)
if url.password:
os.write(fd, 'password="{}"\n'.format(url.password).encode(encoding))
print('password="{}"'.format(url.password), file=cfg)
if not dbName:
dbName = url.database
if dbName:
os.write(fd, 'database={}'.format(dbName).encode(encoding))
print('database={}'.format(dbName), file=cfg)
# not all platforms can read file while it's open
os.close(fd)
cfg.close()

# build command line, use the options file above
try:
Expand Down

0 comments on commit 31e008a

Please sign in to comment.