Skip to content

Commit

Permalink
feat: 数据库管理基本完成
Browse files Browse the repository at this point in the history
  • Loading branch information
devhaozi committed Nov 25, 2024
1 parent 3fbaecb commit 9a2e68e
Show file tree
Hide file tree
Showing 15 changed files with 175 additions and 67 deletions.
2 changes: 1 addition & 1 deletion internal/apps/mysql/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ func (s *Service) SetRootPassword(w http.ResponseWriter, r *http.Request) {
return
}
} else {
if err = mysql.UserPassword("root", req.Password); err != nil {
if err = mysql.UserPassword("root", req.Password, "localhost"); err != nil {
service.Error(w, http.StatusInternalServerError, "%v", err)
return
}
Expand Down
19 changes: 14 additions & 5 deletions internal/biz/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ import (
"github.com/TheTNB/panel/internal/http/request"
)

type DatabaseStatus string
type DatabaseType string

const (
DatabaseTypeMysql DatabaseType = "mysql"
DatabaseTypePostgresql DatabaseType = "postgresql"
DatabaseTypeMongoDB DatabaseType = "mongodb"
DatabaseSQLite DatabaseType = "sqlite"
DatabaseTypeRedis DatabaseType = "redis"
)

type Database struct {
Name string `json:"name"`
Server string `json:"server"`
ServerID uint `json:"server_id"`
Encoding string `json:"encoding"`
Type DatabaseType `json:"type"`
Name string `json:"name"`
Server string `json:"server"`
ServerID uint `json:"server_id"`
Encoding string `json:"encoding"`
}

type DatabaseRepo interface {
Expand Down
10 changes: 0 additions & 10 deletions internal/biz/database_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,6 @@ import (
"github.com/TheTNB/panel/internal/http/request"
)

type DatabaseType string

const (
DatabaseTypeMysql DatabaseType = "mysql"
DatabaseTypePostgresql DatabaseType = "postgresql"
DatabaseTypeMongoDB DatabaseType = "mongodb"
DatabaseSQLite DatabaseType = "sqlite"
DatabaseTypeRedis DatabaseType = "redis"
)

type DatabaseServerStatus string

const (
Expand Down
2 changes: 2 additions & 0 deletions internal/biz/database_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ type DatabaseUser struct {
Remark string `gorm:"not null" json:"remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`

Server *DatabaseServer `gorm:"foreignKey:ServerID;references:ID" json:"server"`
}

func (r *DatabaseUser) BeforeSave(tx *gorm.DB) error {
Expand Down
26 changes: 18 additions & 8 deletions internal/data/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func (r databaseRepo) List(page, limit uint) ([]*biz.Database, int64, error) {
if databases, err := mysql.Databases(); err == nil {
for item := range slices.Values(databases) {
database = append(database, &biz.Database{
Type: biz.DatabaseTypeMysql,
Name: item.Name,
Server: server.Name,
ServerID: server.ID,
Expand All @@ -47,6 +48,7 @@ func (r databaseRepo) List(page, limit uint) ([]*biz.Database, int64, error) {
if databases, err := postgres.Databases(); err == nil {
for item := range slices.Values(databases) {
database = append(database, &biz.Database{
Type: biz.DatabaseTypePostgresql,
Name: item.Name,
Server: server.Name,
ServerID: server.ID,
Expand All @@ -73,28 +75,36 @@ func (r databaseRepo) Create(req *request.DatabaseCreate) error {
if err != nil {
return err
}
if err = mysql.UserCreate(req.Username, req.Password); err != nil {
return err
if req.CreateUser {
if err = mysql.UserCreate(req.Username, req.Password, req.Host); err != nil {
return err
}
}
if err = mysql.DatabaseCreate(req.Name); err != nil {
return err
}
if err = mysql.PrivilegesGrant(req.Username, req.Name); err != nil {
return err
if req.Username != "" {
if err = mysql.PrivilegesGrant(req.Username, req.Name, req.Host); err != nil {
return err
}
}
case biz.DatabaseTypePostgresql:
postgres, err := db.NewPostgres(server.Username, server.Password, server.Host, server.Port)
if err != nil {
return err
}
if err = postgres.UserCreate(req.Username, req.Password); err != nil {
return err
if req.CreateUser {
if err = postgres.UserCreate(req.Username, req.Password); err != nil {
return err
}
}
if err = postgres.DatabaseCreate(req.Name); err != nil {
return err
}
if err = postgres.PrivilegesGrant(req.Username, req.Name); err != nil {
return err
if req.Username != "" {
if err = postgres.PrivilegesGrant(req.Username, req.Name); err != nil {
return err
}
}
}

Expand Down
13 changes: 7 additions & 6 deletions internal/data/database_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (r databaseUserRepo) Count() (int64, error) {
func (r databaseUserRepo) List(page, limit uint) ([]*biz.DatabaseUser, int64, error) {
var user []*biz.DatabaseUser
var total int64
err := app.Orm.Model(&biz.DatabaseUser{}).Order("id desc").Count(&total).Offset(int((page - 1) * limit)).Limit(int(limit)).Find(&user).Error
err := app.Orm.Model(&biz.DatabaseUser{}).Preload("Server").Order("id desc").Count(&total).Offset(int((page - 1) * limit)).Limit(int(limit)).Find(&user).Error

for u := range slices.Values(user) {
r.fillUser(u)
Expand All @@ -41,7 +41,7 @@ func (r databaseUserRepo) List(page, limit uint) ([]*biz.DatabaseUser, int64, er

func (r databaseUserRepo) Get(id uint) (*biz.DatabaseUser, error) {
user := new(biz.DatabaseUser)
if err := app.Orm.Where("id = ?", id).First(user).Error; err != nil {
if err := app.Orm.Preload("Server").Where("id = ?", id).First(user).Error; err != nil {
return nil, err
}

Expand All @@ -62,11 +62,11 @@ func (r databaseUserRepo) Create(req *request.DatabaseUserCreate) error {
if err != nil {
return err
}
if err = mysql.UserCreate(req.Username, req.Password); err != nil {
if err = mysql.UserCreate(req.Username, req.Password, req.Host); err != nil {
return err
}
for name := range slices.Values(req.Privileges) {
if err = mysql.PrivilegesGrant(req.Username, name); err != nil {
if err = mysql.PrivilegesGrant(req.Username, name, req.Host); err != nil {
return err
}
}
Expand All @@ -89,6 +89,7 @@ func (r databaseUserRepo) Create(req *request.DatabaseUserCreate) error {
ServerID: req.ServerID,
Username: req.Username,
Password: req.Password,
Host: req.Host,
Remark: req.Remark,
}

Expand All @@ -113,12 +114,12 @@ func (r databaseUserRepo) Update(req *request.DatabaseUserUpdate) error {
return err
}
if req.Password != "" {
if err = mysql.UserPassword(user.Username, req.Password); err != nil {
if err = mysql.UserPassword(user.Username, req.Password, user.Host); err != nil {
return err
}
}
for name := range slices.Values(req.Privileges) {
if err = mysql.PrivilegesGrant(user.Username, name); err != nil {
if err = mysql.PrivilegesGrant(user.Username, name, user.Host); err != nil {
return err
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/data/website.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,13 +308,13 @@ func (r *websiteRepo) Create(req *request.WebsiteCreate) (*biz.Website, error) {
if err != nil {
return nil, err
}
if err = mysql.UserCreate(req.DBUser, req.DBPassword); err != nil {
if err = mysql.UserCreate(req.DBUser, req.DBPassword, "localhost"); err != nil {
return nil, err
}
if err = mysql.DatabaseCreate(req.DBName); err != nil {
return nil, err
}
if err = mysql.PrivilegesGrant(req.DBUser, req.DBName); err != nil {
if err = mysql.PrivilegesGrant(req.DBUser, req.DBName, "localhost"); err != nil {
return nil, err
}
}
Expand Down
5 changes: 3 additions & 2 deletions internal/http/request/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ type DatabaseCreate struct {
ServerID uint `form:"server_id" json:"server_id" validate:"required,exists=database_servers id"`
Name string `form:"name" json:"name" validate:"required"`
CreateUser bool `form:"create_user" json:"create_user"`
Username string `form:"username" json:"username"`
Password string `form:"password" json:"password"`
Username string `form:"username" json:"username" validate:"required_if=CreateUser true"`
Password string `form:"password" json:"password" validate:"required_if=CreateUser true"`
Host string `form:"host" json:"host"`
Remark string `form:"remark" json:"remark"`
}

Expand Down
5 changes: 3 additions & 2 deletions internal/http/request/database_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package request

type DatabaseUserCreate struct {
ServerID uint `form:"server_id" json:"server_id" validate:"required,exists=database_servers id"`
Username string `form:"username" json:"username"`
Password string `form:"password" json:"password"`
Username string `form:"username" json:"username" validate:"required"`
Password string `form:"password" json:"password" validate:"required"`
Host string `form:"host" json:"host"`
Privileges []string `form:"privileges" json:"privileges"`
Remark string `form:"remark" json:"remark"`
}
Expand Down
16 changes: 8 additions & 8 deletions pkg/db/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ func (m *MySQL) DatabaseSize(name string) (int64, error) {
return size, err
}

func (m *MySQL) UserCreate(user, password string) error {
_, err := m.Exec(fmt.Sprintf("CREATE USER IF NOT EXISTS '%s'@'localhost' IDENTIFIED BY '%s'", user, password))
func (m *MySQL) UserCreate(user, password, host string) error {
_, err := m.Exec(fmt.Sprintf("CREATE USER IF NOT EXISTS '%s'@'%s' IDENTIFIED BY '%s'", user, host, password))
m.flushPrivileges()
return err
}
Expand All @@ -110,14 +110,14 @@ func (m *MySQL) UserDrop(user string) error {
return err
}

func (m *MySQL) UserPassword(user, password string) error {
_, err := m.Exec(fmt.Sprintf("ALTER USER '%s'@'localhost' IDENTIFIED BY '%s'", user, password))
func (m *MySQL) UserPassword(user, password, host string) error {
_, err := m.Exec(fmt.Sprintf("ALTER USER '%s'@'%s' IDENTIFIED BY '%s'", user, host, password))
m.flushPrivileges()
return err
}

func (m *MySQL) PrivilegesGrant(user, database string) error {
_, err := m.Exec(fmt.Sprintf("GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost'", database, user))
func (m *MySQL) PrivilegesGrant(user, database, host string) error {
_, err := m.Exec(fmt.Sprintf("GRANT ALL PRIVILEGES ON %s.* TO '%s'@'%s'", database, user, host))
m.flushPrivileges()
return err
}
Expand Down Expand Up @@ -164,8 +164,8 @@ func (m *MySQL) UserPrivileges(user, host string) (map[string][]string, error) {
return privileges, nil
}

func (m *MySQL) PrivilegesRevoke(user, database string) error {
_, err := m.Exec(fmt.Sprintf("REVOKE ALL PRIVILEGES ON %s.* FROM '%s'@'localhost'", database, user))
func (m *MySQL) PrivilegesRevoke(user, database, host string) error {
_, err := m.Exec(fmt.Sprintf("REVOKE ALL PRIVILEGES ON %s.* FROM '%s'@'%s'", database, user, host))
m.flushPrivileges()
return err
}
Expand Down
50 changes: 44 additions & 6 deletions web/src/views/database/CreateDatabaseModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import { NButton, NInput } from 'naive-ui'
const show = defineModel<boolean>('show', { type: Boolean, required: true })
const createModel = ref({
database: '',
server_id: null,
name: '',
create_user: false,
username: '',
password: '',
host: 'localhost'
})
const servers = ref<{ label: string; value: string }[]>([])
const hostType = [
{ label: '本地(localhost)', value: 'localhost' },
{ label: '所有(%)', value: '%' },
Expand All @@ -23,6 +27,17 @@ const handleCreate = () => {
window.$bus.emit('database:refresh')
})
}
onMounted(() => {
database.serverList(1, 10000).then((data: any) => {
for (const server of data.items) {
servers.value.push({
label: server.name,
value: server.id
})
}
})
})
</script>

<template>
Expand All @@ -37,39 +52,62 @@ const handleCreate = () => {
@close="show = false"
>
<n-form :model="createModel">
<n-form-item path="server_id" label="服务器">
<n-select
v-model:value="createModel.server_id"
@keydown.enter.prevent
placeholder="选择服务器"
:options="servers"
/>
</n-form-item>
<n-form-item path="database" label="数据库名">
<n-input
v-model:value="createModel.database"
v-model:value="createModel.name"
type="text"
@keydown.enter.prevent
placeholder="输入数据库名称"
/>
</n-form-item>
<n-form-item path="username" label="用户名">
<n-form-item path="create_user" label="创建用户">
<n-switch v-model:value="createModel.create_user" />
</n-form-item>
<n-form-item v-if="!createModel.create_user" path="username" label="授权用户">
<n-input
v-model:value="createModel.username"
type="text"
@keydown.enter.prevent
placeholder="输入授权用户名"
/>
</n-form-item>
<n-form-item v-if="createModel.create_user" path="username" label="用户名">
<n-input
v-model:value="createModel.username"
type="text"
@keydown.enter.prevent
placeholder="输入用户名"
/>
</n-form-item>
<n-form-item path="password" label="密码">
<n-form-item v-if="createModel.create_user" path="password" label="密码">
<n-input
v-model:value="createModel.password"
type="password"
@keydown.enter.prevent
placeholder="输入密码"
/>
</n-form-item>
<n-form-item path="host-select" label="主机">
<n-form-item v-if="createModel.create_user" path="host-select" label="主机">
<n-select
v-model:value="createModel.host"
@keydown.enter.prevent
placeholder="选择主机"
:options="hostType"
/>
</n-form-item>
<n-form-item v-if="createModel.host === ''" path="host" label="指定主机">
<n-form-item
v-if="createModel.create_user && createModel.host === ''"
path="host"
label="指定主机"
>
<n-input
v-model:value="createModel.host"
type="text"
Expand Down
Loading

0 comments on commit 9a2e68e

Please sign in to comment.