예제 #1
0
def _class_for_table(session,
                     engine,
                     selectable,
                     base_cls=object,
                     **mapper_kwargs):
    selectable = expression._clause_element_as_expr(selectable)
    mapname = 'Mapped' + _selectable_name(selectable)
    # Py2K
    if isinstance(mapname, unicode):
        engine_encoding = engine.dialect.encoding
        mapname = mapname.encode(engine_encoding)
    # end Py2K

    if isinstance(selectable, Table):
        klass = TableClassType(mapname, (base_cls, ), {})
    else:
        klass = SelectableClassType(mapname, (base_cls, ), {})

    def _compare(self, o):
        L = list(self.__class__.c.keys())
        L.sort()
        t1 = [getattr(self, k) for k in L]
        try:
            t2 = [getattr(o, k) for k in L]
        except AttributeError:
            raise TypeError('unable to compare with %s' % o.__class__)
        return t1, t2

    # python2/python3 compatible system of
    # __cmp__ - __lt__ + __eq__

    def __lt__(self, o):
        t1, t2 = _compare(self, o)
        return t1 < t2

    def __eq__(self, o):
        t1, t2 = _compare(self, o)
        return t1 == t2

    def __repr__(self):
        L = [
            "%s=%r" % (key, getattr(self, key, ''))
            for key in self.__class__.c.keys()
        ]
        return '%s(%s)' % (self.__class__.__name__, ','.join(L))

    for m in ['__eq__', '__repr__', '__lt__']:
        setattr(klass, m, eval(m))
    klass._table = selectable
    klass.c = expression.ColumnCollection()
    mappr = mapper(klass,
                   selectable,
                   extension=AutoAdd(session),
                   **mapper_kwargs)

    for k in mappr.iterate_properties:
        klass.c[k.key] = k.columns[0]

    klass._query = session.query_property()
    return klass
    def dispatch(event, table, bind):
        if event in ('before-create', 'before-drop'):
            regular_cols = [c for c in table.c if not
                                    isinstance(c.type, Geometry)]
            gis_cols = set(table.c).difference(regular_cols)
            table.info["_saved_columns"] = table.c

            # temporarily patch a set of columns not including the
            # Geometry columns
            table.columns = expression.ColumnCollection(*regular_cols)

            if event == 'before-drop':
                for c in gis_cols:
                    bind.execute(
                            select([
                                func.DropGeometryColumn(
                                    'public', table.name, c.name)],
                                    autocommit=True)
                            )

        elif event == 'after-create':
            table.columns = table.info.pop('_saved_columns')
            for c in table.c:
                if isinstance(c.type, Geometry):
                    bind.execute(
                            select([
                                    func.AddGeometryColumn(
                                        table.name, c.name,
                                        c.type.srid,
                                        c.type.name,
                                        c.type.dimension)],
                                autocommit=True)
                        )
        elif event == 'after-drop':
            table.columns = table.info.pop('_saved_columns')
예제 #3
0
    def __call__(self, event, table, bind):
        spatial_dialect = DialectManager.get_spatial_dialect(bind.dialect)
        if event in ('before-create', 'before-drop'):
            """Remove geometry column from column list (table._columns), so that it 
            does not show up in the create statement ("create table tab (..)"). 
            Afterwards (on event 'after-create') restore the column list from self._stack.
            """
            regular_cols = [
                c for c in table.c if not isinstance(c.type, Geometry)
            ]
            gis_cols = set(table.c).difference(regular_cols)
            self._stack.append(table.c)
            setattr(table, self.columns_attribute,
                    expression.ColumnCollection(*regular_cols))

            if event == 'before-drop':
                for c in gis_cols:
                    spatial_dialect.handle_ddl_before_drop(bind, table, c)

        elif event == 'after-create':
            setattr(table, self.columns_attribute, self._stack.pop())

            for c in table.c:
                if isinstance(c.type, Geometry):
                    spatial_dialect.handle_ddl_after_create(bind, table, c)

        elif event == 'after-drop':
            setattr(table, self.columns_attribute, self._stack.pop())
예제 #4
0
    def __call__(self, event, table, bind):
        if event in ('before-create', 'before-drop'):
            regular_cols = [
                c for c in table.c if not isinstance(c.type, Geometry)
            ]
            gis_cols = set(table.c).difference(regular_cols)
            self._stack.append(table.c)
            table._columns = expression.ColumnCollection(*regular_cols)

            if event == 'before-drop':
                for c in gis_cols:
                    bind.execute(
                        select([
                            func.DropGeometryColumn('public', table.name,
                                                    c.name)
                        ],
                               autocommit=True))

        elif event == 'after-create':
            table._columns = self._stack.pop()

            for c in table.c:
                if isinstance(c.type, Geometry):
                    bind.execute(
                        select([
                            func.AddGeometryColumn(table.name, c.name,
                                                   c.type.srid, c.type.name,
                                                   c.type.dimension)
                        ],
                               autocommit=True))
        elif event == 'after-drop':
            table._columns = self._stack.pop()
