Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-download): client-side SQL result download module (isDev-gated) (#20317)
zchpeter5f0420d1ba5a
diff --git a/.sonarcloud.properties b/.sonarcloud.propertiesindex 1f062a2da7..33738beb20 100644--- a/.sonarcloud.properties+++ b/.sonarcloud.properties@@ -10,6 +10,7 @@ sonar.exclusions=\bytebase-build/**,\frontend/node_modules/**,\frontend/playwright.config.ts,\+ frontend/src/utils/sql-download/__tests__/goldens/**,\scripts/cosmos-repro-dotnet/**,\scripts/cosmos-repro-go/**diff --git a/backend/component/export/csv.go b/backend/component/export/csv.goindex 6b903e10a8..b1917eb12a 100644--- a/backend/component/export/csv.go+++ b/backend/component/export/csv.go@@ -3,6 +3,7 @@ package exportimport ("encoding/hex""io"+ "slices""strconv""strings"@@ -126,10 +127,16 @@ func convertValueValueToBytes(value *structpb.Value) []byte {result = append(result, '"')return resultcase *structpb.Value_StructValue:+ fields := value.GetStructValue().Fields+ keys := make([]string, 0, len(fields))+ for k := range fields {+ keys = append(keys, k)+ }+ slices.Sort(keys)first := truevar buf []bytebuf = append(buf, '"')- for k, v := range value.GetStructValue().Fields {+ for _, k := range keys {if first {first = false} else {@@ -137,7 +144,7 @@ func convertValueValueToBytes(value *structpb.Value) []byte {}buf = append(buf, []byte(k)...)buf = append(buf, ':')- buf = append(buf, convertValueValueToBytes(v)...)+ buf = append(buf, convertValueValueToBytes(fields[k])...)}buf = append(buf, '"')return bufdiff --git a/backend/component/export/formatter_goldens_test.go b/backend/component/export/formatter_goldens_test.gonew file mode 100644index 0000000000..2bdce23e04--- /dev/null+++ b/backend/component/export/formatter_goldens_test.go@@ -0,0 +1,132 @@+package export++import (+ "bufio"+ "encoding/hex"+ "math"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"++ "google.golang.org/protobuf/types/known/timestamppb"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// goldensFormatterDir locates the shared TSV fixtures both Go and TS read from.+func goldensFormatterDir(t *testing.T) string {+ t.Helper()+ wd, err := os.Getwd()+ if err != nil {+ t.Fatalf("getwd: %v", err)+ }+ for dir := wd; dir != "/"; dir = filepath.Dir(dir) {+ candidate := filepath.Join(dir, "frontend", "src", "utils", "sql-download", "__tests__", "goldens", "formatters")+ if info, err := os.Stat(candidate); err == nil && info.IsDir() {+ return candidate+ }+ }+ t.Fatal("could not locate frontend/src/utils/sql-download/__tests__/goldens/formatters")+ return ""+}++func readTSVLines(t *testing.T, path string) [][]string {+ t.Helper()+ f, err := os.Open(path)+ if err != nil {+ t.Fatalf("open %s: %v", path, err)+ }+ defer f.Close()+ var out [][]string+ s := bufio.NewScanner(f)+ for s.Scan() {+ line := s.Text()+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }+ out = append(out, strings.Split(line, "\t"))+ }+ if err := s.Err(); err != nil {+ t.Fatalf("scan %s: %v", path, err)+ }+ return out+}++func TestFloat32FormatterGolden(t *testing.T) {+ t.Parallel()+ for _, row := range readTSVLines(t, filepath.Join(goldensFormatterDir(t), "float32.tsv")) {+ if len(row) != 2 {+ t.Fatalf("float32.tsv malformed row: %v", row)+ }+ bits, err := hex.DecodeString(row[0])+ if err != nil || len(bits) != 4 {+ t.Fatalf("invalid hex %q: %v", row[0], err)+ }+ u := uint32(bits[0])<<24 | uint32(bits[1])<<16 | uint32(bits[2])<<8 | uint32(bits[3])+ f := math.Float32frombits(u)+ got := strconv.FormatFloat(float64(f), 'f', -1, 32)+ if got != row[1] {+ t.Errorf("bits=%s: got %q, want %q", row[0], got, row[1])+ }+ }+}++func TestTimestampFormatterGolden(t *testing.T) {+ t.Parallel()+ for _, row := range readTSVLines(t, filepath.Join(goldensFormatterDir(t), "timestamp.tsv")) {+ if len(row) != 3 {+ t.Fatalf("timestamp.tsv malformed row: %v", row)+ }+ sec, err := strconv.ParseInt(row[0], 10, 64)+ if err != nil {+ t.Fatalf("parse seconds %q: %v", row[0], err)+ }+ nanos, err := strconv.ParseInt(row[1], 10, 32)+ if err != nil {+ t.Fatalf("parse nanos %q: %v", row[1], err)+ }+ ts := &v1pb.RowValue_Timestamp{+ GoogleTimestamp: ×tamppb.Timestamp{Seconds: sec, Nanos: int32(nanos)},+ }+ got := formatTimestamp(ts)+ if got != row[2] {+ t.Errorf("seconds=%d nanos=%d: got %q, want %q", sec, nanos, got, row[2])+ }+ }+}++func TestTimestampTZFormatterGolden(t *testing.T) {+ t.Parallel()+ for _, row := range readTSVLines(t, filepath.Join(goldensFormatterDir(t), "timestamptz.tsv")) {+ if len(row) != 5 {+ t.Fatalf("timestamptz.tsv malformed row: %v", row)+ }+ sec, err := strconv.ParseInt(row[0], 10, 64)+ if err != nil {+ t.Fatalf("parse seconds %q: %v", row[0], err)+ }+ nanos, err := strconv.ParseInt(row[1], 10, 32)+ if err != nil {+ t.Fatalf("parse nanos %q: %v", row[1], err)+ }+ zone := row[2]+ if zone == "-" {+ zone = ""+ }+ offset, err := strconv.ParseInt(row[3], 10, 32)+ if err != nil {+ t.Fatalf("parse offset %q: %v", row[3], err)+ }+ ts := &v1pb.RowValue_TimestampTZ{+ GoogleTimestamp: ×tamppb.Timestamp{Seconds: sec, Nanos: int32(nanos)},+ Zone: zone,+ Offset: int32(offset),+ }+ got := formatTimestampTz(ts)+ if got != row[4] {+ t.Errorf("seconds=%d nanos=%d zone=%q offset=%d: got %q, want %q", sec, nanos, zone, offset, got, row[4])+ }+ }+}diff --git a/frontend/biome.json b/frontend/biome.jsonindex b69227aa3b..dcfe19ebc9 100644--- a/frontend/biome.json+++ b/frontend/biome.json@@ -3,7 +3,12 @@"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },"files": {"ignoreUnknown": true,- "includes": ["src/**/*", "!!src/bbkit/BBUtil.ts", "!!src/types/proto-es/**"]+ "includes": [+ "src/**/*",+ "!!src/bbkit/BBUtil.ts",+ "!!src/types/proto-es/**",+ "!!src/utils/sql-download/__tests__/goldens/**"+ ]},"formatter": {"enabled": true,diff --git a/frontend/package.json b/frontend/package.jsonindex 03285cbf17..6bf3222aae 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -42,6 +42,7 @@"@markdoc/markdoc": "0.5.7","@tanstack/react-virtual": "^3.13.24","@vueuse/core": "14.3.0",+ "@zip.js/zip.js": "^2.8.26","bootstrap": "5.3.8","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -53,6 +54,7 @@"elkjs": "^0.11.0","emittery": "^1.2.0","events": "^3.3.0",+ "exceljs": "^4.4.0","file-saver": "^2.0.5","highlight.js": "11.11.1","html-query-plan": "^2.6.1",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 3287a003e5..435c7bb2c3 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -4,6 +4,12 @@ settings:autoInstallPeers: trueexcludeLinksFromLockfile: false+overrides:+ readdir-glob>minimatch: ^5.1.9+ tmp: ^0.2.5+ exceljs>archiver: ^7.0.0+ exceljs>unzipper: ^0.12.0+pnpmfileChecksum: sha256-D+Oiltjq0mI5+T73et/+VdZYEDWjB/193i1+mwbpq0Y=importers:@@ -64,6 +70,9 @@ importers:'@vueuse/core':specifier: 14.3.0version: 14.3.0([email protected]([email protected]))+ '@zip.js/zip.js':+ specifier: ^2.8.26+ version: 2.8.26bootstrap:specifier: 5.3.8version: 5.3.8(@popperjs/[email protected])@@ -97,6 +106,9 @@ importers:events:specifier: ^3.3.0version: 3.3.0+ exceljs:+ specifier: ^4.4.0+ version: 4.4.0file-saver:specifier: ^2.0.5version: 2.0.5@@ -1679,6 +1691,12 @@ packages:'@noble/hashes':optional: true+ '@fast-csv/[email protected]':+ resolution: {integrity: sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==}++ '@fast-csv/[email protected]':+ resolution: {integrity: sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==}+'@floating-ui/[email protected]':resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}@@ -2379,6 +2397,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==}+'@types/[email protected]':resolution: {integrity: sha512-8oljBDGun9cIsZRJR6fkihn0TSXJI0UDOOhncYaERq6M0JMDoPLxyscwruJcb4GKS6dvK/d8xebYBg27h/duaQ==}@@ -2704,10 +2725,18 @@ packages:peerDependencies:vue: ^3.5.0+ '@zip.js/[email protected]':+ resolution: {integrity: sha512-RQ4h9F6DOiHxpdocUDrOl6xBM+yOtz+LkUol47AVWcfebGBDpZ7w7Xvz9PS24JgXvLGiXXzSAfdCdVy1tPlaFA==}+ engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'}+resolution: {integrity: sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==}engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}+ resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}+ engines: {node: '>=6.5'}+resolution: {integrity: sha512-BsLm5vFMRUrrLeCcRc+G0t2qOaTzpoJQLOubq2XM72eNpjF5UdU5o/5NvlNhx95XHcAvcl8OMXr4mlg/fRgUXQ==}engines: {node: '>=6'}@@ -2767,6 +2796,14 @@ packages:resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}engines: {node: '>=12'}+ resolution: {integrity: sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==}@@ -2794,6 +2831,14 @@ packages:peerDependencies:postcss: ^8.1.0+ resolution: {integrity: sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==}+ peerDependencies:+ react-native-b4a: '*'+ peerDependenciesMeta:+ react-native-b4a:+ optional: true+resolution: {integrity: sha512-Co2Y9wX854ts6U8gAAPXfn0GmAyctHuK8n0Yhfjd6t30g7yvKjspvvOo9yG+z52PZRgFErt7Ka2pYnXCjLKEpg==}peerDependencies:@@ -2819,6 +2864,47 @@ packages:resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}engines: {node: 18 || 20 || >=22}+ resolution: {integrity: sha512-HdUm8EMQBLaJvGUdidNNbqpA1kYkwNcb+MYxkxCLAPJGQzlv9J0C24h8V65Z4c5GLd/JEALDvpFCQgpLJqc0zw==}+ peerDependencies:+ bare-abort-controller: '*'+ peerDependenciesMeta:+ bare-abort-controller:+ optional: true++ resolution: {integrity: sha512-WDRsyVN52eAx/lBamKD6uyw8H4228h/x0sGGGegOamM2cd7Pag88GfMQalobXI+HaEUxpCkbKQUDOQqt9wawRw==}+ engines: {bare: '>=1.16.0'}+ peerDependencies:+ bare-buffer: '*'+ peerDependenciesMeta:+ bare-buffer:+ optional: true++ resolution: {integrity: sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ==}+ engines: {bare: '>=1.14.0'}++ resolution: {integrity: sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==}++ resolution: {integrity: sha512-Vp0cnjYyrEC4whYTymQ+YZi6pBpfiICZO3cfRG8sy67ZNWe951urv1x4eW1BKNngw3U+3fPYb5JQvHbCtxH7Ow==}+ peerDependencies:+ bare-abort-controller: '*'+ bare-buffer: '*'+ bare-events: '*'+ peerDependenciesMeta:+ bare-abort-controller:+ optional: true+ bare-buffer:+ optional: true+ bare-events:+ optional: true++ resolution: {integrity: sha512-Kccpc7ACfXaxfeInfqKcZtW4pT5YBn1mesc4sCsun6sRwtbJ4h+sNOaksUpYEJUKfN65YWC6Bw2OJEFiKxq8nQ==}+resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}@@ -2833,6 +2919,9 @@ packages:resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==}+ resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}+resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}@@ -2867,6 +2956,10 @@ packages:engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}hasBin: true+ resolution: {integrity: sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==}+ engines: {node: '>=8.0.0'}+resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}@@ -2964,6 +3057,10 @@ packages:resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==}engines: {node: '>= 10'}+ resolution: {integrity: sha512-6FqVXeETqWPoGcfzrXb37E50NP0LXT8kAMu5ooZayhWWdgEY4lBEEcbQNXtkuKQsGduxiIcI4gOTsxTmuq/bSg==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==}@@ -2995,6 +3092,15 @@ packages:resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}+ resolution: {integrity: sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==}+ engines: {node: '>=0.8'}+ hasBin: true++ resolution: {integrity: sha512-piICUB6ei4IlTv1+653yq5+KoqfBYmj9bw6LqXoOneTMDXk5nM1qt12mFW1caG3LlJXEKW1Bp0WggEmIfQB34g==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}@@ -3251,6 +3357,9 @@ packages:resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}+resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}@@ -3433,10 +3542,21 @@ packages:resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}+resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}+ resolution: {integrity: sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==}+ engines: {node: '>=8.3.0'}+resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}engines: {node: '>=12.0.0'}@@ -3447,9 +3567,16 @@ packages:resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}+ resolution: {integrity: sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==}+ engines: {node: '>=10.0.0'}+resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}+ resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==}+resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}engines: {node: '>=8.6.0'}@@ -3518,6 +3645,10 @@ packages:react-dom:optional: true+ resolution: {integrity: sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==}+ engines: {node: '>=14.14'}+resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}@@ -3751,6 +3882,10 @@ packages:resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}+ resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==}engines: {node: '>=18'}@@ -3832,6 +3967,9 @@ packages:resolution: {integrity: sha512-WYDyuc/uFcGp6YtM2H0uKmUwieOuzeE/5YocFJLnLfclZ4inf3mRn8ZVy1s7Hxji7Jxm6Ss8gqpexD/GlKoGgg==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}+ resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==}+resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}@@ -3841,6 +3979,10 @@ packages:resolution: {integrity: sha512-v2xMAarJOFy51kuesYEIIx5r4WHvsV+VLMU49K24bdiRZGUpo1ZulO1DRrLozM5BMbXUfRfrUTM2PbBfYCeA4Q==}+ resolution: {integrity: sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==}+ engines: {node: '>= 0.6.3'}+resolution: {integrity: sha512-UyIwNb1lJBChJnGfjmO0OR+ezh2iVu1Kas3nvBS/BzGnx79dv6g7unpKIDNPMhfdTEGoc7mC8uAu51XEtX+FHQ==}engines: {node: '>=6'}@@ -4002,6 +4144,31 @@ packages:resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}+ resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}++ resolution: {integrity: sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==}++ resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==}++ resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}+ deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.++ resolution: {integrity: sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==}++ resolution: {integrity: sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==}++ resolution: {integrity: sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==}++ resolution: {integrity: sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==}+resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==}@@ -4233,6 +4400,10 @@ packages:resolution: {integrity: sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==}engines: {node: '>=10'}+ resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w==}engines: {node: '>=16 || 14 >=14.17'}@@ -4316,6 +4487,9 @@ packages:resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==}hasBin: true+ resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}+resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==}@@ -4324,6 +4498,10 @@ packages:engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}hasBin: true+ resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}+ engines: {node: '>=0.10.0'}+resolution: {integrity: sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==}@@ -4501,6 +4679,10 @@ packages:resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}+ resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==}+ engines: {node: '>= 0.6.0'}+resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}@@ -4633,6 +4815,13 @@ packages:resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}engines: {node: '>= 6'}+ resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==}+ engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}++ resolution: {integrity: sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==}+resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==}engines: {node: '>= 20.19.0'}@@ -4758,6 +4947,10 @@ packages:resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}+ resolution: {integrity: sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}engines: {node: '>=v12.22.7'}@@ -4864,6 +5057,9 @@ packages:resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}+ resolution: {integrity: sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg==}+resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}engines: {node: '>=8'}@@ -4938,11 +5134,20 @@ packages:resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}engines: {node: '>=6'}+ resolution: {integrity: sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==}++ resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}+resolution: {integrity: sha512-LBAhFyLho16harJoWMg/nZsQYgTrg5jXOn2nCYjRUcZZEdE3qa2zb8QEDRUGVZBW4rlazf2fxkg8tztybTaqWw==}engines: {node: '>=10'}hasBin: true+ resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}+resolution: {integrity: sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==}@@ -4974,8 +5179,8 @@ packages:resolution: {integrity: sha512-8PWx8tvC4jDB39BQw1m4x8y5MH1BcQ5xHeL2n7UVFulMPH/3Q0uiamahFJ3lXA0zO2SUyRXuVVbWSDmstlt9YA==}hasBin: true- resolution: {integrity: sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==}+ resolution: {integrity: sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==}engines: {node: '>=14.14'}@@ -5093,6 +5298,10 @@ packages:resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}engines: {node: '>= 4.0.0'}+ resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}+ engines: {node: '>= 10.0.0'}+resolution: {integrity: sha512-5lWVjgi6vuHhJ526bI4nlCOmkCIF3nnfXkCMDeMJrtdvxTs6ZFCM8oNufGTsDbKv/tJ/xj8RpvXjRuPBZJuJog==}engines: {node: '>=20.19.0'}@@ -5111,6 +5320,9 @@ packages:resolution: {integrity: sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==}engines: {node: '>=18.12.0'}+ resolution: {integrity: sha512-PZ8hTS+AqcGxsaQntl3IRBw65QrBI6lxzqDEL7IAo/XCEqRTKGfOX56Vea5TH9SZczRVxuzk1re04z/YjuYCJA==}+resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}hasBin: true@@ -5436,6 +5648,10 @@ packages:resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}engines: {node: '>=10'}+ resolution: {integrity: sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-efI2tVaVQPqtOh114loML/Z80Y4NP3yc+Ff0fYiZJPauNeWZeIp/bRFD7I9bfmCOYBh/PHxlglQ9+wvlwnPikQ==}engines: {node: '>=12.20.0'}@@ -6816,6 +7032,25 @@ snapshots:'@exodus/[email protected]': {}+ '@fast-csv/[email protected]':+ dependencies:+ '@types/node': 14.18.63+ lodash.escaperegexp: 4.1.2+ lodash.isboolean: 3.0.3+ lodash.isequal: 4.5.0+ lodash.isfunction: 3.0.9+ lodash.isnil: 4.0.0++ '@fast-csv/[email protected]':+ dependencies:+ '@types/node': 14.18.63+ lodash.escaperegexp: 4.1.2+ lodash.groupby: 4.6.0+ lodash.isfunction: 3.0.9+ lodash.isnil: 4.0.0+ lodash.isundefined: 3.0.1+ lodash.uniq: 4.5.0+'@floating-ui/[email protected]':dependencies:'@floating-ui/utils': 0.2.11@@ -7391,6 +7626,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:undici-types: 7.16.0@@ -7859,8 +8096,14 @@ snapshots:dependencies:vue: 3.5.34([email protected])+ '@zip.js/[email protected]': {}++ dependencies:+ event-target-shim: 5.0.1+dependencies:buffer: 5.7.1@@ -7919,6 +8162,30 @@ snapshots:+ dependencies:+ glob: 10.5.0+ graceful-fs: 4.2.11+ is-stream: 2.0.1+ lazystream: 1.0.1+ lodash: 4.17.23+ normalize-path: 3.0.0+ readable-stream: 4.7.0++ dependencies:+ archiver-utils: 5.0.2+ async: 3.2.6+ buffer-crc32: 1.0.0+ readable-stream: 4.7.0+ readdir-glob: 1.1.3+ tar-stream: 3.2.0+ zip-stream: 6.0.1+ transitivePeerDependencies:+ - bare-abort-controller+ - bare-buffer+ - react-native-b4a+@@ -7942,6 +8209,8 @@ snapshots:postcss: 8.5.14postcss-value-parser: 4.2.0+ [email protected]: {}+[email protected](@babel/[email protected]):dependencies:'@babel/compat-data': 7.29.0@@ -7972,6 +8241,38 @@ snapshots:+ [email protected]: {}++ dependencies:+ bare-events: 2.8.3+ bare-path: 3.0.0+ bare-stream: 2.13.1([email protected])+ bare-url: 2.4.3+ fast-fifo: 1.3.2+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a++ [email protected]: {}++ dependencies:+ bare-os: 3.9.1++ dependencies:+ streamx: 2.25.0+ teex: 1.0.1+ optionalDependencies:+ bare-events: 2.8.3+ transitivePeerDependencies:+ - react-native-b4a++ dependencies:+ bare-path: 3.0.0+@@ -7982,6 +8283,8 @@ snapshots:+ [email protected]: {}+[email protected](@popperjs/[email protected]):@@ -8018,6 +8321,8 @@ snapshots:node-releases: 2.0.38update-browserslist-db: 1.2.3([email protected])+ [email protected]: {}+@@ -8113,6 +8418,14 @@ snapshots:+ dependencies:+ crc-32: 1.2.2+ crc32-stream: 6.0.0+ is-stream: 2.0.1+ normalize-path: 3.0.0+ readable-stream: 4.7.0+@@ -8140,6 +8453,13 @@ snapshots:+ [email protected]: {}++ dependencies:+ crc-32: 1.2.2+ readable-stream: 4.7.0+@@ -8406,6 +8726,10 @@ snapshots:es-errors: 1.3.0gopd: 1.2.0+ dependencies:+ readable-stream: 2.3.8+@@ -8641,16 +8965,47 @@ snapshots:+ [email protected]: {}++ dependencies:+ bare-events: 2.8.3+ transitivePeerDependencies:+ - bare-abort-controller++ dependencies:+ archiver: 7.0.1+ dayjs: 1.11.20+ fast-csv: 4.3.6+ jszip: 3.10.1+ readable-stream: 3.6.2+ saxes: 5.0.1+ tmp: 0.2.5+ unzipper: 0.12.3+ uuid: 8.3.2+ transitivePeerDependencies:+ - bare-abort-controller+ - bare-buffer+ - react-native-b4a++ dependencies:+ '@fast-csv/format': 4.3.5+ '@fast-csv/parse': 4.3.6++ [email protected]: {}+dependencies:'@nodelib/fs.stat': 2.0.5@@ -8714,6 +9069,12 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])+ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 6.2.1+ universalify: 2.0.1+optional: true@@ -8930,6 +9291,8 @@ snapshots:+ [email protected]: {}+@@ -9015,6 +9378,12 @@ snapshots:espree: 9.6.1semver: 7.8.0+ dependencies:+ universalify: 2.0.1+ optionalDependencies:+ graceful-fs: 4.2.11+dependencies:lie: 3.3.0@@ -9031,6 +9400,10 @@ snapshots:chalk: 4.1.1dotenv: 16.6.1+ dependencies:+ readable-stream: 2.3.8+dependencies:buffer: 5.7.1@@ -9175,6 +9548,22 @@ snapshots:+ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}+@@ -9599,6 +9988,10 @@ snapshots:dependencies:brace-expansion: 2.0.2+ dependencies:+ brace-expansion: 2.0.2+dependencies:brace-expansion: 2.0.2@@ -9696,12 +10089,16 @@ snapshots:+ [email protected]: {}+dependencies:abbrev: 2.0.0+ [email protected]: {}+@@ -9948,6 +10345,8 @@ snapshots:+ [email protected]: {}+@@ -10090,6 +10489,18 @@ snapshots:string_decoder: 1.3.0util-deprecate: 1.0.2+ dependencies:+ abort-controller: 3.0.0+ buffer: 6.0.3+ events: 3.3.0+ process: 0.11.10+ string_decoder: 1.3.0++ dependencies:+ minimatch: 5.1.9+@@ -10261,6 +10672,10 @@ snapshots:+ dependencies:+ xmlchars: 2.2.0+dependencies:xmlchars: 2.2.0@@ -10353,6 +10768,15 @@ snapshots:+ dependencies:+ events-universal: 1.0.1+ fast-fifo: 1.3.2+ text-decoder: 1.2.7+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a+dependencies:emoji-regex: 8.0.0@@ -10426,6 +10850,24 @@ snapshots:+ dependencies:+ b4a: 1.8.1+ bare-fs: 4.7.1+ fast-fifo: 1.3.2+ streamx: 2.25.0+ transitivePeerDependencies:+ - bare-abort-controller+ - bare-buffer+ - react-native-b4a++ dependencies:+ streamx: 2.25.0+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a+dependencies:'@jridgewell/source-map': 0.3.11@@ -10433,6 +10875,12 @@ snapshots:commander: 2.20.3source-map-support: 0.5.21+ dependencies:+ b4a: 1.8.1+ transitivePeerDependencies:+ - react-native-b4a+dependencies:inherits: 2.0.4@@ -10461,7 +10909,7 @@ snapshots:dependencies:tldts-core: 7.0.19- [email protected]: {}+ [email protected]: {}dependencies:@@ -10583,6 +11031,8 @@ snapshots:+ [email protected]: {}+dependencies:pathe: 2.0.3@@ -10608,6 +11058,14 @@ snapshots:picomatch: 4.0.4webpack-virtual-modules: 0.6.2+ dependencies:+ bluebird: 3.7.2+ duplexer2: 0.1.4+ fs-extra: 11.3.5+ graceful-fs: 4.2.11+ node-int64: 0.4.0+dependencies:browserslist: 4.28.2@@ -10650,7 +11108,7 @@ snapshots:cac: 6.7.14import-from-esm: 1.3.4rollup-plugin-visualizer: 5.14.0([email protected])- tmp: 0.2.3+ tmp: 0.2.5transitivePeerDependencies:- rolldown- rollup@@ -10872,6 +11330,12 @@ snapshots:+ dependencies:+ archiver-utils: 5.0.2+ compress-commons: 6.0.2+ readable-stream: 4.7.0+[email protected](@types/[email protected])([email protected])([email protected])([email protected]([email protected])):optionalDependencies:'@types/react': 19.2.14diff --git a/frontend/pnpm-workspace.yaml b/frontend/pnpm-workspace.yamlindex fd42c05fc4..97f1ad1d31 100644--- a/frontend/pnpm-workspace.yaml+++ b/frontend/pnpm-workspace.yaml@@ -2,6 +2,31 @@ peerDependencyRules:allowedVersions:typescript: '6'+overrides:+ # Patch transitive minimatch <5.1.8 reached through exceljs > archiver >+ # readdir-glob. The 5.x line has three high-severity ReDoS advisories+ # (GHSA-3ppc-4f35-3m26, GHSA-7r86-cg39-jmmj, GHSA-3vr3-vh78-x7vq) fixed+ # in 5.1.8+. exceljs's internal use is not user-controllable but the+ # advisory still trips Snyk. Scoped via parent so we don't disturb+ # archiver-utils' [email protected] chain.+ readdir-glob>minimatch: ^5.1.9+ # Patch transitive [email protected] reached through exceljs. The 0.2.3 line is+ # vulnerable to a symlink attack via the `dir` parameter; fixed in 0.2.4+.+ # exceljs's internal use of tmp is for creating XLSX shared-strings temp+ # files on disk; in our browser bundle the temp paths are managed by+ # exceljs itself and not user-influenced, but the advisory still trips+ # Snyk. 0.2.x is API-stable, so the bump is drop-in.+ tmp: ^0.2.5+ # Force exceljs's archiver + unzipper to versions that drop the+ # glob@7 → [email protected] transitive chain. inflight is unmaintained+ # with no published fix for its memory-leak advisory (CVSS 6.2).+ # archiver@7 uses archiver-utils@5 → glob@10 (no inflight); [email protected]+ # uses fs-extra (no fstream/rimraf/glob@7 chain). Both retain the same+ # outer API exceljs consumes (Archiver.pipe / Open.file), so the bump+ # is drop-in — verified by the serializeXLSX tests.+ exceljs>archiver: ^7.0.0+ exceljs>unzipper: ^0.12.0+allowBuilds:core-js: trueesbuild: truediff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjsindex 19c6c11609..1897b22c21 100644--- a/frontend/scripts/check-react-i18n.mjs+++ b/frontend/scripts/check-react-i18n.mjs@@ -32,6 +32,14 @@ const DYNAMIC_PREFIXES = ["settings.sensitive-data.algorithms.","instance.selected-n-instances","settings.sidebar.",+ // Referenced via error.i18n.key on a thrown DownloadError, not as a literal+ // `t("…")` call in source. See sql-download/error-messages.ts and the+ // throw sites in sql-download/index.ts / formats/{sql,xlsx}.ts.+ "sql-editor.download-too-large-bytes",+ "sql-editor.download-too-large-cells",+ "sql-editor.download-too-large-xlsx-columns",+ "sql-editor.download-too-large-xlsx-rows",+ "sql-editor.sql-download-engine-unsupported",// Returned from getReviewBadge as labelKey string literals, not invoked// via t("…") in source. See frontend/src/react/pages/project/utils/reviewBadge.ts."common.bypassed",@@ -50,7 +58,13 @@ const LOCALES_DIR = resolve(REACT_DIR, "locales");// keeps its React tree co-located with its framework-agnostic logic at// `src/plugins/ai/react/`; include those files when scanning for `t(...)`// usage so its i18n keys don't read as "unused".-const EXTRA_REACT_DIRS = [resolve(ROOT, "src/plugins/ai/react")];+const EXTRA_REACT_DIRS = [+ resolve(ROOT, "src/plugins/ai/react"),+ // sql-download lives outside src/react/ as a framework-neutral module+ // but its `t(...)` calls (e.g. in error-messages.ts) consume keys from+ // src/react/locales — include it so those keys don't read as "unused".+ resolve(ROOT, "src/utils/sql-download"),+];const LOCALES = ["en-US", "zh-CN", "es-ES", "ja-JP", "vi-VN"];let errors = 0;diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 4ed444fee6..15431b6b2f 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -298,8 +298,12 @@"readonly": "Read-only"}},+ "download-encryption-failed": "Failed to encrypt download.",+ "download-failed": "Download failed.",+ "download-too-large": "Result is too large for download. Reduce the row count or use Export.","expired": "Expired",- "self": "SQL Editor"+ "self": "SQL Editor",+ "sql-download-unavailable": "SQL download is unavailable for this connection."},"sql-review": {"category": {},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 13ec52c4b5..98f0628531 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -298,8 +298,12 @@"readonly": "Sólo lectura"}},+ "download-encryption-failed": "Error al cifrar la descarga.",+ "download-failed": "Error en la descarga.",+ "download-too-large": "El resultado es demasiado grande para descargar. Reduzca el número de filas o use Exportar.","expired": "Expired",- "self": "Editor de SQL"+ "self": "Editor de SQL",+ "sql-download-unavailable": "La descarga SQL no está disponible para esta conexión."},"sql-review": {"category": {},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex b6681a3cd4..67c06705b2 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -298,8 +298,12 @@"readonly": "読み取り専用"}},+ "download-encryption-failed": "ダウンロードの暗号化に失敗しました。",+ "download-failed": "ダウンロードに失敗しました。",+ "download-too-large": "ダウンロードするには結果が大きすぎます。行数を減らすか、エクスポートを使用してください。","expired": "Expired",- "self": "SQLエディタ"+ "self": "SQLエディタ",+ "sql-download-unavailable": "この接続では SQL ダウンロードを利用できません。"},"sql-review": {"category": {},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 72bebf8b26..935b22105f 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -298,8 +298,12 @@"readonly": "Chỉ đọc"}},+ "download-encryption-failed": "Không thể mã hóa bản tải xuống.",+ "download-failed": "Tải xuống thất bại.",+ "download-too-large": "Kết quả quá lớn để tải xuống. Hãy giảm số dòng hoặc sử dụng Xuất.","expired": "Expired",- "self": "Trình soạn thảo SQL"+ "self": "Trình soạn thảo SQL",+ "sql-download-unavailable": "Tải xuống SQL không khả dụng cho kết nối này."},"sql-review": {"category": {},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex ffe271259f..3d5a7e103c 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -298,8 +298,12 @@"readonly": "只读数据源"}},+ "download-encryption-failed": "下载加密失败。",+ "download-failed": "下载失败。",+ "download-too-large": "结果过大,无法下载。请减少行数或使用导出。","expired": "已过期",- "self": "SQL 编辑器"+ "self": "SQL 编辑器",+ "sql-download-unavailable": "当前连接不支持 SQL 下载。"},"sql-review": {"category": {},diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsxindex 99e6be42e8..cb3f7ac2ba 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx@@ -18,6 +18,7 @@ import { cn } from "@/react/lib/utils";import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";import { pushNotification, useDatabaseV1Store, useSQLStore } from "@/store";+import { isValidDatabaseName } from "@/types";import { ExportFormat } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";@@ -28,6 +29,10 @@ import {getInstanceResource,hexToRgb,} from "@/utils";+import { buildDownloadBlob, type DownloadGroup } from "@/utils/sql-download";+import { SQL_ENGINE_QUOTES } from "@/utils/sql-download/engines";+import { downloadErrorMessage } from "@/utils/sql-download/error-messages";+import { isDev } from "@/utils/util";import { TabContextMenu } from "./ContextMenu";import { type CloseTabAction, resultTabEvents } from "./resultTabContext";@@ -84,6 +89,10 @@ export function BatchQuerySelect({>(new Set());const queryDataPolicy = useVueState(() => editorStore.queryDataPolicy);+ // Editor's per-execution row limit. Used by the dev-path export to infer+ // probable truncation: `r.rows.length === resultRowsLimit` → query+ // capped, likely more rows available.+ const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);// Read the Map's `.keys()` directly inside the Vue getter so Vue's// reactivity tracks the iteration. `useVueState(() => tabStore.currentTab)`@@ -145,6 +154,31 @@ export function BatchQuerySelect({[queriedDatabaseNames, databaseStore]);+ // Drop SQL from the export drawer when isDev() is active and any+ // user-SELECTED database's engine can't be rendered as INSERTs. Gating+ // on the full queried-database set was too conservative (a tab with one+ // MongoDB + one MySQL would hide SQL even when the user selected only+ // MySQL). Empty selection shows all formats so the user sees the SQL+ // option before picking incompatible databases.+ const supportFormats = useMemo(() => {+ const all = [+ ExportFormat.CSV,+ ExportFormat.JSON,+ ExportFormat.SQL,+ ExportFormat.XLSX,+ ];+ if (!isDev()) return all;+ if (selectedDatabaseNames.size === 0) return all;+ const allSupportSql = Array.from(selectedDatabaseNames).every((name) => {+ const db = databaseStore.getDatabaseByName(name);+ if (!isValidDatabaseName(db.name)) return true; // skipped at export time+ return SQL_ENGINE_QUOTES.has(getInstanceResource(db).engine);+ });+ return allSupportSql+ ? all+ : [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];+ }, [selectedDatabaseNames, databaseStore]);+const handleCloseSingleResultView = (item: BatchQueryItem) => {const tab = tabStore.currentTab;const contexts = tab?.databaseQueryContexts?.get(item.database.name);@@ -196,8 +230,119 @@ export function BatchQuerySelect({const validateExport = () =>selectedDatabaseNames.size > 0 && selectedDatabaseNames.size <= MAX_EXPORT;- const handleExport = ({ options, resolve }: DataExportRequest) => {+ const handleExport = ({ options, resolve, reject }: DataExportRequest) => {void (async () => {+ // === Dev path: client-side ZIP via buildDownloadBlob ===+ if (isDev()) {+ try {+ // Stale format guard: drop the export if the user-selected format+ // is no longer in the (selection-aware) supportFormats list.+ if (!supportFormats.includes(options.format)) {+ reject(+ "The selected format is not supported for the current database selection. Pick a different format."+ );+ return;+ }+ const tab = tabStore.currentTab;+ const groups: DownloadGroup[] = [];+ const limit = options.limit > 0 ? options.limit : Infinity;+ for (const databaseName of Array.from(selectedDatabaseNames)) {+ const database = databaseStore.getDatabaseByName(databaseName);+ // Skip stub-database returns with a WARN toast so the user+ // knows their selection became stale (tab torn down mid-export).+ if (!isValidDatabaseName(database.name)) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("sql-editor.batch-export.failed-for-db", {+ db: databaseName,+ }),+ description: t(+ "sql-editor.batch-export.database-no-longer-available"+ ),+ });+ continue;+ }+ const context = head(tab?.databaseQueryContexts?.get(databaseName));+ const resultSet = context?.resultSet;+ const resultError =+ resultSet?.error ||+ resultSet?.results.find((r) => r.error)?.error;+ if (resultError) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("sql-editor.batch-export.failed-for-db", {+ db: databaseName,+ }),+ description: resultError,+ });+ continue;+ }+ const results = resultSet?.results ?? [];+ if (results.length === 0) continue;+ // Truncation inference using execution-time limit.+ const executedLimit = context?.params.limit ?? resultRowsLimit;+ if (+ options.limit > 0 &&+ results.some(+ (r) =>+ r.rows.length === executedLimit &&+ options.limit > r.rows.length+ )+ ) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("sql-editor.batch-export.failed-for-db", {+ db: databaseName,+ }),+ description: t(+ "sql-editor.batch-export.export-limit-exceeds-executed",+ {+ exportLimit: options.limit,+ executedLimit,+ }+ ),+ });+ }+ const { databaseName: dbSeg, instanceName } =+ extractDatabaseResourceName(database.name);+ groups.push({+ instanceId: instanceName,+ databaseName: dbSeg,+ engine: getInstanceResource(database).engine,+ statements: results.map((r) => ({+ result:+ r.rows.length > limit+ ? { ...r, rows: r.rows.slice(0, limit) }+ : r,+ statement: r.statement || context?.params.statement || "",+ })),+ });+ }+ if (groups.length === 0) {+ reject(t("sql-editor.batch-export.no-results"));+ return;+ }+ const out = await buildDownloadBlob({+ groups,+ format: options.format,+ baseFilename: `batch-export.${dayjs().format(+ "YYYY-MM-DDTHH-mm-ss"+ )}`,+ password: options.password,+ });+ const content = new Uint8Array(await out.blob.arrayBuffer());+ resolve([{ content, filename: out.filename }]);+ setSelectedDatabaseNames(new Set());+ } catch (e) {+ reject(downloadErrorMessage(e, t));+ }+ return;+ }++ // === Prod path: per-database backend Export RPC ===const contents: DownloadContent[] = [];const tab = tabStore.currentTab;for (const databaseName of Array.from(selectedDatabaseNames)) {@@ -274,12 +419,7 @@ export function BatchQuerySelect({<DataExportButtonsize="sm"viewMode="DRAWER"- supportFormats={[- ExportFormat.CSV,- ExportFormat.JSON,- ExportFormat.SQL,- ExportFormat.XLSX,- ]}+ supportFormats={supportFormats}supportPasswordtext={t("sql-editor.batch-export.self")}tooltip={t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxindex 528874321b..f181f33b1d 100644--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -38,9 +38,14 @@ import {import type { Database } from "@/types/proto-es/v1/database_service_pb";import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import { buildDownloadBlob } from "@/utils/sql-download";+import { SQL_ENGINE_QUOTES } from "@/utils/sql-download/engines";+import { downloadErrorMessage } from "@/utils/sql-download/error-messages";+import { isDev } from "@/utils/util";import {extractDatabaseResourceName,getDatabaseProject,+ getInstanceResource,} from "@/utils/v1/database";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";@@ -72,9 +77,15 @@ export function ResultView({}: ResultViewProps) {const { t } = useTranslation();const policyStore = usePolicyV1Store();- const queryDataPolicy = useVueState(- () => useSQLEditorVueState().queryDataPolicy- );+ // Hoist the editor state singleton so the useVueState getters below don't+ // appear to call a React Hook inside a callback (Sonar S6440).+ const editorState = useSQLEditorVueState();+ const queryDataPolicy = useVueState(() => editorState.queryDataPolicy);+ // The editor's per-execution row limit. A result whose .rows.length+ // exactly equals this is probably truncated; fewer rows is probably+ // complete. Used by the dev-path export to WARN only when the user's+ // requested limit can't be satisfied from the cached result.+ const resultRowsLimit = useVueState(() => editorState.resultRowsLimit);const tabStore = useSQLEditorTabStore();const permissionDeniedError = useMemo<@@ -128,10 +139,141 @@ export function ResultView({const tabName = (index: number) => `${t("common.query")} #${index + 1}`;+ // Format list for the export drawer. Under the isDev() gate, drop SQL when+ // the database's engine can't be serialized as INSERTs — otherwise+ // selecting SQL would reach serializeSQL and throw UnsupportedFormat at+ // runtime. Production (backend Export RPC) handles all engines.+ const supportFormats = useMemo(() => {+ const all = [+ ExportFormat.CSV,+ ExportFormat.JSON,+ ExportFormat.SQL,+ ExportFormat.XLSX,+ ];+ if (!isDev()) return all;+ const engine = getInstanceResource(database).engine;+ return SQL_ENGINE_QUOTES.has(engine)+ ? all+ : [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];+ }, [database]);+const handleExport = async (req: DataExportRequest & { statement: string }) => {const { options, resolve, reject, statement } = req;++ // === Dev path: client-side ZIP via buildDownloadBlob ===+ // Production builds keep using the backend Export RPC below until the+ // client-side download module ships GA.+ if (isDev()) {+ try {+ // Guard against stale format selection: DataExportButton keeps its+ // `format` state across engine changes, so a user who picked SQL+ // before an engine switch would still submit SQL here.+ if (!supportFormats.includes(options.format)) {+ reject(+ "The selected format is not supported for the current database engine. Pick a different format."+ );+ return;+ }+ const { databaseName, instanceName } = extractDatabaseResourceName(+ database.name+ );+ const engine = getInstanceResource(database).engine;+ // Abort the whole export if ANY sub-result errored — including+ // SET statements (which we drop from `candidates` below for+ // serialization purposes). Backend's doExport (sql_service.go:1109)+ // iterates every result and aborts on the first error regardless of+ // whether the statement would have produced rows, so scanning the+ // unfiltered resultSet here keeps us in lockstep. Skipping the SET+ // filter for the error check covers cases like+ // `SELECT ...; SET unknown_var = 1;` where the failing statement+ // is non-row-producing.+ const erroredResult = resultSet?.results?.find((r) => r.error);+ if (erroredResult) {+ reject(erroredResult.error);+ return;+ }+ const candidates =+ viewMode === "MULTI-RESULT"+ ? filteredResults+ : (resultSet?.results?.slice(0, 1) ?? []);+ if (candidates.length === 0) {+ reject(t("sql-editor.batch-export.no-results"));+ return;+ }+ const sourceResults = candidates;+ const baseFilename = `${databaseName}.${dayjs().format(+ "YYYY-MM-DDTHH-mm-ss"+ )}`;+ // Apply the export drawer's row limit per-result, mirroring the+ // server-side LIMIT clause semantics. The dev path operates on+ // already-fetched rows; when the user-requested limit exceeds the+ // cached count we can only serve what we have.+ const limit = options.limit > 0 ? options.limit : Infinity;+ // Probable-truncation inference: compare cached row count against+ // the limit IN EFFECT AT EXECUTION TIME, captured in+ // `executeParams.limit`. The current editor `resultRowsLimit` is a+ // snapshot of when the user clicked Export (they may have changed+ // it between Run and Export), so it can't be the ground truth.+ const executedLimit = executeParams.limit ?? resultRowsLimit;+ if (+ options.limit > 0 &&+ sourceResults.some(+ (r) =>+ r.rows.length === executedLimit && options.limit > r.rows.length+ )+ ) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("sql-editor.batch-export.failed-for-db", {+ db: databaseName,+ }),+ description: t(+ "sql-editor.batch-export.export-limit-exceeds-executed",+ {+ exportLimit: options.limit,+ executedLimit,+ }+ ),+ });+ }+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: instanceName,+ databaseName,+ engine,+ statements: sourceResults.map((r) => ({+ result:+ r.rows.length > limit+ ? { ...r, rows: r.rows.slice(0, limit) }+ : r,+ // For multi-result, `r.statement` is the substatement the+ // backend split out — that's what the user should see. For+ // single-result, prefer the caller's verbatim `statement`+ // (the per-result form may have an auto-appended LIMIT).+ statement:+ viewMode === "MULTI-RESULT"+ ? r.statement || statement+ : statement || r.statement,+ })),+ },+ ],+ format: options.format,+ baseFilename,+ password: options.password,+ });+ const content = new Uint8Array(await out.blob.arrayBuffer());+ resolve([{ content, filename: out.filename }]);+ } catch (e) {+ reject(downloadErrorMessage(e, t));+ }+ return;+ }++ // === Prod path: backend Export RPC ===const admin = tabStore.currentTab?.mode === "ADMIN";try {const content = await useSQLStore().exportData(@@ -234,12 +376,7 @@ export function ResultView({<DataExportButtonsize="sm"disabled={false}- supportFormats={[- ExportFormat.CSV,- ExportFormat.JSON,- ExportFormat.SQL,- ExportFormat.XLSX,- ]}+ supportFormats={supportFormats}viewMode="DRAWER"supportPasswordmaximumExportCount={queryDataPolicy?.maximumResultRows}diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxindex 914a3bbac6..7a1e7c87c0 100644--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -44,12 +44,13 @@ import {type RowValue,} from "@/types/proto-es/v1/sql_service_pb";import { createExplainToken } from "@/utils/pev2";+import { SQL_ENGINE_QUOTES } from "@/utils/sql-download/engines";import {flattenElasticsearchSearchResult,flattenNoSQLQueryResult,} from "@/utils/sqlResult";import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";-import { isNullOrUndefined } from "@/utils/util";+import { isDev, isNullOrUndefined } from "@/utils/util";import {extractDatabaseResourceName,getDatabaseEnvironment,@@ -238,6 +239,23 @@ function SingleResultViewInner({const { runQuery } = useExecuteSQL();const { copyAll } = useSelectionContext();+ // Under isDev() (client-side download), drop SQL from the format list+ // when the engine isn't in SQL_ENGINE_QUOTES — otherwise selecting SQL+ // would reach serializeSQL and throw UnsupportedFormat at runtime.+ // Production (backend Export RPC) handles all engines.+ const supportFormats = useMemo(() => {+ const all = [+ ExportFormat.CSV,+ ExportFormat.JSON,+ ExportFormat.SQL,+ ExportFormat.XLSX,+ ];+ if (!isDev()) return all;+ return SQL_ENGINE_QUOTES.has(engine)+ ? all+ : [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];+ }, [engine]);+const dataTableRef = useRef<VirtualDataTableHandle | VirtualDataBlockHandle | null>(null);@@ -553,12 +571,7 @@ function SingleResultViewInner({<DataExportButtonsize="sm"disabled={!result || isEmpty(result)}- supportFormats={[- ExportFormat.CSV,- ExportFormat.JSON,- ExportFormat.SQL,- ExportFormat.XLSX,- ]}+ supportFormats={supportFormats}viewMode="DRAWER"supportPasswordmaximumExportCount={maximumExportCount}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex e04ace9ff1..01bdf49ada 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -2697,7 +2697,10 @@"allow-admin-mode-only": "Instance <instance></instance> is accessible in admin mode only.","and-n-more-databases": "and {{n}} more databases","batch-export": {+ "database-no-longer-available": "Database is no longer available in the current tab.",+ "export-limit-exceeds-executed": "Export limit {{exportLimit}} exceeds the executed query's row limit ({{executedLimit}}); exporting cached rows only.","failed-for-db": "Failed to export data for {{db}}",+ "no-results": "No results to download.","self": "Batch export","tooltip": "Select at most {{max}} databases to batch export latest query results"},@@ -2731,6 +2734,13 @@"copy-url": "Copy URL","ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.","download-as-file": "Download as {{file}}",+ "download-encryption-failed": "Failed to encrypt download.",+ "download-failed": "Download failed.",+ "download-too-large": "Result is too large for download. Reduce the row count or use Export.",+ "download-too-large-bytes": "Download is ~{{megabytes}} MB across {{statements}} statement(s); limit is {{capMb}} MB. Reduce the result size or use Export.",+ "download-too-large-cells": "Download has {{cells}} cells across {{statements}} statement(s); limit is {{limit}}. Reduce the row count or use Export.",+ "download-too-large-xlsx-columns": "XLSX cannot exceed {{limit}} columns; got {{count}}. Use Export or a different format.",+ "download-too-large-xlsx-rows": "XLSX cannot exceed {{limit}} data rows; got {{count}}. Use Export or a different format.","duration-day": "{{days}} day","duration-days": "{{days}} days","duration-hour": "{{hours}} hour",@@ -2821,6 +2831,8 @@"self": "SQL Editor","show-databases-without-query-permission": "Show databases without query permissions","show-in-editor": "Show in Editor",+ "sql-download-engine-unsupported": "SQL download is not supported for engine {{engine}}.",+ "sql-download-unavailable": "SQL download is unavailable for this connection.","sync-in-progress": "Sync in progress","tab": {"context-menu": {diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 2e60558247..8226aa82c8 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -2686,7 +2686,10 @@"allow-admin-mode-only": "La instancia <instance></instance> solo es accesible en modo administrador.","and-n-more-databases": "and {{n}} more databases","batch-export": {+ "database-no-longer-available": "La base de datos ya no está disponible en la pestaña actual.",+ "export-limit-exceeds-executed": "El límite de exportación {{exportLimit}} supera el límite de filas de la consulta ejecutada ({{executedLimit}}); se exportarán solo las filas en caché.","failed-for-db": "No se pudieron exportar los datos de {{db}}",+ "no-results": "No hay resultados para descargar.","self": "Exportación por lotes","tooltip": "Seleccione como máximo {{max}} bases de datos para exportar por lotes los resultados de las últimas consultas"},@@ -2720,6 +2723,13 @@"copy-url": "Copiar URL","ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.","download-as-file": "Descargar como {{file}}",+ "download-encryption-failed": "No se pudo cifrar la descarga.",+ "download-failed": "Error en la descarga.",+ "download-too-large": "El resultado es demasiado grande para descargar. Reduzca el número de filas o use Exportar.",+ "download-too-large-bytes": "La descarga es de ~{{megabytes}} MB en {{statements}} sentencia(s); el límite es {{capMb}} MB. Reduzca el tamaño del resultado o use Exportar.",+ "download-too-large-cells": "La descarga tiene {{cells}} celdas en {{statements}} sentencia(s); el límite es {{limit}}. Reduzca el número de filas o use Exportar.",+ "download-too-large-xlsx-columns": "XLSX no puede superar {{limit}} columnas; se obtuvieron {{count}}. Use Exportar o un formato diferente.",+ "download-too-large-xlsx-rows": "XLSX no puede superar {{limit}} filas de datos; se obtuvieron {{count}}. Use Exportar o un formato diferente.","duration-day": "{{days}} day","duration-days": "{{days}} days","duration-hour": "{{hours}} hora",@@ -2810,6 +2820,8 @@"self": "Editor de SQL","show-databases-without-query-permission": "Muestra las bases de datos que no tienen permisos de consulta","show-in-editor": "Mostrar en editor",+ "sql-download-engine-unsupported": "La descarga SQL no es compatible con el motor {{engine}}.",+ "sql-download-unavailable": "La descarga SQL no está disponible para esta conexión.","sync-in-progress": "Sincronización en progreso","tab": {"context-menu": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 5ca2294d61..5e5ed84c8d 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -2686,7 +2686,10 @@"allow-admin-mode-only": "インスタンス <instance></instance> には管理者モードでのみアクセスできます。","and-n-more-databases": "and {{n}} more databases","batch-export": {+ "database-no-longer-available": "現在のタブでデータベースを利用できません。",+ "export-limit-exceeds-executed": "エクスポート上限 {{exportLimit}} が実行済みクエリの行数上限 ({{executedLimit}}) を超えています。キャッシュされた行のみエクスポートします。","failed-for-db": "{{db}} のデータのエクスポートに失敗しました",+ "no-results": "ダウンロードできる結果がありません。","self": "一括エクスポート","tooltip": "最新のクエリ結果を一括エクスポートするには、最大 {{max}} 個のデータベースを選択してください"},@@ -2720,6 +2723,13 @@"copy-url": "URLをコピー","ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。","download-as-file": "{{file}} 形式でダウンロード",+ "download-encryption-failed": "ダウンロードの暗号化に失敗しました。",+ "download-failed": "ダウンロードに失敗しました。",+ "download-too-large": "ダウンロードするには結果が大きすぎます。行数を減らすか、エクスポートを使用してください。",+ "download-too-large-bytes": "{{statements}} 件のステートメントで合計約 {{megabytes}} MB のダウンロードです。上限は {{capMb}} MB です。結果サイズを減らすか、エクスポートを使用してください。",+ "download-too-large-cells": "{{statements}} 件のステートメントで合計 {{cells}} セルのダウンロードです。上限は {{limit}} セルです。行数を減らすか、エクスポートを使用してください。",+ "download-too-large-xlsx-columns": "XLSX の列数は {{limit}} を超えられません(取得: {{count}})。エクスポートまたは別の形式を使用してください。",+ "download-too-large-xlsx-rows": "XLSX のデータ行数は {{limit}} を超えられません(取得: {{count}})。エクスポートまたは別の形式を使用してください。","duration-day": "{{days}} day","duration-days": "{{days}} days","duration-hour": "{{hours}} 時間",@@ -2810,6 +2820,8 @@"self": "SQLエディタ","show-databases-without-query-permission": "クエリ権限のないデータベースを表示します","show-in-editor": "エディタに表示",+ "sql-download-engine-unsupported": "エンジン {{engine}} では SQL ダウンロードがサポートされていません。",+ "sql-download-unavailable": "この接続では SQL ダウンロードを利用できません。","sync-in-progress": "同期中","tab": {"context-menu": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 19439fd29a..e044a0e48d 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -2686,7 +2686,10 @@"allow-admin-mode-only": "Phiên bản <instance></instance> chỉ có thể truy cập ở chế độ quản trị.","and-n-more-databases": "and {{n}} more databases","batch-export": {+ "database-no-longer-available": "Cơ sở dữ liệu không còn khả dụng trong tab hiện tại.",+ "export-limit-exceeds-executed": "Giới hạn xuất {{exportLimit}} vượt quá giới hạn số dòng của truy vấn đã thực thi ({{executedLimit}}); chỉ xuất các dòng đã được lưu trong bộ nhớ đệm.","failed-for-db": "Không xuất được dữ liệu cho {{db}}",+ "no-results": "Không có kết quả để tải xuống.","self": "Xuất hàng loạt","tooltip": "Chọn tối đa {{max}} cơ sở dữ liệu để xuất hàng loạt kết quả truy vấn mới nhất"},@@ -2720,6 +2723,13 @@"copy-url": "Sao chép URL","ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.","download-as-file": "Tải xuống dưới dạng {{file}}",+ "download-encryption-failed": "Không thể mã hóa bản tải xuống.",+ "download-failed": "Tải xuống thất bại.",+ "download-too-large": "Kết quả quá lớn để tải xuống. Hãy giảm số dòng hoặc sử dụng Xuất.",+ "download-too-large-bytes": "Tải xuống ~{{megabytes}} MB qua {{statements}} câu lệnh; giới hạn là {{capMb}} MB. Hãy giảm kích thước kết quả hoặc sử dụng Xuất.",+ "download-too-large-cells": "Tải xuống có {{cells}} ô qua {{statements}} câu lệnh; giới hạn là {{limit}}. Hãy giảm số dòng hoặc sử dụng Xuất.",+ "download-too-large-xlsx-columns": "XLSX không thể vượt quá {{limit}} cột; nhận được {{count}}. Hãy sử dụng Xuất hoặc định dạng khác.",+ "download-too-large-xlsx-rows": "XLSX không thể vượt quá {{limit}} dòng dữ liệu; nhận được {{count}}. Hãy sử dụng Xuất hoặc định dạng khác.","duration-day": "{{days}} day","duration-days": "{{days}} days","duration-hour": "{{hours}} giờ",@@ -2810,6 +2820,8 @@"self": "Trình soạn thảo SQL","show-databases-without-query-permission": "Hiển thị cơ sở dữ liệu không có quyền truy vấn","show-in-editor": "Hiển thị trong editor",+ "sql-download-engine-unsupported": "Tải xuống SQL không được hỗ trợ cho engine {{engine}}.",+ "sql-download-unavailable": "Tải xuống SQL không khả dụng cho kết nối này.","sync-in-progress": "Đang đồng bộ","tab": {"context-menu": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex ccfdd1da9e..a812527356 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -2686,7 +2686,10 @@"allow-admin-mode-only": "实例<instance></instance>只能通过管理员模式访问。","and-n-more-databases": "及其他 {{n}} 个数据库","batch-export": {+ "database-no-longer-available": "该数据库在当前标签页中已不可用。",+ "export-limit-exceeds-executed": "导出上限 {{exportLimit}} 超过了已执行查询的行数上限 ({{executedLimit}});仅导出已缓存的行。","failed-for-db": "无法导出 {{db}} 的数据",+ "no-results": "没有可下载的结果。","self": "批量导出","tooltip": "最多选择 {{max}} 个数据库,批量导出最后一次执行的查询结果"},@@ -2720,6 +2723,13 @@"copy-url": "复制 URL","ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。","download-as-file": "下载为 {{file}} 格式",+ "download-encryption-failed": "加密下载失败。",+ "download-failed": "下载失败。",+ "download-too-large": "结果过大,无法下载。请减少行数或使用导出。",+ "download-too-large-bytes": "下载在 {{statements}} 条语句中约 {{megabytes}} MB;上限为 {{capMb}} MB。请减小结果体积或使用导出。",+ "download-too-large-cells": "下载在 {{statements}} 条语句中包含 {{cells}} 个单元格;上限为 {{limit}}。请减少行数或使用导出。",+ "download-too-large-xlsx-columns": "XLSX 列数不能超过 {{limit}};当前为 {{count}}。请使用导出或其他格式。",+ "download-too-large-xlsx-rows": "XLSX 数据行数不能超过 {{limit}};当前为 {{count}}。请使用导出或其他格式。","duration-day": "{{days}} 天","duration-days": "{{days}} 天","duration-hour": "{{hours}} 小时",@@ -2810,6 +2820,8 @@"self": "SQL 编辑器","show-databases-without-query-permission": "显示没有查询权限的数据库","show-in-editor": "在编辑器中显示",+ "sql-download-engine-unsupported": "数据库引擎 {{engine}} 不支持 SQL 下载。",+ "sql-download-unavailable": "当前连接不支持 SQL 下载。","sync-in-progress": "正在同步","tab": {"context-menu": {diff --git a/frontend/src/utils/sql-download/__tests__/csv.test.ts b/frontend/src/utils/sql-download/__tests__/csv.test.tsnew file mode 100644index 0000000000..507f9cbd5b--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/csv.test.ts@@ -0,0 +1,102 @@+import { create } from "@bufbuild/protobuf";+import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, it } from "vitest";+import {+ type QueryResult,+ QueryResultSchema,+ QueryRowSchema,+ type RowValue,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { serializeCSV } from "../formats/csv";++const TEXT_DECODER = new TextDecoder("utf-8");++const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });+const intRow = (n: bigint): RowValue =>+ create(RowValueSchema, { kind: { case: "int64Value", value: n } });+const strRow = (s: string): RowValue =>+ create(RowValueSchema, { kind: { case: "stringValue", value: s } });+const f32Row = (n: number): RowValue =>+ create(RowValueSchema, { kind: { case: "floatValue", value: n } });+const f64Row = (n: number): RowValue =>+ create(RowValueSchema, { kind: { case: "doubleValue", value: n } });+const valueRow = (v: Value): RowValue =>+ create(RowValueSchema, { kind: { case: "valueValue", value: v } });++const csv = (result: QueryResult): string =>+ TEXT_DECODER.decode(serializeCSV(result));++describe("serializeCSV", () => {+ it("emits header-only output for an empty result", () => {+ const r = create(QueryResultSchema, { columnNames: ["id", "name"] });+ expect(csv(r)).toBe("id,name\n");+ });++ it("emits basic ASCII rows (every string cell unconditionally CSV-quoted)", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["id", "name"],+ rows: [+ rowOf(intRow(1n), strRow("Alice")),+ rowOf(intRow(2n), strRow("Bob")),+ ],+ });+ expect(csv(r)).toBe('id,name\n1,"Alice"\n2,"Bob"');+ });++ it('doubles embedded `"` inside CSV-quoted strings and preserves newline/comma literals', () => {+ const r = create(QueryResultSchema, {+ columnNames: ["s"],+ rows: [rowOf(strRow(`a"b`)), rowOf(strRow("a,b")), rowOf(strRow("a\nb"))],+ });+ expect(csv(r)).toBe('s\n"a""b"\n"a,b"\n"a\nb"');+ });++ it("emits float32 via formatFloat32 (never exponential) and float64 native", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["f32", "f64"],+ rows: [rowOf(f32Row(1.5), f64Row(1e21))],+ });+ // f32: shortest-roundtrip 'f' verb; f64: JS native exponential at >= 1e21.+ expect(csv(r)).toBe("f32,f64\n1.5,1e+21");+ });++ it("emits NaN / +Inf / -Inf as textual float tokens, not empty cells", () => {+ // Regression: prior to this guard, non-finite float64 became "", which+ // is indistinguishable from a NULL cell and silently loses data. Now+ // matches the backend's strconv.FormatFloat tokens.+ const r = create(QueryResultSchema, {+ columnNames: ["nan", "posinf", "neginf"],+ rows: [+ rowOf(+ f64Row(Number.NaN),+ f64Row(Number.POSITIVE_INFINITY),+ f64Row(Number.NEGATIVE_INFINITY)+ ),+ ],+ });+ expect(csv(r)).toBe("nan,posinf,neginf\nNaN,+Inf,-Inf");+ });++ it("emits structpb cells as CSV-quoted JSON (Tier 2)", () => {+ const struct = create(ValueSchema, {+ kind: {+ case: "structValue",+ value: create(StructSchema, {+ fields: {+ a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),+ b: create(ValueSchema, {+ kind: { case: "stringValue", value: "x" },+ }),+ },+ }),+ },+ });+ const r = create(QueryResultSchema, {+ columnNames: ["v"],+ rows: [rowOf(valueRow(struct))],+ });+ // JSON.stringify preserves insertion order; CSV escapes embedded `"` to `""`.+ expect(csv(r)).toBe(`v\n"{""a"":1,""b"":""x""}"`);+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/engines.test.ts b/frontend/src/utils/sql-download/__tests__/engines.test.tsnew file mode 100644index 0000000000..e6ed369097--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/engines.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { SQL_ENGINE_QUOTES } from "../engines";++describe("SQL_ENGINE_QUOTES engine coverage", () => {+ // Mirrors backend SQLStatementPrefix in backend/component/export/sql.go:55-64.+ // serializeSQL throws UnsupportedFormat for any engine not in the map; this+ // truth table catches accidental engine removals.+ it.each([+ Engine.MYSQL,+ Engine.MARIADB,+ Engine.TIDB,+ Engine.OCEANBASE,+ Engine.SPANNER,+ Engine.CLICKHOUSE,+ Engine.MSSQL,+ Engine.ORACLE,+ Engine.POSTGRES,+ Engine.REDSHIFT,+ Engine.SQLITE,+ Engine.SNOWFLAKE,+ ])("supports engine %d", (engine) => {+ expect(SQL_ENGINE_QUOTES.has(engine)).toBe(true);+ });++ it.each([+ Engine.ENGINE_UNSPECIFIED,+ Engine.MONGODB,+ Engine.REDIS,+ Engine.ELASTICSEARCH,+ Engine.DYNAMODB,+ Engine.COSMOSDB,+ Engine.CASSANDRA,+ Engine.STARROCKS,+ Engine.DORIS,+ Engine.HIVE,+ Engine.BIGQUERY,+ Engine.COCKROACHDB,+ Engine.DATABRICKS,+ Engine.TRINO,+ ])("does not support engine %d", (engine) => {+ expect(SQL_ENGINE_QUOTES.has(engine)).toBe(false);+ });+});++describe("SQL_ENGINE_QUOTES", () => {+ it("uses backtick for MySQL family", () => {+ expect(SQL_ENGINE_QUOTES.get(Engine.MYSQL)).toBe("`");+ expect(SQL_ENGINE_QUOTES.get(Engine.MARIADB)).toBe("`");+ expect(SQL_ENGINE_QUOTES.get(Engine.TIDB)).toBe("`");+ });+ it("uses double-quote for Postgres family", () => {+ expect(SQL_ENGINE_QUOTES.get(Engine.POSTGRES)).toBe(`"`);+ expect(SQL_ENGINE_QUOTES.get(Engine.REDSHIFT)).toBe(`"`);+ });+ it("returns undefined for unsupported engine", () => {+ expect(SQL_ENGINE_QUOTES.get(Engine.MONGODB)).toBeUndefined();+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/error-messages.test.ts b/frontend/src/utils/sql-download/__tests__/error-messages.test.tsnew file mode 100644index 0000000000..122d4924fb--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/error-messages.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest";+import { downloadErrorMessage } from "../error-messages";++const t = (key: string) => key;++// Helper: realistic DownloadError shape — an Error instance with a .code+// field. Matches what `downloadError()` from types.ts produces. Plain+// objects without `instanceof Error` fall through to the generic path+// because `isDownloadError` requires both.+const makeDownloadError = (+ code: string,+ message = ""+): Error & { code: string } => Object.assign(new Error(message), { code });++describe("downloadErrorMessage", () => {+ it("maps ResultTooLarge (no message → locale fallback)", () => {+ expect(downloadErrorMessage(makeDownloadError("ResultTooLarge"), t)).toBe(+ "sql-editor.download-too-large"+ );+ });+ it("maps UnsupportedFormat (no message → locale fallback)", () => {+ expect(+ downloadErrorMessage(makeDownloadError("UnsupportedFormat"), t)+ ).toBe("sql-editor.sql-download-unavailable");+ });+ it("falls back to error message", () => {+ expect(downloadErrorMessage(new Error("oops"), t)).toBe("oops");+ });+ it("truncates multi-line errors to the first line", () => {+ expect(+ downloadErrorMessage(new Error("oops\ncause: something\n more"), t)+ ).toBe("oops");+ });+ it("truncates excessively long messages", () => {+ const long = "x".repeat(500);+ const out = downloadErrorMessage(new Error(long), t);+ expect(out.length).toBeLessThanOrEqual(240);+ expect(out.endsWith("…")).toBe(true);+ });+ it("ResultTooLarge surfaces the bytes/cells message from the error", () => {+ const e = makeDownloadError(+ "ResultTooLarge",+ "Result is ~520 MB; client-side limit is 200 MB."+ );+ expect(downloadErrorMessage(e, t)).toContain("520 MB");+ });+ it("UnsupportedFormat surfaces the concrete message (e.g. unsupported SQL engine)", () => {+ // serializeSQL throws UnsupportedFormat with the engine name when the+ // engine isn't in SQL_ENGINE_QUOTES; falling back to the generic+ // "sql-download-unavailable" locale would lose that detail.+ const e = makeDownloadError(+ "UnsupportedFormat",+ "SQL download is not supported for engine MONGODB"+ );+ expect(downloadErrorMessage(e, t)).toContain("MONGODB");+ });+ it("UnsupportedFormat falls back to locale string when no message", () => {+ expect(+ downloadErrorMessage(makeDownloadError("UnsupportedFormat"), t)+ ).toBe("sql-editor.sql-download-unavailable");+ });+ it("falls back to a localized generic when no message", () => {+ // Plain object (not an Error instance) — exercises the non-DownloadError+ // branch.+ expect(downloadErrorMessage({}, t)).toBe("sql-editor.download-failed");+ });+ it("falls back to message extraction for non-DownloadError Error instances", () => {+ // A vanilla Error (no .code field) — isDownloadError returns false,+ // so the generic message branch handles it.+ expect(downloadErrorMessage(new Error("plain"), t)).toBe("plain");+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/filename.test.ts b/frontend/src/utils/sql-download/__tests__/filename.test.tsnew file mode 100644index 0000000000..55c59ca542--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/filename.test.ts@@ -0,0 +1,144 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import {+ FALLBACK_BASENAME,+ MAX_BASENAME_LENGTH,+ sanitizeBasename,+ uniqueFilename,+} from "../filename";++describe("sanitizeBasename (B5 — ZIP filename path traversal)", () => {+ it("returns plain ASCII names unchanged", () => {+ expect(sanitizeBasename("prod-db-2026-05-09")).toBe("prod-db-2026-05-09");+ });++ it("replaces forward slashes with underscores", () => {+ expect(sanitizeBasename("a/b")).toBe("a_b");+ });++ it("replaces backslashes with underscores", () => {+ expect(sanitizeBasename("a\\b")).toBe("a_b");+ });++ it("strips NUL bytes", () => {+ expect(sanitizeBasename("a\x00b")).toBe("ab");+ });++ it("collapses parent-directory hints embedded in the name", () => {+ // `..` and `.` segments inside a basename can still be re-interpreted+ // by some ZIP readers after we strip the slashes.+ expect(sanitizeBasename("..")).toBe(FALLBACK_BASENAME);+ // `../foo` -> slash becomes `_` -> `.._foo` -> dot-run collapses to `._foo`+ // -> leading dots/whitespace trimmed -> `_foo`. Underscore is safe.+ expect(sanitizeBasename("../foo")).toBe("_foo");+ // `foo/..` -> `foo_..` -> `foo_.` -> trimmed trailing dot -> `foo_`.+ expect(sanitizeBasename("foo/..")).toBe("foo_");+ });++ it("trims leading and trailing dots and whitespace", () => {+ expect(sanitizeBasename(" prod ")).toBe("prod");+ expect(sanitizeBasename("...prod")).toBe("prod");+ expect(sanitizeBasename("prod...")).toBe("prod");+ });++ it("truncates names longer than the cap", () => {+ const long = "a".repeat(MAX_BASENAME_LENGTH + 50);+ const out = sanitizeBasename(long);+ expect(out.length).toBe(MAX_BASENAME_LENGTH);+ });++ it("falls back to 'download' when input is empty or only stripped chars", () => {+ expect(sanitizeBasename("")).toBe(FALLBACK_BASENAME);+ expect(sanitizeBasename("\x00\x00")).toBe(FALLBACK_BASENAME);+ expect(sanitizeBasename("///")).toBe("___"); // slashes become underscores, not empty+ expect(sanitizeBasename("....")).toBe(FALLBACK_BASENAME);+ expect(sanitizeBasename(" ")).toBe(FALLBACK_BASENAME);+ });++ it("preserves non-ASCII printable Unicode (databases may carry it)", () => {+ expect(sanitizeBasename("生产-db")).toBe("生产-db");+ });++ it("strips bidi-override / format chars that can spoof archive viewers", () => {+ // U+202E RIGHT-TO-LEFT OVERRIDE could rearrange display: `evil_<RLO>gpj.exe` -> `evil_exe.jpg`.+ expect(sanitizeBasename("evil_gpj.exe")).toBe("evil_gpj.exe");+ // BOM+ expect(sanitizeBasename("prod")).toBe("prod");+ // LRM/RLM+ expect(sanitizeBasename("ab")).toBe("ab");+ // Bidi isolates+ expect(sanitizeBasename("prod")).toBe("prod");+ // U+061C ARABIC LETTER MARK (bidi control older than U+202x)+ expect(sanitizeBasename("ab")).toBe("ab");+ });++ it("does not split a surrogate pair when truncating to the length cap", () => {+ // 199 ASCII chars + 1 emoji (surrogate pair = 2 UTF-16 units) → s.length=201.+ // Slice(0, 200) cuts inside the pair; the high surrogate would be invalid.+ const input = "a".repeat(199) + "😀";+ const out = sanitizeBasename(input);+ expect(out.length).toBe(199); // emoji dropped entirely+ // No lone surrogate left at the tail.+ const last = out.charCodeAt(out.length - 1);+ expect(last >= 0xd800 && last <= 0xdfff).toBe(false);+ });+});++describe("uniqueFilename (B10 — batch ZIP duplicate filenames)", () => {+ it("returns the name unchanged when not yet taken", () => {+ const taken = new Set<string>();+ expect(uniqueFilename("prod.csv", taken)).toBe("prod.csv");+ expect(taken.has("prod.csv")).toBe(true);+ });++ it("appends -1 on first collision, -2 on second", () => {+ const taken = new Set<string>(["prod.csv"]);+ expect(uniqueFilename("prod.csv", taken)).toBe("prod-1.csv");+ expect(uniqueFilename("prod.csv", taken)).toBe("prod-2.csv");+ });++ it("skips past pre-existing suffixed siblings rather than colliding with them", () => {+ // If a customer's batch already had "db" and "db-1" as distinct+ // databases, a third group named "db" must become "db-2" rather than+ // double-collide with the existing literal "db-1" entry.+ const taken = new Set<string>(["db", "db-1"]);+ expect(uniqueFilename("db", taken)).toBe("db-2");+ });++ it("appends suffix at end if no extension", () => {+ const taken = new Set<string>(["batch"]);+ expect(uniqueFilename("batch", taken)).toBe("batch-1");+ });++ it("respects the LAST dot as extension separator", () => {+ const taken = new Set<string>(["a.b.csv"]);+ expect(uniqueFilename("a.b.csv", taken)).toBe("a.b-1.csv");+ });++ it("treats case-only-different names as colliding (Windows extraction)", () => {+ const taken = new Set<string>();+ expect(uniqueFilename("Prod.csv", taken)).toBe("Prod.csv");+ // Same name in different case must dedup.+ expect(uniqueFilename("prod.csv", taken)).toBe("prod-1.csv");+ expect(uniqueFilename("PROD.csv", taken)).toBe("PROD-2.csv");+ });++ it("treats NFC and NFD forms of the same string as colliding", () => {+ const taken = new Set<string>();+ const nfc = "café.csv"; // single code point é (U+00E9)+ const nfd = "café.csv"; // e + combining acute+ expect(uniqueFilename(nfc, taken)).toBe(nfc);+ expect(uniqueFilename(nfd, taken)).toBe("café-1.csv");+ });+ it("appends -N at the end (not before a dot) for path-like inputs", () => {+ // dirPrefix dedup in buildDownloadBlob passes "inst/db" paths. When the+ // database segment legitimately contains a dot (e.g. "prod.app_v2"),+ // treating the dot as an extension boundary would yield "prod-1.app_v2"+ // and mis-label the path. The "/" in the input signals path-mode.+ const taken = new Set<string>(["inst/prod.app_v2"]);+ expect(uniqueFilename("inst/prod.app_v2", taken)).toBe(+ "inst/prod.app_v2-1"+ );+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/formatter-goldens.test.ts b/frontend/src/utils/sql-download/__tests__/formatter-goldens.test.tsnew file mode 100644index 0000000000..7b7d35d62d--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/formatter-goldens.test.ts@@ -0,0 +1,74 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, it } from "vitest";+import {+ RowValue_TimestampSchema,+ RowValue_TimestampTZSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { formatFloat32, formatTimestamp, formatTimestampTZ } from "../value";++const here = dirname(fileURLToPath(import.meta.url));+const formattersDir = resolve(here, "goldens", "formatters");++function readTSV(filename: string): string[][] {+ const text = readFileSync(resolve(formattersDir, filename), "utf-8");+ return text+ .split("\n")+ .map((l) => l.trim())+ .filter((l) => l.length > 0 && !l.startsWith("#"))+ .map((l) => l.split("\t"));+}++function float32FromHex(hex: string): number {+ if (hex.length !== 8) throw new Error(`bad hex ${hex}`);+ const u = Number.parseInt(hex, 16);+ const buf = new ArrayBuffer(4);+ new DataView(buf).setUint32(0, u, false);+ return new DataView(buf).getFloat32(0, false);+}++describe("formatter cross-side goldens", () => {+ it("formatFloat32 matches Go strconv.FormatFloat(_, 'f', -1, 32)", () => {+ for (const [hex, expected] of readTSV("float32.tsv")) {+ const got = formatFloat32(float32FromHex(hex));+ expect(got, `bits=${hex}`).toBe(expected);+ }+ });++ it('formatTimestamp matches Go time.Format("2006-01-02 15:04:05.000000")', () => {+ for (const [secStr, nanosStr, expected] of readTSV("timestamp.tsv")) {+ const ts = create(RowValue_TimestampSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: BigInt(secStr),+ nanos: Number.parseInt(nanosStr, 10),+ }),+ });+ const got = formatTimestamp(ts);+ expect(got, `seconds=${secStr} nanos=${nanosStr}`).toBe(expected);+ }+ });++ it("formatTimestampTZ matches Go time.RFC3339Nano in FixedZone", () => {+ for (const [secStr, nanosStr, zoneRaw, offsetStr, expected] of readTSV(+ "timestamptz.tsv"+ )) {+ const zone = zoneRaw === "-" ? "" : zoneRaw;+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: BigInt(secStr),+ nanos: Number.parseInt(nanosStr, 10),+ }),+ zone,+ offset: Number.parseInt(offsetStr, 10),+ });+ const got = formatTimestampTZ(tz);+ expect(+ got,+ `seconds=${secStr} nanos=${nanosStr} zone=${zoneRaw} offset=${offsetStr}`+ ).toBe(expected);+ }+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/goldens/formatters/float32.tsv b/frontend/src/utils/sql-download/__tests__/goldens/formatters/float32.tsvnew file mode 100644index 0000000000..69d9aa7ad3--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/goldens/formatters/float32.tsv@@ -0,0 +1,18 @@+# float32 shortest round-trip emission. Backend: strconv.FormatFloat(_, 'f', -1, 32).+# Frontend: formatFloat32 in value.ts. Never exponential. Negative zero preserved.+# Format: <ieee754-bits-hex>\t<expected-output>+# Generated from backend Go implementation; both sides must reproduce byte-for-byte.+00000000 0+80000000 -0+3F800000 1+BF800000 -1+3FC00000 1.5+501502F9 10000000000+33D6BF95 0.0000001+4048F5C3 3.14+7F7FFFFF 340282350000000000000000000000000000000+00000001 0.000000000000000000000000000000000000000000001+00800000 0.000000000000000000000000000000000000011754944+3DCCCCCD 0.1+40490FDB 3.1415927+3F4EFA39 0.8085056diff --git a/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamp.tsv b/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamp.tsvnew file mode 100644index 0000000000..d93820c67d--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamp.tsv@@ -0,0 +1,10 @@+# Timestamp emission. Backend: ts.GoogleTimestamp.AsTime().Format("2006-01-02 15:04:05.000000").+# Frontend: formatTimestamp in value.ts. UTC. 4-digit zero-padded year. 6-digit microseconds (sub-microsecond truncated).+# Format: <seconds>\t<nanos>\t<expected-output>+0 0 1970-01-01 00:00:00.000000+-62135596800 0 0001-01-01 00:00:00.000000+1700000000 0 2023-11-14 22:13:20.000000+1700000000 123456789 2023-11-14 22:13:20.123456+1700000000 1 2023-11-14 22:13:20.000000+1700000000 999999999 2023-11-14 22:13:20.999999+253402300799 0 9999-12-31 23:59:59.000000diff --git a/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamptz.tsv b/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamptz.tsvnew file mode 100644index 0000000000..5e2a3a28ce--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/goldens/formatters/timestamptz.tsv@@ -0,0 +1,10 @@+# TimestampTZ emission. Backend: ts.AsTime().In(time.FixedZone(zone, offset)).Format(time.RFC3339Nano).+# Frontend: formatTimestampTZ in value.ts. 4-digit zero-padded year. Variable-precision fractional seconds (trailing zeros trimmed; offset=0 emits "Z" regardless of zone name).+# Format: <seconds>\t<nanos>\t<zone>\t<offset-seconds>\t<expected-output>+# Empty zone column is represented as a single dash literal "-" because TSV treats an empty cell ambiguously.+0 0 UTC 0 1970-01-01T00:00:00Z+1700000000 500000000 JST 32400 2023-11-15T07:13:20.5+09:00+1700000000 0 PDT -25200 2023-11-14T15:13:20-07:00+1700000000 0 +0530 19800 2023-11-15T03:43:20+05:30+1700000000 0 -0330 -12600 2023-11-14T18:43:20-03:30+0 0 - 0 1970-01-01T00:00:00Zdiff --git a/frontend/src/utils/sql-download/__tests__/index.test.ts b/frontend/src/utils/sql-download/__tests__/index.test.tsnew file mode 100644index 0000000000..61de9cf23c--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/index.test.ts@@ -0,0 +1,423 @@+// @vitest-environment node++import { create } from "@bufbuild/protobuf";+import * as zipjs from "@zip.js/zip.js";+import { describe, expect, it } from "vitest";+import { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";+import {+ QueryResultSchema,+ QueryRowSchema,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { buildDownloadBlob } from "../index";+import type { DownloadGroup } from "../types";++const tinyResult = create(QueryResultSchema, {+ columnNames: ["id"],+ columnTypeNames: ["INT"],+ rows: [],+});++const oneStmtGroup = (+ overrides: Partial<DownloadGroup> = {}+): DownloadGroup => ({+ instanceId: "prod-instance",+ databaseName: "demo-db",+ engine: Engine.MYSQL,+ statements: [{ result: tinyResult, statement: "SELECT 1" }],+ ...overrides,+});++async function readZipEntries(blob: Blob, password?: string) {+ const reader = new zipjs.ZipReader(new zipjs.BlobReader(blob), { password });+ const entries = await reader.getEntries();+ await reader.close();+ return entries;+}++async function readEntryText(entry: zipjs.Entry): Promise<string> {+ if (!("getData" in entry) || !entry.getData) {+ throw new Error("expected file entry, got directory");+ }+ return entry.getData(new zipjs.TextWriter());+}++describe("buildDownloadBlob", () => {+ it("rejects empty groups", async () => {+ await expect(+ buildDownloadBlob({+ groups: [],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ })+ ).rejects.toMatchObject({ code: "SerializationFailed" });+ });++ it("rejects groups with zero statements", async () => {+ await expect(+ buildDownloadBlob({+ groups: [+ {+ instanceId: "i",+ databaseName: "d",+ engine: Engine.MYSQL,+ statements: [],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ })+ ).rejects.toMatchObject({ code: "SerializationFailed" });+ });++ it("rejects unsupported format", async () => {+ await expect(+ buildDownloadBlob({+ groups: [oneStmtGroup()],+ format: 99 as ExportFormat,+ baseFilename: "demo",+ })+ ).rejects.toMatchObject({ code: "UnsupportedFormat" });+ });++ describe("single statement (1 group, 1 statement)", () => {+ it("emits ZIP with <instance>/<db>/statement-1.sql and .result.csv", async () => {+ const out = await buildDownloadBlob({+ groups: [oneStmtGroup()],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ });+ expect(out.filename).toBe("demo.zip");+ expect(out.mimeType).toBe("application/zip");+ const entries = await readZipEntries(out.blob);+ expect(entries.map((e) => e.filename).sort()).toEqual([+ "prod-instance/demo-db/statement-1.result.csv",+ "prod-instance/demo-db/statement-1.sql",+ ]);+ });++ it("statement-1.sql contains the SQL text", async () => {+ const out = await buildDownloadBlob({+ groups: [+ oneStmtGroup({+ statements: [+ {+ result: tinyResult,+ statement: "SELECT * FROM users WHERE id = 1",+ },+ ],+ }),+ ],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ });+ const entries = await readZipEntries(out.blob);+ const sqlEntry = entries.find((e) => e.filename.endsWith(".sql"))!;+ const text = await readEntryText(sqlEntry);+ expect(text).toBe("SELECT * FROM users WHERE id = 1");+ });++ it.each([+ [ExportFormat.JSON, "result.json"],+ [ExportFormat.SQL, "result.sql"],+ [ExportFormat.XLSX, "result.xlsx"],+ ])("format %p produces statement-1.%s alongside statement-1.sql", async (format, ext) => {+ const out = await buildDownloadBlob({+ groups: [oneStmtGroup()],+ format,+ baseFilename: "demo",+ });+ const entries = await readZipEntries(out.blob);+ const filenames = entries.map((e) => e.filename).sort();+ expect(filenames).toContain(`prod-instance/demo-db/statement-1.sql`);+ expect(filenames).toContain(`prod-instance/demo-db/statement-1.${ext}`);+ });++ it("encrypts every entry under one password", async () => {+ const out = await buildDownloadBlob({+ groups: [oneStmtGroup()],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ password: "p@ss",+ });+ const entries = await readZipEntries(out.blob, "p@ss");+ expect(entries.every((e) => e.encrypted)).toBe(true);+ });+ });++ describe("multi-statement (1 group, N statements)", () => {+ it("numbers statements 1..N inside the same instance/db dir", async () => {+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: "prod",+ databaseName: "db1",+ engine: Engine.POSTGRES,+ statements: [+ { result: tinyResult, statement: "SELECT 1" },+ { result: tinyResult, statement: "SELECT 2" },+ { result: tinyResult, statement: "SELECT 3" },+ ],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "multi",+ });+ const entries = await readZipEntries(out.blob);+ expect(entries.map((e) => e.filename).sort()).toEqual([+ "prod/db1/statement-1.result.csv",+ "prod/db1/statement-1.sql",+ "prod/db1/statement-2.result.csv",+ "prod/db1/statement-2.sql",+ "prod/db1/statement-3.result.csv",+ "prod/db1/statement-3.sql",+ ]);+ });++ it("each statement-N.sql contains its own SQL text", async () => {+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: "i",+ databaseName: "d",+ engine: Engine.MYSQL,+ statements: [+ { result: tinyResult, statement: "SELECT alpha" },+ { result: tinyResult, statement: "SELECT beta" },+ ],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "x",+ });+ const entries = await readZipEntries(out.blob);+ const sqls = entries+ .filter((e) => e.filename.endsWith(".sql"))+ .sort((a, b) => a.filename.localeCompare(b.filename));+ const t1 = await readEntryText(sqls[0]);+ const t2 = await readEntryText(sqls[1]);+ expect(t1).toBe("SELECT alpha");+ expect(t2).toBe("SELECT beta");+ });+ });++ describe("multi-group (batch — N instances/dbs)", () => {+ it("each group becomes its own <instance>/<db>/ subtree", async () => {+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: "prod",+ databaseName: "db-a",+ engine: Engine.MYSQL,+ statements: [{ result: tinyResult, statement: "SELECT 1" }],+ },+ {+ instanceId: "stage",+ databaseName: "db-b",+ engine: Engine.POSTGRES,+ statements: [+ { result: tinyResult, statement: "SELECT 1" },+ { result: tinyResult, statement: "SELECT 2" },+ ],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "batch",+ });+ const entries = await readZipEntries(out.blob);+ expect(entries.map((e) => e.filename).sort()).toEqual([+ "prod/db-a/statement-1.result.csv",+ "prod/db-a/statement-1.sql",+ "stage/db-b/statement-1.result.csv",+ "stage/db-b/statement-1.sql",+ "stage/db-b/statement-2.result.csv",+ "stage/db-b/statement-2.sql",+ ]);+ });++ it("uses each group's engine for SQL serialization", async () => {+ const result = create(QueryResultSchema, {+ columnNames: ["id"],+ columnTypeNames: ["INT"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "int64Value", value: 42n },+ }),+ ],+ }),+ ],+ });+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: "prod",+ databaseName: "my",+ engine: Engine.MYSQL,+ statements: [{ result, statement: "SELECT 42" }],+ },+ {+ instanceId: "prod",+ databaseName: "pg",+ engine: Engine.POSTGRES,+ statements: [{ result, statement: "SELECT 42" }],+ },+ ],+ format: ExportFormat.SQL,+ baseFilename: "x",+ });+ const entries = await readZipEntries(out.blob);+ const myEntry = entries.find(+ (e) => e.filename === "prod/my/statement-1.result.sql"+ )!;+ const pgEntry = entries.find(+ (e) => e.filename === "prod/pg/statement-1.result.sql"+ )!;+ const myText = await readEntryText(myEntry);+ const pgText = await readEntryText(pgEntry);+ expect(myText).toContain("`<table_name>`"); // MySQL backtick+ expect(pgText).toContain('"<table_name>"'); // Postgres double-quote+ });+ });++ describe("path sanitization", () => {+ it("sanitizes instanceId and databaseName as path segments", async () => {+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: "../../etc",+ databaseName: "passwd\\x00",+ engine: Engine.MYSQL,+ statements: [{ result: tinyResult, statement: "SELECT 1" }],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ });+ const entries = await readZipEntries(out.blob);+ // No leading dot / parent-directory, no slash inside segments.+ for (const e of entries) {+ expect(e.filename).not.toMatch(/^\./);+ expect(e.filename).not.toContain("\\");+ expect(e.filename).not.toContain("\0");+ // exactly two `/` separators (the structure we constructed).+ const slashes = (e.filename.match(/\//g) ?? []).length;+ expect(slashes).toBe(2);+ }+ });++ it("disambiguates cross-group dirPrefixes that sanitize to the same path", async () => {+ // Two distinct (instanceId, databaseName) inputs that both sanitize+ // to "inst_A/db_1". Without dedup, zip.js rejects the second group+ // with `File already exists` and aborts the whole batch.+ const out = await buildDownloadBlob({+ groups: [+ {+ instanceId: "inst/A",+ databaseName: "db/1",+ engine: Engine.MYSQL,+ statements: [{ result: tinyResult, statement: "SELECT 1" }],+ },+ {+ instanceId: "inst\\A",+ databaseName: "db\\1",+ engine: Engine.MYSQL,+ statements: [{ result: tinyResult, statement: "SELECT 1" }],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ });+ const entries = await readZipEntries(out.blob);+ const filenames = entries.map((e) => e.filename).sort();+ // 2 groups × 2 entries (.sql + .result.csv) = 4 entries, all unique.+ expect(filenames).toHaveLength(4);+ expect(new Set(filenames).size).toBe(4);+ // First group keeps the candidate prefix; second gets disambiguated.+ expect(filenames).toContain("inst_A/db_1/statement-1.sql");+ expect(filenames.some((f) => f.startsWith("inst_A/db_1-"))).toBe(true);+ });+ });++ describe("caps", () => {+ it("rejects when total cells across all groups exceeds cap", async () => {+ const wide = create(QueryResultSchema, {+ columnNames: Array.from({ length: 100 }, (_, i) => `c${i}`),+ rows: Array.from({ length: 30_000 }, () =>+ create(QueryRowSchema, { values: [] })+ ),+ });+ // 2 groups × 30k rows × 100 cols = 6M cells > 5M cap.+ await expect(+ buildDownloadBlob({+ groups: [+ {+ instanceId: "i",+ databaseName: "a",+ engine: Engine.MYSQL,+ statements: [{ result: wide, statement: "SELECT" }],+ },+ {+ instanceId: "i",+ databaseName: "b",+ engine: Engine.MYSQL,+ statements: [{ result: wide, statement: "SELECT" }],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ })+ ).rejects.toMatchObject({ code: "ResultTooLarge" });+ });++ it("rejects when total estimated bytes across all groups exceeds cap", async () => {+ const huge = "x".repeat(25 * 1024 * 1024);+ const wideStrings = create(QueryResultSchema, {+ columnNames: Array.from({ length: 10 }, (_, i) => `c${i}`),+ rows: Array.from({ length: 10 }, () =>+ create(QueryRowSchema, {+ values: Array.from({ length: 10 }, () =>+ create(RowValueSchema, {+ kind: { case: "stringValue", value: huge },+ })+ ),+ })+ ),+ });+ await expect(+ buildDownloadBlob({+ groups: [+ {+ instanceId: "i",+ databaseName: "a",+ engine: Engine.MYSQL,+ statements: [{ result: wideStrings, statement: "SELECT" }],+ },+ ],+ format: ExportFormat.CSV,+ baseFilename: "demo",+ })+ ).rejects.toMatchObject({ code: "ResultTooLarge" });+ });+ });++ describe("SQL-engine guard", () => {+ it("propagates UnsupportedFormat from per-group engine", async () => {+ await expect(+ buildDownloadBlob({+ groups: [+ {+ instanceId: "i",+ databaseName: "d",+ engine: Engine.ENGINE_UNSPECIFIED,+ statements: [{ result: tinyResult, statement: "SELECT" }],+ },+ ],+ format: ExportFormat.SQL,+ baseFilename: "demo",+ })+ ).rejects.toMatchObject({ code: "UnsupportedFormat" });+ });+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/json-encoder.test.ts b/frontend/src/utils/sql-download/__tests__/json-encoder.test.tsnew file mode 100644index 0000000000..7f107702bf--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/json-encoder.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { encodeIndentedJSON } from "../formats/json";+import { float32 } from "../value";++// Tier 2 relaxation: the encoder no longer mirrors Go json.MarshalIndent+// (alphabetical key sort, HTML-safe escape, U+2028/2029 escape, throw on+// NaN/Inf). It now uses native JSON.stringify escape rules + JS Object+// insertion order + float32 cells via formatFloat32. The tests below cover+// the new contract.+describe("encodeIndentedJSON", () => {+ it("encodes empty containers", () => {+ expect(encodeIndentedJSON([])).toBe("[]");+ expect(encodeIndentedJSON({})).toBe("{}");+ });++ it("encodes scalars", () => {+ expect(encodeIndentedJSON(null)).toBe("null");+ expect(encodeIndentedJSON(true)).toBe("true");+ expect(encodeIndentedJSON("a")).toBe('"a"');+ expect(encodeIndentedJSON(42)).toBe("42");+ expect(encodeIndentedJSON(1.5)).toBe("1.5");+ });++ it("encodes bigint via .toString() — JSON.stringify can't take bigint natively", () => {+ expect(encodeIndentedJSON(9223372036854775807n)).toBe(+ "9223372036854775807"+ );+ });++ it("indents arrays and nested objects with two spaces", () => {+ expect(encodeIndentedJSON([1, 2])).toBe("[\n 1,\n 2\n]");+ expect(encodeIndentedJSON({ a: 1, b: { c: 2 } })).toBe(+ '{\n "a": 1,\n "b": {\n "c": 2\n }\n}'+ );+ });++ it("preserves object insertion order (NOT alphabetical sort)", () => {+ expect(encodeIndentedJSON({ b: 1, a: 2 })).toBe(+ '{\n "b": 1,\n "a": 2\n}'+ );+ });++ it("emits float64 via JS-native Number.toString (exponential at JS thresholds)", () => {+ expect(encodeIndentedJSON(1e10)).toBe("10000000000");+ expect(encodeIndentedJSON(1e21)).toBe("1e+21");+ expect(encodeIndentedJSON(1e-7)).toBe("1e-7");+ });++ it("emits float32 cells via formatFloat32 (always 'f' verb, byte-equal to backend CSV/SQL/XLSX)", () => {+ expect(encodeIndentedJSON(float32(1.5))).toBe("1.5");+ // MaxFloat32 stays in 'f' verb (no exponential). Backend JSON's encoding/json+ // would emit "3.4028235e+38" for the same value — diverged under Tier 2.+ expect(encodeIndentedJSON(float32(3.4028235e38))).toBe(+ "340282350000000000000000000000000000000"+ );+ });++ it("maps NaN / +Inf / -Inf to null (matches JSON.stringify)", () => {+ expect(encodeIndentedJSON(Number.NaN)).toBe("null");+ expect(encodeIndentedJSON(Number.POSITIVE_INFINITY)).toBe("null");+ expect(encodeIndentedJSON(Number.NEGATIVE_INFINITY)).toBe("null");+ });++ it("delegates string escapes to JSON.stringify — no HTML-safe `<>&` escape", () => {+ expect(encodeIndentedJSON("<a>&")).toBe('"<a>&"');+ expect(encodeIndentedJSON('a"b')).toBe('"a\\"b"');+ expect(encodeIndentedJSON("a\\b")).toBe('"a\\\\b"');+ expect(encodeIndentedJSON("a\x00b")).toBe('"a\\u0000b"');+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/json.test.ts b/frontend/src/utils/sql-download/__tests__/json.test.tsnew file mode 100644index 0000000000..f0da19ded7--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/json.test.ts@@ -0,0 +1,151 @@+import { create } from "@bufbuild/protobuf";+import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, it } from "vitest";+import {+ type QueryResult,+ QueryResultSchema,+ QueryRowSchema,+ type RowValue,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { serializeJSON } from "../formats/json";++const TEXT_DECODER = new TextDecoder("utf-8");++const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });+const intRow = (n: bigint): RowValue =>+ create(RowValueSchema, { kind: { case: "int64Value", value: n } });+const strRow = (s: string): RowValue =>+ create(RowValueSchema, { kind: { case: "stringValue", value: s } });+const f32Row = (n: number): RowValue =>+ create(RowValueSchema, { kind: { case: "floatValue", value: n } });+const f64Row = (n: number): RowValue =>+ create(RowValueSchema, { kind: { case: "doubleValue", value: n } });+const valueRow = (v: Value): RowValue =>+ create(RowValueSchema, { kind: { case: "valueValue", value: v } });++const json = (result: QueryResult): string =>+ TEXT_DECODER.decode(serializeJSON(result));++describe("serializeJSON", () => {+ it("emits [] for an empty result", () => {+ expect(json(create(QueryResultSchema, { columnNames: ["a"] }))).toBe("[]");+ });++ it("emits basic ASCII rows with column-declaration key order", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["id", "name"],+ rows: [rowOf(intRow(1n), strRow("Alice"))],+ });+ expect(json(r)).toBe(`[+ {+ "id": 1,+ "name": "Alice"+ }+]`);+ });++ it("uses JS-native JSON string escapes (no HTML escape)", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["s"],+ rows: [rowOf(strRow(`<a>&\n"`))],+ });+ expect(json(r)).toBe(`[+ {+ "s": "<a>&\\n\\""+ }+]`);+ });++ it("emits float32 via formatFloat32 and float64 via JS native", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["f32", "f64"],+ rows: [rowOf(f32Row(1.5), f64Row(1e-7))],+ });+ expect(json(r)).toBe(`[+ {+ "f32": 1.5,+ "f64": 1e-7+ }+]`);+ });++ it("emits structpb cells as JSON-as-string (Tier 2)", () => {+ const struct = create(ValueSchema, {+ kind: {+ case: "structValue",+ value: create(StructSchema, {+ fields: {+ a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),+ b: create(ValueSchema, {+ kind: { case: "stringValue", value: "x" },+ }),+ },+ }),+ },+ });+ const r = create(QueryResultSchema, {+ columnNames: ["v"],+ rows: [rowOf(valueRow(struct))],+ });+ expect(json(r)).toBe(`[+ {+ "v": "{\\"a\\":1,\\"b\\":\\"x\\"}"+ }+]`);+ });++ it("emits NaN / +Inf / -Inf as null (matches JSON.stringify) for both float32 and float64 cells", () => {+ // Regression: prior to the JSONFloat32 non-finite guard, float32 NaN/Inf+ // cells emitted bare `NaN` / `+Inf` / `-Inf` tokens (formatFloat32 output)+ // which are not valid JSON and would fail downstream parsers.+ const r = create(QueryResultSchema, {+ columnNames: [+ "nan64",+ "posinf64",+ "neginf64",+ "nan32",+ "posinf32",+ "neginf32",+ ],+ rows: [+ rowOf(+ f64Row(Number.NaN),+ f64Row(Number.POSITIVE_INFINITY),+ f64Row(Number.NEGATIVE_INFINITY),+ f32Row(Number.NaN),+ f32Row(Number.POSITIVE_INFINITY),+ f32Row(Number.NEGATIVE_INFINITY)+ ),+ ],+ });+ expect(json(r)).toBe(`[+ {+ "nan64": null,+ "posinf64": null,+ "neginf64": null,+ "nan32": null,+ "posinf32": null,+ "neginf32": null+ }+]`);+ });++ it("emits int64 / uint64 as decimal integer tokens via bigint.toString()", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["i"],+ rows: [+ rowOf(intRow(-9223372036854775808n)),+ rowOf(intRow(9223372036854775807n)),+ ],+ });+ expect(json(r)).toBe(`[+ {+ "i": -9223372036854775808+ },+ {+ "i": 9223372036854775807+ }+]`);+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/sql.test.ts b/frontend/src/utils/sql-download/__tests__/sql.test.tsnew file mode 100644index 0000000000..1ad2b0e4fb--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/sql.test.ts@@ -0,0 +1,91 @@+import { create } from "@bufbuild/protobuf";+import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, it } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import {+ type QueryResult,+ QueryResultSchema,+ QueryRowSchema,+ type RowValue,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { serializeSQL } from "../formats/sql";++const TEXT_DECODER = new TextDecoder("utf-8");++const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });+const intRow = (n: bigint): RowValue =>+ create(RowValueSchema, { kind: { case: "int64Value", value: n } });+const strRow = (s: string): RowValue =>+ create(RowValueSchema, { kind: { case: "stringValue", value: s } });+const valueRow = (v: Value): RowValue =>+ create(RowValueSchema, { kind: { case: "valueValue", value: v } });++const sql = (result: QueryResult, engine: Engine): string =>+ TEXT_DECODER.decode(serializeSQL(result, engine));++describe("serializeSQL", () => {+ it("MySQL uses backtick identifiers and single-quoted string literals with `'` doubled", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["id", "name"],+ rows: [rowOf(intRow(1n), strRow("it's"))],+ });+ expect(sql(r, Engine.MYSQL)).toBe(+ "INSERT INTO `<table_name>` (`id`,`name`) VALUES (1,'it''s');"+ );+ });++ it("Postgres uses double-quote identifiers and pq.QuoteLiteral for strings", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["id", "name"],+ rows: [+ rowOf(intRow(1n), strRow("plain")),+ // Backslash in PG triggers the `E'...'` escape-string syntax.+ rowOf(intRow(2n), strRow("a\\b")),+ ],+ });+ expect(sql(r, Engine.POSTGRES)).toBe(+ `INSERT INTO "<table_name>" ("id","name") VALUES (1,'plain');\nINSERT INTO "<table_name>" ("id","name") VALUES (2, E'a\\\\b');`+ );+ });++ it("structpb cell uses engine-aware SQL string quoting (single-quote, embedded `'` doubled), not CSV-style", () => {+ const struct = create(ValueSchema, {+ kind: {+ case: "structValue",+ value: create(StructSchema, {+ fields: {+ a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),+ b: create(ValueSchema, {+ kind: { case: "stringValue", value: "x" },+ }),+ },+ }),+ },+ });+ const r = create(QueryResultSchema, {+ columnNames: ["v"],+ rows: [rowOf(valueRow(struct))],+ });+ // Postgres: pq.QuoteLiteral wraps in `'...'`. No backslash in payload, so no `E'...'`.+ expect(sql(r, Engine.POSTGRES)).toBe(+ `INSERT INTO "<table_name>" ("v") VALUES ('{"a":1,"b":"x"}');`+ );+ // MySQL: non-PG engines use Go's strconv.Quote-style escape inside the+ // single-quoted literal, which escapes embedded `"` as `\"`. Payload has+ // no `'`, so the only escapes come from the JSON-as-string `"` chars.+ expect(sql(r, Engine.MYSQL)).toBe(+ 'INSERT INTO `<table_name>` (`v`) VALUES (\'{\\"a\\":1,\\"b\\":\\"x\\"}\');'+ );+ });++ it("throws UnsupportedFormat for engines without a quote-character mapping", () => {+ const r = create(QueryResultSchema, {+ columnNames: ["a"],+ rows: [rowOf(intRow(1n))],+ });+ expect(() => serializeSQL(r, Engine.ENGINE_UNSPECIFIED)).toThrow(+ /UnsupportedFormat|engine/i+ );+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/value.test.ts b/frontend/src/utils/sql-download/__tests__/value.test.tsnew file mode 100644index 0000000000..c0a347d9e3--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/value.test.ts@@ -0,0 +1,454 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, it } from "vitest";+import {+ RowValue_TimestampSchema,+ RowValue_TimestampTZSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import {+ formatFloat32,+ formatFloat64,+ formatTimestamp,+ formatTimestampTZ,+ goQuoteInner,+ pqQuoteLiteral,+} from "../value";++describe("formatTimestamp", () => {+ it("formats epoch as midnight UTC with six fractional zeros", () => {+ const ts = create(RowValue_TimestampSchema, {+ googleTimestamp: create(TimestampSchema, { seconds: 0n, nanos: 0 }),+ });+ expect(formatTimestamp(ts)).toBe("1970-01-01 00:00:00.000000");+ });++ it("preserves microseconds and truncates sub-microsecond nanos", () => {+ // 123456789 ns = 123456 us + 789 ns; expect 123456 in output (truncate, not round)+ const ts = create(RowValue_TimestampSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 123456789,+ }),+ });+ expect(formatTimestamp(ts)).toBe("2023-11-14 22:13:20.123456");+ });++ it("emits trailing zeros, not stripped", () => {+ const ts = create(RowValue_TimestampSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 500000000, // exactly 500000 us+ }),+ });+ expect(formatTimestamp(ts)).toBe("2023-11-14 22:13:20.500000");+ });++ it("pads historical years to 4 digits (matches Go's time.Format)", () => {+ // Year 1 AD: Go emits "0001-01-01 00:00:00.000000"; JS's getUTCFullYear()+ // returns 1, which without padding would yield "1-01-01 ...".+ // Unix seconds for 0001-01-01 00:00:00 UTC = -62135596800.+ const tsYear1 = create(RowValue_TimestampSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: -62135596800n,+ nanos: 0,+ }),+ });+ expect(formatTimestamp(tsYear1)).toBe("0001-01-01 00:00:00.000000");+ });+});++describe("formatTimestampTZ", () => {+ it("emits Z for zero offset and integer seconds", () => {+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 0,+ }),+ zone: "UTC",+ offset: 0,+ });+ expect(formatTimestampTZ(tz)).toBe("2023-11-14T22:13:20Z");+ });++ it("strips trailing zero digits from fractional second", () => {+ // 500_000_000 ns → ".5" (not ".500" or ".500000000")+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 500_000_000,+ }),+ zone: "UTC",+ offset: 0,+ });+ expect(formatTimestampTZ(tz)).toBe("2023-11-14T22:13:20.5Z");+ });++ it("preserves all nine digits when none are trailing zeros", () => {+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 123_456_789,+ }),+ zone: "UTC",+ offset: 0,+ });+ expect(formatTimestampTZ(tz)).toBe("2023-11-14T22:13:20.123456789Z");+ });++ it("renders positive offset as +HH:MM", () => {+ // PDT-like: -7 hours from UTC has offset -25200, but test +HH:MM with positive+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 0,+ }),+ zone: "JST",+ offset: 9 * 3600,+ });+ expect(formatTimestampTZ(tz)).toBe("2023-11-15T07:13:20+09:00");+ });++ it("renders negative offset as -HH:MM and shifts wall time", () => {+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: 1700000000n,+ nanos: 0,+ }),+ zone: "PDT",+ offset: -7 * 3600,+ });+ expect(formatTimestampTZ(tz)).toBe("2023-11-14T15:13:20-07:00");+ });++ it("pads historical years to 4 digits (matches Go's RFC3339Nano)", () => {+ const tz = create(RowValue_TimestampTZSchema, {+ googleTimestamp: create(TimestampSchema, {+ seconds: -62135596800n,+ nanos: 0,+ }),+ zone: "UTC",+ offset: 0,+ });+ expect(formatTimestampTZ(tz)).toBe("0001-01-01T00:00:00Z");+ });+});++describe("formatFloat64", () => {+ it.each([+ [0, "0"],+ [-0, "-0"],+ [1.5, "1.5"],+ [1e21, "1000000000000000000000"], // never exponential+ [1e-7, "0.0000001"],+ ])("formats %p as %p (Go strconv 'f' verb, no exponent)", (input, expected) => {+ expect(formatFloat64(input)).toBe(expected);+ });+ // Note: Number.MAX_VALUE is verified via the floats_edges golden in Chunk 3,+ // not in this unit test — the exact 309-digit Go output is fragile to+ // reproduce by hand. Goldens are the source of truth for that case.++ it("emits NaN, +Inf, -Inf strings", () => {+ expect(formatFloat64(Number.NaN)).toBe("NaN");+ expect(formatFloat64(Number.POSITIVE_INFINITY)).toBe("+Inf");+ expect(formatFloat64(Number.NEGATIVE_INFINITY)).toBe("-Inf");+ });+});++describe("formatFloat32", () => {+ it("rounds to float32 first, then prints shortest decimal", () => {+ // Math.fround(1/3) = 0.3333333432674408+ expect(formatFloat32(1 / 3)).toBe("0.33333334");+ });++ it("shares special-value rules with formatFloat64", () => {+ expect(formatFloat32(Number.NaN)).toBe("NaN");+ expect(formatFloat32(Number.POSITIVE_INFINITY)).toBe("+Inf");+ expect(formatFloat32(Number.NEGATIVE_INFINITY)).toBe("-Inf");+ });+});++describe("goQuoteInner (strconv.Quote inner content)", () => {+ it("returns ASCII verbatim", () => {+ expect(goQuoteInner("hello")).toBe("hello");+ });++ it.each([+ [`a"b`, `a\\"b`], // " escaped+ [`a\\b`, `a\\\\b`], // \ escaped+ ["a\nb", "a\\nb"],+ ["a\rb", "a\\rb"],+ ["a\tb", "a\\tb"],+ ["a\bb", "a\\bb"],+ ["a\fb", "a\\fb"],+ ["a\vb", "a\\vb"],+ ["a\x07b", "a\\ab"], // BEL → \a+ ["a\x00b", "a\\x00b"], // NUL → \x00 (lowercase)+ ["a\x1bb", "a\\x1bb"], // ESC → \x1b+ ["a\x7fb", "a\\x7fb"], // DEL → \x7f+ ["a'b", "a'b"], // single quote NOT escaped by strconv.Quote+ ])("escapes %p as %p", (input, expected) => {+ expect(goQuoteInner(input)).toBe(expected);+ });++ it("emits non-printable runes as \\uHHHH (no curly braces)", () => {+ // U+200B ZERO WIDTH SPACE is non-printable per unicode.IsPrint+ expect(goQuoteInner("ab")).toBe("a\\u200bb");+ });++ it("emits non-BMP non-printable runes as \\UHHHHHHHH", () => {+ // U+E0001 (LANGUAGE TAG) is non-printable+ const langTag = String.fromCodePoint(0xe0001);+ expect(goQuoteInner(`a${langTag}b`)).toBe("a\\U000e0001b");+ });++ it("emits printable BMP runes verbatim (CJK, emoji)", () => {+ expect(goQuoteInner("中文")).toBe("中文");+ expect(goQuoteInner("👍")).toBe("👍");+ });++ // B9: explicit non-print categories.+ it("escapes Private-Use Area BMP runes as \\uHHHH", () => {+ expect(goQuoteInner(`a\u{e000}b`)).toBe("a\\ue000b");+ expect(goQuoteInner(`a\u{f8ff}b`)).toBe("a\\uf8ffb");+ });++ it("escapes Supplementary Private-Use runes as \\UHHHHHHHH", () => {+ expect(goQuoteInner(`a${String.fromCodePoint(0xf0000)}b`)).toBe(+ "a\\U000f0000b"+ );+ expect(goQuoteInner(`a${String.fromCodePoint(0x100000)}b`)).toBe(+ "a\\U00100000b"+ );+ });++ it("escapes Zs space-separator runes as \\uHHHH (parity with Go)", () => {+ // Go's unicode.IsPrint returns false for the Zs general category except+ // ASCII space (0x20). Backend escapes these as `\uXXXX`; the client must+ // match or SQL exports diverge for any string with exotic whitespace.+ expect(goQuoteInner("a b")).toBe("a\\u2000b"); // EN QUAD+ expect(goQuoteInner("a b")).toBe("a\\u200ab"); // HAIR SPACE+ expect(goQuoteInner("a b")).toBe("a\\u202fb"); // NARROW NBSP+ expect(goQuoteInner("a b")).toBe("a\\u205fb"); // MEDIUM MATH SPACE+ expect(goQuoteInner("a b")).toBe("a\\u3000b"); // IDEOGRAPHIC SPACE+ expect(goQuoteInner("a b")).toBe("a\\u1680b"); // OGHAM SPACE MARK+ });++ it("emits invalid UTF-8 byte as \\xHH", () => {+ // We can't form an invalid UTF-8 string in JS directly; this test asserts+ // the encoded-bytes path. Skip in JS if no synthetic byte path exists;+ // covered instead via Chunk 2 goldens for all-bytes 0x00..0xFF strings.+ const lone = String.fromCharCode(0xd800); // lone surrogate+ // TextEncoder replaces lone surrogates with U+FFFD; expect REPLACEMENT+ // CHARACTER's UTF-8 encoded escape (E� = printable, so verbatim).+ expect(goQuoteInner(lone)).toBe("�");+ });+});++describe("pqQuoteLiteral", () => {+ it("wraps simple string in single quotes", () => {+ expect(pqQuoteLiteral("hello")).toBe("'hello'");+ });++ it("doubles single quotes inside plain form", () => {+ expect(pqQuoteLiteral("it's")).toBe("'it''s'");+ });++ it("uses E'…' form when a backslash is present and escapes it", () => {+ // Note: Go's pq.QuoteLiteral prepends a space before E' (matches libpq behavior)+ expect(pqQuoteLiteral("a\\b")).toBe(" E'a\\\\b'");+ });++ it("doubles single quotes inside E form too", () => {+ expect(pqQuoteLiteral("it's\\")).toBe(" E'it''s\\\\'");+ });+});++import {+ type RowValue,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import {+ csvCellFromRowValue,+ estimateResultBytes,+ JSONFloat32,+ jsonValueFromRowValue,+ sqlValueFromRowValue,+ xlsxValueFromRowValue,+} from "../value";++const rv = (kind: RowValue["kind"]) => create(RowValueSchema, { kind });++describe("csvCellFromRowValue", () => {+ it("null → empty", () =>+ expect(csvCellFromRowValue(rv({ case: "nullValue", value: 0 }))).toBe(""));+ it("bool true → true", () =>+ expect(csvCellFromRowValue(rv({ case: "boolValue", value: true }))).toBe(+ "true"+ ));+ it("int32 → bare digits", () =>+ expect(csvCellFromRowValue(rv({ case: "int32Value", value: 42 }))).toBe(+ "42"+ ));+ it("int64 → bare digits", () =>+ expect(+ csvCellFromRowValue(+ rv({ case: "int64Value", value: 9223372036854775807n })+ )+ ).toBe("9223372036854775807"));+ it('string → double-quoted with `"` doubled', () =>+ expect(csvCellFromRowValue(rv({ case: "stringValue", value: 'a"b' }))).toBe(+ `"a""b"`+ ));+ it("bytes → quoted lowercase 0x hex", () =>+ expect(+ csvCellFromRowValue(+ rv({ case: "bytesValue", value: new Uint8Array([0x00, 0xff]) })+ )+ ).toBe(`"0x00ff"`));+});++describe("jsonValueFromRowValue", () => {+ it("null → null", () =>+ expect(+ jsonValueFromRowValue(rv({ case: "nullValue", value: 0 }))+ ).toBeNull());+ it("int64 bigint passes through unchanged", () => {+ const out = jsonValueFromRowValue(rv({ case: "int64Value", value: 1n }));+ expect(out).toBe(1n);+ });+ it("string is plain string (encoder will JSON-escape)", () => {+ expect(jsonValueFromRowValue(rv({ case: "stringValue", value: "x" }))).toBe(+ "x"+ );+ });+ it("float32 returns JSONFloat32 instance", () => {+ const out = jsonValueFromRowValue(rv({ case: "floatValue", value: 1.5 }));+ expect(out).toBeInstanceOf(JSONFloat32);+ expect((out as JSONFloat32).value).toBe(Math.fround(1.5));+ });+});++describe("sqlValueFromRowValue", () => {+ it("non-PG string uses goQuote then SQL '' for single quotes", () => {+ expect(+ sqlValueFromRowValue(rv({ case: "stringValue", value: "it's" }), false)+ ).toBe(`'it''s'`);+ });+ it("PG string uses pqQuoteLiteral", () => {+ // Note: pqQuoteLiteral prepends a space before E' (matches Go lib/pq)+ expect(+ sqlValueFromRowValue(rv({ case: "stringValue", value: "a\\b" }), true)+ ).toBe(` E'a\\\\b'`);+ });+ it("null → NULL", () =>+ expect(+ sqlValueFromRowValue(rv({ case: "nullValue", value: 0 }), false)+ ).toBe("NULL"));+ it("bytes → unquoted 0xhex", () =>+ expect(+ sqlValueFromRowValue(+ rv({ case: "bytesValue", value: new Uint8Array([0x00]) }),+ false+ )+ ).toBe("0x00"));+});++describe("xlsxValueFromRowValue", () => {+ it("null → empty string", () =>+ expect(xlsxValueFromRowValue(rv({ case: "nullValue", value: 0 }))).toBe(+ ""+ ));+ it("bytes → base64", () =>+ expect(+ xlsxValueFromRowValue(+ rv({ case: "bytesValue", value: new Uint8Array([0x00, 0xff]) })+ )+ ).toBe("AP8="));+});++describe("estimateResultBytes (cap guard worst-case bounds)", () => {+ // Lazy schema imports inside each test to avoid top-of-file churn — the+ // existing test file mixes imports throughout.+ const loadSchemas = async () => {+ const sql = await import("@/types/proto-es/v1/sql_service_pb");+ const wkt = await import("@bufbuild/protobuf/wkt");+ return { sql, wkt };+ };++ it("MaxFloat64 cells are bounded above the formatted byte length", async () => {+ const { sql } = await loadSchemas();+ // The previous flat 16 const undercounted MaxFloat64 by ~20x: its+ // non-exponential form is ~326 chars. The new APPROX_FLOAT64_BYTES+ // (336) covers that.+ const result = create(sql.QueryResultSchema, {+ columnNames: ["d"],+ rows: [+ { values: [rv({ case: "doubleValue", value: Number.MAX_VALUE })] },+ ],+ });+ const formattedLen = csvCellFromRowValue(+ rv({ case: "doubleValue", value: Number.MAX_VALUE })+ ).length;+ const est = estimateResultBytes(result, Number.MAX_SAFE_INTEGER);+ expect(est).toBeGreaterThan(formattedLen);+ });++ it("hex-encoded bytes are bounded by 2x byteLength + overhead", async () => {+ const { sql } = await loadSchemas();+ const longBytes = new Uint8Array(10000);+ longBytes.fill(0xab);+ // CSV/SQL hex output is 2x byteLength + delimiters; the estimator must+ // bound that. The previous `byteLength + 4` const under-counted.+ const csvLen = csvCellFromRowValue(+ rv({ case: "bytesValue", value: longBytes })+ ).length;+ const result = create(sql.QueryResultSchema, {+ columnNames: ["b"],+ rows: [{ values: [rv({ case: "bytesValue", value: longBytes })] }],+ });+ const est = estimateResultBytes(result, Number.MAX_SAFE_INTEGER);+ expect(est).toBeGreaterThanOrEqual(csvLen);+ });++ it("structpb value_value is bounded by recursive walk, not a flat 1KB", async () => {+ const { sql, wkt } = await loadSchemas();+ // A struct whose single string field is 64KB. The old flat 1024 const+ // under-counted this by ~64x and let a single cell bypass the byte cap.+ const bigString = "x".repeat(64 * 1024);+ const inner = create(wkt.ValueSchema, {+ kind: {+ case: "structValue",+ value: create(wkt.StructSchema, {+ fields: {+ payload: create(wkt.ValueSchema, {+ kind: { case: "stringValue", value: bigString },+ }),+ },+ }),+ },+ });+ const result = create(sql.QueryResultSchema, {+ columnNames: ["v"],+ rows: [{ values: [rv({ case: "valueValue", value: inner })] }],+ });+ const est = estimateResultBytes(result, Number.MAX_SAFE_INTEGER);+ expect(est).toBeGreaterThan(bigString.length);+ });++ it("short-circuits once running total crosses cap", async () => {+ const { sql } = await loadSchemas();+ const rows = [];+ for (let i = 0; i < 1000; i++) {+ rows.push({+ values: [rv({ case: "doubleValue", value: Number.MAX_VALUE })],+ });+ }+ const result = create(sql.QueryResultSchema, { columnNames: ["d"], rows });+ // cap = 1000; with ~336 bytes per doubleValue the loop bails after a few+ // rows. The returned value is the running total when it crossed cap, not+ // the full 1000×336 sum.+ const est = estimateResultBytes(result, 1000);+ expect(est).toBeGreaterThan(1000);+ expect(est).toBeLessThan(336 * 10);+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/xlsx.test.ts b/frontend/src/utils/sql-download/__tests__/xlsx.test.tsnew file mode 100644index 0000000000..531f96fd4c--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/xlsx.test.ts@@ -0,0 +1,125 @@+import { create } from "@bufbuild/protobuf";+import { StructSchema, type Value, ValueSchema } from "@bufbuild/protobuf/wkt";+import ExcelJS from "exceljs";+import { describe, expect, it } from "vitest";+import {+ QueryResultSchema,+ QueryRowSchema,+ type RowValue,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { serializeXLSX } from "../formats/xlsx";++const rowOf = (...values: RowValue[]) => create(QueryRowSchema, { values });+const intRow = (n: bigint): RowValue =>+ create(RowValueSchema, { kind: { case: "int64Value", value: n } });+const strRow = (s: string): RowValue =>+ create(RowValueSchema, { kind: { case: "stringValue", value: s } });+const f64Row = (n: number): RowValue =>+ create(RowValueSchema, { kind: { case: "doubleValue", value: n } });+const valueRow = (v: Value): RowValue =>+ create(RowValueSchema, { kind: { case: "valueValue", value: v } });++async function loadCells(bytes: Uint8Array): Promise<string[][]> {+ const book = new ExcelJS.Workbook();+ const ab = bytes.buffer.slice(+ bytes.byteOffset,+ bytes.byteOffset + bytes.byteLength+ );+ await book.xlsx.load(ab as ArrayBuffer);+ const sheet = book.getWorksheet("Sheet1")!;+ const rows: string[][] = [];+ sheet.eachRow({ includeEmpty: true }, (row) => {+ const cells: string[] = [];+ row.eachCell({ includeEmpty: true }, (cell) => {+ cells.push(cell.value == null ? "" : String(cell.value));+ });+ rows.push(cells);+ });+ return rows;+}++describe("serializeXLSX", () => {+ it("writes a header row plus N data rows with string-typed cells", async () => {+ const r = create(QueryResultSchema, {+ columnNames: ["id", "name"],+ rows: [+ rowOf(intRow(1n), strRow("Alice")),+ rowOf(intRow(2n), strRow("Bob")),+ ],+ });+ expect(await loadCells(await serializeXLSX(r))).toEqual([+ ["id", "name"],+ ["1", "Alice"],+ ["2", "Bob"],+ ]);+ });++ it("emits NaN / +Inf / -Inf as textual float tokens in cell text, not empty cells", async () => {+ // Regression: prior to this guard, non-finite float64 became "", which+ // is indistinguishable from a NULL cell in XLSX. Now matches the+ // backend's strconv.FormatFloat tokens.+ const r = create(QueryResultSchema, {+ columnNames: ["nan", "posinf", "neginf"],+ rows: [+ rowOf(+ f64Row(Number.NaN),+ f64Row(Number.POSITIVE_INFINITY),+ f64Row(Number.NEGATIVE_INFINITY)+ ),+ ],+ });+ expect(await loadCells(await serializeXLSX(r))).toEqual([+ ["nan", "posinf", "neginf"],+ ["NaN", "+Inf", "-Inf"],+ ]);+ });++ it("emits structpb cells as JSON-as-string in the cell text (Tier 2)", async () => {+ const struct = create(ValueSchema, {+ kind: {+ case: "structValue",+ value: create(StructSchema, {+ fields: {+ a: create(ValueSchema, { kind: { case: "numberValue", value: 1 } }),+ b: create(ValueSchema, {+ kind: { case: "stringValue", value: "x" },+ }),+ },+ }),+ },+ });+ const r = create(QueryResultSchema, {+ columnNames: ["v"],+ rows: [rowOf(valueRow(struct))],+ });+ expect(await loadCells(await serializeXLSX(r))).toEqual([+ ["v"],+ [`{"a":1,"b":"x"}`],+ ]);+ });++ it("throws ResultTooLarge when columns exceed 16384", async () => {+ const tooWide = create(QueryResultSchema, {+ columnNames: Array.from({ length: 16385 }, (_, i) => `c${i}`),+ rows: [],+ });+ await expect(serializeXLSX(tooWide)).rejects.toMatchObject({+ code: "ResultTooLarge",+ message: expect.stringContaining("16384"),+ });+ });++ it("throws ResultTooLarge when data rows exceed 1,048,575", async () => {+ // Sparse array — guard rejects on `rows.length` before iteration.+ const sparseRows = new Array(1_048_576) as never[];+ const tooTall = create(QueryResultSchema, {+ columnNames: ["a"],+ rows: sparseRows,+ });+ await expect(serializeXLSX(tooTall)).rejects.toMatchObject({+ code: "ResultTooLarge",+ message: expect.stringMatching(/1,?048,?575/),+ });+ });+});diff --git a/frontend/src/utils/sql-download/__tests__/zip.test.ts b/frontend/src/utils/sql-download/__tests__/zip.test.tsnew file mode 100644index 0000000000..c5c658db9d--- /dev/null+++ b/frontend/src/utils/sql-download/__tests__/zip.test.ts@@ -0,0 +1,32 @@+// @vitest-environment node++import * as zipjs from "@zip.js/zip.js";+import { describe, expect, it } from "vitest";+import { wrapWithMultiEntryZip } from "../zip";++describe("wrapWithMultiEntryZip", () => {+ it("produces an encrypted ZIP whose entry decrypts back to original bytes", async () => {+ const inner = new TextEncoder().encode("hello world");+ const out = await wrapWithMultiEntryZip(+ [{ bytes: inner, filename: "hello.txt" }],+ "secret",+ "outer"+ );+ expect(out.filename).toBe("outer.zip");+ expect(out.mimeType).toBe("application/zip");++ const reader = new zipjs.ZipReader(new zipjs.BlobReader(out.blob), {+ password: "secret",+ });+ const entries = await reader.getEntries();+ expect(entries).toHaveLength(1);+ expect(entries[0].filename).toBe("hello.txt");+ const entry = entries[0];+ if (!("getData" in entry) || !entry.getData) {+ throw new Error("expected file entry, got directory");+ }+ const back = await entry.getData(new zipjs.Uint8ArrayWriter());+ await reader.close();+ expect(new TextDecoder().decode(back)).toBe("hello world");+ });+});diff --git a/frontend/src/utils/sql-download/engines.ts b/frontend/src/utils/sql-download/engines.tsnew file mode 100644index 0000000000..d37a9012e7--- /dev/null+++ b/frontend/src/utils/sql-download/engines.ts@@ -0,0 +1,20 @@+import { Engine } from "@/types/proto-es/v1/common_pb";++/**+ * Mirrors backend SQLStatementPrefix in backend/component/export/sql.go:55-64.+ * Adding an engine here without adding it on the backend will break goldens.+ */+export const SQL_ENGINE_QUOTES: ReadonlyMap<Engine, "`" | '"'> = new Map([+ [Engine.MYSQL, "`"],+ [Engine.MARIADB, "`"],+ [Engine.TIDB, "`"],+ [Engine.OCEANBASE, "`"],+ [Engine.SPANNER, "`"],+ [Engine.CLICKHOUSE, '"'],+ [Engine.MSSQL, '"'],+ [Engine.ORACLE, '"'],+ [Engine.POSTGRES, '"'],+ [Engine.REDSHIFT, '"'],+ [Engine.SQLITE, '"'],+ [Engine.SNOWFLAKE, '"'],+]);diff --git a/frontend/src/utils/sql-download/error-messages.ts b/frontend/src/utils/sql-download/error-messages.tsnew file mode 100644index 0000000000..1a9c2757e9--- /dev/null+++ b/frontend/src/utils/sql-download/error-messages.ts@@ -0,0 +1,43 @@+import { isDownloadError } from "./types";++// Accept any translation function that maps a key (plus optional interpolation+// params) to a string; both Vue i18n's ComposerTranslation and react-i18next's+// TFunction satisfy this. Params are passed straight through to whichever+// engine — naming conventions (`{name}` for Vue, `{{name}}` for react-i18next)+// are handled by the engine itself when the matching locale file is loaded.+type AnyTranslate = (+ key: string,+ params?: Record<string, string | number>+) => string;++export function downloadErrorMessage(error: unknown, t: AnyTranslate): string {+ if (isDownloadError(error)) {+ // If the throw site attached an i18n hint, prefer it: this is the only+ // path that produces translated copy for ResultTooLarge / UnsupportedFormat+ // (those error.message strings carry numeric detail that the bare locale+ // fallback can't reproduce, but the hint key/params let us reconstruct+ // the same sentence localized).+ if (error.i18n) {+ return t(error.i18n.key, error.i18n.params);+ }+ if (error.code === "ResultTooLarge") {+ return error.message || t("sql-editor.download-too-large");+ }+ if (error.code === "UnsupportedFormat") {+ return error.message || t("sql-editor.sql-download-unavailable");+ }+ if (error.code === "EncryptionFailed") {+ return t("sql-editor.download-encryption-failed");+ }+ // SerializationFailed and any future code fall through to the generic+ // message-extraction path below.+ }+ // Truncate multi-line errors (zip.js / exceljs throw deep cause chains).+ // Cap the displayed message at 240 chars INCLUDING the trailing ellipsis.+ const message = (error as Error | null)?.message;+ if (message && message.length > 0) {+ const firstLine = message.split("\n", 1)[0];+ return firstLine.length > 240 ? firstLine.slice(0, 239) + "…" : firstLine;+ }+ return t("sql-editor.download-failed");+}diff --git a/frontend/src/utils/sql-download/filename.ts b/frontend/src/utils/sql-download/filename.tsnew file mode 100644index 0000000000..93a837bd13--- /dev/null+++ b/frontend/src/utils/sql-download/filename.ts@@ -0,0 +1,102 @@+/**+ * Sanitize a user-supplied base filename so it is safe to embed inside a ZIP+ * entry name or used directly as the outer download filename.+ *+ * Threat model: a database name or batch label flows from server-controlled+ * data through the UI into the ZIP we hand the user. A ZIP entry name like+ * `../../etc/passwd` is honored by some unzip implementations; NUL bytes+ * confuse downstream tooling; backslashes are path separators on Windows.+ *+ * Rules (applied in order):+ * 1. Strip NUL bytes (always invalid in filenames).+ * 2. Replace forward and back slashes with `_` so no path components survive.+ * 3. Collapse parent-directory segments (`.`, `..`) since they would still be+ * interpretable after step 2.+ * 4. Trim leading/trailing whitespace and dots (Windows hostility).+ * 5. Truncate to 200 characters — long enough for "<dbname>-YYYYMMDD-HHMMSS"+ * style names, short enough to keep ZIP central directory entries small.+ * 6. Fall back to "download" if the result is empty.+ *+ * Note: this intentionally does NOT validate Windows-reserved device names+ * (CON, PRN, NUL, AUX, COM1..COM9, LPT1..LPT9). Adding `.csv`/`.zip` etc.+ * after sanitization makes them legal again on Windows, and the user-side+ * impact is minor compared to the cost of false positives.+ */+export const FALLBACK_BASENAME = "download";+export const MAX_BASENAME_LENGTH = 200;++export function sanitizeBasename(input: string): string {+ let s = input ?? "";+ // Drop NUL bytes outright.+ s = s.replaceAll("\0", "");+ // Replace path separators (forward and back) with `_`.+ s = s.replace(/[/\\]/g, "_");+ // Strip Unicode bidi-override and other format characters that can spoof+ // displayed filenames in archive viewers (e.g. `evil_<U+202E>gpj.exe`+ // appears as `evil_exe.jpg`). Only strip the known-dangerous set, not all+ // of category Cf — combining marks and joiners are legitimate in non-ASCII+ // identifiers.+ // U+061C: Arabic Letter Mark (bidi control predates U+202x)+ // U+200B-200F: zero-width / LRM/RLM+ // U+202A-202E: bidi embed/override+ // U+2066-2069: bidi isolates+ // U+FEFF: BOM+ s = s.replace(/[\u061C\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g, "");+ // Collapse `..` and `.` segments — after replacing slashes there are no+ // segments, but a literal "..foo" or trailing "." is still treated as a+ // parent-directory hint by some unzip tools. Replace runs of dots with a+ // single dot only inside the body (leading/trailing dots are trimmed+ // separately below).+ s = s.replace(/\.{2,}/g, ".");+ // Trim leading/trailing whitespace and dots.+ s = s.replace(/^[\s.]+|[\s.]+$/g, "");+ if (s.length > MAX_BASENAME_LENGTH) {+ s = s.slice(0, MAX_BASENAME_LENGTH);+ // If the cap split a surrogate pair, drop the trailing high surrogate+ // so we don't return an invalid JS string.+ const last = s.charCodeAt(s.length - 1);+ if (last >= 0xd800 && last <= 0xdbff) {+ s = s.slice(0, -1);+ }+ }+ if (s.length === 0) {+ return FALLBACK_BASENAME;+ }+ return s;+}++/**+ * De-duplicate a filename within a set of already-used names. If `name` is+ * unused, returns it as-is and reserves it. Otherwise appends `-1`, `-2`, ...+ * before the extension (or at the end if no extension) until unused.+ *+ * Intended for ZIP entry names where two database results may share the same+ * baseFilename and we must not silently produce two entries with identical+ * names — readers behavior is unspecified and at least one entry is lost.+ *+ * Comparison is case-insensitive AND Unicode-normalized (NFC) so that+ * `Prod.csv` / `prod.csv` collide on Windows extraction, and `é` (U+00E9)+ * collides with `é` (e + U+0301) on macOS HFS+. Stored set uses the folded+ * form; returned filename preserves the caller's original casing.+ */+export function uniqueFilename(name: string, taken: Set<string>): string {+ const fold = (s: string) => s.normalize("NFC").toLowerCase();+ if (!taken.has(fold(name))) {+ taken.add(fold(name));+ return name;+ }+ // For filenames, suffix `-N` BEFORE the extension (`prod.csv` → `prod-1.csv`).+ // For path-like inputs (containing `/`) the trailing segment isn't a file+ // extension — a database named `prod.app_v2` would otherwise become+ // `prod-1.app_v2`, which mis-labels the path. Suffix at the end instead.+ const dot = name.includes("/") ? -1 : name.lastIndexOf(".");+ const stem = dot > 0 ? name.slice(0, dot) : name;+ const ext = dot > 0 ? name.slice(dot) : "";+ for (let i = 1; ; i++) {+ const candidate = `${stem}-${i}${ext}`;+ if (!taken.has(fold(candidate))) {+ taken.add(fold(candidate));+ return candidate;+ }+ }+}diff --git a/frontend/src/utils/sql-download/formats/csv.ts b/frontend/src/utils/sql-download/formats/csv.tsnew file mode 100644index 0000000000..923b4bb5dc--- /dev/null+++ b/frontend/src/utils/sql-download/formats/csv.ts@@ -0,0 +1,18 @@+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";+import { csvCellFromRowValue } from "../value";++const TEXT_ENCODER = new TextEncoder();++export function serializeCSV(result: QueryResult): Uint8Array {+ // Backend writes columnNames + "\n" UNCONDITIONALLY (csv.go:21-26), then+ // joins data rows with "\n" with no trailing newline. So:+ // zero rows → "header\n"+ // N rows → "header\nr1\nr2\n…\nrN"+ // A naive [header, ...rows].join("\n") produces "header" for zero rows —+ // diverges by one byte. Build header + "\n" + rowJoin instead.+ const header = result.columnNames.join(",");+ const rowLines = result.rows.map((r) =>+ r.values.map(csvCellFromRowValue).join(",")+ );+ return TEXT_ENCODER.encode(`${header}\n${rowLines.join("\n")}`);+}diff --git a/frontend/src/utils/sql-download/formats/json.ts b/frontend/src/utils/sql-download/formats/json.tsnew file mode 100644index 0000000000..3e402fdaff--- /dev/null+++ b/frontend/src/utils/sql-download/formats/json.ts@@ -0,0 +1,72 @@+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";+import {+ formatFloat32,+ JSONFloat32,+ type JSONInput,+ jsonValueFromRowValue,+} from "../value";++const TEXT_ENCODER = new TextEncoder();++/**+ * Encode a JSONInput tree as indented JSON text. Tier-2 relaxed encoder:+ *+ * - String escaping delegates to `JSON.stringify`, inheriting ES2019+ rules+ * (no HTML escape; U+2028/2029 escaped as ` ` / ` `).+ * - Object keys are emitted in insertion order — typically column order+ * from `serializeJSON` below. (Pre-Tier-2 encoder sorted alphabetically+ * to match Go map[string]any iteration.)+ * - float32 cells still emit via `formatFloat32` to preserve cross-side+ * byte-equality (the contract for float32 listed in goldens/formatters/).+ * - float64 / int / string / bool emit via JS-native rules.+ * - bigint (int64 / uint64 from proto) emit via `.toString()` since+ * `JSON.stringify` throws on bigint.+ * - NaN / ±Inf → "null" (mirrors `JSON.stringify` and JSON-spec rejection).+ */+function encode(v: JSONInput, indent: string, prefix: string): string {+ if (v === null) return "null";+ if (typeof v === "boolean") return v ? "true" : "false";+ if (typeof v === "string") return JSON.stringify(v);+ if (typeof v === "bigint") return v.toString();+ if (v instanceof JSONFloat32) {+ // `formatFloat32` emits "NaN" / "+Inf" / "-Inf" for non-finite values —+ // valid output for CSV/SQL/XLSX text cells but NOT valid JSON, so the+ // download would be a parse error. Match the bare-number guard just+ // below and emit `null` instead.+ if (!Number.isFinite(v.value)) return "null";+ return formatFloat32(v.value);+ }+ if (typeof v === "number") {+ if (!Number.isFinite(v)) return "null";+ return String(v);+ }+ if (Array.isArray(v)) {+ if (v.length === 0) return "[]";+ const inner = prefix + indent;+ return `[\n${v.map((x) => inner + encode(x, indent, inner)).join(",\n")}\n${prefix}]`;+ }+ const keys = Object.keys(v);+ if (keys.length === 0) return "{}";+ const inner = prefix + indent;+ return `{\n${keys+ .map((k) => `${inner}${JSON.stringify(k)}: ${encode(v[k], indent, inner)}`)+ .join(",\n")}\n${prefix}}`;+}++export function encodeIndentedJSON(value: JSONInput, indent = " "): string {+ return encode(value, indent, "");+}++export function serializeJSON(result: QueryResult): Uint8Array {+ const records = result.rows.map((r) => {+ // Object.create(null) so a column literally named `__proto__` (legal SQL:+ // `SELECT 1 AS "__proto__"`) becomes an own enumerable property instead+ // of triggering Object.prototype's setter and getting silently dropped.+ const obj = Object.create(null) as { [k: string]: JSONInput };+ for (let i = 0; i < result.columnNames.length; i++) {+ obj[result.columnNames[i]] = jsonValueFromRowValue(r.values[i]);+ }+ return obj;+ });+ return TEXT_ENCODER.encode(encode(records, " ", ""));+}diff --git a/frontend/src/utils/sql-download/formats/sql.ts b/frontend/src/utils/sql-download/formats/sql.tsnew file mode 100644index 0000000000..925748d592--- /dev/null+++ b/frontend/src/utils/sql-download/formats/sql.ts@@ -0,0 +1,40 @@+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";+import { SQL_ENGINE_QUOTES } from "../engines";+import { downloadError } from "../types";+import { isPgLike, sqlValueFromRowValue } from "../value";++const TABLE_PLACEHOLDER = "<table_name>";+const TEXT_ENCODER = new TextEncoder();++function buildPrefix(engine: Engine, columnNames: readonly string[]): string {+ const q = SQL_ENGINE_QUOTES.get(engine);+ if (!q) {+ const engineName = Engine[engine] ?? String(engine);+ throw downloadError(+ "UnsupportedFormat",+ `SQL download is not supported for engine ${engineName}`,+ undefined,+ {+ key: "sql-editor.sql-download-engine-unsupported",+ params: { engine: engineName },+ }+ );+ }+ const cols = columnNames.map((c) => `${q}${c}${q}`).join(",");+ return `INSERT INTO ${q}${TABLE_PLACEHOLDER}${q} (${cols}) VALUES (`;+}++export function serializeSQL(result: QueryResult, engine: Engine): Uint8Array {+ const prefix = buildPrefix(engine, result.columnNames);+ // Resolve engine → PG-like once. Hot inner loop only sees a boolean.+ const isPg = isPgLike(engine);+ const lines: string[] = [];+ for (const r of result.rows) {+ const vals = r.values.map((v) => sqlValueFromRowValue(v, isPg)).join(",");+ lines.push(`${prefix}${vals});`);+ }+ // Backend joins rows with "\n", no trailing newline (sql.go:42-49).+ // Zero rows → empty bytes.+ return TEXT_ENCODER.encode(lines.join("\n"));+}diff --git a/frontend/src/utils/sql-download/formats/xlsx.ts b/frontend/src/utils/sql-download/formats/xlsx.tsnew file mode 100644index 0000000000..5c38ca5fa5--- /dev/null+++ b/frontend/src/utils/sql-download/formats/xlsx.ts@@ -0,0 +1,69 @@+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";+import { downloadError } from "../types";+import { xlsxValueFromRowValue } from "../value";++// Excel / ECMA-376 hard limit: column XFD (16,384). ExcelJS's col-cache+// throws "Out of bounds. Excel supports columns from 1 to 16384" once+// getCell(_, 16385) is invoked.+const EXCEL_MAX_COLUMN = 16384;+// Excel's hard worksheet row limit (2^20). The serializer writes a header in+// row 1 and data in rows 2..N+1, so max data rows = EXCEL_MAX_ROWS - 1.+// Writing past this produces a workbook Excel cannot reliably open.+const EXCEL_MAX_ROWS = 1_048_576;++export async function serializeXLSX(result: QueryResult): Promise<Uint8Array> {+ // Column and row overflows are "result too large for THIS format" — the+ // user can still download CSV/JSON/SQL of the same data, or use Export+ // for a server-streamed flow. ResultTooLarge keeps the message verbatim+ // through downloadErrorMessage so the actual counts reach the user.+ if (result.columnNames.length > EXCEL_MAX_COLUMN) {+ throw downloadError(+ "ResultTooLarge",+ `XLSX cannot exceed ${EXCEL_MAX_COLUMN} columns; got ${result.columnNames.length}. Use Export or a different format.`,+ undefined,+ {+ key: "sql-editor.download-too-large-xlsx-columns",+ params: {+ limit: EXCEL_MAX_COLUMN,+ count: result.columnNames.length,+ },+ }+ );+ }+ if (result.rows.length > EXCEL_MAX_ROWS - 1) {+ throw downloadError(+ "ResultTooLarge",+ `XLSX cannot exceed ${EXCEL_MAX_ROWS - 1} data rows; got ${result.rows.length}. Use Export or a different format.`,+ undefined,+ {+ key: "sql-editor.download-too-large-xlsx-rows",+ params: {+ limit: (EXCEL_MAX_ROWS - 1).toLocaleString(),+ count: result.rows.length.toLocaleString(),+ },+ }+ );+ }+ // ExcelJS ships as CJS. Vite's dep-prebundle exposes only the default+ // export, while Node native ESM exposes both `default` and the named+ // members. Destructure `default` to work in both — without this, the+ // prod Vite build hits `new undefined()` and every XLSX download fails+ // while vitest (which uses Node's resolver, not Vite's prebundle) passes.+ const { default: ExcelJS } = await import("exceljs");+ const book = new ExcelJS.Workbook();+ const sheet = book.addWorksheet("Sheet1");++ // Headers in row 1+ for (let j = 0; j < result.columnNames.length; j++) {+ sheet.getCell(1, j + 1).value = result.columnNames[j];+ }+ // Rows from row 2; every cell stored as text (parity with backend).+ for (let i = 0; i < result.rows.length; i++) {+ const row = result.rows[i];+ for (let j = 0; j < row.values.length; j++) {+ sheet.getCell(i + 2, j + 1).value = xlsxValueFromRowValue(row.values[j]);+ }+ }+ const buf = await book.xlsx.writeBuffer();+ return new Uint8Array(buf as ArrayBuffer);+}diff --git a/frontend/src/utils/sql-download/index.ts b/frontend/src/utils/sql-download/index.tsnew file mode 100644index 0000000000..a695169396--- /dev/null+++ b/frontend/src/utils/sql-download/index.ts@@ -0,0 +1,216 @@+import { ExportFormat } from "@/types/proto-es/v1/common_pb";+import { sanitizeBasename, uniqueFilename } from "./filename";+import { downloadError, isDownloadError } from "./types";+import type { DownloadInput, DownloadOutput } from "./types";+import { estimateResultBytes } from "./value";+import { serializeCSV } from "./formats/csv";+import { serializeJSON } from "./formats/json";+import { serializeSQL } from "./formats/sql";+import { serializeXLSX } from "./formats/xlsx";+import { wrapWithMultiEntryZip } from "./zip";++export type {+ DownloadInput,+ DownloadOutput,+ DownloadGroup,+ DownloadStatement,+ DownloadErrorCode,+ DownloadError,+} from "./types";++const TEXT_ENCODER = new TextEncoder();++const EXTENSIONS: ReadonlyMap<ExportFormat, { ext: string; mime: string }> =+ new Map([+ [ExportFormat.CSV, { ext: "csv", mime: "text/csv" }],+ [ExportFormat.JSON, { ext: "json", mime: "application/json" }],+ [ExportFormat.SQL, { ext: "sql", mime: "application/sql" }],+ [+ ExportFormat.XLSX,+ {+ ext: "xlsx",+ mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ },+ ],+ ]);++/**+ * Two-level soft cap. The cell cap (1) is O(1) and catches "lots of small+ * cells". The byte cap (2) walks RowValues once and short-circuits when the+ * running estimate exceeds the limit, catching "small grid with huge cells"+ * which the cell cap alone misses. Both throw the same error code.+ *+ * The maximumResultRows policy at the query stage already bounds N for typical+ * customers; these caps are a defensive guard against misconfiguration or+ * future policy changes.+ *+ * Caps apply GLOBALLY across every statement in every group, not per-entry.+ */+export const MAX_DOWNLOADABLE_CELLS = 5_000_000;+export const MAX_ESTIMATED_BYTES = 200 * 1024 * 1024; // 200 MB raw cell text++/**+ * Build the download blob — always a ZIP whose internal layout mirrors+ * backend's `exportResultToZip`:+ *+ * <baseFilename>.zip+ * <instanceId>/<databaseName>/statement-1.sql+ * <instanceId>/<databaseName>/statement-1.result.<ext>+ * ...+ *+ * Single SQL editor query → 1 group, 1 statement+ * Multi-statement query → 1 group, N statements+ * Batch (multi-database) → N groups, each with its own statements+ *+ * `instanceId` and `databaseName` are sanitized as path segments (slashes,+ * NULs, bidi-overrides removed) so a malicious database name can't escape+ * the ZIP's intended directory tree.+ */+export async function buildDownloadBlob(+ input: DownloadInput+): Promise<DownloadOutput> {+ if (input.groups.length === 0) {+ throw downloadError(+ "SerializationFailed",+ "buildDownloadBlob called with no groups"+ );+ }++ const meta = EXTENSIONS.get(input.format);+ if (!meta) {+ throw downloadError(+ "UnsupportedFormat",+ `Unsupported format ${input.format}`+ );+ }++ // Cap check across every statement in every group.+ let totalCells = 0;+ let totalEstBytes = 0;+ let totalStmts = 0;+ for (const group of input.groups) {+ for (const stmt of group.statements) {+ totalStmts += 1;+ totalCells += stmt.result.rows.length * stmt.result.columnNames.length;+ if (totalCells > MAX_DOWNLOADABLE_CELLS) {+ throw downloadError(+ "ResultTooLarge",+ `Download has ${totalCells.toLocaleString()} cells across ${totalStmts} statement(s); limit is ${MAX_DOWNLOADABLE_CELLS.toLocaleString()}. Reduce the row count or use Export.`,+ undefined,+ {+ key: "sql-editor.download-too-large-cells",+ params: {+ cells: totalCells.toLocaleString(),+ statements: totalStmts,+ limit: MAX_DOWNLOADABLE_CELLS.toLocaleString(),+ },+ }+ );+ }+ totalEstBytes += estimateResultBytes(+ stmt.result,+ MAX_ESTIMATED_BYTES - totalEstBytes+ );+ if (totalEstBytes > MAX_ESTIMATED_BYTES) {+ const estMB = (totalEstBytes / (1024 * 1024)).toFixed(0);+ const capMB = (MAX_ESTIMATED_BYTES / (1024 * 1024)).toFixed(0);+ throw downloadError(+ "ResultTooLarge",+ `Download is ~${estMB} MB across ${totalStmts} statement(s); limit is ${capMB} MB. Reduce the result size or use Export.`,+ undefined,+ {+ key: "sql-editor.download-too-large-bytes",+ params: {+ megabytes: estMB,+ statements: totalStmts,+ capMb: capMB,+ },+ }+ );+ }+ }+ }++ if (totalStmts === 0) {+ throw downloadError(+ "SerializationFailed",+ "buildDownloadBlob called with groups but no statements"+ );+ }++ // Serialize each statement's result + bundle the original SQL alongside.+ // Path layout: <instanceId>/<databaseName>/statement-N.{sql,result.<ext>}+ //+ // Cross-group dirPrefix collisions can occur after sanitization (e.g.+ // "inst/A" and "inst_A" both sanitize to "inst_A"; macOS HFS+ collapses+ // NFC vs. NFD; Windows extraction is case-insensitive). Run each+ // candidate prefix through `uniqueFilename` so distinct inputs always+ // produce distinct ZIP entries; otherwise zip.js rejects the second+ // group with `File already exists` and the whole batch aborts.+ const entries: Array<{ bytes: Uint8Array; filename: string }> = [];+ const usedPrefixes = new Set<string>();++ for (const group of input.groups) {+ const instSeg = sanitizeBasename(group.instanceId);+ const dbSeg = sanitizeBasename(group.databaseName);+ const dirPrefix = uniqueFilename(`${instSeg}/${dbSeg}`, usedPrefixes);++ for (let i = 0; i < group.statements.length; i++) {+ const stmt = group.statements[i];+ const n = i + 1;++ // SQL statement file — always written, even for non-SQL result formats.+ entries.push({+ bytes: TEXT_ENCODER.encode(stmt.statement),+ filename: `${dirPrefix}/statement-${n}.sql`,+ });++ // Result file — serialize per the chosen export format.+ let resultBytes: Uint8Array;+ try {+ switch (input.format) {+ case ExportFormat.CSV:+ resultBytes = serializeCSV(stmt.result);+ break;+ case ExportFormat.JSON:+ resultBytes = serializeJSON(stmt.result);+ break;+ case ExportFormat.SQL:+ resultBytes = serializeSQL(stmt.result, group.engine);+ break;+ case ExportFormat.XLSX:+ resultBytes = await serializeXLSX(stmt.result);+ break;+ default:+ throw downloadError(+ "UnsupportedFormat",+ `Unsupported format ${input.format}`+ );+ }+ } catch (e) {+ // Rethrow any DownloadError verbatim so its actionable message+ // (e.g. "JSON cannot encode NaN", "XLSX cannot exceed 1,048,575+ // data rows") reaches the user via downloadErrorMessage. Wrapping+ // would replace the message with the generic "Failed to serialize+ // result" string. isDownloadError is the type guard for the union;+ // checking it here avoids drift when DownloadErrorCode grows.+ if (isDownloadError(e)) {+ throw e;+ }+ throw downloadError(+ "SerializationFailed",+ "Failed to serialize result",+ e+ );+ }++ entries.push({+ bytes: resultBytes,+ filename: `${dirPrefix}/statement-${n}.result.${meta.ext}`,+ });+ }+ }++ const safeOuter = sanitizeBasename(input.baseFilename);+ return wrapWithMultiEntryZip(entries, input.password, safeOuter);+}diff --git a/frontend/src/utils/sql-download/types.ts b/frontend/src/utils/sql-download/types.tsnew file mode 100644index 0000000000..e163d3744b--- /dev/null+++ b/frontend/src/utils/sql-download/types.ts@@ -0,0 +1,100 @@+import type { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";++/**+ * One query result paired with the SQL text that produced it. Goes into a+ * group's `statements` array. The `statement` is written to a sibling+ * `.sql` file inside the ZIP so users can see what produced each result.+ */+export interface DownloadStatement {+ result: QueryResult;+ statement: string;+}++/**+ * One (instance, database) target. Becomes a `<instanceId>/<databaseName>/`+ * subdirectory in the output ZIP. Multiple statements under the same group+ * share that subdirectory and are numbered `statement-1`, `statement-2`, ...+ */+export interface DownloadGroup {+ instanceId: string;+ databaseName: string;+ engine: Engine;+ statements: DownloadStatement[];+}++/**+ * Top-level download request.+ *+ * Layout produced (always a ZIP, even for a single statement):+ * <baseFilename>.zip+ * <instanceId>/<databaseName>/statement-1.sql+ * <instanceId>/<databaseName>/statement-1.result.<ext>+ * <instanceId>/<databaseName>/statement-2.sql+ * ...+ *+ * Mirrors backend `exportResultToZip` in `backend/api/v1/sql_service.go`.+ */+export interface DownloadInput {+ groups: DownloadGroup[];+ format: ExportFormat;+ baseFilename: string;+ password?: string;+}++export interface DownloadOutput {+ blob: Blob;+ filename: string;+ mimeType: string;+}++export type DownloadErrorCode =+ | "SerializationFailed"+ | "EncryptionFailed"+ | "UnsupportedFormat"+ | "ResultTooLarge";++/** Translation hint attached to a DownloadError. When present, downloadErrorMessage+ * surfaces `t(i18n.key, i18n.params)` so the user gets locale-aware copy with+ * the runtime numeric details (cell counts, byte limits, engine names) folded+ * in via interpolation. Throw sites still set a plain-English `message` as a+ * developer-readable fallback (used by tests and console errors). */+export interface DownloadErrorI18n {+ key: string;+ params?: Record<string, string | number>;+}++export interface DownloadError extends Error {+ code: DownloadErrorCode;+ cause?: unknown;+ i18n?: DownloadErrorI18n;+}++/** Narrow an unknown thrown value to a DownloadError without enumerating the+ * code union at every catch site — the rethrow ladder in buildDownloadBlob+ * and the message extraction in downloadErrorMessage both want this. Using+ * the union literally elsewhere risks drift when a new code is added here. */+export function isDownloadError(e: unknown): e is DownloadError {+ return (+ e instanceof Error &&+ "code" in e &&+ typeof (e as { code?: unknown }).code === "string"+ );+}++export function downloadError(+ code: DownloadErrorCode,+ message: string,+ cause?: unknown,+ i18n?: DownloadErrorI18n+): DownloadError {+ const err = new Error(message) as DownloadError;+ err.code = code;+ if (cause !== undefined) {+ err.cause = cause;+ }+ if (i18n !== undefined) {+ err.i18n = i18n;+ }+ return err;+}diff --git a/frontend/src/utils/sql-download/value.ts b/frontend/src/utils/sql-download/value.tsnew file mode 100644index 0000000000..2f24deea92--- /dev/null+++ b/frontend/src/utils/sql-download/value.ts@@ -0,0 +1,698 @@+import type { Value as StructpbValue } from "@bufbuild/protobuf/wkt";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type {+ QueryResult,+ RowValue,+ RowValue_Timestamp,+ RowValue_TimestampTZ,+} from "@/types/proto-es/v1/sql_service_pb";++const pad = (n: number, width: number): string =>+ n.toString().padStart(width, "0");++/** Format a Timestamp like Go's "2006-01-02 15:04:05.000000". UTC. Truncates sub-microsecond nanos. */+export function formatTimestamp(ts: RowValue_Timestamp): string {+ const seconds = Number(ts.googleTimestamp?.seconds ?? 0n);+ const nanos = ts.googleTimestamp?.nanos ?? 0;+ const date = new Date(seconds * 1000); // UTC ms+ // Pad years to 4 digits — Go's time.Format("2006-...") emits "0001-01-01"+ // for year 1, while JS's getUTCFullYear() returns 1. Without padding,+ // historical-date exports come out as "1-01-01" and break parity.+ const yyyy = pad(date.getUTCFullYear(), 4);+ const mm = pad(date.getUTCMonth() + 1, 2);+ const dd = pad(date.getUTCDate(), 2);+ const hh = pad(date.getUTCHours(), 2);+ const mi = pad(date.getUTCMinutes(), 2);+ const ss = pad(date.getUTCSeconds(), 2);+ const micros = pad(Math.floor(nanos / 1000), 6);+ return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}.${micros}`;+}++/** Format a TimestampTZ like Go's RFC3339Nano in the proto's FixedZone. */+export function formatTimestampTZ(tz: RowValue_TimestampTZ): string {+ const seconds = Number(tz.googleTimestamp?.seconds ?? 0n);+ const nanos = tz.googleTimestamp?.nanos ?? 0;+ const offset = tz.offset ?? 0; // seconds east of UTC++ // Apply the fixed offset to get wall-clock components in that zone.+ const shifted = new Date((seconds + offset) * 1000);+ // See formatTimestamp — same year-padding rationale (Go's RFC3339Nano+ // produces "0001-01-01T00:00:00Z" for year 1).+ const yyyy = pad(shifted.getUTCFullYear(), 4);+ const mm = pad(shifted.getUTCMonth() + 1, 2);+ const dd = pad(shifted.getUTCDate(), 2);+ const hh = pad(shifted.getUTCHours(), 2);+ const mi = pad(shifted.getUTCMinutes(), 2);+ const ss = pad(shifted.getUTCSeconds(), 2);++ let frac = "";+ if (nanos > 0) {+ const padded = pad(nanos, 9).replace(/0+$/, "");+ frac = padded.length > 0 ? `.${padded}` : "";+ }++ let zoneStr: string;+ if (offset === 0) {+ zoneStr = "Z";+ } else {+ const sign = offset > 0 ? "+" : "-";+ const abs = Math.abs(offset);+ const oh = pad(Math.floor(abs / 3600), 2);+ const om = pad(Math.floor((abs % 3600) / 60), 2);+ zoneStr = `${sign}${oh}:${om}`;+ }++ return `${yyyy}-${mm}-${dd}T${hh}:${mi}:${ss}${frac}${zoneStr}`;+}++/**+ * Convert a number to Go's strconv.FormatFloat(v, 'f', -1, 64) form:+ * shortest round-trip decimal, NEVER exponential, no trailing zeros except+ * "0" / "-0".+ */+export function formatFloat64(v: number): string {+ if (Number.isNaN(v)) return "NaN";+ if (v === Number.POSITIVE_INFINITY) return "+Inf";+ if (v === Number.NEGATIVE_INFINITY) return "-Inf";+ if (Object.is(v, -0)) return "-0";+ if (v === 0) return "0";++ const s = v.toString();+ if (!/[eE]/.test(s)) return s; // already non-exponential++ // Expand "1.234e21" / "1.234e-7" into fixed decimal manually.+ return expandExponential(s);+}++/**+ * Mirrors Go's strconv.FormatFloat(v, 'f', -1, 32): shortest round-trip+ * decimal for float32 precision, never exponential.+ * Uses toPrecision to find the shortest significand that round-trips as+ * float32, then expands exponential notation if needed.+ */+export function formatFloat32(v: number): string {+ if (Number.isNaN(v)) return "NaN";+ if (v === Number.POSITIVE_INFINITY) return "+Inf";+ if (v === Number.NEGATIVE_INFINITY) return "-Inf";+ const f32 = Math.fround(v);+ if (Object.is(f32, -0)) return "-0";+ if (f32 === 0) return "0";+ // Find shortest significant-digit count that round-trips through float32.+ for (let p = 1; p <= 17; p++) {+ const s = f32.toPrecision(p);+ if (Math.fround(Number.parseFloat(s)) === f32) {+ if (/[eE]/.test(s)) return expandExponential(s);+ return s.includes(".") ? s.replace(/\.?0+$/, "") : s;+ }+ }+ return expandExponential(f32.toString());+}++// Hot-path TextEncoder/TextDecoder — `goQuoteInner` runs per SQL string cell,+// so allocating a fresh encoder per call shows up in profiles on wide string+// columns. Both are safe to share (no per-call state).+const TEXT_ENCODER = new TextEncoder();+const FATAL_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });++const HEX = "0123456789abcdef";+const hex2 = (n: number): string => HEX[(n >> 4) & 0xf] + HEX[n & 0xf];+const hex4 = (n: number): string =>+ HEX[(n >> 12) & 0xf] ++ HEX[(n >> 8) & 0xf] ++ HEX[(n >> 4) & 0xf] ++ HEX[n & 0xf];+const hex8 = (n: number): string =>+ hex4((n >>> 16) & 0xffff) + hex4(n & 0xffff);++// Rough port of Go's unicode.IsPrint: letters, marks, numbers, punct, symbol,+// and ASCII space (0x20) only. We use Intl-free heuristics good enough for+// goldens-driven validation; final correctness anchored to byte-equal goldens.+//+// B9: explicitly reject surrogates (Cs) and Private-Use Area (Co) ranges.+// `unicode.IsPrint` rejects all Cc/Cf/Co/Cs/Cn categories. A full lookup+// table would be excessive — we cover the surrogate range and the three+// PUA blocks (BMP + supplementary). New runes that fall outside these+// known-non-print ranges still go through the heuristic; goldens are the+// source of truth for any specific rune we ship into customer output.+function isPrintRune(cp: number): boolean {+ if (cp === 0x20) return true;+ if (cp < 0x20 || cp === 0x7f) return false;+ // Format / control / unassigned ranges deemed non-print:+ if (cp >= 0x80 && cp <= 0xa0) return false;+ if (cp === 0xad) return false; // soft hyphen+ if (cp === 0x200b || cp === 0x200c || cp === 0x200d) return false;+ if (cp === 0x2028 || cp === 0x2029) return false;+ // Go's unicode.IsPrint returns false for the Zs (Space_Separator)+ // general category except ASCII space; matching that ensures SQL+ // exports containing en quads / em spaces / ideographic space round-+ // trip through `\uXXXX` escapes the same as the Go backend would.+ if (cp === 0x1680) return false; // Ogham space mark+ if (cp >= 0x2000 && cp <= 0x200a) return false; // en quad..hair space+ if (cp === 0x202f) return false; // narrow no-break space+ if (cp === 0x205f) return false; // medium mathematical space+ if (cp === 0x3000) return false; // ideographic space+ if (cp === 0xfeff) return false;+ if (cp >= 0xfff0 && cp <= 0xfffc) return false; // specials except U+FFFD (replacement char is printable)+ if (cp === 0xfffe || cp === 0xffff) return false; // BOM and non-char+ // Surrogates (Cs). TextEncoder normalizes lone surrogates to U+FFFD before+ // we ever see one here, but defense in depth is cheap.+ if (cp >= 0xd800 && cp <= 0xdfff) return false;+ // Private-Use Areas (Co):+ if (cp >= 0xe000 && cp <= 0xf8ff) return false; // BMP PUA+ if (cp >= 0xf0000 && cp <= 0xffffd) return false; // Supplementary PUA-A+ if (cp >= 0x100000 && cp <= 0x10fffd) return false; // Supplementary PUA-B+ if (cp >= 0xe0000 && cp <= 0xe007f) return false;+ return true;+}++/**+ * Reproduce the inner contents of Go's strconv.Quote(s):+ * the double-quote-stripped middle of `"…"`. Caller wraps in single quotes+ * and replaces ' with '' for SQL literals.+ *+ * Substrate: encode JS string to UTF-8, decode rune-by-rune; isolated bytes+ * that fail UTF-8 decode become \xHH (matches Go's per-byte behavior).+ */+export function goQuoteInner(s: string): string {+ const bytes = TEXT_ENCODER.encode(s);+ const decoder = FATAL_UTF8_DECODER;+ let out = "";+ let i = 0;+ while (i < bytes.length) {+ // Determine UTF-8 sequence length from leading byte.+ const b = bytes[i];+ let size: number;+ if (b < 0x80) size = 1;+ else if ((b & 0xe0) === 0xc0) size = 2;+ else if ((b & 0xf0) === 0xe0) size = 3;+ else if ((b & 0xf8) === 0xf0) size = 4;+ else size = 1; // invalid leading byte → single+ let rune: number | null = null;+ if (size > 1 && i + size <= bytes.length) {+ try {+ const seg = bytes.subarray(i, i + size);+ const text = decoder.decode(seg);+ if (text.length > 0) {+ rune = text.codePointAt(0)!;+ }+ } catch {+ rune = null;+ }+ } else if (size === 1) {+ rune = b;+ }+ if (rune === null) {+ out += "\\x" + hex2(b);+ i += 1;+ continue;+ }+ out += escapeRune(rune);+ i += size;+ }+ return out;+}++function escapeRune(cp: number): string {+ switch (cp) {+ case 0x07:+ return "\\a";+ case 0x08:+ return "\\b";+ case 0x09:+ return "\\t";+ case 0x0a:+ return "\\n";+ case 0x0b:+ return "\\v";+ case 0x0c:+ return "\\f";+ case 0x0d:+ return "\\r";+ case 0x22:+ return '\\"';+ case 0x5c:+ return "\\\\";+ }+ if (cp < 0x20 || cp === 0x7f) {+ return "\\x" + hex2(cp);+ }+ if (isPrintRune(cp)) {+ return String.fromCodePoint(cp);+ }+ if (cp <= 0xffff) {+ return "\\u" + hex4(cp);+ }+ return "\\U" + hex8(cp);+}++function expandExponential(s: string): string {+ const m = /^(-?)(\d+)(?:\.(\d+))?[eE]([+-]?\d+)$/.exec(s);+ if (!m) {+ // Defensive — should never happen for finite numbers.+ return s;+ }+ const [, sign, intPart, fracPart = "", expPart] = m;+ const exp = Number.parseInt(expPart, 10);+ const digits = intPart + fracPart;+ const decimalPos = intPart.length + exp;++ if (decimalPos <= 0) {+ return (+ `${sign}0.${"0".repeat(-decimalPos)}${digits}`.replace(/0+$/, "") ||+ `${sign}0`+ );+ }+ if (decimalPos >= digits.length) {+ return `${sign}${digits}${"0".repeat(decimalPos - digits.length)}`;+ }+ const left = digits.slice(0, decimalPos);+ const right = digits.slice(decimalPos).replace(/0+$/, "");+ return right.length === 0 ? `${sign}${left}` : `${sign}${left}.${right}`;+}++/**+ * Mirror lib/pq.QuoteLiteral — note the leading space before E' when+ * backslashes are present. This matches Go's pq.QuoteLiteral exactly:+ * https://github.com/lib/pq/blob/v1.11.1/quote.go#L75+ *+ * B12: NUL bytes (\\x00) are preserved literally inside the single quotes+ * for byte-for-byte parity with Go lib/pq. Postgres itself rejects NUL on+ * INSERT, so a customer who imports the resulting SQL will get an error+ * downstream — this is consistent with the backend behavior and the spec+ * accepts it as the contract. We do NOT silently strip or escape NUL here.+ */+export function pqQuoteLiteral(s: string): string {+ if (s.includes("\\")) {+ const escaped = s.replaceAll("\\", "\\\\").replaceAll("'", "''");+ return ` E'${escaped}'`;+ }+ return `'${s.replaceAll("'", "''")}'`;+}++/**+ * Compact JSON encoding of a structpb.Value — the cell-content string used+ * for VARIANT-style columns across every export format under the Tier 2+ * relaxation. Each side emits canonical JSON via JSON.stringify on the+ * unwrapped tree; the cross-side byte-equal contract no longer covers+ * structpb cells (each side picks its language-natural JSON form, which+ * happens to agree for ASCII content and may diverge on HTML-unsafe chars+ * or struct field order).+ * Inf / NaN → null to mirror JSON.stringify and JSON-spec restrictions.+ */+export function structpbValueAsJSON(v: StructpbValue | undefined): string {+ return JSON.stringify(unwrapStructpbValue(v));+}++function unwrapStructpbValue(v: StructpbValue | undefined): unknown {+ if (!v?.kind) return null;+ switch (v.kind.case) {+ case "nullValue":+ return null;+ case "boolValue":+ return v.kind.value;+ case "numberValue": {+ const n = v.kind.value;+ return Number.isFinite(n) ? n : null;+ }+ case "stringValue":+ return v.kind.value;+ case "listValue":+ return v.kind.value.values.map(unwrapStructpbValue);+ case "structValue": {+ // Object.create(null) so a column literally named "__proto__" inside+ // a structpb cell can't pollute the output via Object.prototype.+ const out: Record<string, unknown> = Object.create(null);+ for (const [k, val] of Object.entries(v.kind.value.fields ?? {})) {+ out[k] = unwrapStructpbValue(val);+ }+ return out;+ }+ default:+ return null;+ }+}++/** CSV cell rendering of a structpb value: JSON content surrounded by CSV+ * quotes with embedded quotes doubled. Kept exported for compatibility+ * with the `value.test.ts` import path; previously emitted the bracket+ * "a:1,b:2" form (Tier 1) — now emits JSON-as-string (Tier 2). */+export function csvCellFromStructpbValue(v: StructpbValue | undefined): string {+ return csvQuoteString(structpbValueAsJSON(v));+}++/** XLSX cell rendering of a structpb value: raw JSON string (no CSV quoting,+ * no surrounding quotes). Also used by the JSON encoder as the scalar+ * string value for VARIANT columns. */+export function xlsxStringFromStructpbValue(+ v: StructpbValue | undefined+): string {+ return structpbValueAsJSON(v);+}++const ENGINES_PG_LIKE: ReadonlySet<Engine> = new Set([+ Engine.POSTGRES,+ Engine.REDSHIFT,+]);++const bytesToHex = (b: Uint8Array): string => {+ let s = "";+ for (const byte of b) s += hex2(byte);+ return s;+};++const bytesToBase64 = (b: Uint8Array): string => {+ let s = "";+ for (const byte of b) s += String.fromCharCode(byte);+ return btoa(s);+};++const csvQuoteString = (s: string): string => `"${s.replaceAll('"', '""')}"`;++/** Engine-aware single-quoted SQL literal. PG/Redshift use pq-style; others+ * use Go's strconv.Quote inner with single-quote doubling. Hoist the+ * PG-vs-non-PG branch once per call to avoid repeating the ternary in+ * every type case below. */+export function quoteSqlString(s: string, isPg: boolean): string {+ return isPg+ ? pqQuoteLiteral(s)+ : `'${goQuoteInner(s).replaceAll("'", "''")}'`;+}++export function csvCellFromRowValue(v: RowValue | undefined): string {+ if (!v?.kind) return "";+ switch (v.kind.case) {+ case "nullValue":+ return "";+ case "stringValue":+ return csvQuoteString(v.kind.value);+ case "boolValue":+ return v.kind.value ? "true" : "false";+ case "int32Value":+ return v.kind.value.toString();+ case "int64Value":+ return v.kind.value.toString();+ case "uint32Value":+ return v.kind.value.toString();+ case "uint64Value":+ return v.kind.value.toString();+ case "floatValue":+ return formatFloat32(v.kind.value);+ case "doubleValue": {+ // Tier 2 relaxation: language-natural number emission for CSV/JSON/XLSX+ // float64 when finite. SQL float64 still uses formatFloat64 (engine-+ // literal compat). NaN / ±Inf cannot be expressed as a JS-native number+ // token (`String(NaN)` is "NaN" but `String(Infinity)` is "Infinity",+ // diverging from Go's "+Inf"/"-Inf"), AND emitting "" would lose the+ // distinction between a non-finite value and a NULL cell — so fall+ // through to formatFloat64 for non-finite, which produces the same+ // "NaN" / "+Inf" / "-Inf" tokens as the backend.+ const n = v.kind.value;+ return Number.isFinite(n) ? String(n) : formatFloat64(n);+ }+ case "bytesValue":+ return csvQuoteString("0x" + bytesToHex(v.kind.value));+ case "timestampValue":+ return csvQuoteString(formatTimestamp(v.kind.value));+ case "timestampTzValue":+ return csvQuoteString(formatTimestampTZ(v.kind.value));+ case "valueValue":+ return csvCellFromStructpbValue(v.kind.value);+ default:+ return "";+ }+}++/** What the JSON encoder accepts. `bigint` enables raw int64/uint64 tokens+ * without going through JSON.stringify (which throws on bigint).+ *+ * `JSONFloat32` is a class instance — NOT a plain object with a magic key —+ * so a column literally named "__jsonFloat32" can never collide with the+ * discriminator. The encoder uses `instanceof JSONFloat32` for routing. */+export class JSONFloat32 {+ constructor(public readonly value: number) {}+}+export const float32 = (n: number): JSONFloat32 =>+ new JSONFloat32(Math.fround(n));++export type JSONInput =+ | null+ | boolean+ | number+ | bigint+ | string+ | JSONFloat32+ | JSONInput[]+ | { [key: string]: JSONInput };++/** Map a single proto RowValue to the encoder's input tree directly — no+ * intermediate atom shape, no round-trip. Throws SerializationFailed on+ * NaN/Inf to mirror Go's encoding/json error. */+export function jsonValueFromRowValue(v: RowValue | undefined): JSONInput {+ if (!v?.kind) return null;+ switch (v.kind.case) {+ case "nullValue":+ return null;+ case "stringValue":+ return v.kind.value;+ case "boolValue":+ return v.kind.value;+ case "int32Value":+ return v.kind.value;+ case "uint32Value":+ return v.kind.value;+ case "int64Value":+ return v.kind.value; // bigint+ case "uint64Value":+ return v.kind.value; // bigint+ case "floatValue":+ return float32(v.kind.value);+ case "doubleValue":+ return v.kind.value;+ case "bytesValue":+ return bytesToBase64(v.kind.value);+ case "timestampValue":+ return formatTimestamp(v.kind.value);+ case "timestampTzValue":+ return formatTimestampTZ(v.kind.value);+ case "valueValue":+ return xlsxStringFromStructpbValue(v.kind.value);+ default:+ return null;+ }+}++/** Engine is reduced to a single boolean upstream (in serializeSQL) for the hot loop. */+export function sqlValueFromRowValue(+ v: RowValue | undefined,+ isPg: boolean+): string {+ if (!v?.kind) return "";+ switch (v.kind.case) {+ case "nullValue":+ return "NULL";+ case "stringValue":+ return quoteSqlString(v.kind.value, isPg);+ case "boolValue":+ return v.kind.value ? "true" : "false";+ case "int32Value":+ return v.kind.value.toString();+ case "int64Value":+ return v.kind.value.toString();+ case "uint32Value":+ return v.kind.value.toString();+ case "uint64Value":+ return v.kind.value.toString();+ case "floatValue":+ return formatFloat32(v.kind.value);+ case "doubleValue":+ return formatFloat64(v.kind.value);+ case "bytesValue":+ return "0x" + bytesToHex(v.kind.value);+ case "timestampValue":+ return quoteSqlString(formatTimestamp(v.kind.value), isPg);+ case "timestampTzValue":+ return quoteSqlString(formatTimestampTZ(v.kind.value), isPg);+ case "valueValue":+ // Structpb cells use proper engine-aware SQL string quoting (single-+ // quote literals with embedded `'` doubled, or `pq.QuoteLiteral` for+ // PG/Redshift). Backend currently still emits CSV-style double-quoted+ // strings here (a long-standing quirk noted in HANDOFF.md's "Known+ // SQL identifier / CSV header parity gap"); fixing the backend would+ // also require regenerating its tests and is intentionally deferred.+ // Tier 2 already drops cross-side byte equality for structpb cells,+ // so the frontend gets to be correct on its own.+ return quoteSqlString(structpbValueAsJSON(v.kind.value), isPg);+ default:+ return "";+ }+}++export const isPgLike = (engine: Engine): boolean =>+ ENGINES_PG_LIKE.has(engine);++/**+ * Estimate serialized byte size of `result`'s cells, walking RowValues once+ * without allocating any serialized output. Returns the running total+ * accumulated up to the moment it crosses `cap` (or the full sum if under).+ * Caller compares to the cap to decide whether to bail. Includes column-name+ * overhead so wide-schema-with-no-rows results aren't free.+ *+ * Per-cell upper bound bytes, conservative across CSV / SQL / JSON / XLSX+ * serialization. The estimator must NEVER under-count: the cap exists to+ * prevent browser OOM, so over-estimating is acceptable but under-estimating+ * defeats the guard.+ *+ * string → length * 6 + 4+ * JSON `\u00XX` escape is the worst case: a string of pure+ * control bytes / `<`,`>`,`&` (Go encoding/json escapes+ * these by default) inflates to 6 ASCII bytes per source+ * code unit. UTF-8 expansion alone bounds at 3x; the JSON+ * escape dominates. CSV/SQL/XLSX worst cases stay under 6x.+ * bytes → byteLength * 2 + 4+ * CSV/SQL hex-encode (each byte → two hex chars). JSON and+ * XLSX base64-encode (4/3x). 2x bounds both.+ * float32 → 48+ * Max float32 (3.4e+38) in non-exponential form ≈ 40 chars.+ * float64 → 336+ * MaxFloat64 in non-exponential form ≈ 326 chars (309 integer+ * digits + dot + 17 mantissa digits). The previous flat 16+ * under-counted by 20x on dense float64 columns.+ * int/uint → 24 (covers -9223372036854775808 worst case)+ * bool → 8+ * timestamp→ 64 (RFC3339Nano with sub-second precision + zone)+ * value_value → recursive walk over the structpb tree. The previous+ * flat 1024 const let a single huge nested string/list/struct+ * bypass the cap.+ * null → 4+ */+const APPROX_NULL_BYTES = 4;+const APPROX_BOOL_BYTES = 8;+const APPROX_INT_BYTES = 24;+const APPROX_FLOAT32_BYTES = 48;+const APPROX_FLOAT64_BYTES = 336;+const APPROX_TIMESTAMP_BYTES = 64;+const APPROX_BYTES_OVERHEAD = 4;+const APPROX_STRUCT_OVERHEAD = 16;++export function estimateResultBytes(result: QueryResult, cap: number): number {+ // JSON re-emits every column name per row (`{"col": v, ...}`), and SQL+ // re-emits the INSERT prefix's column list per row. Charging column-name+ // overhead only for the header would let a 5M-row × 1-col × 64-byte+ // result bypass the cap when serialized as JSON/SQL. Pre-compute the+ // per-row column-name cost once and apply it to header + each data row.+ // Column names use the SAME 6x string multiplier as cell strings (see+ // approxCellBytes) — a JSON object key like `"<col>"` can inflate+ // 6x via `<` escaping the same way value strings can.+ let columnOverhead = 0;+ for (const c of result.columnNames) columnOverhead += c.length * 6 + 4;+ let total = columnOverhead;+ for (const r of result.rows) {+ total += columnOverhead;+ for (const v of r.values) {+ total += approxCellBytes(v);+ if (total > cap) return total;+ }+ }+ return total;+}++function approxCellBytes(v: RowValue | undefined): number {+ if (!v?.kind) return APPROX_NULL_BYTES;+ switch (v.kind.case) {+ case "nullValue":+ return APPROX_NULL_BYTES;+ case "boolValue":+ return APPROX_BOOL_BYTES;+ case "int32Value":+ case "int64Value":+ case "uint32Value":+ case "uint64Value":+ return APPROX_INT_BYTES;+ case "floatValue":+ return APPROX_FLOAT32_BYTES;+ case "doubleValue":+ return APPROX_FLOAT64_BYTES;+ case "stringValue":+ return v.kind.value.length * 6 + 4;+ case "bytesValue":+ return v.kind.value.byteLength * 2 + APPROX_BYTES_OVERHEAD;+ case "timestampValue":+ case "timestampTzValue":+ return APPROX_TIMESTAMP_BYTES;+ case "valueValue":+ return approxStructpbBytes(v.kind.value);+ default:+ return APPROX_INT_BYTES;+ }+}++function approxStructpbBytes(v: StructpbValue | undefined): number {+ if (!v?.kind) return APPROX_NULL_BYTES;+ switch (v.kind.case) {+ case "nullValue":+ return APPROX_NULL_BYTES;+ case "boolValue":+ return APPROX_BOOL_BYTES;+ case "numberValue":+ return APPROX_FLOAT64_BYTES;+ case "stringValue":+ return v.kind.value.length * 6 + 4;+ case "listValue": {+ let total = APPROX_STRUCT_OVERHEAD;+ for (const item of v.kind.value.values ?? []) {+ total += approxStructpbBytes(item);+ }+ return total;+ }+ case "structValue": {+ let total = APPROX_STRUCT_OVERHEAD;+ for (const [k, val] of Object.entries(v.kind.value.fields ?? {})) {+ total += k.length * 6 + 4;+ total += approxStructpbBytes(val);+ }+ return total;+ }+ default:+ return APPROX_INT_BYTES;+ }+}++export function xlsxValueFromRowValue(v: RowValue | undefined): string {+ if (!v?.kind) return "";+ switch (v.kind.case) {+ case "nullValue":+ return "";+ case "stringValue":+ return v.kind.value;+ case "boolValue":+ return v.kind.value ? "true" : "false";+ case "int32Value":+ return v.kind.value.toString();+ case "int64Value":+ return v.kind.value.toString();+ case "uint32Value":+ return v.kind.value.toString();+ case "uint64Value":+ return v.kind.value.toString();+ case "floatValue":+ return formatFloat32(v.kind.value);+ case "doubleValue": {+ // See csvCellFromRowValue's doubleValue branch for the rationale.+ // Native String() for finite; formatFloat64 for NaN / ±Inf so we emit+ // textual tokens matching the backend ("NaN" / "+Inf" / "-Inf") instead+ // of "" (which would be indistinguishable from a NULL cell).+ const n = v.kind.value;+ return Number.isFinite(n) ? String(n) : formatFloat64(n);+ }+ case "bytesValue":+ return bytesToBase64(v.kind.value);+ case "timestampValue":+ return formatTimestamp(v.kind.value);+ case "timestampTzValue":+ return formatTimestampTZ(v.kind.value);+ case "valueValue":+ return xlsxStringFromStructpbValue(v.kind.value);+ default:+ return "";+ }+}diff --git a/frontend/src/utils/sql-download/zip.ts b/frontend/src/utils/sql-download/zip.tsnew file mode 100644index 0000000000..cce1be02b8--- /dev/null+++ b/frontend/src/utils/sql-download/zip.ts@@ -0,0 +1,58 @@+import type { DownloadOutput } from "./types";+import { downloadError } from "./types";++// zipjs.configure mutates a process-global; hoist to a single lazy init.+let zipjsConfigured = false;+async function loadZipjs(): Promise<typeof import("@zip.js/zip.js")> {+ const zipjs = await import("@zip.js/zip.js");+ if (!zipjsConfigured) {+ zipjs.configure({ useWebWorkers: false });+ zipjsConfigured = true;+ }+ return zipjs;+}++/**+ * Wrap entries in a single ZIP. When `password` is set, every entry is+ * encrypted with WinZip AES-256 (zip.js default), matching the backend's+ * alexmullins/zip output: extra-field 0x9901, vendor "AE", strength=3,+ * actual-method=deflate.+ *+ * The dynamic import is inside try/catch so a chunk-load failure (slow+ * network, blocked CDN, stale service worker) maps to EncryptionFailed+ * rather than an unrecognized rejection.+ */+export async function wrapWithMultiEntryZip(+ entries: Array<{ bytes: Uint8Array; filename: string }>,+ password: string | undefined,+ outerBaseFilename: string+): Promise<DownloadOutput> {+ try {+ const zipjs = await loadZipjs();+ const writer = new zipjs.ZipWriter(+ new zipjs.BlobWriter("application/zip"),+ {+ ...(password ? { password } : {}),+ keepOrder: true,+ }+ );+ for (const entry of entries) {+ await writer.add(entry.filename, new zipjs.Uint8ArrayReader(entry.bytes));+ }+ const blob = await writer.close();+ return {+ blob,+ filename: `${outerBaseFilename}.zip`,+ mimeType: "application/zip",+ };+ } catch (e) {+ // EncryptionFailed only when a password was actually involved. Other+ // failure modes (dynamic-import failure, duplicate filename rejection,+ // OOM) under an unencrypted ZIP shouldn't surface as encryption errors.+ throw downloadError(+ password ? "EncryptionFailed" : "SerializationFailed",+ "Failed to build download ZIP",+ e+ );+ }+}