Ejemplo n.º 1
0
    def __init__(self, database_name='', SQLITE_ROOT='', pragmas=None, **argv):
        """Initialize an instance of Connection.

        Parameters:
        
            database_name: The name of the Sqlite database. This is generally the file name
            SQLITE_ROOT: The path to the directory holding the database. Joining "SQLITE_ROOT" with
              "database_name" results in the full path to the sqlite file.
            pragmas: Any pragma statements, in the form of a dictionary.
            timeout: The amount of time, in seconds, to wait for a lock to be released. 
              Optional. Default is 5.
            isolation_level: The type of isolation level to use. One of None, 
              DEFERRED, IMMEDIATE, or EXCLUSIVE. Default is None (autocommit mode).
            
        If the operation fails, an exception of type weedb.OperationalError will be raised.
        """

        self.file_path = get_filepath(SQLITE_ROOT, database_name, **argv)
        if not os.path.exists(self.file_path):
            raise weedb.OperationalError("Attempt to open a non-existent database %s" % self.file_path)
        timeout = to_int(argv.get('timeout', 5))
        isolation_level = argv.get('isolation_level')
        try:
            connection = sqlite3.connect(self.file_path, timeout=timeout, isolation_level=isolation_level)
        except sqlite3.OperationalError:
            # The Pysqlite driver does not include the database file path.
            # Include it in case it might be useful.
            raise weedb.OperationalError("Unable to open database '%s'" % (self.file_path,))

        if pragmas is not None:
            for pragma in pragmas:
                connection.execute("PRAGMA %s=%s;" % (pragma, pragmas[pragma]))
        weedb.Connection.__init__(self, connection, database_name, 'sqlite')
Ejemplo n.º 2
0
Archivo: mysql.py Proyecto: jof/weewx
def drop(host='localhost',
         user='',
         password='',
         database_name='',
         driver='',
         port=3306,
         engine=DEFAULT_ENGINE,
         **kwargs):
    """Drop (delete) the specified database."""
    # Open up a connection
    try:
        connect = MySQLdb.connect(host=host,
                                  user=user,
                                  passwd=password,
                                  port=int(port),
                                  **kwargs)
        cursor = connect.cursor()
        try:
            cursor.execute("DROP DATABASE %s" % database_name)
        except _mysql_exceptions.OperationalError:
            raise weedb.NoDatabase(
                """Attempt to drop non-existent database %s""" %
                (database_name, ))
        finally:
            cursor.close()
    except _mysql_exceptions.OperationalError, e:
        raise weedb.OperationalError(e)
Ejemplo n.º 3
0
Archivo: mysql.py Proyecto: jof/weewx
def create(host='localhost',
           user='',
           password='',
           database_name='',
           driver='',
           port=3306,
           engine=DEFAULT_ENGINE,
           **kwargs):
    """Create the specified database. If it already exists,
    an exception of type weedb.DatabaseExists will be thrown."""
    # Open up a connection w/o specifying the database.
    try:
        connect = MySQLdb.connect(host=host,
                                  user=user,
                                  passwd=password,
                                  port=int(port),
                                  **kwargs)
        set_engine(connect, engine)
        cursor = connect.cursor()
        # An exception will get thrown if the database already exists.
        try:
            # Now create the database.
            cursor.execute("CREATE DATABASE %s" % (database_name, ))
        except _mysql_exceptions.ProgrammingError:
            # The database already exists. Change the type of exception.
            raise weedb.DatabaseExists("Database %s already exists" %
                                       (database_name, ))
        finally:
            cursor.close()
    except _mysql_exceptions.OperationalError, e:
        raise weedb.OperationalError(e)
