Using the how_to_index annotations in the table class definitions,
	construct a set of indexes for the database at the given
	connection.
326438
def build_indexes(connection, verbose = False):
	
	cursor = connection.cursor()
	for table_name in get_table_names(connection):
		# FIXME:  figure out how to do this extensibly
		if table_name in TableByName:
			how_to_index = TableByName[table_name].how_to_index
		elif table_name in lsctables.TableByName:
			how_to_index = lsctables.TableByName[table_name].how_to_index
		else:
			continue
		if how_to_index is not None:
			if verbose:
				print >>sys.stderr, "indexing %s table ..." % table_name
			for index_name, cols in how_to_index.iteritems():
				cursor.execute("CREATE INDEX IF NOT EXISTS %s ON %s (%s)" % (index_name, table_name, ",".join(cols)))
	connection.commit()
374338
def create_index(index_definition, origin_module=Object)
			transaction {
				klass = if(index_definition.fulltext)
									FulltextIndex
								elsif(index_definition.resolve_search_term.is_a?(Hash))
									ConditionIndex
								else
									Index
								end
				index = klass.new(index_definition, origin_module)
				indices.store(index_definition.index_name, index)
				indices.odba_store_unsaved
				index
			}
		end
1060828
function (connectionName, collectionName, definition, cb) {

      var connectionObject = connections[connectionName];
      if (!connectionObject) return cb(Errors.InvalidConnection);

      var collection = connectionObject.collections[collectionName];
      if (!collection) return cb(Errors.CollectionNotRegistered);

      collection.createTable(cb);
    }
1218099
def set_table(self, schema, **kwargs):
        
        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            if self.has_table(str(schema), **kwargs): return True

            try:
                with self.transaction(**kwargs):
                    self._set_table(schema, **kwargs)

                    for index_name, index in schema.indexes.items():
                        self.set_index(
                            schema,
                            name=index.name,
                            fields=index.fields,
                            connection=connection,
                            **index.options
                        )

            except InterfaceError:
                # check to see if this table now exists, it might have been created
                # in another thread
                if not self.has_table(schema, **kwargs):
                    raise
447137
public void addCallbackToConnectionIndex(
    ConnectionImpl connection,
    String topicExpression,
    boolean isWildcarded,
    ConsumerSetChangeCallback callback)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.entry(
          tc,
          "addCallbackToConnectionIndex",
          new Object[] {connection, topicExpression, new Boolean(isWildcarded), callback });

    // Map of callbacks-to-expressions for a connection
    Map connMap = null;
    if(_callbackIndex.containsKey(connection))
    {
      // Already have registered callbacks for this connection
      connMap = (HashMap)_callbackIndex.get(connection);
    }
    else
    {
      // No registered callbacks for this connection
      connMap = new HashMap();
      _callbackIndex.put(connection,connMap);
    }

    // Add the new callback to the index, so we can find it when we deregister
    TopicRecord tRecord = new TopicRecord(topicExpression, isWildcarded);
    connMap.put(callback, tRecord);

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "addCallbackToConnectionIndex");

  }
1219664
public <T> JdbcIndex<T> buildIndex(Class<T> model) {
        JdbcIndex<T> index = new JdbcIndex<>();

        index.setModelClass(model);
        index.setName(indexNameTranslator.translate(model));

        index.setFields(buildFields(index));

        return index;
    }
1245244
def _build_query(self, table, tree, visitor):
        
        kwargs = {}
        index = None
        if tree.using:
            index_name = kwargs["index"] = tree.using[1]
            index = table.get_index(index_name)
        if tree.where:
            constraints = ConstraintExpression.from_where(tree.where)
            possible_hash = constraints.possible_hash_fields()
            possible_range = constraints.possible_range_fields()
            if index is None:
                # See if we can find an index to query on
                indexes = table.get_matching_indexes(possible_hash, possible_range)
                if not indexes:
                    action = "scan"
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
                elif len(indexes) == 1:
                    index = indexes[0]
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    names = ", ".join([index.name for index in indexes])
                    raise SyntaxError(
                        "No index specified with USING <index>, "
                        "but multiple possibilities for query: "
                        "%s" % names
                    )
            else:
                if index.hash_key in possible_hash:
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    action = "scan"
                    if not index.scannable:
                        raise SyntaxError("Cannot scan local index %r" % index_name)
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
        else:
            action = "scan"
        return [action, kwargs, index]
