def map_to(self,
               attrname,
               tablename=None,
               selectable=None,
               schema=None,
               base=None,
               mapper_args=util.immutabledict()):

        if attrname in self._cache:
            raise AttributeError('Attibute {} is already mapped to {}'.format(
                attrname,
                class_mapper(self._cache[attrname]).mapped_table))

        if tablename is not None:
            if not isinstance(tablename, str):
                raise ArgumentError(
                    'Tablename must be a string, type found: {}'.format(
                        type(tablename)))

            if selectable is not None:
                raise ArgumentError(
                    '`tablename` and `selectable` are mutually exclusive')

            selectable = Table(tablename,
                               self.metadata,
                               autoload=True,
                               autoload_with=self.bind,
                               schema=schema or self.schema)
        elif schema:
            raise ArgumentError(
                '`tablename` argument is required when using schema.')

        elif selectable is not None:
            if not isinstance(selectable, expression.FromClause):
                raise ArgumentError('`selectable` argument must be a table,'
                                    'select, joing, or other construct.')

        else:
            raise ArgumentError(
                '`tablename` or `selectable` argument is required.')

        if not selectable.primary_key.columns and not \
            'primary_key' in mapper_args:

            if tablename:
                raise NoForeignKeysError(
                    'table {} does not have a primary key defined'.format(
                        tablename))
            else:
                raise NoForeignKeysError(
                    'Selectable {} does not have a primary key defined.'.
                    format(selectable))

        mapped_cls = class_for_table(self.sess, self.engine, selectable, base
                                     or self.base, mapper_args)

        self._cache[attrname] = mapped_cls
        return mapped_cls
Exemple #2
0
def recieve_chat_init(target, args, kwargs):
    chat_name = kwargs.get('name')
    if not chat_name:
        raise ArgumentError("Missing chat name")
    chat = Chat.query.filter_by(name=chat_name).first()
    if chat:
        raise ArgumentError("Chat name must be an unique")
    users = kwargs['users']
    for user in users:
        user = User.query.get(user.id)
        if not user:
            raise ArgumentError("User not found")
    return kwargs
    def new(uri, reinitialize=False, echo=False):
        """
        Factory method for instantiating a database object from a URI. For URI
        specifications, see SQLiteDatabase, PostgreSQLDatabase.

        :param echo: echo SQL commands to the console as they are executed by SQLAlchemy.
        :param reinitialize: drop all tables before (re)creating them
        :param uri: an RFC 3986 URI pointing to the database
        :return: An initialized database object or raise an ArgumentError if the
        URI was not recognizable.
        """
        if uri.startswith('postgresql+psycopg2://'):
            return PostgreSQLDatabase(uri=uri,
                                      reinitialize=reinitialize,
                                      echo=echo)
        if uri.startswith('postgresql://'):
            return PostgreSQLDatabase(uri=uri,
                                      reinitialize=reinitialize,
                                      echo=echo)
        elif uri.startswith('sqlite://'):
            return SQLiteDatabase(uri=uri,
                                  reinitialize=reinitialize,
                                  echo=echo)
        else:
            raise ArgumentError(
                'database URI ({}) not recognized.'.format(uri))
Exemple #4
0
    def __init__(self, engine_or_metadata, base=object, session=None):
        """Initialize a new :class:`.SqlSoup`.

        :param engine_or_metadata: a string database URL, :class:`.Engine`
          or :class:`.MetaData` object to associate with. If the
          argument is a :class:`.MetaData`, it should be *bound*
          to an :class:`.Engine`.
        :param base: a class which will serve as the default class for
          returned mapped classes.  Defaults to ``object``.
        :param session: a :class:`.ScopedSession` or :class:`.Session` with
          which to associate ORM operations for this :class:`.SqlSoup` instance.
          If ``None``, a :class:`.ScopedSession` that's local to this
          module is used.

        """

        self.session = session or Session
        self.base=base

        if isinstance(engine_or_metadata, MetaData):
            self._metadata = engine_or_metadata
        elif isinstance(engine_or_metadata, (basestring, Engine)):
            self._metadata = MetaData(engine_or_metadata)
        else:
            raise ArgumentError("invalid engine or metadata argument %r" %
                                engine_or_metadata)

        self._cache = {}
        self.schema = None
 def __init__(self, user_id):
     if WBUserModel.query.filter_by(id=user_id).count() > 0:
         self.session_id = binascii.hexlify(
             os.urandom(self.session_id_byte_length))
         self.secret = binascii.hexlify(os.urandom(self.secret_byte_length))
         self.user_id = user_id
         self.created = arrow.utcnow()
         self.accessed = self.created
     else:
         raise ArgumentError('Unknown user id')
