Change table column names, otherwise leaving table unaltered

    Parameters
    ----------
    substitutions

    Returns
    -------
    relabeled : TableExpr
188248
def _table_relabel(table, substitutions, replacements=None):
    
    if replacements is not None:
        raise NotImplementedError

    observed = set()

    exprs = []
    for c in table.columns:
        expr = table[c]
        if c in substitutions:
            expr = expr.name(substitutions[c])
            observed.add(c)
        exprs.append(expr)

    for c in substitutions:
        if c not in observed:
            raise KeyError('{0!r} is not an existing column'.format(c))

    return table.projection(exprs)
983605
def get_alter_table_sql(self, diff):
        
        column_sql = []
        query_parts = []

        if diff.new_name is not False:
            query_parts.append('RENAME TO %s' % diff.new_name)

        # Added columns?

        # Removed columns?

        for column_diff in diff.changed_columns.values():
            column = column_diff.column
            column_dict = column.to_dict()

            # Don't propagate default value changes for unsupported column types.
            if column_diff.has_changed('default') \
                    and len(column_diff.changed_properties) == 1 \
                    and (column_dict['type'] == 'text' or column_dict['type'] == 'blob'):
                continue

            query_parts.append('CHANGE %s %s'
                               % (column_diff.get_old_column_name(),
                                  self.get_column_declaration_sql(column.get_name(), column_dict)))

        for old_column_name, column in diff.renamed_columns.items():
            column_dict = column.to_dict()
            query_parts.append('CHANGE %s %s'
                               % (self.quote(old_column_name),
                                  self.get_column_declaration_sql(self.quote(column.get_name()), column_dict)))

        sql = []

        if len(query_parts) > 0:
            sql.append('ALTER TABLE %s %s' % (diff.name, ', '.join(query_parts)))

        return sql
1287334
def column_rename(self, existing_name, hsh=None):
        
        try:
            existing_name = str(existing_name)
        except UnicodeEncodeError:
            pass
        if hsh is None:
            hsh = self._hash()
        if self._name:
            return '%s(%s) [%s]' %(self._name, self._remove_hashes(existing_name),
                    hsh)
        return '%s [%s]'%(self._remove_hashes(existing_name),
                    hsh)
647587
def convert_table(app, docname, source):
    """"""
    num_tables = 0
    for i,j in enumerate(source):
        table = []
        output = ''
        in_table = False
        for l in j.split('\n'):
            r = l.strip()
            if r.startswith('|'):
                table.append(r)
                in_table = True
            else:
                if in_table is True:
                    converted = _convert_md_table_to_rst(table)
                    if converted is '':
                        print("Failed to convert the markdown table")
                        print(table)
                    else:
                        num_tables += 1
                    output += converted
                    in_table = False
                    table = []
                output += l + '\n'
        source[i] = output
    if num_tables > 0:
        print('Converted %d tables in %s' % (num_tables, docname))
1339293
def get_foreign_keys_in_altered_table(self, diff):
        
        foreign_keys = diff.from_table.get_foreign_keys()
        column_names = self.get_column_names_in_altered_table(diff)

        for key, constraint in foreign_keys.items():
            changed = False
            local_columns = []
            for column_name in constraint.get_local_columns():
                normalized_column_name = column_name.lower()
                if normalized_column_name not in column_names:
                    del foreign_keys[key]
                    break
                else:
                    local_columns.append(column_names[normalized_column_name])
                    if column_name != column_names[normalized_column_name]:
                        changed = True

            if changed:
                pass

        return foreign_keys
30423
def rename(self, old_table, new_table):
        
        try:
            command = 'RENAME TABLE {0} TO {1}'.format(wrap(old_table), wrap(new_table))
        except:
            command = 'ALTER TABLE {0} RENAME {1}'.format(wrap(old_table), wrap(new_table))
        self.execute(command)
        self._printer('Renamed {0} to {1}'.format(wrap(old_table), wrap(new_table)))
        return old_table, new_table
744941
public static function renameColumn(string $table, string $oldColumn, string $newColumn): string
    {
        $query = self::getQuery(true);

        return (string) $query->element(
            'exec sp_rename',
            $query->quote([
                $table . '.' . $oldColumn,
                $newColumn,
                'COLUMN'
            ])
        );
    }
279680
def UpdateColums(self, cursor, field, FieldType, model, columns, UNCHANGED):
        '''
        '''
        table = model.__name__.lower()
        if field not in columns:
            n = UNCHANGED.pop()
            new_sql = f"ALTER TABLE {table} ADD COLUMN {field} {FieldType} AFTER {n}"
            cursor.execute(new_sql)
            print("\n\n", new_sql)
        else:
            UNCHANGED.append(field)

        # We drop the fields in the table not in models
        TCOLS = set(columns)-set(model._fields)
        for col in TCOLS:
            columns.remove(col)
            QRY = f"ALTER TABLE {table} DROP COLUMN {col}"
            cursor.execute(QRY)
            print("\n\n", QRY)

        return True
1006643
def _columns_for_table(table_name):
    
    return {cname: col
            for (tname, cname), col in _COLUMNS.items()
            if tname == table_name}
