Get primary key properties for a SQLAlchemy cls.
        Taken from marshmallow_sqlalchemy
516857
def primary_keys_full(cls):
        
        mapper = cls.__mapper__
        return [
            mapper.get_property_by_column(column)
            for column in mapper.primary_key
        ]
598890
def identity_attributes(cls):
        
        columns = inspect(cls).primary_key
        names = [c.name for c in columns if c.name not in ('width', 'height')]
        return names
890946
def sql(self):
        
        assert self.in_key and not self.nullable   # primary key attributes are never nullable
        return '`{name}` {type} NOT NULL COMMENT "{comment}"'.format(
            name=self.name, type=self.type, comment=self.comment)
24505
def get_key_columns(self, cursor, table_name):
        
        source_field_dict = self._name_to_index(cursor, table_name)

        sql = """
select
    COLUMN_NAME = fk_cols.COLUMN_NAME,
    REFERENCED_TABLE_NAME = pk.TABLE_NAME,
    REFERENCED_COLUMN_NAME = pk_cols.COLUMN_NAME
from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ref_const
join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
    on ref_const.CONSTRAINT_CATALOG = fk.CONSTRAINT_CATALOG
    and ref_const.CONSTRAINT_SCHEMA = fk.CONSTRAINT_SCHEMA
    and ref_const.CONSTRAINT_NAME = fk.CONSTRAINT_NAME
    and fk.CONSTRAINT_TYPE = 'FOREIGN KEY'

join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
    on ref_const.UNIQUE_CONSTRAINT_CATALOG = pk.CONSTRAINT_CATALOG
    and ref_const.UNIQUE_CONSTRAINT_SCHEMA = pk.CONSTRAINT_SCHEMA
    and ref_const.UNIQUE_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
    And pk.CONSTRAINT_TYPE = 'PRIMARY KEY'

join INFORMATION_SCHEMA.KEY_COLUMN_USAGE fk_cols
    on ref_const.CONSTRAINT_NAME = fk_cols.CONSTRAINT_NAME

join INFORMATION_SCHEMA.KEY_COLUMN_USAGE pk_cols
    on pk.CONSTRAINT_NAME = pk_cols.CONSTRAINT_NAME
where
    fk.TABLE_NAME = %s"""

        cursor.execute(sql,[table_name])
        relations = cursor.fetchall()

        key_columns = []
        key_columns.extend([(source_column, target_table, target_column) \
            for source_column, target_table, target_column in relations])
        return key_columns
492335
private BasicDBObject getKeys(EntityMetadata m, String[] columns)
    {
        BasicDBObject keys = new BasicDBObject();
        if (columns != null && columns.length > 0)
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                    .getMetamodel(m.getPersistenceUnit());
            EntityType entity = metaModel.entity(m.getEntityClazz());
            for (int i = 1; i < columns.length; i++)
            {
                if (columns[i] != null)
                {
                    Attribute col = entity.getAttribute(columns[i]);
                    if (col == null)
                    {
                        throw new QueryHandlerException("column type is null for: " + columns);
                    }
                    keys.put(((AbstractAttribute) col).getJPAColumnName(), 1);
                }
            }
        }
        return keys;
    }
1266218
def get_primary_key(self, table):
        """"""
        for column in self.get_schema(table):
            if len(column) > 3 and 'pri' in column[3].lower():
                return column[0]
350105
def get_model_indexes(model, add_reserver_flag=True):
    
    import uliweb.orm as orm
    from sqlalchemy.engine.reflection import Inspector

    indexes = []
    engine = model.get_engine().engine
    insp = Inspector.from_engine(engine)
    for index in insp.get_indexes(model.tablename):
        d = {}
        d['name'] = index['name']
        d['unique'] = index['unique']
        d['fields'] = index['column_names']
        if add_reserver_flag:
            d['_reserved'] = True
        indexes.append(d)

    return indexes
