From 7e533d7bb9a512c8dbef5b80163aceebcc934775 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 06:38:45 -0300 Subject: [PATCH] feat: Go + Wails backend, phase 1 (SQLite, PostgreSQL) Start replacing the Rust/Tauri backend with Go on Wails v3, keeping the Svelte interface. src-tauri stays until the Go build reaches parity. - main.go: Wails app with a frameless window, embedded dist/ and the version from package.json. - internal/app: one bound method, Service.Invoke, answers the same command names and arguments as the Tauri commands, so api.ts and the dev mock are unchanged. - internal/profiles: reads and writes connections.json in the same folder, and saved passwords in the same credential store entries. - internal/drivers: SQLite (ncruces/go-sqlite3) and PostgreSQL (pgx, binary values decoded as in pg_value.rs), checked against the shared view and DDL fixtures. - src/lib/host.ts replaces the @tauri-apps imports: dialogs, window frame, events, opener. - Update checks only notify for now; the macOS menu is stubbed. - CI: Go tests against PostgreSQL 13 and 17, and a Windows app build. Refs #41 --- .github/workflows/ci.yml | 46 + .gitignore | 1 + bun.lock | 3 + go.mod | 26 + go.sum | 55 + internal/app/app.go | 205 +++ internal/app/commands.go | 206 +++ internal/app/engines.go | 22 + internal/app/service.go | 72 ++ internal/app/updates.go | 75 ++ internal/app/updates_test.go | 23 + internal/apperr/apperr.go | 70 ++ internal/drivers/drivers.go | 112 ++ internal/drivers/drivers_test.go | 23 + internal/drivers/fixtures/fixtures.go | 216 ++++ internal/drivers/postgres/ddl.go | 238 ++++ internal/drivers/postgres/edit.go | 534 ++++++++ internal/drivers/postgres/edit_test.go | 375 ++++++ internal/drivers/postgres/integration_test.go | 617 +++++++++ internal/drivers/postgres/postgres.go | 1103 +++++++++++++++++ internal/drivers/postgres/types.go | 390 ++++++ internal/drivers/postgres/value.go | 988 +++++++++++++++ internal/drivers/postgres/value_test.go | 334 +++++ internal/drivers/sqlite/edit.go | 637 ++++++++++ internal/drivers/sqlite/edit_test.go | 640 ++++++++++ internal/drivers/sqlite/errors.go | 187 +++ internal/drivers/sqlite/sqlite.go | 614 +++++++++ internal/drivers/sqlite/sqlite_test.go | 722 +++++++++++ internal/drivers/sqlite/values.go | 284 +++++ internal/model/model.go | 262 ++++ internal/profiles/profiles.go | 214 ++++ internal/profiles/profiles_test.go | 85 ++ internal/profiles/secrets_other.go | 35 + internal/profiles/secrets_windows.go | 66 + internal/profiles/secrets_windows_test.go | 24 + internal/textcodec/decode.go | 54 + internal/textcodec/decode_test.go | 23 + main.go | 159 +++ package.json | 3 + scripts/dev-app.mjs | 47 + src/App.svelte | 6 +- src/lib/api.ts | 2 +- src/lib/app-menu.ts | 37 +- src/lib/components/ConnectionDialog.svelte | 2 +- src/lib/components/ExportDialog.svelte | 3 +- src/lib/components/OracleClientPicker.svelte | 2 +- src/lib/components/ResultsPanel.svelte | 3 +- src/lib/components/TitleBar.svelte | 11 +- src/lib/dev-mock.ts | 6 +- src/lib/host.ts | 171 +++ src/lib/state/actions.svelte.ts | 2 +- src/lib/state/importer.svelte.ts | 2 +- src/lib/state/transfer.svelte.ts | 3 +- src/lib/state/updates.svelte.ts | 132 +- src/lib/state/window-frame.svelte.ts | 33 +- src/main.ts | 3 +- vite.config.ts | 20 +- 57 files changed, 10025 insertions(+), 203 deletions(-) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/app/app.go create mode 100644 internal/app/commands.go create mode 100644 internal/app/engines.go create mode 100644 internal/app/service.go create mode 100644 internal/app/updates.go create mode 100644 internal/app/updates_test.go create mode 100644 internal/apperr/apperr.go create mode 100644 internal/drivers/drivers.go create mode 100644 internal/drivers/drivers_test.go create mode 100644 internal/drivers/fixtures/fixtures.go create mode 100644 internal/drivers/postgres/ddl.go create mode 100644 internal/drivers/postgres/edit.go create mode 100644 internal/drivers/postgres/edit_test.go create mode 100644 internal/drivers/postgres/integration_test.go create mode 100644 internal/drivers/postgres/postgres.go create mode 100644 internal/drivers/postgres/types.go create mode 100644 internal/drivers/postgres/value.go create mode 100644 internal/drivers/postgres/value_test.go create mode 100644 internal/drivers/sqlite/edit.go create mode 100644 internal/drivers/sqlite/edit_test.go create mode 100644 internal/drivers/sqlite/errors.go create mode 100644 internal/drivers/sqlite/sqlite.go create mode 100644 internal/drivers/sqlite/sqlite_test.go create mode 100644 internal/drivers/sqlite/values.go create mode 100644 internal/model/model.go create mode 100644 internal/profiles/profiles.go create mode 100644 internal/profiles/profiles_test.go create mode 100644 internal/profiles/secrets_other.go create mode 100644 internal/profiles/secrets_windows.go create mode 100644 internal/profiles/secrets_windows_test.go create mode 100644 internal/textcodec/decode.go create mode 100644 internal/textcodec/decode_test.go create mode 100644 main.go create mode 100644 scripts/dev-app.mjs create mode 100644 src/lib/host.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7352a0..eb88306 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,52 @@ jobs: exit 1 fi + go: + name: Go backend (PostgreSQL ${{ matrix.postgres }}) + runs-on: ubuntu-22.04 + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + postgres: ["13", "17"] + services: + postgres: + image: postgres:${{ matrix.postgres }} + env: + POSTGRES_PASSWORD: lowquery + ports: ["5432:5432"] + options: >- + --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10 + env: + LQ_PG_HOST: localhost + LQ_PG_PORT: "5432" + LQ_PG_USER: postgres + LQ_PG_PASSWORD: lowquery + LQ_PG_DB: postgres + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Formatting + run: test -z "$(gofmt -l internal main.go)" + - run: go vet ./internal/... + - name: Unit and integration tests + run: go test -count=1 ./internal/... + + go-app: + name: Go app build (Windows) + runs-on: windows-2022 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - run: bun install --frozen-lockfile + - run: bun run build:app + lint: name: Rust format and lint runs-on: ubuntu-22.04 diff --git a/.gitignore b/.gitignore index d5d023e..07ba6d2 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,7 @@ bun-debug.log* # --- Vite --- /dist /build +/bin vite.config.js.timestamp-* vite.config.ts.timestamp-* .vite/ diff --git a/bun.lock b/bun.lock index ba2383c..e8939bf 100644 --- a/bun.lock +++ b/bun.lock @@ -22,6 +22,7 @@ "@tauri-apps/plugin-opener": "^2.7.2", "@tauri-apps/plugin-process": "^2.4.0", "@tauri-apps/plugin-updater": "^2.14.0", + "@wailsio/runtime": "3.1.0", "codemirror": "^6.0.2", }, "devDependencies": { @@ -179,6 +180,8 @@ "@types/node": ["@types/node@26.6.5", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg=="], + "@wailsio/runtime": ["@wailsio/runtime@3.1.0", "", {}, "sha512-noEAedvRyO8TLCrqhGwzrp+mbMxAIDa2rYmdJQOzvJV9MxgaZeXAJGNBiMiKMTSSy4ESOtQi4VH/5heSzi6ZmA=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], "aria-query": ["aria-query@5.3.1", "", {}, "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g=="], diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f4699ec --- /dev/null +++ b/go.mod @@ -0,0 +1,26 @@ +module github.com/LowBloat/LowQuery + +go 1.26.4 + +require ( + github.com/danieljoos/wincred v1.2.3 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.13.0 + github.com/ncruces/go-sqlite3 v0.38.2 + github.com/wailsapp/wails/v3 v3.1.0 + github.com/zalando/go-keyring v0.2.8 + golang.org/x/sys v0.50.0 +) + +require ( + github.com/coder/websocket v1.8.14 // indirect + github.com/ebitengine/purego v0.11.1 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/godbus/dbus/v5 v5.2.2 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/ncruces/go-sqlite3-wasm/v6 v6.7.35401 // indirect + github.com/ncruces/julianday v1.0.0 // indirect + golang.org/x/term v0.46.0 // indirect + golang.org/x/text v0.44.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b41f206 --- /dev/null +++ b/go.sum @@ -0,0 +1,55 @@ +github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= +github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= +github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= +github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= +github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= +github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/ncruces/go-sqlite3 v0.38.2 h1:jYcxFaXfFCNE2PAnRzVEccmn5HvC4cZwy04RGnkJy7E= +github.com/ncruces/go-sqlite3 v0.38.2/go.mod h1:qPQrrHbHYP7FQsgp9rAD0xr14DCDOXZwk8jeU6Y+dUg= +github.com/ncruces/go-sqlite3-wasm/v6 v6.7.35401 h1:BlrYMg6wi+S0oxZ8IeGMHXi2nfjK+06KLQ3w85bqxOM= +github.com/ncruces/go-sqlite3-wasm/v6 v6.7.35401/go.mod h1:K/Z0eKUURoWW9cJ9rHeMGDF0G4pr0A6WizdC+Ohzj54= +github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M= +github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/wailsapp/wails/v3 v3.1.0 h1:ld0AXSicXiTTsIvmTq3qNn9FzCP8vIHRSJdkRLgaAo8= +github.com/wailsapp/wails/v3 v3.1.0/go.mod h1:tzDY3W1jzN3ksSqfGalTt7K3PwnGfIqtl+IgIXlXz0I= +github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= +github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 0000000..48ef9e2 --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,205 @@ +// Package app is the backend the interface talks to: the session registry, +// password resolution and one handler per command the interface sends +// (src/lib/api.ts). Commands keep the names and named arguments of the Tauri +// commands they replace, so the interface code stays the same. +package app + +import ( + "context" + "strings" + "sync" + + "github.com/google/uuid" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/profiles" +) + +type App struct { + version string + profiles *profiles.Store + window Window + + mu sync.RWMutex + sessions map[string]drivers.Session +} + +// Window is what the backend needs from the main window. +type Window interface { + // Painted is called once the page has painted and whenever the theme + // changes, with the page background as #rrggbb. + Painted(background string) +} + +func New(version string, store *profiles.Store) *App { + return &App{ + version: version, + profiles: store, + sessions: map[string]drivers.Session{}, + } +} + +// SetWindow connects the main window once it exists. +func (a *App) SetWindow(w Window) { a.window = w } + +func (a *App) session(id string) (drivers.Session, error) { + a.mu.RLock() + defer a.mu.RUnlock() + s, ok := a.sessions[id] + if !ok { + return nil, apperr.New(apperr.NotFound, "Session closed. Connect again.") + } + return s, nil +} + +// CloseAll closes every open session (on exit). +func (a *App) CloseAll() { + a.mu.Lock() + all := a.sessions + a.sessions = map[string]drivers.Session{} + a.mu.Unlock() + for _, s := range all { + _ = s.Close() + } +} + +var authFailureCodes = map[string]bool{ + "28P01": true, "28000": true, "ORA-01017": true, "ORA-01005": true, + "1045 (28000)": true, "1044 (42000)": true, "1698 (28000)": true, + "NOAUTH": true, "WRONGPASS": true, "AuthenticationError": true, +} + +func isAuthFailure(e *apperr.Error) bool { + return authFailureCodes[e.Code] || + strings.HasPrefix(e.Code, "Msg 18456,") || + strings.Contains(e.Message, "password") +} + +// openWithPassword resolves the password: the one provided now, the one in +// the credential store, or none (trust authentication, for example). Asks +// for it when the user chose not to save it. +func openWithPassword(ctx context.Context, profile model.ConnectionProfile, password *string) (drivers.Session, error) { + // SQLite files and Windows-authenticated SQL Server need no password. + if profile.Engine == model.SQLite || (profile.Engine == model.SQLServer && profile.WindowsAuth) { + return openSession(ctx, profile, nil) + } + provided := password != nil + if password == nil { + password, _ = profiles.StoredPassword(profile.ID) + } + if password == nil && !profile.SavePassword { + return nil, apperr.New(apperr.PasswordRequired, "Enter the password.") + } + hadPassword := password != nil + s, err := openSession(ctx, profile, password) + if err != nil && !provided { + if e := apperr.From(err); isAuthFailure(e) { + msg := "Enter the password." + if hadPassword { + msg = "The saved password was rejected." + } + out := apperr.New(apperr.PasswordRequired, msg) + out.Detail = e.Error() + return nil, out + } + } + return s, err +} + +func (a *App) testConnection(ctx context.Context, profile model.ConnectionProfile, password *string) (model.ServerInfo, error) { + s, err := openWithPassword(ctx, profile, password) + if err != nil { + return model.ServerInfo{}, err + } + defer s.Close() + return model.ServerInfo{ServerVersion: s.ServerVersion()}, nil +} + +func (a *App) openSession(ctx context.Context, profileID string, password *string) (model.SessionInfo, error) { + profile, err := a.profiles.Get(profileID) + if err != nil { + return model.SessionInfo{}, err + } + s, err := openWithPassword(ctx, profile, password) + if err != nil { + return model.SessionInfo{}, err + } + // A password typed at connect time is kept when the profile saves + // passwords, so the next connection does not ask again. + if password != nil && profile.SavePassword { + _ = profiles.RememberPassword(profile.ID, *password) + } + id := uuid.NewString() + info := model.SessionInfo{ + SessionID: id, + ProfileID: profileID, + Engine: s.Engine(), + ServerVersion: s.ServerVersion(), + CurrentUser: s.CurrentUser(), + CurrentSchema: s.CurrentSchema(), + Autocommit: s.TxState().Autocommit, + } + a.mu.Lock() + a.sessions[id] = s + a.mu.Unlock() + return info, nil +} + +func (a *App) closeSession(id string) { + a.mu.Lock() + s, ok := a.sessions[id] + delete(a.sessions, id) + a.mu.Unlock() + if ok { + // A running statement keeps the driver busy; close once it returns. + go s.Close() + } +} + +func (a *App) execute(ctx context.Context, sessionID string, req model.ExecRequest) (*model.ExecResult, error) { + s, err := a.session(sessionID) + if err != nil { + return nil, err + } + if strings.TrimSpace(req.SQL) == "" { + return nil, apperr.New(apperr.Invalid, "Nothing to execute.") + } + r, err := s.Execute(ctx, req) + if err != nil { + return nil, err + } + r.Normalize() + return r, nil +} + +func (a *App) applyChanges(ctx context.Context, sessionID string, req model.ApplyRequest) (*model.ApplyResult, error) { + s, err := a.session(sessionID) + if err != nil { + return nil, err + } + if len(req.Changes) == 0 { + return &model.ApplyResult{InTransaction: s.TxState().InTransaction}, nil + } + if len(req.Target.Key) == 0 { + return nil, apperr.New(apperr.Invalid, "This result has no key to identify its rows.") + } + return s.ApplyChanges(ctx, req) +} + +func (a *App) objectDDL(ctx context.Context, sessionID, schema, name, kind string) (string, error) { + s, err := a.session(sessionID) + if err != nil { + return "", err + } + ddl, err := s.ObjectDDL(ctx, schema, name, kind) + if err != nil { + return "", err + } + if strings.TrimSpace(ddl) == "" { + return "", apperr.Newf(apperr.NotFound, + "The database returned no definition for %s. It may be encrypted, or this user may lack the privilege to read it.", name) + } + return ddl, nil +} diff --git a/internal/app/commands.go b/internal/app/commands.go new file mode 100644 index 0000000..2d38229 --- /dev/null +++ b/internal/app/commands.go @@ -0,0 +1,206 @@ +package app + +import ( + "context" + "encoding/json" + "os" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/textcodec" +) + +type handler func(ctx context.Context, args json.RawMessage) (any, error) + +// command adapts a typed function to a handler: args holds the named +// arguments the interface sends, decoded into A. +func command[A any, R any](f func(ctx context.Context, a A) (R, error)) handler { + return func(ctx context.Context, raw json.RawMessage) (any, error) { + var args A + if len(raw) > 0 && string(raw) != "null" { + if err := json.Unmarshal(raw, &args); err != nil { + return nil, apperr.Invalidf("Invalid arguments: %v", err) + } + } + return f(ctx, args) + } +} + +type none struct{} + +type sessionArgs struct { + SessionID string `json:"sessionId"` +} + +func (a *App) commands() map[string]handler { + return map[string]handler{ + "list_profiles": command(func(ctx context.Context, _ none) ([]model.ConnectionProfile, error) { + return a.profiles.List() + }), + "save_profile": command(func(ctx context.Context, p struct { + Profile model.ConnectionProfile `json:"profile"` + Password *string `json:"password"` + }) (model.ConnectionProfile, error) { + return a.profiles.Save(p.Profile, p.Password) + }), + "delete_profile": command(func(ctx context.Context, p struct { + ID string `json:"id"` + }) (any, error) { + return nil, a.profiles.Delete(p.ID) + }), + "test_connection": command(func(ctx context.Context, p struct { + Profile model.ConnectionProfile `json:"profile"` + Password *string `json:"password"` + }) (model.ServerInfo, error) { + return a.testConnection(ctx, p.Profile, p.Password) + }), + "open_session": command(func(ctx context.Context, p struct { + ProfileID string `json:"profileId"` + Password *string `json:"password"` + }) (model.SessionInfo, error) { + return a.openSession(ctx, p.ProfileID, p.Password) + }), + "close_session": command(func(ctx context.Context, p sessionArgs) (any, error) { + a.closeSession(p.SessionID) + return nil, nil + }), + "execute": command(func(ctx context.Context, p struct { + SessionID string `json:"sessionId"` + Request model.ExecRequest `json:"request"` + }) (*model.ExecResult, error) { + return a.execute(ctx, p.SessionID, p.Request) + }), + "apply_changes": command(func(ctx context.Context, p struct { + SessionID string `json:"sessionId"` + Request model.ApplyRequest `json:"request"` + }) (*model.ApplyResult, error) { + return a.applyChanges(ctx, p.SessionID, p.Request) + }), + "cancel_query": command(func(ctx context.Context, p sessionArgs) (any, error) { + s, err := a.session(p.SessionID) + if err != nil { + return nil, err + } + return nil, s.Cancel(ctx) + }), + "set_autocommit": command(func(ctx context.Context, p struct { + SessionID string `json:"sessionId"` + On bool `json:"on"` + }) (model.TxState, error) { + s, err := a.session(p.SessionID) + if err != nil { + return model.TxState{}, err + } + return s.SetAutocommit(ctx, p.On) + }), + "commit": command(func(ctx context.Context, p sessionArgs) (model.TxState, error) { + s, err := a.session(p.SessionID) + if err != nil { + return model.TxState{}, err + } + return s.EndTransaction(ctx, true) + }), + "rollback": command(func(ctx context.Context, p sessionArgs) (model.TxState, error) { + s, err := a.session(p.SessionID) + if err != nil { + return model.TxState{}, err + } + return s.EndTransaction(ctx, false) + }), + "list_schemas": command(func(ctx context.Context, p sessionArgs) ([]string, error) { + s, err := a.session(p.SessionID) + if err != nil { + return nil, err + } + return nonNil(s.ListSchemas(ctx)) + }), + "list_objects": command(func(ctx context.Context, p struct { + SessionID string `json:"sessionId"` + Schema string `json:"schema"` + }) ([]model.DbObject, error) { + s, err := a.session(p.SessionID) + if err != nil { + return nil, err + } + return nonNil(s.ListObjects(ctx, p.Schema)) + }), + "list_columns": command(func(ctx context.Context, p struct { + SessionID string `json:"sessionId"` + Schema string `json:"schema"` + Table string `json:"table"` + }) ([]model.DbColumn, error) { + s, err := a.session(p.SessionID) + if err != nil { + return nil, err + } + return nonNil(s.ListColumns(ctx, p.Schema, p.Table)) + }), + "object_ddl": command(func(ctx context.Context, p struct { + SessionID string `json:"sessionId"` + Schema string `json:"schema"` + Name string `json:"name"` + Kind string `json:"kind"` + }) (string, error) { + return a.objectDDL(ctx, p.SessionID, p.Schema, p.Name, p.Kind) + }), + // A SQL script as text, whatever its encoding (UTF-8, UTF-16, + // Windows-1252). + "read_sql_file": command(func(ctx context.Context, p struct { + Path string `json:"path"` + }) (string, error) { + b, err := os.ReadFile(p.Path) + if err != nil { + return "", apperr.Internalf("%v", err) + } + text, _ := textcodec.Decode(b) + return text, nil + }), + // Writes a file the user picked in the "Save as" dialog. + "write_text_file": command(func(ctx context.Context, p struct { + Path string `json:"path"` + Content string `json:"content"` + }) (any, error) { + if err := os.WriteFile(p.Path, []byte(p.Content), 0o644); err != nil { + return nil, apperr.Internalf("%v", err) + } + return nil, nil + }), + + // Host services the Tauri plugins used to provide. + "app_version": command(func(ctx context.Context, _ none) (string, error) { + return a.version, nil + }), + "window_painted": command(func(ctx context.Context, p struct { + Background string `json:"background"` + }) (any, error) { + if a.window != nil { + a.window.Painted(p.Background) + } + return nil, nil + }), + "reveal_item_in_dir": command(func(ctx context.Context, p struct { + Path string `json:"path"` + }) (any, error) { + return nil, revealInFolder(p.Path) + }), + // Self-update arrives with the installers; until then this build + // only learns about new versions. + "update_policy": command(func(ctx context.Context, _ none) (map[string]any, error) { + return map[string]any{"channel": "portable", "canInstall": false, "target": nil}, nil + }), + "update_check": command(func(ctx context.Context, _ none) (*availableUpdate, error) { + return a.checkUpdate(ctx) + }), + } +} + +// nonNil turns a nil list into an empty one, so the interface gets []. +func nonNil[T any](list []T, err error) ([]T, error) { + if err != nil { + return nil, err + } + if list == nil { + list = []T{} + } + return list, nil +} diff --git a/internal/app/engines.go b/internal/app/engines.go new file mode 100644 index 0000000..60796f7 --- /dev/null +++ b/internal/app/engines.go @@ -0,0 +1,22 @@ +package app + +import ( + "context" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/postgres" + "github.com/LowBloat/LowQuery/internal/drivers/sqlite" + "github.com/LowBloat/LowQuery/internal/model" +) + +// openSession connects with the driver of the profile's engine. +func openSession(ctx context.Context, p model.ConnectionProfile, password *string) (drivers.Session, error) { + switch p.Engine { + case model.Postgres: + return postgres.Connect(ctx, p, password) + case model.SQLite: + return sqlite.Connect(ctx, p) + } + return nil, apperr.Newf(apperr.Invalid, "This build of LowQuery does not connect to %s yet.", p.Engine) +} diff --git a/internal/app/service.go b/internal/app/service.go new file mode 100644 index 0000000..6d0ab25 --- /dev/null +++ b/internal/app/service.go @@ -0,0 +1,72 @@ +package app + +import ( + "context" + "encoding/json" + "log" + "os/exec" + "path/filepath" + "runtime" + "sync" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// Service is the one method bound to the interface. The interface calls it +// with a command name and its named arguments (see src/lib/host.ts); errors +// reach it as the JSON of *apperr.Error. +type Service struct { + app *App + once sync.Once + handlers map[string]handler +} + +func NewService(a *App) *Service { return &Service{app: a} } + +func (s *Service) Invoke(ctx context.Context, command string, args json.RawMessage) (result any, err error) { + s.once.Do(func() { s.handlers = s.app.commands() }) + h, ok := s.handlers[command] + if !ok { + return nil, apperr.Newf(apperr.Invalid, "This build of LowQuery cannot do that yet (%s).", command) + } + defer func() { + // A driver bug must not take the whole app down. + if r := recover(); r != nil { + log.Printf("panic in %s: %v", command, r) + err = apperr.Internalf("Internal error in %s: %v", command, r) + } + }() + result, err = h(ctx, args) + if err != nil { + return nil, apperr.From(err) + } + return result, nil +} + +// MarshalError is the Wails error marshaller: *apperr.Error becomes the +// object the interface reads (kind, message, code, position, ...). +func MarshalError(err error) []byte { + b, jerr := json.Marshal(apperr.From(err)) + if jerr != nil { + return nil + } + return b +} + +// revealInFolder opens the system file manager with path selected. +func revealInFolder(path string) error { + var cmd *exec.Cmd + switch runtime.GOOS { + case "windows": + cmd = exec.Command("explorer", "/select,", filepath.Clean(path)) + case "darwin": + cmd = exec.Command("open", "-R", path) + default: + cmd = exec.Command("xdg-open", filepath.Dir(path)) + } + if err := cmd.Start(); err != nil { + return apperr.Internalf("Could not open the folder: %v", err) + } + go func() { _ = cmd.Wait() }() + return nil +} diff --git a/internal/app/updates.go b/internal/app/updates.go new file mode 100644 index 0000000..bcc1bf2 --- /dev/null +++ b/internal/app/updates.go @@ -0,0 +1,75 @@ +package app + +import ( + "context" + "encoding/json" + "net/http" + "strconv" + "strings" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// latestManifest is the update manifest every release publishes. +const latestManifest = "https://github.com/LowBloat/LowQuery/releases/latest/download/latest.json" + +// A check that hangs (a network that changed under it, a sleeping laptop) +// would otherwise keep every later check waiting. +const updateCheckTimeout = 30 * time.Second + +type availableUpdate struct { + Version string `json:"version"` + Notes string `json:"notes"` +} + +// checkUpdate returns the latest release when it is newer than this build. +func (a *App) checkUpdate(ctx context.Context) (*availableUpdate, error) { + ctx, cancel := context.WithTimeout(ctx, updateCheckTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, latestManifest, nil) + if err != nil { + return nil, apperr.Internalf("%v", err) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, apperr.Connectionf("Could not check for updates: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, apperr.Connectionf("Could not check for updates: %s", resp.Status) + } + var latest availableUpdate + if err := json.NewDecoder(resp.Body).Decode(&latest); err != nil { + return nil, apperr.Connectionf("Could not read the update manifest: %v", err) + } + if !newerVersion(latest.Version, a.version) { + return nil, nil + } + latest.Version = strings.TrimPrefix(latest.Version, "v") + return &latest, nil +} + +// newerVersion reports whether semver a is newer than b. Pre-release and +// build suffixes are ignored. +func newerVersion(a, b string) bool { + pa, pb := versionParts(a), versionParts(b) + for i := range pa { + if pa[i] != pb[i] { + return pa[i] > pb[i] + } + } + return false +} + +func versionParts(v string) [3]int { + v = strings.TrimPrefix(strings.TrimSpace(v), "v") + if i := strings.IndexAny(v, "-+"); i >= 0 { + v = v[:i] + } + var out [3]int + for i, part := range strings.SplitN(v, ".", 3) { + out[i], _ = strconv.Atoi(part) + } + return out +} diff --git a/internal/app/updates_test.go b/internal/app/updates_test.go new file mode 100644 index 0000000..1ef5831 --- /dev/null +++ b/internal/app/updates_test.go @@ -0,0 +1,23 @@ +package app + +import "testing" + +func TestNewerVersion(t *testing.T) { + cases := []struct { + a, b string + want bool + }{ + {"0.5.8", "0.5.7", true}, + {"v0.6.0", "0.5.7", true}, + {"0.5.7", "0.5.7", false}, + {"0.5.6", "0.5.7", false}, + {"1.0.0", "0.99.99", true}, + {"0.10.0", "0.9.0", true}, + {"0.5.7-beta.1", "0.5.7", false}, + } + for _, c := range cases { + if got := newerVersion(c.a, c.b); got != c.want { + t.Errorf("newerVersion(%q, %q) = %v, want %v", c.a, c.b, got, c.want) + } + } +} diff --git a/internal/apperr/apperr.go b/internal/apperr/apperr.go new file mode 100644 index 0000000..e089fd9 --- /dev/null +++ b/internal/apperr/apperr.go @@ -0,0 +1,70 @@ +// Package apperr is the error every command returns. It is serialized as an +// object so the interface can highlight the error position in the editor and +// show the database's native code (SQLSTATE on PostgreSQL, ORA-NNNNN on +// Oracle). +package apperr + +import ( + "errors" + "fmt" +) + +type Kind string + +const ( + // Error returned by the server while executing SQL. + Database Kind = "database" + // Network failure, authentication failure or closed session. + Connection Kind = "connection" + // The profile has no saved password and none was provided. + PasswordRequired Kind = "password_required" + NotFound Kind = "not_found" + Cancelled Kind = "cancelled" + Invalid Kind = "invalid" + Internal Kind = "internal" +) + +type Error struct { + Kind Kind `json:"kind"` + Message string `json:"message"` + Code string `json:"code,omitempty"` + // Position (0-based, in characters) within the executed SQL. + Position *int `json:"position,omitempty"` + Detail string `json:"detail,omitempty"` + Hint string `json:"hint,omitempty"` +} + +func (e *Error) Error() string { + if e.Code != "" { + return e.Code + ": " + e.Message + } + return e.Message +} + +func New(kind Kind, message string) *Error { return &Error{Kind: kind, Message: message} } + +func Newf(kind Kind, format string, args ...any) *Error { + return &Error{Kind: kind, Message: fmt.Sprintf(format, args...)} +} + +func Internalf(format string, args ...any) *Error { return Newf(Internal, format, args...) } +func Invalidf(format string, args ...any) *Error { return Newf(Invalid, format, args...) } +func NotFoundf(format string, args ...any) *Error { return Newf(NotFound, format, args...) } +func Connectionf(format string, args ...any) *Error { + return Newf(Connection, format, args...) +} + +// CancelledErr is what a stopped query or job reports. +func CancelledErr() *Error { return New(Cancelled, "Cancelled.") } + +// From returns err as an *Error, wrapping any other error as internal. +func From(err error) *Error { + if err == nil { + return nil + } + var e *Error + if errors.As(err, &e) { + return e + } + return New(Internal, err.Error()) +} diff --git a/internal/drivers/drivers.go b/internal/drivers/drivers.go new file mode 100644 index 0000000..9bbb1d9 --- /dev/null +++ b/internal/drivers/drivers.go @@ -0,0 +1,112 @@ +// Package drivers holds the Session every database engine implements. Each +// engine lives in its own subpackage and speaks its native protocol; there is +// no generic ODBC/JDBC layer. Rules every driver follows are in +// docs/ARCHITECTURE.md. +package drivers + +import ( + "context" + "strings" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// Session is an open connection. Each query tab has its own, so transactions +// do not mix across tabs. +// +// Execute, the metadata calls and the transaction calls are serialized by the +// driver (one statement at a time per connection). Cancel may be called from +// another goroutine while Execute runs and must interrupt it. +type Session interface { + Engine() model.Engine + ServerVersion() string + CurrentUser() *string + CurrentSchema() *string + TxState() model.TxState + + Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) + Cancel(ctx context.Context) error + SetAutocommit(ctx context.Context, on bool) (model.TxState, error) + EndTransaction(ctx context.Context, commit bool) (model.TxState, error) + + ListSchemas(ctx context.Context) ([]string, error) + ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) + ListColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) + // ObjectDDL returns the statements that create an object, read from the + // database's own catalog. kind is one of the DbObject kinds. + ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) + + // ApplyChanges applies grid edits as one unit: with autocommit on they + // commit together or not at all; with autocommit off they join the open + // transaction behind a savepoint. + ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) + + // Stream runs a query and sends its columns, then its rows in batches of + // StreamBatch, with values in full (see WithFullValues). Returns the + // number of rows. Stops with a cancelled error when ctx is done. + Stream(ctx context.Context, sql string, sink chan<- StreamEvent) (uint64, error) + + Close() error +} + +// StreamEvent is what Session.Stream sends: Columns first, then Rows. +type StreamEvent struct { + Columns []model.ColumnInfo + Rows []model.Row +} + +// StreamBatch is the number of rows per StreamEvent. +const StreamBatch = 500 + +type fullValuesKey struct{} + +// WithFullValues marks ctx so values are formatted in full: binary values are +// not cut to the grid's preview size. +func WithFullValues(ctx context.Context) context.Context { + return context.WithValue(ctx, fullValuesKey{}, true) +} + +// BinaryLimit is the number of bytes of a binary value shown as text: +// preview in the grid, all of them under WithFullValues. +func BinaryLimit(ctx context.Context, preview int) int { + if full, _ := ctx.Value(fullValuesKey{}).(bool); full { + return int(^uint(0) >> 1) + } + return preview +} + +// FirstKeywords returns the first n words of the statement, uppercased, +// skipping whitespace and comments. Stops at the first punctuation. +func FirstKeywords(sql string, n int) []string { + words := make([]string, 0, n) + i := 0 + for i < len(sql) && len(words) < n { + c := sql[i] + switch { + case c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v': + i++ + case c == '-' && i+1 < len(sql) && sql[i+1] == '-': + for i < len(sql) && sql[i] != '\n' { + i++ + } + case c == '/' && i+1 < len(sql) && sql[i+1] == '*': + i += 2 + for i+1 < len(sql) && !(sql[i] == '*' && sql[i+1] == '/') { + i++ + } + i += 2 + case isAlpha(c) || c == '_': + start := i + for i < len(sql) && (isAlpha(sql[i]) || isDigit(sql[i]) || sql[i] == '_') { + i++ + } + words = append(words, strings.ToUpper(sql[start:i])) + default: + return words + } + } + return words +} + +func isAlpha(c byte) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } +func isDigit(c byte) bool { return c >= '0' && c <= '9' } diff --git a/internal/drivers/drivers_test.go b/internal/drivers/drivers_test.go new file mode 100644 index 0000000..b8832bc --- /dev/null +++ b/internal/drivers/drivers_test.go @@ -0,0 +1,23 @@ +package drivers + +import ( + "reflect" + "testing" +) + +func TestFirstKeywordsSkipComments(t *testing.T) { + cases := []struct { + sql string + n int + want []string + }{ + {"-- x\n /* y */ begin transaction", 2, []string{"BEGIN", "TRANSACTION"}}, + {" select(1)", 3, []string{"SELECT"}}, + {"", 2, []string{}}, + } + for _, c := range cases { + if got := FirstKeywords(c.sql, c.n); !reflect.DeepEqual(got, c.want) { + t.Errorf("FirstKeywords(%q, %d) = %q, want %q", c.sql, c.n, got, c.want) + } + } +} diff --git a/internal/drivers/fixtures/fixtures.go b/internal/drivers/fixtures/fixtures.go new file mode 100644 index 0000000..53e1bf7 --- /dev/null +++ b/internal/drivers/fixtures/fixtures.go @@ -0,0 +1,216 @@ +// Package fixtures runs the SQL the interface writes against a real +// database, from the JSON fixtures the frontend tests keep in step with the +// code that writes it: +// +// - src/lib/view.fixtures.json: grid sort and filter on a result that hit +// the row limit (src/lib/view.ts). +// - src/lib/sql/ddl.fixtures.json: tree menus and the table designer +// (src/lib/sql/ddl.ts), plus a round trip of the DDL each driver reads +// from its catalog (drop the object, run its DDL, compare the columns). +// +// Dialects are named as in the frontend: postgres, oracle, mysql, sqlserver, +// sqlite. +package fixtures + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +func repoFile(t *testing.T, rel string) []byte { + t.Helper() + _, here, _, _ := runtime.Caller(0) + root := filepath.Join(filepath.Dir(here), "..", "..", "..") + data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rel))) + if err != nil { + t.Fatalf("read %s: %v", rel, err) + } + return data +} + +func run(ctx context.Context, s drivers.Session, sql string) (*model.ExecResult, error) { + return s.Execute(ctx, model.ExecRequest{SQL: sql, MaxRows: 100}) +} + +func firstColumn(r *model.ExecResult) []string { + out := make([]string, 0, len(r.Rows)) + for _, row := range r.Rows { + if len(row) > 0 && row[0] != nil { + out = append(out, *row[0]) + } else { + out = append(out, "") + } + } + return out +} + +// CheckView runs every view fixture of dialect and compares the ids in the +// first column. +func CheckView(t *testing.T, s drivers.Session, dialect string) { + t.Helper() + var f struct { + Dialects map[string]struct { + Cases []struct { + Label string `json:"label"` + SQL string `json:"sql"` + IDs []string `json:"ids"` + } `json:"cases"` + } `json:"dialects"` + } + if err := json.Unmarshal(repoFile(t, "src/lib/view.fixtures.json"), &f); err != nil { + t.Fatal(err) + } + cases := f.Dialects[dialect].Cases + if len(cases) == 0 { + t.Fatalf("no view fixtures for %s", dialect) + } + ctx := context.Background() + for _, c := range cases { + r, err := run(ctx, s, c.SQL) + if err != nil { + t.Fatalf("%s, %s: %v\n%s", dialect, c.Label, err, c.SQL) + } + if got := firstColumn(r); !reflect.DeepEqual(got, c.IDs) { + t.Errorf("%s, %s: got %q, want %q\n%s", dialect, c.Label, got, c.IDs, c.SQL) + } + } +} + +// Statements splits a DDL script: lines ending in `;` close a statement (the +// fixtures hold no routine bodies), SQL Server batches end at GO. Parts that +// are only comments are left out. +func Statements(ddl, dialect string) []string { + var out []string + var current strings.Builder + for _, line := range strings.Split(strings.ReplaceAll(ddl, "\r\n", "\n"), "\n") { + trimmed := strings.TrimSpace(line) + if dialect == "sqlserver" { + if strings.EqualFold(trimmed, "GO") { + out = append(out, current.String()) + current.Reset() + } else { + current.WriteString(line) + current.WriteByte('\n') + } + continue + } + current.WriteString(line) + current.WriteByte('\n') + if strings.HasSuffix(trimmed, ";") { + out = append(out, strings.TrimSuffix(strings.TrimSpace(current.String()), ";")) + current.Reset() + } + } + out = append(out, current.String()) + kept := out[:0] + for _, stmt := range out { + for _, l := range strings.Split(stmt, "\n") { + if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "--") { + kept = append(kept, stmt) + break + } + } + } + return kept +} + +// CheckDDL runs the DDL scenario of dialect; schema replaces the fixtures' +// placeholder schema. +func CheckDDL(t *testing.T, s drivers.Session, dialect, schema string) { + t.Helper() + type objectRef struct { + Name string `json:"name"` + Kind string `json:"kind"` + Drop string `json:"drop"` + Contains string `json:"contains"` + } + var f struct { + Dialects map[string]struct { + Schema string `json:"schema"` + Cleanup []string `json:"cleanup"` + Steps []struct { + Label string `json:"label"` + SQL string `json:"sql"` + Rows []string `json:"rows"` + RoundTrip *objectRef `json:"roundTrip"` + DDL *objectRef `json:"ddl"` + } `json:"steps"` + } `json:"dialects"` + } + if err := json.Unmarshal(repoFile(t, "src/lib/sql/ddl.fixtures.json"), &f); err != nil { + t.Fatal(err) + } + d, ok := f.Dialects[dialect] + if !ok { + t.Fatalf("no ddl fixtures for %s", dialect) + } + sqlOf := func(sql string) string { return strings.ReplaceAll(sql, d.Schema, schema) } + ctx := context.Background() + cleanup := func() { + for _, sql := range d.Cleanup { + _, _ = run(ctx, s, sqlOf(sql)) + } + } + cleanup() + defer cleanup() + + columns := func(label, name string) string { + cols, err := s.ListColumns(ctx, schema, name) + if err != nil { + t.Fatalf("%s, %s: columns: %v", dialect, label, err) + } + b, _ := json.Marshal(cols) + return string(b) + } + + for _, step := range d.Steps { + switch { + case step.RoundTrip != nil: + rt := step.RoundTrip + ddl, err := s.ObjectDDL(ctx, schema, rt.Name, rt.Kind) + if err != nil { + t.Fatalf("%s, %s: %v", dialect, step.Label, err) + } + before := columns(step.Label, rt.Name) + if _, err := run(ctx, s, sqlOf(rt.Drop)); err != nil { + t.Fatalf("%s, %s: %v\n%s", dialect, step.Label, err, sqlOf(rt.Drop)) + } + for _, stmt := range Statements(ddl, dialect) { + if _, err := run(ctx, s, stmt); err != nil { + t.Fatalf("%s, %s: %v\n%s\n\nfrom:\n%s", dialect, step.Label, err, stmt, ddl) + } + } + if after := columns(step.Label, rt.Name); after != before { + t.Fatalf("%s, %s: columns changed\nbefore: %s\nafter: %s\n%s", dialect, step.Label, before, after, ddl) + } + case step.DDL != nil: + ddl, err := s.ObjectDDL(ctx, schema, step.DDL.Name, step.DDL.Kind) + if err != nil { + t.Fatalf("%s, %s: %v", dialect, step.Label, err) + } + if !strings.Contains(strings.ToLower(ddl), step.DDL.Contains) { + t.Fatalf("%s, %s: %q not in\n%s", dialect, step.Label, step.DDL.Contains, ddl) + } + default: + sql := sqlOf(step.SQL) + r, err := run(ctx, s, sql) + if err != nil { + t.Fatalf("%s, %s: %v\n%s", dialect, step.Label, err, sql) + } + if step.Rows != nil { + if got := firstColumn(r); !reflect.DeepEqual(got, step.Rows) { + t.Fatalf("%s, %s: got %q, want %q\n%s", dialect, step.Label, got, step.Rows, sql) + } + } + } + } +} diff --git a/internal/drivers/postgres/ddl.go b/internal/drivers/postgres/ddl.go new file mode 100644 index 0000000..794cc66 --- /dev/null +++ b/internal/drivers/postgres/ddl.go @@ -0,0 +1,238 @@ +package postgres + +import ( + "context" + "fmt" + "strings" + "unicode" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// ObjectDDL returns the statements that create an object, read from the +// catalog: tables from pg_attribute, pg_constraint and pg_index, views, +// functions and sequences from pg_get_viewdef, pg_get_functiondef and +// pg_sequence. +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + end, err := s.begin(ctx) + if err != nil { + return "", err + } + defer end() + + if kind == "function" || kind == "procedure" { + rows, err := s.textRows(`SELECT pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = $1 + AND p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' = $2`, + schema, name) + if err != nil { + return "", err + } + def := "" + if len(rows) > 0 { + def = cellText(rows[0], 0) + } + if strings.TrimSpace(def) == "" { + return def, nil + } + return strings.TrimRightFunc(def, unicode.IsSpace) + ";\n", nil + } + + rel, err := s.textRows(`SELECT c.oid::text, c.relkind::text, c.relpersistence::text, + quote_ident(n.nspname) || '.' || quote_ident(c.relname) + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = $1 AND c.relname = $2`, schema, name) + if err != nil { + return "", err + } + if len(rel) == 0 { + return "", apperr.NotFoundf("%s.%s was not found.", schema, name) + } + oid := cellText(rel[0], 0) + relkind := cellText(rel[0], 1) + target := cellText(rel[0], 3) + var out string + switch relkind { + case "v", "m": + def, err := s.textRows("SELECT pg_get_viewdef($1::text::oid, true)", oid) + if err != nil { + return "", err + } + body := "" + if len(def) > 0 { + body = cellText(def[0], 0) + } + body = strings.TrimRight(strings.TrimSpace(body), ";") + if relkind == "v" { + out = fmt.Sprintf("CREATE OR REPLACE VIEW %s AS\n%s;\n", target, body) + } else { + out = fmt.Sprintf("CREATE MATERIALIZED VIEW %s AS\n%s\nWITH DATA;\n", target, body) + } + case "S": + if out, err = s.sequenceDDL(oid, target); err != nil { + return "", err + } + case "r", "p", "f": + if out, err = s.tableDDL(oid, relkind, cellText(rel[0], 2), target); err != nil { + return "", err + } + default: + return "", apperr.Invalidf("LowQuery cannot script this kind of relation (%s).", relkind) + } + + // Indexes not behind a constraint, triggers and comments. + extra, err := s.textRows(`SELECT * FROM ( + SELECT pg_get_indexdef(i.indexrelid) || ';' FROM pg_index i + WHERE i.indrelid = $1::text::oid + AND NOT EXISTS (SELECT 1 FROM pg_constraint c + WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) + ORDER BY 1) ix + UNION ALL + SELECT * FROM ( + SELECT pg_get_triggerdef(t.oid, true) || ';' FROM pg_trigger t + WHERE t.tgrelid = $1::text::oid AND NOT t.tgisinternal ORDER BY t.tgname) tr + UNION ALL + SELECT 'COMMENT ON ' || CASE c.relkind WHEN 'v' THEN 'VIEW' + WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE' + WHEN 'f' THEN 'FOREIGN TABLE' ELSE 'TABLE' END + || ' ' || $2::text || ' IS ' || quote_literal(d.description) || ';' + FROM pg_description d JOIN pg_class c ON c.oid = d.objoid + WHERE d.objoid = $1::text::oid AND d.classoid = 'pg_class'::regclass + AND d.objsubid = 0 + UNION ALL + SELECT * FROM ( + SELECT 'COMMENT ON COLUMN ' || $2::text || '.' || quote_ident(a.attname) + || ' IS ' || quote_literal(d.description) || ';' + FROM pg_description d + JOIN pg_attribute a ON a.attrelid = d.objoid AND a.attnum = d.objsubid + WHERE d.objoid = $1::text::oid AND d.classoid = 'pg_class'::regclass + AND d.objsubid > 0 + ORDER BY d.objsubid) cm`, oid, target) + if err != nil { + return "", err + } + var sb strings.Builder + sb.WriteString(out) + for _, row := range extra { + sb.WriteString("\n" + cellText(row, 0) + "\n") + } + return sb.String(), nil +} + +func (s *Session) sequenceDDL(oid, target string) (string, error) { + rows, err := s.textRows(`SELECT format_type(s.seqtypid, NULL), s.seqincrement::text, s.seqmin::text, + s.seqmax::text, s.seqstart::text, s.seqcache::text, s.seqcycle::text + FROM pg_sequence s WHERE s.seqrelid = $1::text::oid`, oid) + if err != nil || len(rows) == 0 { + return "", err + } + q := rows[0] + cycle := "NO " + if cellText(q, 6) == "true" { + cycle = "" + } + return fmt.Sprintf("CREATE SEQUENCE %s\n AS %s\n INCREMENT BY %s\n MINVALUE %s\n MAXVALUE %s\n START WITH %s\n CACHE %s\n %sCYCLE;\n", + target, cellText(q, 0), cellText(q, 1), cellText(q, 2), cellText(q, 3), cellText(q, 4), + cellText(q, 5), cycle), nil +} + +// tableDDL writes CREATE TABLE with columns, defaults, identity and +// generated columns, and the primary key, unique, check and exclusion +// constraints; foreign keys follow as ALTER TABLE so tables can be created +// in any order. +func (s *Session) tableDDL(oid, relkind, persistence, target string) (string, error) { + // attidentity (10+) and attgenerated (12+) are read through to_jsonb so + // older servers leave them empty instead of failing. + columns, err := s.textRows(`SELECT quote_ident(a.attname), format_type(a.atttypid, a.atttypmod), + a.attnotnull::text, pg_get_expr(d.adbin, d.adrelid), + to_jsonb(a) ->> 'attidentity', to_jsonb(a) ->> 'attgenerated' + FROM pg_attribute a + LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE a.attrelid = $1::text::oid AND a.attnum > 0 AND NOT a.attisdropped + ORDER BY a.attnum`, oid) + if err != nil { + return "", err + } + constraints, err := s.textRows(`SELECT quote_ident(conname), pg_get_constraintdef(oid, true), contype::text + FROM pg_constraint + WHERE conrelid = $1::text::oid AND contype IN ('p', 'u', 'c', 'x', 'f') AND conislocal + ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 + WHEN 'x' THEN 3 ELSE 4 END, conname`, oid) + if err != nil { + return "", err + } + lines := make([]string, 0, len(columns)+len(constraints)) + for _, c := range columns { + line := " " + cellText(c, 0) + " " + cellText(c, 1) + def := cellText(c, 3) + identity, generated := cellText(c, 4), cellText(c, 5) + switch { + case identity == "a": + line += " GENERATED ALWAYS AS IDENTITY" + case identity == "d": + line += " GENERATED BY DEFAULT AS IDENTITY" + case generated == "s": + line += " GENERATED ALWAYS AS (" + def + ") STORED" + case generated == "v": + line += " GENERATED ALWAYS AS (" + def + ") VIRTUAL" + case def != "": + line += " DEFAULT " + def + } + if cellText(c, 2) == "true" { + line += " NOT NULL" + } + lines = append(lines, line) + } + var foreignKeys []string + for _, c := range constraints { + def := "CONSTRAINT " + cellText(c, 0) + " " + cellText(c, 1) + if cellText(c, 2) == "f" { + foreignKeys = append(foreignKeys, "ALTER TABLE "+target+" ADD "+def+";") + } else { + lines = append(lines, " "+def) + } + } + head := "CREATE TABLE" + switch { + case relkind == "f": + head = "CREATE FOREIGN TABLE" + case persistence == "u": + head = "CREATE UNLOGGED TABLE" + } + var out strings.Builder + fmt.Fprintf(&out, "%s %s (\n%s\n)", head, target, strings.Join(lines, ",\n")) + if relkind == "p" { + key, err := s.textRows("SELECT pg_get_partkeydef($1::text::oid)", oid) + if err != nil { + return "", err + } + k := "" + if len(key) > 0 { + k = cellText(key[0], 0) + } + out.WriteString("\nPARTITION BY " + k) + } + if relkind == "f" { + server, err := s.textRows(`SELECT quote_ident(s.srvname), + (SELECT string_agg(quote_ident(split_part(o, '=', 1)) || ' ' + || quote_literal(substr(o, strpos(o, '=') + 1)), ', ') + FROM unnest(ft.ftoptions) o) + FROM pg_foreign_table ft JOIN pg_foreign_server s ON s.oid = ft.ftserver + WHERE ft.ftrelid = $1::text::oid`, oid) + if err != nil { + return "", err + } + if len(server) > 0 { + out.WriteString("\nSERVER " + cellText(server[0], 0)) + if options := cellText(server[0], 1); options != "" { + out.WriteString("\nOPTIONS (" + options + ")") + } + } + } + out.WriteString(";\n") + for _, fk := range foreignKeys { + out.WriteString("\n" + fk + "\n") + } + return out.String(), nil +} diff --git a/internal/drivers/postgres/edit.go b/internal/drivers/postgres/edit.go new file mode 100644 index 0000000..e94a8cc --- /dev/null +++ b/internal/drivers/postgres/edit.go @@ -0,0 +1,534 @@ +package postgres + +import ( + "fmt" + "strconv" + "strings" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + notATable = "Read-only: only rows from a table can be edited." + joinsTables = "Read-only: the query joins tables; select from one table to edit its rows." + severalTabs = "Read-only: the result combines columns from several tables." + severalQs = "Read-only: the result combines rows from several queries." + keyUnreadMsg = "Read-only: the table's key could not be read." +) + +// origin is the table OID and attribute number the server reports for a +// result column; zero means none (an expression). +type origin struct { + table uint32 + column int16 +} + +// metaColumn is one table column: attribute number, name and type as in +// DDL. +type metaColumn struct { + attnum int16 + name string + typ string +} + +// tableMeta is the catalog data of a table behind a result. +type tableMeta struct { + schema string + name string + // pg_class.relkind: r table, p partitioned table, v view... + kind string + columns []metaColumn + // Attribute numbers of the primary key, or of a unique key whose + // columns are all NOT NULL, in key order; nil when there is none. + key []int16 + primary bool +} + +// tableMetaSQL returns one row per column, all values as text (simple +// protocol). The chosen key is the primary key, else the narrowest valid +// unique index without expressions or predicate whose key columns are all +// NOT NULL. +func tableMetaSQL(oid uint32) string { + return fmt.Sprintf(`SELECT n.nspname, c.relname, c.relkind, a.attnum, a.attname, + pg_catalog.format_type(a.atttypid, a.atttypmod), k.cols, k.indisprimary + FROM pg_catalog.pg_class c + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + LEFT JOIN pg_catalog.pg_attribute a + ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped + LEFT JOIN LATERAL ( + SELECT (SELECT string_agg(u.k::text, ',' ORDER BY u.o) + FROM unnest(i.indkey::int2[]) WITH ORDINALITY u(k, o) + WHERE u.o <= i.indnkeyatts) AS cols, + i.indisprimary + FROM pg_catalog.pg_index i + WHERE i.indrelid = c.oid AND i.indisunique AND i.indisvalid + AND (i.indisprimary OR ( + i.indpred IS NULL AND i.indexprs IS NULL + AND NOT EXISTS ( + SELECT 1 + FROM unnest(i.indkey::int2[]) WITH ORDINALITY u(k, o) + JOIN pg_catalog.pg_attribute x + ON x.attrelid = c.oid AND x.attnum = u.k + WHERE u.o <= i.indnkeyatts AND NOT x.attnotnull))) + ORDER BY i.indisprimary DESC, i.indnkeyatts, i.indexrelid + LIMIT 1) k ON true + WHERE c.oid = %d + ORDER BY a.attnum`, oid) +} + +func cell(row []*string, i int) *string { + if i < len(row) { + return row[i] + } + return nil +} + +// parseTableMeta reads the rows of tableMetaSQL; nil when they do not +// describe a table. +func parseTableMeta(rows [][]*string) *tableMeta { + if len(rows) == 0 { + return nil + } + first := rows[0] + schema, name, kind := cell(first, 0), cell(first, 1), cell(first, 2) + if schema == nil || name == nil || kind == nil { + return nil + } + m := &tableMeta{schema: *schema, name: *name, kind: *kind} + if cols := cell(first, 6); cols != nil { + for _, k := range strings.Split(*cols, ",") { + if n, err := strconv.ParseInt(strings.TrimSpace(k), 10, 16); err == nil { + m.key = append(m.key, int16(n)) + } + } + } + for _, row := range rows { + attnum, col, typ := cell(row, 3), cell(row, 4), cell(row, 5) + if attnum == nil || col == nil || typ == nil { + continue + } + n, err := strconv.ParseInt(*attnum, 10, 16) + if err != nil { + return nil + } + m.columns = append(m.columns, metaColumn{int16(n), *col, *typ}) + } + if p := cell(first, 7); p != nil && *p == "t" { + m.primary = true + } + return m +} + +// singleTable is the one table all base columns come from. +func singleTable(origins []origin) (uint32, string) { + var table uint32 + for _, o := range origins { + switch { + case o.table == 0: + case table == 0: + table = o.table + case table != o.table: + return 0, severalTabs + } + } + if table == 0 { + return 0, notATable + } + return table, "" +} + +func (m *tableMeta) column(attnum int16) *metaColumn { + for i := range m.columns { + if m.columns[i].attnum == attnum { + return &m.columns[i] + } + } + return nil +} + +// targetFor builds the edit target of a result from one table, or says +// why it is read-only. +func targetFor(meta *tableMeta, oid uint32, origins []origin) (*model.EditTarget, string) { + if meta.kind != "r" && meta.kind != "p" { + return nil, notATable + } + if meta.key == nil { + return nil, fmt.Sprintf("Read-only: table %s has no primary key.", meta.name) + } + columns := make([]*model.EditColumn, len(origins)) + for i, o := range origins { + if o.table == oid && o.column != 0 { + if c := meta.column(o.column); c != nil { + columns[i] = &model.EditColumn{Name: c.name, TypeName: c.typ} + } + } + } + key := make([]int, 0, len(meta.key)) + missing := false + for _, k := range meta.key { + pos := -1 + for i, o := range origins { + if o.table == oid && o.column == k { + pos = i + break + } + } + if pos < 0 || columns[pos] == nil { + missing = true + continue + } + key = append(key, pos) + } + if missing { + names := make([]string, len(meta.key)) + for i, k := range meta.key { + names[i] = "?" + if c := meta.column(k); c != nil { + names[i] = c.name + } + } + what := "key" + if meta.primary { + what = "primary key" + } + return nil, fmt.Sprintf("Read-only: add the %s columns (%s) to the query to edit rows.", + what, strings.Join(names, ", ")) + } + schema := meta.schema + return &model.EditTarget{Schema: &schema, Table: meta.name, Columns: columns, Key: key}, "" +} + +type tokenKind uint8 + +const ( + tokWord tokenKind = iota + tokOpen + tokClose + tokComma +) + +// sqlToken is a keyword (uppercased) or the punctuation that shapes +// clauses, outside strings, quoted identifiers, comments and dollar quotes. +type sqlToken struct { + kind tokenKind + word string +} + +func isWordByte(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '$' || c >= 0x80 +} + +func sqlTokens(sql string) []sqlToken { + var tokens []sqlToken + b := sql + at := func(i int) byte { + if i < len(b) { + return b[i] + } + return 0 + } + i := 0 + for i < len(b) { + c := b[i] + prevWord := i > 0 && isWordByte(b[i-1]) + switch { + case c == '-' && at(i+1) == '-': + for i < len(b) && b[i] != '\n' { + i++ + } + case c == '/' && at(i+1) == '*': + // Block comments nest. + depth := 0 + for i < len(b) { + if b[i] == '/' && at(i+1) == '*' { + depth++ + i += 2 + } else if b[i] == '*' && at(i+1) == '/' { + depth-- + i += 2 + if depth == 0 { + break + } + } else { + i++ + } + } + case c == '\'' || c == '"': + // E'...' strings accept backslash escapes. + escapes := c == '\'' && i > 0 && (b[i-1] == 'e' || b[i-1] == 'E') && + !(i > 1 && isWordByte(b[i-2])) + i++ + for i < len(b) { + if escapes && b[i] == '\\' { + i += 2 + } else if b[i] == c { + if at(i+1) == c { + i += 2 + } else { + break + } + } else { + i++ + } + } + i++ + case c == '$' && !prevWord: + // Dollar quote: $$...$$ or $tag$...$tag$. + j := i + 1 + for j < len(b) && (b[j] >= 'a' && b[j] <= 'z' || b[j] >= 'A' && b[j] <= 'Z' || + b[j] >= '0' && b[j] <= '9' || b[j] == '_' || b[j] >= 0x80) { + j++ + } + next := at(i + 1) + if j < len(b) && b[j] == '$' && !(i+1 < len(b) && next >= '0' && next <= '9') { + tag := b[i : j+1] + if end := strings.Index(b[j+1:], tag); end >= 0 { + i = j + 1 + end + len(tag) + } else { + i = len(b) + } + } else { + i++ + } + case isWordByte(c) && !prevWord: + start := i + for i < len(b) && isWordByte(b[i]) { + i++ + } + tokens = append(tokens, sqlToken{kind: tokWord, word: asciiOnlyUpper(b[start:i])}) + default: + switch c { + case '(': + tokens = append(tokens, sqlToken{kind: tokOpen}) + case ')': + tokens = append(tokens, sqlToken{kind: tokClose}) + case ',': + tokens = append(tokens, sqlToken{kind: tokComma}) + } + i++ + } + } + return tokens +} + +// asciiOnlyUpper uppercases ASCII letters only and leaves other bytes as +// they are. +func asciiOnlyUpper(s string) string { + out := []byte(s) + for i, c := range out { + if c >= 'a' && c <= 'z' { + out[i] = c - ('a' - 'A') + } + } + return string(out) +} + +// hasUnion says whether UNION appears as a keyword. +func hasUnion(tokens []sqlToken) bool { + for _, t := range tokens { + if t.kind == tokWord && t.word == "UNION" { + return true + } + } + return false +} + +// joinsTablesIn says whether the query joins tables at any depth: a JOIN +// keyword, or a comma in a FROM list. Both sides of a self-join report the +// same table OID, so the row description alone cannot tell them apart. +func joinsTablesIn(tokens []sqlToken) bool { + // One entry per paren depth: inside a FROM list at that depth. + inFrom := []bool{false} + for _, t := range tokens { + switch t.kind { + case tokOpen: + inFrom = append(inFrom, false) + case tokClose: + if len(inFrom) > 1 { + inFrom = inFrom[:len(inFrom)-1] + } + case tokComma: + if inFrom[len(inFrom)-1] { + return true + } + case tokWord: + switch t.word { + case "JOIN": + return true + case "FROM": + inFrom[len(inFrom)-1] = true + case "WHERE", "GROUP", "HAVING", "WINDOW", "ORDER", "LIMIT", "OFFSET", "FETCH", "FOR", + "UNION", "INTERSECT", "EXCEPT": + inFrom[len(inFrom)-1] = false + } + } + } + return false +} + +type changeKind uint8 + +const ( + changeUpdate changeKind = iota + changeDelete + changeInsert +) + +// builtChange is one statement ready to run, with its parameters in +// order (text format; nil is NULL). +type builtChange struct { + kind changeKind + sql string + params []*string +} + +func quoteIdent(name string) string { + return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` +} + +func qualifiedTable(t *model.EditTarget) string { + if t.Schema != nil { + return quoteIdent(*t.Schema) + "." + quoteIdent(t.Table) + } + return quoteIdent(t.Table) +} + +func editColumn(t *model.EditTarget, index int) (*model.EditColumn, error) { + if index >= 0 && index < len(t.Columns) && t.Columns[index] != nil { + return t.Columns[index], nil + } + return nil, apperr.Invalidf("Column %d cannot be edited.", index+1) +} + +// placeholder is $n, routed through numeric for money, whose own input +// depends on lc_monetary. +func placeholder(n int, c *model.EditColumn) string { + if c.TypeName == "money" { + return fmt.Sprintf("$%d::numeric::money", n) + } + return fmt.Sprintf("$%d", n) +} + +func checkValue(v *string) (*string, error) { + if v != nil && strings.Contains(*v, "… (") { + return nil, apperr.New(apperr.Invalid, "This value is only a preview and cannot be saved.") + } + return v, nil +} + +type assignment struct { + column *model.EditColumn + value *string +} + +// assignments returns the table columns and values of a change; a column +// given twice keeps the last value. +func assignments(t *model.EditTarget, values []model.CellValue) ([]assignment, error) { + out := make([]assignment, 0, len(values)) + for _, v := range values { + column, err := editColumn(t, v.Column) + if err != nil { + return nil, err + } + value, err := checkValue(v.Value) + if err != nil { + return nil, err + } + found := false + for i := range out { + if out[i].column.Name == column.Name { + out[i].value = value + found = true + break + } + } + if !found { + out = append(out, assignment{column, value}) + } + } + return out, nil +} + +func whereKey(t *model.EditTarget, key []*string, params *[]*string) (string, error) { + if len(key) != len(t.Key) { + return "", apperr.New(apperr.Invalid, "The row key does not match the result's key columns.") + } + parts := make([]string, 0, len(key)) + for i, index := range t.Key { + column, err := editColumn(t, index) + if err != nil { + return "", err + } + value, err := checkValue(key[i]) + if err != nil { + return "", err + } + if value == nil { + parts = append(parts, quoteIdent(column.Name)+" IS NULL") + continue + } + *params = append(*params, value) + parts = append(parts, quoteIdent(column.Name)+" = "+placeholder(len(*params), column)) + } + return strings.Join(parts, " AND "), nil +} + +// buildChange returns the statement for one change; nil for an update +// without values. +func buildChange(t *model.EditTarget, change model.RowChange) (*builtChange, error) { + table := qualifiedTable(t) + var params []*string + switch change.Op { + case model.OpUpdate: + sets, err := assignments(t, change.Values) + if err != nil { + return nil, err + } + if len(sets) == 0 { + return nil, nil + } + setSQL := make([]string, 0, len(sets)) + for _, s := range sets { + params = append(params, s.value) + setSQL = append(setSQL, quoteIdent(s.column.Name)+" = "+placeholder(len(params), s.column)) + } + filter, err := whereKey(t, change.Key, ¶ms) + if err != nil { + return nil, err + } + return &builtChange{ + kind: changeUpdate, + sql: "UPDATE " + table + " SET " + strings.Join(setSQL, ", ") + " WHERE " + filter, + params: params, + }, nil + case model.OpDelete: + filter, err := whereKey(t, change.Key, ¶ms) + if err != nil { + return nil, err + } + return &builtChange{kind: changeDelete, sql: "DELETE FROM " + table + " WHERE " + filter, params: params}, nil + case model.OpInsert: + sets, err := assignments(t, change.Values) + if err != nil { + return nil, err + } + if len(sets) == 0 { + return &builtChange{kind: changeInsert, sql: "INSERT INTO " + table + " DEFAULT VALUES"}, nil + } + names := make([]string, 0, len(sets)) + slots := make([]string, 0, len(sets)) + for _, s := range sets { + params = append(params, s.value) + names = append(names, quoteIdent(s.column.Name)) + slots = append(slots, placeholder(len(params), s.column)) + } + return &builtChange{ + kind: changeInsert, + sql: "INSERT INTO " + table + " (" + strings.Join(names, ", ") + ") VALUES (" + + strings.Join(slots, ", ") + ")", + params: params, + }, nil + } + return nil, apperr.Invalidf("Unknown change %q.", change.Op) +} diff --git a/internal/drivers/postgres/edit_test.go b/internal/drivers/postgres/edit_test.go new file mode 100644 index 0000000..5bf260a --- /dev/null +++ b/internal/drivers/postgres/edit_test.go @@ -0,0 +1,375 @@ +package postgres + +import ( + "context" + "fmt" + "reflect" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgconn" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func str(v string) *string { return &v } + +func testTarget() *model.EditTarget { + return &model.EditTarget{ + Schema: str("My Schema"), + Table: `Order "Lines"`, + Columns: []*model.EditColumn{ + {Name: "Id", TypeName: "integer"}, + {Name: "price", TypeName: "money"}, + nil, + {Name: "code", TypeName: "text"}, + }, + Key: []int{0, 3}, + } +} + +func cellValue(column int, value *string) model.CellValue { + return model.CellValue{Column: column, Value: value} +} + +func paramsOf(c *builtChange) []*string { return c.params } + +func TestQuotesIdentifiers(t *testing.T) { + cases := map[string]string{ + "a": `"a"`, + "Mixed Case": `"Mixed Case"`, + `say "hi"`: `"say ""hi"""`, + } + for in, want := range cases { + if got := quoteIdent(in); got != want { + t.Errorf("quoteIdent(%q) = %q, want %q", in, got, want) + } + } + if got := qualifiedTable(testTarget()); got != `"My Schema"."Order ""Lines"""` { + t.Errorf("qualifiedTable = %q", got) + } +} + +func TestBuildsUpdateWithNullKeyAndMoney(t *testing.T) { + change := model.RowChange{ + Op: model.OpUpdate, + Key: []*string{str("7"), nil}, + Values: []model.CellValue{cellValue(1, str("12.34")), cellValue(3, nil)}, + } + built, err := buildChange(testTarget(), change) + if err != nil { + t.Fatal(err) + } + if built.kind != changeUpdate { + t.Errorf("kind %v", built.kind) + } + want := `UPDATE "My Schema"."Order ""Lines""" SET "price" = $1::numeric::money, "code" = $2 WHERE "Id" = $3 AND "code" IS NULL` + if built.sql != want { + t.Errorf("sql %q", built.sql) + } + if !reflect.DeepEqual(paramsOf(built), []*string{str("12.34"), nil, str("7")}) { + t.Errorf("params %v", built.params) + } +} + +func TestUpdateKeepsLastValueOfAColumnAndSkipsEmpty(t *testing.T) { + change := model.RowChange{ + Op: model.OpUpdate, + Key: []*string{str("1"), str("a")}, + Values: []model.CellValue{cellValue(3, str("x")), cellValue(3, str("y"))}, + } + built, err := buildChange(testTarget(), change) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(built.sql, `SET "code" = $1 WHERE`) { + t.Errorf("sql %q", built.sql) + } + if !reflect.DeepEqual(built.params, []*string{str("y"), str("1"), str("a")}) { + t.Errorf("params %v", built.params) + } + empty := model.RowChange{Op: model.OpUpdate, Key: []*string{str("1"), str("a")}} + if built, err := buildChange(testTarget(), empty); err != nil || built != nil { + t.Errorf("empty update: %v, %v", built, err) + } +} + +func TestBuildsDeleteAndInsert(t *testing.T) { + built, err := buildChange(testTarget(), model.RowChange{Op: model.OpDelete, Key: []*string{str("1"), str("a'b")}}) + if err != nil { + t.Fatal(err) + } + if built.sql != `DELETE FROM "My Schema"."Order ""Lines""" WHERE "Id" = $1 AND "code" = $2` { + t.Errorf("sql %q", built.sql) + } + if !reflect.DeepEqual(built.params, []*string{str("1"), str("a'b")}) { + t.Errorf("params %v", built.params) + } + + built, err = buildChange(testTarget(), model.RowChange{ + Op: model.OpInsert, + Values: []model.CellValue{cellValue(0, str("5")), cellValue(1, str("1.00")), cellValue(3, nil)}, + }) + if err != nil { + t.Fatal(err) + } + want := `INSERT INTO "My Schema"."Order ""Lines""" ("Id", "price", "code") VALUES ($1, $2::numeric::money, $3)` + if built.sql != want { + t.Errorf("sql %q", built.sql) + } + if !reflect.DeepEqual(built.params, []*string{str("5"), str("1.00"), nil}) { + t.Errorf("params %v", built.params) + } + + built, err = buildChange(testTarget(), model.RowChange{Op: model.OpInsert}) + if err != nil { + t.Fatal(err) + } + if built.sql != `INSERT INTO "My Schema"."Order ""Lines""" DEFAULT VALUES` || len(built.params) != 0 { + t.Errorf("defaults: %q %v", built.sql, built.params) + } +} + +func TestRejectsInvalidChanges(t *testing.T) { + _, err := buildChange(testTarget(), model.RowChange{ + Op: model.OpUpdate, + Key: []*string{str("1"), str("a")}, + Values: []model.CellValue{cellValue(3, str(`\x0102… (40000 bytes)`))}, + }) + e := apperr.From(err) + if e == nil || e.Kind != apperr.Invalid || e.Message != "This value is only a preview and cannot be saved." { + t.Errorf("preview: %v", err) + } + invalid := []model.RowChange{ + {Op: model.OpInsert, Values: []model.CellValue{cellValue(2, str("x"))}}, + {Op: model.OpInsert, Values: []model.CellValue{cellValue(9, str("x"))}}, + {Op: model.OpInsert, Values: []model.CellValue{cellValue(-1, str("x"))}}, + {Op: model.OpDelete, Key: []*string{str("1")}}, + {Op: "merge"}, + } + for _, c := range invalid { + _, err := buildChange(testTarget(), c) + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid { + t.Errorf("%+v: %v", c, err) + } + } +} + +func testMeta(kind string, key []int16, primary bool) *tableMeta { + return &tableMeta{ + schema: "public", + name: "orders", + kind: kind, + columns: []metaColumn{ + {1, "id", "integer"}, + {2, "name", "character varying(20)"}, + {3, "total", "numeric(10,2)"}, + }, + key: key, + primary: primary, + } +} + +func TestDetectsEditableResults(t *testing.T) { + origins := []origin{{10, 2}, {0, 0}, {10, 1}, {10, 3}} + target, reason := targetFor(testMeta("r", []int16{1}, true), 10, origins) + if target == nil { + t.Fatal(reason) + } + if *target.Schema != "public" || target.Table != "orders" || !reflect.DeepEqual(target.Key, []int{2}) { + t.Errorf("target %+v", target) + } + if target.Columns[1] != nil { + t.Error("expression column is editable") + } + if c := target.Columns[0]; c.Name != "name" || c.TypeName != "character varying(20)" { + t.Errorf("column 0: %+v", c) + } + + // Key in key order, not result order. + target, _ = targetFor(testMeta("p", []int16{3, 1}, false), 10, origins) + if target == nil || !reflect.DeepEqual(target.Key, []int{3, 2}) { + t.Errorf("target %+v", target) + } +} + +func TestExplainsReadOnlyResults(t *testing.T) { + origins := []origin{{10, 2}, {10, 3}} + reasons := []struct { + meta *tableMeta + want string + }{ + {testMeta("r", []int16{1}, true), "Read-only: add the primary key columns (id) to the query to edit rows."}, + {testMeta("r", []int16{1, 2}, false), "Read-only: add the key columns (id, name) to the query to edit rows."}, + {testMeta("r", nil, false), "Read-only: table orders has no primary key."}, + {testMeta("v", []int16{2}, true), notATable}, + } + for _, c := range reasons { + if target, reason := targetFor(c.meta, 10, origins); target != nil || reason != c.want { + t.Errorf("got %q, want %q", reason, c.want) + } + } + if _, reason := singleTable([]origin{{0, 0}}); reason != notATable { + t.Errorf("no table: %q", reason) + } + if _, reason := singleTable([]origin{{1, 1}, {0, 0}, {2, 1}}); reason != severalTabs { + t.Errorf("several: %q", reason) + } + if oid, reason := singleTable([]origin{{0, 0}, {5, 1}, {5, 2}}); oid != 5 || reason != "" { + t.Errorf("one table: %d %q", oid, reason) + } +} + +func TestParsesCatalogRows(t *testing.T) { + row := func(attnum, name, ty string) []*string { + return []*string{str("public"), str("orders"), str("r"), str(attnum), str(name), str(ty), str("2,1"), str("t")} + } + m := parseTableMeta([][]*string{row("1", "id", "integer"), row("2", "Name", "text")}) + if m == nil { + t.Fatal("nil meta") + } + if !reflect.DeepEqual(m.key, []int16{2, 1}) || !m.primary { + t.Errorf("key %v primary %v", m.key, m.primary) + } + if m.columns[1] != (metaColumn{2, "Name", "text"}) { + t.Errorf("column %+v", m.columns[1]) + } + + noKey := []*string{str("s"), str("t"), str("r"), str("1"), str("a"), str("integer"), nil, nil} + m = parseTableMeta([][]*string{noKey}) + if m == nil || m.key != nil || m.primary { + t.Errorf("no key: %+v", m) + } + if parseTableMeta(nil) != nil { + t.Error("empty rows parsed") + } +} + +func joins(sql string) bool { return joinsTablesIn(sqlTokens(sql)) } +func union(sql string) bool { return hasUnion(sqlTokens(sql)) } + +func TestFindsJoinsAtAnyDepth(t *testing.T) { + yes := []string{ + "SELECT a.id, a.x FROM t a JOIN t b ON b.id = a.parent", + "select a.id from t a cross join t b", + "SELECT a.id FROM t a NATURAL JOIN t b", + "SELECT a.id, b.x FROM t a, t b WHERE a.id = b.id", + "SELECT * FROM (SELECT a.id, b.x FROM t a, t b) s ORDER BY 1", + "SELECT * FROM (SELECT a.id FROM t a JOIN t b USING (id)) s", + "SELECT a.id FROM t a, LATERAL (SELECT 1) l", + } + no := []string{ + "select a, b from t", + "select f(a, b) from t where x in (1,2)", + "select * from t order by a, b", + "SELECT a, b FROM t GROUP BY a, b LIMIT 5", + "SELECT extract(year FROM d), b FROM t", + "SELECT a FROM t WHERE b IN (SELECT x FROM u) AND c = 'x, y'", + "SELECT a FROM t FOR UPDATE OF t, u", + "SELECT a FROM \"join, x\" -- join\n WHERE b = 'join'", + "WITH c AS (SELECT 1) SELECT a FROM t", + "SELECT a, (SELECT max(b) FROM u WHERE u.a = t.a) FROM t", + } + for _, sql := range yes { + if !joins(sql) { + t.Errorf("no join found in %q", sql) + } + } + for _, sql := range no { + if joins(sql) { + t.Errorf("join found in %q", sql) + } + } +} + +func TestFindsUnionOutsideLiterals(t *testing.T) { + yes := []string{ + "SELECT 1 UNION SELECT 2", + "select a from t\nunion all select a from u", + "SELECT 'a''b' union SELECT 'c'", + } + no := []string{ + "SELECT 'union' FROM t", + `SELECT "union" FROM t`, + "SELECT 1 -- union\nFROM t", + "SELECT 1 /* a /* union */ b */ FROM t", + "SELECT $$ union $$, $q$ union $q$ FROM t", + `SELECT E'it\'s union' FROM t`, + "SELECT reunion, union_id, x$union FROM t WHERE a = $1", + "SELECT 'olá' AS união FROM t", + } + for _, sql := range yes { + if !union(sql) { + t.Errorf("no union found in %q", sql) + } + } + for _, sql := range no { + if union(sql) { + t.Errorf("union found in %q", sql) + } + } +} + +func TestStatementsOutsideTransactions(t *testing.T) { + outside := []string{ + "VACUUM t", "vacuum", "CREATE DATABASE x", "drop tablespace x", "ALTER SYSTEM SET x = 1", + "CREATE INDEX CONCURRENTLY i ON t (a)", "reindex table concurrently t", + "DROP INDEX CONCURRENTLY i", + } + inside := []string{"CREATE INDEX i ON t (a)", "ALTER TABLE t ADD c int", "SELECT 1", "DROP TABLE t"} + for _, sql := range outside { + if !mustRunOutsideTransaction(sql) { + t.Errorf("%q should run outside a transaction", sql) + } + } + for _, sql := range inside { + if mustRunOutsideTransaction(sql) { + t.Errorf("%q can run inside a transaction", sql) + } + } +} + +func TestMapsServerErrors(t *testing.T) { + e := mapError(errFromServer("42P01", 15)) + if e.Kind != apperr.Database || e.Code != "42P01" || e.Position == nil || *e.Position != 14 || + e.Detail != "d" || e.Hint != "h" || e.Message != "m" { + t.Errorf("%+v", e) + } + if e := mapError(errFromServer("57014", 0)); e.Kind != apperr.Cancelled || e.Position != nil { + t.Errorf("%+v", e) + } + for _, code := range []string{"28P01", "08006"} { + if e := mapError(errFromServer(code, 0)); e.Kind != apperr.Connection || e.Code != code { + t.Errorf("%+v", e) + } + } +} + +func TestRefusedConnectionsFailFast(t *testing.T) { + profile := model.DefaultProfile() + profile.Host = "127.0.0.1" + profile.Port = 1 + profile.User = "x" + profile.Database = "x" + started := time.Now() + s, err := Connect(context.Background(), profile, str("x")) + if err == nil { + s.Close() + t.Fatal("connected to a closed port") + } + t.Log(err) + if e := apperr.From(err); e.Kind != apperr.Connection { + t.Errorf("kind %q: %v", e.Kind, err) + } + if time.Since(started) > 20*time.Second { + t.Errorf("took %v", time.Since(started)) + } +} + +func errFromServer(code string, position int32) error { + return fmt.Errorf("wrapped: %w", &pgconn.PgError{ + Severity: "ERROR", Code: code, Message: "m", Detail: "d", Hint: "h", Position: position, + }) +} diff --git a/internal/drivers/postgres/integration_test.go b/internal/drivers/postgres/integration_test.go new file mode 100644 index 0000000..d937bf9 --- /dev/null +++ b/internal/drivers/postgres/integration_test.go @@ -0,0 +1,617 @@ +package postgres + +// Tests against a real server. They only run with LQ_PG_HOST set (and +// optionally LQ_PG_PORT, LQ_PG_USER, LQ_PG_PASSWORD, LQ_PG_DB). + +import ( + "context" + "os" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/fixtures" + "github.com/LowBloat/LowQuery/internal/model" +) + +func env(name, fallback string) string { + if v := os.Getenv(name); v != "" { + return v + } + return fallback +} + +func pgSession(t *testing.T) *Session { + t.Helper() + host := os.Getenv("LQ_PG_HOST") + if host == "" { + t.Skip("LQ_PG_HOST is not set") + } + profile := model.DefaultProfile() + profile.Name = "test" + profile.Host = host + profile.Port = 5432 + if p, err := strconv.ParseUint(os.Getenv("LQ_PG_PORT"), 10, 16); err == nil { + profile.Port = uint16(p) + } + profile.User = env("LQ_PG_USER", "postgres") + profile.Database = env("LQ_PG_DB", "postgres") + profile.SslMode = model.SslPrefer + var password *string + if pw := os.Getenv("LQ_PG_PASSWORD"); pw != "" { + password = &pw + } + s, err := Connect(context.Background(), profile, password) + if err != nil { + t.Fatalf("connection: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func execSQL(t *testing.T, s *Session, sql string, maxRows int) *model.ExecResult { + t.Helper() + r, err := s.Execute(context.Background(), model.ExecRequest{SQL: sql, MaxRows: maxRows}) + if err != nil { + t.Fatalf("%s: %v", sql, err) + } + return r +} + +func exec(t *testing.T, s *Session, sql string) *model.ExecResult { + t.Helper() + return execSQL(t, s, sql, 1000) +} + +func rowsOf(t *testing.T, s *Session, sql string) [][]string { + t.Helper() + return texts(exec(t, s, sql).Rows) +} + +// texts shows rows with NULL as "NULL", for comparisons. +func texts(rows []model.Row) [][]string { + out := make([][]string, len(rows)) + for i, row := range rows { + out[i] = make([]string, len(row)) + for j, v := range row { + if v == nil { + out[i][j] = "NULL" + } else { + out[i][j] = *v + } + } + } + return out +} + +func reason(t *testing.T, s *Session, sql string) string { + t.Helper() + r := exec(t, s, sql) + if r.Editable != nil { + t.Fatalf("%s should be read-only", sql) + } + if r.ReadOnlyReason == nil { + t.Fatalf("%s: no reason", sql) + } + return *r.ReadOnlyReason +} + +func TestPostgresTypesLimitsAndTransactions(t *testing.T) { + s := pgSession(t) + ctx := context.Background() + + r := execSQL(t, s, `SELECT 1::int2, 2::int4, 3::int8, 1.50::numeric(10,2), 'NaN'::numeric, + 12345678901234567890.123456789::numeric, 1.5::float4, 'Infinity'::float8, + true, 'texto'::text, NULL::text, '2024-02-29'::date, 'infinity'::date, + '2024-02-29 13:45:10.25'::timestamp, '1 year 2 mons 3 days 04:05:06'::interval, + '{"a": [1, 2]}'::jsonb, 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid, + '\xdeadbeef'::bytea, ARRAY[1, NULL, 3], ARRAY['a b', 'c'], + '[1,10)'::int4range, '192.168.0.1/24'::inet, '13:00:01'::time, + ROW(1, 'x'), 12.34::money`, 10) + want := []string{ + "1", "2", "3", "1.50", "NaN", "12345678901234567890.123456789", "1.5", "Infinity", "true", + "texto", "NULL", "2024-02-29", "infinity", "2024-02-29 13:45:10.25", + "1 year 2 mons 3 days 04:05:06", `{"a": [1, 2]}`, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", + `\xdeadbeef`, "{1,NULL,3}", `{"a b",c}`, "[1,10)", "192.168.0.1/24", "13:00:01", "(1,x)", + "12.34", + } + if got := texts(r.Rows); len(got) != 1 || !reflect.DeepEqual(got[0], want) { + t.Errorf("values:\n got %q\nwant %q", got, want) + } + kinds := []model.ValueKind{model.KindNumber, model.KindNumber, model.KindNumber, model.KindNumber} + for i, k := range kinds { + if r.Columns[i].Kind != k { + t.Errorf("column %d kind %q", i, r.Columns[i].Kind) + } + } + if r.Columns[18].TypeName != "int4[]" || r.Columns[2].TypeName != "int8" { + t.Errorf("type names %q %q", r.Columns[18].TypeName, r.Columns[2].TypeName) + } + + // Row limit via portal. + r = execSQL(t, s, "SELECT g FROM generate_series(1, 1000) g", 100) + if len(r.Rows) != 100 || !r.Truncated { + t.Errorf("limit: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + r = execSQL(t, s, "SELECT g FROM generate_series(1, 100) g", 100) + if r.Truncated { + t.Error("100 rows of 100 truncated") + } + + // Error position. + _, err := s.Execute(ctx, model.ExecRequest{SQL: "SELECT * FROM missing_table", MaxRows: 10}) + e := apperr.From(err) + if e == nil || e.Code != "42P01" || e.Position == nil || *e.Position != 14 { + t.Errorf("error: %+v", e) + } + + // Server NOTICE. + r = execSQL(t, s, "DO $$ BEGIN RAISE NOTICE 'olá %', 42; END $$", 0) + found := false + for _, n := range r.Notices { + found = found || strings.Contains(n, "olá 42") + } + if !found { + t.Errorf("notices %q", r.Notices) + } + + // Manual transaction: rollback undoes, commit persists. + execSQL(t, s, "CREATE TEMP TABLE lq_t (id int)", 0) + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + r = execSQL(t, s, "INSERT INTO lq_t VALUES (1), (2)", 0) + if r.RowsAffected == nil || *r.RowsAffected != 2 || !r.InTransaction { + t.Errorf("insert: %+v", r) + } + count := func() string { + t.Helper() + return texts(execSQL(t, s, "SELECT count(*) FROM lq_t", 0).Rows)[0][0] + } + if c := count(); c != "2" { + t.Errorf("count %s", c) + } + if st, err := s.EndTransaction(ctx, false); err != nil || st.InTransaction { + t.Errorf("rollback: %+v %v", st, err) + } + if c := count(); c != "0" { + t.Errorf("count after rollback %s", c) + } + execSQL(t, s, "INSERT INTO lq_t VALUES (3)", 0) + if _, err := s.EndTransaction(ctx, true); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(ctx, true); err != nil { + t.Fatal(err) + } + if c := count(); c != "1" { + t.Errorf("count after commit %s", c) + } + + // An error inside a manual transaction rolls back and frees the session. + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + execSQL(t, s, "INSERT INTO lq_t VALUES (4)", 0) + if _, err := s.Execute(ctx, model.ExecRequest{SQL: "SELECT 1/0"}); err == nil { + t.Error("division by zero succeeded") + } + if s.TxState().InTransaction { + t.Error("still in a transaction after the error") + } + if c := count(); c != "1" { + t.Errorf("count after error %s", c) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + + // Metadata. + schemas, err := s.ListSchemas(ctx) + if err != nil || !contains(schemas, "pg_catalog") { + t.Errorf("schemas %q %v", schemas, err) + } + objects, err := s.ListObjects(ctx, "pg_catalog") + if err != nil { + t.Fatal(err) + } + found = false + for _, o := range objects { + found = found || (o.Name == "pg_class" && o.Kind == "table") + } + if !found { + t.Error("pg_class not listed") + } + cols, err := s.ListColumns(ctx, "pg_catalog", "pg_class") + if err != nil { + t.Fatal(err) + } + found = false + for _, c := range cols { + found = found || c.Name == "oid" + } + if !found { + t.Error("pg_class.oid not listed") + } +} + +func contains(list []string, v string) bool { + for _, x := range list { + if x == v { + return true + } + } + return false +} + +func TestPostgresCancelInterruptsQuery(t *testing.T) { + s := pgSession(t) + done := make(chan error, 1) + go func() { + _, err := s.Execute(context.Background(), model.ExecRequest{SQL: "SELECT pg_sleep(30)"}) + done <- err + }() + time.Sleep(500 * time.Millisecond) + if err := s.Cancel(context.Background()); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Errorf("error %v", err) + } + case <-time.After(20 * time.Second): + t.Fatal("the query was not cancelled") + } +} + +func TestPostgresContextCancelsQuery(t *testing.T) { + s := pgSession(t) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + _, err := s.Execute(ctx, model.ExecRequest{SQL: "SELECT pg_sleep(30)"}) + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Errorf("error %v", err) + } + if got := rowsOf(t, s, "SELECT 1"); !reflect.DeepEqual(got, [][]string{{"1"}}) { + t.Errorf("after cancel: %q", got) + } +} + +func TestPostgresStream(t *testing.T) { + s := pgSession(t) + sink := make(chan drivers.StreamEvent, 10) + total, err := s.Stream(context.Background(), + "SELECT g, CASE WHEN g = 1 THEN decode(repeat('ab', 40000), 'hex') END FROM generate_series(1, 1234) g", sink) + close(sink) + if err != nil { + t.Fatal(err) + } + if total != 1234 { + t.Errorf("total %d", total) + } + var events []drivers.StreamEvent + for ev := range sink { + events = append(events, ev) + } + if len(events) != 4 || len(events[0].Columns) != 2 || len(events[1].Rows) != drivers.StreamBatch || + len(events[3].Rows) != 234 { + t.Fatalf("events: %d", len(events)) + } + if v := *events[1].Rows[0][1]; len(v) != 2+80000 || strings.Contains(v, "…") { + t.Errorf("binary value not in full: %d characters", len(v)) + } + if s.TxState().InTransaction { + t.Error("stream left a transaction open") + } +} + +func TestPostgresResultViewSQL(t *testing.T) { + fixtures.CheckView(t, pgSession(t), "postgres") +} + +func TestPostgresDDLSQL(t *testing.T) { + fixtures.CheckDDL(t, pgSession(t), "postgres", "public") +} + +func TestPostgresEditDetection(t *testing.T) { + s := pgSession(t) + ctx := context.Background() + for _, sql := range []string{ + "DROP VIEW IF EXISTS lq_edit_view", + "DROP TABLE IF EXISTS lq_edit_det, lq_edit_det2, lq_edit_nokey, lq_edit_uniq", + "CREATE TABLE lq_edit_det (id int PRIMARY KEY, name text, qty numeric(10,2))", + "CREATE TABLE lq_edit_det2 (id int PRIMARY KEY, det_id int)", + "CREATE TABLE lq_edit_nokey (a int, b text)", + "CREATE TABLE lq_edit_uniq (a int NOT NULL, b int NOT NULL, c text, UNIQUE (a, b))", + "CREATE VIEW lq_edit_view AS SELECT * FROM lq_edit_det", + "INSERT INTO lq_edit_det VALUES (1, 'x', 1.5)", + } { + exec(t, s, sql) + } + + r := exec(t, s, "SELECT name, upper(name) AS u, id, qty FROM lq_edit_det") + if r.ReadOnlyReason != nil || r.Editable == nil { + t.Fatalf("not editable: %v", r.ReadOnlyReason) + } + target := r.Editable + if target.Table != "lq_edit_det" || !reflect.DeepEqual(target.Schema, s.CurrentSchema()) || + !reflect.DeepEqual(target.Key, []int{2}) || target.Columns[1] != nil || + target.Columns[0].Name != "name" || target.Columns[3].TypeName != "numeric(10,2)" { + t.Errorf("target %+v", target) + } + + if target := exec(t, s, "SELECT c, b, a FROM lq_edit_uniq").Editable; target == nil || + !reflect.DeepEqual(target.Key, []int{2, 1}) { + t.Errorf("unique key: %+v", target) + } + + if got := reason(t, s, "SELECT d.id, d.name, e.id FROM lq_edit_det d JOIN lq_edit_det2 e ON e.det_id = d.id"); !strings.Contains(got, "several tables") { + t.Errorf("join: %q", got) + } + // Self-joins report one table OID for both aliases. + if got := reason(t, s, "SELECT a.id, a.name, b.qty FROM lq_edit_det a JOIN lq_edit_det b ON b.id = a.id"); got != joinsTables { + t.Errorf("self-join: %q", got) + } + if got := reason(t, s, "SELECT a.id, b.name FROM lq_edit_det a, lq_edit_det b"); got != joinsTables { + t.Errorf("comma join: %q", got) + } + if got := reason(t, s, "SELECT * FROM lq_edit_nokey"); got != "Read-only: table lq_edit_nokey has no primary key." { + t.Errorf("no key: %q", got) + } + if got := reason(t, s, "SELECT name FROM lq_edit_det"); got != "Read-only: add the primary key columns (id) to the query to edit rows." { + t.Errorf("missing key: %q", got) + } + if got := reason(t, s, "SELECT * FROM lq_edit_view"); got != notATable { + t.Errorf("view: %q", got) + } + if got := reason(t, s, "SELECT 1"); got != notATable { + t.Errorf("expression: %q", got) + } + // The server reports no source table for UNION columns; the scan + // covers servers that report the first branch's table. + if got := reason(t, s, "SELECT id, name FROM lq_edit_det UNION ALL SELECT id, name FROM lq_edit_det"); got != notATable && !strings.Contains(got, "several queries") { + t.Errorf("union: %q", got) + } + + // Detection inside a manual transaction (cache miss) keeps it usable. + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + r = exec(t, s, "SELECT id, det_id FROM lq_edit_det2") + if !r.InTransaction || r.Editable == nil || !reflect.DeepEqual(r.Editable.Key, []int{0}) { + t.Errorf("manual: %+v", r) + } + if got := rowsOf(t, s, "SELECT 1"); !reflect.DeepEqual(got, [][]string{{"1"}}) { + t.Errorf("after detection: %q", got) + } + if !s.TxState().InTransaction { + t.Error("transaction ended") + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(ctx, true); err != nil { + t.Fatal(err) + } + + // DDL clears the cache: a key added later is seen. + exec(t, s, "ALTER TABLE lq_edit_nokey ADD PRIMARY KEY (a)") + if target := exec(t, s, "SELECT b, a FROM lq_edit_nokey").Editable; target == nil || + !reflect.DeepEqual(target.Key, []int{1}) { + t.Errorf("after DDL: %+v", target) + } + + exec(t, s, "DROP VIEW lq_edit_view") + exec(t, s, "DROP TABLE lq_edit_det, lq_edit_det2, lq_edit_nokey, lq_edit_uniq") +} + +func update(key string, values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpUpdate, Key: []*string{str(key)}, Values: values} +} + +func insert(key string, value *string) model.RowChange { + values := []model.CellValue{cellValue(0, str(key))} + if value != nil { + values = append(values, cellValue(1, value)) + } + return model.RowChange{Op: model.OpInsert, Values: values} +} + +func apply(s *Session, target *model.EditTarget, changes ...model.RowChange) (*model.ApplyResult, error) { + return s.ApplyChanges(context.Background(), model.ApplyRequest{Target: *target, Changes: changes}) +} + +func TestPostgresEditRoundTripsTypes(t *testing.T) { + s := pgSession(t) + exec(t, s, "DROP TABLE IF EXISTS lq_edit_types") + exec(t, s, `CREATE TABLE lq_edit_types (id serial PRIMARY KEY, n numeric(12,3), nn numeric, + i2 smallint, i4 integer, i8 bigint, f4 real, f8 double precision, b boolean, + d date, ts timestamp(6), tstz timestamptz, tm time, ttz timetz, iv interval, + t text, vc varchar(20), ch char(5), by bytea, arr int[], tarr text[], j jsonb, + u uuid, m money, ip inet, tsarr timestamptz[])`) + exec(t, s, `INSERT INTO lq_edit_types (n, nn, i2, i4, i8, f4, f8, b, d, ts, tstz, tm, ttz, iv, + t, vc, ch, by, arr, tarr, j, u, m, ip, tsarr) + VALUES (12345.678, 'NaN', -32768, 2147483647, -9223372036854775808, 1.1, 0.1, true, + '2024-02-29', '2024-02-29 13:45:10.123456', '2024-02-29 13:45:10.25+00', + '23:59:59.999999', '13:00:01+05:30', '1 year 2 mons -3 days 04:05:06.5', + E'it''s\n"quoted" \\ end', 'abc', 'ab', '\xdeadbeef00', '{1,NULL,3}', + '{"a b","c,d","","NULL",NULL}', '{"a": [1, 2]}', + 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 12.34::numeric::money, + '192.168.0.1/24', '{"2024-01-01 00:00:00+00","1999-12-31 23:59:59.5-03"}')`) + exec(t, s, "INSERT INTO lq_edit_types DEFAULT VALUES") + + const sql = "SELECT * FROM lq_edit_types ORDER BY id" + before := exec(t, s, sql) + target := before.Editable + if target == nil || !reflect.DeepEqual(target.Key, []int{0}) { + t.Fatalf("target %+v", target) + } + var changes []model.RowChange + for _, row := range before.Rows { + var values []model.CellValue + for i := 1; i < len(row); i++ { + values = append(values, cellValue(i, row[i])) + } + changes = append(changes, update(*row[0], values...)) + } + r, err := apply(s, target, changes...) + if err != nil { + t.Fatalf("apply: %v", err) + } + if r.Updated != 2 || r.InTransaction { + t.Errorf("result %+v", r) + } + if after := exec(t, s, sql); !reflect.DeepEqual(texts(after.Rows), texts(before.Rows)) { + t.Errorf("values changed:\n%q\n%q", texts(before.Rows), texts(after.Rows)) + } + + // The stored values themselves did not move. + check := rowsOf(t, s, `SELECT count(*) FROM lq_edit_types WHERE n = 12345.678 AND nn = 'NaN' + AND f4 = 1.1::real AND f8 = 0.1::float8 + AND tstz = '2024-02-29 13:45:10.25+00' AND ttz = '13:00:01+05:30' + AND iv = '1 year 2 mons -3 days 04:05:06.5'::interval + AND t = E'it''s\n"quoted" \\ end' AND by = '\xdeadbeef00'::bytea + AND m = 12.34::numeric::money AND ch = 'ab' + AND tarr = '{"a b","c,d","","NULL",NULL}'::text[] + AND tsarr[2] = '1999-12-31 23:59:59.5-03'`) + if !reflect.DeepEqual(check, [][]string{{"1"}}) { + t.Errorf("check %q", check) + } + + // NULL in one row, a value in the row of NULLs. + id := *before.Rows[0][0] + if _, err := apply(s, target, update(id, cellValue(15, nil), cellValue(8, str("false")))); err != nil { + t.Fatal(err) + } + if got := rowsOf(t, s, "SELECT t, b FROM lq_edit_types WHERE id = "+id); !reflect.DeepEqual(got, [][]string{{"NULL", "false"}}) { + t.Errorf("null: %q", got) + } + id2 := *before.Rows[1][0] + if _, err := apply(s, target, update(id2, cellValue(18, str(`\x00ff`)))); err != nil { + t.Fatal(err) + } + if got := rowsOf(t, s, "SELECT by FROM lq_edit_types WHERE id = "+id2); !reflect.DeepEqual(got, [][]string{{`\x00ff`}}) { + t.Errorf("bytea: %q", got) + } + + // Too long for varchar(20) fails instead of being cut. + _, err = apply(s, target, update(id, cellValue(16, str(strings.Repeat("x", 21))))) + if e := apperr.From(err); e == nil || e.Code != "22001" { + t.Errorf("long value: %v", err) + } + + exec(t, s, "DROP TABLE lq_edit_types") +} + +func TestPostgresEditChangesAndTransactions(t *testing.T) { + s := pgSession(t) + ctx := context.Background() + exec(t, s, `DROP TABLE IF EXISTS "lq_edit_Mixed Case", lq_edit_defaults`) + exec(t, s, `CREATE TABLE "lq_edit_Mixed Case" ("Key Col" int PRIMARY KEY, + "Value ""Q""" text, created int DEFAULT 7)`) + exec(t, s, "CREATE TABLE lq_edit_defaults (id serial PRIMARY KEY, v int DEFAULT 5)") + + const sel = `SELECT "Key Col", "Value ""Q""" FROM "lq_edit_Mixed Case" ORDER BY 1` + target := exec(t, s, sel).Editable + if target == nil || target.Table != "lq_edit_Mixed Case" || target.Columns[1].Name != `Value "Q"` { + t.Fatalf("target %+v", target) + } + + r, err := apply(s, target, insert("1", str("one")), insert("2", str("two")), insert("3", nil)) + if err != nil || r.Inserted != 3 { + t.Fatalf("insert: %+v %v", r, err) + } + if got := rowsOf(t, s, `SELECT created FROM "lq_edit_Mixed Case" WHERE "Key Col" = 3`); !reflect.DeepEqual(got, [][]string{{"7"}}) { + t.Errorf("default: %q", got) + } + + r, err = apply(s, target, update("1", cellValue(1, str("uno"))), + model.RowChange{Op: model.OpDelete, Key: []*string{str("2")}}) + if err != nil || r.Updated != 1 || r.Deleted != 1 { + t.Fatalf("update and delete: %+v %v", r, err) + } + expected := [][]string{{"1", "uno"}, {"3", "NULL"}} + if got := rowsOf(t, s, sel); !reflect.DeepEqual(got, expected) { + t.Errorf("rows %q", got) + } + + // A key that matches nothing undoes the whole batch. + _, err = apply(s, target, update("1", cellValue(1, str("changed"))), update("99", cellValue(1, str("x")))) + if e := apperr.From(err); e == nil || e.Kind != apperr.Database || + !strings.HasPrefix(e.Message, "Row 2 was not saved: 0 rows matched") { + t.Errorf("missing key: %v", err) + } + if got := rowsOf(t, s, sel); !reflect.DeepEqual(got, expected) { + t.Errorf("rows after failed batch %q", got) + } + + // Server errors keep their code. + _, err = apply(s, target, insert("1", str("dup"))) + if e := apperr.From(err); e == nil || e.Code != "23505" || !strings.HasPrefix(e.Message, "Row 1 was not saved") { + t.Errorf("duplicate: %v", err) + } + if got := rowsOf(t, s, sel); !reflect.DeepEqual(got, expected) { + t.Errorf("rows after duplicate %q", got) + } + + // Manual commit: the edits open a transaction and stay in it. + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + r, err = apply(s, target, update("1", cellValue(1, str("manual")))) + if err != nil || !r.InTransaction || !s.TxState().InTransaction { + t.Fatalf("manual: %+v %v", r, err) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + if got := rowsOf(t, s, sel); !reflect.DeepEqual(got, expected) { + t.Errorf("rows after rollback %q", got) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + + // A failed batch inside an open transaction keeps the transaction and + // its earlier work. + exec(t, s, `UPDATE "lq_edit_Mixed Case" SET created = 8 WHERE "Key Col" = 3`) + if !s.TxState().InTransaction { + t.Fatal("no transaction") + } + _, err = apply(s, target, update("3", cellValue(1, str("three"))), update("99", cellValue(1, str("x")))) + if e := apperr.From(err); e == nil || e.Kind != apperr.Database { + t.Errorf("failed batch: %v", err) + } + if !s.TxState().InTransaction { + t.Error("transaction lost") + } + if _, err := s.EndTransaction(ctx, true); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(ctx, true); err != nil { + t.Fatal(err) + } + if got := rowsOf(t, s, `SELECT created, "Value ""Q""" FROM "lq_edit_Mixed Case" WHERE "Key Col" = 3`); !reflect.DeepEqual(got, [][]string{{"8", "NULL"}}) { + t.Errorf("after commit: %q", got) + } + + // No values: all defaults. + target = exec(t, s, "SELECT id, v FROM lq_edit_defaults").Editable + if target == nil { + t.Fatal("not editable") + } + r, err = apply(s, target, model.RowChange{Op: model.OpInsert}) + if err != nil || r.Inserted != 1 { + t.Fatalf("defaults: %+v %v", r, err) + } + if got := rowsOf(t, s, "SELECT v FROM lq_edit_defaults"); !reflect.DeepEqual(got, [][]string{{"5"}}) { + t.Errorf("defaults: %q", got) + } + + exec(t, s, `DROP TABLE "lq_edit_Mixed Case", lq_edit_defaults`) +} diff --git a/internal/drivers/postgres/postgres.go b/internal/drivers/postgres/postgres.go new file mode 100644 index 0000000..3167a4b --- /dev/null +++ b/internal/drivers/postgres/postgres.go @@ -0,0 +1,1103 @@ +// Package postgres is the PostgreSQL session, over the extended query +// protocol of pgconn. +// +// - Each statement is prepared first, which gives the column types without +// executing it. Queries that return rows run in a portal with a row limit +// (Execute with max rows), so a SELECT on a huge table does not pull +// everything over the network. +// - Values arrive in binary format and are formatted as the server would +// print them (value.go). +// - Server NOTICE/WARNING messages (RAISE NOTICE) are collected and +// returned along with the result. +// - Cancellation uses the server's cancel protocol, on a separate +// connection, without waiting for the running query. +// - A SELECT is editable in the grid when the row description (table OID +// and attribute number of each column) points to one table whose key is +// in the result. Edits are sent as text-format parameters, so the server +// parses them with each column's own input function. +package postgres + +import ( + "context" + "crypto/tls" + "errors" + "math" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgproto3" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +// Session is one PostgreSQL connection. +type Session struct { + // mu serializes every call except Cancel. + mu sync.Mutex + conn *pgconn.PgConn + + stateMu sync.Mutex + state model.TxState + + noticeMu sync.Mutex + notices []string + + // Catalog data of tables seen in results, by table OID. + tables map[uint32]*tableMeta + // Types read from the catalog, by OID. + types typeSet + stmtSeq uint64 + + serverVersion string + currentUser *string + currentSchema *string +} + +var _ drivers.Session = (*Session)(nil) + +// formatBinary is the binary format code of the wire protocol. +const formatBinary int16 = 1 + +const closedMessage = "The connection to the server was closed." + +// cancelGrace is how long a cancelled call waits for the server to stop +// before the connection is cut. +const cancelGrace = 15 * time.Second + +// Connect opens a session. password nil means none. +func Connect(ctx context.Context, profile model.ConnectionProfile, password *string) (*Session, error) { + // Only the profile decides where and how to connect: the PG* environment + // variables and pgpass are not read. + cfg, err := pgconn.ParseConfig("sslmode=disable") + if err != nil { + return nil, apperr.Connectionf("%v", err) + } + host := strings.TrimSpace(profile.Host) + port := profile.Port + if port == 0 { + port = 5432 + } + cfg.Host = host + cfg.Port = port + cfg.Database = strings.TrimSpace(profile.Database) + cfg.User = strings.TrimSpace(profile.User) + cfg.Password = "" + if password != nil { + cfg.Password = *password + } + cfg.ConnectTimeout = 15 * time.Second + dialer := &net.Dialer{KeepAlive: 60 * time.Second} + cfg.DialFunc = dialer.DialContext + cfg.RuntimeParams = map[string]string{ + "application_name": "LowQuery", + "client_encoding": "UTF8", + } + cfg.ValidateConnect = nil + cfg.AfterConnect = nil + cfg.SSLNegotiation = "postgres" + cfg.MinProtocolVersion = "3.0" + cfg.MaxProtocolVersion = "3.0" + cfg.ChannelBinding = "prefer" + cfg.RequireAuth = "" + cfg.TLSConfig, cfg.Fallbacks = tlsConfigs(profile.SslMode, host, port) + + s := &Session{ + state: model.TxState{Autocommit: true}, + tables: map[uint32]*tableMeta{}, + types: typeSet{}, + } + cfg.OnNotice = s.onNotice + + conn, err := pgconn.ConnectConfig(ctx, cfg) + if err != nil { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + return nil, mapError(err) + } + s.conn = conn + + res, err := conn.Exec(context.Background(), + "SELECT current_setting('server_version'), current_user::text, current_schema()::text").ReadAll() + if err == nil && (len(res) == 0 || len(res[0].Rows) == 0) { + err = errors.New("the server did not report its version") + } + if err != nil { + closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _ = conn.Close(closeCtx) + cancel() + return nil, mapError(err) + } + row := res[0].Rows[0] + text := func(i int) *string { + if i < len(row) && row[i] != nil { + v := string(row[i]) + return &v + } + return nil + } + if v := text(0); v != nil { + s.serverVersion = "PostgreSQL " + *v + } else { + s.serverVersion = "PostgreSQL" + } + s.currentUser = text(1) + s.currentSchema = text(2) + return s, nil +} + +// tlsConfigs follows libpq: verify-full checks the chain and the host name; +// prefer and require encrypt without validating the certificate, and +// prefer falls back to a plain connection. +func tlsConfigs(mode model.SslMode, host string, port uint16) (*tls.Config, []*pgconn.FallbackConfig) { + switch mode { + case model.SslDisable: + return nil, nil + case model.SslVerifyFull: + return &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}, nil + } + insecure := &tls.Config{ServerName: host, InsecureSkipVerify: true, MinVersion: tls.VersionTLS12} + if mode == model.SslRequire { + return insecure, nil + } + return insecure, []*pgconn.FallbackConfig{{Host: host, Port: port}} +} + +func (s *Session) onNotice(_ *pgconn.PgConn, n *pgconn.Notice) { + // 25001/25P01: redundant BEGIN/ROLLBACK warnings, produced by the + // internal transaction handling. + if n.Code == "25001" || n.Code == "25P01" { + return + } + s.noticeMu.Lock() + s.notices = append(s.notices, n.Severity+": "+n.Message) + s.noticeMu.Unlock() +} + +func (s *Session) pushNotice(text string) { + s.noticeMu.Lock() + s.notices = append(s.notices, text) + s.noticeMu.Unlock() +} + +func (s *Session) takeNotices() []string { + s.noticeMu.Lock() + defer s.noticeMu.Unlock() + out := s.notices + s.notices = nil + if out == nil { + out = []string{} + } + return out +} + +func (s *Session) Engine() model.Engine { return model.Postgres } +func (s *Session) ServerVersion() string { return s.serverVersion } +func (s *Session) CurrentUser() *string { return s.currentUser } +func (s *Session) CurrentSchema() *string { return s.currentSchema } +func (s *Session) isClosed() bool { return s.conn.IsClosed() } +func closedErr() *apperr.Error { return apperr.New(apperr.Connection, closedMessage) } +func (s *Session) setInTransaction(on bool) { + s.stateMu.Lock() + s.state.InTransaction = on + s.stateMu.Unlock() +} + +func (s *Session) TxState() model.TxState { + s.stateMu.Lock() + defer s.stateMu.Unlock() + return s.state +} + +// watch sends a cancel request to the server when ctx is done before the +// returned stop is called. If the server does not answer within +// cancelGrace, the connection is cut. Every call runs pgconn with a +// background context, so this is the only cancellation path. +func (s *Session) watch(ctx context.Context) (stop func()) { + if ctx.Done() == nil { + return func() {} + } + done := make(chan struct{}) + finished := make(chan struct{}) + var cut atomic.Bool + go func() { + defer close(finished) + select { + case <-done: + return + case <-ctx.Done(): + } + cancelCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + _ = s.conn.CancelRequest(cancelCtx) + cancel() + select { + case <-done: + case <-time.After(cancelGrace): + cut.Store(true) + _ = s.conn.Conn().SetDeadline(time.Now()) + } + }() + return func() { + close(done) + <-finished + if cut.Load() { + _ = s.conn.Conn().SetDeadline(time.Time{}) + } + } +} + +// simple runs statements through the simple query protocol. +func (s *Session) simple(sql string) error { + _, err := s.conn.Exec(context.Background(), sql).ReadAll() + if err != nil { + return s.mapErr(err) + } + return nil +} + +// textRows runs a query with text parameters and returns its values as +// text; nil is NULL. +func (s *Session) textRows(sql string, params ...string) ([][]*string, error) { + values := make([][]byte, len(params)) + for i, p := range params { + values[i] = []byte(p) + } + res := s.conn.ExecParams(context.Background(), sql, values, nil, nil, nil).Read() + if res.Err != nil { + return nil, s.mapErr(res.Err) + } + return textValues(res.Rows), nil +} + +func textValues(rows [][][]byte) [][]*string { + out := make([][]*string, len(rows)) + for i, row := range rows { + cells := make([]*string, len(row)) + for j, v := range row { + if v != nil { + t := string(v) + cells[j] = &t + } + } + out[i] = cells + } + return out +} + +func cellText(row []*string, i int) string { + if v := cell(row, i); v != nil { + return *v + } + return "" +} + +// mustRunOutsideTransaction lists the statements the server rejects inside +// a transaction block. +func mustRunOutsideTransaction(sql string) bool { + kw := drivers.FirstKeywords(sql, 2) + first, second := "", "" + if len(kw) > 0 { + first = kw[0] + } + if len(kw) > 1 { + second = kw[1] + } + switch { + case first == "VACUUM": + return true + case (first == "CREATE" || first == "DROP") && (second == "DATABASE" || second == "TABLESPACE"): + return true + case first == "ALTER" && second == "SYSTEM": + return true + case first == "CREATE" || first == "DROP" || first == "REINDEX": + return strings.Contains(asciiOnlyUpper(sql), "CONCURRENTLY") + } + return false +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.isClosed() { + return nil, closedErr() + } + stop := s.watch(ctx) + defer stop() + + s.takeNotices() + started := time.Now() + state := s.TxState() + keywords := drivers.FirstKeywords(req.SQL, 2) + first, second := "", "" + if len(keywords) > 0 { + first = keywords[0] + } + if len(keywords) > 1 { + second = keywords[1] + } + + result, err := s.run(ctx, req, state) + + // Updates the transaction state based on what was executed. + inTransaction := s.TxState().InTransaction + switch { + case err == nil && (first == "BEGIN" || first == "START"): + s.setInTransaction(true) + case err == nil && (first == "COMMIT" || first == "ROLLBACK" || first == "END" || first == "ABORT"): + // ROLLBACK TO SAVEPOINT keeps the transaction open. + if second != "TO" { + s.setInTransaction(false) + } + case err != nil && inTransaction: + // An error inside the block invalidates the whole transaction: the + // only option is to roll it back. Doing it here keeps the next + // statement from failing with "current transaction is aborted". + if !s.isClosed() { + _ = s.simple("ROLLBACK") + } + s.setInTransaction(false) + s.pushNotice("The transaction was rolled back because of the error.") + } + // DDL (or undoing it) may change keys and column types. + switch first { + case "CREATE", "ALTER", "DROP", "ROLLBACK", "ABORT", "DO", "CALL", "IMPORT": + clear(s.tables) + default: + if err != nil && inTransaction { + clear(s.tables) + } + } + + if err != nil { + if ctx.Err() != nil && apperr.From(err).Kind == apperr.Connection { + return nil, apperr.CancelledErr() + } + return nil, err + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.Notices = s.takeNotices() + result.InTransaction = s.TxState().InTransaction + result.Normalize() + return result, nil +} + +func isTxControl(word string) bool { + switch word { + case "BEGIN", "START", "COMMIT", "ROLLBACK", "END", "ABORT", "SAVEPOINT", "RELEASE": + return true + } + return false +} + +func (s *Session) run(ctx context.Context, req model.ExecRequest, state model.TxState) (*model.ExecResult, error) { + stmt, err := s.prepare(req.SQL) + if err != nil { + return nil, err + } + manual := !state.Autocommit || state.InTransaction + + if len(stmt.Fields) == 0 { + if !state.Autocommit && !state.InTransaction && !mustRunOutsideTransaction(req.SQL) { + kw := drivers.FirstKeywords(req.SQL, 1) + if len(kw) == 0 || !isTxControl(kw[0]) { + if err := s.simple("BEGIN"); err != nil { + s.closeStatement(stmt.Name) + return nil, err + } + s.setInTransaction(true) + } + } + out, err := s.execPortal(stmt.Name, 0, nil) + if err != nil { + return nil, err + } + affected := uint64(out.tag.RowsAffected()) + return &model.ExecResult{RowsAffected: &affected}, nil + } + + columns := s.columns(stmt.Fields) + if manual && !state.InTransaction { + if err := s.simple("BEGIN"); err != nil { + s.closeStatement(stmt.Name) + return nil, err + } + s.setInTransaction(true) + } + + // In autocommit the portal runs in the implicit transaction of its own + // Sync, committed right after; in manual mode it runs inside the user's + // transaction. + var limit uint32 + if req.MaxRows > 0 { + limit = uint32(min(int64(req.MaxRows)+1, math.MaxInt32)) + } + dec := s.decoder(drivers.BinaryLimit(ctx, binaryPreviewBytes)) + oids := fieldOIDs(stmt.Fields) + rows := make([]model.Row, 0) + var decodeErr error + _, err = s.execPortal(stmt.Name, limit, func(values [][]byte) { + if decodeErr != nil { + return + } + row, err := dec.row(oids, values) + if err != nil { + decodeErr = apperr.Internalf("%v", err) + return + } + rows = append(rows, row) + }) + if err != nil { + return nil, err + } + if decodeErr != nil { + return nil, decodeErr + } + truncated := req.MaxRows > 0 && len(rows) > req.MaxRows + if truncated { + rows = rows[:req.MaxRows] + } + origins := make([]origin, len(stmt.Fields)) + for i, f := range stmt.Fields { + origins[i] = origin{table: f.TableOID, column: int16(f.TableAttributeNumber)} + } + result := &model.ExecResult{Columns: columns, Rows: rows, Truncated: truncated} + if target, reason := s.editTarget(req.SQL, origins); target != nil { + result.Editable = target + } else { + result.ReadOnlyReason = &reason + } + return result, nil +} + +func fieldOIDs(fields []pgconn.FieldDescription) []uint32 { + oids := make([]uint32, len(fields)) + for i, f := range fields { + oids[i] = f.DataTypeOID + } + return oids +} + +func (s *Session) columns(fields []pgconn.FieldDescription) []model.ColumnInfo { + columns := make([]model.ColumnInfo, len(fields)) + for i, f := range fields { + columns[i] = model.ColumnInfo{ + Name: f.Name, + TypeName: s.types.label(f.DataTypeOID), + Kind: s.types.valueKind(f.DataTypeOID), + } + } + return columns +} + +func (s *Session) decoder(limit int) *decoder { + return &decoder{types: s.types, limit: limit} +} + +// prepare parses and describes a statement under a new name, and reads +// the catalog for any result type the session does not know yet. +func (s *Session) prepare(sql string) (*pgconn.StatementDescription, error) { + s.stmtSeq++ + name := "lq_" + strconv.FormatUint(s.stmtSeq, 10) + desc, err := s.conn.Prepare(context.Background(), name, sql, nil) + if err != nil { + var pe *pgconn.PrepareError + if errors.As(err, &pe) && pe.ParseComplete { + s.closeStatement(name) + } + return nil, s.mapErr(err) + } + if err := s.resolveTypes(fieldOIDs(desc.Fields)); err != nil { + s.closeStatement(name) + return nil, err + } + return desc, nil +} + +func (s *Session) closeStatement(name string) { + if !s.isClosed() { + _ = s.conn.Deallocate(context.Background(), name) + } +} + +type portalOutcome struct { + tag pgconn.CommandTag + suspended bool +} + +// execPortal binds the prepared statement to the unnamed portal, runs it +// up to maxRows rows (0 = all) and closes the statement. Rows go to onRow +// while they arrive; their values are only valid during the call. +func (s *Session) execPortal(stmtName string, maxRows uint32, onRow func([][]byte)) (portalOutcome, error) { + fe := s.conn.Frontend() + fe.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ResultFormatCodes: []int16{formatBinary}}) + fe.SendExecute(&pgproto3.Execute{MaxRows: maxRows}) + fe.SendSync(&pgproto3.Sync{}) + // The statement is closed after its own Sync, so it goes away even when + // the execution fails. + fe.SendClose(&pgproto3.Close{ObjectType: 'S', Name: stmtName}) + fe.SendSync(&pgproto3.Sync{}) + if err := fe.Flush(); err != nil { + return portalOutcome{}, s.broken(err) + } + return s.readResults(2, onRow) +} + +// readResults reads messages until the given number of ReadyForQuery and +// returns the first server error. +func (s *Session) readResults(syncs int, onRow func([][]byte)) (portalOutcome, error) { + var out portalOutcome + var serverErr *pgconn.PgError + completed := false + for ready := 0; ready < syncs; { + msg, err := s.conn.ReceiveMessage(context.Background()) + if err != nil { + return out, s.broken(err) + } + switch m := msg.(type) { + case *pgproto3.DataRow: + if onRow != nil { + onRow(m.Values) + } + case *pgproto3.CommandComplete: + if !completed { + out.tag = pgconn.NewCommandTag(string(m.CommandTag)) + completed = true + } + case *pgproto3.PortalSuspended: + out.suspended = true + completed = true + case *pgproto3.ErrorResponse: + if serverErr == nil { + serverErr = pgconn.ErrorResponseToPgError(m) + } + case *pgproto3.CopyInResponse: + fe := s.conn.Frontend() + fe.Send(&pgproto3.CopyFail{Message: "COPY FROM STDIN is not supported here."}) + if err := fe.Flush(); err != nil { + return out, s.broken(err) + } + case *pgproto3.ReadyForQuery: + ready++ + } + } + if serverErr != nil { + return out, fromPgError(serverErr) + } + return out, nil +} + +// broken closes a connection whose protocol state is lost after a network +// failure. +func (s *Session) broken(err error) error { + if !s.isClosed() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + _ = s.conn.Close(ctx) + cancel() + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return fromPgError(pgErr) + } + return closedErr() +} + +// mapErr maps an error of a call on the open session. +func (s *Session) mapErr(err error) error { + e := mapError(err) + if e.Kind == apperr.Connection && e.Code == "" && s.isClosed() { + return closedErr() + } + return e +} + +// mapError turns pgconn errors into the app error: server errors keep their +// SQLSTATE, position, detail and hint. +func mapError(err error) *apperr.Error { + var ae *apperr.Error + if errors.As(err, &ae) { + return ae + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return fromPgError(pgErr) + } + if errors.Is(err, pgconn.ErrConnClosed) { + return closedErr() + } + return apperr.New(apperr.Connection, err.Error()) +} + +func fromPgError(pgErr *pgconn.PgError) *apperr.Error { + kind := apperr.Database + if pgErr.Code == "57014" { + kind = apperr.Cancelled + } + // Authentication (class 28) and connection (08) errors are not SQL + // errors. + if strings.HasPrefix(pgErr.Code, "28") || strings.HasPrefix(pgErr.Code, "08") { + kind = apperr.Connection + } + e := &apperr.Error{ + Kind: kind, + Message: pgErr.Message, + Code: pgErr.Code, + Detail: pgErr.Detail, + Hint: pgErr.Hint, + } + if pgErr.Position > 0 { + p := int(pgErr.Position) - 1 + e.Position = &p + } + return e +} + +func (s *Session) Cancel(ctx context.Context) error { + if err := s.conn.CancelRequest(ctx); err != nil { + return mapError(err) + } + return nil +} + +func (s *Session) SetAutocommit(ctx context.Context, on bool) (model.TxState, error) { + s.mu.Lock() + defer s.mu.Unlock() + if on && s.TxState().InTransaction { + // Switching back to autocommit commits pending work, as JDBC + // clients do. + stop := s.watch(ctx) + err := s.endTransaction(true) + stop() + if err != nil { + return s.TxState(), err + } + } + s.stateMu.Lock() + defer s.stateMu.Unlock() + s.state.Autocommit = on + return s.state, nil +} + +func (s *Session) EndTransaction(ctx context.Context, commit bool) (model.TxState, error) { + s.mu.Lock() + defer s.mu.Unlock() + stop := s.watch(ctx) + defer stop() + if err := s.endTransaction(commit); err != nil { + return s.TxState(), err + } + return s.TxState(), nil +} + +func (s *Session) endTransaction(commit bool) error { + if s.isClosed() { + return closedErr() + } + sql := "ROLLBACK" + if commit { + sql = "COMMIT" + } + if err := s.simple(sql); err != nil { + return err + } + if !commit { + clear(s.tables) + } + s.setInTransaction(false) + return nil +} + +// begin locks the session for a metadata call and watches ctx. +func (s *Session) begin(ctx context.Context) (func(), error) { + s.mu.Lock() + if s.isClosed() { + s.mu.Unlock() + return nil, closedErr() + } + stop := s.watch(ctx) + return func() { + stop() + s.mu.Unlock() + }, nil +} + +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + rows, err := s.textRows(`SELECT nspname::text FROM pg_namespace + WHERE nspname NOT LIKE 'pg\_toast%' AND nspname NOT LIKE 'pg\_temp\_%' + ORDER BY nspname IN ('pg_catalog', 'information_schema'), nspname`) + if err != nil { + return nil, err + } + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = cellText(r, 0) + } + return out, nil +} + +func (s *Session) ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) { + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + rows, err := s.textRows(`SELECT c.relname::text, + CASE c.relkind WHEN 'r' THEN 'table' WHEN 'p' THEN 'table' + WHEN 'v' THEN 'view' WHEN 'm' THEN 'matview' + WHEN 'f' THEN 'foreign' ELSE 'sequence' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = $1 AND c.relkind IN ('r','p','v','m','f','S') + AND NOT c.relispartition + UNION ALL + SELECT p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')', + CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END + FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = $1 AND p.prokind IN ('f','p') + ORDER BY 2, 1`, schema) + if err != nil { + return nil, err + } + out := make([]model.DbObject, len(rows)) + for i, r := range rows { + out[i] = model.DbObject{Name: cellText(r, 0), Kind: cellText(r, 1)} + } + return out, nil +} + +func (s *Session) ListColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) { + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + rows, err := s.textRows(`SELECT a.attname::text, format_type(a.atttypid, a.atttypmod), + NOT a.attnotnull, + COALESCE(a.attnum = ANY(i.indkey::int2[]), false), + pg_get_expr(d.adbin, d.adrelid) + FROM pg_attribute a + JOIN pg_class c ON c.oid = a.attrelid + JOIN pg_namespace n ON n.oid = c.relnamespace + LEFT JOIN pg_index i ON i.indrelid = c.oid AND i.indisprimary + LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped + ORDER BY a.attnum`, schema, table) + if err != nil { + return nil, err + } + out := make([]model.DbColumn, len(rows)) + for i, r := range rows { + out[i] = model.DbColumn{ + Name: cellText(r, 0), + TypeName: cellText(r, 1), + Nullable: cellText(r, 2) == "t", + PrimaryKey: cellText(r, 3) == "t", + DefaultValue: cell(r, 4), + } + } + return out, nil +} + +// Stream reads the rows through a portal in a read-only snapshot, one +// batch at a time. +func (s *Session) Stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + end, err := s.begin(ctx) + if err != nil { + return 0, err + } + defer end() + total, err := s.stream(ctx, sql, sink) + if err != nil && ctx.Err() != nil && apperr.From(err).Kind == apperr.Connection { + return total, apperr.CancelledErr() + } + return total, err +} + +func send(ctx context.Context, sink chan<- drivers.StreamEvent, ev drivers.StreamEvent) bool { + select { + case sink <- ev: + return true + case <-ctx.Done(): + return false + } +} + +func (s *Session) stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + stmt, err := s.prepare(sql) + if err != nil { + return 0, err + } + if !send(ctx, sink, drivers.StreamEvent{Columns: s.columns(stmt.Fields)}) { + s.closeStatement(stmt.Name) + return 0, apperr.CancelledErr() + } + if err := s.simple("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY"); err != nil { + s.closeStatement(stmt.Name) + return 0, err + } + fail := func(err error) error { + if !s.isClosed() { + _ = s.simple("ROLLBACK") + } + s.closeStatement(stmt.Name) + return err + } + + dec := s.decoder(drivers.BinaryLimit(drivers.WithFullValues(ctx), binaryPreviewBytes)) + oids := fieldOIDs(stmt.Fields) + fe := s.conn.Frontend() + fe.SendBind(&pgproto3.Bind{PreparedStatement: stmt.Name, ResultFormatCodes: []int16{formatBinary}}) + var total uint64 + for { + fe.SendExecute(&pgproto3.Execute{MaxRows: drivers.StreamBatch}) + fe.SendSync(&pgproto3.Sync{}) + if err := fe.Flush(); err != nil { + return total, s.broken(err) + } + batch := make([]model.Row, 0, drivers.StreamBatch) + var decodeErr error + out, err := s.readResults(1, func(values [][]byte) { + if decodeErr != nil { + return + } + row, err := dec.row(oids, values) + if err != nil { + decodeErr = apperr.Internalf("%v", err) + return + } + batch = append(batch, row) + }) + if err == nil { + err = decodeErr + } + if err != nil { + return total, fail(err) + } + total += uint64(len(batch)) + if len(batch) > 0 && !send(ctx, sink, drivers.StreamEvent{Rows: batch}) { + return total, fail(apperr.CancelledErr()) + } + if !out.suspended { + break + } + } + if err := s.simple("COMMIT"); err != nil { + s.closeStatement(stmt.Name) + return total, err + } + s.closeStatement(stmt.Name) + return total, nil +} + +// editTarget says whether the rows of a result can be edited, from the +// table OID and attribute number the server reports for each column. An +// empty reason comes with a target. +func (s *Session) editTarget(sql string, origins []origin) (*model.EditTarget, string) { + first := drivers.FirstKeywords(sql, 1) + if len(first) == 0 || (first[0] != "SELECT" && first[0] != "WITH" && first[0] != "TABLE") { + return nil, notATable + } + oid, reason := singleTable(origins) + if reason != "" { + return nil, reason + } + tokens := sqlTokens(sql) + // The row description of a UNION names the first branch's table, but + // the rows may come from any branch. + if hasUnion(tokens) { + return nil, severalQs + } + if joinsTablesIn(tokens) { + return nil, joinsTables + } + meta := s.tableMeta(oid) + if meta == nil { + return nil, keyUnreadMsg + } + return targetFor(meta, oid, origins) +} + +// tableMeta returns the catalog data of one table, cached. One round trip +// on a miss; inside a transaction it runs under a savepoint so a failure +// cannot abort it. +func (s *Session) tableMeta(oid uint32) *tableMeta { + if m := s.tables[oid]; m != nil { + return m + } + query := tableMetaSQL(oid) + inTx := s.TxState().InTransaction + sql := query + if inTx { + sql = "SAVEPOINT lq_edit_meta; " + query + "; RELEASE SAVEPOINT lq_edit_meta" + } + results, err := s.conn.Exec(context.Background(), sql).ReadAll() + if err != nil { + if inTx && !s.isClosed() { + _ = s.simple("ROLLBACK TO SAVEPOINT lq_edit_meta; RELEASE SAVEPOINT lq_edit_meta") + } + return nil + } + var rows [][]*string + for _, r := range results { + rows = append(rows, textValues(r.Rows)...) + } + meta := parseTableMeta(rows) + if meta == nil { + return nil + } + if len(s.tables) >= 256 { + clear(s.tables) + } + s.tables[oid] = meta + return meta +} + +// ApplyChanges runs the grid edits as one unit. With autocommit they +// commit together or not at all. Inside an open transaction they run under +// a savepoint, so a failure undoes only this batch and the transaction +// stays usable. In manual mode without a transaction, one is opened and +// left open. +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + changes := make([]*builtChange, len(req.Changes)) + for i, c := range req.Changes { + built, err := buildChange(&req.Target, c) + if err != nil { + return nil, err + } + changes[i] = built + } + end, err := s.begin(ctx) + if err != nil { + return nil, err + } + defer end() + + started := time.Now() + state := s.TxState() + manual := !state.Autocommit || state.InTransaction + opened := !state.InTransaction + + open := "SAVEPOINT lq_apply" + if opened { + open = "BEGIN" + } + if err := s.simple(open); err != nil { + return nil, err + } + if manual && opened { + s.setInTransaction(true) + } + + result, err := s.runChanges(changes) + if err == nil { + end := "" + switch { + case !opened: + end = "RELEASE SAVEPOINT lq_apply" + case !manual: + end = "COMMIT" + } + if end != "" { + if e := s.simple(end); e != nil { + if end == "COMMIT" { + // A failed COMMIT ends the transaction anyway. + return nil, e + } + err = e + } + } + } + if err != nil { + // Undo only this batch inside an existing transaction; if that + // fails too, end the transaction. + kept := !opened && !s.isClosed() && + s.simple("ROLLBACK TO SAVEPOINT lq_apply; RELEASE SAVEPOINT lq_apply") == nil + if !kept { + if !s.isClosed() { + _ = s.simple("ROLLBACK") + } + s.setInTransaction(false) + clear(s.tables) + } + if ctx.Err() != nil && apperr.From(err).Kind == apperr.Connection { + return nil, apperr.CancelledErr() + } + return nil, err + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.InTransaction = s.TxState().InTransaction + return result, nil +} + +// runChanges runs the statements in order, inside the caller's +// transaction. Parameters go in text format, so the server parses them +// with the input function of each column's type. +func (s *Session) runChanges(changes []*builtChange) (*model.ApplyResult, error) { + result := &model.ApplyResult{} + for i, change := range changes { + if change == nil { + continue + } + row := i + 1 + params := make([][]byte, len(change.params)) + for j, p := range change.params { + if p != nil { + params[j] = []byte(*p) + } + } + res := s.conn.ExecParams(context.Background(), change.sql, params, nil, nil, nil).Read() + if res.Err != nil { + err := apperr.From(s.mapErr(res.Err)) + if err.Kind == apperr.Database { + e := *err + e.Message = "Row " + strconv.Itoa(row) + " was not saved: " + e.Message + e.Position = nil + return nil, &e + } + return nil, err + } + affected := res.CommandTag.RowsAffected() + if change.kind == changeInsert { + result.Inserted += uint64(affected) + continue + } + if affected != 1 { + msg := "Row " + strconv.Itoa(row) + " was not saved: " + strconv.FormatInt(affected, 10) + + " rows matched its key" + if affected == 0 { + msg += " (changed or removed by someone else)." + } else { + msg += "." + } + return nil, apperr.New(apperr.Database, msg) + } + if change.kind == changeUpdate { + result.Updated++ + } else { + result.Deleted++ + } + } + return result, nil +} + +// Close closes the connection; a running call is interrupted. +func (s *Session) Close() error { + if !s.mu.TryLock() { + _ = s.conn.Conn().Close() + s.mu.Lock() + } + defer s.mu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return s.conn.Close(ctx) +} diff --git a/internal/drivers/postgres/types.go b/internal/drivers/postgres/types.go new file mode 100644 index 0000000..1a3e0f8 --- /dev/null +++ b/internal/drivers/postgres/types.go @@ -0,0 +1,390 @@ +package postgres + +import ( + "context" + "fmt" + "strconv" + "strings" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// Built-in type OIDs the decoder and the value kinds know by number. +const ( + oidBool = 16 + oidBytea = 17 + oidChar = 18 + oidName = 19 + oidInt8 = 20 + oidInt2 = 21 + oidInt4 = 23 + oidRegproc = 24 + oidText = 25 + oidOID = 26 + oidTID = 27 + oidXID = 28 + oidCID = 29 + oidJSON = 114 + oidXML = 142 + oidPoint = 600 + oidLseg = 601 + oidBox = 603 + oidLine = 628 + oidCIDR = 650 + oidFloat4 = 700 + oidFloat8 = 701 + oidUnknown = 705 + oidCircle = 718 + oidMacaddr8 = 774 + oidMoney = 790 + oidMacaddr = 829 + oidInet = 869 + oidBpchar = 1042 + oidVarchar = 1043 + oidDate = 1082 + oidTime = 1083 + oidTimestamp = 1114 + oidTimestamptz = 1184 + oidInterval = 1186 + oidTimetz = 1266 + oidBit = 1560 + oidVarbit = 1562 + oidNumeric = 1700 + oidRefcursor = 1790 + oidRegprocedure = 2202 + oidRegoper = 2203 + oidRegoperator = 2204 + oidRegclass = 2205 + oidRegtype = 2206 + oidRecord = 2249 + oidCstring = 2275 + oidVoid = 2278 + oidUUID = 2950 + oidPgLsn = 3220 + oidRegconfig = 3734 + oidRegdictionary = 3769 + oidJSONB = 3802 + oidJSONPath = 4072 + oidRegnamespace = 4089 + oidRegrole = 4096 + oidRegcollation = 4191 + oidXID8 = 5069 +) + +type typeKind uint8 + +const ( + kindSimple typeKind = iota + kindPseudo + kindEnum + kindDomain + kindArray + kindRange + kindMultirange + kindComposite +) + +// pgType is what the driver knows about a type OID. +type pgType struct { + oid uint32 + name string + schema string + kind typeKind + // Base type of a domain, member of an array, subtype of a range or + // multirange. + elem uint32 + // Field types of a composite type. + fields []uint32 +} + +// typeSet holds the types read from the catalog; built-in types are +// looked up in builtinTypes. +type typeSet map[uint32]*pgType + +// get returns the type of oid; an OID nobody knows is a simple type +// without a name (its values are shown as text or hex). +func (ts typeSet) get(oid uint32) *pgType { + if t := ts[oid]; t != nil { + return t + } + if t := builtinTypes[oid]; t != nil { + return t + } + return &pgType{oid: oid} +} + +func (ts typeSet) known(oid uint32) bool { + return ts[oid] != nil || builtinTypes[oid] != nil +} + +// valueKind is the column category the grid uses. +func (ts typeSet) valueKind(oid uint32) model.ValueKind { + t := ts.get(oid) + switch t.kind { + case kindDomain: + if t.elem != oid { + return ts.valueKind(t.elem) + } + case kindEnum: + return model.KindText + case kindArray, kindRange, kindMultirange, kindComposite: + return model.KindOther + } + switch oid { + case oidInt2, oidInt4, oidInt8, oidFloat4, oidFloat8, oidNumeric, oidMoney, oidOID, oidXID, + oidXID8, oidCID: + return model.KindNumber + case oidBool: + return model.KindBool + case oidDate, oidTime, oidTimetz, oidTimestamp, oidTimestamptz, oidInterval: + return model.KindTemporal + case oidBytea: + return model.KindBinary + case oidJSON, oidJSONB, oidJSONPath: + return model.KindJSON + case oidText, oidVarchar, oidBpchar, oidName, oidChar, oidUUID, oidXML, oidUnknown, oidCstring: + return model.KindText + } + return model.KindOther +} + +// label is the readable type name: varchar, int4[], schema.type. +func (ts typeSet) label(oid uint32) string { + t := ts.get(oid) + if t.kind == kindArray && t.elem != oid { + return ts.label(t.elem) + "[]" + } + switch t.schema { + case "pg_catalog", "public", "": + return t.name + } + return t.schema + "." + t.name +} + +// builtinTypes are the types every server has, by OID. Any other type is +// read from the catalog the first time a result uses it; anonymous records +// decode their fields with these only. +var builtinTypes = map[uint32]*pgType{} + +func init() { + scalars := []struct { + oid uint32 + name string + kind typeKind + }{ + {oidBool, "bool", kindSimple}, {oidBytea, "bytea", kindSimple}, {oidChar, "char", kindSimple}, + {oidName, "name", kindSimple}, {oidInt8, "int8", kindSimple}, {oidInt2, "int2", kindSimple}, + {oidInt4, "int4", kindSimple}, {oidRegproc, "regproc", kindSimple}, {oidText, "text", kindSimple}, + {oidOID, "oid", kindSimple}, {oidTID, "tid", kindSimple}, {oidXID, "xid", kindSimple}, + {oidCID, "cid", kindSimple}, {oidJSON, "json", kindSimple}, {oidXML, "xml", kindSimple}, + {oidPoint, "point", kindSimple}, {oidLseg, "lseg", kindSimple}, {602, "path", kindSimple}, + {oidBox, "box", kindSimple}, {604, "polygon", kindSimple}, {oidLine, "line", kindSimple}, + {oidCIDR, "cidr", kindSimple}, {oidFloat4, "float4", kindSimple}, {oidFloat8, "float8", kindSimple}, + {oidUnknown, "unknown", kindPseudo}, {oidCircle, "circle", kindSimple}, + {oidMacaddr8, "macaddr8", kindSimple}, {oidMoney, "money", kindSimple}, + {oidMacaddr, "macaddr", kindSimple}, {oidInet, "inet", kindSimple}, {1033, "aclitem", kindSimple}, + {oidBpchar, "bpchar", kindSimple}, {oidVarchar, "varchar", kindSimple}, {oidDate, "date", kindSimple}, + {oidTime, "time", kindSimple}, {oidTimestamp, "timestamp", kindSimple}, + {oidTimestamptz, "timestamptz", kindSimple}, {oidInterval, "interval", kindSimple}, + {oidTimetz, "timetz", kindSimple}, {oidBit, "bit", kindSimple}, {oidVarbit, "varbit", kindSimple}, + {oidNumeric, "numeric", kindSimple}, {oidRefcursor, "refcursor", kindSimple}, + {oidRegprocedure, "regprocedure", kindSimple}, {oidRegoper, "regoper", kindSimple}, + {oidRegoperator, "regoperator", kindSimple}, {oidRegclass, "regclass", kindSimple}, + {oidRegtype, "regtype", kindSimple}, {oidRecord, "record", kindPseudo}, + {oidCstring, "cstring", kindPseudo}, {oidVoid, "void", kindPseudo}, {oidUUID, "uuid", kindSimple}, + {oidPgLsn, "pg_lsn", kindSimple}, {3614, "tsvector", kindSimple}, + {oidRegconfig, "regconfig", kindSimple}, {oidRegdictionary, "regdictionary", kindSimple}, + {oidJSONB, "jsonb", kindSimple}, {oidJSONPath, "jsonpath", kindSimple}, + {oidRegnamespace, "regnamespace", kindSimple}, {oidRegrole, "regrole", kindSimple}, + {oidRegcollation, "regcollation", kindSimple}, {oidXID8, "xid8", kindSimple}, + } + for _, s := range scalars { + builtinTypes[s.oid] = &pgType{oid: s.oid, name: s.name, schema: "pg_catalog", kind: s.kind} + } + ranges := []struct { + oid uint32 + name string + sub uint32 + }{ + {3904, "int4range", oidInt4}, {3906, "numrange", oidNumeric}, {3908, "tsrange", oidTimestamp}, + {3910, "tstzrange", oidTimestamptz}, {3912, "daterange", oidDate}, {3926, "int8range", oidInt8}, + } + for _, r := range ranges { + builtinTypes[r.oid] = &pgType{oid: r.oid, name: r.name, schema: "pg_catalog", kind: kindRange, elem: r.sub} + } + multiranges := []struct { + oid uint32 + name string + sub uint32 + }{ + {4451, "int4multirange", oidInt4}, {4532, "nummultirange", oidNumeric}, + {4533, "tsmultirange", oidTimestamp}, {4534, "tstzmultirange", oidTimestamptz}, + {4535, "datemultirange", oidDate}, {4536, "int8multirange", oidInt8}, + } + for _, r := range multiranges { + builtinTypes[r.oid] = &pgType{oid: r.oid, name: r.name, schema: "pg_catalog", kind: kindMultirange, elem: r.sub} + } + // Array type OID → member OID. + arrays := []struct{ oid, member uint32 }{ + {143, oidXML}, {199, oidJSON}, {271, oidXID8}, {629, oidLine}, {651, oidCIDR}, {719, oidCircle}, + {791, oidMoney}, {1000, oidBool}, {1001, oidBytea}, {1002, oidChar}, {1003, oidName}, + {1005, oidInt2}, {1007, oidInt4}, {1009, oidText}, {1010, oidTID}, {1011, oidXID}, + {1012, oidCID}, {1014, oidBpchar}, {1015, oidVarchar}, {1016, oidInt8}, {1017, oidPoint}, + {1018, oidLseg}, {1019, 602}, {1020, oidBox}, {1021, oidFloat4}, {1022, oidFloat8}, + {1027, 604}, {1028, oidOID}, {1034, 1033}, {1040, oidMacaddr}, {1041, oidInet}, + {1115, oidTimestamp}, {1182, oidDate}, {1183, oidTime}, {1185, oidTimestamptz}, + {1187, oidInterval}, {1231, oidNumeric}, {1270, oidTimetz}, {1561, oidBit}, {1563, oidVarbit}, + {2287, oidRecord}, {2951, oidUUID}, {3643, 3614}, {3807, oidJSONB}, {4073, oidJSONPath}, + {3905, 3904}, {3907, 3906}, {3909, 3908}, {3911, 3910}, {3913, 3912}, {3927, 3926}, + {6150, 4451}, {6151, 4532}, {6152, 4533}, {6153, 4534}, {6155, 4535}, {6157, 4536}, + } + for _, a := range arrays { + builtinTypes[a.oid] = &pgType{ + oid: a.oid, name: "_" + builtinTypes[a.member].name, schema: "pg_catalog", + kind: kindArray, elem: a.member, + } + } +} + +// typeInfoSQL reads what the decoder needs about types it does not know. +// The subtype of a multirange (PostgreSQL 14+) is read through to_jsonb so +// older servers, which have no rngmultitypid, do not fail. +const typeInfoSQL = `SELECT t.oid::text, t.typname::text, n.nspname::text, t.typtype::text, + t.typlen::text, t.typelem::text, t.typbasetype::text, t.typrelid::text, + COALESCE(r.rngsubtype, 0::oid)::text, + COALESCE(CASE WHEN t.typtype = 'm' THEN + (SELECT x.rngsubtype FROM pg_catalog.pg_range x + WHERE (pg_catalog.to_jsonb(x) ->> 'rngmultitypid')::oid = t.oid) END, 0::oid)::text +FROM pg_catalog.pg_type t +JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace +LEFT JOIN pg_catalog.pg_range r ON r.rngtypid = t.oid +WHERE t.oid IN (%s)` + +const typeFieldsSQL = `SELECT a.attrelid::text, a.atttypid::text +FROM pg_catalog.pg_attribute a +WHERE a.attrelid IN (%s) AND a.attnum > 0 AND NOT a.attisdropped +ORDER BY a.attrelid, a.attnum` + +func oidList(oids []uint32) string { + parts := make([]string, len(oids)) + for i, o := range oids { + parts[i] = strconv.FormatUint(uint64(o), 10) + } + return strings.Join(parts, ",") +} + +func parseOID(s *string) uint32 { + if s == nil { + return 0 + } + v, _ := strconv.ParseUint(*s, 10, 32) + return uint32(v) +} + +// typeFromCatalog classifies a pg_type row the way the decoder needs it. +func typeFromCatalog(row []*string) *pgType { + t := &pgType{ + oid: parseOID(cell(row, 0)), + name: cellText(row, 1), + schema: cellText(row, 2), + } + typtype := cellText(row, 3) + typlen := cellText(row, 4) + elem, base := parseOID(cell(row, 5)), parseOID(cell(row, 6)) + switch { + case typtype == "e": + t.kind = kindEnum + case typtype == "p": + t.kind = kindPseudo + case typtype == "d" && base != 0: + t.kind, t.elem = kindDomain, base + case elem != 0 && typlen == "-1": + t.kind, t.elem = kindArray, elem + case typtype == "c": + t.kind = kindComposite + case typtype == "r": + t.kind, t.elem = kindRange, parseOID(cell(row, 8)) + case typtype == "m": + t.kind, t.elem = kindMultirange, parseOID(cell(row, 9)) + } + return t +} + +// resolveTypes reads from the catalog every type in oids the session does +// not know yet, with the types they are made of. +func (s *Session) resolveTypes(oids []uint32) error { + if len(s.types) > 4096 { + clear(s.types) + } + pending := s.unknownTypes(oids) + for len(pending) > 0 { + rows, err := s.queryText(fmt.Sprintf(typeInfoSQL, oidList(pending))) + if err != nil { + return err + } + var next []uint32 + relids := map[uint32]*pgType{} + for _, row := range rows { + t := typeFromCatalog(row) + s.types[t.oid] = t + if t.elem != 0 { + next = append(next, t.elem) + } + if relid := parseOID(cell(row, 7)); t.kind == kindComposite && relid != 0 { + relids[relid] = t + } + } + if len(relids) > 0 { + ids := make([]uint32, 0, len(relids)) + for id := range relids { + ids = append(ids, id) + } + fields, err := s.queryText(fmt.Sprintf(typeFieldsSQL, oidList(ids))) + if err != nil { + return err + } + for _, f := range fields { + if t := relids[parseOID(cell(f, 0))]; t != nil { + field := parseOID(cell(f, 1)) + t.fields = append(t.fields, field) + next = append(next, field) + } + } + } + // A type the catalog does not return stays unnamed, so the loop + // ends. + for _, oid := range pending { + if s.types[oid] == nil { + s.types[oid] = &pgType{oid: oid} + } + } + pending = s.unknownTypes(next) + } + return nil +} + +func (s *Session) unknownTypes(oids []uint32) []uint32 { + var out []uint32 + seen := map[uint32]bool{} + for _, oid := range oids { + if oid != 0 && !seen[oid] && !s.types.known(oid) { + seen[oid] = true + out = append(out, oid) + } + } + return out +} + +// queryText runs a query without parameters through the simple protocol; +// its values come as text. +func (s *Session) queryText(sql string) ([][]*string, error) { + results, err := s.conn.Exec(context.Background(), sql).ReadAll() + if err != nil { + return nil, s.mapErr(err) + } + var rows [][]*string + for _, r := range results { + rows = append(rows, textValues(r.Rows)...) + } + return rows, nil +} diff --git a/internal/drivers/postgres/value.go b/internal/drivers/postgres/value.go new file mode 100644 index 0000000..df6ca30 --- /dev/null +++ b/internal/drivers/postgres/value.go @@ -0,0 +1,988 @@ +package postgres + +// Decoding of the PostgreSQL binary format to text. +// +// Results are requested in binary format. Instead of relying on generic +// conversions (which fail on NUMERIC NaN/Infinity, infinite dates, +// extension types, etc.), each type is decoded here and formatted the way +// the server itself would in text output. timestamptz is shown in the +// machine's local zone, as a client with a local TimeZone would, and money +// as a plain number so it does not depend on lc_monetary. + +import ( + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "math" + "net/netip" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// binaryPreviewBytes is the number of bytes shown for very large binary +// values in the grid. +const binaryPreviewBytes = 32 * 1024 + +// decoder turns binary values into text. types resolves the type OIDs of +// the result; limit is the number of binary bytes shown as hex. +type decoder struct { + types typeSet + limit int +} + +// row decodes one DataRow; a nil value is NULL. +func (d *decoder) row(oids []uint32, values [][]byte) (model.Row, error) { + row := make(model.Row, len(values)) + for i, raw := range values { + if raw == nil { + continue + } + var oid uint32 + if i < len(oids) { + oid = oids[i] + } + text, err := d.decode(d.types.get(oid), raw) + if err != nil { + return nil, fmt.Errorf("Column %d: %w", i+1, err) + } + row[i] = &text + } + return row, nil +} + +func (d *decoder) decode(t *pgType, raw []byte) (string, error) { + switch t.kind { + case kindDomain: + return d.decode(d.types.get(t.elem), raw) + case kindEnum: + return lossyUTF8(raw), nil + case kindArray: + return d.decodeArray(d.types.get(t.elem), raw) + case kindRange: + return d.decodeRange(d.types.get(t.elem), raw) + case kindMultirange: + return d.decodeMultirange(d.types.get(t.elem), raw) + case kindComposite: + fields := make([]*pgType, len(t.fields)) + for i, f := range t.fields { + fields[i] = d.types.get(f) + } + return d.decodeRecord(fields, raw) + } + r := &reader{buf: raw} + switch t.oid { + case oidBool: + b, err := r.u8() + if err != nil { + return "", err + } + if b != 0 { + return "true", nil + } + return "false", nil + case oidInt2: + v, err := r.i16() + return strconv.FormatInt(int64(v), 10), err + case oidInt4: + v, err := r.i32() + return strconv.FormatInt(int64(v), 10), err + case oidInt8: + v, err := r.i64() + return strconv.FormatInt(v, 10), err + case oidOID, oidXID, oidCID, oidRegproc, oidRegprocedure, oidRegoper, oidRegoperator, + oidRegclass, oidRegtype, oidRegconfig, oidRegdictionary, oidRegnamespace, oidRegrole, + oidRegcollation: + v, err := r.u32() + return strconv.FormatUint(uint64(v), 10), err + case oidXID8: + v, err := r.u64() + return strconv.FormatUint(v, 10), err + case oidFloat4: + v, err := r.f32() + return formatFloat(float64(v), true), err + case oidFloat8: + v, err := r.f64() + return formatFloat(v, false), err + case oidNumeric: + return numeric(raw) + case oidMoney: + v, err := r.i64() + return money(v), err + case oidText, oidVarchar, oidBpchar, oidName, oidUnknown, oidXML, oidRefcursor, oidCstring, oidJSON: + return lossyUTF8(raw), nil + case oidChar: + b, err := r.u8() + // One byte read as Latin-1, like Rust's char::from(u8). + return string(rune(b)), err + case oidJSONB, oidJSONPath: + // The first byte is the format version (1). + if len(raw) == 0 { + return "", nil + } + return lossyUTF8(raw[1:]), nil + case oidUUID: + if len(raw) != 16 { + return "", fmt.Errorf("invalid length for uuid: expected 16 bytes, found %d", len(raw)) + } + return formatUUID(raw), nil + case oidBytea: + return hexBytea(raw, d.limit), nil + case oidDate: + v, err := r.i32() + return date(v), err + case oidTime: + v, err := r.i64() + return timeOfDay(v), err + case oidTimetz: + micros, err := r.i64() + if err != nil { + return "", err + } + // The zone comes in seconds WEST of UTC. + zone, err := r.i32() + if err != nil { + return "", err + } + return timeOfDay(micros) + offset(-zone), nil + case oidTimestamp: + v, err := r.i64() + return timestamp(v, false), err + case oidTimestamptz: + v, err := r.i64() + return timestamp(v, true), err + case oidInterval: + micros, err := r.i64() + if err != nil { + return "", err + } + days, err := r.i32() + if err != nil { + return "", err + } + months, err := r.i32() + if err != nil { + return "", err + } + return interval(micros, days, months), nil + case oidInet, oidCIDR: + return inet(raw, t.oid == oidCIDR, d.limit) + case oidMacaddr, oidMacaddr8: + parts := make([]string, len(raw)) + for i, b := range raw { + parts[i] = fmt.Sprintf("%02x", b) + } + return strings.Join(parts, ":"), nil + case oidPoint: + f, err := r.floats(2) + if err != nil { + return "", err + } + return "(" + f[0] + "," + f[1] + ")", nil + case oidLseg, oidBox: + f, err := r.floats(4) + if err != nil { + return "", err + } + open, close := "", "" + if t.oid == oidLseg { + open, close = "[", "]" + } + return open + "(" + f[0] + "," + f[1] + "),(" + f[2] + "," + f[3] + ")" + close, nil + case oidLine: + f, err := r.floats(3) + if err != nil { + return "", err + } + return "{" + f[0] + "," + f[1] + "," + f[2] + "}", nil + case oidCircle: + f, err := r.floats(3) + if err != nil { + return "", err + } + return "<(" + f[0] + "," + f[1] + ")," + f[2] + ">", nil + case oidBit, oidVarbit: + n, err := r.i32() + if err != nil { + return "", err + } + length := max(int(n), 0) + var sb strings.Builder + sb.Grow(length) + for i := range length { + var b byte + if j := 4 + i/8; j < len(raw) { + b = raw[j] + } + if b&(0x80>>(i%8)) != 0 { + sb.WriteByte('1') + } else { + sb.WriteByte('0') + } + } + return sb.String(), nil + case oidPgLsn: + v, err := r.u64() + return fmt.Sprintf("%X/%X", v>>32, v&0xFFFF_FFFF), err + case oidTID: + block, err := r.u32() + if err != nil { + return "", err + } + off, err := r.u16() + if err != nil { + return "", err + } + return fmt.Sprintf("(%d,%d)", block, off), nil + case oidRecord: + return d.decodeRecord(nil, raw) + case oidVoid: + return "", nil + } + if t.name == "hstore" { + return hstore(raw) + } + // citext and other textual extension types use plain UTF-8. + return fallback(raw, d.limit), nil +} + +var errTruncated = errors.New("truncated binary value") + +type reader struct { + buf []byte + pos int +} + +func (r *reader) take(n int) ([]byte, error) { + if n < 0 || n > len(r.buf)-r.pos { + return nil, errTruncated + } + b := r.buf[r.pos : r.pos+n] + r.pos += n + return b, nil +} + +func (r *reader) u8() (byte, error) { + b, err := r.take(1) + if err != nil { + return 0, err + } + return b[0], nil +} + +func (r *reader) u16() (uint16, error) { + b, err := r.take(2) + if err != nil { + return 0, err + } + return binary.BigEndian.Uint16(b), nil +} + +func (r *reader) i16() (int16, error) { + v, err := r.u16() + return int16(v), err +} + +func (r *reader) u32() (uint32, error) { + b, err := r.take(4) + if err != nil { + return 0, err + } + return binary.BigEndian.Uint32(b), nil +} + +func (r *reader) i32() (int32, error) { + v, err := r.u32() + return int32(v), err +} + +func (r *reader) u64() (uint64, error) { + b, err := r.take(8) + if err != nil { + return 0, err + } + return binary.BigEndian.Uint64(b), nil +} + +func (r *reader) i64() (int64, error) { + v, err := r.u64() + return int64(v), err +} + +func (r *reader) f32() (float32, error) { + v, err := r.u32() + return math.Float32frombits(v), err +} + +func (r *reader) f64() (float64, error) { + v, err := r.u64() + return math.Float64frombits(v), err +} + +// floats reads n float8 values formatted as text. +func (r *reader) floats(n int) ([]string, error) { + out := make([]string, n) + for i := range out { + v, err := r.f64() + if err != nil { + return nil, err + } + out[i] = formatFloat(v, false) + } + return out, nil +} + +// sized reads a length-prefixed value; nil means NULL (length -1). +func (r *reader) sized() ([]byte, bool, error) { + n, err := r.i32() + if err != nil { + return nil, false, err + } + if n < 0 { + return nil, false, nil + } + b, err := r.take(int(n)) + return b, true, err +} + +// lossyUTF8 converts raw to a string, replacing each maximal invalid +// subsequence with U+FFFD (like Rust's String::from_utf8_lossy). +func lossyUTF8(raw []byte) string { + if utf8.Valid(raw) { + return string(raw) + } + var sb strings.Builder + sb.Grow(len(raw) + 8) + for i := 0; i < len(raw); { + r, size := utf8.DecodeRune(raw[i:]) + if r != utf8.RuneError || size > 1 { + sb.Write(raw[i : i+size]) + i += size + continue + } + sb.WriteRune(utf8.RuneError) + i += invalidSubpart(raw[i:]) + } + return sb.String() +} + +// invalidSubpart is the length of the maximal prefix of an invalid UTF-8 +// sequence: a lead byte followed by the continuation bytes it accepts. +func invalidSubpart(b []byte) int { + lo, hi := byte(0x80), byte(0xBF) + var need int + switch c := b[0]; { + case c >= 0xC2 && c <= 0xDF: + need = 1 + case c == 0xE0: + need, lo = 2, 0xA0 + case c >= 0xE1 && c <= 0xEC, c == 0xEE, c == 0xEF: + need = 2 + case c == 0xED: + need, hi = 2, 0x9F + case c == 0xF0: + need, lo = 3, 0x90 + case c >= 0xF1 && c <= 0xF3: + need = 3 + case c == 0xF4: + need, hi = 3, 0x8F + default: + return 1 + } + n := 1 + for k := 0; k < need && n < len(b); k++ { + if b[n] < lo || b[n] > hi { + break + } + n++ + lo, hi = 0x80, 0xBF + } + return n +} + +// fallback shows raw as text when it looks like text, otherwise as +// hexadecimal, like bytea. +func fallback(raw []byte, limit int) string { + if utf8.Valid(raw) { + s := string(raw) + text := true + for _, c := range s { + if unicode.IsControl(c) && c != '\n' && c != '\r' && c != '\t' { + text = false + break + } + } + if text { + return s + } + } + return hexBytea(raw, limit) +} + +func hexBytea(raw []byte, limit int) string { + shown := raw[:min(len(raw), max(limit, 0))] + var sb strings.Builder + sb.Grow(2 + 2*len(shown)) + sb.WriteString(`\x`) + sb.WriteString(hex.EncodeToString(shown)) + if len(raw) > len(shown) { + fmt.Fprintf(&sb, "… (%d bytes)", len(raw)) + } + return sb.String() +} + +func formatUUID(b []byte) string { + h := hex.EncodeToString(b) + return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32] +} + +func formatFloat(v float64, single bool) string { + switch { + case math.IsNaN(v): + return "NaN" + case math.IsInf(v, 1): + return "Infinity" + case math.IsInf(v, -1): + return "-Infinity" + case single: + // Shortest representation that preserves the 32-bit value. + return strconv.FormatFloat(float64(float32(v)), 'f', -1, 32) + default: + return strconv.FormatFloat(v, 'f', -1, 64) + } +} + +func money(cents int64) string { + sign := "" + abs := uint64(cents) + if cents < 0 { + sign = "-" + abs = -abs + } + return fmt.Sprintf("%s%d.%02d", sign, abs/100, abs%100) +} + +// numeric formats NUMERIC: base-10000 digits with weight and display scale. +func numeric(raw []byte) (string, error) { + r := &reader{buf: raw} + nd, err := r.i16() + if err != nil { + return "", err + } + w, err := r.i16() + if err != nil { + return "", err + } + sign, err := r.u16() + if err != nil { + return "", err + } + ds, err := r.u16() + if err != nil { + return "", err + } + switch sign { + case 0xC000: + return "NaN", nil + case 0xD000: + return "Infinity", nil + case 0xF000: + return "-Infinity", nil + } + ndigits := max(int(nd), 0) + weight := int(w) + dscale := int(ds) + digits := make([]int16, ndigits) + for i := range digits { + if digits[i], err = r.i16(); err != nil { + return "", err + } + } + digit := func(i int) int16 { + if i < 0 || i >= len(digits) { + return 0 + } + return digits[i] + } + + var sb strings.Builder + if sign == 0x4000 { + sb.WriteByte('-') + } + if weight < 0 { + sb.WriteByte('0') + } else { + for i := 0; i <= weight; i++ { + if i == 0 { + fmt.Fprintf(&sb, "%d", digit(i)) + } else { + fmt.Fprintf(&sb, "%04d", digit(i)) + } + } + } + if dscale > 0 { + sb.WriteByte('.') + var frac strings.Builder + for i := weight + 1; frac.Len() < dscale; i++ { + fmt.Fprintf(&frac, "%04d", digit(i)) + } + sb.WriteString(frac.String()[:dscale]) + } + return sb.String(), nil +} + +// pgEpoch is 2000-01-01 in Unix seconds. +const pgEpoch = 946_684_800 + +// ymdFromDays returns the proleptic Gregorian date of a day count since +// 2000-01-01; year 0 is 1 BC. +func ymdFromDays(days int64) (year int64, month, day int) { + t := time.Unix(pgEpoch+days*86_400, 0).UTC() + return int64(t.Year()), int(t.Month()), t.Day() +} + +// formatYMD formats a date and says whether it is BC. +func formatYMD(year int64, month, day int) (string, bool) { + if year <= 0 { + return fmt.Sprintf("%04d-%02d-%02d", 1-year, month, day), true + } + return fmt.Sprintf("%04d-%02d-%02d", year, month, day), false +} + +func date(days int32) string { + switch days { + case math.MaxInt32: + return "infinity" + case math.MinInt32: + return "-infinity" + } + s, bc := formatYMD(ymdFromDays(int64(days))) + if bc { + return s + " BC" + } + return s +} + +func fraction(micros int64) string { + if micros == 0 { + return "" + } + return strings.TrimRight(fmt.Sprintf(".%06d", micros), "0") +} + +func floorDiv(a, b int64) int64 { + q := a / b + if a%b != 0 && (a < 0) != (b < 0) { + q-- + } + return q +} + +func floorMod(a, b int64) int64 { + return a - floorDiv(a, b)*b +} + +func timeOfDay(micros int64) string { + secs := floorDiv(micros, 1_000_000) + frac := floorMod(micros, 1_000_000) + return fmt.Sprintf("%02d:%02d:%02d%s", secs/3600, (secs/60)%60, secs%60, fraction(frac)) +} + +// offset formats seconds east of UTC: +03, -03:30. +func offset(east int32) string { + sign := byte('+') + abs := uint32(east) + if east < 0 { + sign = '-' + abs = -abs + } + h, m, s := abs/3600, (abs/60)%60, abs%60 + switch { + case m == 0 && s == 0: + return fmt.Sprintf("%c%02d", sign, h) + case s == 0: + return fmt.Sprintf("%c%02d:%02d", sign, h, m) + default: + return fmt.Sprintf("%c%02d:%02d:%02d", sign, h, m, s) + } +} + +// localOffset is the machine's offset east of UTC at a Unix time. +var localOffset = func(unixSecs int64) int32 { + _, east := time.Unix(unixSecs, 0).In(time.Local).Zone() + return int32(east) +} + +// timestamp formats TIMESTAMP(TZ): microseconds since 2000-01-01. With a +// time zone, shows the machine's local zone, as a client with a local +// TimeZone would. +func timestamp(micros int64, withTZ bool) string { + switch micros { + case math.MaxInt64: + return "infinity" + case math.MinInt64: + return "-infinity" + } + tz := "" + if withTZ { + east := localOffset(floorDiv(micros, 1_000_000) + pgEpoch) + micros += int64(east) * 1_000_000 + tz = offset(east) + } + days := floorDiv(micros, 86_400_000_000) + inDay := floorMod(micros, 86_400_000_000) + ymd, bc := formatYMD(ymdFromDays(days)) + s := ymd + " " + timeOfDay(inDay) + tz + if bc { + s += " BC" + } + return s +} + +// interval formats in the postgres style (the server default): +// 1 year 2 mons 3 days 04:05:06. +func interval(micros int64, days, months int32) string { + var parts []string + plural := func(n int64, one, many string) string { + if n == 1 || n == -1 { + return fmt.Sprintf("%d %s", n, one) + } + return fmt.Sprintf("%d %s", n, many) + } + years := months / 12 + mons := months % 12 + if years != 0 { + parts = append(parts, plural(int64(years), "year", "years")) + } + if mons != 0 { + parts = append(parts, plural(int64(mons), "mon", "mons")) + } + if days != 0 { + parts = append(parts, plural(int64(days), "day", "days")) + } + if micros != 0 || len(parts) == 0 { + sign := "" + abs := uint64(micros) + if micros < 0 { + sign = "-" + abs = -abs + } + secs := abs / 1_000_000 + frac := int64(abs % 1_000_000) + parts = append(parts, fmt.Sprintf("%s%02d:%02d:%02d%s", + sign, secs/3600, (secs/60)%60, secs%60, fraction(frac))) + } + return strings.Join(parts, " ") +} + +func inet(raw []byte, cidrType bool, limit int) (string, error) { + r := &reader{buf: raw} + family, err := r.u8() + if err != nil { + return "", err + } + bits, err := r.u8() + if err != nil { + return "", err + } + if _, err := r.u8(); err != nil { // is_cidr flag + return "", err + } + n, err := r.u8() + if err != nil { + return "", err + } + addr, err := r.take(int(n)) + if err != nil { + return "", err + } + var text string + var maxBits byte + switch { + case family == 2 && n == 4: + text = netip.AddrFrom4([4]byte(addr)).String() + maxBits = 32 + case family == 3 && n == 16: + text = netip.AddrFrom16([16]byte(addr)).String() + maxBits = 128 + default: + return hexBytea(raw, limit), nil + } + if cidrType || bits != maxBits { + return fmt.Sprintf("%s/%d", text, bits), nil + } + return text, nil +} + +func hstore(raw []byte) (string, error) { + r := &reader{buf: raw} + count, err := r.i32() + if err != nil { + return "", err + } + pairs := make([]string, 0, max(int(count), 0)) + for range max(int(count), 0) { + key, _, err := r.sized() + if err != nil { + return "", err + } + v, ok, err := r.sized() + if err != nil { + return "", err + } + value := "NULL" + if ok { + value = `"` + escapeQuoted(lossyUTF8(v)) + `"` + } + pairs = append(pairs, `"`+escapeQuoted(lossyUTF8(key))+`"=>`+value) + } + return strings.Join(pairs, ", "), nil +} + +func escapeQuoted(s string) string { + return strings.ReplaceAll(strings.ReplaceAll(s, `\`, `\\`), `"`, `\"`) +} + +func containsAny(s string, special string) bool { + for _, c := range s { + if strings.ContainsRune(special, c) || unicode.IsSpace(c) { + return true + } + } + return false +} + +// arrayElement quotes like array output: empty strings, a literal NULL, +// whitespace or special characters require quotes. +func arrayElement(s string) string { + if s == "" || asciiEqualFold(s, "null") || containsAny(s, `{},"\`) { + return `"` + escapeQuoted(s) + `"` + } + return s +} + +func asciiEqualFold(a, b string) bool { + if len(a) != len(b) { + return false + } + for i := 0; i < len(a); i++ { + x, y := a[i], b[i] + if 'A' <= x && x <= 'Z' { + x += 'a' - 'A' + } + if 'A' <= y && y <= 'Z' { + y += 'a' - 'A' + } + if x != y { + return false + } + } + return true +} + +type arrayDim struct { + length int + lower int32 +} + +func (d *decoder) decodeArray(member *pgType, raw []byte) (string, error) { + r := &reader{buf: raw} + n, err := r.i32() + if err != nil { + return "", err + } + if _, err := r.i32(); err != nil { // has nulls + return "", err + } + if _, err := r.u32(); err != nil { // element OID + return "", err + } + ndim := max(int(n), 0) + if ndim == 0 { + return "{}", nil + } + dims := make([]arrayDim, ndim) + total := 1 + bounds := false + for i := range dims { + length, err := r.i32() + if err != nil { + return "", err + } + lower, err := r.i32() + if err != nil { + return "", err + } + dims[i] = arrayDim{max(int(length), 0), lower} + total *= dims[i].length + bounds = bounds || lower != 1 + } + var out strings.Builder + if bounds { + for _, dim := range dims { + fmt.Fprintf(&out, "[%d:%d]", dim.lower, dim.lower+int32(dim.length)-1) + } + out.WriteByte('=') + } + elems := make([]string, 0, total) + for range total { + b, ok, err := r.sized() + if err != nil { + return "", err + } + if !ok { + elems = append(elems, "NULL") + continue + } + v, err := d.decode(member, b) + if err != nil { + return "", err + } + elems = append(elems, arrayElement(v)) + } + idx := 0 + writeDims(&out, dims, elems, &idx) + return out.String(), nil +} + +func writeDims(out *strings.Builder, dims []arrayDim, elems []string, idx *int) { + out.WriteByte('{') + for i := range dims[0].length { + if i > 0 { + out.WriteByte(',') + } + if len(dims) > 1 { + writeDims(out, dims[1:], elems, idx) + } else if *idx < len(elems) { + out.WriteString(elems[*idx]) + *idx++ + } + } + out.WriteByte('}') +} + +func (d *decoder) decodeRange(inner *pgType, raw []byte) (string, error) { + const ( + empty = 0x01 + lbInc = 0x02 + ubInc = 0x04 + lbInf = 0x08 + ubInf = 0x10 + ) + r := &reader{buf: raw} + flags, err := r.u8() + if err != nil { + return "", err + } + if flags&empty != 0 { + return "empty", nil + } + bound := func(inf bool) (string, error) { + if inf { + return "", nil + } + b, ok, err := r.sized() + if err != nil || !ok { + return "", err + } + v, err := d.decode(inner, b) + if err != nil { + return "", err + } + if containsAny(v, `,()[]"`) { + return `"` + escapeQuoted(v) + `"`, nil + } + return v, nil + } + lower, err := bound(flags&lbInf != 0) + if err != nil { + return "", err + } + upper, err := bound(flags&ubInf != 0) + if err != nil { + return "", err + } + open, close := "(", ")" + if flags&lbInc != 0 { + open = "[" + } + if flags&ubInc != 0 { + close = "]" + } + return open + lower + "," + upper + close, nil +} + +func (d *decoder) decodeMultirange(inner *pgType, raw []byte) (string, error) { + r := &reader{buf: raw} + count, err := r.i32() + if err != nil { + return "", err + } + parts := make([]string, 0, max(int(count), 0)) + for range max(int(count), 0) { + b, ok, err := r.sized() + if err != nil { + return "", err + } + if !ok { + continue + } + v, err := d.decodeRange(inner, b) + if err != nil { + return "", err + } + parts = append(parts, v) + } + return "{" + strings.Join(parts, ",") + "}", nil +} + +// decodeRecord decodes a composite type or record. Without the field types +// (anonymous record), it uses the built-in type of the OID carried in the +// value itself. +func (d *decoder) decodeRecord(fields []*pgType, raw []byte) (string, error) { + r := &reader{buf: raw} + n, err := r.i32() + if err != nil { + return "", err + } + count := max(int(n), 0) + parts := make([]string, 0, count) + for i := range count { + fieldOID, err := r.u32() + if err != nil { + return "", err + } + var t *pgType + if i < len(fields) { + t = fields[i] + } else { + t = builtinTypes[fieldOID] + } + b, ok, err := r.sized() + if err != nil { + return "", err + } + if !ok { + parts = append(parts, "") + continue + } + var v string + if t != nil { + if v, err = d.decode(t, b); err != nil { + return "", err + } + } else { + v = fallback(b, d.limit) + } + if v == "" || containsAny(v, `,()"\`) { + v = `"` + escapeQuoted(v) + `"` + } + parts = append(parts, v) + } + return "(" + strings.Join(parts, ",") + ")", nil +} diff --git a/internal/drivers/postgres/value_test.go b/internal/drivers/postgres/value_test.go new file mode 100644 index 0000000..0ca863f --- /dev/null +++ b/internal/drivers/postgres/value_test.go @@ -0,0 +1,334 @@ +package postgres + +import ( + "encoding/binary" + "math" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func be16(v uint16) []byte { return binary.BigEndian.AppendUint16(nil, v) } +func be32(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) } +func be64(v uint64) []byte { return binary.BigEndian.AppendUint64(nil, v) } +func beI32(v int32) []byte { return be32(uint32(v)) } + +func cat(parts ...[]byte) []byte { + var out []byte + for _, p := range parts { + out = append(out, p...) + } + return out +} + +// sized encodes a length-prefixed value; nil is NULL. +func sized(v []byte) []byte { + if v == nil { + return be32(math.MaxUint32) + } + return cat(be32(uint32(len(v))), v) +} + +func numericBytes(ndigits, weight int16, sign, dscale uint16, digits ...int16) []byte { + out := cat(be16(uint16(ndigits)), be16(uint16(weight)), be16(sign), be16(dscale)) + for _, d := range digits { + out = append(out, be16(uint16(d))...) + } + return out +} + +func TestNumericFormatsLikeServer(t *testing.T) { + cases := []struct { + raw []byte + want string + }{ + // 12345.678 → digits [1, 2345, 6780], weight 1, scale 3 + {numericBytes(3, 1, 0, 3, 1, 2345, 6780), "12345.678"}, + // -0.0012 → [12], weight -1, scale 4 + {numericBytes(1, -1, 0x4000, 4, 12), "-0.0012"}, + // 0.00000001 → groups 0000 0001: digit [1], weight -2, scale 8 + {numericBytes(1, -2, 0, 8, 1), "0.00000001"}, + // 10000 → [1], weight 1, scale 0 (trailing zeros omitted from the digits) + {numericBytes(1, 1, 0, 0, 1), "10000"}, + // 1.50 → scale 2 keeps the zero + {numericBytes(2, 0, 0, 2, 1, 5000), "1.50"}, + {numericBytes(0, 0, 0, 0), "0"}, + {numericBytes(0, 0, 0xC000, 0), "NaN"}, + {numericBytes(0, 0, 0xD000, 0), "Infinity"}, + {numericBytes(0, 0, 0xF000, 0), "-Infinity"}, + } + for _, c := range cases { + got, err := numeric(c.raw) + if err != nil || got != c.want { + t.Errorf("numeric = %q, %v; want %q", got, err, c.want) + } + } + if _, err := numeric([]byte{0, 1}); err == nil { + t.Error("truncated numeric decoded") + } +} + +func TestDatesAndTimes(t *testing.T) { + eq := func(got, want string) { + t.Helper() + if got != want { + t.Errorf("got %q, want %q", got, want) + } + } + eq(date(0), "2000-01-01") + eq(date(-1), "1999-12-31") + eq(date(math.MaxInt32), "infinity") + eq(date(math.MinInt32), "-infinity") + eq(date(-730119), "0001-01-01") + eq(date(-730120), "0001-12-31 BC") + eq(date(1520), "2004-02-29") + eq(timestamp(86_400_000_000+3_723_500_000, false), "2000-01-02 01:02:03.5") + eq(timestamp(-1, false), "1999-12-31 23:59:59.999999") + eq(timestamp(math.MaxInt64, true), "infinity") + eq(timestamp(math.MinInt64, false), "-infinity") + eq(timeOfDay(45_296_000_001), "12:34:56.000001") + eq(timeOfDay(86_400_000_000), "24:00:00") + eq(offset(-3*3600), "-03") + eq(offset(5*3600+1800), "+05:30") + eq(offset(-(3600 + 60 + 1)), "-01:01:01") + eq(offset(0), "+00") +} + +func TestTimestampWithZoneUsesLocalOffset(t *testing.T) { + saved := localOffset + defer func() { localOffset = saved }() + localOffset = func(int64) int32 { return -3 * 3600 } + if got := timestamp(0, true); got != "1999-12-31 21:00:00-03" { + t.Errorf("got %q", got) + } + localOffset = func(int64) int32 { return 5*3600 + 1800 } + if got := timestamp(250_000, true); got != "2000-01-01 05:30:00.25+05:30" { + t.Errorf("got %q", got) + } +} + +func TestIntervals(t *testing.T) { + cases := []struct { + micros int64 + days, months int32 + want string + }{ + {0, 0, 0, "00:00:00"}, + {14_706_000_000, 3, 14, "1 year 2 mons 3 days 04:05:06"}, + {-1_500_000, 1, 0, "1 day -00:00:01.5"}, + {0, -1, -25, "-2 years -1 mon -1 day"}, + {3_600_000_000 * 30, 0, 0, "30:00:00"}, + } + for _, c := range cases { + if got := interval(c.micros, c.days, c.months); got != c.want { + t.Errorf("interval(%d, %d, %d) = %q, want %q", c.micros, c.days, c.months, got, c.want) + } + } +} + +func TestArrays(t *testing.T) { + d := &decoder{types: typeSet{}, limit: binaryPreviewBytes} + raw := cat(be32(1), be32(1), be32(oidText), be32(3), be32(1), + sized([]byte("a b")), sized(nil), sized([]byte("x"))) + got, err := d.decodeArray(builtinTypes[oidText], raw) + if err != nil || got != `{"a b",NULL,x}` { + t.Errorf("got %q, %v", got, err) + } + + // Two dimensions with a lower bound other than 1. + raw = cat(be32(2), be32(0), be32(oidInt4), be32(2), be32(0), be32(2), be32(1), + sized(be32(1)), sized(be32(2)), sized(be32(3)), sized(be32(4))) + got, err = d.decode(builtinTypes[1007], raw) + if err != nil || got != "[0:1][1:2]={{1,2},{3,4}}" { + t.Errorf("got %q, %v", got, err) + } + + empty := cat(be32(0), be32(0), be32(oidInt4)) + if got, _ := d.decode(builtinTypes[1007], empty); got != "{}" { + t.Errorf("empty array: %q", got) + } + + if got := arrayElement("null"); got != `"null"` { + t.Errorf("arrayElement(null) = %q", got) + } + if got := arrayElement(`a"b\c`); got != `"a\"b\\c"` { + t.Errorf("arrayElement = %q", got) + } +} + +func TestInetValues(t *testing.T) { + cases := []struct { + raw []byte + cidr bool + want string + }{ + {[]byte{2, 32, 0, 4, 10, 0, 0, 1}, false, "10.0.0.1"}, + {[]byte{2, 24, 1, 4, 10, 0, 0, 0}, true, "10.0.0.0/24"}, + {[]byte{2, 24, 0, 4, 192, 168, 0, 1}, false, "192.168.0.1/24"}, + {cat([]byte{3, 128, 0, 16}, []byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), false, "2001:db8::1"}, + {cat([]byte{3, 128, 0, 16}, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 1, 2, 3, 4}), false, "::ffff:1.2.3.4"}, + } + for _, c := range cases { + got, err := inet(c.raw, c.cidr, binaryPreviewBytes) + if err != nil || got != c.want { + t.Errorf("inet = %q, %v; want %q", got, err, c.want) + } + } +} + +func TestDecodesScalars(t *testing.T) { + d := &decoder{types: typeSet{}, limit: 4} + cases := []struct { + oid uint32 + raw []byte + want string + }{ + {oidBool, []byte{1}, "true"}, + {oidBool, []byte{0}, "false"}, + {oidInt2, be16(0xFFFF), "-1"}, + {oidInt8, be64(math.MaxUint64), "-1"}, + {oidOID, be32(math.MaxUint32), "4294967295"}, + {oidFloat4, be32(math.Float32bits(1.5)), "1.5"}, + {oidFloat4, be32(math.Float32bits(0.1)), "0.1"}, + {oidFloat8, be64(math.Float64bits(0.1)), "0.1"}, + {oidFloat8, be64(math.Float64bits(1e21)), "1000000000000000000000"}, + {oidFloat8, be64(math.Float64bits(math.Inf(1))), "Infinity"}, + {oidFloat8, be64(math.Float64bits(math.Copysign(0, -1))), "-0"}, + {oidFloat8, be64(math.Float64bits(math.NaN())), "NaN"}, + {oidMoney, be64(1234), "12.34"}, + {oidMoney, be64(uint64(math.MaxUint64 - 4)), "-0.05"}, + {oidText, []byte("olá"), "olá"}, + {oidText, []byte{'a', 0xE2, 0x82, 'b', 0xFF, 0xFE}, "a�b��"}, + {oidChar, []byte{0xE9}, "é"}, + {oidJSONB, cat([]byte{1}, []byte(`{"a": [1, 2]}`)), `{"a": [1, 2]}`}, + {oidUUID, []byte{0xa0, 0xee, 0xbc, 0x99, 0x9c, 0x0b, 0x4e, 0xf8, 0xbb, 0x6d, 0x6b, 0xb9, 0xbd, 0x38, 0x0a, 0x11}, + "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"}, + {oidBytea, []byte{0xde, 0xad, 0xbe, 0xef}, `\xdeadbeef`}, + {oidBytea, []byte{0xde, 0xad, 0xbe, 0xef, 0x00}, `\xdeadbeef… (5 bytes)`}, + {oidTime, be64(46_801_000_000), "13:00:01"}, + {oidTimetz, cat(be64(46_801_000_000), beI32(-19800)), "13:00:01+05:30"}, + {oidBit, cat(be32(5), []byte{0xA8}), "10101"}, + {oidPgLsn, be64(0x16_B374D848), "16/B374D848"}, + {oidTID, cat(be32(7), be16(3)), "(7,3)"}, + {oidMacaddr, []byte{8, 0, 0x2b, 1, 2, 3}, "08:00:2b:01:02:03"}, + {oidPoint, cat(be64(math.Float64bits(1.5)), be64(math.Float64bits(-2))), "(1.5,-2)"}, + {oidCircle, cat(be64(math.Float64bits(0)), be64(math.Float64bits(0)), be64(math.Float64bits(3))), "<(0,0),3>"}, + {oidVoid, nil, ""}, + // Unknown types: text when it looks like text, otherwise hex. + {99999, []byte("citext value"), "citext value"}, + {99999, []byte{0, 1, 2}, `\x000102`}, + } + for _, c := range cases { + got, err := d.decode(d.types.get(c.oid), c.raw) + if err != nil || got != c.want { + t.Errorf("decode(%d, %x) = %q, %v; want %q", c.oid, c.raw, got, err, c.want) + } + } + if _, err := d.decode(builtinTypes[oidInt4], []byte{1}); err == nil { + t.Error("truncated int4 decoded") + } +} + +func TestBinaryLimitInFull(t *testing.T) { + raw := make([]byte, binaryPreviewBytes+1) + preview := hexBytea(raw, binaryPreviewBytes) + if !strings.HasSuffix(preview, "… (32769 bytes)") { + t.Errorf("preview ends with %q", preview[len(preview)-20:]) + } + full := hexBytea(raw, math.MaxInt) + if len(full) != 2+2*len(raw) { + t.Errorf("full value has %d characters", len(full)) + } +} + +func TestRangesRecordsAndCatalogTypes(t *testing.T) { + types := typeSet{ + // A domain over int4, an enum, a composite (int4, text[]) and a + // user range over numeric. + 90001: {oid: 90001, name: "posint", schema: "public", kind: kindDomain, elem: oidInt4}, + 90002: {oid: 90002, name: "mood", schema: "app", kind: kindEnum}, + 90003: {oid: 90003, name: "pair", schema: "app", kind: kindComposite, fields: []uint32{oidInt4, 1009}}, + 90004: {oid: 90004, name: "_pair", schema: "app", kind: kindArray, elem: 90003}, + 90005: {oid: 90005, name: "hstore", schema: "public"}, + } + d := &decoder{types: types, limit: binaryPreviewBytes} + + int4range := cat([]byte{0x02}, sized(be32(1)), sized(be32(10))) + cases := []struct { + oid uint32 + raw []byte + want string + }{ + {3904, int4range, "[1,10)"}, + {3904, []byte{0x01}, "empty"}, + {3904, cat([]byte{0x08 | 0x04}, sized(be32(5))), "(,5]"}, + {3910 - 2, cat([]byte{0x02 | 0x10}, sized(be64(0))), `["2000-01-01 00:00:00",)`}, + {4451, cat(be32(2), sized(int4range), sized(cat([]byte{0x02}, sized(be32(20)), sized(be32(30))))), "{[1,10),[20,30)}"}, + {oidRecord, cat(be32(3), be32(oidInt4), sized(be32(1)), be32(oidText), sized([]byte("x")), + be32(oidText), sized(nil)), "(1,x,)"}, + {oidRecord, cat(be32(2), be32(oidText), sized([]byte("a b")), be32(oidText), sized([]byte{})), `("a b","")`}, + {90001, be32(42), "42"}, + {90002, []byte("happy"), "happy"}, + {90003, cat(be32(2), be32(oidInt4), sized(be32(7)), + be32(1009), sized(cat(be32(1), be32(0), be32(oidText), be32(2), be32(1), sized([]byte("a")), sized([]byte("b c"))))), + `(7,"{a,\"b c\"}")`}, + {90005, cat(be32(2), sized([]byte("k")), sized([]byte(`v"1`)), sized([]byte("n")), sized(nil)), `"k"=>"v\"1", "n"=>NULL`}, + } + for _, c := range cases { + got, err := d.decode(d.types.get(c.oid), c.raw) + if err != nil || got != c.want { + t.Errorf("decode(%d) = %q, %v; want %q", c.oid, got, err, c.want) + } + } + + labels := map[uint32]string{ + oidInt4: "int4", 1007: "int4[]", oidVarchar: "varchar", 90001: "posint", 90002: "app.mood", + 90004: "app.pair[]", 3904: "int4range", + } + for oid, want := range labels { + if got := types.label(oid); got != want { + t.Errorf("label(%d) = %q, want %q", oid, got, want) + } + } + kinds := map[uint32]model.ValueKind{ + oidInt4: model.KindNumber, oidMoney: model.KindNumber, oidBool: model.KindBool, + oidTimestamptz: model.KindTemporal, oidBytea: model.KindBinary, oidJSONB: model.KindJSON, + oidUUID: model.KindText, 1007: model.KindOther, 3904: model.KindOther, oidRecord: model.KindOther, + 90001: model.KindNumber, 90002: model.KindText, 90003: model.KindOther, oidInet: model.KindOther, + } + for oid, want := range kinds { + if got := types.valueKind(oid); got != want { + t.Errorf("valueKind(%d) = %q, want %q", oid, got, want) + } + } +} + +func TestClassifiesCatalogRows(t *testing.T) { + s := func(v string) *string { return &v } + row := func(typtype, typlen, elem, base, rngsub, multisub string) []*string { + return []*string{s("90100"), s("t"), s("public"), s(typtype), s(typlen), s(elem), s(base), s("0"), s(rngsub), s(multisub)} + } + cases := []struct { + row []*string + kind typeKind + elem uint32 + }{ + {row("b", "-1", "0", "0", "0", "0"), kindSimple, 0}, + {row("b", "-1", "25", "0", "0", "0"), kindArray, 25}, + // name-like fixed-length types with typelem are not arrays. + {row("b", "64", "18", "0", "0", "0"), kindSimple, 0}, + {row("d", "4", "0", "23", "0", "0"), kindDomain, 23}, + {row("e", "4", "0", "0", "0", "0"), kindEnum, 0}, + {row("p", "-1", "0", "0", "0", "0"), kindPseudo, 0}, + {row("c", "-1", "0", "0", "0", "0"), kindComposite, 0}, + {row("r", "-1", "0", "0", "1700", "0"), kindRange, 1700}, + {row("m", "-1", "0", "0", "0", "1082"), kindMultirange, 1082}, + } + for i, c := range cases { + got := typeFromCatalog(c.row) + if got.kind != c.kind || got.elem != c.elem || got.oid != 90100 || got.name != "t" { + t.Errorf("case %d: %+v", i, got) + } + } +} diff --git a/internal/drivers/sqlite/edit.go b/internal/drivers/sqlite/edit.go new file mode 100644 index 0000000..7e0ed96 --- /dev/null +++ b/internal/drivers/sqlite/edit.go @@ -0,0 +1,637 @@ +package sqlite + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +const unknownTable = "Read-only: the table behind this result could not be identified." + +type tableKey struct{ db, table string } + +// tableMeta holds the keys and columns of a table behind editable results. +type tableMeta struct { + // Column names, with whether each one can be written (generated and + // hidden columns cannot). + columns []metaColumn + // Primary key columns in key order. + pk []string + // UNIQUE keys whose columns are all NOT NULL. + unique [][]string +} + +type metaColumn struct { + name string + writable bool +} + +// origin is the database, table and column behind a result column. +type origin struct{ db, table, column string } + +// columnOrigins returns the origin of each result column, nil for +// expressions. +func columnOrigins(stmt *sqlite3.Stmt) []*origin { + n := stmt.ColumnCount() + out := make([]*origin, n) + for i := range n { + o := origin{ + db: stmt.ColumnDatabaseName(i), + table: stmt.ColumnTableName(i), + column: stmt.ColumnOriginName(i), + } + if o.db != "" && o.table != "" && o.column != "" { + out[i] = &o + } + } + return out +} + +// asciiEqualFold compares names ignoring ASCII case, as SQLite does. +func asciiEqualFold(a, b string) bool { + if len(a) != len(b) { + return false + } + for i := 0; i < len(a); i++ { + x, y := a[i], b[i] + if 'A' <= x && x <= 'Z' { + x += 'a' - 'A' + } + if 'A' <= y && y <= 'Z' { + y += 'a' - 'A' + } + if x != y { + return false + } + } + return true +} + +// editTarget returns the table an editable result comes from, or why it is +// read-only. +func (s *Session) editTarget(sql string, origins []*origin, decls []string) (*model.EditTarget, string) { + var first *origin + for _, o := range origins { + if o == nil { + continue + } + if first == nil { + first = o + } else if o.db != first.db || o.table != first.table { + return nil, "Read-only: the result combines columns from several tables." + } + } + if first == nil { + return nil, "Read-only: only rows from a table can be edited." + } + shape, err := s.queryPlan(sql) + if err != nil { + return nil, unknownTable + } + if shape.compound { + return nil, "Read-only: the result combines rows from several queries." + } + if shape.sources != 1 { + return nil, "Read-only: the result combines rows from several tables." + } + meta, err := s.tableMeta(first.db, first.table) + if err != nil { + return nil, unknownTable + } + return buildTarget(first.db, first.table, meta, origins, decls) +} + +func buildTarget(db, table string, meta *tableMeta, origins []*origin, decls []string) (*model.EditTarget, string) { + hasRowid := len(meta.pk) == 0 && !slices.ContainsFunc(meta.columns, func(c metaColumn) bool { + return asciiEqualFold(c.name, "rowid") + }) + columns := make([]*model.EditColumn, len(origins)) + for i, o := range origins { + if o == nil { + continue + } + at := slices.IndexFunc(meta.columns, func(c metaColumn) bool { return asciiEqualFold(c.name, o.column) }) + switch { + case at >= 0: + if c := meta.columns[at]; c.writable { + decl := "" + if i < len(decls) { + decl = decls[i] + } + columns[i] = &model.EditColumn{Name: c.name, TypeName: decl} + } + // rowid, oid and _rowid_ all report "rowid". + case hasRowid && asciiEqualFold(o.column, "rowid"): + columns[i] = &model.EditColumn{Name: "rowid", TypeName: "INTEGER"} + } + } + find := func(name string) int { + return slices.IndexFunc(columns, func(c *model.EditColumn) bool { + return c != nil && asciiEqualFold(c.Name, name) + }) + } + all := func(names []string) []int { + key := make([]int, 0, len(names)) + for _, n := range names { + i := find(n) + if i < 0 { + return nil + } + key = append(key, i) + } + return key + } + var key []int + if len(meta.pk) > 0 { + if key = all(meta.pk); key == nil { + return nil, fmt.Sprintf("Read-only: add the primary key columns (%s) to the query to edit rows.", + strings.Join(meta.pk, ", ")) + } + } else { + for _, u := range meta.unique { + if key = all(u); key != nil { + break + } + } + if key == nil && hasRowid { + if i := find("rowid"); i >= 0 { + key = []int{i} + } + } + } + switch { + case key != nil: + return &model.EditTarget{Schema: model.Str(db), Table: table, Columns: columns, Key: key}, "" + case hasRowid: + return nil, fmt.Sprintf("Read-only: table %s has no primary key; add rowid to the query to edit rows.", table) + } + return nil, fmt.Sprintf("Read-only: table %s has no primary key.", table) +} + +func (s *Session) tableMeta(db, table string) (*tableMeta, error) { + key := tableKey{db, table} + if meta, ok := s.catalog[key]; ok { + return meta, nil + } + meta, err := s.loadTableMeta(db, table) + if err != nil { + return nil, err + } + s.catalog[key] = meta + return meta, nil +} + +// query runs sql with text parameters and calls row for each result row. +func (s *Session) query(sql string, params []string, row func(*sqlite3.Stmt)) error { + stmt, _, err := s.conn.Prepare(sql) + if err != nil { + return err + } + defer stmt.Close() + for i, p := range params { + if err := stmt.BindText(i+1, p); err != nil { + return err + } + } + for stmt.Step() { + row(stmt) + } + return stmt.Err() +} + +func (s *Session) loadTableMeta(db, table string) (*tableMeta, error) { + meta := &tableMeta{} + type pkColumn struct { + position int64 + name string + } + var pk []pkColumn + var notNull []string + err := s.query(`SELECT name, "notnull", pk, hidden FROM pragma_table_xinfo(?1, ?2) ORDER BY cid`, + []string{table, db}, func(st *sqlite3.Stmt) { + name := st.ColumnText(0) + if st.ColumnInt64(1) != 0 { + notNull = append(notNull, strings.ToLower(name)) + } + if position := st.ColumnInt64(2); position > 0 { + pk = append(pk, pkColumn{position, name}) + } + // hidden: 1 virtual table hidden column, 2 and 3 generated. + meta.columns = append(meta.columns, metaColumn{name, st.ColumnInt64(3) == 0}) + }) + if err != nil { + return nil, err + } + slices.SortFunc(pk, func(a, b pkColumn) int { + if a.position != b.position { + return int(a.position - b.position) + } + return strings.Compare(a.name, b.name) + }) + for _, c := range pk { + meta.pk = append(meta.pk, c.name) + } + + // Expression columns of an index have no name: such an index is not + // usable as a key. + type index struct { + name string + columns []string + usable bool + } + var indexes []*index + err = s.query(`SELECT il.name, ii.name FROM pragma_index_list(?1, ?2) AS il, `+ + `pragma_index_info(il.name, ?2) AS ii `+ + `WHERE il."unique" AND NOT il.partial AND il.origin <> 'pk' `+ + `ORDER BY il.seq, ii.seqno`, + []string{table, db}, func(st *sqlite3.Stmt) { + name := st.ColumnText(0) + if len(indexes) == 0 || indexes[len(indexes)-1].name != name { + indexes = append(indexes, &index{name: name, usable: true}) + } + entry := indexes[len(indexes)-1] + if st.ColumnType(1) != sqlite3.NULL { + column := st.ColumnText(1) + if slices.Contains(notNull, strings.ToLower(column)) { + entry.columns = append(entry.columns, column) + return + } + } + entry.usable = false + }) + if err != nil { + return nil, err + } + for _, ix := range indexes { + if ix.usable && len(ix.columns) > 0 { + meta.unique = append(meta.unique, ix.columns) + } + } + return meta, nil +} + +// planShape is what EXPLAIN QUERY PLAN says about where the rows come from. +type planShape struct { + // UNION, INTERSECT, EXCEPT or a recursive CTE produces rows. + compound bool + // Table scans that produce rows (joins count each table). + sources int +} + +type planLine struct { + id, parent int64 + detail string +} + +func (s *Session) queryPlan(sql string) (planShape, error) { + stmt, err := s.prepare("EXPLAIN QUERY PLAN " + sql) + if err != nil { + return planShape{}, err + } + if stmt == nil { + return planShape{}, apperr.Internalf("empty plan") + } + defer stmt.Close() + // Parameters stay unbound (NULL), as in Execute. + var lines []planLine + for stmt.Step() { + lines = append(lines, planLine{stmt.ColumnInt64(0), stmt.ColumnInt64(1), stmt.ColumnText(3)}) + } + if err := stmt.Err(); err != nil { + return planShape{}, err + } + return readPlan(lines), nil +} + +// readPlan reads plan rows. Subqueries in expressions (WHERE, select list) +// do not add rows; scans of a co-routine or materialized subquery read rows +// already counted inside it; an OR over several indexes is one scan. +func readPlan(lines []planLine) planShape { + ancestors := func(i int) []int { + var out []int + parent := lines[i].parent + for parent != 0 && len(out) < len(lines) { + p := slices.IndexFunc(lines, func(l planLine) bool { return l.id == parent }) + if p < 0 { + break + } + out = append(out, p) + parent = lines[p].parent + } + return out + } + hasPrefix := func(d string, prefixes ...string) bool { + return slices.ContainsFunc(prefixes, func(p string) bool { return strings.HasPrefix(d, p) }) + } + inExpression := func(d string) bool { + return hasPrefix(d, "SCALAR SUBQUERY", "CORRELATED SCALAR SUBQUERY", + "LIST SUBQUERY", "CORRELATED LIST SUBQUERY") + } + subqueryName := func(d string) (string, bool) { + if name, ok := strings.CutPrefix(d, "CO-ROUTINE "); ok { + return name, true + } + return strings.CutPrefix(d, "MATERIALIZE ") + } + names := func(rest, name string) bool { + r, ok := strings.CutPrefix(rest, name) + return ok && (r == "" || strings.HasPrefix(r, " ")) + } + var shape planShape + for i, line := range lines { + detail := line.detail + up := ancestors(i) + if inExpression(detail) || slices.ContainsFunc(up, func(a int) bool { return inExpression(lines[a].detail) }) { + continue + } + if hasPrefix(detail, "COMPOUND", "MERGE (", "SETUP", "RECURSIVE STEP", "LEFT-MOST SUBQUERY") { + shape.compound = true + } + if strings.HasPrefix(detail, "MULTI-INDEX OR") { + shape.sources++ + continue + } + if slices.ContainsFunc(up, func(a int) bool { return strings.HasPrefix(lines[a].detail, "MULTI-INDEX OR") }) { + continue + } + rest, ok := strings.CutPrefix(detail, "SCAN ") + if !ok { + if rest, ok = strings.CutPrefix(detail, "SEARCH "); !ok { + continue + } + } + // A constant row, or an EXISTS turned into a semi-join: no rows. + if strings.HasPrefix(rest, "CONSTANT ROW") || strings.Contains(rest, " EXISTS") { + continue + } + readsSubquery := false + for j, l := range lines { + if name, ok := subqueryName(l.detail); ok && names(rest, name) && !slices.Contains(up, j) { + readsSubquery = true + break + } + } + if !readsSubquery { + shape.sources++ + } + } + return shape +} + +type changeOp int + +const ( + opUpdate changeOp = iota + opDelete + opInsert +) + +// step is one statement of an apply, with its bound values. +type step struct { + // 1-based index of the change, for messages. + row int + op changeOp + sql string + params []any +} + +func planChanges(target model.EditTarget, changes []model.RowChange) ([]step, error) { + table := quoteIdent(target.Table) + if target.Schema != nil { + table = quoteIdent(*target.Schema) + "." + table + } + steps := make([]step, 0, len(changes)) + for i, change := range changes { + var params []any + var op changeOp + var sql string + switch change.Op { + case model.OpUpdate: + if len(change.Values) == 0 { + // Nothing to save for this row. + continue + } + sets := make([]string, 0, len(change.Values)) + for _, v := range change.Values { + column, err := targetColumn(target, v.Column) + if err != nil { + return nil, err + } + sets = append(sets, quoteIdent(column.Name)+" = ?") + value, err := toValue(v.Value, column.TypeName) + if err != nil { + return nil, err + } + params = append(params, value) + } + cond, err := keyCondition(target, change.Key, ¶ms) + if err != nil { + return nil, err + } + op, sql = opUpdate, "UPDATE "+table+" SET "+strings.Join(sets, ", ")+" WHERE "+cond + case model.OpDelete: + cond, err := keyCondition(target, change.Key, ¶ms) + if err != nil { + return nil, err + } + op, sql = opDelete, "DELETE FROM "+table+" WHERE "+cond + case model.OpInsert: + if len(change.Values) == 0 { + op, sql = opInsert, "INSERT INTO "+table+" DEFAULT VALUES" + break + } + names := make([]string, 0, len(change.Values)) + for _, v := range change.Values { + column, err := targetColumn(target, v.Column) + if err != nil { + return nil, err + } + names = append(names, quoteIdent(column.Name)) + value, err := toValue(v.Value, column.TypeName) + if err != nil { + return nil, err + } + params = append(params, value) + } + marks := strings.TrimSuffix(strings.Repeat("?, ", len(names)), ", ") + op, sql = opInsert, "INSERT INTO "+table+" ("+strings.Join(names, ", ")+") VALUES ("+marks+")" + default: + return nil, apperr.Invalidf("Unknown change %q.", change.Op) + } + steps = append(steps, step{row: i + 1, op: op, sql: sql, params: params}) + } + return steps, nil +} + +func targetColumn(target model.EditTarget, index int) (*model.EditColumn, error) { + if index >= 0 && index < len(target.Columns) && target.Columns[index] != nil { + return target.Columns[index], nil + } + return nil, apperr.Invalidf("Result column %d is not a table column and cannot be edited.", index+1) +} + +func keyCondition(target model.EditTarget, key []*string, params *[]any) (string, error) { + if len(key) != len(target.Key) { + return "", apperr.Invalidf("The row key does not match the key columns of the result.") + } + parts := make([]string, 0, len(key)) + for i, index := range target.Key { + column, err := targetColumn(target, index) + if err != nil { + return "", err + } + name := quoteIdent(column.Name) + if key[i] == nil { + parts = append(parts, name+" IS NULL") + continue + } + parts = append(parts, name+" = ?") + value, err := toValue(key[i], column.TypeName) + if err != nil { + return "", err + } + *params = append(*params, value) + } + return strings.Join(parts, " AND "), nil +} + +func (s *Session) ApplyChanges(ctx context.Context, req model.ApplyRequest) (*model.ApplyResult, error) { + // Every value is converted before anything runs. + steps, err := planChanges(req.Target, req.Changes) + if err != nil { + return nil, err + } + release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + autocommit := s.TxState().Autocommit + started := time.Now() + result, err := s.applySteps(steps, autocommit) + inTransaction := !s.conn.GetAutocommit() + s.setInTransaction(inTransaction) + if err != nil { + return nil, err + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.InTransaction = inTransaction + return result, nil +} + +// applySteps runs the steps as one unit. Outside a transaction it opens one: +// with autocommit it commits, in manual mode it stays open, as for user +// statements. Inside an open transaction a savepoint undoes a failed batch +// and keeps earlier work. +func (s *Session) applySteps(steps []step, autocommit bool) (*model.ApplyResult, error) { + result := &model.ApplyResult{} + if s.conn.GetAutocommit() { + begin := "BEGIN" + if autocommit { + begin = "BEGIN IMMEDIATE" + } + if err := s.conn.Exec(begin); err != nil { + return nil, mapError(err, "") + } + err := s.runSteps(steps, result) + if err == nil && autocommit { + if e := s.conn.Exec("COMMIT"); e != nil { + err = mapError(e, "") + } + } + if err != nil { + if !s.conn.GetAutocommit() { + s.clearInterrupt() + _ = s.conn.Exec("ROLLBACK") + } + return nil, err + } + return result, nil + } + if err := s.conn.Exec("SAVEPOINT lq_apply"); err != nil { + return nil, mapError(err, "") + } + err := s.runSteps(steps, result) + if err != nil { + s.clearInterrupt() + _ = s.conn.Exec("ROLLBACK TO lq_apply") + } + released := s.conn.Exec("RELEASE lq_apply") + if err != nil { + return nil, err + } + if released != nil { + return nil, mapError(released, "") + } + return result, nil +} + +func (s *Session) runSteps(steps []step, result *model.ApplyResult) error { + for _, st := range steps { + changed, err := s.execStep(st) + if err != nil { + e := *mapError(err, st.sql) + // The position would point into SQL the user never saw. + e.Position = nil + if e.Kind == apperr.Database { + e.Message = fmt.Sprintf("Row %d was not saved: %s", st.row, e.Message) + } + return &e + } + switch { + case st.op == opInsert: + result.Inserted += uint64(changed) + case changed != 1: + why := "" + if changed == 0 { + why = " (changed or removed by someone else)" + } + return apperr.Newf(apperr.Database, "Row %d was not saved: %d rows matched its key%s.", st.row, changed, why) + case st.op == opUpdate: + result.Updated++ + default: + result.Deleted++ + } + } + return nil +} + +func (s *Session) execStep(st step) (int64, error) { + stmt, _, err := s.conn.Prepare(st.sql) + if err != nil { + return 0, err + } + defer stmt.Close() + for i, p := range st.params { + if err := bind(stmt, i+1, p); err != nil { + return 0, err + } + } + if err := stmt.Exec(); err != nil { + return 0, err + } + return s.conn.Changes(), nil +} + +func bind(stmt *sqlite3.Stmt, param int, value any) error { + switch v := value.(type) { + case nil: + return stmt.BindNull(param) + case int64: + return stmt.BindInt64(param, v) + case float64: + return stmt.BindFloat(param, v) + case string: + return stmt.BindText(param, v) + case []byte: + return stmt.BindBlob(param, v) + } + return apperr.Internalf("cannot bind %T", value) +} diff --git a/internal/drivers/sqlite/edit_test.go b/internal/drivers/sqlite/edit_test.go new file mode 100644 index 0000000..2517e6d --- /dev/null +++ b/internal/drivers/sqlite/edit_test.go @@ -0,0 +1,640 @@ +package sqlite + +import ( + "math" + "reflect" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func set(column int, value *string) model.CellValue { + return model.CellValue{Column: column, Value: value} +} + +func s(v string) *string { return &v } + +func key(values ...*string) []*string { return values } + +func ec(name, typeName string) *model.EditColumn { + return &model.EditColumn{Name: name, TypeName: typeName} +} + +func update(k []*string, values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpUpdate, Key: k, Values: values} +} + +func del(k []*string) model.RowChange { return model.RowChange{Op: model.OpDelete, Key: k} } + +func insert(values ...model.CellValue) model.RowChange { + return model.RowChange{Op: model.OpInsert, Values: values} +} + +func (db *tempDB) target(sql string) *model.EditTarget { + db.t.Helper() + r := db.run(sql) + if r.ReadOnlyReason != nil { + db.t.Fatalf("%s: %s", sql, *r.ReadOnlyReason) + } + if r.Editable == nil { + db.t.Fatalf("%s: not editable", sql) + } + return r.Editable +} + +func (db *tempDB) reason(sql string) string { + db.t.Helper() + r := db.run(sql) + if r.Editable != nil { + db.t.Fatalf("%s: editable", sql) + } + if r.ReadOnlyReason == nil { + db.t.Fatalf("%s: no reason", sql) + } + return *r.ReadOnlyReason +} + +func (db *tempDB) apply(target *model.EditTarget, changes ...model.RowChange) (*model.ApplyResult, error) { + return db.s.ApplyChanges(bg, model.ApplyRequest{Target: *target, Changes: changes}) +} + +func (db *tempDB) mustApply(target *model.EditTarget, changes ...model.RowChange) *model.ApplyResult { + db.t.Helper() + r, err := db.apply(target, changes...) + if err != nil { + db.t.Fatal(err) + } + return r +} + +func (db *tempDB) applyErr(target *model.EditTarget, changes ...model.RowChange) *apperr.Error { + db.t.Helper() + _, err := db.apply(target, changes...) + if err == nil { + db.t.Fatal("no error") + } + return asApp(db.t, err) +} + +func TestAffinityRules(t *testing.T) { + cases := map[string]affinityKind{ + "INTEGER": affInteger, + "BIGINT": affInteger, + // "POINT" contains INT, as in SQLite. + "POINT": affInteger, + "VARCHAR(20)": affText, + "CLOB": affText, + "BLOB": affBlob, + "": affBlob, + "DOUBLE PRECISION": affReal, + "FLOAT": affReal, + "NUMERIC(10,2)": affNumeric, + "DECIMAL": affNumeric, + "BOOLEAN": affNumeric, + "DATETIME": affNumeric, + } + for decl, want := range cases { + if got := affinity(decl); got != want { + t.Errorf("affinity(%q) = %d, want %d", decl, got, want) + } + } +} + +func TestConvertsTextByAffinity(t *testing.T) { + v := func(text, decl string) any { + t.Helper() + out, err := toValue(&text, decl) + if err != nil { + t.Fatalf("%q %q: %v", text, decl, err) + } + return out + } + if out, err := toValue(nil, "INTEGER"); out != nil || err != nil { + t.Errorf("NULL: %v %v", out, err) + } + cases := []struct { + text, decl string + want any + }{ + {"-42", "INTEGER", int64(-42)}, + {" 7 ", "INT", int64(7)}, + {"2.5", "INTEGER", 2.5}, + {"abc", "INTEGER", "abc"}, + {"3.0", "REAL", 3.0}, + {"1.0e+300", "REAL", 1e300}, + {"-1.5e-7", "DOUBLE", -1.5e-7}, + {"Inf", "REAL", math.Inf(1)}, + {"-Inf", "REAL", math.Inf(-1)}, + {"NaN", "REAL", "NaN"}, + {"12.5", "NUMERIC(10,2)", 12.5}, + {"12", "DECIMAL", int64(12)}, + {"0x10", "NUMERIC", "0x10"}, + {"true", "BOOLEAN", int64(1)}, + {"FALSE", "BOOL", int64(0)}, + {"true", "NUMERIC", "true"}, + {"2024-05-01 13:45:00.123", "DATETIME", "2024-05-01 13:45:00.123"}, + // TEXT affinity keeps everything as typed. + {"42", "TEXT", "42"}, + {"X'00'", "VARCHAR", "X'00'"}, + // No affinity: the display format tells the storage class. + {"X'00FF10'", "BLOB", []byte{0, 0xff, 0x10}}, + {"x''", "", []byte{}}, + {"X'0'", "BLOB", "X'0'"}, + {"X'ZZ'", "BLOB", "X'ZZ'"}, + {"42", "", int64(42)}, + {"007", "", "007"}, + {"3.0", "BLOB", 3.0}, + {"3.50", "", "3.50"}, + {"hello", "", "hello"}, + // Ordinary text with an ellipsis is not a preview. + {"wait… (2)", "TEXT", "wait… (2)"}, + } + for _, c := range cases { + if got := v(c.text, c.decl); !reflect.DeepEqual(got, c.want) { + t.Errorf("toValue(%q, %q) = %#v, want %#v", c.text, c.decl, got, c.want) + } + } + + _, err := toValue(s("X'0000'… (40000 bytes)"), "BLOB") + if e := asApp(t, err); e.Kind != apperr.Invalid || e.Message != "This value is only a preview and cannot be saved." { + t.Errorf("%+v", e) + } +} + +func TestBuildsStatements(t *testing.T) { + target := model.EditTarget{ + Schema: s("main"), + Table: `lq_edit Odd "T"`, + Columns: []*model.EditColumn{ec("My Id", "INTEGER"), ec("v", "TEXT"), nil, ec("k2", "TEXT")}, + Key: []int{0, 3}, + } + steps, err := planChanges(target, []model.RowChange{ + update(key(s("1"), nil), set(1, s("it's")), set(0, s("2"))), + update(key(s("9"), s("x"))), + del(key(s("3"), s("b"))), + insert(set(1, nil), set(3, s("k"))), + insert(), + }) + if err != nil { + t.Fatal(err) + } + tbl := `"main"."lq_edit Odd ""T"""` + want := []step{ + {1, opUpdate, `UPDATE ` + tbl + ` SET "v" = ?, "My Id" = ? WHERE "My Id" = ? AND "k2" IS NULL`, + []any{"it's", int64(2), int64(1)}}, + {3, opDelete, `DELETE FROM ` + tbl + ` WHERE "My Id" = ? AND "k2" = ?`, []any{int64(3), "b"}}, + {4, opInsert, `INSERT INTO ` + tbl + ` ("v", "k2") VALUES (?, ?)`, []any{nil, "k"}}, + {5, opInsert, `INSERT INTO ` + tbl + ` DEFAULT VALUES`, nil}, + } + if !reflect.DeepEqual(steps, want) { + t.Errorf("steps\n%#v\nwant\n%#v", steps, want) + } + + for _, changes := range [][]model.RowChange{ + {insert(set(2, s("x")))}, + {del(key(s("1")))}, + {update(key(s("1"), s("a")), set(1, s("X'00'… (9 bytes)")))}, + {{Op: "merge"}}, + } { + _, err := planChanges(target, changes) + if e := asApp(t, err); e.Kind != apperr.Invalid { + t.Errorf("%+v: %+v", changes, e) + } + } +} + +func TestReadsQueryPlans(t *testing.T) { + type line = planLine + shape := func(lines ...line) [2]any { + sh := readPlan(lines) + return [2]any{sh.compound, sh.sources} + } + check := func(got [2]any, compound bool, sources int) { + t.Helper() + if got != [2]any{compound, sources} { + t.Errorf("got %v, want %v %d", got, compound, sources) + } + } + check(shape(line{2, 0, "SCAN t"}), false, 1) + // OR over two indexes is one scan. + check(shape( + line{4, 0, "MULTI-INDEX OR"}, + line{5, 4, "INDEX 1"}, + line{11, 5, "SEARCH t USING INDEX t_name (name=?)"}, + line{16, 4, "INDEX 2"}, + line{22, 16, "SEARCH t USING INDEX t_n (n=?)"}, + ), false, 1) + // EXISTS as a semi-join, and subqueries in expressions. + check(shape( + line{4, 0, "SCAN t"}, + line{6, 0, "SEARCH u EXISTS USING PRIMARY KEY (a=?)"}, + ), false, 1) + check(shape( + line{2, 0, "SEARCH t USING INTEGER PRIMARY KEY (rowid=?)"}, + line{6, 0, "LIST SUBQUERY 2"}, + line{8, 6, "MERGE (UNION)"}, + line{10, 8, "LEFT"}, + line{13, 10, "SCAN u"}, + line{23, 0, "CORRELATED SCALAR SUBQUERY 1"}, + line{29, 23, "SCAN u"}, + ), false, 1) + // Window functions read t through a co-routine. + check(shape( + line{3, 0, "CO-ROUTINE (subquery-2)"}, + line{6, 3, "SCAN t USING COVERING INDEX t_name"}, + line{18, 0, "SCAN (subquery-2)"}, + ), false, 1) + // A subquery aliased with the name of its table. + check(shape(line{2, 0, "CO-ROUTINE t"}, line{5, 2, "SCAN t"}, line{9, 0, "SCAN t"}), false, 1) + // Joins, self-joins and compounds. + check(shape( + line{3, 0, "SCAN a"}, + line{5, 0, "SEARCH b USING INTEGER PRIMARY KEY (rowid=?)"}, + ), false, 2) + check(shape( + line{1, 0, "COMPOUND QUERY"}, + line{2, 1, "LEFT-MOST SUBQUERY"}, + line{4, 2, "SCAN t"}, + line{10, 1, "UNION ALL"}, + line{12, 10, "SCAN CONSTANT ROW"}, + ), true, 1) + if got := shape( + line{2, 0, "CO-ROUTINE r"}, + line{5, 2, "SETUP"}, + line{7, 5, "SCAN t"}, + line{20, 2, "RECURSIVE STEP"}, + line{21, 20, "SCAN r"}, + line{31, 0, "SCAN r"}, + ); got[0] != true { + t.Error("recursive CTE is compound") + } + check(shape(line{2, 0, "SCAN CONSTANT ROW"}), false, 0) +} + +func colsOf(columns []*model.EditColumn) []string { + out := make([]string, len(columns)) + for i, c := range columns { + if c == nil { + out[i] = "" + } else { + out[i] = c.Name + ":" + c.TypeName + } + } + return out +} + +func TestDetectsEditableResults(t *testing.T) { + db := newTempDB(t, "edit-detect") + db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, name TEXT NOT NULL, n NUMERIC(10,2), " + + "g TEXT GENERATED ALWAYS AS (name || '!') VIRTUAL)") + db.run("CREATE INDEX lq_edit_t_name ON lq_edit_t (name)") + db.run("CREATE INDEX lq_edit_t_n ON lq_edit_t (n)") + db.run("INSERT INTO lq_edit_t (name, n) VALUES ('a', 1), ('b', 2)") + db.run("CREATE TABLE lq_edit_c (b TEXT, a INT, v TEXT, PRIMARY KEY (b, a)) WITHOUT ROWID") + db.run("CREATE TABLE lq_edit_nk (x INT, y TEXT)") + db.run("CREATE TABLE lq_edit_u (code TEXT NOT NULL UNIQUE, maybe TEXT UNIQUE, v TEXT)") + db.run("CREATE VIEW lq_edit_v AS SELECT id, name FROM lq_edit_t WHERE id > 0") + db.run("CREATE VIEW lq_edit_vu AS SELECT id, name FROM lq_edit_t UNION ALL SELECT x, y FROM lq_edit_nk") + + tg := db.target("SELECT id, name, name || '?' AS e, n, g FROM lq_edit_t") + if deref(tg.Schema) != "main" || tg.Table != "lq_edit_t" || !reflect.DeepEqual(tg.Key, []int{0}) { + t.Errorf("%+v", tg) + } + // Generated columns cannot be written. + if got := colsOf(tg.Columns); !reflect.DeepEqual(got, []string{"id:INTEGER", "name:TEXT", "", "n:NUMERIC(10,2)", ""}) { + t.Errorf("columns %q", got) + } + if k := db.target("SELECT name, id AS k FROM lq_edit_t").Key; !reflect.DeepEqual(k, []int{1}) { + t.Errorf("key %v", k) + } + // rowid of a table with INTEGER PRIMARY KEY is the key column. + if got := colsOf(db.target("SELECT rowid, name FROM lq_edit_t").Columns)[0]; got != "id:INTEGER" { + t.Errorf("rowid %q", got) + } + // Composite key in key order, whatever the result order. + if k := db.target("SELECT v, a, b FROM lq_edit_c").Key; !reflect.DeepEqual(k, []int{2, 1}) { + t.Errorf("composite key %v", k) + } + // Filters, sorting, OR over indexes, subqueries and window functions. + for _, sql := range []string{ + "SELECT * FROM lq_edit_t WHERE name = 'a' OR n = 2 ORDER BY name", + "SELECT * FROM lq_edit_t WHERE id IN (SELECT a FROM lq_edit_c)", + "SELECT * FROM lq_edit_t t WHERE EXISTS (SELECT 1 FROM lq_edit_c c WHERE c.b = t.name)", + "SELECT id, (SELECT count(*) FROM lq_edit_c) AS c FROM lq_edit_t", + "SELECT id, name, row_number() OVER (ORDER BY name) FROM lq_edit_t", + "SELECT * FROM (SELECT id, name FROM lq_edit_t ORDER BY name LIMIT 5)", + "WITH c AS (SELECT * FROM lq_edit_t) SELECT * FROM c", + // SQLite resolves view columns to the base table. + "SELECT * FROM lq_edit_v", + } { + tg := db.target(sql) + if tg.Table != "lq_edit_t" || !reflect.DeepEqual(tg.Key, []int{0}) { + t.Errorf("%s: %+v", sql, tg) + } + } + if got := colsOf(db.target("SELECT id, (SELECT 1) FROM lq_edit_t").Columns)[1]; got != "" { + t.Errorf("expression %q", got) + } + + reasons := []struct{ sql, want string }{ + {"SELECT t.id, c.v FROM lq_edit_t t JOIN lq_edit_c c ON c.b = t.name", + "Read-only: the result combines columns from several tables."}, + {"SELECT a.id, b.name FROM lq_edit_t a JOIN lq_edit_t b ON b.id = a.id + 1", + "Read-only: the result combines rows from several tables."}, + {"SELECT id, name FROM lq_edit_t UNION ALL SELECT 9, 'z'", + "Read-only: the result combines rows from several queries."}, + {"SELECT * FROM lq_edit_vu", "Read-only: the result combines rows from several queries."}, + {"SELECT 1, 'x'", "Read-only: only rows from a table can be edited."}, + {"SELECT count(*) FROM lq_edit_t", "Read-only: only rows from a table can be edited."}, + {"SELECT name, n FROM lq_edit_t", "Read-only: add the primary key columns (id) to the query to edit rows."}, + {"SELECT v, a FROM lq_edit_c", "Read-only: add the primary key columns (b, a) to the query to edit rows."}, + {"SELECT * FROM lq_edit_nk", + "Read-only: table lq_edit_nk has no primary key; add rowid to the query to edit rows."}, + } + for _, c := range reasons { + if got := db.reason(c.sql); got != c.want { + t.Errorf("%s: %q", c.sql, got) + } + } + // Without a primary key: rowid, oid or _rowid_ in the result. + for _, sql := range []string{ + "SELECT rowid, * FROM lq_edit_nk", + "SELECT x, oid FROM lq_edit_nk", + "SELECT _rowid_, y FROM lq_edit_nk", + } { + tg := db.target(sql) + if got := colsOf(tg.Columns)[tg.Key[0]]; got != "rowid:INTEGER" { + t.Errorf("%s: %q", sql, got) + } + } + // A UNIQUE NOT NULL key; the nullable one does not count. + if k := db.target("SELECT v, code FROM lq_edit_u").Key; !reflect.DeepEqual(k, []int{1}) { + t.Errorf("unique key %v", k) + } + if got := db.reason("SELECT v, maybe FROM lq_edit_u"); got != + "Read-only: table lq_edit_u has no primary key; add rowid to the query to edit rows." { + t.Errorf("nullable unique: %q", got) + } + + // Attached and temporary schemas. + db.attach("edit-detect-other", "extra") + db.run("CREATE TABLE extra.lq_edit_t (k TEXT PRIMARY KEY, v)") + db.run("CREATE TEMP TABLE lq_edit_tmp (k INTEGER PRIMARY KEY, v)") + tg = db.target("SELECT v, k FROM extra.lq_edit_t") + if deref(tg.Schema) != "extra" || !reflect.DeepEqual(tg.Key, []int{1}) || colsOf(tg.Columns)[0] != "v:" { + t.Errorf("attached %+v %q", tg, colsOf(tg.Columns)) + } + if tg := db.target("SELECT * FROM lq_edit_tmp"); deref(tg.Schema) != "temp" { + t.Errorf("temp %+v", tg) + } + + // Statements that are not queries say nothing. + for _, sql := range []string{ + "PRAGMA table_info(lq_edit_t)", + "INSERT INTO lq_edit_nk VALUES (1, 'r') RETURNING *", + "EXPLAIN QUERY PLAN SELECT * FROM lq_edit_t", + } { + if r := db.run(sql); r.Editable != nil || r.ReadOnlyReason != nil { + t.Errorf("%s: %+v", sql, r) + } + } + + // Keys are reloaded after DDL. + db.run("DROP TABLE lq_edit_nk") + db.run("CREATE TABLE lq_edit_nk (x INT PRIMARY KEY, y TEXT)") + if k := db.target("SELECT y, x FROM lq_edit_nk").Key; !reflect.DeepEqual(k, []int{1}) { + t.Errorf("reloaded key %v", k) + } + + db.run("DETACH DATABASE extra") +} + +func TestAppliesUpdatesDeletesAndInserts(t *testing.T) { + db := newTempDB(t, "edit-apply") + db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, name TEXT NOT NULL DEFAULT 'none', n INT DEFAULT 5)") + db.run("INSERT INTO lq_edit_t (name, n) VALUES ('a', 1), ('b', 2), ('c', 3)") + tg := db.target("SELECT id, name, n, n * 2 FROM lq_edit_t") + r := db.mustApply(tg, + update(key(s("1")), set(1, s("a'2\nline")), set(2, nil)), + del(key(s("2"))), + insert(set(1, s("d"))), + insert(), + ) + if r.Updated != 1 || r.Deleted != 1 || r.Inserted != 2 || r.InTransaction || db.s.TxState().InTransaction { + t.Errorf("%+v", r) + } + want := texts( + []string{"1", "a'2\nline", ""}, + []string{"3", "c", "3"}, + []string{"4", "d", "5"}, + []string{"5", "none", "5"}, + ) + if got := db.rows("SELECT id, name, n FROM lq_edit_t ORDER BY id"); !reflect.DeepEqual(got, want) { + t.Errorf("rows %v", got) + } + // Changing the key itself. + db.mustApply(tg, update(key(s("5")), set(0, s("50")))) + if got := deref(db.scalar("SELECT name FROM lq_edit_t WHERE id = 50")); got != "none" { + t.Errorf("moved row %q", got) + } + // A column that is not in the table. + if e := db.applyErr(tg, update(key(s("1")), set(3, s("1")))); e.Kind != apperr.Invalid { + t.Errorf("%+v", e) + } + + // A table without a key, edited through rowid. + db.run("CREATE TABLE lq_edit_nk (x INT, y TEXT)") + db.run("INSERT INTO lq_edit_nk VALUES (1, 'same'), (2, 'same')") + tg = db.target("SELECT rowid, x, y FROM lq_edit_nk") + db.mustApply(tg, update(key(s("2")), set(2, s("other"))), del(key(s("1")))) + if got := db.rows("SELECT rowid, x, y FROM lq_edit_nk"); !reflect.DeepEqual(got, texts([]string{"2", "2", "other"})) { + t.Errorf("rows %v", got) + } +} + +func TestRoundTripsDisplayedValues(t *testing.T) { + db := newTempDB(t, "edit-roundtrip") + db.run("CREATE TABLE lq_edit_types (id INTEGER PRIMARY KEY, i INTEGER, bi BIGINT, r REAL, " + + "d DOUBLE, num NUMERIC(10,2), dec DECIMAL(20,6), b BOOLEAN, dt DATE, ts DATETIME, " + + "tz TIMESTAMP WITH TIME ZONE, t TEXT, vc VARCHAR(40), bl BLOB, u, nu TEXT)") + db.run("INSERT INTO lq_edit_types VALUES (1, -42, 9223372036854775807, 2.5, 0.30000000000000004, " + + "12.5, 1234567.125, 1, '2024-02-29', '2024-05-01 13:45:00.123456', " + + "'2024-05-01T13:45:00.123+02:00', 'it''s \"q\"' || char(10) || 'line 2', 'olá', " + + "x'00FF10', 7, NULL)") + db.run("INSERT INTO lq_edit_types VALUES (2, 0, -9223372036854775808, 1e300, -1.5e-7, " + + "100, -0.5, 0, '1999-12-31', '2000-01-01 00:00:00', '2000-01-01T00:00:00Z', '', " + + "'42', x'', 2.5, 'x')") + db.run("INSERT INTO lq_edit_types VALUES (3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, " + + "NULL, NULL, NULL, NULL, NULL, 'text in untyped', NULL)") + typed := "SELECT * FROM lq_edit_types ORDER BY id" + classes := "SELECT id, typeof(i), typeof(bi), typeof(r), typeof(d), typeof(num), " + + "typeof(dec), typeof(b), typeof(dt), typeof(ts), typeof(tz), typeof(t), " + + "typeof(vc), typeof(bl), typeof(u), typeof(nu) FROM lq_edit_types ORDER BY id" + before := db.run(typed) + classesBefore := db.rows(classes) + tg := before.Editable + if tg == nil || !reflect.DeepEqual(tg.Key, []int{0}) { + t.Fatalf("%+v", before.ReadOnlyReason) + } + + // Write every displayed value back, keys included. + var changes []model.RowChange + for _, row := range before.Rows { + var values []model.CellValue + for i, v := range row { + values = append(values, set(i, v)) + } + changes = append(changes, update(key(row[0]), values...)) + } + if r := db.mustApply(tg, changes...); r.Updated != 3 { + t.Errorf("%+v", r) + } + if got := db.rows(typed); !reflect.DeepEqual(got, before.Rows) { + t.Errorf("values changed\n%v\n%v", got, before.Rows) + } + if got := db.rows(classes); !reflect.DeepEqual(got, classesBefore) { + t.Errorf("storage classes changed\n%v\n%v", got, classesBefore) + } + + // Values typed in the grid. + db.mustApply(tg, update(key(s("3")), + set(1, s("12")), set(3, s("3")), set(5, s("9.99")), set(7, s("true")), set(13, s("X'CAFE'")))) + got := db.rows("SELECT typeof(i), r, typeof(r), num, b, hex(bl) FROM lq_edit_types WHERE id = 3") + if want := texts([]string{"integer", "3.0", "real", "9.99", "1", "CAFE"}); !reflect.DeepEqual(got, want) { + t.Errorf("typed values %v", got) + } + + // A preview of a large blob cannot be saved. + db.run("UPDATE lq_edit_types SET bl = zeroblob(40000) WHERE id = 1") + preview := db.scalar("SELECT bl FROM lq_edit_types WHERE id = 1") + e := db.applyErr(tg, update(key(s("1")), set(13, preview))) + if e.Kind != apperr.Invalid || e.Message != "This value is only a preview and cannot be saved." { + t.Errorf("%+v", e) + } +} + +func TestFailedChangeRollsBackTheBatch(t *testing.T) { + db := newTempDB(t, "edit-rollback") + db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, name TEXT UNIQUE)") + db.run("INSERT INTO lq_edit_t VALUES (1, 'a'), (2, 'b')") + tg := db.target("SELECT id, name FROM lq_edit_t") + before := db.rows("SELECT * FROM lq_edit_t ORDER BY id") + + e := db.applyErr(tg, + update(key(s("1")), set(1, s("changed"))), + insert(set(1, s("new"))), + update(key(s("99")), set(1, s("gone"))), + ) + if e.Kind != apperr.Database || + e.Message != "Row 3 was not saved: 0 rows matched its key (changed or removed by someone else)." { + t.Errorf("%+v", e) + } + if got := db.rows("SELECT * FROM lq_edit_t ORDER BY id"); !reflect.DeepEqual(got, before) { + t.Errorf("rows %v", got) + } + if db.s.TxState().InTransaction { + t.Error("left a transaction") + } + + // Server errors keep their code and name the row. + e = db.applyErr(tg, + del(key(s("1"))), + update(key(s("2")), set(1, s("x"))), + insert(set(1, s("x"))), + ) + if e.Code != "SQLITE_CONSTRAINT_UNIQUE" || !strings.HasPrefix(e.Message, "Row 3 was not saved: UNIQUE") || + e.Position != nil { + t.Errorf("%+v", e) + } + if got := db.rows("SELECT * FROM lq_edit_t ORDER BY id"); !reflect.DeepEqual(got, before) { + t.Errorf("rows %v", got) + } + + // The session is still usable. + db.mustApply(tg, del(key(s("2")))) + if got := deref(db.scalar("SELECT count(*) FROM lq_edit_t")); got != "1" { + t.Errorf("count %s", got) + } +} + +func TestManualCommitKeepsTheTransaction(t *testing.T) { + db := newTempDB(t, "edit-manual") + db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, v TEXT)") + db.run("INSERT INTO lq_edit_t VALUES (1, 'a')") + tg := db.target("SELECT id, v FROM lq_edit_t") + if _, err := db.s.SetAutocommit(bg, false); err != nil { + t.Fatal(err) + } + if _, err := db.s.EndTransaction(bg, false); err != nil { + t.Fatal(err) + } + + r := db.mustApply(tg, insert(set(1, s("b")))) + if !r.InTransaction || !db.s.TxState().InTransaction { + t.Error("apply did not keep the transaction") + } + if _, err := db.s.EndTransaction(bg, false); err != nil { + t.Fatal(err) + } + if got := deref(db.scalar("SELECT count(*) FROM lq_edit_t")); got != "1" { + t.Errorf("count %s", got) + } + + // Inside an open transaction a failed batch undoes only itself. + db.run("INSERT INTO lq_edit_t VALUES (2, 'mine')") + e := db.applyErr(tg, update(key(s("1")), set(1, s("z"))), del(key(s("7")))) + if !strings.HasPrefix(e.Message, "Row 2 was not saved") { + t.Errorf("%+v", e) + } + if !db.s.TxState().InTransaction { + t.Error("failed batch ended the transaction") + } + if got := db.rows("SELECT id, v FROM lq_edit_t ORDER BY id"); !reflect.DeepEqual(got, texts([]string{"1", "a"}, []string{"2", "mine"})) { + t.Errorf("rows %v", got) + } + if r := db.mustApply(tg, update(key(s("1")), set(1, s("z")))); !r.InTransaction { + t.Error("apply ended the transaction") + } + if _, err := db.s.EndTransaction(bg, true); err != nil { + t.Fatal(err) + } + if got := db.rows("SELECT id, v FROM lq_edit_t ORDER BY id"); !reflect.DeepEqual(got, texts([]string{"1", "z"}, []string{"2", "mine"})) { + t.Errorf("rows %v", got) + } + + // Autocommit with a transaction the user opened: it stays open. + if _, err := db.s.SetAutocommit(bg, true); err != nil { + t.Fatal(err) + } + db.run("BEGIN") + if r := db.mustApply(tg, del(key(s("2")))); !r.InTransaction { + t.Error("apply ended the user's transaction") + } + db.run("ROLLBACK") + if got := deref(db.scalar("SELECT count(*) FROM lq_edit_t")); got != "2" { + t.Errorf("count %s", got) + } +} + +func TestEditsNamesThatNeedQuoting(t *testing.T) { + db := newTempDB(t, "edit-quoting") + db.run(`CREATE TABLE "lq_edit Mixed Case" ("My Id" INTEGER PRIMARY KEY, "Some ""Value""" TEXT)`) + db.run(`INSERT INTO "lq_edit Mixed Case" VALUES (1, 'a'), (2, 'b')`) + tg := db.target(`SELECT "Some ""Value""" AS v, "My Id" FROM "lq_edit Mixed Case" AS "q r"`) + if tg.Table != "lq_edit Mixed Case" || !reflect.DeepEqual(tg.Key, []int{1}) || colsOf(tg.Columns)[0] != `Some "Value":TEXT` { + t.Errorf("%+v %q", tg, colsOf(tg.Columns)) + } + r := db.mustApply(tg, + update(key(s("1")), set(0, s("A"))), + del(key(s("2"))), + insert(set(0, s("c")), set(1, s("10"))), + ) + if r.Updated != 1 || r.Deleted != 1 || r.Inserted != 1 { + t.Errorf("%+v", r) + } + if got := db.rows(`SELECT * FROM "lq_edit Mixed Case" ORDER BY 1`); !reflect.DeepEqual(got, texts([]string{"1", "A"}, []string{"10", "c"})) { + t.Errorf("rows %v", got) + } +} diff --git a/internal/drivers/sqlite/errors.go b/internal/drivers/sqlite/errors.go new file mode 100644 index 0000000..b3b1e1a --- /dev/null +++ b/internal/drivers/sqlite/errors.go @@ -0,0 +1,187 @@ +package sqlite + +import ( + "errors" + "strconv" + "strings" + "unicode/utf8" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// codeNames holds the (extended) result codes by name, as in the SQLite +// documentation. +var codeNames = map[int]string{ + int(sqlite3.ERROR): "SQLITE_ERROR", + int(sqlite3.INTERNAL): "SQLITE_INTERNAL", + int(sqlite3.PERM): "SQLITE_PERM", + int(sqlite3.ABORT): "SQLITE_ABORT", + int(sqlite3.BUSY): "SQLITE_BUSY", + int(sqlite3.LOCKED): "SQLITE_LOCKED", + int(sqlite3.NOMEM): "SQLITE_NOMEM", + int(sqlite3.READONLY): "SQLITE_READONLY", + int(sqlite3.INTERRUPT): "SQLITE_INTERRUPT", + int(sqlite3.IOERR): "SQLITE_IOERR", + int(sqlite3.CORRUPT): "SQLITE_CORRUPT", + int(sqlite3.NOTFOUND): "SQLITE_NOTFOUND", + int(sqlite3.FULL): "SQLITE_FULL", + int(sqlite3.CANTOPEN): "SQLITE_CANTOPEN", + int(sqlite3.PROTOCOL): "SQLITE_PROTOCOL", + int(sqlite3.EMPTY): "SQLITE_EMPTY", + int(sqlite3.SCHEMA): "SQLITE_SCHEMA", + int(sqlite3.TOOBIG): "SQLITE_TOOBIG", + int(sqlite3.CONSTRAINT): "SQLITE_CONSTRAINT", + int(sqlite3.MISMATCH): "SQLITE_MISMATCH", + int(sqlite3.MISUSE): "SQLITE_MISUSE", + int(sqlite3.NOLFS): "SQLITE_NOLFS", + int(sqlite3.AUTH): "SQLITE_AUTH", + int(sqlite3.FORMAT): "SQLITE_FORMAT", + int(sqlite3.RANGE): "SQLITE_RANGE", + int(sqlite3.NOTADB): "SQLITE_NOTADB", + + int(sqlite3.ERROR_MISSING_COLLSEQ): "SQLITE_ERROR_MISSING_COLLSEQ", + int(sqlite3.ERROR_RETRY): "SQLITE_ERROR_RETRY", + int(sqlite3.ERROR_SNAPSHOT): "SQLITE_ERROR_SNAPSHOT", + int(sqlite3.IOERR_READ): "SQLITE_IOERR_READ", + int(sqlite3.IOERR_SHORT_READ): "SQLITE_IOERR_SHORT_READ", + int(sqlite3.IOERR_WRITE): "SQLITE_IOERR_WRITE", + int(sqlite3.IOERR_FSYNC): "SQLITE_IOERR_FSYNC", + int(sqlite3.IOERR_DIR_FSYNC): "SQLITE_IOERR_DIR_FSYNC", + int(sqlite3.IOERR_TRUNCATE): "SQLITE_IOERR_TRUNCATE", + int(sqlite3.IOERR_FSTAT): "SQLITE_IOERR_FSTAT", + int(sqlite3.IOERR_UNLOCK): "SQLITE_IOERR_UNLOCK", + int(sqlite3.IOERR_RDLOCK): "SQLITE_IOERR_RDLOCK", + int(sqlite3.IOERR_DELETE): "SQLITE_IOERR_DELETE", + int(sqlite3.IOERR_BLOCKED): "SQLITE_IOERR_BLOCKED", + int(sqlite3.IOERR_NOMEM): "SQLITE_IOERR_NOMEM", + int(sqlite3.IOERR_ACCESS): "SQLITE_IOERR_ACCESS", + int(sqlite3.IOERR_CHECKRESERVEDLOCK): "SQLITE_IOERR_CHECKRESERVEDLOCK", + int(sqlite3.IOERR_LOCK): "SQLITE_IOERR_LOCK", + int(sqlite3.IOERR_CLOSE): "SQLITE_IOERR_CLOSE", + int(sqlite3.IOERR_DIR_CLOSE): "SQLITE_IOERR_DIR_CLOSE", + int(sqlite3.IOERR_SHMOPEN): "SQLITE_IOERR_SHMOPEN", + int(sqlite3.IOERR_SHMSIZE): "SQLITE_IOERR_SHMSIZE", + int(sqlite3.IOERR_SHMLOCK): "SQLITE_IOERR_SHMLOCK", + int(sqlite3.IOERR_SHMMAP): "SQLITE_IOERR_SHMMAP", + int(sqlite3.IOERR_SEEK): "SQLITE_IOERR_SEEK", + int(sqlite3.IOERR_DELETE_NOENT): "SQLITE_IOERR_DELETE_NOENT", + int(sqlite3.IOERR_MMAP): "SQLITE_IOERR_MMAP", + int(sqlite3.IOERR_GETTEMPPATH): "SQLITE_IOERR_GETTEMPPATH", + int(sqlite3.IOERR_CONVPATH): "SQLITE_IOERR_CONVPATH", + int(sqlite3.IOERR_VNODE): "SQLITE_IOERR_VNODE", + int(sqlite3.IOERR_AUTH): "SQLITE_IOERR_AUTH", + int(sqlite3.IOERR_BEGIN_ATOMIC): "SQLITE_IOERR_BEGIN_ATOMIC", + int(sqlite3.IOERR_COMMIT_ATOMIC): "SQLITE_IOERR_COMMIT_ATOMIC", + int(sqlite3.IOERR_ROLLBACK_ATOMIC): "SQLITE_IOERR_ROLLBACK_ATOMIC", + int(sqlite3.IOERR_DATA): "SQLITE_IOERR_DATA", + int(sqlite3.IOERR_CORRUPTFS): "SQLITE_IOERR_CORRUPTFS", + int(sqlite3.LOCKED_SHAREDCACHE): "SQLITE_LOCKED_SHAREDCACHE", + int(sqlite3.LOCKED_VTAB): "SQLITE_LOCKED_VTAB", + int(sqlite3.BUSY_RECOVERY): "SQLITE_BUSY_RECOVERY", + int(sqlite3.BUSY_SNAPSHOT): "SQLITE_BUSY_SNAPSHOT", + int(sqlite3.BUSY_TIMEOUT): "SQLITE_BUSY_TIMEOUT", + int(sqlite3.CANTOPEN_NOTEMPDIR): "SQLITE_CANTOPEN_NOTEMPDIR", + int(sqlite3.CANTOPEN_ISDIR): "SQLITE_CANTOPEN_ISDIR", + int(sqlite3.CANTOPEN_FULLPATH): "SQLITE_CANTOPEN_FULLPATH", + int(sqlite3.CANTOPEN_CONVPATH): "SQLITE_CANTOPEN_CONVPATH", + int(sqlite3.CANTOPEN) | 5<<8: "SQLITE_CANTOPEN_DIRTYWAL", + int(sqlite3.CANTOPEN_SYMLINK): "SQLITE_CANTOPEN_SYMLINK", + int(sqlite3.CORRUPT_VTAB): "SQLITE_CORRUPT_VTAB", + int(sqlite3.CORRUPT_SEQUENCE): "SQLITE_CORRUPT_SEQUENCE", + int(sqlite3.CORRUPT_INDEX): "SQLITE_CORRUPT_INDEX", + int(sqlite3.READONLY_RECOVERY): "SQLITE_READONLY_RECOVERY", + int(sqlite3.READONLY_CANTLOCK): "SQLITE_READONLY_CANTLOCK", + int(sqlite3.READONLY_ROLLBACK): "SQLITE_READONLY_ROLLBACK", + int(sqlite3.READONLY_DBMOVED): "SQLITE_READONLY_DBMOVED", + int(sqlite3.READONLY_CANTINIT): "SQLITE_READONLY_CANTINIT", + int(sqlite3.READONLY_DIRECTORY): "SQLITE_READONLY_DIRECTORY", + int(sqlite3.ABORT_ROLLBACK): "SQLITE_ABORT_ROLLBACK", + int(sqlite3.CONSTRAINT_CHECK): "SQLITE_CONSTRAINT_CHECK", + int(sqlite3.CONSTRAINT_COMMITHOOK): "SQLITE_CONSTRAINT_COMMITHOOK", + int(sqlite3.CONSTRAINT_FOREIGNKEY): "SQLITE_CONSTRAINT_FOREIGNKEY", + int(sqlite3.CONSTRAINT_FUNCTION): "SQLITE_CONSTRAINT_FUNCTION", + int(sqlite3.CONSTRAINT_NOTNULL): "SQLITE_CONSTRAINT_NOTNULL", + int(sqlite3.CONSTRAINT_PRIMARYKEY): "SQLITE_CONSTRAINT_PRIMARYKEY", + int(sqlite3.CONSTRAINT_TRIGGER): "SQLITE_CONSTRAINT_TRIGGER", + int(sqlite3.CONSTRAINT_UNIQUE): "SQLITE_CONSTRAINT_UNIQUE", + int(sqlite3.CONSTRAINT_VTAB): "SQLITE_CONSTRAINT_VTAB", + int(sqlite3.CONSTRAINT_ROWID): "SQLITE_CONSTRAINT_ROWID", + int(sqlite3.CONSTRAINT_PINNED): "SQLITE_CONSTRAINT_PINNED", + int(sqlite3.CONSTRAINT_DATATYPE): "SQLITE_CONSTRAINT_DATATYPE", + int(sqlite3.AUTH_USER): "SQLITE_AUTH_USER", +} + +// codeName names an (extended) result code; unknown extended codes fall +// back to their primary code. +func codeName(code int) string { + if name, ok := codeNames[code]; ok { + return name + } + if name, ok := codeNames[code&0xff]; ok { + return name + } + return "SQLITE_" + strconv.Itoa(code) +} + +// errstr is sqlite3_errstr: the English text of a result code. +func errstr(code sqlite3.ExtendedErrorCode) string { + return strings.TrimPrefix(code.Error(), "sqlite3: ") +} + +// sqliteError builds the error for a result code and the message SQLite +// gave, or the text of the code when it gave none. +func sqliteError(code sqlite3.ExtendedErrorCode, msg string) *apperr.Error { + if msg == "" { + msg = errstr(code) + } + err := apperr.New(apperr.Database, msg) + if code.Code() == sqlite3.INTERRUPT { + err.Kind = apperr.Cancelled + err.Message = "The statement was cancelled." + } + err.Code = codeName(int(code)) + return err +} + +// mapError turns a driver error into an *apperr.Error. sql is the statement +// that was prepared: a syntax error's byte offset in it becomes a character +// position. +func mapError(err error, sql string) *apperr.Error { + if err == nil { + return nil + } + var app *apperr.Error + if errors.As(err, &app) { + return app + } + var se *sqlite3.Error + if errors.As(err, &se) { + code := se.ExtendedCode() + // Error() is "sqlite3: [: ][: ]". + msg := strings.TrimPrefix(strings.TrimPrefix(se.Error(), code.Error()), ": ") + if sys := se.Unwrap(); sys != nil { + msg = strings.TrimSuffix(strings.TrimSuffix(msg, sys.Error()), ": ") + } + out := sqliteError(code, msg) + if rest := se.SQL(); sql != "" && rest != "" && strings.HasSuffix(sql, rest) { + // SQLite reports a byte offset; the interface wants characters. + pos := utf8.RuneCountInString(sql[:len(sql)-len(rest)]) + out.Position = &pos + } + return out + } + var code sqlite3.ExtendedErrorCode + if errors.As(err, &code) { + return sqliteError(code, "") + } + return apperr.New(apperr.Database, err.Error()) +} + +// connectionError is mapError for failures while connecting. +func connectionError(err error) *apperr.Error { + out := *mapError(err, "") + out.Kind = apperr.Connection + return &out +} diff --git a/internal/drivers/sqlite/sqlite.go b/internal/drivers/sqlite/sqlite.go new file mode 100644 index 0000000..0faf7a6 --- /dev/null +++ b/internal/drivers/sqlite/sqlite.go @@ -0,0 +1,614 @@ +// Package sqlite is the SQLite session on an embedded database file, through +// github.com/ncruces/go-sqlite3 (SQLite compiled to Go, no cgo). +// +// A connection is not safe for concurrent use: every call takes the session +// lock, so one statement runs at a time. The row limit stops stepping the +// statement at maxRows + 1. Cancel interrupts the running call through the +// connection's interrupt context, which SQLite checks from its progress +// handler while a statement runs. +// +// Grid editing: the column origins come from sqlite3_column_table_name and +// friends, which resolve views and subqueries to their base table. An +// EXPLAIN QUERY PLAN then checks that the rows come from one table instance +// (no joins, self-joins or compound selects, whose origins SQLite reports +// from one arm only). Keys come from pragma_table_xinfo, cached per session. +package sqlite + +import ( + "context" + "os" + "strings" + "sync" + "time" + "unicode" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + binaryPreviewBytes = 32 * 1024 + busyTimeout = 5 * time.Second +) + +// Session is an open SQLite database. +type Session struct { + // lock is a one-slot semaphore: whoever holds it owns conn and catalog. + lock chan struct{} + conn *sqlite3.Conn + catalog map[tableKey]*tableMeta + version string + + stateMu sync.Mutex + state model.TxState + + // stop cancels the interrupt context of the call holding the lock. + stopMu sync.Mutex + stop context.CancelFunc +} + +var _ drivers.Session = (*Session)(nil) + +// Connect opens the database file named by profile.Database. The file is +// created only when profile.CreateFile is set; ":memory:" and "file:" URIs +// are passed to SQLite as they are. +func Connect(ctx context.Context, profile model.ConnectionProfile) (*Session, error) { + path := strings.TrimSpace(profile.Database) + if path == "" { + return nil, apperr.Invalidf("Choose the database file.") + } + special := path == ":memory:" || strings.HasPrefix(path, "file:") + if !special && !profile.CreateFile { + if _, err := os.Stat(path); err != nil { + return nil, apperr.Connectionf("Database file not found: %s", path) + } + } + flags := sqlite3.OPEN_READWRITE | sqlite3.OPEN_URI + if profile.CreateFile { + flags |= sqlite3.OPEN_CREATE + } + conn, err := sqlite3.OpenFlags(path, flags) + if err != nil { + return nil, connectionError(err) + } + version, err := setup(ctx, conn) + if err != nil { + _ = conn.Close() + return nil, connectionError(err) + } + return &Session{ + lock: make(chan struct{}, 1), + conn: conn, + catalog: map[tableKey]*tableMeta{}, + version: "SQLite " + version, + state: model.TxState{Autocommit: true}, + }, nil +} + +// setup configures a new connection and returns the SQLite version. Opening +// is lazy: reading the schema catches files that are not databases now +// instead of on the first statement. +func setup(ctx context.Context, conn *sqlite3.Conn) (string, error) { + conn.SetInterrupt(ctx) + defer conn.SetInterrupt(context.Background()) + if err := conn.BusyTimeout(busyTimeout); err != nil { + return "", err + } + if err := conn.Exec("PRAGMA foreign_keys = ON"); err != nil { + return "", err + } + if _, err := scalar(conn, "SELECT count(*) FROM sqlite_schema"); err != nil { + return "", err + } + return scalar(conn, "SELECT sqlite_version()") +} + +func scalar(conn *sqlite3.Conn, sql string) (string, error) { + stmt, _, err := conn.Prepare(sql) + if err != nil { + return "", err + } + defer stmt.Close() + var out string + if stmt.Step() { + out = stmt.ColumnText(0) + } + return out, stmt.Err() +} + +// acquire takes the session lock and arms the interrupt context of the call, +// which Cancel or ctx stop. release clears both. +func (s *Session) acquire(ctx context.Context) (release func(), err error) { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + select { + case s.lock <- struct{}{}: + case <-ctx.Done(): + return nil, apperr.CancelledErr() + } + if s.conn == nil { + <-s.lock + return nil, apperr.Connectionf("The connection is closed.") + } + opCtx, cancel := context.WithCancel(ctx) + s.stopMu.Lock() + s.stop = cancel + s.stopMu.Unlock() + s.conn.SetInterrupt(opCtx) + return func() { + s.conn.SetInterrupt(context.Background()) + s.stopMu.Lock() + s.stop = nil + s.stopMu.Unlock() + cancel() + <-s.lock + }, nil +} + +// clearInterrupt lets cleanup statements (ROLLBACK after a cancelled call) +// run once the call has been interrupted. +func (s *Session) clearInterrupt() { + s.conn.SetInterrupt(context.Background()) +} + +func (s *Session) Engine() model.Engine { return model.SQLite } +func (s *Session) ServerVersion() string { return s.version } +func (s *Session) CurrentUser() *string { return nil } +func (s *Session) CurrentSchema() *string { return model.Str("main") } +func (s *Session) TxState() model.TxState { s.stateMu.Lock(); defer s.stateMu.Unlock(); return s.state } + +func (s *Session) setInTransaction(on bool) { + s.stateMu.Lock() + s.state.InTransaction = on + s.stateMu.Unlock() +} + +// Close closes the connection once the running call, if any, returns. +func (s *Session) Close() error { + s.lock <- struct{}{} + defer func() { <-s.lock }() + if s.conn == nil { + return nil + } + err := s.conn.Close() + s.conn = nil + if err != nil { + return mapError(err, "") + } + return nil +} + +// Cancel interrupts the running call, if any. It may be called from any +// goroutine. +func (s *Session) Cancel(context.Context) error { + s.stopMu.Lock() + defer s.stopMu.Unlock() + if s.stop != nil { + s.stop() + } + return nil +} + +func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.ExecResult, error) { + release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + autocommit := s.TxState().Autocommit + started := time.Now() + result, err := s.run(ctx, req.SQL, req.MaxRows, autocommit) + // SQLite knows whether a transaction is open, including one started or + // ended by the user's own BEGIN/COMMIT/ROLLBACK. + inTransaction := !s.conn.GetAutocommit() + s.setInTransaction(inTransaction) + if err != nil { + return nil, err + } + result.ElapsedMs = uint64(time.Since(started).Milliseconds()) + result.InTransaction = inTransaction + result.Normalize() + return result, nil +} + +// SetAutocommit switches the commit mode. Switching back to autocommit +// commits pending work, as JDBC clients do. +func (s *Session) SetAutocommit(ctx context.Context, on bool) (model.TxState, error) { + release, err := s.acquire(ctx) + if err != nil { + return model.TxState{}, err + } + defer release() + var outcome error + if on && !s.conn.GetAutocommit() { + outcome = s.conn.Exec("COMMIT") + } + s.stateMu.Lock() + defer s.stateMu.Unlock() + s.state.InTransaction = !s.conn.GetAutocommit() + if outcome != nil { + return model.TxState{}, mapError(outcome, "") + } + s.state.Autocommit = on + return s.state, nil +} + +func (s *Session) EndTransaction(ctx context.Context, commit bool) (model.TxState, error) { + release, err := s.acquire(ctx) + if err != nil { + return model.TxState{}, err + } + defer release() + var outcome error + if !s.conn.GetAutocommit() { + if commit { + outcome = s.conn.Exec("COMMIT") + } else { + outcome = s.conn.Exec("ROLLBACK") + } + } + s.stateMu.Lock() + defer s.stateMu.Unlock() + s.state.InTransaction = !s.conn.GetAutocommit() + if outcome != nil { + return model.TxState{}, mapError(outcome, "") + } + return s.state, nil +} + +func (s *Session) ListSchemas(ctx context.Context) ([]string, error) { + rows, err := s.queryRows(ctx, + `SELECT name FROM pragma_database_list + ORDER BY CASE name WHEN 'main' THEN 0 WHEN 'temp' THEN 2 ELSE 1 END, name`) + if err != nil { + return nil, err + } + out := make([]string, 0, len(rows)) + for _, r := range rows { + out = append(out, r[0]) + } + return out, nil +} + +func (s *Session) ListObjects(ctx context.Context, schema string) ([]model.DbObject, error) { + rows, err := s.queryRows(ctx, `SELECT name, type FROM `+quoteIdent(schema)+`.sqlite_schema + WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\_%' ESCAPE '\' + ORDER BY type, name`) + if err != nil { + return nil, err + } + out := make([]model.DbObject, 0, len(rows)) + for _, r := range rows { + out = append(out, model.DbObject{Name: r[0], Kind: r[1]}) + } + return out, nil +} + +func (s *Session) ListColumns(ctx context.Context, schema, table string) ([]model.DbColumn, error) { + // table_xinfo also lists generated columns; hidden = 1 are the hidden + // columns of virtual tables. + rows, err := s.queryRows(ctx, + `SELECT name, type, "notnull", pk, dflt_value FROM pragma_table_xinfo(?1, ?2) + WHERE hidden <> 1 ORDER BY cid`, table, schema) + if err != nil { + return nil, err + } + out := make([]model.DbColumn, 0, len(rows)) + for _, r := range rows { + c := model.DbColumn{ + Name: r[0], + TypeName: r[1], + Nullable: r[2] == "0", + PrimaryKey: r[3] != "0", + } + if r[4] != "" { + c.DefaultValue = model.Str(r[4]) + } + out = append(out, c) + } + return out, nil +} + +// ObjectDDL returns the statements SQLite keeps for the table or view, then +// its indexes and triggers. +func (s *Session) ObjectDDL(ctx context.Context, schema, name, kind string) (string, error) { + if kind != "table" && kind != "view" { + return "", apperr.Invalidf("LowQuery cannot script a %s on SQLite.", kind) + } + rows, err := s.queryRows(ctx, `SELECT sql FROM `+quoteIdent(schema)+`.sqlite_schema + WHERE sql IS NOT NULL + AND ((type IN ('table', 'view') AND name = ?1) + OR (type IN ('index', 'trigger') AND tbl_name = ?1)) + ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'view' THEN 0 WHEN 'index' THEN 1 ELSE 2 END, + name`, name) + if err != nil { + return "", err + } + parts := make([]string, 0, len(rows)) + for _, r := range rows { + sql := strings.TrimRight(strings.TrimRightFunc(r[0], unicode.IsSpace), ";") + parts = append(parts, sql+";\n") + } + return strings.Join(parts, "\n"), nil +} + +// Stream steps through the rows of a query, sending them in batches with +// values in full. It does not close sink. +func (s *Session) Stream(ctx context.Context, sql string, sink chan<- drivers.StreamEvent) (uint64, error) { + release, err := s.acquire(ctx) + if err != nil { + return 0, err + } + defer release() + stmt, err := s.prepare(sql) + if err != nil { + return 0, err + } + defer stmt.Close() + if stmt == nil || stmt.ColumnCount() == 0 { + return 0, apperr.Invalidf("The statement returns no rows.") + } + n := stmt.ColumnCount() + info := make([]model.ColumnInfo, n) + for i := range n { + decl := strings.TrimSpace(stmt.ColumnDeclType(i)) + kind := classKind(0) + if decl != "" { + kind = declaredKind(decl) + } + info[i] = model.ColumnInfo{Name: stmt.ColumnName(i), TypeName: decl, Kind: kind} + } + send := func(ev drivers.StreamEvent) error { + select { + case sink <- ev: + return nil + case <-ctx.Done(): + return apperr.CancelledErr() + } + } + if err := send(drivers.StreamEvent{Columns: info}); err != nil { + return 0, err + } + limit := drivers.BinaryLimit(drivers.WithFullValues(ctx), binaryPreviewBytes) + var total uint64 + batch := make([]model.Row, 0, drivers.StreamBatch) + for stmt.Step() { + row := make(model.Row, n) + for i := range n { + row[i] = cell(stmt, i, stmt.ColumnType(i), limit) + } + batch = append(batch, row) + total++ + if len(batch) == drivers.StreamBatch { + if err := send(drivers.StreamEvent{Rows: batch}); err != nil { + return total, err + } + batch = make([]model.Row, 0, drivers.StreamBatch) + } + } + if err := stmt.Err(); err != nil { + if ctx.Err() != nil { + return total, apperr.CancelledErr() + } + return total, mapError(err, sql) + } + if len(batch) > 0 { + if err := send(drivers.StreamEvent{Rows: batch}); err != nil { + return total, err + } + } + return total, nil +} + +// queryRows runs a metadata query with text parameters; NULL reads as "". +func (s *Session) queryRows(ctx context.Context, sql string, params ...string) ([][]string, error) { + release, err := s.acquire(ctx) + if err != nil { + return nil, err + } + defer release() + stmt, err := s.prepare(sql) + if err != nil { + return nil, err + } + defer stmt.Close() + for i, p := range params { + if err := stmt.BindText(i+1, p); err != nil { + return nil, mapError(err, sql) + } + } + n := stmt.ColumnCount() + var out [][]string + for stmt.Step() { + cells := make([]string, n) + for i := range n { + if v := cell(stmt, i, stmt.ColumnType(i), binaryPreviewBytes); v != nil { + cells[i] = *v + } + } + out = append(out, cells) + } + if err := stmt.Err(); err != nil { + return nil, mapError(err, sql) + } + return out, nil +} + +// prepare compiles one statement and rejects SQL that holds more than one. +// The statement is nil when sql holds only comments. +func (s *Session) prepare(sql string) (*sqlite3.Stmt, error) { + stmt, tail, err := s.conn.Prepare(sql) + if err != nil { + return nil, mapError(err, sql) + } + if tail != "" { + next, _, err := s.conn.Prepare(tail) + if err != nil { + _ = stmt.Close() + return nil, mapError(err, sql) + } + if next != nil { + _ = next.Close() + _ = stmt.Close() + return nil, apperr.Invalidf("Only one statement can run at a time.") + } + } + return stmt, nil +} + +// run runs one statement. In manual-commit mode a transaction is opened +// first and stays open until the user ends it. +func (s *Session) run(ctx context.Context, sql string, maxRows int, autocommit bool) (*model.ExecResult, error) { + if isBlank(sql) { + return &model.ExecResult{}, nil + } + first := "" + if kw := drivers.FirstKeywords(sql, 1); len(kw) > 0 { + first = kw[0] + } + // Transaction control is the user's own; VACUUM, ATTACH and DETACH + // cannot run inside a transaction, and several PRAGMAs are ignored or + // fail there. + skipBegin := false + switch first { + case "BEGIN", "COMMIT", "END", "ROLLBACK", "SAVEPOINT", "RELEASE", + "VACUUM", "ATTACH", "DETACH", "PRAGMA": + skipBegin = true + } + opened := !autocommit && s.conn.GetAutocommit() && !skipBegin + if opened { + if err := s.conn.Exec("BEGIN"); err != nil { + return nil, mapError(err, "") + } + } + result, err := s.statement(ctx, sql, maxRows, first) + if err != nil && opened && !s.conn.GetAutocommit() { + // The failed statement was the only one in the transaction opened + // for it: do not leave an empty transaction behind. + s.clearInterrupt() + _ = s.conn.Exec("ROLLBACK") + } + return result, err +} + +func (s *Session) statement(ctx context.Context, sql string, maxRows int, first string) (*model.ExecResult, error) { + stmt, err := s.prepare(sql) + if err != nil { + return nil, err + } + if stmt == nil { + return &model.ExecResult{}, nil + } + defer stmt.Close() + readonly := stmt.ReadOnly() + if !readonly || first == "ATTACH" || first == "DETACH" { + // DDL may change keys: reload them on the next query. + clear(s.catalog) + } + n := stmt.ColumnCount() + if n == 0 { + if err := stmt.Exec(); err != nil { + return nil, mapError(err, sql) + } + result := &model.ExecResult{} + // Changes keeps the count of the last DML, so it only means + // something right after one. WITH without result columns is DML. + switch first { + case "INSERT", "UPDATE", "DELETE", "REPLACE", "WITH": + changes := uint64(s.conn.Changes()) + result.RowsAffected = &changes + } + return result, nil + } + + names := make([]string, n) + decls := make([]string, n) + for i := range n { + names[i] = stmt.ColumnName(i) + decls[i] = strings.TrimSpace(stmt.ColumnDeclType(i)) + } + editable := readonly && (first == "SELECT" || first == "WITH") + var origins []*origin + if editable { + origins = columnOrigins(stmt) + } + // Storage class of the first non-null value, for columns without a + // declared type (expressions). Zero means none yet. + classes := make([]sqlite3.Datatype, n) + limit := drivers.BinaryLimit(ctx, binaryPreviewBytes) + rows := []model.Row{} + truncated := false + for stmt.Step() { + if maxRows > 0 && len(rows) == maxRows { + truncated = true + break + } + row := make(model.Row, n) + for i := range n { + t := stmt.ColumnType(i) + if classes[i] == 0 && t != sqlite3.NULL { + classes[i] = t + } + row[i] = cell(stmt, i, t, limit) + } + rows = append(rows, row) + } + if err := stmt.Err(); err != nil { + return nil, mapError(err, sql) + } + // Reset the statement before the plan query below. + _ = stmt.Close() + + columns := make([]model.ColumnInfo, n) + for i := range n { + if decls[i] != "" { + columns[i] = model.ColumnInfo{Name: names[i], TypeName: decls[i], Kind: declaredKind(decls[i])} + } else { + columns[i] = model.ColumnInfo{Name: names[i], TypeName: className(classes[i]), Kind: classKind(classes[i])} + } + } + result := &model.ExecResult{Columns: columns, Rows: rows, Truncated: truncated} + if editable { + target, reason := s.editTarget(sql, origins, decls) + if target != nil { + result.Editable = target + } else { + result.ReadOnlyReason = model.Str(reason) + } + } + return result, nil +} + +// isBlank reports SQL that is only whitespace, comments and semicolons: +// SQLite prepares nothing. +func isBlank(sql string) bool { + i := 0 + for i < len(sql) { + c := sql[i] + switch { + case c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == ';': + i++ + case c == '-' && i+1 < len(sql) && sql[i+1] == '-': + for i < len(sql) && sql[i] != '\n' { + i++ + } + case c == '/' && i+1 < len(sql) && sql[i+1] == '*': + i += 2 + for i+1 < len(sql) && !(sql[i] == '*' && sql[i+1] == '/') { + i++ + } + i += 2 + default: + return false + } + } + return true +} + +func quoteIdent(name string) string { + return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` +} diff --git a/internal/drivers/sqlite/sqlite_test.go b/internal/drivers/sqlite/sqlite_test.go new file mode 100644 index 0000000..d8826dd --- /dev/null +++ b/internal/drivers/sqlite/sqlite_test.go @@ -0,0 +1,722 @@ +package sqlite + +import ( + "context" + "errors" + "math" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/fixtures" + "github.com/LowBloat/LowQuery/internal/model" +) + +var bg = context.Background() + +func profile(path string, create bool) model.ConnectionProfile { + p := model.DefaultProfile() + p.Engine = model.SQLite + p.Database = path + p.CreateFile = create + return p +} + +type tempDB struct { + t *testing.T + dir string + s *Session +} + +// newTempDB opens a new database file in a test directory; the session is +// closed before the directory is removed. +func newTempDB(t *testing.T, name string) *tempDB { + t.Helper() + dir := t.TempDir() + s, err := Connect(bg, profile(filepath.Join(dir, name+".db"), true)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return &tempDB{t: t, dir: dir, s: s} +} + +func (db *tempDB) run(sql string) *model.ExecResult { + db.t.Helper() + return db.runLimit(sql, 0) +} + +func (db *tempDB) runLimit(sql string, maxRows int) *model.ExecResult { + db.t.Helper() + r, err := db.tryRun(sql, maxRows) + if err != nil { + db.t.Fatalf("%s: %v", sql, err) + } + return r +} + +func (db *tempDB) tryRun(sql string, maxRows int) (*model.ExecResult, error) { + return db.s.Execute(bg, model.ExecRequest{SQL: sql, MaxRows: maxRows}) +} + +func (db *tempDB) fail(sql string) *apperr.Error { + db.t.Helper() + _, err := db.tryRun(sql, 0) + if err == nil { + db.t.Fatalf("%s: no error", sql) + } + var e *apperr.Error + if !errors.As(err, &e) { + db.t.Fatalf("%s: %T %v", sql, err, err) + } + return e +} + +func (db *tempDB) scalar(sql string) *string { + db.t.Helper() + return db.run(sql).Rows[0][0] +} + +func (db *tempDB) rows(sql string) []model.Row { + db.t.Helper() + return db.run(sql).Rows +} + +func (db *tempDB) attach(name, alias string) { + db.t.Helper() + path := filepath.Join(db.dir, name+".db") + db.run("ATTACH DATABASE '" + strings.ReplaceAll(path, "'", "''") + "' AS " + alias) +} + +func deref(p *string) string { + if p == nil { + return "" + } + return *p +} + +func strs(row model.Row) []string { + out := make([]string, len(row)) + for i, v := range row { + out[i] = deref(v) + } + return out +} + +func texts(rows ...[]string) []model.Row { + out := make([]model.Row, len(rows)) + for i, r := range rows { + out[i] = make(model.Row, len(r)) + for j, v := range r { + if v != "" { + out[i][j] = model.Str(v) + } + } + } + return out +} + +func asApp(t *testing.T, err error) *apperr.Error { + t.Helper() + var e *apperr.Error + if !errors.As(err, &e) { + t.Fatalf("not an app error: %T %v", err, err) + } + return e +} + +func TestFormatsRealsShortest(t *testing.T) { + // Variables, so the sum is computed in float64 and not as an exact + // constant. + a, b := 0.1, 0.2 + cases := map[float64]string{ + 3.0: "3.0", + -0.5: "-0.5", + a + b: "0.30000000000000004", + 1e300: "1.0e+300", + -1.5e-7: "-1.5e-7", + 123456789.125: "123456789.125", + math.Inf(1): "Inf", + 0.0: "0.0", + } + for v, want := range cases { + if got := formatReal(v); got != want { + t.Errorf("formatReal(%v) = %q, want %q", v, got, want) + } + } +} + +func TestKindsFollowAffinity(t *testing.T) { + cases := map[string]model.ValueKind{ + "INTEGER": model.KindNumber, + "bigint": model.KindNumber, + "NUMERIC(10,2)": model.KindNumber, + "DOUBLE PRECISION": model.KindNumber, + "VARCHAR(20)": model.KindText, + "DATETIME": model.KindTemporal, + "BOOLEAN": model.KindBool, + "JSON": model.KindJSON, + "BLOB": model.KindBinary, + "GEOMETRY": model.KindOther, + } + for decl, want := range cases { + if got := declaredKind(decl); got != want { + t.Errorf("declaredKind(%q) = %q, want %q", decl, got, want) + } + } +} + +func TestNamesResultCodes(t *testing.T) { + if got := codeName(int(sqlite3.ERROR)); got != "SQLITE_ERROR" { + t.Error(got) + } + if got := codeName(int(sqlite3.CONSTRAINT_UNIQUE)); got != "SQLITE_CONSTRAINT_UNIQUE" { + t.Error(got) + } + if got := codeName(int(sqlite3.IOERR) | 99<<8); got != "SQLITE_IOERR" { + t.Error(got) + } +} + +func TestBlankStatements(t *testing.T) { + if !isBlank(" ; -- x\n /* y */ ;") { + t.Error("comments and semicolons are blank") + } + if isBlank("-- x\nselect 1") { + t.Error("a statement is not blank") + } +} + +func TestFormatsEveryStorageClass(t *testing.T) { + db := newTempDB(t, "values") + if !strings.HasPrefix(db.s.ServerVersion(), "SQLite 3.") { + t.Errorf("version %q", db.s.ServerVersion()) + } + if got := deref(db.s.CurrentSchema()); got != "main" { + t.Errorf("schema %q", got) + } + db.run("CREATE TABLE v (i INTEGER, r REAL, t TEXT, b BLOB, n NUMERIC, d DATETIME, j JSON, f BOOLEAN)") + db.run(`INSERT INTO v VALUES (-42, 2.5, 'olá', x'00ff10', 12.50, '2024-05-01 13:45:00', '{"a":1}', 1)`) + db.run("INSERT INTO v VALUES (NULL, 3, NULL, NULL, NULL, NULL, NULL, NULL)") + r := db.run("SELECT * FROM v") + var types []string + var kinds []model.ValueKind + for _, c := range r.Columns { + types = append(types, c.TypeName) + kinds = append(kinds, c.Kind) + } + if want := []string{"INTEGER", "REAL", "TEXT", "BLOB", "NUMERIC", "DATETIME", "JSON", "BOOLEAN"}; !reflect.DeepEqual(types, want) { + t.Errorf("types %q", types) + } + wantKinds := []model.ValueKind{model.KindNumber, model.KindNumber, model.KindText, model.KindBinary, + model.KindNumber, model.KindTemporal, model.KindJSON, model.KindBool} + if !reflect.DeepEqual(kinds, wantKinds) { + t.Errorf("kinds %q", kinds) + } + want := []string{"-42", "2.5", "olá", "X'00FF10'", "12.5", "2024-05-01 13:45:00", `{"a":1}`, "1"} + if got := strs(r.Rows[0]); !reflect.DeepEqual(got, want) { + t.Errorf("row 0 %q", got) + } + // REAL affinity stores 3 as 3.0. + if got := deref(r.Rows[1][1]); got != "3.0" { + t.Errorf("real %q", got) + } + if r.Rows[1][0] != nil { + t.Error("NULL expected") + } + + r = db.run("SELECT 1 + 1 AS a, 0.1 + 0.2, 'x', x'0A', NULL, 1e300, typeof(1)") + types = nil + for _, c := range r.Columns { + types = append(types, c.TypeName) + } + if want := []string{"INTEGER", "REAL", "TEXT", "BLOB", "NULL", "REAL", "TEXT"}; !reflect.DeepEqual(types, want) { + t.Errorf("expression types %q", types) + } + if r.Columns[0].Name != "a" || r.Columns[4].Kind != model.KindOther { + t.Errorf("columns %+v", r.Columns) + } + want = []string{"2", "0.30000000000000004", "x", "X'0A'", "", "1.0e+300", "integer"} + if got := strs(r.Rows[0]); !reflect.DeepEqual(got, want) { + t.Errorf("expressions %q", got) + } + + big := deref(db.scalar("SELECT zeroblob(40000)")) + suffix := "'… (40000 bytes)" + if !strings.HasPrefix(big, "X'0000") || !strings.HasSuffix(big, suffix) { + t.Errorf("big blob %q...", big[:20]) + } + if len(big) != 2+binaryPreviewBytes*2+len(suffix) { + t.Errorf("big blob length %d", len(big)) + } + // In full when the caller asks for it. + full, err := db.s.Execute(drivers.WithFullValues(bg), model.ExecRequest{SQL: "SELECT zeroblob(40000)"}) + if err != nil { + t.Fatal(err) + } + if got := len(deref(full.Rows[0][0])); got != 2+40000*2+1 { + t.Errorf("full blob length %d", got) + } +} + +func TestAppliesRowLimit(t *testing.T) { + db := newTempDB(t, "limit") + sql := "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 10) SELECT x FROM c" + r := db.runLimit(sql, 5) + if len(r.Rows) != 5 || !r.Truncated || deref(r.Rows[4][0]) != "5" { + t.Errorf("limit 5: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + r = db.runLimit(sql, 10) + if len(r.Rows) != 10 || r.Truncated { + t.Errorf("limit 10: %d rows, truncated %v", len(r.Rows), r.Truncated) + } + r = db.runLimit(sql, 0) + if len(r.Rows) != 10 || r.Truncated { + t.Errorf("no limit: %d rows, truncated %v", len(r.Rows), r.Truncated) + } +} + +func affected(r *model.ExecResult) string { + if r.RowsAffected == nil { + return "none" + } + return strconv.FormatUint(*r.RowsAffected, 10) +} + +func TestReportsRowsAffected(t *testing.T) { + db := newTempDB(t, "affected") + r := db.run("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)") + if r.RowsAffected != nil || r.Columns != nil { + t.Errorf("DDL: %+v", r) + } + if got := affected(db.run("INSERT INTO t (v) VALUES ('a'), ('b'), ('c');")); got != "3" { + t.Errorf("insert %s", got) + } + if got := affected(db.run("UPDATE t SET v = 'z' WHERE id > 1")); got != "2" { + t.Errorf("update %s", got) + } + // A DDL right after keeps no stale count. + if got := affected(db.run("CREATE INDEX t_v ON t (v)")); got != "none" { + t.Errorf("index %s", got) + } + if got := affected(db.run("DELETE FROM t")); got != "3" { + t.Errorf("delete %s", got) + } + // INSERT ... RETURNING returns rows. + if r := db.run("INSERT INTO t (v) VALUES ('r') RETURNING id, v"); len(r.Rows) != 1 { + t.Errorf("returning %d rows", len(r.Rows)) + } + // Comments only: nothing to do. + if r := db.run("-- nothing\n;"); r.Columns != nil { + t.Error("comments returned columns") + } + // Trigger bodies arrive as one statement. + db.run("CREATE TABLE log (msg TEXT)") + db.run("CREATE TRIGGER t_ins AFTER INSERT ON t BEGIN\n INSERT INTO log VALUES (new.v);\n INSERT INTO log VALUES ('again');\nEND;") + db.run("INSERT INTO t (v) VALUES ('x')") + if got := deref(db.scalar("SELECT count(*) FROM log")); got != "2" { + t.Errorf("trigger ran %s times", got) + } +} + +func TestMapsErrors(t *testing.T) { + db := newTempDB(t, "errors") + e := db.fail("SELEC 1") + if e.Kind != apperr.Database || e.Code != "SQLITE_ERROR" || e.Position == nil || *e.Position != 0 || + !strings.Contains(e.Message, "syntax error") { + t.Errorf("syntax error: %+v", e) + } + // Character offset, not bytes: 'ção' has multibyte characters. + if e := db.fail("SELECT 'ção', FROM t"); e.Position == nil || *e.Position != 14 { + t.Errorf("position: %+v", e) + } + if e := db.fail("SELECT * FROM missing"); e.Code != "SQLITE_ERROR" || !strings.Contains(e.Message, "no such table") { + t.Errorf("missing table: %+v", e) + } + + db.run("CREATE TABLE u (k TEXT UNIQUE)") + db.run("INSERT INTO u VALUES ('a')") + if e := db.fail("INSERT INTO u VALUES ('a')"); e.Code != "SQLITE_CONSTRAINT_UNIQUE" || e.Kind != apperr.Database { + t.Errorf("unique: %+v", e) + } + + // Foreign keys are enforced. + db.run("CREATE TABLE p (id INTEGER PRIMARY KEY)") + db.run("CREATE TABLE c (p INTEGER REFERENCES p (id))") + if e := db.fail("INSERT INTO c VALUES (7)"); e.Code != "SQLITE_CONSTRAINT_FOREIGNKEY" { + t.Errorf("foreign key: %+v", e) + } + + if e := db.fail("SELECT 1; SELECT 2"); e.Kind != apperr.Invalid { + t.Errorf("two statements: %+v", e) + } + // A syntax error in a second statement points into the whole text. + if e := db.fail("SELECT 1; SELEC 2"); e.Position == nil || *e.Position != 10 { + t.Errorf("tail position: %+v", e) + } +} + +func TestManualTransactions(t *testing.T) { + db := newTempDB(t, "manual") + db.run("CREATE TABLE t (v INTEGER)") + st, err := db.s.SetAutocommit(bg, false) + if err != nil || st.Autocommit || st.InTransaction { + t.Fatalf("%+v %v", st, err) + } + + if r := db.run("INSERT INTO t VALUES (1)"); !r.InTransaction || !db.s.TxState().InTransaction { + t.Error("insert did not open a transaction") + } + if st, _ := db.s.EndTransaction(bg, false); st.InTransaction { + t.Error("rollback left a transaction") + } + r := db.run("SELECT count(*) FROM t") + if deref(r.Rows[0][0]) != "0" { + t.Error("rollback kept the row") + } + // Reads also open the transaction in manual mode. + if !r.InTransaction { + t.Error("read did not open a transaction") + } + + db.run("INSERT INTO t VALUES (2)") + if st, _ := db.s.EndTransaction(bg, true); st.InTransaction { + t.Error("commit left a transaction") + } + if got := deref(db.scalar("SELECT count(*) FROM t")); got != "1" { + t.Errorf("count %s", got) + } + if _, err := db.s.EndTransaction(bg, true); err != nil { + t.Fatal(err) + } + + // A failing first statement does not leave an empty transaction. + if e := db.fail("SELEC 1"); e.Code != "SQLITE_ERROR" { + t.Errorf("%+v", e) + } + if db.s.TxState().InTransaction { + t.Error("failed statement left a transaction") + } + + // A failing statement inside a transaction keeps earlier work. + db.run("INSERT INTO t VALUES (3)") + db.fail("INSERT INTO nope VALUES (1)") + if !db.s.TxState().InTransaction { + t.Error("failed statement ended the transaction") + } + + // COMMIT typed by the user ends it. + if r := db.run("COMMIT"); r.InTransaction || db.s.TxState().InTransaction { + t.Error("COMMIT left a transaction") + } + if got := deref(db.scalar("SELECT count(*) FROM t")); got != "2" { + t.Errorf("count %s", got) + } + + // Back to autocommit commits pending work. + db.run("INSERT INTO t VALUES (4)") + st, err = db.s.SetAutocommit(bg, true) + if err != nil || !st.Autocommit || st.InTransaction { + t.Fatalf("%+v %v", st, err) + } + if got := deref(db.scalar("SELECT count(*) FROM t")); got != "3" { + t.Errorf("count %s", got) + } + if db.s.TxState().InTransaction { + t.Error("autocommit left a transaction") + } +} + +func TestUserTypedTransactionControl(t *testing.T) { + db := newTempDB(t, "typed") + db.run("CREATE TABLE t (v INTEGER)") + if r := db.run("BEGIN"); !r.InTransaction { + t.Error("BEGIN") + } + db.run("INSERT INTO t VALUES (1)") + db.run("SAVEPOINT sp") + db.run("INSERT INTO t VALUES (2)") + if r := db.run("ROLLBACK TO sp"); !r.InTransaction { + t.Error("ROLLBACK TO ended the transaction") + } + if r := db.run("COMMIT"); r.InTransaction { + t.Error("COMMIT") + } + if got := deref(db.scalar("SELECT count(*) FROM t")); got != "1" { + t.Errorf("count %s", got) + } + + db.run("BEGIN") + db.run("DELETE FROM t") + if r := db.run("ROLLBACK"); r.InTransaction { + t.Error("ROLLBACK") + } + if got := deref(db.scalar("SELECT count(*) FROM t")); got != "1" { + t.Errorf("count %s", got) + } + if !db.s.TxState().Autocommit { + t.Error("autocommit changed") + } +} + +const longQuery = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 1000000000) SELECT count(*) FROM c" + +func TestInterruptsLongQuery(t *testing.T) { + db := newTempDB(t, "cancel") + done := make(chan error, 1) + go func() { + _, err := db.tryRun(longQuery, 0) + done <- err + }() + time.Sleep(200 * time.Millisecond) + started := time.Now() + if err := db.s.Cancel(bg); err != nil { + t.Fatal(err) + } + var err error + select { + case err = <-done: + case <-time.After(10 * time.Second): + t.Fatal("the query was not interrupted") + } + e := asApp(t, err) + if e.Kind != apperr.Cancelled || e.Code != "SQLITE_INTERRUPT" || e.Message != "The statement was cancelled." { + t.Errorf("%+v", e) + } + if time.Since(started) > 5*time.Second { + t.Error("cancel was slow") + } + // The session is usable afterwards. + if got := deref(db.scalar("SELECT 1")); got != "1" { + t.Errorf("after cancel: %s", got) + } +} + +func TestContextStopsQuery(t *testing.T) { + db := newTempDB(t, "ctx") + ctx, cancel := context.WithTimeout(bg, 200*time.Millisecond) + defer cancel() + _, err := db.s.Execute(ctx, model.ExecRequest{SQL: longQuery}) + if e := asApp(t, err); e.Kind != apperr.Cancelled { + t.Errorf("%+v", e) + } + if got := deref(db.scalar("SELECT 1")); got != "1" { + t.Errorf("after cancel: %s", got) + } +} + +func TestCreatesFileOnlyWhenAsked(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "create.db") + _, err := Connect(bg, profile(path, false)) + e := asApp(t, err) + if e.Kind != apperr.Connection || e.Message != "Database file not found: "+path { + t.Errorf("%+v", e) + } + if _, err := os.Stat(path); err == nil { + t.Error("file was created") + } + + s, err := Connect(bg, profile(path, true)) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Error("file was not created") + } + _ = s.Close() + // An existing file opens without CreateFile. + s, err = Connect(bg, profile(path, false)) + if err != nil { + t.Fatal(err) + } + _ = s.Close() + + // A file that is not a database fails at connect time. + junk := filepath.Join(dir, "junk.db") + if err := os.WriteFile(junk, []byte(strings.Repeat("x", 4096)), 0o644); err != nil { + t.Fatal(err) + } + _, err = Connect(bg, profile(junk, false)) + if e := asApp(t, err); e.Kind != apperr.Connection || e.Code != "SQLITE_NOTADB" { + t.Errorf("%+v", e) + } + + _, err = Connect(bg, profile(" ", true)) + if e := asApp(t, err); e.Kind != apperr.Invalid || e.Message != "Choose the database file." { + t.Errorf("%+v", e) + } +} + +func TestListsMetadata(t *testing.T) { + db := newTempDB(t, "meta") + db.run("CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, " + + "score NUMERIC(10,2), full TEXT GENERATED ALWAYS AS (name || '!') VIRTUAL)") + db.run("INSERT INTO person (name) VALUES ('a')") + db.run("CREATE VIEW people AS SELECT name FROM person") + db.run("CREATE TABLE another (x)") + db.attach("meta-other", "extra") + db.run("CREATE TABLE extra.ext (k TEXT, v BLOB, PRIMARY KEY (k, v))") + db.run("CREATE TEMP TABLE scratch (z)") + + schemas, err := db.s.ListSchemas(bg) + if err != nil || !reflect.DeepEqual(schemas, []string{"main", "extra", "temp"}) { + t.Errorf("schemas %q %v", schemas, err) + } + + objects, err := db.s.ListObjects(bg, "main") + if err != nil { + t.Fatal(err) + } + // sqlite_sequence is internal and hidden. + want := []model.DbObject{{Name: "another", Kind: "table"}, {Name: "person", Kind: "table"}, {Name: "people", Kind: "view"}} + if !reflect.DeepEqual(objects, want) { + t.Errorf("objects %+v", objects) + } + if ext, _ := db.s.ListObjects(bg, "extra"); len(ext) != 1 || ext[0].Name != "ext" { + t.Errorf("extra %+v", ext) + } + if tmp, _ := db.s.ListObjects(bg, "temp"); len(tmp) == 0 || tmp[0].Name != "scratch" { + t.Errorf("temp %+v", tmp) + } + + cols, err := db.s.ListColumns(bg, "main", "person") + if err != nil { + t.Fatal(err) + } + type shape struct { + name, typ string + nullable, k bool + } + var got []shape + for _, c := range cols { + got = append(got, shape{c.Name, c.TypeName, c.Nullable, c.PrimaryKey}) + } + wantCols := []shape{ + {"id", "INTEGER", true, true}, + {"name", "TEXT", false, false}, + {"score", "NUMERIC(10,2)", true, false}, + {"full", "TEXT", true, false}, + } + if !reflect.DeepEqual(got, wantCols) { + t.Errorf("columns %+v", got) + } + cols, _ = db.s.ListColumns(bg, "extra", "ext") + for _, c := range cols { + if !c.PrimaryKey { + t.Errorf("%s is part of the key", c.Name) + } + } + if cols, _ := db.s.ListColumns(bg, "main", "ext"); len(cols) != 0 { + t.Errorf("main.ext %+v", cols) + } + + db.run("DETACH DATABASE extra") +} + +func TestScriptsObjects(t *testing.T) { + db := newTempDB(t, "ddl") + db.run("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);") + db.run("CREATE INDEX t_v ON t (v)") + db.run("CREATE TRIGGER t_ins AFTER INSERT ON t BEGIN SELECT 1; END") + ddl, err := db.s.ObjectDDL(bg, "main", "t", "table") + if err != nil { + t.Fatal(err) + } + want := "CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);\n\n" + + "CREATE INDEX t_v ON t (v);\n\n" + + "CREATE TRIGGER t_ins AFTER INSERT ON t BEGIN SELECT 1; END;\n" + if ddl != want { + t.Errorf("ddl %q", ddl) + } + _, err = db.s.ObjectDDL(bg, "main", "t", "sequence") + if e := asApp(t, err); e.Kind != apperr.Invalid || e.Message != "LowQuery cannot script a sequence on SQLite." { + t.Errorf("%+v", e) + } +} + +func TestStreamsRows(t *testing.T) { + db := newTempDB(t, "stream") + db.run("CREATE TABLE t (id INTEGER PRIMARY KEY, b BLOB)") + db.run("WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 1201) " + + "INSERT INTO t SELECT x, CASE x WHEN 1 THEN zeroblob(40000) END FROM c") + sink := make(chan drivers.StreamEvent, 16) + total, err := db.s.Stream(bg, "SELECT id, b, 1 + 1 FROM t ORDER BY id", sink) + close(sink) + if err != nil || total != 1201 { + t.Fatalf("%d rows, %v", total, err) + } + var events []drivers.StreamEvent + for ev := range sink { + events = append(events, ev) + } + if len(events) != 4 { + t.Fatalf("%d events", len(events)) + } + cols := events[0].Columns + if len(cols) != 3 || cols[0].TypeName != "INTEGER" || cols[1].Kind != model.KindBinary || + cols[2].TypeName != "" || cols[2].Kind != model.KindOther { + t.Errorf("columns %+v", cols) + } + if n := []int{len(events[1].Rows), len(events[2].Rows), len(events[3].Rows)}; !reflect.DeepEqual(n, []int{500, 500, 201}) { + t.Errorf("batches %v", n) + } + // Values in full. + if got := len(deref(events[1].Rows[0][1])); got != 2+40000*2+1 { + t.Errorf("blob length %d", got) + } + if events[1].Rows[1][1] != nil || deref(events[3].Rows[200][0]) != "1201" { + t.Error("values") + } + + _, err = db.s.Stream(bg, "CREATE TABLE x (y)", make(chan drivers.StreamEvent, 1)) + if e := asApp(t, err); e.Kind != apperr.Invalid || e.Message != "The statement returns no rows." { + t.Errorf("%+v", e) + } + + // A reader that stops reading cancels the stream. + ctx, cancel := context.WithCancel(bg) + stalled := make(chan drivers.StreamEvent) + go func() { + <-stalled + cancel() + }() + _, err = db.s.Stream(ctx, "SELECT id FROM t", stalled) + if e := asApp(t, err); e.Kind != apperr.Cancelled { + t.Errorf("%+v", e) + } + if got := deref(db.scalar("SELECT count(*) FROM t")); got != "1201" { + t.Errorf("after stream: %s", got) + } +} + +func TestClosedSession(t *testing.T) { + db := newTempDB(t, "closed") + if err := db.s.Close(); err != nil { + t.Fatal(err) + } + if err := db.s.Close(); err != nil { + t.Fatal(err) + } + if e := asApp(t, func() error { _, err := db.tryRun("SELECT 1", 0); return err }()); e.Kind != apperr.Connection { + t.Errorf("%+v", e) + } +} + +func TestResultViewSQL(t *testing.T) { + db := newTempDB(t, "view") + fixtures.CheckView(t, db.s, "sqlite") +} + +func TestDDLSQL(t *testing.T) { + db := newTempDB(t, "ddl-fixtures") + fixtures.CheckDDL(t, db.s, "sqlite", "main") +} diff --git a/internal/drivers/sqlite/values.go b/internal/drivers/sqlite/values.go new file mode 100644 index 0000000..356bd55 --- /dev/null +++ b/internal/drivers/sqlite/values.go @@ -0,0 +1,284 @@ +package sqlite + +import ( + "encoding/hex" + "errors" + "math" + "strconv" + "strings" + "unicode/utf8" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +// declaredKind is the kind for a declared type, following SQLite's affinity +// rules plus the common names for booleans, dates and JSON. +func declaredKind(decl string) model.ValueKind { + t := strings.ToUpper(decl) + has := func(s string) bool { return strings.Contains(t, s) } + switch { + case has("BOOL"): + return model.KindBool + case has("JSON"): + return model.KindJSON + case has("DATE") || has("TIME"): + return model.KindTemporal + case has("INT"): + return model.KindNumber + case has("CHAR") || has("CLOB") || has("TEXT") || has("STRING") || has("UUID"): + return model.KindText + case has("BLOB") || has("BINARY"): + return model.KindBinary + case has("REAL") || has("FLOA") || has("DOUB") || has("NUM") || has("DEC") || has("MONEY"): + return model.KindNumber + } + return model.KindOther +} + +// className names a storage class; zero (no value seen) is NULL. +func className(class sqlite3.Datatype) string { + switch class { + case sqlite3.INTEGER: + return "INTEGER" + case sqlite3.FLOAT: + return "REAL" + case sqlite3.TEXT: + return "TEXT" + case sqlite3.BLOB: + return "BLOB" + } + return "NULL" +} + +func classKind(class sqlite3.Datatype) model.ValueKind { + switch class { + case sqlite3.INTEGER, sqlite3.FLOAT: + return model.KindNumber + case sqlite3.TEXT: + return model.KindText + case sqlite3.BLOB: + return model.KindBinary + } + return model.KindOther +} + +// cell formats column i of the current row, of storage class t; binary +// values show their first limit bytes. +func cell(stmt *sqlite3.Stmt, i int, t sqlite3.Datatype, limit int) *string { + var s string + switch t { + case sqlite3.NULL: + return nil + case sqlite3.INTEGER: + s = strconv.FormatInt(stmt.ColumnInt64(i), 10) + case sqlite3.FLOAT: + s = formatReal(stmt.ColumnFloat(i)) + case sqlite3.BLOB: + s = blob(stmt.ColumnRawBlob(i), limit) + default: + s = lossyUTF8(stmt.ColumnRawText(i)) + } + return &s +} + +// lossyUTF8 replaces invalid UTF-8 with U+FFFD. +func lossyUTF8(b []byte) string { + if utf8.Valid(b) { + return string(b) + } + var out strings.Builder + out.Grow(len(b)) + for len(b) > 0 { + r, size := utf8.DecodeRune(b) + if r == utf8.RuneError && size == 1 { + out.WriteRune(utf8.RuneError) + } else { + out.Write(b[:size]) + } + b = b[size:] + } + return out.String() +} + +// formatReal is the shortest text that reads back as the same double. It +// always shows it is a REAL (3.0, 1.0e+300), like the sqlite3 shell. +func formatReal(v float64) string { + if math.IsNaN(v) { + return "NaN" + } + if math.IsInf(v, 1) { + return "Inf" + } + if math.IsInf(v, -1) { + return "-Inf" + } + abs := math.Abs(v) + if abs != 0 && (abs < 1e-5 || abs >= 1e16) { + s := strconv.FormatFloat(v, 'e', -1, 64) + mantissa, exp, _ := strings.Cut(s, "e") + if !strings.Contains(mantissa, ".") { + mantissa += ".0" + } + n, _ := strconv.Atoi(exp) + sign := "+" + if n < 0 { + sign = "-" + n = -n + } + return mantissa + "e" + sign + strconv.Itoa(n) + } + s := strconv.FormatFloat(v, 'f', -1, 64) + if !strings.Contains(s, ".") { + s += ".0" + } + return s +} + +// blob writes X'00FF' like a blob literal; values longer than limit show +// their first limit bytes and the full size. +func blob(b []byte, limit int) string { + shown := b[:min(len(b), limit)] + var s strings.Builder + s.Grow(len(shown)*2 + 3) + s.WriteString("X'") + s.WriteString(strings.ToUpper(hex.EncodeToString(shown))) + s.WriteByte('\'') + if len(b) > len(shown) { + s.WriteString("… (" + strconv.Itoa(len(b)) + " bytes)") + } + return s.String() +} + +type affinityKind int + +const ( + affInteger affinityKind = iota + affText + affBlob + affReal + affNumeric +) + +// affinity is the column affinity of a declared type (SQLite "Datatypes", +// 3.1). +func affinity(decl string) affinityKind { + t := strings.ToUpper(decl) + has := func(s string) bool { return strings.Contains(t, s) } + switch { + case has("INT"): + return affInteger + case has("CHAR") || has("CLOB") || has("TEXT"): + return affText + case has("BLOB") || strings.TrimSpace(t) == "": + return affBlob + case has("REAL") || has("FLOA") || has("DOUB"): + return affReal + } + return affNumeric +} + +// toValue converts grid text back to a value for a column with the declared +// type: nil, int64, float64, string or []byte. Numeric affinities bind +// numbers; columns without affinity (BLOB or no type) keep their storage +// class through the display format: X'..' is a blob, and text that the +// formatter would print for an integer or real is that number. +func toValue(text *string, decl string) (any, error) { + if text == nil { + return nil, nil + } + t := *text + if strings.HasPrefix(t, "X'") && strings.Contains(t, "'… (") { + return nil, apperr.Invalidf("This value is only a preview and cannot be saved.") + } + switch affinity(decl) { + case affInteger, affReal, affNumeric: + trimmed := strings.TrimSpace(t) + boolean := strings.Contains(strings.ToUpper(decl), "BOOL") + switch { + case boolean && strings.EqualFold(trimmed, "true"): + return int64(1), nil + case boolean && strings.EqualFold(trimmed, "false"): + return int64(0), nil + } + if i, err := strconv.ParseInt(trimmed, 10, 64); err == nil { + return i, nil + } + if f, ok := parseReal(trimmed); ok { + return f, nil + } + case affBlob: + if b, ok := hexBlob(t); ok { + return b, nil + } + if i, err := strconv.ParseInt(t, 10, 64); err == nil && strconv.FormatInt(i, 10) == t { + return i, nil + } + if f, ok := parseReal(t); ok && formatReal(f) == t { + return f, nil + } + } + return t, nil +} + +// parseReal reads a decimal or exponent literal, or the Inf the formatter +// prints. +func parseReal(t string) (float64, bool) { + switch t { + case "Inf", "+Inf": + return math.Inf(1), true + case "-Inf": + return math.Inf(-1), true + } + digit := false + for i := 0; i < len(t); i++ { + c := t[i] + switch { + case c >= '0' && c <= '9': + digit = true + case strings.IndexByte("+-.eE", c) >= 0: + default: + return 0, false + } + } + if !digit { + return 0, false + } + f, err := strconv.ParseFloat(t, 64) + if err != nil { + // Out of range reads as infinity or zero, as in Rust. + var ne *strconv.NumError + if errors.As(err, &ne) && ne.Err == strconv.ErrRange { + return f, true + } + return 0, false + } + return f, true +} + +// hexBlob reads the bytes of an X'00FF' literal. +func hexBlob(t string) ([]byte, bool) { + var rest string + switch { + case strings.HasPrefix(t, "X'"): + rest = t[2:] + case strings.HasPrefix(t, "x'"): + rest = t[2:] + default: + return nil, false + } + digits, ok := strings.CutSuffix(rest, "'") + if !ok || len(digits)%2 != 0 { + return nil, false + } + b, err := hex.DecodeString(digits) + if err != nil { + return nil, false + } + if b == nil { + b = []byte{} + } + return b, true +} diff --git a/internal/model/model.go b/internal/model/model.go new file mode 100644 index 0000000..a56a340 --- /dev/null +++ b/internal/model/model.go @@ -0,0 +1,262 @@ +// Package model holds the types shared with the interface. Their JSON shape +// is the contract with src/lib/api.ts: camelCase fields, nullable values as +// null. +package model + +import "encoding/json" + +type Engine string + +const ( + Postgres Engine = "postgres" + Oracle Engine = "oracle" + MySQL Engine = "mysql" + MariaDB Engine = "mariadb" + SQLServer Engine = "sqlserver" + SQLite Engine = "sqlite" + Redis Engine = "redis" + Cassandra Engine = "cassandra" +) + +// SslMode holds the libpq `sslmode` values that make sense for a desktop +// client: disable, prefer, require, verify-full. +type SslMode string + +const ( + SslDisable SslMode = "disable" + SslPrefer SslMode = "prefer" + SslRequire SslMode = "require" + SslVerifyFull SslMode = "verify-full" +) + +// OracleConnectType says how the Oracle address is built: service +// (host:port/service_name), sid, tns (alias from tnsnames.ora) or custom +// (full descriptor or Easy Connect Plus string). +type OracleConnectType string + +const ( + OracleService OracleConnectType = "service" + OracleSID OracleConnectType = "sid" + OracleTNS OracleConnectType = "tns" + OracleCustom OracleConnectType = "custom" +) + +// OraclePrivilege: none, sysdba, sysoper, sysbackup, sysdg, syskm, sysrac, +// sysasm. +type OraclePrivilege string + +// AiAccess is what AI agents connected through the MCP server may do with a +// connection: off (not listed), read (read-only queries) or write. +type AiAccess string + +// ConnectionProfile is a saved connection. The password is never part of the +// profile: it lives in the OS credential store when SavePassword is on. +type ConnectionProfile struct { + ID string `json:"id"` + Name string `json:"name"` + Engine Engine `json:"engine"` + // Identification color (for example, red for production). + Color *string `json:"color"` + Host string `json:"host"` + Port uint16 `json:"port"` + // PostgreSQL, MySQL, SQL Server: database. Oracle: service name or SID. + // SQLite: path of the database file. Redis: logical database index. + // Cassandra: default keyspace (optional). + Database string `json:"database"` + User string `json:"user"` + SavePassword bool `json:"savePassword"` + SslMode SslMode `json:"sslMode"` + OracleConnectType OracleConnectType `json:"oracleConnectType"` + ConnectString string `json:"connectString"` + // Alias looked up in tnsnames.ora when OracleConnectType is tns. + TnsAlias string `json:"tnsAlias"` + // Directory with tnsnames.ora / sqlnet.ora (TNS_ADMIN). Null means + // automatic discovery. + ConfigDir *string `json:"configDir"` + OraclePrivilege OraclePrivilege `json:"oraclePrivilege"` + // SQL Server named instance (resolved through the SQL Browser service). + Instance string `json:"instance"` + // SQL Server: sign in with the current Windows account. + WindowsAuth bool `json:"windowsAuth"` + // SQLite: create the file when it does not exist. + CreateFile bool `json:"createFile"` + // Cassandra: local datacenter; empty means every node. + Datacenter string `json:"datacenter"` + AiAccess AiAccess `json:"aiAccess"` +} + +// DefaultProfile is what a missing field in connections.json falls back to. +func DefaultProfile() ConnectionProfile { + return ConnectionProfile{ + Engine: Postgres, + Host: "localhost", + Port: 5432, + SavePassword: true, + SslMode: SslPrefer, + OracleConnectType: OracleService, + OraclePrivilege: "none", + AiAccess: "off", + } +} + +// UnmarshalJSON fills fields the JSON leaves out with their defaults, so +// older connections.json files keep loading. +func (p *ConnectionProfile) UnmarshalJSON(data []byte) error { + type plain ConnectionProfile + out := plain(DefaultProfile()) + if err := json.Unmarshal(data, &out); err != nil { + return err + } + *p = ConnectionProfile(out) + return nil +} + +type SessionInfo struct { + SessionID string `json:"sessionId"` + ProfileID string `json:"profileId"` + Engine Engine `json:"engine"` + ServerVersion string `json:"serverVersion"` + CurrentUser *string `json:"currentUser"` + CurrentSchema *string `json:"currentSchema"` + Autocommit bool `json:"autocommit"` +} + +// ValueKind is the column category the grid uses for alignment and +// formatting. +type ValueKind string + +const ( + KindNumber ValueKind = "number" + KindText ValueKind = "text" + KindBool ValueKind = "bool" + KindTemporal ValueKind = "temporal" + KindBinary ValueKind = "binary" + KindJSON ValueKind = "json" + KindOther ValueKind = "other" +) + +type ColumnInfo struct { + Name string `json:"name"` + // Type name as the database describes it (int4, VARCHAR2(30)...). + TypeName string `json:"typeName"` + Kind ValueKind `json:"kind"` +} + +type ExecRequest struct { + SQL string `json:"sql"` + // 0 = no limit. + MaxRows int `json:"maxRows"` +} + +// Row is one result row; nil is SQL NULL. Values arrive as text already +// formatted by the driver, so NUMERIC and date precision never depend on +// JavaScript numbers. +type Row = []*string + +// ExecResult is the result of one statement. +type ExecResult struct { + // Nil for statements that return no rows. + Columns []ColumnInfo `json:"columns"` + Rows []Row `json:"rows"` + Truncated bool `json:"truncated"` + RowsAffected *uint64 `json:"rowsAffected"` + ElapsedMs uint64 `json:"elapsedMs"` + Notices []string `json:"notices"` + InTransaction bool `json:"inTransaction"` + // Set when the rows come from one table with its key in the result, so + // the grid can edit them. + Editable *EditTarget `json:"editable"` + // Why a row-returning result cannot be edited (shown in the grid). + ReadOnlyReason *string `json:"readOnlyReason"` +} + +// Normalize turns nil lists the interface expects as arrays into empty ones. +func (r *ExecResult) Normalize() { + if r.Rows == nil { + r.Rows = []Row{} + } + if r.Notices == nil { + r.Notices = []string{} + } +} + +// EditTarget is the table behind an editable result. +type EditTarget struct { + Schema *string `json:"schema"` + Table string `json:"table"` + // One entry per result column: the table column it shows, or nil for + // expressions, which stay read-only. + Columns []*EditColumn `json:"columns"` + // Result column indexes that form the table's primary (or unique) key. + Key []int `json:"key"` +} + +type EditColumn struct { + Name string `json:"name"` + // Type as the engine names it in DDL, used to convert the text value. + TypeName string `json:"typeName"` +} + +// CellValue is a value for one result column. +type CellValue struct { + Column int `json:"column"` + Value *string `json:"value"` +} + +// RowChange is one pending change from the grid: op is update, delete or +// insert. Key holds the original values of the key columns, in the order of +// EditTarget.Key. +type RowChange struct { + Op string `json:"op"` + Key []*string `json:"key,omitempty"` + Values []CellValue `json:"values,omitempty"` +} + +const ( + OpUpdate = "update" + OpDelete = "delete" + OpInsert = "insert" +) + +type ApplyRequest struct { + Target EditTarget `json:"target"` + Changes []RowChange `json:"changes"` +} + +type ApplyResult struct { + Updated uint64 `json:"updated"` + Deleted uint64 `json:"deleted"` + Inserted uint64 `json:"inserted"` + ElapsedMs uint64 `json:"elapsedMs"` + InTransaction bool `json:"inTransaction"` +} + +type DbObject struct { + Name string `json:"name"` + // table, view, matview, foreign, sequence, function, procedure, package, + // type, synonym. + Kind string `json:"kind"` +} + +type DbColumn struct { + Name string `json:"name"` + TypeName string `json:"typeName"` + Nullable bool `json:"nullable"` + PrimaryKey bool `json:"primaryKey"` + // Default as an SQL expression, as the table definition writes it. + DefaultValue *string `json:"defaultValue"` + // Cassandra: partition, clustering, static or regular. Nil elsewhere. + KeyRole *string `json:"keyRole"` +} + +type ServerInfo struct { + ServerVersion string `json:"serverVersion"` +} + +type TxState struct { + Autocommit bool `json:"autocommit"` + InTransaction bool `json:"inTransaction"` +} + +// Str returns a pointer to s, for nullable text fields. +func Str(s string) *string { return &s } diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.go new file mode 100644 index 0000000..abe7012 --- /dev/null +++ b/internal/profiles/profiles.go @@ -0,0 +1,214 @@ +// Package profiles keeps connection profiles in connections.json in the +// user's configuration folder. Passwords live in the OS credential store +// (Windows Credential Manager, Keychain, Secret Service), never in the file. +package profiles + +import ( + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/google/uuid" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +const keyringService = "dev.lowbloat.lowquery" + +type Store struct { + path string + mu sync.Mutex +} + +func NewStore(configDir string) (*Store, error) { + if err := os.MkdirAll(configDir, 0o755); err != nil { + return nil, err + } + return &Store{path: filepath.Join(configDir, "connections.json")}, nil +} + +func (s *Store) List() ([]model.ConnectionProfile, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.read() +} + +func (s *Store) Get(id string) (model.ConnectionProfile, error) { + all, err := s.List() + if err != nil { + return model.ConnectionProfile{}, err + } + for _, p := range all { + if p.ID == id { + return p, nil + } + } + return model.ConnectionProfile{}, apperr.New(apperr.NotFound, "Connection not found.") +} + +// Save creates or updates the profile. password: non-nil stores it (an empty +// string deletes it), nil keeps the current password. +func (s *Store) Save(profile model.ConnectionProfile, password *string) (model.ConnectionProfile, error) { + if err := validate(&profile); err != nil { + return profile, err + } + s.mu.Lock() + defer s.mu.Unlock() + all, err := s.read() + if err != nil { + return profile, err + } + if profile.ID == "" { + profile.ID = uuid.NewString() + } + found := false + for i := range all { + if all[i].ID == profile.ID { + all[i] = profile + found = true + break + } + } + if !found { + all = append(all, profile) + } + if err := s.write(all); err != nil { + return profile, err + } + + switch { + case !profile.SavePassword: + err = deleteSecret(profile.ID) + case password != nil && *password == "": + err = deleteSecret(profile.ID) + case password != nil: + err = setSecret(profile.ID, *password) + } + if err != nil { + return profile, storeError(err) + } + return profile, nil +} + +func (s *Store) Delete(id string) error { + s.mu.Lock() + defer s.mu.Unlock() + all, err := s.read() + if err != nil { + return err + } + kept := all[:0] + for _, p := range all { + if p.ID != id { + kept = append(kept, p) + } + } + if err := s.write(kept); err != nil { + return err + } + if err := deleteSecret(id); err != nil { + return storeError(err) + } + return nil +} + +func (s *Store) read() ([]model.ConnectionProfile, error) { + data, err := os.ReadFile(s.path) + if errors.Is(err, fs.ErrNotExist) { + return []model.ConnectionProfile{}, nil + } + if err != nil { + return nil, apperr.Internalf("%v", err) + } + var all []model.ConnectionProfile + if err := json.Unmarshal(data, &all); err != nil { + return nil, apperr.Internalf("%v", err) + } + if all == nil { + all = []model.ConnectionProfile{} + } + return all, nil +} + +// write goes to a temporary file that is then renamed, so the JSON is not +// corrupted if the process dies mid-write. +func (s *Store) write(all []model.ConnectionProfile) error { + data, err := json.MarshalIndent(all, "", " ") + if err != nil { + return apperr.Internalf("%v", err) + } + tmp := s.path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return apperr.Internalf("%v", err) + } + if err := os.Rename(tmp, s.path); err != nil { + return apperr.Internalf("%v", err) + } + return nil +} + +func validate(p *model.ConnectionProfile) error { + if strings.TrimSpace(p.Name) == "" { + return apperr.New(apperr.Invalid, "Enter a name for the connection.") + } + if p.Engine == model.Oracle { + switch p.OracleConnectType { + case model.OracleCustom: + if strings.TrimSpace(p.ConnectString) == "" { + return apperr.New(apperr.Invalid, "Enter the descriptor or Easy Connect string.") + } + return nil + case model.OracleTNS: + if strings.TrimSpace(p.TnsAlias) == "" { + return apperr.New(apperr.Invalid, "Choose a TNS alias.") + } + return nil + } + } + if p.Engine == model.SQLite { + if strings.TrimSpace(p.Database) == "" { + return apperr.New(apperr.Invalid, "Choose the database file.") + } + return nil + } + if strings.TrimSpace(p.Host) == "" { + return apperr.New(apperr.Invalid, "Enter the host.") + } + return nil +} + +// StoredPassword returns the password saved for a profile, if any. +func StoredPassword(id string) (*string, error) { + if id == "" { + return nil, nil + } + pw, ok, err := getSecret(id) + if err != nil { + return nil, storeError(err) + } + if !ok { + return nil, nil + } + return &pw, nil +} + +// RememberPassword stores a password typed at connect time when the profile +// keeps passwords. +func RememberPassword(id, password string) error { + if id == "" || password == "" { + return nil + } + if err := setSecret(id, password); err != nil { + return storeError(err) + } + return nil +} + +func storeError(err error) error { + return apperr.Internalf("System credential store: %v", err) +} diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.go new file mode 100644 index 0000000..1bb74db --- /dev/null +++ b/internal/profiles/profiles_test.go @@ -0,0 +1,85 @@ +package profiles + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// connections.json written by the Rust releases loads with every field, and +// fields an older file lacks get their defaults. +func TestReadsRustConnectionsFile(t *testing.T) { + dir := t.TempDir() + file := `[ + { + "id": "a1", + "name": "Local", + "engine": "sqlite", + "color": null, + "host": "localhost", + "port": 5432, + "database": "C:\\data\\x.db", + "user": "", + "savePassword": true, + "sslMode": "verify-full", + "oracleConnectType": "tns", + "connectString": "", + "tnsAlias": "PROD", + "configDir": "C:\\oracle", + "oraclePrivilege": "sysdba", + "instance": "", + "windowsAuth": false, + "createFile": true, + "datacenter": "", + "aiAccess": "read" + }, + { "id": "b2", "name": "Old", "engine": "postgres" } +]` + if err := os.WriteFile(filepath.Join(dir, "connections.json"), []byte(file), 0o644); err != nil { + t.Fatal(err) + } + s, err := NewStore(dir) + if err != nil { + t.Fatal(err) + } + all, err := s.List() + if err != nil { + t.Fatal(err) + } + if len(all) != 2 { + t.Fatalf("got %d profiles", len(all)) + } + a := all[0] + if a.Engine != model.SQLite || a.SslMode != model.SslVerifyFull || a.TnsAlias != "PROD" || + a.ConfigDir == nil || *a.ConfigDir != `C:\oracle` || a.OraclePrivilege != "sysdba" || + !a.CreateFile || a.AiAccess != "read" || a.Color != nil { + t.Fatalf("profile a = %+v", a) + } + b := all[1] + want := model.DefaultProfile() + want.ID, want.Name = "b2", "Old" + if b != want { + got, _ := json.Marshal(b) + t.Fatalf("defaults not applied: %s", got) + } +} + +func TestValidate(t *testing.T) { + p := model.DefaultProfile() + if err := validate(&p); err == nil || err.Error() != "Enter a name for the connection." { + t.Fatalf("err = %v", err) + } + p.Name = "x" + p.Engine = model.SQLite + if err := validate(&p); err == nil || err.Error() != "Choose the database file." { + t.Fatalf("err = %v", err) + } + p.Engine = model.Oracle + p.OracleConnectType = model.OracleTNS + if err := validate(&p); err == nil || err.Error() != "Choose a TNS alias." { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/profiles/secrets_other.go b/internal/profiles/secrets_other.go new file mode 100644 index 0000000..f50ada4 --- /dev/null +++ b/internal/profiles/secrets_other.go @@ -0,0 +1,35 @@ +//go:build !windows + +package profiles + +import ( + "errors" + + "github.com/zalando/go-keyring" +) + +// macOS Keychain and the Secret Service keep the service and account the +// Rust keyring crate used, so passwords saved by earlier releases are found. + +func getSecret(id string) (string, bool, error) { + pw, err := keyring.Get(keyringService, id) + if errors.Is(err, keyring.ErrNotFound) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return pw, true, nil +} + +func setSecret(id, password string) error { + return keyring.Set(keyringService, id, password) +} + +func deleteSecret(id string) error { + err := keyring.Delete(keyringService, id) + if errors.Is(err, keyring.ErrNotFound) { + return nil + } + return err +} diff --git a/internal/profiles/secrets_windows.go b/internal/profiles/secrets_windows.go new file mode 100644 index 0000000..cd7ebeb --- /dev/null +++ b/internal/profiles/secrets_windows.go @@ -0,0 +1,66 @@ +//go:build windows + +package profiles + +import ( + "errors" + "unicode/utf16" + + "github.com/danieljoos/wincred" + "golang.org/x/sys/windows" +) + +// Windows Credential Manager entries use the layout of the Rust keyring +// crate the first LowQuery releases used: target ".", user +// "", the password as UTF-16LE. Keeping it lets passwords saved by those +// releases keep working. + +func target(id string) string { return id + "." + keyringService } + +func getSecret(id string) (string, bool, error) { + cred, err := wincred.GetGenericCredential(target(id)) + if errors.Is(err, windows.ERROR_NOT_FOUND) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return decodeUTF16(cred.CredentialBlob), true, nil +} + +func setSecret(id, password string) error { + cred := wincred.NewGenericCredential(target(id)) + cred.UserName = id + cred.CredentialBlob = encodeUTF16(password) + cred.Persist = wincred.PersistEnterprise + return cred.Write() +} + +func deleteSecret(id string) error { + cred, err := wincred.GetGenericCredential(target(id)) + if errors.Is(err, windows.ERROR_NOT_FOUND) { + return nil + } + if err != nil { + return err + } + return cred.Delete() +} + +func encodeUTF16(s string) []byte { + units := utf16.Encode([]rune(s)) + out := make([]byte, 2*len(units)) + for i, u := range units { + out[2*i] = byte(u) + out[2*i+1] = byte(u >> 8) + } + return out +} + +func decodeUTF16(b []byte) string { + units := make([]uint16, len(b)/2) + for i := range units { + units[i] = uint16(b[2*i]) | uint16(b[2*i+1])<<8 + } + return string(utf16.Decode(units)) +} diff --git a/internal/profiles/secrets_windows_test.go b/internal/profiles/secrets_windows_test.go new file mode 100644 index 0000000..05b83e3 --- /dev/null +++ b/internal/profiles/secrets_windows_test.go @@ -0,0 +1,24 @@ +//go:build windows + +package profiles + +import ( + "bytes" + "testing" +) + +// Passwords saved by the Rust releases are UTF-16LE blobs under +// ".dev.lowbloat.lowquery". +func TestCredentialLayoutMatchesRustKeyring(t *testing.T) { + if got := target("abc"); got != "abc.dev.lowbloat.lowquery" { + t.Fatalf("target = %q", got) + } + blob := encodeUTF16("sénha€1") + want := []byte{'s', 0, 0xE9, 0, 'n', 0, 'h', 0, 'a', 0, 0xAC, 0x20, '1', 0} + if !bytes.Equal(blob, want) { + t.Fatalf("blob = %v, want %v", blob, want) + } + if got := decodeUTF16(blob); got != "sénha€1" { + t.Fatalf("round trip = %q", got) + } +} diff --git a/internal/textcodec/decode.go b/internal/textcodec/decode.go new file mode 100644 index 0000000..b91c21c --- /dev/null +++ b/internal/textcodec/decode.go @@ -0,0 +1,54 @@ +// Package textcodec reads text files whatever their encoding: UTF-8 (with or +// without BOM), UTF-16 with a BOM, or Windows-1252. +package textcodec + +import ( + "strings" + "unicode/utf16" + "unicode/utf8" +) + +// Decode returns the text and the name of the encoding it was read as. +func Decode(b []byte) (string, string) { + switch { + case len(b) >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF: + return strings.ToValidUTF8(string(b[3:]), "�"), "UTF-8" + case len(b) >= 2 && b[0] == 0xFF && b[1] == 0xFE: + return decodeUTF16(b[2:], true), "UTF-16" + case len(b) >= 2 && b[0] == 0xFE && b[1] == 0xFF: + return decodeUTF16(b[2:], false), "UTF-16" + case utf8.Valid(b): + return string(b), "UTF-8" + } + var sb strings.Builder + sb.Grow(len(b)) + for _, c := range b { + sb.WriteRune(cp1252(c)) + } + return sb.String(), "Windows-1252" +} + +func decodeUTF16(b []byte, le bool) string { + units := make([]uint16, len(b)/2) + for i := range units { + if le { + units[i] = uint16(b[2*i]) | uint16(b[2*i+1])<<8 + } else { + units[i] = uint16(b[2*i])<<8 | uint16(b[2*i+1]) + } + } + return string(utf16.Decode(units)) +} + +var cp1252High = [32]rune{ + '€', '\u0081', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u008d', 'Ž', + '\u008f', '\u0090', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u009d', + 'ž', 'Ÿ', +} + +func cp1252(b byte) rune { + if b >= 0x80 && b < 0xA0 { + return cp1252High[b-0x80] + } + return rune(b) +} diff --git a/internal/textcodec/decode_test.go b/internal/textcodec/decode_test.go new file mode 100644 index 0000000..1215305 --- /dev/null +++ b/internal/textcodec/decode_test.go @@ -0,0 +1,23 @@ +package textcodec + +import "testing" + +func TestDecode(t *testing.T) { + cases := []struct { + in []byte + text string + encoding string + }{ + {[]byte("select 'ã'"), "select 'ã'", "UTF-8"}, + {append([]byte{0xEF, 0xBB, 0xBF}, "x"...), "x", "UTF-8"}, + {[]byte{0xFF, 0xFE, 'a', 0, 0xE3, 0}, "aã", "UTF-16"}, + {[]byte{0xFE, 0xFF, 0, 'a', 0, 0xE3}, "aã", "UTF-16"}, + {[]byte{'n', 0xE3, 'o', ' ', 0x80}, "não €", "Windows-1252"}, + } + for _, c := range cases { + text, enc := Decode(c.in) + if text != c.text || enc != c.encoding { + t.Errorf("Decode(%v) = %q, %s; want %q, %s", c.in, text, enc, c.text, c.encoding) + } + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..9bd1a1e --- /dev/null +++ b/main.go @@ -0,0 +1,159 @@ +// LowQuery: a lightweight multi-database SQL client. +package main + +import ( + "embed" + "encoding/json" + "log" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/LowBloat/LowQuery/internal/app" + "github.com/LowBloat/LowQuery/internal/profiles" +) + +// The interface, built by `bun run build` into dist/. +// +//go:embed all:dist +var assets embed.FS + +// The app version comes from package.json, the one place releases bump. +// +//go:embed package.json +var packageJSON []byte + +// How long the window waits for the page before it is shown anyway, so a +// page that fails to load never leaves an invisible app. +const firstShowFallback = 5 * time.Second + +func main() { + var pkg struct { + Version string `json:"version"` + } + _ = json.Unmarshal(packageJSON, &pkg) + + configDir, err := os.UserConfigDir() + if err != nil { + log.Fatalf("user configuration directory unavailable: %v", err) + } + // Same folder the first releases used: %APPDATA%\LowBloat\LowQuery\config + // on Windows, ~/Library/Application Support/dev.LowBloat.LowQuery on + // macOS, ~/.config/lowquery on Linux. + store, err := profiles.NewStore(appConfigDir(configDir)) + if err != nil { + log.Fatalf("could not create the configuration directory: %v", err) + } + + backend := app.New(pkg.Version, store) + wails := application.New(application.Options{ + Name: "LowQuery", + Description: "A lightweight multi-database SQL client", + Services: []application.Service{ + application.NewService(app.NewService(backend)), + }, + MarshalError: app.MarshalError, + Assets: application.AssetOptions{ + Handler: application.AssetFileServerFS(assets), + }, + Mac: application.MacOptions{ + ApplicationShouldTerminateAfterLastWindowClosed: true, + }, + Windows: application.WindowsOptions{ + WebviewUserDataPath: webviewDataDir(), + // Extra browser arguments for tests: --remote-debugging-port=9333 + // lets them drive the window over CDP. Wails blanks WebView2's own + // WEBVIEW2_* variables, hence a variable of ours. + AdditionalBrowserArgs: strings.Fields(os.Getenv("LQ_WEBVIEW_ARGS")), + }, + OnShutdown: backend.CloseAll, + }) + + // The window starts hidden so the webview's white background never shows + // while the page loads; the page shows it once it has painted. + win := wails.Window.NewWithOptions(application.WebviewWindowOptions{ + Name: "main", + Title: "LowQuery", + Width: 1280, + Height: 800, + MinWidth: 720, + MinHeight: 480, + Frameless: true, + Hidden: true, + BackgroundColour: application.NewRGB(0x11, 0x11, 0x11), + URL: "/", + Mac: application.MacWindow{ + TitleBar: application.MacTitleBarHiddenInset, + InvisibleTitleBarHeight: 40, + }, + }) + frame := &mainWindow{win: win} + backend.SetWindow(frame) + time.AfterFunc(firstShowFallback, frame.showFirstTime) + + if err := wails.Run(); err != nil { + log.Fatal(err) + } +} + +func appConfigDir(base string) string { + switch { + case filepath.Base(base) == "Application Support": // macOS + return filepath.Join(base, "dev.LowBloat.LowQuery") + case os.PathSeparator == '\\': // Windows: %APPDATA% + return filepath.Join(base, "LowBloat", "LowQuery", "config") + default: + return filepath.Join(base, "lowquery") + } +} + +// webviewDataDir is the WebView2 profile (local storage with editor drafts, +// cache) on Windows: %LOCALAPPDATA%\LowBloat\LowQuery\WebView. LQ_WEBVIEW_DATA +// overrides it, so a test copy does not share the profile of the one in use. +func webviewDataDir() string { + if dir := os.Getenv("LQ_WEBVIEW_DATA"); dir != "" { + return dir + } + if local := os.Getenv("LOCALAPPDATA"); local != "" { + return filepath.Join(local, "LowBloat", "LowQuery", "WebView") + } + return "" +} + +type mainWindow struct { + win *application.WebviewWindow + shown sync.Once +} + +func (w *mainWindow) showFirstTime() { + w.shown.Do(func() { + w.win.Show() + w.win.Focus() + }) +} + +// Painted gives the native window the page background, so resizing never +// uncovers another color, and shows it the first time. +func (w *mainWindow) Painted(background string) { + if r, g, b, ok := parseHex(background); ok { + w.win.SetBackgroundColour(application.NewRGB(r, g, b)) + } + w.showFirstTime() +} + +func parseHex(s string) (r, g, b uint8, ok bool) { + s = strings.TrimPrefix(s, "#") + if len(s) != 6 { + return 0, 0, 0, false + } + v, err := strconv.ParseUint(s, 16, 32) + if err != nil { + return 0, 0, 0, false + } + return uint8(v >> 16), uint8(v >> 8), uint8(v), true +} diff --git a/package.json b/package.json index 08f5b3f..f006821 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,9 @@ "type": "module", "scripts": { "dev": "vite", + "app": "bun scripts/dev-app.mjs", "build": "vite build", + "build:app": "vite build && go build -tags production -trimpath -ldflags \"-s -w -H windowsgui\" -o bin/LowQuery.exe .", "preview": "vite preview", "check": "svelte-check --tsconfig ./tsconfig.json", "test": "bun test", @@ -39,6 +41,7 @@ "@tauri-apps/plugin-opener": "^2.7.2", "@tauri-apps/plugin-process": "^2.4.0", "@tauri-apps/plugin-updater": "^2.14.0", + "@wailsio/runtime": "3.1.0", "codemirror": "^6.0.2" }, "devDependencies": { diff --git a/scripts/dev-app.mjs b/scripts/dev-app.mjs new file mode 100644 index 0000000..2174dea --- /dev/null +++ b/scripts/dev-app.mjs @@ -0,0 +1,47 @@ +// Runs the desktop app in development: the Vite dev server for the interface +// (hot reload) and the Go backend, which proxies the interface from Vite. +// Restart it after changing Go code; `go run` rebuilds in seconds. +// +// bun run app +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; + +const VITE_URL = "http://127.0.0.1:1420"; + +// The Go binary embeds dist/; dev mode serves from Vite, but the embed still +// needs the folder to hold a file. +if (!existsSync("dist/index.html")) { + mkdirSync("dist", { recursive: true }); + writeFileSync("dist/index.html", "LowQuery"); +} + +const children = []; +const stop = (code = 0) => { + for (const child of children) child.kill(); + process.exit(code); +}; +process.on("SIGINT", () => stop(0)); + +const vite = spawn("bun", ["x", "vite"], { stdio: "inherit", shell: process.platform === "win32" }); +children.push(vite); + +async function viteReady() { + for (let i = 0; i < 300; i++) { + try { + if ((await fetch(VITE_URL)).ok) return; + } catch { + // Not listening yet. + } + await new Promise((r) => setTimeout(r, 200)); + } + throw new Error(`Vite did not start at ${VITE_URL}`); +} + +await viteReady(); +const app = spawn("go", ["run", "."], { + stdio: "inherit", + env: { ...process.env, FRONTEND_DEVSERVER_URL: VITE_URL }, +}); +children.push(app); +app.on("exit", (code) => stop(code ?? 0)); +vite.on("exit", (code) => stop(code ?? 1)); diff --git a/src/App.svelte b/src/App.svelte index e253057..fdf057f 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -1,9 +1,7 @@