1216881
private Connection createConnection() {

    if (mConnInfo != null) {
      DBConnCreator dbConnCreator = new DBConnCreator(mConnInfo);
      Connection conn = dbConnCreator.createDBConnection();
      return conn;
    } else if (mDbcpPropertyFile != null) {
      Properties properties = new Properties();
      InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(mDbcpPropertyFile);
      try {
        properties.load(is);
        DataSource ds;
        ds = BasicDataSourceFactory.createDataSource(properties);
        Connection conn = ds.getConnection();
        return conn;
      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

    }
    return null;

  }
813276
def init_from_database(self, conn, database, table_name):
        
        info = conn.query('SHOW TABLE STATUS FROM `{database}` WHERE name="{table_name}"'.format(
            table_name=table_name, database=database), as_dict=True).fetchone()
        if info is None:
            if table_name == '~log':
                logger.warning('Could not create the ~log table')
                return
            else:
                raise DataJointError('The table `{database}`.`{table_name}` is not defined.'.format(
                    table_name=table_name, database=database))
        self.table_info = {k.lower(): v for k, v in info.items()}

        cur = conn.query(
            'SHOW FULL COLUMNS FROM `{table_name}` IN `{database}`'.format(
                table_name=table_name, database=database), as_dict=True)

        attributes = cur.fetchall()

        rename_map = {
            'Field': 'name',
            'Type': 'type',
            'Null': 'nullable',
            'Default': 'default',
            'Key': 'in_key',
            'Comment': 'comment'}

        fields_to_drop = ('Privileges', 'Collation')

        # rename and drop attributes
        attributes = [{rename_map[k] if k in rename_map else k: v
                       for k, v in x.items() if k not in fields_to_drop}
                      for x in attributes]

        numeric_types = {
            ('float', False): np.float64,
            ('float', True): np.float64,
            ('double', False): np.float64,
            ('double', True): np.float64,
            ('tinyint', False): np.int64,
            ('tinyint', True): np.int64,
            ('smallint', False): np.int64,
            ('smallint', True): np.int64,
            ('mediumint', False): np.int64,
            ('mediumint', True): np.int64,
            ('int', False): np.int64,
            ('int', True): np.int64,
            ('bigint', False): np.int64,
            ('bigint', True): np.uint64}

        sql_literals = ['CURRENT_TIMESTAMP']

        # additional attribute properties
        for attr in attributes:
            # process external attributes
            split_comment = attr['comment'].split(':')
            attr['is_external'] = len(split_comment) >= 3 and split_comment[1].startswith('external')
            if attr['is_external']:
                attr['comment'] = ':'.join(split_comment[2:])
                attr['type'] = split_comment[1]

            attr['nullable'] = (attr['nullable'] == 'YES')
            attr['in_key'] = (attr['in_key'] == 'PRI')
            attr['autoincrement'] = bool(re.search(r'auto_increment', attr['Extra'], flags=re.IGNORECASE))
            attr['type'] = re.sub(r'int\(\d+\)', 'int', attr['type'], count=1)   # strip size off integers
            attr['numeric'] = bool(re.match(r'(tiny|small|medium|big)?int|decimal|double|float', attr['type']))
            attr['string'] = bool(re.match(r'(var)?char|enum|date|year|time|timestamp', attr['type']))
            attr['is_blob'] = attr['is_external'] or bool(re.match(r'(tiny|medium|long)?blob', attr['type']))
            attr['database'] = database

            if attr['string'] and attr['default'] is not None and attr['default'] not in sql_literals:
                attr['default'] = '"%s"' % attr['default']

            if attr['nullable']:   # nullable fields always default to null
                attr['default'] = 'null'

            attr['sql_expression'] = None
            if not (attr['numeric'] or attr['string'] or attr['is_blob']):
                raise DataJointError('Unsupported field type {field} in `{database}`.`{table_name}`'.format(
                    field=attr['type'], database=database, table_name=table_name))
            attr.pop('Extra')

            # fill out dtype. All floats and non-nullable integers are turned into specific dtypes
            attr['dtype'] = object
            if attr['numeric']:
                is_integer = bool(re.match(r'(tiny|small|medium|big)?int', attr['type']))
                is_float = bool(re.match(r'(double|float)', attr['type']))
                if is_integer and not attr['nullable'] or is_float:
                    is_unsigned = bool(re.match('\sunsigned', attr['type'], flags=re.IGNORECASE))
                    t = attr['type']
                    t = re.sub(r'\(.*\)', '', t)    # remove parentheses
                    t = re.sub(r' unsigned$', '', t)   # remove unsigned
                    assert (t, is_unsigned) in numeric_types, 'dtype not found for type %s' % t
                    attr['dtype'] = numeric_types[(t, is_unsigned)]
        self.attributes = OrderedDict([(q['name'], Attribute(**q)) for q in attributes])

        # Read and tabulate secondary indexes
        keys = defaultdict(dict)
        for item in conn.query('SHOW KEYS FROM `{db}`.`{tab}`'.format(db=database, tab=table_name), as_dict=True):
            if item['Key_name'] != 'PRIMARY':
                keys[item['Key_name']][item['Seq_in_index']] = dict(
                    column=item['Column_name'],
                    unique=(item['Non_unique'] == 0),
                    nullable=item['Null'].lower() == 'yes')
        self.indexes = {
            tuple(item[k]['column'] for k in sorted(item.keys())):
                dict(unique=item[1]['unique'],
                     nullable=any(v['nullable'] for v in item.values()))
            for item in keys.values()}
190868
def init_db_conn(connection_name, HOSTS=None):
    
    el = elasticsearch.Elasticsearch(hosts=HOSTS)
    el_pool.connections[connection_name] = ElasticSearchClient(el)
957564
def indexables(self):
        
        if self._indexables is None:

            self._indexables = []

            # index columns
            self._indexables.extend([
                IndexCol(name=name, axis=axis, pos=i)
                for i, (axis, name) in enumerate(self.attrs.index_cols)
            ])

            # values columns
            dc = set(self.data_columns)
            base_pos = len(self._indexables)

            def f(i, c):
                klass = DataCol
                if c in dc:
                    klass = DataIndexableCol
                return klass.create_for_block(i=i, name=c, pos=base_pos + i,
                                              version=self.version)

            self._indexables.extend(
                [f(i, c) for i, c in enumerate(self.attrs.values_cols)])

        return self._indexables
1295764
private void createIndexTables(AccumuloTable table)
    {
        // Early-out if table is not indexed
        if (!table.isIndexed()) {
            return;
        }

        // Create index table if it does not exist (for 'external' table)
        if (!tableManager.exists(table.getIndexTableName())) {
            tableManager.createAccumuloTable(table.getIndexTableName());
        }

        // Create index metrics table if it does not exist
        if (!tableManager.exists(table.getMetricsTableName())) {
            tableManager.createAccumuloTable(table.getMetricsTableName());
        }

        // Set locality groups on index and metrics table
        Map<String, Set<Text>> indexGroups = Indexer.getLocalityGroups(table);
        tableManager.setLocalityGroups(table.getIndexTableName(), indexGroups);
        tableManager.setLocalityGroups(table.getMetricsTableName(), indexGroups);

        // Attach iterators to metrics table
        for (IteratorSetting setting : Indexer.getMetricIterators(table)) {
            tableManager.setIterator(table.getMetricsTableName(), setting);
        }
    }
1054821
public static <T> int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass)
			throws SQLException {
		Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);
		return doCreateTable(dao, true);
	}