811707
def rename_column(self, column, new_name):
        
        if type(column) is not str: column = self.ckeys[column]
        self.ckeys[self.ckeys.index(column)] = new_name
        self.columns[new_name] = self.columns.pop(column)
        return self
366519
def _sanitize_column_names(data):
    """"""
    new_names = {}
    for name in data.columns:
        new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
    return new_names
1216288
def nextColRegex(sheet, colregex):
    ''
    pivot = sheet.cursorVisibleColIndex
    for i in itertools.chain(range(pivot+1, len(sheet.visibleCols)), range(0, pivot+1)):
        c = sheet.visibleCols[i]
        if re.search(colregex, c.name, regex_flags()):
            return i

    fail('no column name matches /%s/' % colregex)
138504
def get_alter_table_sql(self, diff):
        
        sql = self._get_simple_alter_table_sql(diff)
        if sql is not False:
            return sql

        from_table = diff.from_table
        if not isinstance(from_table, Table):
            raise DBALException(
                "SQLite platform requires for the alter table the table diff "
                "referencing the original table"
            )

        table = from_table.clone()
        columns = OrderedDict()
        old_column_names = OrderedDict()
        new_column_names = OrderedDict()
        column_sql = []
        for column_name, column in table.get_columns().items():
            column_name = column_name.lower()
            columns[column_name] = column
            old_column_names[column_name] = column.get_quoted_name(self)
            new_column_names[column_name] = column.get_quoted_name(self)

        for column_name, column in diff.removed_columns.items():
            column_name = column_name.lower()
            if column_name in columns:
                del columns[column_name]
                del old_column_names[column_name]
                del new_column_names[column_name]

        for old_column_name, column in diff.renamed_columns.items():
            old_column_name = old_column_name.lower()
            if old_column_name in columns:
                del columns[old_column_name]

            columns[column.get_name().lower()] = column

            if old_column_name in new_column_names:
                new_column_names[old_column_name] = column.get_quoted_name(self)

        for old_column_name, column_diff in diff.changed_columns.items():
            if old_column_name in columns:
                del columns[old_column_name]

            columns[column_diff.column.get_name().lower()] = column_diff.column

            if old_column_name in new_column_names:
                new_column_names[old_column_name] = column_diff.column.get_quoted_name(
                    self
                )

        for column_name, column in diff.added_columns.items():
            columns[column_name.lower()] = column

        table_sql = []

        data_table = Table("__temp__" + table.get_name())
        new_table = Table(
            table.get_quoted_name(self),
            columns,
            self._get_primary_index_in_altered_table(diff),
            self._get_foreign_keys_in_altered_table(diff),
            table.get_options(),
        )
        new_table.add_option("alter", True)

        sql = self.get_pre_alter_table_index_foreign_key_sql(diff)
        sql.append(
            "CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s"
            % (
                data_table.get_quoted_name(self),
                ", ".join(old_column_names.values()),
                table.get_quoted_name(self),
            )
        )
        sql.append(self.get_drop_table_sql(from_table))

        sql += self.get_create_table_sql(new_table)
        sql.append(
            "INSERT INTO %s (%s) SELECT %s FROM %s"
            % (
                new_table.get_quoted_name(self),
                ", ".join(new_column_names.values()),
                ", ".join(old_column_names.values()),
                data_table.get_name(),
            )
        )
        sql.append(self.get_drop_table_sql(data_table))

        sql += self.get_post_alter_table_index_foreign_key_sql(diff)

        return sql
1108259
def from_(self, table, alias=None):
        
        if isinstance(table, str):
            table = [[table, alias]]
        self.raw_tables = table
        return self
921006
def bind_to(self, table, name):
        
        if self.bound_to is not None:
            raise AttributeError(
                "Column is already bound to '%s' as '%s'" %\
                    self.bound_to)

        self.bound_to = (table, name)
288376
def requiredUnlessTable(col_name, arg, dm, df, con=None):
    
    table_name = arg
    if col_name in df.columns:
        return None
    elif not con:
        return None
    elif table_name in con.tables:
        return None
    else:
        return "{} column is required unless table {} is present".format(col_name, table_name)
760311
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
        
        tables = self._parse_tables(soup)
        v_sep_len = len(v_separator)
        v_left_sep = v_separator.lstrip()
        for t in tables:
            html = ''
            trs = t['trs']
            h_length = 1 + (v_sep_len * len(t['col_width'])) + t['width']
            head_foot = (h_separator * h_length) + "\n"
            html += head_foot
            for tr in trs:
                html += v_left_sep
                for i, td in enumerate(tr):
                    text = td['text']
                    col_width = t['col_width'][i] + v_sep_len
                    if td['colspan'] > 1:
                        for j in range(td['colspan']-1):
                            j = j + 1
                            if (i+j) < len(t['col_width']):
                                col_width += t['col_width'][i+j] + v_sep_len
                    html += ('%' + str(col_width) + 's') % (text + v_separator)
                html += "\n"
            html += head_foot
            new_table = soup.new_tag('div')
            new_table.string = html
            t['table'].replace_with(new_table)
        return soup