575745
def sqlalchemy(self, is_top=True):
        """"""
        table_def = self.table_backref_remover.sub('', self.table.__repr__())

        # inject UNIQUE constraints into table definition
        constraint_defs = []
        for constraint in self.table.constraints:
            if isinstance(constraint, sa.sql.schema.UniqueConstraint):
                col_list = ', '.join("'%s'" % c.name
                                     for c in constraint.columns)
                constraint_defs.append('UniqueConstraint(%s)' % col_list)
        if constraint_defs:
            constraint_defs = ',\n  '.join(constraint_defs) + ','
            table_def = table_def.replace('schema=None', '\n  ' + constraint_defs + 'schema=None')

        table_def = table_def.replace("MetaData(bind=None)", "metadata")
        table_def = table_def.replace("Column(", "\n  Column(")
        table_def = table_def.replace("schema=", "\n  schema=")
        result = [table_def, ]
        result.extend(c.sqlalchemy(is_top=False) for c in self.children.values())
        result = "\n%s = %s" % (self.table_name, "\n".join(result))
        if is_top:
            sqla_imports = set(self.capitalized_words.findall(table_def))
            sqla_imports &= set(dir(sa))
            sqla_imports = sorted(sqla_imports)
            result = self.sqlalchemy_setup_template % (
                ", ".join(sqla_imports), result, self.table.name)
            result = textwrap.dedent(result)
        return result
600467
def _members(self):
        
        return {
            key: value
            for key, value in self.__dict__.items()
            # NB: ignore internal SQLAlchemy state and nested relationships
            if not key.startswith("_") and not isinstance(value, Model)
        }
1050435
def _get_pk_from_identity(obj):
        """"""
        from sqlalchemy.orm.util import identity_key

        cls, key = identity_key(instance=obj)[0:2]
        return ":".join(text_type(x) for x in key)
240282
def get_library_value(self, key: str) -> typing.Any:
        
        desc = Metadata.session_key_map.get(key)
        if desc is not None:
            field_id = desc['path'][-1]
            return getattr(ApplicationData.get_session_metadata_model(), field_id)
        raise KeyError()
1038405
def _get_fields_for_model(model):
    
    fields = []
    for name in model._sa_class_manager:
        prop = getattr(model, name)
        if isinstance(prop.property, RelationshipProperty):
            for pk in prop.property.mapper.primary_key:
                fields.append('{0}.{1}'.format(name, pk.name))
        else:
            fields.append(name)
    return tuple(fields)
222761
def get_pks(self, field_vals):
        """"""
        field_name = self.schema.pk.name
        return self.in_field(field_name, field_vals).get()
74898
def _extract_columns(self, table_name):
        
        '''  '''
        
        import re
        from sqlalchemy import MetaData, VARCHAR, INTEGER, BLOB, BOOLEAN, FLOAT
        from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, BIT, BYTEA
    
    # retrieve list of tables
        metadata_object = MetaData()
        table_list = self.engine.table_names()
    
    # determine columns
        prior_columns = {}
        if table_name in table_list:
            metadata_object.reflect(self.engine)
            existing_table = metadata_object.tables[table_name]
            for column in existing_table.columns:
                column_type = None
                column_length = None
                if column.type.__class__ == FLOAT().__class__:
                    column_type = 'float'
                elif column.type.__class__ == DOUBLE_PRECISION().__class__: # Postgres
                    column_type = 'float'
                elif column.type.__class__ == INTEGER().__class__:
                    column_type = 'integer'
                elif column.type.__class__ == VARCHAR().__class__:
                    column_length = getattr(column.type, 'length', None)
                    if column_length == 1:
                        if column.primary_key:
                            column_length = None
                    column_type = 'string'
                elif column.type.__class__ == BLOB().__class__:
                    column_type = 'list'
                elif column.type.__class__ in (BIT().__class__, BYTEA().__class__):
                    column_type = 'list'
                elif column.type.__class__ == BOOLEAN().__class__:
                    column_type = 'boolean'
                prior_columns[column.key] = (column.key, column_type, '', column_length)
        
        return prior_columns
374387
def get_type_for_inputs(table):
        
        return [
            dict(
                type=INPUT_TYPES.get(
                    type(field_type.type), rc.TEXT_INPUT.value
                ),
                name=name,
                isPrimaryKey=(name in table.primary_key),
                props=None,
            ) for name, field_type in table.c.items()
        ]
97684
def primary_key(self):
        
        primary_key = self.__current_descriptor.get('primaryKey', [])
        if not isinstance(primary_key, list):
            primary_key = [primary_key]
        return primary_key
568321
def _getID(self):
        """"""
        id = []
        for key in self._sqlPrimary:
            value = self.__dict__[key]
            if isinstance(value, Forgetter):
                # It's another object, we store only the ID
                if value._new:
                    # It's a new object too, it must be saved!
                    value.save()
                try:
                    (value,) = value._getID()
                except:
                    raise "Unsupported: Part %s of %s primary key is a reference to %s, with multiple-primary-key %s " % (key, self.__class__, value.__class__, value)
            id.append(value)
        return id