Exemple #6
0
def create_engine(uri, relative_to=None, debug=False):
    """Create a new engine.  This works a bit like SQLAlchemy's
    `create_engine` with the difference that it automaticaly set's MySQL
    engines to 'utf-8', and paths for SQLite are relative to the path
    provided as `relative_to`.

    Furthermore the engine is created with `convert_unicode` by default.
    """
    # special case sqlite.  We want nicer urls for that one.
    if uri.startswith('sqlite:'):
        match = _sqlite_re.match(uri)
        if match is None:
            raise ArgumentError('Could not parse rfc1738 URL')
        database, query = match.groups()
        if database is None:
            database = ':memory:'
        elif relative_to is not None:
            database = path.join(relative_to, database)
        if query:
            query = url_decode(query).to_dict()
        else:
            query = {}
        info = URL('sqlite', database=database, query=query)

    else:
        info = make_url(uri)

        # if mysql is the database engine and no connection encoding is
        # provided we set it to utf-8
        if info.drivername == 'mysql':
            info.query.setdefault('charset', 'utf8')

    options = {'convert_unicode': True}

    # alternative pool sizes / recycle settings and more.  These are
    # interpreter wide and not from the config for the following reasons:
    #
    # - system administrators can set it independently from the webserver
    #   configuration via SetEnv and friends.
    # - this setting is deployment dependent should not affect a development
    #   server for the same instance or a development shell
    for key in 'pool_size', 'pool_recycle', 'pool_timeout':
        value = os.environ.get('ZINE_DATABASE_' + key.upper())
        if value is not None:
            options[key] = int(value)

    # if debugging is enabled, hook the ConnectionDebugProxy in
    if debug:
        options['proxy'] = ConnectionDebugProxy()

    return sqlalchemy.create_engine(info, **options)
Exemple #7
0
 def set_isolation_level(self, connection, level):
     if level is None:
         level = 'CS'
     else:
         if len(level.strip()) < 1:
             level = 'CS'
     level = level.upper().replace("-", " ").replace("_", " ")
     if level not in self._isolation_lookup:
         raise ArgumentError(
             "Invalid value '%s' for isolation_level. "
             "Valid isolation levels for %s are %s" %
             (level, self.name, ", ".join(self._isolation_lookup)))
     attrib = {
         SQL_ATTR_TXN_ISOLATION: self._get_cli_isolation_levels(level)
     }
     res = connection.set_option(attrib)
Exemple #8
0
 def set_isolation_level(self, connection, level):
     if level is None:
         level = 'CS'
     else:
         if len(level.strip()) < 1:
             level = 'CS'
     level.upper().replace("-", " ")
     if level not in self._isolation_lookup:
         raise ArgumentError(
             "Invalid value '%s' for isolation_level. "
             "Valid isolation levels for %s are %s" %
             (level, self.name, ", ".join(self._isolation_lookup)))
     cursor = connection.cursor()
     cursor.execute("SET CURRENT ISOLATION %s" % level)
     cursor.execute("COMMIT")
     cursor.close()
Exemple #9
0
    def database_url(cls):
        """Find the database URL configured for this site.

        For compatibility with old configurations, we will look in the
        site configuration first.

        If it's not there, we will look in the appropriate environment
        variable.
        """

        # To avoid expensive mistakes, test and production databases
        # are always configured with separate keys. The TESTING variable
        # controls which database is used, and it's set by the
        # package_setup() function called in every component's
        # tests/__init__.py.
        test = os.environ.get("TESTING", False)
        if test:
            config_key = cls.DATABASE_TEST_URL
            environment_variable = cls.DATABASE_TEST_ENVIRONMENT_VARIABLE
        else:
            config_key = cls.DATABASE_PRODUCTION_URL
            environment_variable = cls.DATABASE_PRODUCTION_ENVIRONMENT_VARIABLE

        url = os.environ.get(environment_variable)
        if not url:
            raise CannotLoadConfiguration(
                "Database URL was not defined in environment variable (%s)."
                % environment_variable
            )

        url_obj = None
        try:
            url_obj = make_url(url)
        except ArgumentError as e:
            # Improve the error message by giving a guide as to what's
            # likely to work.
            raise ArgumentError(
                "Bad format for database URL (%s). Expected something like postgres://[username]:[password]@[hostname]:[port]/[database name]"
                % url
            )

        # Calling __to_string__ will hide the password.
        logging.info("Connecting to database: %s" % url_obj.__to_string__())
        return url
