Returns an ascending order clause on the versioned unique constraint as well as the
    version column.
168716
def _get_order_clause(archive_table):
    
    order_clause = [
        sa.asc(getattr(archive_table, col_name)) for col_name in archive_table._version_col_names
    ]
    order_clause.append(sa.asc(archive_table.version_id))
    return order_clause
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
742815
def _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning,
                    ignore_duplicate_updates=True, return_untouched=False):
    
    model = queryset.model

    # Use all fields except pk unless the uniqueness constraint is the pk field
    all_fields = [
        field for field in model._meta.fields
        if field.column != model._meta.pk.name or not field.auto_created
    ]

    all_field_names = [field.column for field in all_fields]
    returning = returning if returning is not True else [f.column for f in model._meta.fields]
    all_field_names_sql = ', '.join([_quote(field) for field in all_field_names])

    # Convert field names to db column names
    unique_fields = [
        model._meta.get_field(unique_field)
        for unique_field in unique_fields
    ]
    update_fields = [
        model._meta.get_field(update_field)
        for update_field in update_fields
    ]

    unique_field_names_sql = ', '.join([
        _quote(field.column) for field in unique_fields
    ])
    update_fields_sql = ', '.join([
        '{0} = EXCLUDED.{0}'.format(_quote(field.column))
        for field in update_fields
    ])

    row_values, sql_args = _get_values_for_rows(model_objs, all_fields)

    return_sql = 'RETURNING ' + _get_return_fields_sql(returning, return_status=True) if returning else ''
    ignore_duplicates_sql = ''
    if ignore_duplicate_updates:
        ignore_duplicates_sql = (
            ' WHERE ({update_fields_sql}) IS DISTINCT FROM ({excluded_update_fields_sql}) '
        ).format(
            update_fields_sql=', '.join(
                '{0}.{1}'.format(model._meta.db_table, _quote(field.column))
                for field in update_fields
            ),
            excluded_update_fields_sql=', '.join(
                'EXCLUDED.' + _quote(field.column)
                for field in update_fields
            )
        )

    on_conflict = (
        'DO UPDATE SET {0} {1}'.format(update_fields_sql, ignore_duplicates_sql) if update_fields else 'DO NOTHING'
    )

    if return_untouched:
        row_values_sql = ', '.join([
            '(\'{0}\', {1})'.format(i, row_value[1:-1])
            for i, row_value in enumerate(row_values)
        ])
        sql = (
            ' WITH input_rows("temp_id_", {all_field_names_sql}) AS ('
            '     VALUES {row_values_sql}'
            ' ), ins AS ( '
            '     INSERT INTO {table_name} ({all_field_names_sql})'
            '     SELECT {all_field_names_sql} FROM input_rows ORDER BY temp_id_'
            '     ON CONFLICT ({unique_field_names_sql}) {on_conflict} {return_sql}'
            ' )'
            ' SELECT DISTINCT ON ({table_pk_name}) * FROM ('
            '     SELECT status_, {return_fields_sql}'
            '     FROM   ins'
            '     UNION  ALL'
            '     SELECT \'n\' AS status_, {aliased_return_fields_sql}'
            '     FROM input_rows'
            '     JOIN {table_name} c USING ({unique_field_names_sql})'
            ' ) as results'
            ' ORDER BY results."{table_pk_name}", CASE WHEN(status_ = \'n\') THEN 1 ELSE 0 END;'
        ).format(
            all_field_names_sql=all_field_names_sql,
            row_values_sql=row_values_sql,
            table_name=model._meta.db_table,
            unique_field_names_sql=unique_field_names_sql,
            on_conflict=on_conflict,
            return_sql=return_sql,
            table_pk_name=model._meta.pk.name,
            return_fields_sql=_get_return_fields_sql(returning),
            aliased_return_fields_sql=_get_return_fields_sql(returning, alias='c')
        )
    else:
        row_values_sql = ', '.join(row_values)
        sql = (
            ' INSERT INTO {table_name} ({all_field_names_sql})'
            ' VALUES {row_values_sql}'
            ' ON CONFLICT ({unique_field_names_sql}) {on_conflict} {return_sql}'
        ).format(
            table_name=model._meta.db_table,
            all_field_names_sql=all_field_names_sql,
            row_values_sql=row_values_sql,
            unique_field_names_sql=unique_field_names_sql,
            on_conflict=on_conflict,
            return_sql=return_sql
        )

    return sql, sql_args
473106
public Query returning( List<Column> columns ) {
        return new Query(source, constraint, orderings(), columns, getLimits(), distinct);
    }
732622
public static long getVersionRetroactively(PendingCompaction pendingCompaction) {
        Compaction compaction = pendingCompaction.getCompaction();
        // Calculate the version and create a dummy compaction record for the resolver
        return compaction.getCount() - (long)pendingCompaction.getDeltasToArchive().size();
    }
1373846
def [](version_or_constraint)
      # version constraints must abide the include? contract
      if version_or_constraint.respond_to?(:include?)
        versions.select do |ver|
          version_or_constraint.include?(ver.version)
        end
      else
        versions.find{|pkg_version| pkg_version.version == version_or_constraint}
      end
    end
