예제 #1
0
def normalize_url(raw):
    """
    Build a URL from a string according to obvious rules.

    Converts *.sqlite paths to sqlite:/// URLs, etc.

    >>> str(normalize_url("/tmp/foo.sqlite"))
    'sqlite:////tmp/foo.sqlite'
    >>> str(normalize_url("postgresql://user@host/database"))
    'postgresql://user@host/database'
    """

    from sqlalchemy.engine.url import make_url
    from sqlalchemy.exceptions import ArgumentError

    try:
        return make_url(raw)
    except ArgumentError:
        from os.path import (
            abspath,
            splitext,
            )

        (root, extension) = splitext(raw)

        if extension == ".sqlite":
            return make_url("sqlite:///%s" % abspath(raw))
        else:
            raise ArgumentError("could not parse supposed URL \"%s\"" % raw)
예제 #2
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
예제 #3
0
    def __init__(self, *columns, **kwargs):
        """The list of `columns` describes a single object
        property. If there are multiple tables joined together for the
        mapper, this list represents the equivalent column as it
        appears across each table.
        """

        self.columns = list(columns)
        self.group = kwargs.pop('group', None)
        self.deferred = kwargs.pop('deferred', False)
        self.comparator = ColumnProperty.ColumnComparator(self)
        # sanity check
        for col in columns:
            if not hasattr(col, 'name'):
                if hasattr(col, 'label'):
                    raise ArgumentError(
                        'ColumnProperties must be named for the mapper to work with them.  Try .label() to fix this'
                    )
                raise ArgumentError(
                    '%r is not a valid candidate for ColumnProperty' % col)
예제 #4
0
    def __init__(self, *columns, **kwargs):
        """The list of `columns` describes a single object
        property. If there are multiple tables joined together for the
        mapper, this list represents the equivalent column as it
        appears across each table.
        """

        self.columns = list(columns)
        self.group = kwargs.pop('group', None)
        self.deferred = kwargs.pop('deferred', False)
        self.comparator = ColumnProperty.ColumnComparator(self)
        if self.deferred:
            self.strategy_class = strategies.DeferredColumnLoader
        else:
            self.strategy_class = strategies.ColumnLoader
        # sanity check
        for col in columns:
            if not isinstance(col, ColumnElement):
                raise ArgumentError('column_property() must be given a ColumnElement as its argument.  Try .label() or .as_scalar() for Selectables to fix this.')
예제 #5
0
    def __init__(self, engine_or_metadata, base=object, **kw):
        """Initialize a new ``SqlSoup``.

        `base` is the class that all created entity classes should subclass.

        `args` may either be an ``SQLEngine`` or a set of arguments
        suitable for passing to ``create_engine``.
        """

        self.session = kw.pop('session', 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
예제 #6
0
    def map_to(self,
               attrname,
               tablename=None,
               selectable=None,
               schema=None,
               base=None,
               mapper_args=util.frozendict()):
        """Configure a mapping to the given attrname.

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

        (new in 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