2
0

jsonb_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package storage
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  6. )
  7. // A JSONB column is persisted as the type name the catalog already stores for
  8. // any column, with no row-format change: the canonical document is an ordinary
  9. // text value and survives a manager reload byte-for-byte.
  10. func TestJSONBColumnTypeSurvivesReload(t *testing.T) {
  11. _, pool, schemas, tables := newTestSession(t)
  12. if err := schemas.CreateTable(&Schema{
  13. Name: "docs",
  14. Columns: []Column{
  15. {Name: "id", Type: "INTEGER", PrimaryKey: true, Nullable: false},
  16. {Name: "doc", Type: "JSONB", Nullable: true},
  17. },
  18. }); err != nil {
  19. t.Fatalf("create table: %v", err)
  20. }
  21. canonical := `{"a":1,"b":2}`
  22. if err := tables.Insert("docs", Row{"id": int64(1), "doc": canonical}); err != nil {
  23. t.Fatalf("insert: %v", err)
  24. }
  25. schema, err := schemas.GetSchema("docs")
  26. if err != nil {
  27. t.Fatalf("get schema: %v", err)
  28. }
  29. if len(schema.Columns) != 2 || schema.Columns[1].Type != "JSONB" {
  30. t.Fatalf("declared columns = %+v, want doc JSONB", schema.Columns)
  31. }
  32. info := schema.ToAnalyzerTableInfo()
  33. if len(info.Columns) != 2 || info.Columns[1].Type != analyzer.TypeJSONB {
  34. t.Fatalf("analyzer column types = %+v, want doc JSONB", info.Columns)
  35. }
  36. if info.Columns[1].Array {
  37. t.Fatal("a JSONB column must not be marked as an array")
  38. }
  39. // The durable catalog stores the type name and the row value unchanged.
  40. var catalog string
  41. if err := pool.WithClient(func(c *KVClient) error {
  42. var err error
  43. catalog, err = c.Read("testdb:_schema:docs")
  44. return err
  45. }); err != nil {
  46. t.Fatalf("read catalog: %v", err)
  47. }
  48. if !strings.Contains(catalog, `"type":"JSONB"`) {
  49. t.Fatalf("catalog = %s, want a JSONB column type", catalog)
  50. }
  51. reloadedSchemas := NewSchemaManager(pool, "testdb")
  52. reloadedTables := NewTableManager(pool, reloadedSchemas, "testdb")
  53. reloadedSchema, err := reloadedSchemas.GetSchema("docs")
  54. if err != nil {
  55. t.Fatalf("reload schema: %v", err)
  56. }
  57. if reloadedSchema.Columns[1].Type != "JSONB" {
  58. t.Fatalf("reloaded type = %q, want JSONB", reloadedSchema.Columns[1].Type)
  59. }
  60. rows, err := reloadedTables.Select("docs", nil)
  61. if err != nil || len(rows) != 1 {
  62. t.Fatalf("reloaded rows = %v, err %v", rows, err)
  63. }
  64. if rows[0]["doc"] != canonical {
  65. t.Fatalf("reloaded doc = %v, want %q", rows[0]["doc"], canonical)
  66. }
  67. }