1220430
public VersionComparator getSchemaVersion() {
        PreparedStatement statement = null;
        ResultSet results = null;
        try {
            statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\"");
            results = statement.executeQuery();

            if (results.next()) {
                return new VersionComparator(results.getString(1));
            }
        } catch (SQLException e) {
            // throw it away
        } finally {
            DbUtil.close(results);
            DbUtil.close(statement);
            //DbUtil.close(connection); // do not close connection
        }
        return null;
    }
888169
public static <T> SortedSet<HBaseColumn<T>> asSortedSet(T value, long version) {
        return asSortedSet(value, version, DESC_HBASE_COLUMN_COMPARATOR);
    }
1059567
public void updateSchemaVersion(VersionComparator version) throws SQLException {
        PreparedStatement statement = null;
        PreparedStatement updateStatement = null;
        ResultSet results = null;
        try {
            statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\"");
            results = statement.executeQuery();

            if (results.next()) {
                final VersionComparator currentVersion = new VersionComparator(results.getString(1));
                if (version == null || currentVersion.isNewerThan(version)) {
                    return;
                }
                updateStatement = connection.prepareStatement("UPDATE \"SCHEMAVERSION\" SET \"VERSION\" = ?");
            } else {
                // Does not exist. Populate schema table with current running version
                version = new VersionComparator(Config.getInstance().getApplicationVersion());
                updateStatement = connection.prepareStatement("INSERT INTO \"SCHEMAVERSION\" (\"VERSION\") VALUES (?)");
            }

            LOGGER.debug("Updating database schema to: " + version.toString());

            updateStatement.setString(1, version.toString());
            updateStatement.executeUpdate();
            connection.commit();
        } finally {
            DbUtil.close(results);
            DbUtil.close(updateStatement);
            DbUtil.close(statement);
            //DbUtil.close(connection); // do not close connection
        }
    }
957289
OrderedHashSet getDependentConstraints(int colIndex) {

        OrderedHashSet set = new OrderedHashSet();

        for (int i = 0, size = constraintList.length; i < size; i++) {
            Constraint c = constraintList[i];

            if (c.hasColumnOnly(colIndex)) {
                set.add(c);
            }
        }

        return set;
    }
891630
public Query constrainedBy( Constraint constraint ) {
        return new Query(source, constraint, orderings(), columns, getLimits(), distinct);
    }
749764
OrderedHashSet getContainingConstraints(int colIndex) {

        OrderedHashSet set = new OrderedHashSet();

        for (int i = 0, size = constraintList.length; i < size; i++) {
            Constraint c = constraintList[i];

            if (c.hasColumnPlus(colIndex)) {
                set.add(c);
            }
        }

        return set;
    }
729225
Constraint getUniqueConstraintForColumns(int[] mainTableCols,
            int[] refTableCols) {

        for (int i = 0, size = constraintList.length; i < size; i++) {
            Constraint c    = constraintList[i];
            // A VoltDB extension -- Don't consider non-column expression indexes for this purpose
            if (c.hasExprs()) {
                continue;
            }
            // End of VoltDB extension
            int        type = c.getConstraintType();

            if (type != Constraint.UNIQUE && type != Constraint.PRIMARY_KEY) {
                continue;
            }

            int[] constraintCols = c.getMainColumns();

            if (constraintCols.length != mainTableCols.length) {
                continue;
            }

            if (ArrayUtil.areEqual(constraintCols, mainTableCols,
                                   mainTableCols.length, true)) {
                return c;
            }

            if (ArrayUtil.areEqualSets(constraintCols, mainTableCols)) {
                int[] newRefTableCols = new int[mainTableCols.length];

                for (int j = 0; j < mainTableCols.length; j++) {
                    int pos = ArrayUtil.find(constraintCols, mainTableCols[j]);

                    newRefTableCols[pos] = refTableCols[j];
                }

                for (int j = 0; j < mainTableCols.length; j++) {
                    refTableCols[j] = newRefTableCols[j];
                }

                return c;
            }
        }

        return null;
    }
431279
def constraint(self):
        """"""
        constraint_arr = []
        if self._not_null:
            constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL")
        if self._unique:
            constraint_arr.append("UNIQUE")

        return " ".join(constraint_arr)
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
1281463
private String buildSelectSQL(boolean addOrderBy) {
        SQLParams sqlParams = SQLParams.builder()
                .modelClass(this.modelClass)
                .selectColumns(this.selectColumns)
                .tableName(this.tableName)
                .pkName(this.primaryKeyColumn)
                .conditionSQL(this.conditionSQL)
                .excludedColumns(this.excludedColumns)
                .isSQLLimit(isSQLLimit)
                .build();

        ifThen(addOrderBy, () -> sqlParams.setOrderBy(this.orderBySQL.toString()));

        return Anima.of().dialect().select(sqlParams);
    }
1045277
def squash_old_versions
      specifiers = map_specifiers_to_versions

      compare_versions = lambda do |x, y|
        v_x = x =~ Lyp::PACKAGE_RE && Lyp.version($2)
        v_y = y =~ Lyp::PACKAGE_RE && Lyp.version($2)
        x <=> y
      end

      specifiers.each do |package, clauses|
        # Remove old versions only if the package is referenced using a single
        # specifier clause
        next unless clauses.size == 1

        specs = clauses.values.first
        specs.each do |s|
          if s.versions.values.uniq.size == 1
            versions = s.versions.keys.sort(&compare_versions)
            latest = versions.last
            s.versions.select! {|k, v| k == latest}
          end
        end
      end
    end