Asks an SQLAlchemy ORM object: "what are your primary key(s)?"

    Args:
        obj: SQLAlchemy ORM object

    Returns:
        list of attribute names of primary-key columns
511055
def get_pk_attrnames(obj) -> List[str]:
    
    return [attrname
            for attrname, column in gen_columns(obj)
            if column.primary_key]
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)
674162
def get_model_fields(model, add_reserver_flag=True):
    
    import uliweb.orm as orm

    fields = []
    m = {'type':'type_name', 'hint':'hint',
         'default':'default', 'required':'required'}
    m1 = {'index':'index', 'unique':'unique'}
    for name, prop in model.properties.items():
        if name == 'id':
            continue
        d = {}
        for k, v in m.items():
            d[k] = getattr(prop, v)
        for k, v in m1.items():
            d[k] = bool(prop.kwargs.get(v))
        d['name'] = prop.fieldname or name
        d['verbose_name'] = unicode(prop.verbose_name)
        d['nullable'] = bool(prop.kwargs.get('nullable', orm.__nullable__))
        if d['type'] in ('VARCHAR', 'CHAR', 'BINARY', 'VARBINARY'):
            d['max_length'] = prop.max_length
        if d['type'] in ('Reference', 'OneToOne', 'ManyToMany'):
            d['reference_class'] = prop.reference_class
            #collection_name will be _collection_name, it the original value
            d['collection_name'] = prop._collection_name
        d['server_default'] = prop.kwargs.get('server_default')
        d['_reserved'] = True
        fields.append(d)

    return fields
1185200
def get_pk_colnames(table_: Table) -> List[str]:
    
    pk_names = []  # type: List[str]
    for col in table_.columns:
        if col.primary_key:
            pk_names.append(col.name)
    return pk_names
290488
def primaryKeys(self, table, catalog=None, schema=None):  # nopep8
        """"""
        fut = self._run_operation(self._impl.primaryKeys, table,
                                  catalog=catalog, schema=schema)
        return fut
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)
        }
959231
function GetPrimaryKeyName($remove_prefix = true)
	{
		foreach ($this->PrimaryKeys as $key)
		{
			return ($remove_prefix) ? $this->RemovePrefix($key->KeyColumn) : $key->KeyColumn;
		}
		
		// views don't technically have a primary key but we will return the first column if anybody asks
		if ($this->IsView) return $this->GetColumnNameByIndex(0,$remove_prefix);
	}
1303785
def get_tables(self, models):
        '''
        
        '''
        return { obj._meta.db_table : obj for obj in
                models.__dict__.itervalues() if
                isinstance(obj, peewee.BaseModel) and
                len(obj._meta.fields) > 1
            }
764309
function(req, model) {

    var values = req.body.data.attributes || {};

    if (req.allParams()['id']) {
      values[model.primaryKey] = req.allParams()['id'];
    }

    return values;
  }
384036
def PyobjColumns(obj):
    ''
    return [ColumnAttr(k, type(getattr(obj, k))) for k in getPublicAttrs(obj)]
310798
def _query_db(self, mapping):
        
        model = self.models[mapping.get("table")]

        # Use primary key instead of the field mapped to SF Id
        fields = mapping.get("fields", {}).copy()
        if mapping["oid_as_pk"]:
            del fields["Id"]
        id_column = model.__table__.primary_key.columns.keys()[0]
        columns = [getattr(model, id_column)]

        for f in fields.values():
            columns.append(model.__table__.columns[f])
        lookups = mapping.get("lookups", {}).copy()
        for lookup in lookups.values():
            lookup["aliased_table"] = aliased(
                self.metadata.tables["{}_sf_ids".format(lookup["table"])]
            )
            columns.append(lookup["aliased_table"].columns.sf_id)

        query = self.session.query(*columns)
        if "record_type" in mapping and hasattr(model, "record_type"):
            query = query.filter(model.record_type == mapping["record_type"])
        if "filters" in mapping:
            filter_args = []
            for f in mapping["filters"]:
                filter_args.append(text(f))
            query = query.filter(*filter_args)
        for sf_field, lookup in lookups.items():
            # Outer join with lookup ids table:
            # returns main obj even if lookup is null
            key_field = get_lookup_key_field(lookup, sf_field)
            value_column = getattr(model, key_field)
            query = query.outerjoin(
                lookup["aliased_table"],
                lookup["aliased_table"].columns.id == value_column,
            )
            # Order by foreign key to minimize lock contention
            # by trying to keep lookup targets in the same batch
            lookup_column = getattr(model, key_field)
            query = query.order_by(lookup_column)
        self.logger.info(str(query))
        return query
240463
def id(cls):
        
        if cls.__uuid_primary_key__:
            return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False))
        else:
            return immutable(Column(Integer, primary_key=True, nullable=False))
516857
def primary_keys_full(cls):
        
        mapper = cls.__mapper__
        return [
            mapper.get_property_by_column(column)
            for column in mapper.primary_key
        ]
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
563755
def query_obj(self):
        """"""
        d = super().query_obj()
        d['row_limit'] = self.form_data.get(
            'row_limit', int(config.get('VIZ_ROW_LIMIT')))
        numeric_columns = self.form_data.get('all_columns_x')
        if numeric_columns is None:
            raise Exception(_('Must have at least one numeric column specified'))
        self.columns = numeric_columns
        d['columns'] = numeric_columns + self.groupby
        # override groupby entry to avoid aggregation
        d['groupby'] = []
        return d
367679
def get_obj_attrs(obj):
    
    pr = {}
    if obj is not None:
        if isinstance(obj, numpy.core.records.record):
            for name in obj.dtype.names:
                pr[name] = getattr(obj, name)
        elif hasattr(obj, '__dict__') and obj.__dict__:
            pr = obj.__dict__
        elif hasattr(obj, '__slots__'):
            for slot in obj.__slots__:
                if hasattr(obj, slot):
                    pr[slot] = getattr(obj, slot)
        elif isinstance(obj, dict):
            pr = obj.copy()
        else:
            for name in dir(obj):
                try:
                    value = getattr(obj, name)
                    if not name.startswith('__') and not inspect.ismethod(value):
                        pr[name] = value
                except:
                    continue

    return pr
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