Create an SQL table.
546421
def _initialize(self, chain, length):
        

        if self._getfunc is None:
            self._getfunc = self.db.model._funs_to_tally[self.name]

        # Determine size
        try:
            self._shape = np.shape(self._getfunc())
        except TypeError:
            self._shape = None

        self._vstr = ', '.join(var_str(self._shape))

        # If the table already exists, exit now.
        if chain != 0:
            return

        # Create the variable name strings.
        vstr = ', '.join(v + ' FLOAT' for v in var_str(self._shape))
        query = """CREATE TABLE IF NOT EXISTS [%s]
                     (recid INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                      trace  int(5), %s)""" % (self.name, vstr)
        self.db.cur.execute(query)
384324
def create_table(self):
        

        all_tables = self.aws_conn.list_tables()['TableNames']

        if self.table_name in all_tables:
            log.info("Table %s already exists" % self.table_name)
        else:
            log.info("Table %s does not exist: creating it" % self.table_name)

            self.table = Table.create(
                self.table_name,
                schema=[
                    HashKey('key')
                ],
                throughput={
                    'read': 10,
                    'write': 10,
                },
                connection=self.aws_conn,
            )
983452
private function createTable()
    {
        $stmt = 'CREATE TABLE IF NOT EXISTS "' . $this->name;
        $stmt.= '" ("' . $this->keyColumnName . '" TEXT PRIMARY KEY, "';
        $stmt.= $this->valueColumnName . '" TEXT);';
        $this->db->exec($stmt);
    }
1309275
function createDatabase(tx) {
    var schema = "clicks (id integer primary key, date text)"
    var sql = "create table if not exists " + schema

    tx.executeSql(sql, null, clearDatabase, sqlError);
}
1269315
def _create_sqlite_metatable(self):
        
        sys.stderr.write("Indexing schema. This will take a second...")
        rows_to_insert = []
        tables = [row[0] for row in self.cur.execute("select name from sqlite_master where type='table';")]
        for table in tables:
            for row in self.cur.execute("pragma table_info('{0}')".format(table)):
                rows_to_insert.append((table, row[1], row[2]))
        # find for table and column names
        self.cur.execute("drop table if exists tmp_dbpy_schema;")
        self.cur.execute("create temp table tmp_dbpy_schema(table_name varchar, column_name varchar, data_type varchar);")
        for row in rows_to_insert:
            self.cur.execute("insert into tmp_dbpy_schema(table_name, column_name, data_type) values('{0}', '{1}', '{2}');".format(*row))
        self.cur.execute("SELECT name, sql  FROM sqlite_master where sql like '%REFERENCES%';")

        # find for foreign keys
        self.cur.execute("drop table if exists tmp_dbpy_foreign_keys;")
        self.cur.execute("create temp table tmp_dbpy_foreign_keys(table_name varchar, column_name varchar, foreign_table varchar, foreign_column varchar);")
        foreign_keys = []
        self.cur.execute("SELECT name, sql  FROM sqlite_master ;")
        for (table_name, sql) in self.cur:
            rgx = "FOREIGN KEY \(\[(.*)\]\) REFERENCES \[(.*)\] \(\[(.*)\]\)"
            if sql is None:
                continue
            for (column_name, foreign_table, foreign_key) in re.findall(rgx, sql):
                foreign_keys.append((table_name, column_name, foreign_table, foreign_key))
        for row in foreign_keys:
            sql_insert = "insert into tmp_dbpy_foreign_keys(table_name, column_name, foreign_table, foreign_column) values('{0}', '{1}', '{2}', '{3}');"
            self.cur.execute(sql_insert.format(*row))

        self.con.commit()
        sys.stderr.write("finished!\n")
227001
def setup_sql(self, graphs):
        
        with closing(self.db.cursor()) as cursor:
            for table in graphs:
                cursor.execute(SQL.CREATE_TABLE % (table))
                for index in SQL.INDEXES:
                    cursor.execute(index % (table))
            self.db.commit()
81513
def format_sql(self):
        
        # TODO: finish adding the other parts of the sql generation
        sql = ''

        # build SELECT
        select_segment = self.build_select_fields()
        select_segment = select_segment.replace('SELECT ', '', 1)
        fields = [field.strip() for field in select_segment.split(',')]
        sql += 'SELECT\n\t{0}\n'.format(',\n\t'.join(fields))

        # build FROM
        from_segment = self.build_from_table()
        from_segment = from_segment.replace('FROM ', '', 1)
        tables = [table.strip() for table in from_segment.split(',')]
        sql += 'FROM\n\t{0}\n'.format(',\n\t'.join(tables))

        # build ORDER BY
        order_by_segment = self.build_order_by()
        if len(order_by_segment):
            order_by_segment = order_by_segment.replace('ORDER BY ', '', 1)
            sorters = [sorter.strip() for sorter in order_by_segment.split(',')]
            sql += 'ORDER BY\n\t{0}\n'.format(',\n\t'.join(sorters))

        # build LIMIT
        limit_segment = self.build_limit()
        if len(limit_segment):
            if 'LIMIT' in limit_segment:
                limit_segment = limit_segment.replace('LIMIT ', 'LIMIT\n\t', 1)
                if 'OFFSET' in limit_segment:
                    limit_segment = limit_segment.replace('OFFSET ', '\nOFFSET\n\t', 1)
            elif 'OFFSET' in limit_segment:
                limit_segment = limit_segment.replace('OFFSET ', 'OFFSET\n\t', 1)
            sql += limit_segment

        return sql
