roundtrip_test.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  1. package migrate
  2. import (
  3. "TsDB2/DB/core"
  4. "TsDB2/DB/core/page"
  5. "TsDB2/DB/core/types"
  6. "TsDB2/DB/core/util"
  7. "bytes"
  8. "database/sql"
  9. "errors"
  10. "fmt"
  11. "math"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "testing"
  16. "unicode/utf8"
  17. _ "modernc.org/sqlite"
  18. )
  19. // quiet 一份不往日志里写东西的选项, 免得测试输出被进度刷屏。
  20. func quiet() *Options {
  21. o := DefaultOptions()
  22. o.Log = func(string, ...any) {}
  23. return o
  24. }
  25. // ============================ 样本库 ============================
  26. type sampleRow struct {
  27. pk uint64
  28. vals map[string]any
  29. }
  30. // buildVRTXUsers 用 core 原生接口建一张覆盖各宽度档位的表:
  31. // 8/1/2/4/32 字节 + 浮点 + 变长, 外加一个 B+ 树索引与一个 Hash 索引。
  32. func buildVRTXUsers(t *testing.T, path string) {
  33. t.Helper()
  34. db, err := core.Open(path)
  35. if err != nil {
  36. t.Fatalf("建样本 VRTX 库: %v", err)
  37. }
  38. defer db.Close()
  39. fields := []types.FieldInfo{
  40. {FieldType: types.FieldType_Uint64, FieldName: []byte("_id")},
  41. {FieldType: types.FieldType_String, FieldName: []byte("Name")},
  42. {FieldType: types.FieldType_Uint16, FieldName: []byte("Age")},
  43. {FieldType: types.FieldType_Float64, FieldName: []byte("Score")},
  44. {FieldType: types.FieldType_Dynamicbyte, FieldName: []byte("Blob")},
  45. {FieldType: types.FieldType_Uint8, FieldName: []byte("Flag")},
  46. {FieldType: types.FieldType_Uint32, FieldName: []byte("Count")},
  47. {FieldType: types.FieldType_Uint64, FieldName: []byte("Big")},
  48. }
  49. tbl, err := db.CreateTable("Users", fields)
  50. if err != nil {
  51. t.Fatalf("建表: %v", err)
  52. }
  53. for _, spec := range []struct {
  54. name string
  55. typ page.IndexType
  56. col byte
  57. }{
  58. {"pk_Users", page.IndexTypePrimary, 0},
  59. {"idx_Users_Name", page.IndexTypeHash, 1},
  60. {"idx_Users_Age", page.IndexTypeBTree, 2},
  61. } {
  62. if _, err := tbl.CreateIndex(spec.name, spec.typ, []byte{spec.col}); err != nil {
  63. t.Fatalf("建索引 %s: %v", spec.name, err)
  64. }
  65. }
  66. big := bytes.Repeat([]byte{0xAB}, 300)
  67. rows := []sampleRow{
  68. {1, map[string]any{
  69. "_id": uint64(1), "Name": []byte("Alice"), "Age": int16(30), "Score": 1.5,
  70. "Blob": []byte("hello"), "Flag": uint8(7), "Count": int32(100), "Big": uint64(42),
  71. }},
  72. {2, map[string]any{
  73. // uint64 的负位模式与 255 的有符号/无符号边界
  74. "_id": uint64(2), "Name": []byte("Bob"), "Age": int16(-5), "Score": -2.25,
  75. "Blob": []byte{0, 1, 2, 255}, "Flag": uint8(255), "Count": int32(-1),
  76. "Big": uint64(1) << 63,
  77. }},
  78. {3, map[string]any{
  79. // 空字符串 / 空变长列 / 零值
  80. "_id": uint64(3), "Name": []byte(""), "Age": int16(32767), "Score": float64(0),
  81. "Blob": []byte{}, "Flag": uint8(0), "Count": int32(math.MaxInt32), "Big": uint64(0),
  82. }},
  83. {4, map[string]any{
  84. // 定长串打满 + 多字节 UTF-8 + 变长二进制 + uint64 全 1
  85. "_id": uint64(4), "Name": []byte(strings.Repeat("x", 32)), "Age": int16(-32768),
  86. "Score": 1e-9, "Blob": big, "Flag": uint8(1), "Count": int32(math.MinInt32),
  87. "Big": uint64(math.MaxUint64),
  88. }},
  89. {5, map[string]any{
  90. "_id": uint64(5), "Name": []byte("王小明"), "Age": int16(1),
  91. "Score": 3.141592653589793, "Blob": []byte("中文内容"), "Flag": uint8(128),
  92. "Count": int32(0), "Big": uint64(7),
  93. }},
  94. }
  95. writeVRTXRows(t, tbl, fields, rows)
  96. }
  97. // buildVRTXMetrics 建一张时序表: 行存储索引是 Time 类型, 键是 _ts。
  98. func buildVRTXMetrics(t *testing.T, path string) {
  99. t.Helper()
  100. db, err := core.Open(path)
  101. if err != nil {
  102. t.Fatalf("建时序样本库: %v", err)
  103. }
  104. defer db.Close()
  105. fields := []types.FieldInfo{
  106. {FieldType: types.FieldType_Uint64, FieldName: []byte("_ts")},
  107. {FieldType: types.FieldType_Float64, FieldName: []byte("Value")},
  108. {FieldType: types.FieldType_String, FieldName: []byte("Device")},
  109. }
  110. tbl, err := db.CreateTable("Metrics", fields)
  111. if err != nil {
  112. t.Fatalf("建表: %v", err)
  113. }
  114. if _, err := tbl.CreateIndex("pk_Metrics", page.IndexTypeTime, []byte{0}); err != nil {
  115. t.Fatalf("建时序索引: %v", err)
  116. }
  117. // 时间必须递增: 时序索引按时间段分段, 乱序插入会被拒。
  118. writeVRTXRows(t, tbl, fields, []sampleRow{
  119. {1, map[string]any{"_ts": uint64(1000), "Value": 1.5, "Device": []byte("s1")}},
  120. {2, map[string]any{"_ts": uint64(2000), "Value": 2.5, "Device": []byte("s2")}},
  121. {3, map[string]any{"_ts": uint64(3000), "Value": 3.5, "Device": []byte("s1")}},
  122. })
  123. }
  124. func writeVRTXRows(t *testing.T, tbl *core.Table, fields []types.FieldInfo, rows []sampleRow) {
  125. t.Helper()
  126. for _, r := range rows {
  127. vals := make([]types.FieldValue, len(fields))
  128. for i, f := range fields {
  129. vals[i] = types.FieldValue{FieldName: f.FieldName, Value: r.vals[util.BytesToString(f.FieldName)]}
  130. }
  131. if _, err := tbl.InsertRowWithID(r.pk, vals); err != nil {
  132. t.Fatalf("插入 pk=%d: %v", r.pk, err)
  133. }
  134. }
  135. }
  136. // ============================ 读回真实文件 ============================
  137. // vrtxSnapshot 直接把 VRTX 文件读成 (列结构, 索引, 数据) 三份快照 —— 不走 migrate
  138. // 自己的读端, 免得"读写两端用同一段代码"把不对称的错悄悄抹平。
  139. type vrtxSnapshot struct {
  140. columns []string // "Name:32 字节"
  141. indexes map[string]string
  142. rows map[uint64]map[string]any
  143. }
  144. func snapshotVRTX(t *testing.T, path, table string) vrtxSnapshot {
  145. t.Helper()
  146. db, err := core.Open(path)
  147. if err != nil {
  148. t.Fatalf("打开 %s: %v", path, err)
  149. }
  150. defer db.Close()
  151. tbl, ok := db.FindTable(table)
  152. if !ok {
  153. t.Fatalf("%s 里没有表 %s", path, table)
  154. }
  155. snap := vrtxSnapshot{indexes: map[string]string{}, rows: map[uint64]map[string]any{}}
  156. fields := tbl.GetFields()
  157. for _, f := range fields {
  158. if util.IsHighBitSet(byte(f.FieldType)) {
  159. continue
  160. }
  161. // NULL / 唯一声明也进快照: 它们和类型一样是结构的一部分, 往返丢了就是
  162. // 静默改结构 (列从"可空"变"非空"、约束从"唯一"变"普通")。
  163. snap.columns = append(snap.columns, fmt.Sprintf("%s:%s%s",
  164. util.BytesToString(f.FieldName), TypeName(f.FieldType), flagMarks(f.Flag)))
  165. }
  166. for _, m := range tbl.IndexMeta().GetIndexes() {
  167. var cols []string
  168. for _, fid := range m.Fields() {
  169. cols = append(cols, util.BytesToString(fields[fid].FieldName))
  170. }
  171. mark := ""
  172. if m.Unique() {
  173. mark = " unique"
  174. }
  175. snap.indexes[m.Name()] = fmt.Sprintf("%s(%s)%s",
  176. IndexTypeName(m.IndexType), strings.Join(cols, ","), mark)
  177. }
  178. if err := tbl.Query().ScanWithPKID(func(pkID uint64, vals []types.FieldValue) bool {
  179. m := make(map[string]any, len(vals))
  180. for _, fv := range vals {
  181. m[util.BytesToString(fv.FieldName)] = fv.Value
  182. }
  183. snap.rows[pkID] = m
  184. return true
  185. }); err != nil {
  186. t.Fatalf("扫描 %s.%s: %v", path, table, err)
  187. }
  188. return snap
  189. }
  190. func norm(v any) string {
  191. if b, ok := v.([]byte); ok {
  192. return fmt.Sprintf("bytes:%x", b)
  193. }
  194. if f, ok := v.(float64); ok {
  195. return "f64:" + strconv.FormatFloat(f, 'x', -1, 64)
  196. }
  197. return fmt.Sprintf("%T:%v", v, v)
  198. }
  199. // ============================ 用例 ============================
  200. // TestVRTXSQLiteRoundTrip VRTX → SQLite → VRTX: 结构、索引类型、主键与每一行的
  201. // 每个字段都必须原样回来。
  202. func TestVRTXSQLiteRoundTrip(t *testing.T) {
  203. dir := t.TempDir()
  204. srcPath := filepath.Join(dir, "src.db")
  205. midPath := filepath.Join(dir, "mid.sqlite")
  206. backPath := filepath.Join(dir, "back.db")
  207. buildVRTXUsers(t, srcPath)
  208. // 先取一份源快照, 后面拿它对照
  209. want := snapshotVRTX(t, srcPath, "Users")
  210. // VRTX → SQLite
  211. v1, err := OpenVRTX(srcPath, quiet())
  212. if err != nil {
  213. t.Fatal(err)
  214. }
  215. s1, err := OpenSQLite(midPath, quiet())
  216. if err != nil {
  217. t.Fatal(err)
  218. }
  219. rep, err := Run(v1, s1, quiet())
  220. if err != nil {
  221. t.Fatalf("VRTX→SQLite: %v", err)
  222. }
  223. if rep.Rows != 5 {
  224. t.Fatalf("VRTX→SQLite 应迁 5 行, 实际 %d", rep.Rows)
  225. }
  226. _ = v1.Close()
  227. _ = s1.Close()
  228. // SQLite → VRTX
  229. s2, err := OpenSQLite(midPath, quiet())
  230. if err != nil {
  231. t.Fatal(err)
  232. }
  233. v2, err := OpenVRTX(backPath, quiet())
  234. if err != nil {
  235. t.Fatal(err)
  236. }
  237. if _, err := Run(s2, v2, quiet()); err != nil {
  238. t.Fatalf("SQLite→VRTX: %v", err)
  239. }
  240. _ = s2.Close()
  241. _ = v2.Close()
  242. got := snapshotVRTX(t, backPath, "Users")
  243. if strings.Join(got.columns, "|") != strings.Join(want.columns, "|") {
  244. t.Errorf("列结构不一致\n 源: %v\n 回: %v", want.columns, got.columns)
  245. }
  246. for name, def := range want.indexes {
  247. if got.indexes[name] != def {
  248. t.Errorf("索引 %s 不一致: 源 %q, 回 %q", name, def, got.indexes[name])
  249. }
  250. }
  251. if len(got.indexes) != len(want.indexes) {
  252. t.Errorf("索引数量不一致: 源 %v, 回 %v", want.indexes, got.indexes)
  253. }
  254. if len(got.rows) != len(want.rows) {
  255. t.Fatalf("行数不一致: 源 %d, 回 %d", len(want.rows), len(got.rows))
  256. }
  257. for pk, wantRow := range want.rows {
  258. gotRow, ok := got.rows[pk]
  259. if !ok {
  260. t.Errorf("pk=%d 的行丢了", pk)
  261. continue
  262. }
  263. for col, wantVal := range wantRow {
  264. if norm(gotRow[col]) != norm(wantVal) {
  265. t.Errorf("pk=%d 列 %s 不一致: 源 %s, 回 %s",
  266. pk, col, norm(wantVal), norm(gotRow[col]))
  267. }
  268. }
  269. }
  270. }
  271. // TestVRTXTimeSeriesRoundTrip 时序表: 行存储索引是 Time 类型, 键是 _ts 而不是行号。
  272. // 这种表的行号由索引内部维护 (且首个分段的 pkID 并不可靠), 所以往返时按 _ts 对照;
  273. // 要求是 Time 索引仍建在 _ts 上, 且每个时间点的数据一字不差。
  274. func TestVRTXTimeSeriesRoundTrip(t *testing.T) {
  275. dir := t.TempDir()
  276. srcPath := filepath.Join(dir, "src.db")
  277. midPath := filepath.Join(dir, "mid.sqlite")
  278. backPath := filepath.Join(dir, "back.db")
  279. buildVRTXMetrics(t, srcPath)
  280. want := snapshotVRTX(t, srcPath, "Metrics")
  281. v1, err := OpenVRTX(srcPath, quiet())
  282. if err != nil {
  283. t.Fatal(err)
  284. }
  285. s1, err := OpenSQLite(midPath, quiet())
  286. if err != nil {
  287. t.Fatal(err)
  288. }
  289. if _, err := Run(v1, s1, quiet()); err != nil {
  290. t.Fatalf("VRTX→SQLite: %v", err)
  291. }
  292. _ = v1.Close()
  293. _ = s1.Close()
  294. // 中间库不该冒出 _id 之类的替代主键: 时序表在 SQL 侧本来就没有整数主键
  295. mid, err := OpenSQLite(midPath, quiet())
  296. if err != nil {
  297. t.Fatal(err)
  298. }
  299. midSchema, err := mid.Schema("Metrics")
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. if midSchema.PKColumn != "" {
  304. t.Errorf("时序表导出到 SQL 后不该有主键列, 实际 %q", midSchema.PKColumn)
  305. }
  306. _ = mid.Close()
  307. s2, err := OpenSQLite(midPath, quiet())
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. v2, err := OpenVRTX(backPath, quiet())
  312. if err != nil {
  313. t.Fatal(err)
  314. }
  315. if _, err := Run(s2, v2, quiet()); err != nil {
  316. t.Fatalf("SQLite→VRTX: %v", err)
  317. }
  318. _ = s2.Close()
  319. _ = v2.Close()
  320. got := snapshotVRTX(t, backPath, "Metrics")
  321. if got.indexes["pk_Metrics"] != "time(_ts)" {
  322. t.Errorf("时序索引没回来: %v", got.indexes)
  323. }
  324. if len(got.rows) != len(want.rows) {
  325. t.Fatalf("行数不一致: 源 %d, 回 %d", len(want.rows), len(got.rows))
  326. }
  327. // 行号不可比, 按 _ts 配对
  328. byTS := func(rows map[uint64]map[string]any) map[string]map[string]any {
  329. out := make(map[string]map[string]any, len(rows))
  330. for _, r := range rows {
  331. out[norm(r["_ts"])] = r
  332. }
  333. return out
  334. }
  335. wantTS, gotTS := byTS(want.rows), byTS(got.rows)
  336. for ts, wantRow := range wantTS {
  337. gotRow, ok := gotTS[ts]
  338. if !ok {
  339. t.Errorf("_ts=%s 的点丢了", ts)
  340. continue
  341. }
  342. for _, col := range []string{"_ts", "Value", "Device"} {
  343. if norm(gotRow[col]) != norm(wantRow[col]) {
  344. t.Errorf("_ts=%s 列 %s 不一致: 源 %s, 回 %s",
  345. ts, col, norm(wantRow[col]), norm(gotRow[col]))
  346. }
  347. }
  348. }
  349. }
  350. // TestSQLiteOriginToVRTX SQLite 里手工建的表 (无 __vrtx_meta) → VRTX → SQLite:
  351. // 类型按 SQL 声明就近取档, 主键与二级索引都要保住。
  352. func TestSQLiteOriginToVRTX(t *testing.T) {
  353. dir := t.TempDir()
  354. srcPath := filepath.Join(dir, "src.sqlite")
  355. vrtxPath := filepath.Join(dir, "mid.db")
  356. backPath := filepath.Join(dir, "back.sqlite")
  357. createSQLiteSource(t, srcPath)
  358. want := readSQLiteRows(t, srcPath)
  359. s1, err := OpenSQLite(srcPath, quiet())
  360. if err != nil {
  361. t.Fatal(err)
  362. }
  363. v1, err := OpenVRTX(vrtxPath, quiet())
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. if _, err := Run(s1, v1, quiet()); err != nil {
  368. t.Fatalf("SQLite→VRTX: %v", err)
  369. }
  370. _ = s1.Close()
  371. _ = v1.Close()
  372. // VRTX 侧应该拿到 8 字节主键 + 两个索引 (primary + btree)
  373. vSnap := snapshotVRTX(t, vrtxPath, "Items")
  374. if vSnap.indexes["pk_Items"] != "primary(id)" {
  375. t.Errorf("VRTX 主键索引不对: %v", vSnap.indexes)
  376. }
  377. if vSnap.indexes["idx_Items_name"] != "btree(name)" {
  378. t.Errorf("VRTX 二级索引不对: %v", vSnap.indexes)
  379. }
  380. v2, err := OpenVRTX(vrtxPath, quiet())
  381. if err != nil {
  382. t.Fatal(err)
  383. }
  384. s2, err := OpenSQLite(backPath, quiet())
  385. if err != nil {
  386. t.Fatal(err)
  387. }
  388. if _, err := Run(v2, s2, quiet()); err != nil {
  389. t.Fatalf("VRTX→SQLite: %v", err)
  390. }
  391. _ = v2.Close()
  392. _ = s2.Close()
  393. got := readSQLiteRows(t, backPath)
  394. if len(got) != len(want) {
  395. t.Fatalf("行数不一致: 源 %d, 回 %d", len(want), len(got))
  396. }
  397. for id, wantRow := range want {
  398. gotRow, ok := got[id]
  399. if !ok {
  400. t.Errorf("id=%s 的行丢了", id)
  401. continue
  402. }
  403. if norm(gotRow["name"]) != norm(wantRow["name"]) ||
  404. norm(gotRow["qty"]) != norm(wantRow["qty"]) ||
  405. norm(gotRow["price"]) != norm(wantRow["price"]) ||
  406. norm(gotRow["memo"]) != norm(wantRow["memo"]) {
  407. t.Errorf("id=%s 不一致: 源 %v, 回 %v", id, wantRow, gotRow)
  408. }
  409. }
  410. }
  411. // TestSQLiteTimeColumnsToVRTX 源库的时间列迁到 VRTX。
  412. //
  413. // 三条硬要求, 每一条都对应一个真实踩过的坑:
  414. //
  415. // 1. 落 uint64 —— VRTX 没有日期类型, 时间就是 8 字节整数 (时序键 _ts 同款),
  416. // 只有这样时间列才能比较大小、做范围查询;
  417. // 2. 建在时间列上的索引必须真的建出来。时间列以前落在 dynamic 上, 引擎会拒
  418. // "动态列不能作为索引键", 整张表跟着废掉 (resource_online.idx_ctime 那个报错);
  419. // 3. 值要是时间戳本身, 且按 UTC 解释 —— 同一份数据在不同时区的机器上必须迁出
  420. // 同一个数。
  421. func TestSQLiteTimeColumnsToVRTX(t *testing.T) {
  422. dir := t.TempDir()
  423. srcPath := filepath.Join(dir, "src.sqlite")
  424. midPath := filepath.Join(dir, "mid.db")
  425. db, err := sql.Open("sqlite", srcPath)
  426. if err != nil {
  427. t.Fatal(err)
  428. }
  429. for _, s := range []string{
  430. `CREATE TABLE Events (
  431. id INTEGER PRIMARY KEY,
  432. ctime DATETIME NOT NULL,
  433. day DATE NOT NULL
  434. )`,
  435. `CREATE INDEX idx_Events_ctime ON Events(ctime)`,
  436. `INSERT INTO Events (id, ctime, day) VALUES (1, '2024-03-05 12:34:56', '2024-03-05')`,
  437. } {
  438. if _, err := db.Exec(s); err != nil {
  439. t.Fatalf("执行 %s: %v", s, err)
  440. }
  441. }
  442. _ = db.Close()
  443. s1, err := OpenSQLite(srcPath, quiet())
  444. if err != nil {
  445. t.Fatal(err)
  446. }
  447. v1, err := OpenVRTX(midPath, quiet())
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. rep, err := Run(s1, v1, quiet())
  452. if err != nil {
  453. t.Fatalf("SQLite→VRTX: %v", err)
  454. }
  455. if rep.Rows != 1 {
  456. t.Fatalf("应迁 1 行, 实际 %d", rep.Rows)
  457. }
  458. _ = s1.Close()
  459. _ = v1.Close()
  460. snap := snapshotVRTX(t, midPath, "Events")
  461. // 1. 时间列是 uint64, 不是 dynamic
  462. cols := strings.Join(snap.columns, ",")
  463. for _, want := range []string{"ctime:uint64", "day:uint64"} {
  464. if !strings.Contains(cols, want) {
  465. t.Errorf("时间列应当落成 %s, 实际列结构 %v", want, snap.columns)
  466. }
  467. }
  468. // 2. 索引建出来了 (以前这里整张表都废掉)
  469. if got := snap.indexes["idx_Events_ctime"]; got != "btree(ctime)" {
  470. t.Errorf("建在时间列上的索引没建出来, 实际 %v", snap.indexes)
  471. }
  472. // 3. 值是 UTC 时间戳本身。数字写死是为了不让实现自证自己:
  473. // 2024-03-05 12:34:56 UTC = 1709642096 秒; 2024-03-05 = 1709596800 秒。
  474. for col, wantNS := range map[string]uint64{
  475. "ctime": 1709642096000000000,
  476. "day": 1709596800000000000,
  477. } {
  478. got := snap.rows[1][col]
  479. if s := fmt.Sprintf("%v", got); s != strconv.FormatUint(wantNS, 10) {
  480. t.Errorf("%s 的 Unix 纳秒应为 %d, 实际 %v (%T)", col, wantNS, got, got)
  481. }
  482. }
  483. }
  484. // TestSkippedIndexDoesNotKillTable 目标端建不出来的索引应当只跳它自己。
  485. //
  486. // dynamic 列 (长文本) 不能作为索引键是引擎的硬限制, 但源库里这是条合法索引。
  487. // 迁一张"数据都在, 只是少个索引"的表, 比让整张表陪葬合理 —— 索引可以事后补,
  488. // 数据没迁才是真的丢。跳过的索引要写进报告, 不能静默。
  489. func TestSkippedIndexDoesNotKillTable(t *testing.T) {
  490. dir := t.TempDir()
  491. srcPath := filepath.Join(dir, "src.sqlite")
  492. midPath := filepath.Join(dir, "mid.db")
  493. db, err := sql.Open("sqlite", srcPath)
  494. if err != nil {
  495. t.Fatal(err)
  496. }
  497. for _, s := range []string{
  498. `CREATE TABLE Blobs (
  499. id INTEGER PRIMARY KEY,
  500. body BLOB NOT NULL
  501. )`,
  502. `CREATE INDEX idx_Blobs_body ON Blobs(body)`,
  503. `INSERT INTO Blobs (id, body) VALUES (1, 'hello')`,
  504. } {
  505. if _, err := db.Exec(s); err != nil {
  506. t.Fatalf("执行 %s: %v", s, err)
  507. }
  508. }
  509. _ = db.Close()
  510. s1, err := OpenSQLite(srcPath, quiet())
  511. if err != nil {
  512. t.Fatal(err)
  513. }
  514. v1, err := OpenVRTX(midPath, quiet())
  515. if err != nil {
  516. t.Fatal(err)
  517. }
  518. rep, err := Run(s1, v1, quiet())
  519. if err != nil {
  520. t.Fatalf("跳个索引不该让迁移失败: %v", err)
  521. }
  522. _ = s1.Close()
  523. _ = v1.Close()
  524. if rep.Rows != 1 {
  525. t.Fatalf("表的数据应当照迁, 实际 %d 行", rep.Rows)
  526. }
  527. if len(rep.Tables) != 1 || !strings.Contains(rep.Tables[0].Note, "跳过索引") {
  528. t.Fatalf("跳过的索引必须写进报告, 实际: %+v", rep.Tables)
  529. }
  530. snap := snapshotVRTX(t, midPath, "Blobs")
  531. if _, ok := snap.indexes["idx_Blobs_body"]; ok {
  532. t.Errorf("dynamic 列的索引不该建出来: %v", snap.indexes)
  533. }
  534. if len(snap.rows) != 1 {
  535. t.Errorf("数据应当照常迁过去, 实际 %d 行", len(snap.rows))
  536. }
  537. }
  538. // TestRunRejectsSelfMigration 源和目标指向同一个库必须拦住 —— 否则边读边写会把
  539. // 表毁掉。
  540. func TestRunRejectsSelfMigration(t *testing.T) {
  541. dir := t.TempDir()
  542. path := filepath.Join(dir, "same.db")
  543. buildVRTXUsers(t, path)
  544. a, err := OpenVRTX(path, quiet())
  545. if err != nil {
  546. t.Fatal(err)
  547. }
  548. defer a.Close()
  549. b, err := OpenVRTX(path, quiet())
  550. if err != nil {
  551. t.Fatal(err)
  552. }
  553. defer b.Close()
  554. if _, err := Run(a, b, quiet()); err == nil {
  555. t.Fatal("同一个库的自我迁移应当报错")
  556. }
  557. }
  558. // TestRunLimit 只搬前 N 行。
  559. func TestRunLimit(t *testing.T) {
  560. dir := t.TempDir()
  561. srcPath := filepath.Join(dir, "src.db")
  562. midPath := filepath.Join(dir, "mid.sqlite")
  563. buildVRTXUsers(t, srcPath)
  564. o := quiet()
  565. o.Limit = 2
  566. v1, err := OpenVRTX(srcPath, quiet())
  567. if err != nil {
  568. t.Fatal(err)
  569. }
  570. defer v1.Close()
  571. s1, err := OpenSQLite(midPath, quiet())
  572. if err != nil {
  573. t.Fatal(err)
  574. }
  575. defer s1.Close()
  576. rep, err := Run(v1, s1, o)
  577. if err != nil {
  578. t.Fatalf("限额迁移失败: %v", err)
  579. }
  580. if rep.Rows != 2 {
  581. t.Fatalf("应只搬 2 行, 实际 %d", rep.Rows)
  582. }
  583. }
  584. // createSQLiteSource 用原生 SQL 建一个外部风格的库 (没有 __vrtx_meta)。
  585. func createSQLiteSource(t *testing.T, path string) {
  586. t.Helper()
  587. db, err := sql.Open("sqlite", path)
  588. if err != nil {
  589. t.Fatal(err)
  590. }
  591. defer db.Close()
  592. stmts := []string{
  593. `CREATE TABLE Items (
  594. id INTEGER PRIMARY KEY,
  595. name VARCHAR(32) NOT NULL,
  596. qty INTEGER NOT NULL,
  597. price REAL NOT NULL,
  598. memo BLOB NOT NULL
  599. )`,
  600. `CREATE INDEX idx_Items_name ON Items(name)`,
  601. }
  602. for _, s := range stmts {
  603. if _, err := db.Exec(s); err != nil {
  604. t.Fatalf("执行 %s: %v", s, err)
  605. }
  606. }
  607. rows := []struct {
  608. id int64
  609. name string
  610. qty int64
  611. price float64
  612. memo []byte
  613. }{
  614. {1, "apple", 10, 1.25, []byte("fresh")},
  615. {2, "banana", -3, 0.5, []byte{0x00, 0xFF, 0x10}},
  616. {3, "中文名", 0, 9.99, []byte("")},
  617. }
  618. for _, r := range rows {
  619. if _, err := db.Exec(`INSERT INTO Items (id, name, qty, price, memo) VALUES (?, ?, ?, ?, ?)`,
  620. r.id, r.name, r.qty, r.price, r.memo); err != nil {
  621. t.Fatalf("插入 %v: %v", r, err)
  622. }
  623. }
  624. }
  625. func readSQLiteRows(t *testing.T, path string) map[string]map[string]any {
  626. t.Helper()
  627. db, err := sql.Open("sqlite", path)
  628. if err != nil {
  629. t.Fatal(err)
  630. }
  631. defer db.Close()
  632. rows, err := db.Query(`SELECT id, name, qty, price, memo FROM Items`)
  633. if err != nil {
  634. t.Fatalf("查询 %s: %v", path, err)
  635. }
  636. defer rows.Close()
  637. out := map[string]map[string]any{}
  638. for rows.Next() {
  639. var (
  640. id int64
  641. name string
  642. qty int64
  643. price float64
  644. memo []byte
  645. )
  646. if err := rows.Scan(&id, &name, &qty, &price, &memo); err != nil {
  647. t.Fatal(err)
  648. }
  649. out[strconv.FormatInt(id, 10)] = map[string]any{
  650. "name": name, "qty": qty, "price": price, "memo": memo,
  651. }
  652. }
  653. if err := rows.Err(); err != nil {
  654. t.Fatal(err)
  655. }
  656. return out
  657. }
  658. // TestMySQLDatabasesUnreachable 主机不通时列库要立刻报错 —— 连接界面上是个按钮,
  659. // 绝不能让它挂着不动, 更不能悄悄返回空列表 (会被当成"这台机器上没有库")。
  660. func TestMySQLDatabasesUnreachable(t *testing.T) {
  661. // 1 号端口基本不会有人监听: 连接立即被拒, 不依赖任何真实 MySQL
  662. dsn := "root:@tcp(127.0.0.1:1)/?timeout=2s"
  663. if _, err := MySQLDatabases(dsn); err == nil {
  664. t.Fatal("连不上的主机应当报错, 而不是返回空列表")
  665. }
  666. }
  667. // TestRunContinueOnError 验的是"一张表出问题不能连坐整趟":
  668. // 没有主键的表会被 prepareForVRTX 拒掉, 但同批里能迁的表必须照常迁完 ——
  669. // 失败原因记进报告, 最后 Run 用聚合错误点名, 而不是静默吞掉。
  670. func TestRunContinueOnError(t *testing.T) {
  671. dir := t.TempDir()
  672. srcPath := filepath.Join(dir, "src.sqlite")
  673. db, err := sql.Open("sqlite", srcPath)
  674. if err != nil {
  675. t.Fatal(err)
  676. }
  677. stmts := []string{
  678. // 没有主键: VRTX 侧建不出来, 这张表注定失败
  679. `CREATE TABLE OldUserDetail (id INTEGER, detail TEXT)`,
  680. `INSERT INTO OldUserDetail (id, detail) VALUES (1, 'x')`,
  681. // 正常表: 不管上面那张怎么炸, 它都该迁完
  682. `CREATE TABLE GoodTable (id INTEGER PRIMARY KEY, name VARCHAR(32))`,
  683. `INSERT INTO GoodTable (id, name) VALUES (1, 'a'), (2, 'b')`,
  684. }
  685. for _, s := range stmts {
  686. if _, err := db.Exec(s); err != nil {
  687. t.Fatalf("执行 %s: %v", s, err)
  688. }
  689. }
  690. if err := db.Close(); err != nil {
  691. t.Fatal(err)
  692. }
  693. // 继续档: 坏表跳过, 好表照迁
  694. o := quiet()
  695. o.ContinueOnError = true
  696. src, err := OpenSQLite(srcPath, quiet())
  697. if err != nil {
  698. t.Fatal(err)
  699. }
  700. defer src.Close()
  701. dst, err := OpenVRTX(filepath.Join(dir, "keep.db"), quiet())
  702. if err != nil {
  703. t.Fatal(err)
  704. }
  705. defer dst.Close()
  706. rep, runErr := Run(src, dst, o)
  707. if runErr == nil {
  708. t.Fatalf("有表没能迁完, 应当返回汇总错误; 报告:\n%s", rep)
  709. }
  710. if got := rep.Failed(); got != 1 {
  711. t.Fatalf("应当只有 1 张表失败, 实际 %d; 报告:\n%s", got, rep)
  712. }
  713. if !strings.Contains(runErr.Error(), "OldUserDetail") {
  714. t.Fatalf("汇总错误应点名失败的表: %v", runErr)
  715. }
  716. for _, tr := range rep.Tables {
  717. if tr.Table == "OldUserDetail" && tr.Error == "" {
  718. t.Fatalf("失败原因没记进报告: %+v", tr)
  719. }
  720. }
  721. var (
  722. goodRows uint64
  723. seen bool
  724. )
  725. for _, tr := range rep.Tables {
  726. if tr.Table == "GoodTable" {
  727. seen, goodRows = true, tr.Rows
  728. }
  729. }
  730. if !seen {
  731. t.Fatalf("坏表把后面的表一起带走了, GoodTable 根本没过一遍; 报告:\n%s", rep)
  732. }
  733. if goodRows != 2 {
  734. t.Fatalf("GoodTable 应当迁 2 行, 实际 %d", goodRows)
  735. }
  736. if n := rep.Failed(); n != 1 {
  737. t.Fatalf("报告里的失败表数应为 1, 实际 %d", n)
  738. }
  739. // 对照: 默认档遇错即停, 不该有"带了失败的报告"这种东西返回
  740. strict := quiet()
  741. src2, err := OpenSQLite(srcPath, quiet())
  742. if err != nil {
  743. t.Fatal(err)
  744. }
  745. defer src2.Close()
  746. dst2, err := OpenVRTX(filepath.Join(dir, "strict.db"), quiet())
  747. if err != nil {
  748. t.Fatal(err)
  749. }
  750. defer dst2.Close()
  751. if _, err := Run(src2, dst2, strict); err == nil {
  752. t.Fatal("默认档应当在第一张失败的表上就中止并报错")
  753. }
  754. }
  755. // ============================ NULL / 唯一约束 ============================
  756. // flagMarks 列上的 NULL / 唯一 / decimal scale 声明, 拼成快照里的后缀。
  757. func flagMarks(flag byte) string {
  758. var s string
  759. if flag&types.FlagNullable != 0 {
  760. s += " NULL"
  761. }
  762. if flag&types.FlagUnique != 0 {
  763. s += " UNIQUE"
  764. }
  765. if sc := flag & types.FlagScaleMask; sc != 0 {
  766. s += fmt.Sprintf(" scale=%d", sc)
  767. }
  768. return s
  769. }
  770. // buildVRTXNullUnique 建一张把 NULL 与唯一约束都压满的样本表:
  771. //
  772. // _id uint64 行号 (主键列, 非空)
  773. // Name 32 字节 非空 + 唯一索引 (列上也带声明位)
  774. // Note uint64 可空 + 唯一索引
  775. // Age uint16 可空, 无索引
  776. //
  777. // Note 特意让两行为 NULL: 唯一索引对 NULL 是免除的 (任一分量为 NULL 的行不进索引),
  778. // 非空唯一列测不出这条 —— 也正是"NULL 不能被写成 0"最容易出问题的地方。
  779. func buildVRTXNullUnique(t *testing.T, path string) {
  780. t.Helper()
  781. db, err := core.Open(path)
  782. if err != nil {
  783. t.Fatalf("建样本 VRTX 库: %v", err)
  784. }
  785. defer db.Close()
  786. fields := []types.FieldInfo{
  787. {FieldType: types.FieldType_Uint64, FieldName: []byte("_id")},
  788. {FieldType: types.FieldType_String, FieldName: []byte("Name"), Flag: types.FlagUnique},
  789. {FieldType: types.FieldType_Uint64, FieldName: []byte("Note"), Flag: types.FlagNullable | types.FlagUnique},
  790. {FieldType: types.FieldType_Uint16, FieldName: []byte("Age"), Flag: types.FlagNullable},
  791. }
  792. tbl, err := db.CreateTable("People", fields)
  793. if err != nil {
  794. t.Fatalf("建表: %v", err)
  795. }
  796. for _, spec := range []struct {
  797. name string
  798. typ page.IndexType
  799. col byte
  800. unique bool
  801. }{
  802. {"pk_People", page.IndexTypePrimary, 0, false},
  803. {"idx_People_Name", page.IndexTypeBTree, 1, true},
  804. {"idx_People_Note", page.IndexTypeBTree, 2, true},
  805. } {
  806. if _, err := tbl.CreateIndex(spec.name, spec.typ, []byte{spec.col}, spec.unique); err != nil {
  807. t.Fatalf("建索引 %s: %v", spec.name, err)
  808. }
  809. }
  810. writeVRTXRows(t, tbl, fields, []sampleRow{
  811. {pk: 1, vals: map[string]any{"_id": uint64(1), "Name": []byte("Alice"), "Note": uint64(100), "Age": int16(30)}},
  812. // Note / Age 写 nil: 落盘就是 NULL 位图上的一位
  813. {pk: 2, vals: map[string]any{"_id": uint64(2), "Name": []byte("Bob"), "Note": nil, "Age": nil}},
  814. {pk: 3, vals: map[string]any{"_id": uint64(3), "Name": []byte("Cara"), "Note": nil, "Age": int16(7)}},
  815. })
  816. }
  817. // checkSQLiteShape 直接查中间库的 PRAGMA, 确认可空性与唯一性真的落在了 DDL 上
  818. // (而不是只记在 __vrtx_meta 里, SQL 侧其实什么都没表达)。
  819. func checkSQLiteShape(t *testing.T, path, table string, nullable, unique map[string]bool) {
  820. t.Helper()
  821. db, err := sql.Open("sqlite", path)
  822. if err != nil {
  823. t.Fatalf("打开中间库: %v", err)
  824. }
  825. defer db.Close()
  826. rows, err := db.Query(`PRAGMA table_info("` + table + `")`)
  827. if err != nil {
  828. t.Fatalf("table_info: %v", err)
  829. }
  830. gotNullable := map[string]bool{}
  831. for rows.Next() {
  832. var cid, notNull, pk int
  833. var name, decl string
  834. var dflt any
  835. if err := rows.Scan(&cid, &name, &decl, &notNull, &dflt, &pk); err != nil {
  836. t.Fatalf("扫描 table_info: %v", err)
  837. }
  838. gotNullable[name] = notNull == 0
  839. }
  840. rows.Close()
  841. for col, want := range nullable {
  842. if gotNullable[col] != want {
  843. t.Errorf("中间库列 %s 的可空性不对: 实际 %v, 期望 %v", col, gotNullable[col], want)
  844. }
  845. }
  846. idxRows, err := db.Query(`PRAGMA index_list("` + table + `")`)
  847. if err != nil {
  848. t.Fatalf("index_list: %v", err)
  849. }
  850. gotUnique := map[string]bool{}
  851. for idxRows.Next() {
  852. var seq, uniq, partial int
  853. var name, origin string
  854. if err := idxRows.Scan(&seq, &name, &uniq, &origin, &partial); err != nil {
  855. t.Fatalf("扫描 index_list: %v", err)
  856. }
  857. if origin == "c" { // 显式 CREATE INDEX 建的才是我们要比对的
  858. gotUnique[name] = uniq != 0
  859. }
  860. }
  861. idxRows.Close()
  862. for name, want := range unique {
  863. if gotUnique[name] != want {
  864. t.Errorf("中间库索引 %s 的唯一性不对: 实际 %v, 期望 %v", name, gotUnique[name], want)
  865. }
  866. }
  867. }
  868. // TestVRTXSQLiteNullUniqueRoundTrip 可空列 + 唯一索引的 VRTX → SQLite → VRTX。
  869. //
  870. // 这两个属性在两端各只有一半的表达: NULL 在 VRTX 是行内位图的位、在 SQL 是列可空
  871. // 声明加上行里的 NULL; 唯一在 VRTX 是索引上的标志位、在 SQL 是 UNIQUE INDEX。
  872. // 少带任何一半, 往返都会静默变形 —— NULL 被写成一个 0, 或者约束悄悄退化成普通索引。
  873. func TestVRTXSQLiteNullUniqueRoundTrip(t *testing.T) {
  874. dir := t.TempDir()
  875. srcPath := filepath.Join(dir, "src.db")
  876. midPath := filepath.Join(dir, "mid.sqlite")
  877. backPath := filepath.Join(dir, "back.db")
  878. buildVRTXNullUnique(t, srcPath)
  879. want := snapshotVRTX(t, srcPath, "People")
  880. v1, err := OpenVRTX(srcPath, quiet())
  881. if err != nil {
  882. t.Fatal(err)
  883. }
  884. s1, err := OpenSQLite(midPath, quiet())
  885. if err != nil {
  886. t.Fatal(err)
  887. }
  888. if _, err := Run(v1, s1, quiet()); err != nil {
  889. t.Fatalf("VRTX→SQLite: %v", err)
  890. }
  891. _ = v1.Close()
  892. _ = s1.Close()
  893. // 中间库的结构: 可空列写 NULL (不是硬写 NOT NULL), 索引写 UNIQUE INDEX
  894. checkSQLiteShape(t, midPath, "People",
  895. map[string]bool{"_id": false, "Name": false, "Note": true, "Age": true},
  896. map[string]bool{"idx_People_Name": true, "idx_People_Note": true})
  897. s2, err := OpenSQLite(midPath, quiet())
  898. if err != nil {
  899. t.Fatal(err)
  900. }
  901. v2, err := OpenVRTX(backPath, quiet())
  902. if err != nil {
  903. t.Fatal(err)
  904. }
  905. if _, err := Run(s2, v2, quiet()); err != nil {
  906. t.Fatalf("SQLite→VRTX: %v", err)
  907. }
  908. _ = s2.Close()
  909. _ = v2.Close()
  910. got := snapshotVRTX(t, backPath, "People")
  911. if strings.Join(got.columns, "|") != strings.Join(want.columns, "|") {
  912. t.Errorf("列结构 (含 NULL / 唯一声明) 不一致\n 源: %v\n 回: %v", want.columns, got.columns)
  913. }
  914. if len(got.indexes) != len(want.indexes) {
  915. t.Errorf("索引数量不一致\n 源: %v\n 回: %v", want.indexes, got.indexes)
  916. }
  917. for name, def := range want.indexes {
  918. if got.indexes[name] != def {
  919. t.Errorf("索引 %s 不一致\n 源: %q\n 回: %q", name, def, got.indexes[name])
  920. }
  921. }
  922. if len(got.rows) != len(want.rows) {
  923. t.Fatalf("行数不一致: 源 %d, 回 %d", len(want.rows), len(got.rows))
  924. }
  925. // 逐列比对, 并且把"源里有值/回里没值"也算不一致 —— NULL 往返丢了不会体现在
  926. // norm() 上, 只会体现为"这一列在 map 里消失了"。
  927. for pk, wantRow := range want.rows {
  928. gotRow, ok := got.rows[pk]
  929. if !ok {
  930. t.Errorf("pk=%d 的行丢了", pk)
  931. continue
  932. }
  933. for _, col := range []string{"Name", "Note", "Age"} {
  934. wantVal, wantHas := wantRow[col]
  935. gotVal, gotHas := gotRow[col]
  936. if wantHas != gotHas {
  937. t.Errorf("pk=%d 列 %s 的有无不一致: 源 %v (有值=%v), 回 %v (有值=%v) —— NULL 被写成零值了",
  938. pk, col, wantVal, wantHas, gotVal, gotHas)
  939. continue
  940. }
  941. if wantHas && norm(gotVal) != norm(wantVal) {
  942. t.Errorf("pk=%d 列 %s 不一致: 源 %s, 回 %s", pk, col, norm(wantVal), norm(gotVal))
  943. }
  944. }
  945. }
  946. // 约束回到 VRTX 后必须真的生效, 不是画在 schema 上的装饰
  947. back, err := core.Open(backPath)
  948. if err != nil {
  949. t.Fatal(err)
  950. }
  951. defer back.Close()
  952. btbl, ok := back.FindTable("People")
  953. if !ok {
  954. t.Fatal("回来的库里没有 People 表")
  955. }
  956. if _, err := btbl.InsertRow([]types.FieldValue{
  957. {FieldName: []byte("Name"), Value: []byte("Alice")},
  958. }); !errors.Is(err, core.ErrDuplicatedKey) {
  959. t.Errorf("重复 Name 应当报 ErrDuplicatedKey, 实际 %v", err)
  960. }
  961. if _, err := btbl.InsertRow([]types.FieldValue{
  962. {FieldName: []byte("Name"), Value: []byte("Dan")},
  963. {FieldName: []byte("Note"), Value: uint64(100)},
  964. }); !errors.Is(err, core.ErrDuplicatedKey) {
  965. t.Errorf("重复 Note 应当报 ErrDuplicatedKey, 实际 %v", err)
  966. }
  967. // NULL 不算重复: 再加两行 Note=NULL 都该进得去
  968. for _, nm := range []string{"Eve", "Fay"} {
  969. if _, err := btbl.InsertRow([]types.FieldValue{
  970. {FieldName: []byte("Name"), Value: []byte(nm)},
  971. {FieldName: []byte("Note"), Value: nil},
  972. }); err != nil {
  973. t.Errorf("Note=NULL 的 %s 应当能插入 (唯一索引对 NULL 免除), 实际 %v", nm, err)
  974. }
  975. }
  976. }
  977. // TestSQLiteUniqueConstraintToVRTX 外部库用【列级 UNIQUE 约束】时, 约束也要跟着走。
  978. //
  979. // 这种写法在 SQLite 里没有显式索引, 只生成一条 sqlite_autoindex_* (origin='u')。
  980. // 原实现只收 origin='c' 并跳过它, 注释理由是"VRTX 没有唯一约束的概念" —— 现在有了,
  981. // 跳过就等于把用户的约束悄悄删掉。名字也不能照搬 (sqlite_ 前缀是保留的), 要改。
  982. func TestSQLiteUniqueConstraintToVRTX(t *testing.T) {
  983. dir := t.TempDir()
  984. srcPath := filepath.Join(dir, "ext.sqlite")
  985. dstPath := filepath.Join(dir, "ext.db")
  986. db, err := sql.Open("sqlite", srcPath)
  987. if err != nil {
  988. t.Fatal(err)
  989. }
  990. // code 用 INTEGER: TEXT 落到 VRTX 是动态列 (堆存), 动态列不能当索引键
  991. // (引擎会拒, migrate 记进 SkippedIndexes), 那样测的就不是唯一约束的迁移了。
  992. for _, q := range []string{
  993. `CREATE TABLE t (id INTEGER PRIMARY KEY, code INTEGER UNIQUE, note TEXT)`,
  994. `INSERT INTO t (id, code, note) VALUES (1, 100, 'x')`,
  995. `INSERT INTO t (id, code, note) VALUES (2, 200, NULL)`,
  996. } {
  997. if _, err := db.Exec(q); err != nil {
  998. t.Fatalf("%s: %v", q, err)
  999. }
  1000. }
  1001. _ = db.Close()
  1002. src, err := OpenSQLite(srcPath, quiet())
  1003. if err != nil {
  1004. t.Fatal(err)
  1005. }
  1006. sc, err := src.Schema("t")
  1007. if err != nil {
  1008. t.Fatalf("读外部库结构: %v", err)
  1009. }
  1010. var uniq *IndexSchema
  1011. for i := range sc.Indexes {
  1012. if sc.Indexes[i].Unique {
  1013. uniq = &sc.Indexes[i]
  1014. }
  1015. }
  1016. if uniq == nil {
  1017. t.Fatalf("code 的唯一约束没读出来, 索引: %v", sc.Indexes)
  1018. }
  1019. if len(uniq.Columns) != 1 || uniq.Columns[0] != "code" {
  1020. t.Fatalf("唯一索引的分量不对: %v", uniq.Columns)
  1021. }
  1022. if strings.HasPrefix(uniq.Name, "sqlite_") {
  1023. t.Errorf("唯一索引名不该照搬 SQLite 的保留名: %s", uniq.Name)
  1024. }
  1025. dst, err := OpenVRTX(dstPath, quiet())
  1026. if err != nil {
  1027. t.Fatal(err)
  1028. }
  1029. if _, err := Run(src, dst, quiet()); err != nil {
  1030. t.Fatalf("SQLite→VRTX: %v", err)
  1031. }
  1032. _ = src.Close()
  1033. _ = dst.Close()
  1034. back, err := core.Open(dstPath)
  1035. if err != nil {
  1036. t.Fatal(err)
  1037. }
  1038. defer back.Close()
  1039. tbl, ok := back.FindTable("t")
  1040. if !ok {
  1041. t.Fatal("VRTX 里没有 t 表")
  1042. }
  1043. // 1) 唯一性落到索引上, 且列上补出了"唯一列"的声明位
  1044. var uniqueIdx core.IndexMeta
  1045. hasUnique := false
  1046. for _, m := range tbl.IndexMeta().GetIndexes() {
  1047. if m.Unique() {
  1048. uniqueIdx, hasUnique = m, true
  1049. }
  1050. }
  1051. if !hasUnique {
  1052. t.Fatalf("唯一约束没迁过来: 库里一条唯一索引都没有")
  1053. }
  1054. codeFid := -1
  1055. for i, f := range tbl.GetFields() {
  1056. if util.BytesToString(f.FieldName) == "code" {
  1057. codeFid = i
  1058. }
  1059. }
  1060. if codeFid < 0 {
  1061. t.Fatal("找不到 code 列")
  1062. }
  1063. if !tbl.GetFields()[codeFid].IsUnique() {
  1064. t.Errorf("code 列应当带上唯一声明位")
  1065. }
  1066. if got := uniqueIdx.Fields(); len(got) != 1 || got[0] != byte(codeFid) {
  1067. t.Errorf("唯一索引的分量应当是 code(%d), 实际 %v", codeFid, got)
  1068. }
  1069. // 2) 约束真的会拦: 重复 code 被拒
  1070. if _, err := tbl.InsertRow([]types.FieldValue{
  1071. {FieldName: []byte("id"), Value: uint64(3)},
  1072. {FieldName: []byte("code"), Value: uint64(100)},
  1073. }); !errors.Is(err, core.ErrDuplicatedKey) {
  1074. t.Errorf("重复 code 应当报 ErrDuplicatedKey, 实际 %v", err)
  1075. }
  1076. // 3) NULL 也保住了 (note 第 2 行是 NULL)
  1077. row, err := tbl.FindByPK(2)
  1078. if err != nil {
  1079. t.Fatalf("读回 pk=2: %v", err)
  1080. }
  1081. for _, fv := range row {
  1082. if util.BytesToString(fv.FieldName) == "note" {
  1083. t.Errorf("note 本该是 NULL (不出现), 实际 %v", fv.Value)
  1084. }
  1085. }
  1086. }
  1087. // TestCappedColumnCapacityReported 源库声明了超过单值上限的列必须写进迁移报告。
  1088. //
  1089. // 与 SkippedIndexes 是同一条原则: 静默把容量改小等于悄悄改结构 —— 源库写的是
  1090. // varchar(60000), 到 VRTX 端只能是条装不下 60000 字节的动态列, 不报出来用户永远不会知道。
  1091. //
  1092. // 但它与"丢索引"一样【不该让整张表陪葬】: 超限只说明这一列的上限比声明的小, 大部分数据照样
  1093. // 迁得动, 真有大值会在写入时报出列名并拒 —— 为了一列的容量放弃整张表的数据, 代价不成比例。
  1094. func TestCappedColumnCapacityReported(t *testing.T) {
  1095. dir := t.TempDir()
  1096. srcPath := filepath.Join(dir, "src.sqlite")
  1097. dstPath := filepath.Join(dir, "dst.db")
  1098. raw, err := sql.Open("sqlite", srcPath)
  1099. if err != nil {
  1100. t.Fatal(err)
  1101. }
  1102. // SQLite 不校验 varchar 的长度, 所以"声明了引擎兑现不了的容量"这种库在现实中真会出现。
  1103. stmts := []string{
  1104. `CREATE TABLE Wide (
  1105. id INTEGER PRIMARY KEY,
  1106. big VARCHAR(60000),
  1107. ok VARCHAR(200)
  1108. )`,
  1109. `INSERT INTO Wide (id, big, ok) VALUES (1, 'small', 'fine')`,
  1110. }
  1111. for _, s := range stmts {
  1112. if _, err := raw.Exec(s); err != nil {
  1113. t.Fatalf("建样本 SQLite 库: %v", err)
  1114. }
  1115. }
  1116. if err := raw.Close(); err != nil {
  1117. t.Fatal(err)
  1118. }
  1119. src, err := OpenSQLite(srcPath, quiet())
  1120. if err != nil {
  1121. t.Fatal(err)
  1122. }
  1123. defer src.Close()
  1124. dst, err := OpenVRTX(dstPath, quiet())
  1125. if err != nil {
  1126. t.Fatal(err)
  1127. }
  1128. defer dst.Close()
  1129. rep, err := Run(src, dst, quiet())
  1130. if err != nil {
  1131. t.Fatalf("迁移不该因为容量封顶而失败: %v", err)
  1132. }
  1133. if len(rep.Tables) != 1 {
  1134. t.Fatalf("应当只有 1 张表的报告, 实际 %d", len(rep.Tables))
  1135. }
  1136. note := rep.Tables[0].Note
  1137. // 报告要点名到列, 并给出两个数: 用户写下的 60000 与引擎能给的上限。
  1138. for _, want := range []string{"容量封顶", "big", "60000", strconv.Itoa(types.MaxStringSize)} {
  1139. if !strings.Contains(note, want) {
  1140. t.Errorf("报告里缺少 %q: %q", want, note)
  1141. }
  1142. }
  1143. // 没超限的列不该被连坐 (ok 列只有 200 字节, 在定长档里)。
  1144. if strings.Contains(note, "ok:") {
  1145. t.Errorf("未超限的列不该出现在容量报告里: %q", note)
  1146. }
  1147. // 数据照迁: 容量封顶只是提示, 不是拒绝。
  1148. if rep.Rows != 1 {
  1149. t.Errorf("应照常搬走 1 行, 实际 %d", rep.Rows)
  1150. }
  1151. }
  1152. // TestVRTXWriterNameSourceRowOnOversize 写失败时必须报出【源库里是哪一行】。
  1153. //
  1154. // 起因是真实迁移: steambox_forum.resource_detail 有一行 content 16862 字节, 越过引擎单值
  1155. // 上限 16360。这个值 VRTX 目前确实装不下 (Dynamicbyte 与 Blob 的单值上限一样, "多页分块 +
  1156. // 链式 next"在 types.go 里还只是将来计划), 所以该拒; 但只报"表 x 的 content 超限"不够用 ——
  1157. // 用户要回源库处理那一行 (把列改大 / 把值裁小 / 剔掉), 先得知道是哪一行。那张表的 id 恰好
  1158. // 属于"主键承载不了行号"这一种 (MySQL 的 int(11) 只有 4 字节, 行号换成了补出来的 _id), 所以
  1159. // 最靠得住的身份是源库主键列的值 —— 它降级之后仍然躺在行数据里。
  1160. func TestVRTXWriterNameSourceRowOnOversize(t *testing.T) {
  1161. // 16862 是真实那行的长度, 这里照抄: 刚好越过 16360。
  1162. big := strings.Repeat("x", 16862)
  1163. for _, c := range []struct {
  1164. name string
  1165. srcPK string // SourcePKColumn: 源库主键列名, 被降级成普通列时才非空
  1166. hasPK bool
  1167. want string
  1168. }{
  1169. {"源库主键承载行号", "", true, "主键 77"},
  1170. {"源库无整型主键 (auto-pk 补号)", "", false, "批内第 1 行"},
  1171. {"源库主键被降级成普通列", "id", false, "源表主键 12345"},
  1172. } {
  1173. t.Run(c.name, func(t *testing.T) {
  1174. v, err := OpenVRTX(filepath.Join(t.TempDir(), "t.vrtx"), quiet())
  1175. if err != nil {
  1176. t.Fatalf("建库: %v", err)
  1177. }
  1178. defer v.Close()
  1179. schema := &TableSchema{
  1180. Name: "ResourceDetail",
  1181. PKColumn: "_id",
  1182. PKIndexName: "pk_ResourceDetail",
  1183. PKIndexType: page.IndexTypePrimary,
  1184. SourcePKColumn: c.srcPK,
  1185. Columns: []Column{
  1186. {Name: "id", Type: types.FieldType_Int32},
  1187. {Name: "_id", Type: types.FieldType_Uint64},
  1188. {Name: "content", Type: types.FieldType_Dynamicbyte},
  1189. },
  1190. }
  1191. if err := v.CreateTable(schema, false); err != nil {
  1192. t.Fatalf("建表: %v", err)
  1193. }
  1194. w, err := v.Open("ResourceDetail", schema)
  1195. if err != nil {
  1196. t.Fatalf("打开写入端: %v", err)
  1197. }
  1198. err = w.Write([]Row{{
  1199. PK: 77, HasPK: c.hasPK,
  1200. Values: []any{int64(12345), int64(77), big},
  1201. }})
  1202. if err == nil {
  1203. t.Fatal("16862 字节超过单值上限 16360, 应当报错而不是写进去")
  1204. }
  1205. // 四样都得有: 哪一行、哪一列、值多大、上限多少 —— 少一样用户就得回源库自己捞。
  1206. for _, want := range []string{c.want, "content", "16862", "16360"} {
  1207. if !strings.Contains(err.Error(), want) {
  1208. t.Errorf("错误信息里该有 %q, 实际: %v", want, err)
  1209. }
  1210. }
  1211. })
  1212. }
  1213. }
  1214. // TestRuneSafeCut 截断位置必须落在 UTF-8 字符边界上。
  1215. //
  1216. // 文本列截断最难看的结果是留下半个汉字 (只读起来是无意义的替换字符)。判据是"被排除的
  1217. // 第一个字节是不是字符起始字节": 原值本身是合法文本时, 从字符边界切开得到的必然还是合法
  1218. // 文本。
  1219. func TestRuneSafeCut(t *testing.T) {
  1220. zh := []byte(strings.Repeat("汉", 5)) // 15 字节, 每字 3 字节: 0-2 / 3-5 / 6-8 / 9-11 / 12-14
  1221. // 10 落在第 4 个字 (9-11) 中间 → 退到 9。
  1222. if got := runeSafeCut(zh, 10); got != 9 {
  1223. t.Errorf("切在字符中间应退到边界 9, 实际 %d", got)
  1224. }
  1225. if !utf8.Valid(zh[:9]) {
  1226. t.Errorf("退到边界后应当是合法 UTF-8: %q", zh[:9])
  1227. }
  1228. // 本就落在边界上不退。
  1229. if got := runeSafeCut(zh, 9); got != 9 {
  1230. t.Errorf("本就落在边界上不该退, 实际 %d", got)
  1231. }
  1232. // 不超上限原样返回。
  1233. if got := runeSafeCut(zh, 15); got != 15 {
  1234. t.Errorf("等于长度应原样返回, 实际 %d", got)
  1235. }
  1236. if got := runeSafeCut(zh, 99); got != 15 {
  1237. t.Errorf("超过长度应原样返回, 实际 %d", got)
  1238. }
  1239. // 单字节字符: 按字节截。
  1240. if got := runeSafeCut([]byte("abcdef"), 3); got != 3 {
  1241. t.Errorf("ASCII 应按字节截到 3, 实际 %d", got)
  1242. }
  1243. // 不是文本 (整段都是续字节): 没有字符边界可退, 老实按字节截, 别截成空的。
  1244. if got := runeSafeCut(bytes.Repeat([]byte{0x80}, 10), 5); got != 5 {
  1245. t.Errorf("非文本数据应按字节截到 5, 实际 %d", got)
  1246. }
  1247. }
  1248. // TestVRTXWriterTruncateOversize 打开 TruncateOversize 后, 超限的值按字符边界截断写入,
  1249. // 并且【每一行都报出来】。
  1250. //
  1251. // 与 TestVRTXWriterNameSourceRowOnOversize 是一对: 那个钉"默认报错、且报得出是哪一行",
  1252. // 这个钉"显式打开后不报错, 但必须留下可追查的记录"。两个都不能少 —— 默认关着是为了不静默
  1253. // 丢数据; 打开之后逐行报, 是为了用户还能回源库把内容补回来。
  1254. func TestVRTXWriterTruncateOversize(t *testing.T) {
  1255. // 16380 字节 (3 的倍数), 上限 16360 落在第 5454 个字的中间 (16359 才是个边界),
  1256. // 所以这一条同时验了"超限"与"退字符边界"。
  1257. big := strings.Repeat("汉", 5460)
  1258. var truncLogs []string
  1259. opts := quiet()
  1260. opts.Log = func(format string, args ...any) {
  1261. if s := fmt.Sprintf(format, args...); strings.Contains(s, "超过单值上限") {
  1262. truncLogs = append(truncLogs, s)
  1263. }
  1264. }
  1265. opts.TruncateOversize = true
  1266. v, err := OpenVRTX(filepath.Join(t.TempDir(), "t.vrtx"), opts)
  1267. if err != nil {
  1268. t.Fatalf("建库: %v", err)
  1269. }
  1270. defer v.Close()
  1271. schema := &TableSchema{
  1272. Name: "ResourceDetail",
  1273. PKColumn: "_id",
  1274. PKIndexName: "pk_ResourceDetail",
  1275. PKIndexType: page.IndexTypePrimary,
  1276. Columns: []Column{
  1277. {Name: "_id", Type: types.FieldType_Uint64},
  1278. {Name: "content", Type: types.FieldType_Dynamicbyte},
  1279. },
  1280. }
  1281. if err := v.CreateTable(schema, false); err != nil {
  1282. t.Fatalf("建表: %v", err)
  1283. }
  1284. w, err := v.Open("ResourceDetail", schema)
  1285. if err != nil {
  1286. t.Fatalf("打开写入端: %v", err)
  1287. }
  1288. if err := w.Write([]Row{{PK: 91, HasPK: true, Values: []any{int64(91), big}}}); err != nil {
  1289. t.Fatalf("打开截断开关后不该报错: %v", err)
  1290. }
  1291. if err := v.Commit(); err != nil {
  1292. t.Fatalf("提交: %v", err)
  1293. }
  1294. // 逐行报: 表 / 行 / 列 / 原长 / 上限 / 截后长 —— 缺一样用户就补不回那一行。
  1295. if len(truncLogs) != 1 {
  1296. t.Fatalf("应当逐行报出 1 条截断记录, 实际 %d 条: %v", len(truncLogs), truncLogs)
  1297. }
  1298. for _, want := range []string{"ResourceDetail", "主键 91", "content", "16380", "16360", "16359"} {
  1299. if !strings.Contains(truncLogs[0], want) {
  1300. t.Errorf("截断记录里该有 %q: %q", want, truncLogs[0])
  1301. }
  1302. }
  1303. // 落盘的值确实是被截过的, 而且仍然是合法 UTF-8。
  1304. var got []byte
  1305. if err := v.Scan("ResourceDetail", schema, func(r Row) error {
  1306. b, ok := r.Values[1].([]byte)
  1307. if !ok {
  1308. t.Fatalf("content 读回来应当是 []byte, 实际 %T", r.Values[1])
  1309. }
  1310. got = append([]byte(nil), b...)
  1311. return nil
  1312. }); err != nil {
  1313. t.Fatalf("扫描: %v", err)
  1314. }
  1315. if want := []byte(big[:16359]); !bytes.Equal(got, want) {
  1316. t.Errorf("落盘的值应是前 16359 字节 (字符边界), 实际 %d 字节", len(got))
  1317. }
  1318. if !utf8.Valid(got) {
  1319. t.Error("截断后的值必须是合法 UTF-8 —— 不能留半个汉字")
  1320. }
  1321. }
  1322. // TestVRTXWriterTruncateOversizeOffByDefault -truncate-oversize 默认关着: 不开就不许截。
  1323. //
  1324. // 与 StrictValue (-loose) 的分工也要钉住: 那两个开关管"值装不进这一列的宽度", 这个只管
  1325. // "超过引擎单值上限"。所以只开 -loose 时, 超限值照样要报错 —— 否则用户以为自己在"宽松
  1326. // 模式"下跑, 却没意识到内容已经被砍掉了一截。
  1327. func TestVRTXWriterTruncateOversizeOffByDefault(t *testing.T) {
  1328. big := strings.Repeat("x", 16862)
  1329. for _, c := range []struct {
  1330. name string
  1331. loose bool // StrictValue = !loose
  1332. truncate bool
  1333. wantErr bool
  1334. }{
  1335. {"两个开关都关", false, false, true},
  1336. {"只开 -loose", true, false, true},
  1337. {"只开 -truncate-oversize", false, true, false},
  1338. } {
  1339. t.Run(c.name, func(t *testing.T) {
  1340. opts := quiet()
  1341. opts.StrictValue = !c.loose
  1342. opts.TruncateOversize = c.truncate
  1343. v, err := OpenVRTX(filepath.Join(t.TempDir(), "t.vrtx"), opts)
  1344. if err != nil {
  1345. t.Fatalf("建库: %v", err)
  1346. }
  1347. defer v.Close()
  1348. schema := &TableSchema{
  1349. Name: "Wide",
  1350. PKColumn: "_id",
  1351. PKIndexName: "pk_Wide",
  1352. PKIndexType: page.IndexTypePrimary,
  1353. Columns: []Column{
  1354. {Name: "_id", Type: types.FieldType_Uint64},
  1355. {Name: "content", Type: types.FieldType_Dynamicbyte},
  1356. },
  1357. }
  1358. if err := v.CreateTable(schema, false); err != nil {
  1359. t.Fatalf("建表: %v", err)
  1360. }
  1361. w, err := v.Open("Wide", schema)
  1362. if err != nil {
  1363. t.Fatalf("打开写入端: %v", err)
  1364. }
  1365. err = w.Write([]Row{{PK: 1, HasPK: true, Values: []any{int64(1), big}}})
  1366. if c.wantErr && err == nil {
  1367. t.Fatal("没开 -truncate-oversize 就不该动这个值, 应当报错")
  1368. }
  1369. if !c.wantErr && err != nil {
  1370. t.Fatalf("开了 -truncate-oversize 不该报错: %v", err)
  1371. }
  1372. })
  1373. }
  1374. }