:param model: model class to check
    :param engine: SQLAlchemy engine
    :param col_names: the name of columns which the unique constraint should contain

    :rtype: bool
    :return: True if the given columns are part of a unique constraint on model
16840
def has_constraint(model, engine, *col_names):  # pragma: no cover
    
    table_name = model.__tablename__
    if engine.dialect.has_table(engine, table_name):
        # Use SQLAlchemy reflection to determine unique constraints
        insp = Inspector.from_engine(engine)
        constraints = itertools.chain(
            (sorted(x['column_names']) for x in insp.get_unique_constraints(table_name)),
            sorted(insp.get_pk_constraint(table_name)['constrained_columns']),
        )
        return sorted(col_names) in constraints
    else:
        # Needed to validate test models pre-creation
        constrained_cols = set()
        for arg in getattr(model, '__table_args__', []):
            if isinstance(arg, UniqueConstraint):
                constrained_cols.update([c.name for c in arg.columns])
        for c in model.__table__.columns:
            if c.primary_key or c.unique:
                constrained_cols.add(c.name)
        return constrained_cols.issuperset(col_names)
863365
def _unique_constrains(cls):
        """"""
        unique = [{c.name for c in u.columns} for u in cls.__table_args__
                  if isinstance(u, UniqueConstraint)]
        unique.extend({c.name} for c in cls.__table__.columns if c.unique)
        return unique
424489
def get_models(self, columns=None):
        
        results = self._query.get(columns)

        connection = self._model.get_connection_name()

        return self._model.hydrate(results, connection).all()
1217988
def column_type(col_name)
      cache = Cache.instance
      cache.klass_hash[@_klass_str] ||= {}
      if v = cache.klass_hash[@_klass_str][col_name.to_s]
        cache.hit += 1
        v
      else
        cache.miss += 1
        col = @_klass_str.constantize.columns.find{|c|
          c.name == col_name.to_s
        }
        if col
          cache.klass_hash[@_klass_str][col_name.to_s] = col.type
        end
      end
    end
1281381
def column_family_name(cls, include_keyspace=True):
        
        cf_name = protect_name(cls._raw_column_family_name())
        if include_keyspace:
            keyspace = cls._get_keyspace()
            if not keyspace:
                raise CQLEngineException("Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query.")
            return '{0}.{1}'.format(protect_name(keyspace), cf_name)

        return cf_name
306588
protected function validateModel()
    {
        parent::validateModel();

        $table = $this->getTable();

        // Check to see if any of the column constants are PHP reserved words.
        $colConstants = array();

        foreach ($table->getColumns() as $col) {
            $colConstants[] = $this->getColumnName($col);
        }

        $reservedConstants = array_map('strtoupper', ClassTools::getPhpReservedWords());

        $intersect = array_intersect($reservedConstants, $colConstants);
        if (!empty($intersect)) {
            throw new EngineException("One or more of your column names for [" . $table->getName() . "] table conflict with a PHP reserved word (" . implode(", ", $intersect) . ")");
        }
    }
224834
def _map_table_name(self, model_names):
        

        for model in model_names:
            if isinstance(model, tuple):
                model = model[0]

            try:
                model_cls = getattr(self.models, model)
                self.table_to_class[class_mapper(model_cls).tables[0].name] = model
            except AttributeError:
                pass
257759
def models_with_unique_column(meta, exclude_single_pk=True, exclude_multi_pk=True):
    """"""
    models_with_potential_pk = {}
    fields_distinct = {}
    for model_name, model_fields in meta.iteritems():
        if exclude_single_pk and model_fields['Meta']['primary_key']:
                continue
        fields_distinct = []
        for field_name, field in model_fields.iteritems():
            if field_name is 'Meta':
                continue
            if float(field.get('fraction_distinct', 0)) == 1.:
                fields_distinct += [field_name]
        # if any(not field['primary_key'] and field['num_distinct'] == 1 for field_name, field in model_fields.iteritems() if field is not 'Meta'):
        if (not exclude_multi_pk and fields_distinct) or len(fields_distinct) == 1:
            models_with_potential_pk[model_name] = fields_distinct
    return models_with_potential_pk
524141
def _check_model_types(self, models):
        
        if not hasattr(models, "__iter__"):
            models = {models}
        if not all([isinstance(model, (AbstractStateModel, StateElementModel)) for model in models]):
            raise TypeError("The selection supports only models with base class AbstractStateModel or "
                            "StateElementModel, see handed elements {0}".format(models))
        return models if isinstance(models, set) else set(models)
568308
def _process_names(self, names):
        
        if names is None:
            return []

        table_names = OrderedDict()  # Preserve order and ignore duplicates
        while len(names):
            name = names.pop(0)
            if hasattr(name, '_meta'):
                if name._meta.abstract:
                    raise ValueError("Can't lock abstract model {}"
                                     .format(name.__name__))

                table_names[name._meta.db_table] = True
                # Include all parent models - the keys are the model classes
                if name._meta.parents:
                    names.extend(name._meta.parents.keys())
            else:
                table_names[name] = True
        return table_names.keys()
140155
def auto_model_name_recognize(model_name):
    
    name_list = model_name.split('-')
    return ''.join(['%s%s' % (name[0].upper(), name[1:]) for name in name_list])
525165
def engineIncluded(self, name):
        
        if self._engines is None:
            self._engines = self._dbconn.getStorageEngines()
        return self.envCheckFilter('engine', name) and name in self._engines
420610
def fit_row(connection, row, unique_keys):
    
    new_columns = []
    for column_name, column_value in list(row.items()):
        new_column = sqlalchemy.Column(column_name,
                                       get_column_type(column_value))

        if not column_name in list(_State.table.columns.keys()):
            new_columns.append(new_column)
            _State.table.append_column(new_column)

    if _State.table_pending:
        create_table(unique_keys)
        return

    for new_column in new_columns:
        add_column(connection, new_column)
1188733
def select_single_column(engine, column):
    
    s = select([column])
    return column.name, [row[0] for row in engine.execute(s)]
270884
def _is_auto_field(self, cursor, table_name, column_name):
        
        # COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx

        #from django.db import connection
        #cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
        #                 (connection.ops.quote_name(table_name), column_name))
        cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
                         (self.connection.ops.quote_name(table_name), column_name))
        return cursor.fetchall()[0][0]
738879
def _fieldnames_to_colnames(model_cls, fieldnames):
        """"""
        get_field = model_cls._meta.get_field
        fields = map(get_field, fieldnames)
        return {f.column for f in fields}
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