create from definition
PRIMARY KEY(col1, ...)
UNIQUE KEY(col1, ...)
KEY(col1, ...)
338516
public static function create($name, $definition)
    {
        if (preg_match('/^(.*?)KEY\s*\((.*?)\)/', $definition, $matches)) {
            return new self([
                'name' => $name,
                'columns' => preg_split('/\s*,\s*/', $matches[2]),
                'type' => trim($matches[1])
            ]);
        } else {
            throw new \InvalidArgumentException("Invalid index definition '$definition'");
        }
    }
1028545
public String getKeyType(UniqueKeyDefinition key){
        String tType;

        List<ColumnDefinition> keyColumns = key.getKeyColumns();

        if (keyColumns.size() == 1) {
            tType = getJavaType(keyColumns.get(0).getType());
        }
        else if (keyColumns.size() <= Constants.MAX_ROW_DEGREE) {
            String generics = "";
            String separator = "";

            for (ColumnDefinition column : keyColumns) {
                generics += separator + (getJavaType(column.getType()));
                separator = ", ";
            }

            tType = Record.class.getName() + keyColumns.size() + "<" + generics + ">";
        }
        else {
            tType = Record.class.getName();
        }

        return tType;
    }
134568
private Record newRecordFromCql(Key key, Iterable<Row> rows, Placement placement, String rowKey) {
        Session session = placement.getKeyspace().getCqlSession();
        ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
        CodecRegistry codecRegistry = session.getCluster().getConfiguration().getCodecRegistry();

        Iterator<Map.Entry<DeltaClusteringKey, Change>> changeIter = decodeChangesFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
        Iterator<Map.Entry<DeltaClusteringKey, Compaction>> compactionIter = decodeCompactionsFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
        Iterator<RecordEntryRawMetadata> rawMetadataIter = rawMetadataFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));

        return new RecordImpl(key, compactionIter, changeIter, rawMetadataIter);
    }
149972
private void createTablesAndPkAndIndexes() {

        for (Table t : metadata.getTables()) {
            comment(" == TABLES [ " + t.getName() + " ] =======================");

            createTable(t);
            createIndexes(t);
            if (t.hasH2IdentityPk()) {
                line("ALTER TABLE ", t.getName(), " ALTER COLUMN ", t.getPrimaryKey(), " IDENTITY;");
            } else if (t.hasPk()) {
                line("CREATE PRIMARY KEY ON ", t.getName(), " (", toCsvString(t.getPrimaryKeys()), ");");
            }
            line("");
        }
    }
467532
def _construct_columns(self, column_map):
        
        '''  '''
        
        from sqlalchemy import Column, String, Boolean, Integer, Float, Binary 
    
        column_args = []
        for key, value in column_map.items():
            record_key = value[0]
            datatype = value[1]
            max_length = value[2]
            if record_key == 'id':
                if datatype in ('string', 'float', 'integer'):
                    if datatype == 'string':
                        if max_length:
                            column_args.insert(0, Column(record_key, String(max_length), primary_key=True))
                        else:
                            column_args.insert(0, Column(record_key, String, primary_key=True))
                    elif datatype == 'float':
                        column_args.insert(0, Column(record_key, Float, primary_key=True))
                    elif datatype == 'integer':
                        column_args.insert(0, Column(record_key, Integer, primary_key=True))
                else:
                    raise ValueError('Field "id" in record_schema must be a string, float or integer.')
            else:
                if datatype == 'boolean':
                    column_args.append(Column(record_key, Boolean))
                elif datatype == 'string':
                    if max_length:
                        column_args.append(Column(record_key, String(max_length)))
                    else:
                        column_args.append(Column(record_key, String))
                elif datatype == 'float':
                    column_args.append(Column(record_key, Float))
                elif datatype == 'integer':
                    column_args.append(Column(record_key, Integer))
                elif datatype == 'list':
                    column_args.append(Column(record_key, Binary))
        
        return column_args
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
1248249
def make_key(table_name, objid):
    """"""
    key = datastore.Key()
    path = key.path_element.add()
    path.kind = table_name
    path.name = str(objid)
    return key
1217031
def create_table(table_name, options = {})
      table_definition = TableDefinition.new
      table_definition.define_primary_keys(options[:primary_keys]) if options[:primary_keys]
      table_definition.define_partition_keys(options[:partition_keys]) if options[:partition_keys]
      table_definition.define_options(options[:options]) if options[:options]

      yield table_definition if block_given?

      announce_operation "create_table(#{table_name})"

      create_cql =  "CREATE TABLE #{table_name} ("
      create_cql << table_definition.to_create_cql
      create_cql << ")"
      create_cql << table_definition.options

      announce_suboperation create_cql

      execute create_cql
    end
