Returns the SQL command for creating a table for this model.
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)
693142
def _create_table(self, table_name):
        ''' 
        '''
        if self.fieldnames:
            sql_fields = []
            for field in self._fields:
                if field != '_id':
                    if 'dblite' in self._fields[field]:
                        sql_fields.append(' '.join([field, self._fields[field]['dblite']]))
                    else:
                        sql_fields.append(field)
            sql_fields = ','.join(sql_fields)
            SQL = 'CREATE TABLE IF NOT EXISTS %s (%s);' % (table_name, sql_fields)
            try:
                self._cursor.execute(SQL)
            except sqlite3.OperationalError, err:
                raise RuntimeError('Create table error, %s, SQL: %s' % (err, SQL))
780085
def get_sql(self):
        
        alias = self.get_alias()
        if alias:
            return '{0} AS {1}'.format(self.get_from_name(), alias)

        return self.get_identifier()
1094152
def create_tables(self):
        
        cdir = os.path.dirname( os.path.realpath(__file__) )
        
        # table schemas -------------------------------------
        schema = os.path.join(cdir,"data","partsmaster.sql")
        if self.debug:
            print(self.hdr,"parts master schema is ",schema)
        
        self.populate(schema)
        
        schema = os.path.join(cdir,"data","approvedmfg.sql")
        if self.debug:
            print(self.hdr,"approved mfg list schema is ",schema)
        
        self.populate(schema)
        
        schema = os.path.join(cdir,"data","attachment.sql")
        if self.debug:
            print(self.hdr,"attachment schema is ",schema)
        
        self.populate(schema)

        schema = os.path.join(cdir,"data","bom.sql")
        if self.debug:
            print(self.hdr,"bill of materials schema is ",schema)
        
        self.populate(schema)
        
        return
1223711
def create_model_table(self, model):
        
        try:
            return db_model_factory(self.Base, model, self.models)
        except Exception as exc:
            raise ModelError(
                model.name,
                message="failed to create in-memory table.",
                orig_exc=exc,
                context=self.error_context
            )
252981
public function createCommand($sql = null, $params = [])
    {
        /** @var Command $command */
        $command = new $this->commandClass([
            'db' => $this,
            'sql' => $sql,
        ]);

        return $command->bindValues($params);
    }
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()
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);
    }
438879
function createTableColumn (model, name, spec) {
    // require spec to be object
    assert.ok(typeof spec === 'object', `${name} spec must be object`)
    // require valid type
    assert.ok(columnTypes[spec.type], `invalid type ${spec.type} for ${name}`)
    // build sql string
    var columnType = spec.type === 'id'
        ? (model.binaryIds ? 'BINARY(16)' : 'CHAR(32)')
        : columnTypes[spec.type]
    var sql = `${quoteName(name)} ${columnType}`
    // add unsigned flag if set
    if (spec.unsigned && (spec.type === 'int' || spec.type === 'smallint')) {
        sql += ' UNSIGNED'
    }
    // add not null if null specifically set to false
    if (spec.null === false) {
        sql += ' NOT NULL'
    }
    // add auto increment
    if (spec.auto) {
        sql += ' AUTO_INCREMENT PRIMARY KEY'
    }
    // add default value if set
    if (spec.default !== undefined) {
        // use 0/1 for boolean
        if (spec.type === 'boolean') {
            sql += ` DEFAULT ${spec.default ? 1 : 0}`
        }
        // otherwise use quoteNamed value
        else {
            sql += ` DEFAULT '${spec.default}'`
        }
    }
    // return sql string
    return sql
}
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")
1119233
def as_sql(self):
        

        labels, data = self._get_table()
        table = SqlTable(labels, data, "{:.3f}", "\n")
        return str(table)
1163533
public function createSQL()
	{
		try {

			$lines = array();

			$indices = array();

			$columns = $this->columns;

			$template = "CREATE TABLE %s (\n%s,\n%s\n) ENGINE=%s DEFAULT CHARSET=%s;";

			foreach ($this->columns as $column_name => $column)
			{

				//$column_name = $column["name"];//set the column name

				$data_type = $column["type"];//set the column data type

				$length = $column["length"];//set the lenght of the data type

				if ($column["primary"])	$indices[] = "PRIMARY KEY ({$column_name})"; //add primary key field

				if ($column["index"]) $indices[] = "KEY {$column_name} ({$column_name})"; //add index field

				switch ($data_type)
				{
					case "autonumber":

						$lines[] = "{$column_name} INT(11) NOT NULL AUTO_INCREMENT";

						break;

					case "text":

						if ($length !== null && $length <= 255)	$lines[] = "{$column_name} VARCHAR({$length}) DEFAULT NULL";

						else $lines[] = "{$column_name} text";

						break;

					case "integer":

						$lines[] = "{$column_name} INT(11) DEFAULT NULL";

						break;

					case "decimal":

						$lines[] = "{$column_name} FLOAT DEFAULT NULL";

						break;

					case "boolean":

						$lines[] = "{$column_name} TINYINT(4) DEFAULT NULL";

						break;

					case "datetime":

						$lines[] = "{$column_name} DATETIME DEFAULT NULL";

						break;

				}

			}

			$this->query_string = sprintf($template, $this->table, join(",\n", $lines), join(",\n", $indices), 'InnoDB', 'utf8');//$this->connection->character_set_name()
			
			return $this;

		} catch (MySQLException $e) {

			$e->errorShow();

		}
		
	}
333432
def get_create_foreign_key_sql(self, foreign_key, table):
        
        if isinstance(table, Table):
            table = table.get_quoted_name(self)

        query = "ALTER TABLE %s ADD %s" % (
            table,
            self.get_foreign_key_declaration_sql(foreign_key),
        )

        return query
451939
def build_from_table(self):
        
        table_parts = []

        # get the table sql for each table
        for table in self.tables:
            sql = table.get_sql()
            if len(sql):
                table_parts.append(sql)

        # combine all table sql separated by a comma
        sql = 'FROM {0} '.format(', '.join(table_parts))

        return sql
692795
def _generateDDL(self):
        """"""
        sql = []
        # Next convert each set of columns into a table structure
        for dataset_name in sorted(self.datasets.keys()):

            # SQL to drop the table if it already exists
            sql.append('''drop table if exists %s;''' % dataset_name)

            # Generate the SQL for the cols
            cols = self.datasets[dataset_name]
            col_defs = []
            for col in cols:
                sql_datatype = self.getSQLDataType(col["vartype"])
                col_defs.append("%s %s" % (col["varname"], sql_datatype,))

            stmt = 'CREATE TABLE %s (%s)' % (dataset_name, ','.join(col_defs))
            sql.append(stmt)

        return sql
826131
def sql(self):
        
        clone = self.query.clone()
        sql, params = clone.get_compiler(using=self.db).as_sql()
        return sql % params
753390
def get_select_sql(self):
        
        if self.table:
            return '{0}.{1}'.format(self.table.get_identifier(), self.name)
        return '{0}'.format(self.name)