132439
def _create_indices(self, table_name, indices):
        
        require_string(table_name, "table_name")
        require_iterable_of(indices, (tuple, list))
        for index_column_set in indices:
            self._create_index(table_name, index_column_set)
596241
private function buildIndexes() {
        $indexes = array();
        /** @var ResultSet $results */
        $results = $this->getConfiguration()->getConnection()->query('SHOW INDEX FROM `' . $this->getTableName() . '`');
        while($result = $results->fetch()) {
            $result = (object)$result;
            if(!array_key_exists($result->Key_name, $indexes)) {
                $indexes[$result->Key_name] = new Index();
            }
            /** @var Index $index */
            $index = $indexes[$result->Key_name];
            $index->setUnique(!$result->Non_unique);
            $index->addColumn($result->Column_name);
            $index->setPrimary($result->Key_name == 'PRIMARY');
        }
        $this->setIndexes($indexes);
    }
1134420
public Crud<T, K> table(Connection connection, String table) throws SQLException {
        CrudMeta crudMeta = CrudMeta.of(connection, table, jdbcMapperFactory.columnDefinitions());
        return CrudFactory.<T, K>newInstance(target, keyTarget, crudMeta, jdbcMapperFactory);
    }
134390
private static Set<String> getIndexedColumnSetForTable(Table table) {
        HashSet<String> columns = new HashSet<>();

        for (Index index : table.getIndexes()) {
            for (ColumnRef colRef : index.getColumns()) {
                columns.add(colRef.getColumn().getTypeName());
            }
        }

        return columns;
    }