Exemple #10
0
    def database_url(cls, test=False):
        """Find the database URL configured for this site.

        For compatibility with old configurations, we will look in the
        site configuration first.

        If it's not there, we will look in the appropriate environment
        variable.
        """
        # To avoid expensive mistakes, test and production databases
        # are always configured with separate keys.
        if test:
            config_key = cls.DATABASE_TEST_URL
            environment_variable = cls.DATABASE_TEST_ENVIRONMENT_VARIABLE
        else:
            config_key = cls.DATABASE_PRODUCTION_URL
            environment_variable = cls.DATABASE_PRODUCTION_ENVIRONMENT_VARIABLE

        # Check the legacy location (the config file) first.
        url = None
        database_integration = cls.integration(cls.DATABASE_INTEGRATION)
        if database_integration:
            url = database_integration.get(config_key)

        # If that didn't work, check the new location (the environment
        # variable).
        if not url:
            url = os.environ.get(environment_variable)
        if not url:
            raise CannotLoadConfiguration(
                "Database URL was not defined in environment variable (%s) or configuration file."
                % environment_variable)

        url_obj = None
        try:
            url_obj = make_url(url)
        except ArgumentError, e:
            # Improve the error message by giving a guide as to what's
            # likely to work.
            raise ArgumentError(
                "Bad format for database URL (%s). Expected something like postgres://[username]:[password]@[hostname]:[port]/[database name]"
                % url)
Exemple #11
0
 def set_isolation_level(self, connection, level):
     """
     Set the connection to a given isolation level
     :param connection: pyODBC connection
     :param level: the new level to set isolation to
     """
     if level is None:
         level = 'CS'
     else:
         if len(level.strip()) < 1:
             level = 'CS'
     level.upper().replace("-", " ")
     if level not in self._isolation_lookup:
         raise ArgumentError(
             "Invalid value '%s' for isolation_level. "
             "Valid isolation levels for %s are %s" %
             (level, self.name, ", ".join(self._isolation_lookup)))
     attrib = {
         SQL_ATTR_TXN_ISOLATION: _get_cli_isolation_levels(self, level)
     }
     res = connection.set_option(attrib)
Exemple #12
0
    def map_to(self, attrname, tablename=None, selectable=None,
                    schema=None, base=None, mapper_args=util.immutabledict()):
        """Configure a mapping to the given attrname.

        This is the "master" method that can be used to create any
        configuration.

        .. versionadded:: 0.6.6

        :param attrname: String attribute name which will be
          established as an attribute on this :class:.`.SqlSoup`
          instance.
        :param base: a Python class which will be used as the
          base for the mapped class. If ``None``, the "base"
          argument specified by this :class:`.SqlSoup`
          instance's constructor will be used, which defaults to
          ``object``.
        :param mapper_args: Dictionary of arguments which will
          be passed directly to :func:`.orm.mapper`.
        :param tablename: String name of a :class:`.Table` to be
          reflected. If a :class:`.Table` is already available,
          use the ``selectable`` argument. This argument is
          mutually exclusive versus the ``selectable`` argument.
        :param selectable: a :class:`.Table`, :class:`.Join`, or
          :class:`.Select` object which will be mapped. This
          argument is mutually exclusive versus the ``tablename``
          argument.
        :param schema: String schema name to use if the
          ``tablename`` argument is present.


        """
        if attrname in self._cache:
            raise InvalidRequestError(
                "Attribute '%s' is already mapped to '%s'" % (
                attrname,
                class_mapper(self._cache[attrname]).mapped_table
            ))

        if tablename is not None:
            if not isinstance(tablename, basestring):
                raise ArgumentError("'tablename' argument must be a string."
                                    )
            if selectable is not None:
                raise ArgumentError("'tablename' and 'selectable' "
                                    "arguments are mutually exclusive")

            selectable = Table(tablename,
                                        self._metadata,
                                        autoload=True,
                                        autoload_with=self.bind,
                                        schema=schema or self.schema)
        elif schema:
            raise ArgumentError("'tablename' argument is required when "
                                "using 'schema'.")
        elif selectable is not None:
            if not isinstance(selectable, expression.FromClause):
                raise ArgumentError("'selectable' argument must be a "
                                    "table, select, join, or other "
                                    "selectable construct.")
        else:
            raise ArgumentError("'tablename' or 'selectable' argument is "
                                    "required.")

        if not selectable.primary_key.columns:
            if tablename:
                raise PKNotFoundError(
                            "table '%s' does not have a primary "
                            "key defined" % tablename)
            else:
                raise PKNotFoundError(
                            "selectable '%s' does not have a primary "
                            "key defined" % selectable)

        mapped_cls = _class_for_table(
            self.session,
            self.engine,
            selectable,
            base or self.base,
            mapper_args
        )
        self._cache[attrname] = mapped_cls
        return mapped_cls
Exemple #13
0
def recieve_message_init(target, args, kwargs):
    author, chat = kwargs['author'], kwargs['chat']
    if author in chat.users:
        return kwargs
    else:
        raise ArgumentError("author must be in a chat")
Exemple #14
0
 def validate_barcode(self, key, value):
     max_len = getattr(self.__class__, key).prop.columns[0].type.length
     if value and len(value) > max_len:
         raise ArgumentError('"barcode" value is too long')
     return value