creates a SQLAlchemy Table object with the appropriate number of
        columns given the number of feeds
492756
def _datatable_factory(self):
        
        feed_cols = ['feed{0:03d}'.format(i + 1) for i in range(self.n_feeds)]
        feed_cols = ['override_feed000'] + feed_cols + ['failsafe_feed999']

        ind_sqlatyp = indexingtypes[self.index.indimp].sqlatyp
        dat_sqlatyp = datadefs[self.dtype.datadef].sqlatyp

        atbl = Table(self.name, Base.metadata,
                     Column('indx', ind_sqlatyp, primary_key=True),
                     Column('final', dat_sqlatyp),
                     *(Column(fed_col, dat_sqlatyp) for fed_col in feed_cols),
                     extend_existing=True)
        
        self.dt_feed_cols = feed_cols[:]
        self.dt_all_cols = ['indx', 'final'] + feed_cols[:]
        return atbl
1298432
def generate_schema(table, export_fields, output_format, output_fobj):
    

    if output_format in ("csv", "txt"):
        from rows import plugins

        data = [
            {
                "field_name": fieldname,
                "field_type": fieldtype.__name__.replace("Field", "").lower(),
            }
            for fieldname, fieldtype in table.fields.items()
            if fieldname in export_fields
        ]
        table = plugins.dicts.import_from_dicts(
            data, import_fields=["field_name", "field_type"]
        )
        if output_format == "txt":
            plugins.txt.export_to_txt(table, output_fobj)
        elif output_format == "csv":
            plugins.csv.export_to_csv(table, output_fobj)

    elif output_format == "sql":
        # TODO: may use dict from rows.plugins.sqlite or postgresql
        sql_fields = {
            rows.fields.BinaryField: "BLOB",
            rows.fields.BoolField: "BOOL",
            rows.fields.IntegerField: "INT",
            rows.fields.FloatField: "FLOAT",
            rows.fields.PercentField: "FLOAT",
            rows.fields.DateField: "DATE",
            rows.fields.DatetimeField: "DATETIME",
            rows.fields.TextField: "TEXT",
            rows.fields.DecimalField: "FLOAT",
            rows.fields.EmailField: "TEXT",
            rows.fields.JSONField: "TEXT",
        }
        fields = [
            "    {} {}".format(field_name, sql_fields[field_type])
            for field_name, field_type in table.fields.items()
            if field_name in export_fields
        ]
        sql = (
            dedent(
                """
                CREATE TABLE IF NOT EXISTS {name} (
                {fields}
                );
                """
            )
            .strip()
            .format(name=table.name, fields=",\n".join(fields))
            + "\n"
        )
        output_fobj.write(sql)

    elif output_format == "django":
        django_fields = {
            rows.fields.BinaryField: "BinaryField",
            rows.fields.BoolField: "BooleanField",
            rows.fields.IntegerField: "IntegerField",
            rows.fields.FloatField: "FloatField",
            rows.fields.PercentField: "DecimalField",
            rows.fields.DateField: "DateField",
            rows.fields.DatetimeField: "DateTimeField",
            rows.fields.TextField: "TextField",
            rows.fields.DecimalField: "DecimalField",
            rows.fields.EmailField: "EmailField",
            rows.fields.JSONField: "JSONField",
        }
        table_name = "".join(word.capitalize() for word in table.name.split("_"))

        lines = ["from django.db import models"]
        if rows.fields.JSONField in [
            table.fields[field_name] for field_name in export_fields
        ]:
            lines.append("from django.contrib.postgres.fields import JSONField")
        lines.append("")

        lines.append("class {}(models.Model):".format(table_name))
        for field_name, field_type in table.fields.items():
            if field_name not in export_fields:
                continue

            if field_type is not rows.fields.JSONField:
                django_type = "models.{}()".format(django_fields[field_type])
            else:
                django_type = "JSONField()"
            lines.append("    {} = {}".format(field_name, django_type))

        result = "\n".join(lines) + "\n"
        output_fobj.write(result)
1033755
def to_tables(cols):
  
  tables = OrderedDict()
  for col in cols:
    tname = col["table_name"]
    if tname not in tables:
      tables[tname] = OrderedDict()
    tables[tname][col["column_name"]] = col
  return tables
471697
def table_columns(self):
        ''''''
        with self.conn.cursor() as cur:
            cur.execute(self.TABLE_COLUMNS_QUERY % self.database)
            for row in cur:
                yield row
426787
def dataframe(df, **kwargs):
    
    table(df.values, list(df.columns), **kwargs)
451484
def createTable(dbconn, pd):
    """"""
    cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields)
    sql  = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols))

    dbconn.execute(sql)
    dbconn.commit()
1308140
def columns(self):
        
        c = self._connection.cursor()
        c.execute("describe `%s`.`%s`" % (self._db, self._name))
        self._cols = []
        for col in c.fetchall():
            self._cols.append(Column.build(col, table=self, con=self._connection))
        return self._cols