Ejemplo n.º 4
0
Archivo: mysql.py Proyecto: jof/weewx
    def __init__(self,
                 host='localhost',
                 user='',
                 password='',
                 database_name='',
                 port=3306,
                 engine=DEFAULT_ENGINE,
                 **kwargs):
        """Initialize an instance of Connection.

        Parameters:
        
            host: IP or hostname with the mysql database (required)
            user: User name (required)
            password: The password for the username (required)
            database_name: The database to be used. (required)
            port: Its port number (optional; default is 3306)
            engine: The MySQL database engine to use (optional; default is 'INNODB')
            kwargs:   Any extra arguments you may wish to pass on to MySQL (optional)
            
        If the operation fails, an exception of type weedb.OperationalError will be raised.
        """
        try:
            connection = MySQLdb.connect(host=host,
                                         user=user,
                                         passwd=password,
                                         db=database_name,
                                         port=int(port),
                                         **kwargs)
        except _mysql_exceptions.OperationalError, e:
            # The MySQL driver does not include the database in the
            # exception information. Tack it on, in case it might be useful.
            raise weedb.OperationalError(
                str(e) + " while opening database '%s'" % (database_name, ))
Ejemplo n.º 5
0
def guard(fn):
    """Decorator function that converts sqlite exceptions into weedb exceptions."""
    def guarded_fn(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except sqlite3.IntegrityError, e:
            raise weedb.IntegrityError(e)
        except sqlite3.OperationalError, e:
            # Change no such table errors into a ProgrammingError
            # (this is what MySQL does).
            if e.message.lower().startswith("no such table"):
                raise weedb.ProgrammingError(e)
            raise weedb.OperationalError(e)
Ejemplo n.º 6
0
 def guarded_fn(*args, **kwargs):
     try:
         return fn(*args, **kwargs)
     except sqlite3.IntegrityError as e:
         raise weedb.IntegrityError(e)
     except sqlite3.OperationalError as e:
         msg = str(e).lower()
         if msg.startswith("unable to open"):
             raise weedb.PermissionError(e)
         elif msg.startswith("no such table"):
             raise weedb.NoTableError(e)
         elif msg.endswith("already exists"):
             raise weedb.TableExistsError(e)
         elif msg.startswith("no such column"):
             raise weedb.NoColumnError(e)
         else:
             raise weedb.OperationalError(e)
     except sqlite3.ProgrammingError as e:
         raise weedb.ProgrammingError(e)
Ejemplo n.º 7
0
def guard(fn):
    """Decorator function that converts sqlite exceptions into weedb exceptions."""
    def guarded_fn(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except sqlite3.IntegrityError, e:
            raise weedb.IntegrityError(e)
        except sqlite3.OperationalError, e:
            msg = str(e).lower()
            if msg.startswith("unable to open"):
                raise weedb.PermissionError(e)
            elif msg.startswith("no such table"):
                raise weedb.NoTableError(e)
            elif msg.endswith("already exists"):
                raise weedb.TableExistsError(e)
            elif msg.startswith("no such column"):
                raise weedb.NoColumnError(e)
            else:
                raise weedb.OperationalError(e)
Ejemplo n.º 8
0
from weeutil.weeutil import to_bool
import weedb


def guard(fn):
    """Decorator function that converts MySQL exceptions into weedb exceptions."""

    def guarded_fn(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except _mysql_exceptions.IntegrityError, e:
            raise weedb.IntegrityError(e)
        except _mysql_exceptions.ProgrammingError, e:
            raise weedb.ProgrammingError(e)
        except _mysql_exceptions.OperationalError, e:
            raise weedb.OperationalError(e)

    return guarded_fn


def connect(host='localhost', user='', password='', database_name='', driver='', port=3306, **kwargs):
    """Connect to the specified database"""
    return Connection(host=host, user=user, password=password, 
                      database_name=database_name, port=int(port), **kwargs)


def create(host='localhost', user='', password='', database_name='', driver='', port=3306, **kwargs):
    """Create the specified database. If it already exists,
    an exception of type weedb.DatabaseExists will be thrown."""
    # Open up a connection w/o specifying the database.
    try: