Files
3x-ui/internal/database/host_test.go
T
AmirRnz 42690e1b8c feat(hosts): bulk-add multiple hosts to multiple inbounds (#5677)
* feat(hosts): bulk-add multiple hosts to multiple inbounds

Allow users to select multiple inbound IDs and enter multiple host
addresses (with optional per-host port override) in a single form
submission.

- Add BulkAddHostReq entity and POST /panel/api/hosts/bulk/add endpoint
- Add AddHostsBulk service with GORM transaction safety
- Add parseHostAndPort helper (IPv4, bracketed/bracketless IPv6, port)
- Update HostFormModal to multi-select inbounds and tag-input hosts
- Wire bulkCreate mutation in HostsPage with existing-host suggestions
- Register endpoint in api-docs/endpoints.ts and regenerate OpenAPI/Zod

* feat(hosts): group override records by group_id and support group editing

* fix: import Popover in HostList

* fix: use messageApi in HostFormModal

* fix(hosts): resolve 4 bugs found in host-group code review

- fix(schema): allow empty hosts array in BulkAddHostSchema so users can
  save a host without an address (inherits inbound endpoint). The old
  .min(1) was never enforced at runtime since the schema is only used for
  type inference, but the type was incorrect.

- fix(service): validate new inbound IDs in UpdateHostGroup before deleting
  old rows, matching the same check already present in AddHostGroup. Prevents
  orphaned host rows when an invalid inbound ID is supplied on edit.

- fix(service): replace full-table scan in GetHostsByInbound with two
  targeted queries (DISTINCT group_id WHERE inbound_id=?, then
  WHERE group_id IN ?) to avoid loading every host in the DB.

- fix(mutations): remove unused createMut / create export from
  useHostMutations. The /hosts/add endpoint is identical to /hosts/bulk/add;
  only bulkCreate is used by the UI.

* fix(hosts): address code review feedback (optimize bulk inserts, add validation tests, and remove comments)

* fix(fmt): apply gofumpt formatting to model.go and db.go

The previous merge commit incorrectly applied gofmt (tab-aligned) to
these files. The repository's golangci config requires gofumpt+goimports
which produces space-aligned struct fields. This commit restores the
correct gofumpt formatting that matches upstream/main.

* chore(frontend): regenerate API schemas and update lockfile

* fix

* refactor(hosts): dedupe host-group service and tidy frontend

AddHostGroup and UpdateHostGroup shared an identical ~35-field
model.Host construction and hand-rolled transaction boilerplate
(tx.Begin plus a committed flag plus a deferred recover/rollback).
Extract buildHostRows, validateInboundsExist and formatHostAddr, and
run every mutation through db.Transaction. groupHosts collapses its
duplicated address/port formatting and create/append fork into one
path using slices.Contains. Behavior-preserving: host.go drops ~90
lines with the existing service/controller tests green.

Frontend: drop the Partial union and two as-casts in HostsPage.onSave
(the modal always passes a full BulkAddHostValues), and remove the
movable index map in HostList in favor of the table render index arg.

---------

Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-07-08 23:35:20 +02:00

84 lines
2.5 KiB
Go

package database
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func hostColumns() []string {
return []string{
"id", "group_id", "inbound_id", "sort_order", "remark", "server_description", "is_disabled", "is_hidden", "tags",
"address", "port",
"security", "sni", "host_header", "path", "alpn", "fingerprint",
"override_sni_from_address", "keep_sni_blank", "pinned_peer_cert_sha256",
"verify_peer_cert_by_name", "allow_insecure", "ech_config_list",
"mux_params", "sockopt_params", "final_mask", "vless_route",
"exclude_from_sub_types", "mihomo_ip_version", "mihomo_x25519", "shuffle_host", "node_guids",
"created_at", "updated_at",
}
}
func assertHostSchema(t *testing.T) {
t.Helper()
m := GetDB().Migrator()
if !m.HasTable("hosts") {
t.Fatalf("hosts table not created by initModels")
}
for _, col := range hostColumns() {
if !m.HasColumn(&model.Host{}, col) {
t.Fatalf("hosts table missing column %q", col)
}
}
}
// TestHostAutoMigrateCreatesColumns verifies the hosts table and every expected
// column exist after initModels (SQLite).
func TestHostAutoMigrateCreatesColumns(t *testing.T) {
if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
assertHostSchema(t)
}
// TestHostAutoMigrateCreatesColumns_Postgres is the dual-driver counterpart.
func TestHostAutoMigrateCreatesColumns_Postgres(t *testing.T) {
if strings.TrimSpace(os.Getenv("XUI_DB_DSN")) == "" || os.Getenv("XUI_DB_TYPE") != "postgres" {
t.Skip("set XUI_DB_TYPE=postgres and XUI_DB_DSN to run the postgres schema test")
}
if err := InitDB(""); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
assertHostSchema(t)
}
// TestPruneOrphanedHosts verifies a host whose inbound_id has no matching inbound
// is removed by the prune step.
func TestPruneOrphanedHosts(t *testing.T) {
if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
db := GetDB()
orphan := &model.Host{InboundId: 99999, Remark: "orphan"}
if err := db.Create(orphan).Error; err != nil {
t.Fatalf("create orphan host: %v", err)
}
if err := pruneOrphanedHosts(); err != nil {
t.Fatalf("pruneOrphanedHosts: %v", err)
}
var cnt int64
if err := db.Model(&model.Host{}).Where("id = ?", orphan.Id).Count(&cnt).Error; err != nil {
t.Fatalf("count: %v", err)
}
if cnt != 0 {
t.Fatalf("orphan host not pruned, count=%d", cnt)
}
}