NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
        a globally unique name in postgres

        http://www.postgresql.org/docs/9.1/static/sql-createindex.html
320634
def _set_index(self, schema, name, fields, **index_options):
        
        index_fields = []
        for field_name in fields:
            field = schema.fields[field_name]
            if issubclass(field.type, basestring):
                if field.options.get('ignore_case', False):
                    field_name = 'UPPER({})'.format(self._normalize_name(field_name))
            index_fields.append(field_name)

        query_str = 'CREATE {}INDEX {} ON {} USING BTREE ({})'.format(
            'UNIQUE ' if index_options.get('unique', False) else '',
            self._normalize_name("{}_{}".format(schema, name)),
            self._normalize_table_name(schema),
            ', '.join(index_fields)
        )

        return self.query(query_str, ignore_result=True, **index_options)
280176
def add_index(table_name, column_name, options = {})
      column_names = Array(column_name)
      index_name   = index_name(table_name, :column => column_names)

      if Hash === options # legacy support, since this param was a string
        index_type = options[:unique] ? "UNIQUE" : ""
        index_name = options[:name] || index_name
        index_method = options[:spatial] ? 'USING GIST' : ""
      else
        index_type = options
      end
      quoted_column_names = column_names.map { |e| quote_column_name(e) }.join(", ")
      execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_method} (#{quoted_column_names})"
    end
1143396
private void createIndexes(Table t) {
        for (String indexName : t.getIndexHoldersByName().keySet()) {
            if (!indexName.startsWith("PRIMARY")) {
                createIndex(t, t.getIndexHolderByName(indexName));
            }
        }
    }
376034
private TableIndex getOrCreateTableIndex() {
		TableIndex tableIndex = getTableIndex();

		if (tableIndex == null) {
			try {
				if (!tableIndexDao.isTableExists()) {
					geoPackage.createTableIndexTable();
				}

				tableIndex = new TableIndex();
				tableIndex.setTableName(tableName);
				tableIndex.setLastIndexed(null);

				tableIndexDao.create(tableIndex);
			} catch (SQLException e) {
				throw new GeoPackageException(
						"Failed to create Table Index for GeoPackage: "
								+ geoPackage.getName() + ", Table Name: "
								+ tableName + ", Column Name: " + columnName, e);
			}
		}

		return tableIndex;
	}
831511
public function createIndex(Index $index, $table)
    {
        $this->_execSql($this->_platform->getCreateIndexSQL($index, $table));
    }
589593
public IndexQueryBuilder setIndex(String indexName) {
        Preconditions.checkArgument(StringUtils.isNotBlank(indexName));
        this.indexName=indexName;
        return this;
    }
83051
def ensure_table(self, cls):
        """"""
        id_len = len(uuid())
        index_names = cls.index_names() or []
        cols = [
            'id char(%d) primary key' % (id_len,),
            'value jsonb'
        ] + [
            name + ' text' for name in index_names
        ]

        table_name = cls.get_table_name()

        with self._conn() as conn:
            with conn.cursor() as cur:
                cur.execute('create table if not exists %s (%s);' % (
                    table_name,
                    ','.join(cols)
                ))
                for name in index_names:
                    cur.execute('create index if not exists %s on %s(%s);' % (
                        table_name + '_' + name + '_idx',
                        table_name,
                        name
                    ))
796514
def create_index(self,
                     table: str,
                     field: str,
                     nchars: int = None,
                     indexname: str = None,
                     unique: bool = False) -> Optional[int]:
        """"""
        limit = ""
        if nchars is not None:
            limit = "({})".format(nchars)
        if indexname is None:
            indexname = "_idx_{}".format(field)
        if self.index_exists(table, indexname):
            return None
        uniquestr = "UNIQUE" if unique else ""
        sql = (
            "CREATE {unique} INDEX {indexname} "
            "ON {table} ({field}{limit})".format(
                unique=uniquestr,
                indexname=indexname,
                table=table,
                field=field,
                limit=limit,
            )
        )
        return self.db_exec(sql)
1167039
def index_name(model, *field_names, **kwargs):
    
    if not len(field_names):
        raise ValueError("At least one field name required")
    using = kwargs.pop('using', DEFAULT_DB_ALIAS)
    if len(kwargs):
        raise ValueError("The only supported keyword argument is 'using'")

    existing_fields = {field.name: field for field in model._meta.fields}
    fields = [existing_fields[name] for name in field_names
              if name in existing_fields]

    if len(fields) != len(field_names):
        unfound_names = set(field_names) - {field.name for field in fields}
        raise ValueError("Fields do not exist: " + ",".join(unfound_names))
    column_names = tuple(field.column for field in fields)
    list_sql = get_list_sql(column_names)

    with connections[using].cursor() as cursor:
        cursor.execute(
            """SELECT `INDEX_NAME`, `SEQ_IN_INDEX`, `COLUMN_NAME`
               FROM INFORMATION_SCHEMA.STATISTICS
               WHERE TABLE_SCHEMA = DATABASE() AND
                     TABLE_NAME = %s AND
                     COLUMN_NAME IN {list_sql}
               ORDER BY `INDEX_NAME`, `SEQ_IN_INDEX` ASC
            """.format(list_sql=list_sql),
            (model._meta.db_table,) + column_names,
        )
        indexes = defaultdict(list)
        for index_name, _, column_name in cursor.fetchall():
            indexes[index_name].append(column_name)

    indexes_by_columns = {tuple(v): k for k, v in indexes.items()}
    try:
        return indexes_by_columns[column_names]
    except KeyError:
        raise KeyError("There is no index on (" + ",".join(field_names) + ")")
772043
private List<String> listIndexesOnTables(List<String> tables)
  {
    String sql
      = ""
      + "SELECT indexname "
      + "FROM pg_indexes "
      + "WHERE tablename IN (" + StringUtils.repeat("?", ",", tables.size())
      + ") "
      + "AND lower(indexname) NOT IN "
      + "	(SELECT lower(conname) FROM pg_constraint WHERE contype in ('p', 'u'))";

    return getJdbcTemplate().query(sql, tables.toArray(), stringRowMapper());
  }
984163
def create_fulltext_index(self,
                              table: str,
                              field: str,
                              indexname: str = None) -> Optional[int]:
        
        if indexname is None:
            indexname = "_idxft_{}".format(field)
        if self.index_exists(table, indexname):
            return None
        sql = "CREATE FULLTEXT INDEX {} ON {} ({})".format(indexname, table,
                                                           field)
        return self.db_exec(sql)
657249
def get_create_index_sql(self, index, table):
        
        if isinstance(table, Table):
            table = table.get_quoted_name(self)

        name = index.get_quoted_name(self)
        columns = index.get_quoted_columns(self)

        if not columns:
            raise DBALException('Incomplete definition. "columns" required.')

        if index.is_primary():
            return self.get_create_primary_key_sql(index, table)

        query = "CREATE %sINDEX %s ON %s" % (
            self.get_create_index_sql_flags(index),
            name,
            table,
        )
        query += " (%s)%s" % (
            self.get_index_field_declaration_list_sql(columns),
            self.get_partial_index_sql(index),
        )

        return query
564505
function pg_create_index_name(self, ObjType, type, field, typefield) {
	var name;
	var colname = _parse_predicate_key(ObjType, {'epoch':false}, field);
	var datakey = colname.getMeta('datakey');
	var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key');
	if( (ObjType === NoPg.Document) && (typefield !== undefined)) {
		if(!typefield) {
			throw new TypeError("No typefield set for NoPg.Document!");
		}
		name = pg_convert_index_name(ObjType.meta.table) + "_" + typefield + "_" + pg_convert_index_name(field_name) + "_index";
	} else {
		name = pg_convert_index_name(ObjType.meta.table) + "_" + pg_convert_index_name(field_name) + "_index";
	}
	return name;
}
1213867
function createIndex (model, column) {
    // build query
    var sql = 'ALTER TABLE '+quoteName(model.name)
    // column has unique index
    if (column.spec.unique) {
        sql = sql+' ADD '+createTableUniqueKey(column.name, column.spec)
    }
    // column has non-unique index
    else if (column.spec.index) {
        sql = sql+' ADD '+createTableKey(column.name, column.spec)
    }
    // reture sql string
    return sql
}
976757
def set_indexing(self, index_template):
        
        objs = object_session(self)
        
        if self.index.indimp != index_template.imp_name:
            self._refresh_datatable_schema()
        
        self.index.name = index_template.name
        self.index.indimp = index_template.imp_name
        self.index.case = index_template.case
        self.index.setkwargs(**index_template.kwargs)
        objs.commit()
226417
public boolean addIndexToTable (Connection conn, String table, List<String> columns,
                                    String ixName, boolean unique) throws SQLException
    {
        if (tableContainsIndex(conn, table, ixName)) {
            return false;
        }
        ixName = (ixName != null ? ixName :
                  StringUtil.join(columns.toArray(new String[columns.size()]), "_"));

        StringBuilder update = new StringBuilder("CREATE ");
        if (unique) {
            update.append("UNIQUE ");
        }
        update.append("INDEX ").append(indexSQL(ixName)).append(" ON ").
            append(tableSQL(table)).append(" (");
        appendColumns(columns, update);
        update.append(")");

        executeQuery(conn, update.toString());
        log("Database index '" + ixName + "' added to table '" + table + "'");
        return true;
    }
267099
private boolean indexCovers(Index newIndex, Index existingIndex) {
        assert(newIndex.getParent().getTypeName().equals(existingIndex.getParent().getTypeName()));

        // non-unique indexes don't help with this check
        if (existingIndex.getUnique() == false) {
            return false;
        }

        // expression indexes only help if they are on exactly the same expressions in the same order.
        // OK -- that's obviously overspecifying the requirement, since expression order has nothing
        // to do with it, and uniqueness of just a subset of the new index expressions would do, but
        // that's hard to check for, so we punt on optimized dynamic update except for the critical
        // case of grand-fathering in a surviving pre-existing index.
        if (existingIndex.getExpressionsjson().length() > 0) {
            if (existingIndex.getExpressionsjson().equals(newIndex.getExpressionsjson())) {
                return true;
            } else {
                return false;
            }
        } else if (newIndex.getExpressionsjson().length() > 0) {
            // A column index does not generally provide coverage for an expression index,
            // though there are some special cases not being recognized, here,
            // like expression indexes that list a mix of non-column expressions and unique columns.
            return false;
        }

        // partial indexes must have identical predicates
        if (existingIndex.getPredicatejson().length() > 0) {
            if (existingIndex.getPredicatejson().equals(newIndex.getPredicatejson())) {
                return true;
            } else {
                return false;
            }
        } else if (newIndex.getPredicatejson().length() > 0) {
            return false;
        }

        // iterate over all of the existing columns
        for (ColumnRef existingColRef : existingIndex.getColumns()) {
            boolean foundMatch = false;
            // see if the current column is also in the candidate index
            // for now, assume the tables in question have the same schema
            for (ColumnRef colRef : newIndex.getColumns()) {
                String colName1 = colRef.getColumn().getName();
                String colName2 = existingColRef.getColumn().getName();
                if (colName1.equals(colName2)) {
                    foundMatch = true;
                    break;
                }
            }
            // if this column isn't covered
            if (!foundMatch) {
                return false;
            }
        }

        // There exists a unique index that contains a subset of the columns in the new index
        return true;
    }