977183
protected void setUp() throws SQLException {
        Connection connection = getConnection();
        try {
            if (!isSetUp(connection)) {
                Statement stmt = connection.createStatement();
                stmt.execute(Query.CREATE_TABLE_RECORDS);
                stmt.execute(Query.CREATE_TABLE_FILEHASHES);
                stmt.execute(Query.CREATE_TABLE_META);
                stmt.execute(Query.CREATE_TABLE_CVES);
                stmt.close();
            }
        } finally {
            connection.close();
        }
    }
809829
def create_tables(args):
  """"""

  from bob.db.utils import create_engine_try_nolock
  engine = create_engine_try_nolock(args.type, args.files[0], echo=(args.verbose > 2))
  Base.metadata.create_all(engine)
54804
def execute_sql(self, sql):
        """"""
        cursor = self.get_cursor()
        cursor.execute(sql)
        return cursor
275991
def create_table(self, data, table_name, error_if_exists = False, **kwargs):
    ''

    converted_data = convert(data)
    if len(converted_data) == 0 or converted_data[0] == []:
      raise ValueError(u'You passed no sample values, or all the values you passed were null.')
    else:
      startdata = OrderedDict(converted_data[0])

    # Select a non-null item
    for k, v in startdata.items():
      if v != None:
        break
    else:
      v = None

    if_not_exists = u'' if error_if_exists else u'IF NOT EXISTS'

    # Do nothing if all items are null.
    if v != None:
      try:
        # This is vulnerable to injection.
        sql = u'''
          CREATE TABLE %s %s (
            %s %s
          );''' % (if_not_exists, quote(table_name), quote(k), get_column_type(startdata[k]))
        self.execute(sql, commit = False)
      except:
        raise
      else:
        self.commit()

      for row in converted_data:
        self.__check_and_add_columns(table_name, row)
1346154
def init_database(self):
        """"""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute("""
              CREATE TABLE IF NOT EXISTS users(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name VARCHAR(32)
              )
            """)
293862
def create_table(group, name, dtype, **attributes):
    """"""
    dset = group.create_dataset(
        name, shape=(0,), dtype=dtype, maxshape=(None,))
    set_attributes(dset, **attributes)
    return dset
1060781
async def setup(self):
        """"""
        try:
            engine = await self.db
            created = False
            if not await engine.has_table(self.table_name):
                # create table
                logger.info("Creating SQL table [{}]".format(self.table_name))
                items = self._get_table()
                await engine.execute(CreateTable(items))
                # create indeces
                conn = await engine.connect()
                await conn.execute(
                    "CREATE INDEX `lb_last_updated` ON `{}` (`source_id` DESC,`updated` DESC);".format(self.table_name))
                await conn.execute(
                    "CREATE INDEX `lb_post` ON `{}` (`target_id` DESC,`post_id` DESC);".format(self.table_name))
                await conn.close()
                created = True
            # create control table if not already created.
            if self.control_table_name and not await engine.has_table(self.control_table_name):
                # create table
                logger.info("Creating SQL control table [{}]".format(self.control_table_name))
                items = self._get_control_table()
                await engine.execute(CreateTable(items))
                created = True
            return created
        except Exception as exc:
            logger.error("[DB] Error when setting up SQL table: {}".format(exc))
        return False
25835
protected function createTable()
    {
        if ($this->db->getTableSchema($this->tableName) === null) {
            $this->db->createCommand()
                ->createTable($this->tableName, [
                    'id' => 'pk',
                    'created_at' => 'integer',
                    'updated_at' => 'integer',
                    'data' => 'binary',
                ])->execute();
            $this->db->getTableSchema($this->tableName, true);
        }
    }
9749
def createSQL(self, sql, args=()):
        
        before = time.time()
        self._execSQL(sql, args)
        after = time.time()
        if after - before > 2.0:
            log.msg('Extremely long CREATE: %s' % (after - before,))
            log.msg(sql)
249587
def makeSQL(action, table, cols="*", where=(), group="", order=(), limit=(), values=()):
    """"""
    cols  =    cols if isinstance(cols,  basestring) else ", ".join(cols)
    group =   group if isinstance(group, basestring) else ", ".join(group)
    order = [order] if isinstance(order, basestring) else order
    limit = [limit] if isinstance(limit, (basestring, int)) else limit
    sql = "SELECT %s FROM %s" % (cols, table) if "SELECT" == action else ""
    sql = "DELETE FROM %s"    % (table)       if "DELETE" == action else sql
    sql = "INSERT INTO %s"    % (table)       if "INSERT" == action else sql
    sql = "UPDATE %s"         % (table)       if "UPDATE" == action else sql
    args = {}
    if "INSERT" == action:
        args.update(values)
        cols, vals = (", ".join(x + k for k, v in values) for x in ("", ":"))
        sql += " (%s) VALUES (%s)" % (cols, vals)
    if "UPDATE" == action:
        sql += " SET "
        for i, (col, val) in enumerate(values):
            sql += (", " if i else "") + "%s = :%sU%s" % (col, col, i)
            args["%sU%s" % (col, i)] = val
    if where:
        sql += " WHERE "
        for i, (col, val) in enumerate(where):
            key = "%sW%s" % (re.sub("\\W", "_", col), i)
            dbval = val[1] if isinstance(val, (list, tuple)) else val
            args[key] = dbval
            op = "IS" if dbval == val else val[0]
            op = "=" if dbval is not None and "IS" == op else op
            sql += (" AND " if i else "") + "%s %s :%s" % (col, op, key)
    if group:
        sql += " GROUP BY " + group
    if order:
        sql += " ORDER BY "
        for i, col in enumerate(order):
            name = col[0] if isinstance(col, (list, tuple)) else col
            direction = "" if name == col else " " + col[1]
            sql += (", " if i else "") + name + direction
    if limit:
        sql += " LIMIT %s" % (", ".join(map(str, limit)))
    return sql, args