83607
def create_index(column_names, unique=False):
    
    connection = _State.connection()
    _State.reflect_metadata()
    table_name = _State.table.name

    table = _State.table

    index_name = re.sub(r'[^a-zA-Z0-9]', '', table_name) + '_'
    index_name += '_'.join(re.sub(r'[^a-zA-Z0-9]', '', x)
                           for x in column_names)

    if unique:
        index_name += '_unique'

    columns = []
    for column_name in column_names:
        columns.append(table.columns[column_name])

    current_indices = [x.name for x in table.indexes]
    index = sqlalchemy.schema.Index(index_name, *columns, unique=unique)
    if index.name not in current_indices:
        index.create(bind=_State.engine)
192654
private void addColumn(String storeName, String rowKey, String colName, byte[] colValue) {
        Map<String, Map<String, byte[]>> rowMap = m_columnAdds.get(storeName);
        if (rowMap == null) {
            rowMap = new HashMap<>();
            m_columnAdds.put(storeName, rowMap);
        }
        
        Map<String, byte[]> colMap = rowMap.get(rowKey);
        if (colMap == null) {
            colMap = new HashMap<>();
            rowMap.put(rowKey, colMap);
        }
        
        byte[] oldValue = colMap.put(colName, colValue);
        if (oldValue == null) {
            m_totalUpdates++;
        } else if (!Arrays.equals(oldValue, colValue)) {
            m_logger.debug("Warning: duplicate column mutation with different value: " +
                           "store={}, row={}, col={}, old={}, new={}",
                           new Object[]{storeName, rowKey, colName, oldValue, colValue});
        }
    }
485546
def keys(self):
        """"""
        return set(
            row[self._keycol] for row in self._connection.execute(
                """SELECT DISTINCT {} FROM {} ORDER BY {} ASC;""".format(
                    self.selkeycol,
                    self.table,
                    self._keycol
                )
            )
        )
177034
def all_unique(keys, axis=semantics.axis_default):
    """"""
    index = as_index(keys, axis)
    return index.groups == index.size
320616
public Entry newEntry(Key key, QualifiedName entity) {
	Entry res = of.createEntry();
	res.setKey(key);
	res.setEntity(entity);
	return res;
    }
522264
def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
        """"""
        sql = fieldspec["name"] + " " + fieldspec["sqltype"]
        if "notnull" in fieldspec and fieldspec["notnull"]:
            sql += " NOT NULL"
        if "autoincrement" in fieldspec and fieldspec["autoincrement"]:
            sql += " AUTO_INCREMENT"
        if "pk" in fieldspec and fieldspec["pk"]:
            sql += " PRIMARY KEY"
        else:
            if "unique" in fieldspec and fieldspec["unique"]:
                sql += " UNIQUE"
        if "comment" in fieldspec:
            sql += " COMMENT " + sql_quote_string(fieldspec["comment"])
        return sql
907349
private String[] buildRowKeyColumnNamesForStarToOne(OgmEntityPersister persister, String[] keyColumnNames) {
		String[] identifierColumnNames = persister.getIdentifierColumnNames();
		int length = identifierColumnNames.length + keyColumnNames.length;
		String[] rowKeyColumnNames = new String[length];
		System.arraycopy( identifierColumnNames, 0, rowKeyColumnNames, 0, identifierColumnNames.length );
		System.arraycopy( keyColumnNames, 0, rowKeyColumnNames, identifierColumnNames.length, keyColumnNames.length );
		return rowKeyColumnNames;
	}
1307122
public void createPrimaryKey(HsqlName indexName, int[] columns,
                                 boolean columnsNotNull) {

        if (primaryKeyCols != null) {
            throw Error.runtimeError(ErrorCode.U_S0500, "Table");
        }

        if (columns == null) {
            columns = ValuePool.emptyIntArray;
        } else {
            for (int i = 0; i < columns.length; i++) {
                getColumn(columns[i]).setPrimaryKey(true);
            }
        }

        primaryKeyCols = columns;

        setColumnStructures();

        primaryKeyTypes = new Type[primaryKeyCols.length];

        ArrayUtil.projectRow(colTypes, primaryKeyCols, primaryKeyTypes);

        primaryKeyColsSequence = new int[primaryKeyCols.length];

        ArrayUtil.fillSequence(primaryKeyColsSequence);

        HsqlName name = indexName;

        if (name == null) {
            name = database.nameManager.newAutoName("IDX", getSchemaName(),
                    getName(), SchemaObject.INDEX);
        }

        createPrimaryIndex(primaryKeyCols, primaryKeyTypes, name);
        setBestRowIdentifiers();
    }
431065
def _model_unique(ins):
    
    unique = []
    for t in ins.tables:
        for c in t.constraints:
            if isinstance(c, UniqueConstraint):
                unique.append(tuple(col.key for col in c.columns))
    return unique