예제 #5
0
    def class_for_table(self, selectable, **mapper_kwargs):
        mapname = selectable.name.capitalize()
        klass = TableClassType(mapname, (object, ), {})

        def __cmp__(self, o):
            L = self.__class__.c.keys()
            L.sort()
            t1 = [getattr(self, k) for k in L]
            try:
                t2 = [getattr(o, k) for k in L]
            except AttributeError:
                raise TypeError('unable to compare with %s' % o.__class__)
            return cmp(t1, t2)

        def __repr__(self):
            L = []
            for k in self.__class__.c.keys():
                value = getattr(self, k, '')
                L.append("%s=%r" % (k, value))
            return '%s(%s)' % (self.__class__.__name__, ','.join(L))

        def __unicode__(self):
            L = []
            primary_keys = primary_key_property_names(self)
            special_keys = ["name", "title", "label"]
            keys = [
                k for k in self.__class__.c.keys()
                if k in special_keys or k in primary_keys
            ]
            for k in keys:
                value = getattr(self, k, '')
                L.append("%s=%r" % (k, value))
            return u'%s(%s)' % (self.__class__.__name__, ','.join(L))

        for m in ['__cmp__', '__repr__', "__unicode__"]:
            setattr(klass, m, eval(m))
        klass._table = selectable
        klass.c = expression.ColumnCollection()
        properties = mapper_kwargs.get("properties", {})
        if "properties" in mapper_kwargs:
            del mapper_kwargs["properties"]
        for c in selectable.c:
            if isinstance(c.type, Binary):
                properties[str(c.name)] = deferred(c)
        mappr = mapper(klass,
                       selectable,
                       extension=self._session.extension,
                       allow_null_pks=False,
                       properties=properties,
                       **mapper_kwargs)

        for k in mappr.iterate_properties:
            klass.c[k.key] = k.columns[0]
        return klass
예제 #6
0
def class_for_table(selectable, **mapper_kwargs):
    selectable = expression._selectable(selectable)
    mapname = 'Mapped' + _selectable_name(selectable)
    if isinstance(mapname, unicode):
        engine_encoding = selectable.metadata.bind.dialect.encoding
        mapname = mapname.encode(engine_encoding)
    if isinstance(selectable, Table):
        klass = TableClassType(mapname, (object, ), {})
    else:
        klass = SelectableClassType(mapname, (object, ), {})

    def __cmp__(self, o):
        L = self.__class__.c.keys()
        L.sort()
        t1 = [getattr(self, k) for k in L]
        try:
            t2 = [getattr(o, k) for k in L]
        except AttributeError:
            raise TypeError('unable to compare with %s' % o.__class__)
        return cmp(t1, t2)

    def __repr__(self):
        L = [
            "%s=%r" % (key, getattr(self, key, ''))
            for key in self.__class__.c.keys()
        ]
        return '%s(%s)' % (self.__class__.__name__, ','.join(L))

    for m in ['__cmp__', '__repr__']:
        setattr(klass, m, eval(m))
    klass._table = selectable
    klass.c = expression.ColumnCollection()
    mappr = mapper(klass,
                   selectable,
                   extension=Session.extension,
                   allow_null_pks=_is_outer_join(selectable),
                   **mapper_kwargs)

    for k in mappr.iterate_properties:
        klass.c[k.key] = k.columns[0]

    klass._query = Session.query_property()
    return klass
예제 #7
0
    def dispatch(event, table, bind):
        if event == 'before-create':
            for c in table.c:
                # Add spatial indices for the Geometry and Geography columns
                if isinstance(c.type, (Geometry, Geography)) and \
                        c.type.spatial_index is True:
                    idx_name = 'idx_%s_%s' % (table.name, c.name)
                    get_or_create_GIST_Index(table, idx_name, c)

        if event in ('before-create', 'before-drop'):
            # Filter Geometry columns from the table with management=True
            # Note: Geography and PostGIS >= 2.0 don't need this
            gis_cols = [
                c for c in table.c
                if isinstance(c.type, Geometry) and c.type.management is True
            ]

            # Find all other columns that are not managed Geometries
            regular_cols = [x for x in table.c if x not in gis_cols]

            # Save original table column list for later
            table.info["_saved_columns"] = table.c

            # Temporarily patch a set of columns not including the
            # managed Geometry columns
            column_collection = expression.ColumnCollection()
            for col in regular_cols:
                column_collection.add(col)
            table.columns = column_collection

            if event == 'before-drop':
                # Drop the managed Geometry columns with DropGeometryColumn()
                table_schema = table.schema or 'public'
                for c in gis_cols:
                    stmt = select([
                        func.DropGeometryColumn(table_schema, table.name,
                                                c.name)
                    ])
                    stmt = stmt.execution_options(autocommit=True)
                    bind.execute(stmt)

        elif event == 'after-create':
            # Restore original column list including managed Geometry columns
            table.columns = table.info.pop('_saved_columns')

            table_schema = table.schema or 'public'
            for c in table.c:
                # Add the managed Geometry columns with AddGeometryColumn()
                if isinstance(c.type, Geometry) and c.type.management is True:
                    stmt = select([
                        func.AddGeometryColumn(table_schema, table.name,
                                               c.name, c.type.srid,
                                               c.type.geometry_type,
                                               c.type.dimension)
                    ])
                    stmt = stmt.execution_options(autocommit=True)
                    bind.execute(stmt)

                # Add spatial indices for the Raster columns
                #
                # Note the use of ST_ConvexHull since most raster operators are
                # based on the convex hull of the rasters.
                if isinstance(c.type, Raster) and c.type.spatial_index is True:
                    bind.execute(
                        'CREATE INDEX "idx_%s_%s" ON "%s"."%s" '
                        'USING GIST (ST_ConvexHull("%s"))' %
                        (table.name, c.name, table_schema, table.name, c.name))

        elif event == 'after-drop':
            # Restore original column list including managed Geometry columns
            table.columns = table.info.pop('_saved_columns')