1122858
def load_table(self, table, rows, colnames=None, limit=None):
        

        conn = self.engine.raw_connection()
        cur = conn.cursor()

        colnames = colnames or next(rows)

        cmd = 'INSERT INTO {table} ({colnames}) VALUES ({placeholders})'.format(
            table=self.tables[table],
            colnames=', '.join(colnames),
            placeholders=', '.join([self.placeholder] * len(colnames)))

        cur.executemany(cmd, itertools.islice(rows, limit))
        conn.commit()
127408
def create_table(name=str('_Table'), base=Table, options=None):
    
    try:
        base = tuple(base)
    except TypeError:
        # Then assume that what we have is a single class, so make it
        # into a 1-tuple.
        base = (base,)

    return TableMeta(name, base, options or {})
385862
def create_table(cls):
        
        schema_editor = getattr(connection, 'schema_editor', None)
        if schema_editor:
            with schema_editor() as schema_editor:
                schema_editor.create_model(cls)
        else:
            raw_sql, _ = connection.creation.sql_create_model(
                cls,
                no_style(),
                [])
            cls.delete_table()
            cursor = connection.cursor()
            try:
                cursor.execute(*raw_sql)
            finally:
                cursor.close()
877248
def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str:
    

    def min3(num: int) -> int:
        return 3 if num < 4 else num

    width_by_col: Dict[str, int] = {
        f: min3(max([string_width(str(d.get(f))) for d in data] + [string_width(f)])) for f in fieldnames
    }

    def fill_spaces(word: str, width: int, center=False):
        """ aaa, 4 => ' aaa  ' """
        to_fills: int = width - string_width(word)
        return f" {' ' * floor(to_fills / 2)}{word}{' ' * ceil(to_fills / 2)} " if center \
            else f" {word}{' ' * to_fills} "

    def to_record(r: dict) -> str:
        return f"|{'|'.join([fill_spaces(str(r.get(f)), width_by_col.get(f)) for f in fieldnames])}|"

    return f"""
|{'|'.join([fill_spaces(x, width_by_col.get(x), center=True) for x in fieldnames])}|
|{'|'.join([fill_spaces(width_by_col.get(x) * "-", width_by_col.get(x)) for x in fieldnames])}|
{os.linesep.join([to_record(x) for x in data])}
""".lstrip()
711624
def build_conversion_table(self, dataframes):
        
        self.data = pd.DataFrame(dataframes)
        tmp_pairs = [s.split("/") for s in self.data.columns]
        self.data.columns = pd.MultiIndex.from_tuples(tmp_pairs)
966395
def create_table(self, name, data, columns=None, add_pk=True):
        """"""
        # TODO: Issue occurs when bool values exist in data
        # Remove if the table exists
        if name in self.tables:
            self.drop(name)

        # Set headers list
        if not columns:
            columns = data[0]

        # Validate data shape
        for row in data:
            assert len(row) == len(columns)

        # Create dictionary of column types
        col_types = {columns[i]: sql_column_type([d[i] for d in data], prefer_int=True, prefer_varchar=True)
                     for i in range(0, len(columns))}

        # Join column types into SQL string
        cols = ''.join(['\t{0} {1},\n'.format(name, type_) for name, type_ in col_types.items()])[:-2] + '\n'
        statement = 'CREATE TABLE {0} ({1}{2})'.format(name, '\n', cols)
        self.execute(statement)
        if add_pk:
            self.set_primary_key_auto()
        return True
547141
def create_table_sql(cls, db):
        '''
        
        '''
        parts = ['CREATE TABLE IF NOT EXISTS `%s`.`%s` AS `%s`.`%s`' % (db.db_name, cls.table_name(), db.db_name,
                                                                        cls.engine.main_model.table_name())]
        engine_str = cls.engine.create_table_sql(db)
        parts.append(engine_str)
        return ' '.join(parts)
384036
def PyobjColumns(obj):
    ''
    return [ColumnAttr(k, type(getattr(obj, k))) for k in getPublicAttrs(obj)]
1289677
def from_columns_dict(cls, columns):
        """"""
        warnings.warn("Table.from_columns_dict is deprecated. Use Table().with_columns(...)", FutureWarning)
        return cls().with_columns(columns.items())
859875
def make_table(headers=None, rows=None):
    """"""
    if callable(headers):
        headers = headers()
    if callable(rows):
        rows = rows()
    assert isinstance(headers, list)
    assert isinstance(rows, list)
    assert all(len(row) == len(headers) for row in rows)

    plain_headers = [strip_ansi(six.text_type(v)) for v in headers]
    plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]]

    plain_headers = []
    column_widths = []

    for k, v in enumerate(headers):
        v = six.text_type(v)
        plain = strip_ansi(v)
        plain_headers.append(plain)
        column_widths.append(len(plain))

        if len(v) == len(plain):
            # Value was unstyled, make it bold
            v = click.style(v, bold=True)

        headers[k] = v

    plain_rows = []
    for row in rows:
        plain_row = []
        for k, v in enumerate(row):
            v = six.text_type(v)
            plain = strip_ansi(v)
            plain_row.append(plain)
            column_widths[k] = max(column_widths[k], len(plain))

        plain_rows.append(plain_row)

    return Table(
        headers=headers,
        plain_headers=plain_headers,
        rows=rows,
        plain_rows=plain_rows,
        column_widths=column_widths,
    )