table = "{$wpdb->prefix}$_table"; $this->charset_collate = $wpdb->get_charset_collate(); } public function create() { $sql = "CREATE TABLE {$this->table} ("; $this->sql_fields[] = $sql; return $this; } private function _field($name, $type, $length, $unsigned = false, $is_nullable = false) { $sql = $name . ' ' . strtoupper($type) . '(' . $length . ') '; $sql .= ($unsigned ? 'UNSIGNED ' : ''); $sql .= ($is_nullable ? 'NULL' : 'NOT NULL'); return $sql; } public function string($name, $length = 50, $is_nullable = false) { $sql = $this->_field($name, "VARCHAR", $length, false, $is_nullable); $this->sql_fields[] = $sql; return $this; } public function primary_key($name) { $sql = "PRIMARY KEY($name)"; $this->sql_fields[] = $sql; return $this; } public function foreign_key($name, $reference, $delete) { global $wpdb; $sql = "FOREIGN KEY($name) REFERENCES {$wpdb->prefix}$reference ON DELETE "; switch ($delete) { case self::DELETE_CASCADE: $sql .= "CASCADE"; break; } $this->sql_fields[] = $sql; return $this; } public function run() { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta($this->build_query()); } public function build_query() { $sql = array_shift($this->sql_fields); $sql .= implode(',', $this->sql_fields); $sql .= ')'; if ($this->charset_collate) { $sql .= ' ' . $this->charset_collate . ';'; } return $sql; } public function bigint($name, $length = 20, $unsigned = false, $is_nullable = false, $auto_increment = false) { $sql = $this->_field($name, 'BIGINT', $length, $unsigned, $is_nullable); $sql .= ($auto_increment ? ' AUTO_INCREMENT' : ''); $this->sql_fields[] = $sql; return $this; } public function boolean($name) { $sql = $this->_field($name, 'TINYINT', 1, true, true); $this->sql_fields[] = $sql; return $this; } public function timestamp($name, $is_nullable = false) { $sql = $name . ' ' . 'TIMESTAMP '; $sql .= ($is_nullable ? 'NULL' : 'NOT NULL'); $this->sql_fields[] = $sql; return $this; } }