예제 #8
0
    def dispatch(event, table, bind):
        if event in ('before-create', 'before-drop'):
            # Filter Geometry columns from the table with management=True
            # Note: Geography and PostGIS >= 2.0 don't need this
            gis_cols = [
                c for c in table.c
                if isinstance(c.type, Geometry) and c.type.management is True
            ]

            # Find all other columns that are not managed Geometries
            regular_cols = [x for x in table.c if x not in gis_cols]

            # Save original table column list for later
            table.info["_saved_columns"] = table.c

            # Temporarily patch a set of columns not including the
            # managed Geometry columns
            column_collection = expression.ColumnCollection()
            for col in regular_cols:
                column_collection.add(col)
            table.columns = column_collection

            if event == 'before-drop':
                # Drop the managed Geometry columns
                for c in gis_cols:
                    if bind.dialect.name == 'sqlite':
                        drop_func = 'DiscardGeometryColumn'
                    elif bind.dialect.name == 'postgresql':
                        drop_func = 'DropGeometryColumn'
                    else:
                        raise ArgumentError(
                            'dialect {} is not supported'.format(
                                bind.dialect.name))
                    args = [table.schema] if table.schema else []
                    args.extend([table.name, c.name])

                    stmt = select([getattr(func, drop_func)(*args)])
                    stmt = stmt.execution_options(autocommit=True)
                    bind.execute(stmt)

        elif event == 'after-create':
            # Restore original column list including managed Geometry columns
            table.columns = table.info.pop('_saved_columns')

            for c in table.c:
                # Add the managed Geometry columns with AddGeometryColumn()
                if isinstance(c.type, Geometry) and c.type.management is True:
                    args = [table.schema] if table.schema else []
                    args.extend([
                        table.name, c.name, c.type.srid, c.type.geometry_type,
                        c.type.dimension
                    ])
                    if c.type.use_typmod is not None:
                        args.append(c.type.use_typmod)

                    stmt = select([func.AddGeometryColumn(*args)])
                    stmt = stmt.execution_options(autocommit=True)
                    bind.execute(stmt)

                # Add spatial indices for the Geometry and Geography columns
                if isinstance(c.type, (Geometry, Geography)) and \
                        c.type.spatial_index is True:
                    if bind.dialect.name == 'sqlite':
                        stmt = select(
                            [func.CreateSpatialIndex(table.name, c.name)])
                        stmt = stmt.execution_options(autocommit=True)
                        bind.execute(stmt)
                    elif bind.dialect.name == 'postgresql':
                        if table.schema:
                            bind.execute(
                                'CREATE INDEX "idx_%s_%s" ON "%s"."%s" '
                                'USING GIST ("%s")' %
                                (table.name, c.name, table.schema, table.name,
                                 c.name))
                        else:
                            bind.execute(
                                'CREATE INDEX "idx_%s_%s" ON "%s" '
                                'USING GIST ("%s")' %
                                (table.name, c.name, table.name, c.name))
                    else:
                        raise ArgumentError(
                            'dialect {} is not supported'.format(
                                bind.dialect.name))

                # Add spatial indices for the Raster columns
                #
                # Note the use of ST_ConvexHull since most raster operators are
                # based on the convex hull of the rasters.
                if isinstance(c.type, Raster) and c.type.spatial_index is True:
                    if table.schema:
                        bind.execute('CREATE INDEX "idx_%s_%s" ON "%s"."%s" '
                                     'USING GIST (ST_ConvexHull("%s"))' %
                                     (table.name, c.name, table.schema,
                                      table.name, c.name))
                    else:
                        bind.execute('CREATE INDEX "idx_%s_%s" ON "%s" '
                                     'USING GIST (ST_ConvexHull("%s"))' %
                                     (table.name, c.name, table.name, c.name))

        elif event == 'after-drop':
            # Restore original column list including managed Geometry columns
            table.columns = table.info.pop('_saved_columns')